Subversion Repositories vnag

Compare Revisions

No changes between revisions

Regard whitespace Rev 83 → Rev 84

/trunk/bin/4images_version.phar
291,11 → 291,10
 
Extract_Phar::go();
__HALT_COMPILER(); ?>
y‰a:1:{s:23:"1.3.6.1.4.1.37476.3.0.2";s:347:"sha256||framework/vnag_framework.inc.php|460b109d1c578e9b6af41612e0312c9f36fd8beb51f7aa92f1b7bd49614568e8||plugins/4images_version/FourImagesVersionCheck.class.php|4c11630e2389da14db31e77eb70dda3eaa927f8d4254372c75d0e964bca9125a||plugins/4images_version/check_4images_version.phps|4edc52ae943ba24559eeb69810e9c6b52dda36ec4428118d3e7c09ac0c0d8b8a||";} framework/vnag_framework.inc.phpLÙyï*eLُ4p”¤8plugins/4images_version/FourImagesVersionCheck.class.phpŒ
yï*eŒ
L渤2plugins/4images_version/check_4images_version.phpsÖyï*eփ ¤<?php ?>
<?php
ÅÕa:1:{s:23:"1.3.6.1.4.1.37476.3.0.2";s:423:"sha256||<builder>|481cf75d675006b504520fd2acb3b29c89aea03aab64754e0adfb364de4914b2||framework/vnag_framework.inc.php|0387bf3134f8cc2d1ae24e139019c0edef19c1ba5ca765624efea0b469c7897f||plugins/4images_version/FourImagesVersionCheck.class.php|4c11630e2389da14db31e77eb70dda3eaa927f8d4254372c75d0e964bca9125a||plugins/4images_version/check_4images_version.phps|4edc52ae943ba24559eeb69810e9c6b52dda36ec4428118d3e7c09ac0c0d8b8a||";} framework/vnag_framework.inc.phpBÙº +eBÙÞß=¤8plugins/4images_version/FourImagesVersionCheck.class.phpŒ
º +eŒ
L渤2plugins/4images_version/check_4images_version.phpsÖº +eփ ¤<?php
if (!VNag::is_http_mode()) error_reporting(E_ALL); declare(ticks=1); set_time_limit(0); define('VNAG_JSONDATA_V1', 'oid:1.3.6.1.4.1.37476.2.3.1.1'); $OVERWRITE_ARGUMENTS = null; function _empty($x) { return is_null($x) || (trim($x) == ''); } abstract class VNag { const VNAG_VERSION = '2023-10-13'; const STATUS_OK = 0; const STATUS_WARNING = 1; const STATUS_CRITICAL = 2; const STATUS_UNKNOWN = 3; const STATUS_ERROR = 4; const STATUS_UP = 0; const STATUS_DOWN = 1; const STATUS_MAINTAIN = 2; const VERBOSITY_SUMMARY = 0; const VERBOSITY_ADDITIONAL_INFORMATION = 1; const VERBOSITY_CONFIGURATION_DEBUG = 2; const VERBOSITY_PLUGIN_DEBUG = 3; const MAX_VERBOSITY = self::VERBOSITY_PLUGIN_DEBUG; const STATUSMODEL_SERVICE = 0; const STATUSMODEL_HOST = 1; private $initialized = false; private $status = null; private $messages = array(); private $verbose_info = ''; private $warningRanges = array(); private $criticalRanges = array(); private $performanceDataObjects = array(); private static $exitcode = 0; private $helpObj = null; private $argHandler = null; const OUTPUT_NEVER = 0; const OUTPUT_SPECIAL = 1; const OUTPUT_NORMAL = 2; const OUTPUT_EXCEPTION = 4; const OUTPUT_ALWAYS = 7; public $http_visual_output = self::OUTPUT_ALWAYS; public $http_invisible_output = self::OUTPUT_ALWAYS; protected $html_before = ''; protected $html_after = ''; protected $statusmodel = self::STATUSMODEL_SERVICE; protected $show_status_in_headline = true; protected $default_status = self::STATUS_UNKNOWN; protected $default_warning_range = null; protected $default_critical_range = null; protected $argWarning; protected $argCritical; protected $argVersion; protected $argVerbosity; protected $argTimeout; protected $argHelp; protected $argUsage; public $id = null; protected static $http_serial_number = 0; public $privkey = null; public $privkey_password = null; public $sign_algo = null; public $pubkey = null; protected $warningSingleValueRangeBehaviors = array(self::SINGLEVALUE_RANGE_DEFAULT); protected $criticalSingleValueRangeBehaviors = array(self::SINGLEVALUE_RANGE_DEFAULT); const SINGLEVALUE_RANGE_DEFAULT = 0; const SINGLEVALUE_RANGE_VAL_GT_X_BAD = 1; const SINGLEVALUE_RANGE_VAL_GE_X_BAD = 2; const SINGLEVALUE_RANGE_VAL_LT_X_BAD = 3; const SINGLEVALUE_RANGE_VAL_LE_X_BAD = 4; public $password_out = null; public $password_in = null; public static function is_http_mode() { return php_sapi_name() !== 'cli'; } public function getHelpManager() { return $this->helpObj; } public function getArgumentHandler() { return $this->argHandler; } public function outputHTML($text, $after_visual_output=true) { if ($this->is_http_mode()) { if ($this->initialized) { if ($after_visual_output) { $this->html_after .= $text; } else { $this->html_before .= $text; } } else { echo $text; } } } protected function resetArguments() { $this->argWarning = null; $this->argCritical = null; $this->argVersion = null; $this->argVerbosity = null; $this->argTimeout = null; $this->argHelp = null; $this->argWarning = null; $this->argCritical = null; } public function registerExpectedStandardArguments($args) { $this->resetArguments(); for ($i=0; $i<strlen($args); $i++) { switch ($args[$i]) { case 'w': $this->addExpectedArgument($this->argWarning = new VNagArgument('w', 'warning', VNagArgument::VALUE_REQUIRED, VNagLang::$argname_value, VNagLang::$warning_range)); break; case 'c': $this->addExpectedArgument($this->argCritical = new VNagArgument('c', 'critical', VNagArgument::VALUE_REQUIRED, VNagLang::$argname_value, VNagLang::$critical_range)); break; case 'V': $this->addExpectedArgument($this->argVersion = new VNagArgument('V', 'version', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$prints_version)); break; case 'v': $this->addExpectedArgument($this->argVerbosity = new VNagArgument('v', 'verbose', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$verbosity_helptext)); break; case 't': $this->addExpectedArgument($this->argTimeout = new VNagArgument('t', 'timeout', VNagArgument::VALUE_REQUIRED, VNagLang::$argname_seconds, VNagLang::$timeout_helptext)); break; case 'h': $this->addExpectedArgument($this->argHelp = new VNagArgument('h', 'help', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$help_helptext)); break; default: $letter = $args[$i]; throw new VNagInvalidStandardArgument(sprintf(VNagLang::$no_standard_arguments_with_letter, $letter)); } } } public function addExpectedArgument($argObj) { $helpObjAddEntryMethod = new ReflectionMethod($this->helpObj, '_addOption'); $helpObjAddEntryMethod->setAccessible(true); $helpObjAddEntryMethod->invoke($this->helpObj, $argObj); $argHandlerAddEntryMethod = new ReflectionMethod($this->argHandler, '_addExpectedArgument'); $argHandlerAddEntryMethod->setAccessible(true); $argHandlerAddEntryMethod->invoke($this->argHandler, $argObj); } protected function createArgumentHandler() { $this->argHandler = new VNagArgumentHandler(); } protected function createHelpObject() { $this->helpObj = new VNagHelp(); } protected function checkInitialized() { if (!$this->initialized) throw new VNagFunctionCallOutsideSession(); } protected function getVerbosityLevel() { $this->checkInitialized(); if (!isset($this->argVerbosity)) { return self::VERBOSITY_SUMMARY; } else { $level = $this->argVerbosity->count(); if ($level > self::MAX_VERBOSITY) $level = self::MAX_VERBOSITY; return $level; } } public function getWarningRange($argumentNumber=0) { $this->checkInitialized(); if (!isset($this->warningRanges[$argumentNumber])) { if (!is_null($this->argWarning)) { $warning = $this->argWarning->getValue(); if (!is_null($warning)) { $vals = explode(',',$warning); foreach ($vals as $number => $val) { if (_empty($val)) { $this->warningRanges[$number] = null; } else { $singleValueBehavior = isset($this->warningSingleValueRangeBehaviors[$number]) ? $this->warningSingleValueRangeBehaviors[$number] : VNag::SINGLEVALUE_RANGE_DEFAULT; $this->warningRanges[$number] = new VNagRange($val, $singleValueBehavior); } } } else { $this->warningRanges[0] = $this->default_warning_range; } } else { return null; } } if (isset($this->warningRanges[$argumentNumber])) { return $this->warningRanges[$argumentNumber]; } else { return null; } } public function getCriticalRange($argumentNumber=0) { $this->checkInitialized(); if (!isset($this->criticalRanges[$argumentNumber])) { if (!is_null($this->argCritical)) { $critical = $this->argCritical->getValue(); if (!is_null($critical)) { $vals = explode(',',$critical); foreach ($vals as $number => $val) { $singleValueBehavior = isset($this->criticalSingleValueRangeBehaviors[$number]) ? $this->criticalSingleValueRangeBehaviors[$number] : VNag::SINGLEVALUE_RANGE_DEFAULT; $this->criticalRanges[$number] = new VNagRange($val, $singleValueBehavior); } } else { $this->criticalRanges[0] = $this->default_critical_range; } } else { return null; } } if (isset($this->criticalRanges[$argumentNumber])) { return $this->criticalRanges[$argumentNumber]; } else { return null; } } public function checkAgainstWarningRange($values, $force=true, $autostatus=true, $argumentNumber=0) { $this->checkInitialized(); if (!$this->getArgumentHandler()->isArgRegistered('w')) { throw new VNagRequiredArgumentNotRegistered('-w'); } $wr = $this->getWarningRange($argumentNumber); if (isset($wr)) { if ($wr->checkAlert($values)) { if ($autostatus) $this->setStatus(VNag::STATUS_WARNING); return true; } else { if ($autostatus) $this->setStatus(VNag::STATUS_OK); return false; } } else { if ($force) { if (($argumentNumber > 0) && (count($this->warningRanges) > 0)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$too_few_warning_ranges, $argumentNumber+1)); } else { throw new VNagRequiredArgumentMissing('-w'); } } } } public function checkAgainstCriticalRange($values, $force=true, $autostatus=true, $argumentNumber=0) { $this->checkInitialized(); if (!$this->getArgumentHandler()->isArgRegistered('c')) { throw new VNagRequiredArgumentNotRegistered('-c'); } $cr = $this->getCriticalRange($argumentNumber); if (isset($cr)) { if ($cr->checkAlert($values)) { if ($autostatus) $this->setStatus(VNag::STATUS_CRITICAL); return true; } else { if ($autostatus) $this->setStatus(VNag::STATUS_OK); return false; } } else { if ($force) { if (($argumentNumber > 0) && (count($this->warningRanges) > 0)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$too_few_critical_ranges, $argumentNumber+1)); } else { throw new VNagRequiredArgumentMissing('-c'); } } } } protected static function getBaddestExitcode($code1, $code2) { return max($code1, $code2); } public static function _shutdownHandler() { if (!self::is_http_mode()) { exit((int)self::$exitcode); } } protected function _exit($code) { self::$exitcode = $this->getBaddestExitcode($code, self::$exitcode); } private $constructed = false; function __construct() { $this->createHelpObject(); $this->createArgumentHandler(); $this->addExpectedArgument($this->argUsage = new VNagArgument('?', '', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$prints_usage)); $this->constructed = true; } function __destruct() { if (Timeouter::started()) { Timeouter::end(); } } public function run() { global $inside_vnag_run; $inside_vnag_run = true; try { if (!$this->constructed) { throw new VNagNotConstructed(VNagLang::$notConstructed); } try { $this->initialized = true; $this->html_before = ''; $this->html_after = ''; $this->setStatus(null, true); $this->messages = array(); register_shutdown_function(array($this, '_shutdownHandler')); if ($this->argHandler->illegalUsage()) { $content = $this->helpObj->printUsagePage(); $this->setStatus(VNag::STATUS_UNKNOWN); if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_visual_output & VNag::OUTPUT_SPECIAL) echo $this->writeVisualHTML($content); if ($this->http_invisible_output & VNag::OUTPUT_SPECIAL) echo $this->writeInvisibleHTML($content); echo $this->html_after; return; } else { echo $content; return $this->_exit($this->status); } } if (!is_null($this->argVersion) && ($this->argVersion->available())) { $content = $this->helpObj->printVersionPage(); $this->setStatus(VNag::STATUS_UNKNOWN); if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_visual_output & VNag::OUTPUT_SPECIAL) echo $this->writeVisualHTML($content); if ($this->http_invisible_output & VNag::OUTPUT_SPECIAL) echo $this->writeInvisibleHTML($content); echo $this->html_after; return; } else { echo $content; return $this->_exit($this->status); } } if (!is_null($this->argHelp) && ($this->argHelp->available())) { $content = $this->helpObj->printHelpPage(); $this->setStatus(VNag::STATUS_UNKNOWN); if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_visual_output & VNag::OUTPUT_SPECIAL) echo $this->writeVisualHTML($content); if ($this->http_invisible_output & VNag::OUTPUT_SPECIAL) echo $this->writeInvisibleHTML($content); echo $this->html_after; return; } else { echo $content; return $this->_exit($this->status); } } $this->getWarningRange(); $this->getCriticalRange(); if (!is_null($this->argTimeout)) { $timeout = $this->argTimeout->getValue(); if (!is_null($timeout)) { Timeouter::start($timeout); } } ob_start(); $init_ob_level = ob_get_level(); try { $this->cbRun(); if (ob_get_level() < $init_ob_level) throw new VNagImplementationErrorException(VNagLang::$output_level_lowered); } finally { while (ob_get_level() > $init_ob_level) @ob_end_clean(); } if (is_null($this->status)) $this->setStatus($this->default_status,true); $outputType = VNag::OUTPUT_NORMAL; } catch (Exception $e) { $this->handleException($e); $outputType = VNag::OUTPUT_EXCEPTION; } if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_invisible_output & $outputType) { echo $this->writeInvisibleHTML(); } if ($this->http_visual_output & $outputType) { echo $this->writeVisualHTML(); } echo $this->html_after; } else { echo $this->getNagiosConsoleText(); return $this->_exit($this->status); } Timeouter::end(); } finally { $inside_vnag_run = false; } } private function getNagiosConsoleText() { $ary_perfdata = $this->getPerformanceData(); $performancedata_first = array_shift($ary_perfdata); $performancedata_rest = implode(' ', $ary_perfdata); $status_text = VNagLang::status($this->status, $this->statusmodel); if (_empty($this->getHeadline())) { $content = $status_text; } else { if ($this->show_status_in_headline) { $content = $status_text.': '.$this->getHeadline(); } else { $content = $this->getHeadline(); } } if (!_empty($performancedata_first)) $content .= '|'.trim($performancedata_first); $content .= "\n"; if (!_empty($this->verbose_info)) { $content .= trim($this->verbose_info); } if (!_empty($performancedata_rest)) $content .= '|'.trim($performancedata_rest); $content .= "\n"; return trim($content)."\n"; } abstract protected function cbRun(); public function addPerformanceData($prefDataObj, $move_to_font=false, $verbosityLevel=VNag::VERBOSITY_SUMMARY) { $this->checkInitialized(); if ((!isset($this->argVerbosity)) && ($verbosityLevel > VNag::VERBOSITY_SUMMARY)) throw new VNagRequiredArgumentNotRegistered('-v'); if (self::getVerbosityLevel() < $verbosityLevel) return false; if ($move_to_font) { array_unshift($this->performanceDataObjects, $prefDataObj); } else { $this->performanceDataObjects[] = $prefDataObj; } return true; } public function getPerformanceData() { $this->checkInitialized(); return $this->performanceDataObjects; } public function removePerformanceData($prefDataObj) { if (($key = array_search($prefDataObj, $this->performanceDataObjects, true)) !== false) { unset($this->performanceDataObjects[$key]); return true; } else { return false; } } public function clearPerformanceData() { $this->performanceDataObjects = array(); } public function getVerboseInfo() { return $this->verbose_info; } public function clearVerboseInfo() { $this->verbose_info = ''; } private function writeVisualHTML($special_content=null) { if (!_empty($special_content)) { $content = $special_content; } else { $content = strtoupper(VNagLang::$status.': '.VNagLang::status($this->status, $this->statusmodel))."\n\n"; $content .= strtoupper(VNagLang::$message).":\n"; $status_text = VNagLang::status($this->status, $this->statusmodel); if (_empty($this->getHeadline())) { $content .= $status_text; } else { if ($this->show_status_in_headline) { $content .= $status_text.': '.trim($this->getHeadline()); } else { $content .= trim($this->getHeadline()); } } $content .= "\n\n"; if (!_empty($this->verbose_info)) { $content .= strtoupper(VNagLang::$verbose_info).":\n".trim($this->verbose_info)."\n\n"; } $perfdata = $this->getPerformanceData(); if (count($perfdata) > 0) { $content .= strtoupper(VNagLang::$performance_data).":\n"; foreach ($perfdata as $pd) { $content .= trim($pd)."\n"; } $content .= "\n"; } } $colorinfo = ''; $status = $this->getStatus(); if ($status == VNag::STATUS_OK) $colorinfo = ' style="background-color:green;color:white;font-weight:bold"'; else if ($status == VNag::STATUS_WARNING) $colorinfo = ' style="background-color:yellow;color:black;font-weight:bold"'; else if ($status == VNag::STATUS_CRITICAL) $colorinfo = ' style="background-color:red;color:white;font-weight:bold"'; else if ($status == VNag::STATUS_ERROR) $colorinfo = ' style="background-color:purple;color:white;font-weight:bold"'; else $colorinfo = ' style="background-color:lightgray;color:black;font-weight:bold"'; $html_content = trim($content); $html_content = htmlentities($html_content); $html_content = str_replace(' ', '&nbsp;', $html_content); $html_content = nl2br($html_content); return '<table border="1" cellspacing="2" cellpadding="2" style="width:100%" class="vnag_table">'. '<tr'.$colorinfo.' class="vnag_title_row">'. '<td>'.VNagLang::$nagios_output.'</td>'. '</tr>'. '<tr class="vnag_message_row">'. '<td><code>'. $html_content. '</code></td>'. '</tr>'. '</table>'; } protected function readInvisibleHTML($html) { $this->checkInitialized(); $doc = new DOMDocument(); @$doc->loadHTML($html); $tags = $doc->getElementsByTagName('script'); foreach ($tags as $tag) { $type = $tag->getAttribute('type'); if ($type !== 'application/json') continue; $json = $tag->nodeValue; if (!$json) continue; $data = @json_decode($json,true); if (!is_array($data)) continue; if (!isset($data['type'])) continue; if ($data['type'] === VNAG_JSONDATA_V1) { if (!isset($data['datasets'])) throw new VNagWebInfoException(VNagLang::$dataset_missing); foreach ($data['datasets'] as $dataset) { $payload = base64_decode($dataset['payload']); if (!$payload) { throw new VNagWebInfoException(VNagLang::$payload_not_base64); } if (isset($dataset['encryption'])) { $cryptInfo = $dataset['encryption']; if (!is_array($cryptInfo)) { throw new VNagWebInfoException(VNagLang::$dataset_encryption_no_array); } $password = is_null($this->password_in) ? '' : $this->password_in; $salt = base64_decode($cryptInfo['salt']); if ($cryptInfo['hash'] != hash('sha256',$salt.$password)) { if ($password == '') { throw new VNagWebInfoException(VNagLang::$require_password); } else { throw new VNagWebInfoException(VNagLang::$wrong_password); } } if (!function_exists('openssl_decrypt')) { throw new VNagException(VNagLang::$openssl_missing); } $payload = openssl_decrypt($payload, $cryptInfo['method'], $password, 0, $cryptInfo['iv']); } if (!is_null($this->pubkey) && ($this->pubkey !== '')) { if (substr($this->pubkey,0,3) === '---') { $public_key = $this->pubkey; } else { if (!file_exists($this->pubkey)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$pubkey_file_not_found, $this->pubkey)); } $public_key = @file_get_contents($this->pubkey); if (!$public_key) { throw new VNagPublicKeyException(sprintf(VNagLang::$pubkey_file_not_readable, $this->pubkey)); } } if (!isset($dataset['signature'])) { throw new VNagSignatureException(VNagLang::$signature_missing); } $signature = base64_decode($dataset['signature']); if (!$signature) { throw new VNagSignatureException(VNagLang::$signature_not_bas64); } if (!function_exists('openssl_verify')) { throw new VNagException(VNagLang::$openssl_missing); } $sign_algo = is_null($this->sign_algo) ? OPENSSL_ALGO_SHA256 : $this->sign_algo; if (!openssl_verify($payload, $signature, $public_key, $sign_algo)) { throw new VNagSignatureException(VNagLang::$signature_invalid); } } $payload = @json_decode($payload,true); if (!$payload) { throw new VNagWebInfoException(VNagLang::$payload_not_json); } if ($payload['id'] == $this->id) { return $payload; } } } } return null; } private function getNextMonitorID($peek=false) { $result = is_null($this->id) ? self::$http_serial_number : $this->id; if (!$peek) { $this->id = null; self::$http_serial_number++; } return $result; } private function writeInvisibleHTML($special_content=null) { $payload['id'] = $this->getNextMonitorID(); $payload['status'] = $this->getStatus(); if (!_empty($special_content)) { $payload['text'] = $special_content; } else { $payload['headline'] = $this->getHeadline(); $payload['verbose_info'] = $this->verbose_info; $payload['performance_data'] = array(); foreach ($this->performanceDataObjects as $perfdata) { $payload['performance_data'][] = (string)$perfdata; } } $payload = json_encode($payload); $dataset = array(); if (!is_null($this->privkey) && ($this->privkey !== '')) { if (!function_exists('openssl_pkey_get_private') || !function_exists('openssl_sign')) { throw new VNagException(VNagLang::$openssl_missing); } if (substr($this->privkey,0,3) === '---') { $pkeyid = @openssl_pkey_get_private($this->privkey, $this->privkey_password); if (!$pkeyid) { throw new VNagPrivateKeyException(sprintf(VNagLang::$privkey_not_readable)); } } else { if (!file_exists($this->privkey)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$privkey_file_not_found, $this->privkey)); } $pkeyid = @openssl_pkey_get_private('file://'.$this->privkey, $this->privkey_password); if (!$pkeyid) { throw new VNagPrivateKeyException(sprintf(VNagLang::$privkey_file_not_readable, $this->privkey)); } } $signature = ''; $sign_algo = is_null($this->sign_algo) ? OPENSSL_ALGO_SHA256 : $this->sign_algo; if (@openssl_sign($payload, $signature, $pkeyid, $sign_algo)) { if (version_compare(PHP_VERSION, '8.0.0') < 0) { openssl_free_key($pkeyid); } $dataset['signature'] = base64_encode($signature); } else { throw new VNagPrivateKeyException(sprintf(VNagLang::$signature_failed)); } } if (!is_null($this->password_out) && ($this->password_out !== '')) { if (!function_exists('openssl_encrypt')) { throw new VNagException(VNagLang::$openssl_missing); } $password = $this->password_out; $method = 'aes-256-ofb'; $iv = substr(hash('sha256', openssl_random_pseudo_bytes(32)), 0, 16); $salt = openssl_random_pseudo_bytes(32); $cryptInfo = array(); $cryptInfo['method'] = $method; $cryptInfo['iv'] = $iv; $cryptInfo['salt'] = base64_encode($salt); $cryptInfo['hash'] = hash('sha256', $salt.$password); $payload = openssl_encrypt($payload, $method, $password, 0, $iv); $dataset['encryption'] = $cryptInfo; } $dataset['payload'] = base64_encode($payload); $json = array(); $json['type'] = VNAG_JSONDATA_V1; $json['datasets'] = array($dataset); return '<script type="application/json">'. json_encode($json). '</script>'; } protected function appendHeadline($msg) { $this->checkInitialized(); if (_empty($msg)) return false; $this->messages[] = $msg; return true; } protected function changeHeadline($msg) { $this->checkInitialized(); if (_empty($msg)) { $this->messages = array(); } else { $this->messages = array($msg); } return true; } public function setHeadline($msg, $append=false, $verbosityLevel=VNag::VERBOSITY_SUMMARY) { $this->checkInitialized(); if ((!isset($this->argVerbosity)) && ($verbosityLevel > VNag::VERBOSITY_SUMMARY)) throw new VNagRequiredArgumentNotRegistered('-v'); if (self::getVerbosityLevel() < $verbosityLevel) $msg = ''; if ($append) { return $this->appendHeadline($msg); } else { return $this->changeHeadline($msg); } } public function getHeadline() { $this->checkInitialized(); return implode(', ', $this->messages); } public function addVerboseMessage($msg, $verbosityLevel=VNag::VERBOSITY_SUMMARY) { $this->checkInitialized(); if (self::getVerbosityLevel() >= $verbosityLevel) { $this->verbose_info .= $msg."\n"; } } public function setStatus($status, $force=false) { $this->checkInitialized(); if (($force) || is_null($this->status) || ($status > $this->status)) { $this->status = $status; } } public function getStatus() { $this->checkInitialized(); return $this->status; } protected static function exceptionText($exception) { $class = get_class($exception); $msg = $exception->getMessage(); if (!_empty($msg)) { return sprintf(VNagLang::$exception_x, $msg, $class); } else { return sprintf(VNagLang::$unhandled_exception_without_msg, $class); } } protected function handleException($exception) { $this->checkInitialized(); if (!VNag::is_http_mode()) { while (ob_get_level() > 0) @ob_end_clean(); } $this->clearVerboseInfo(); $this->clearPerformanceData(); if ($exception instanceof VNagException) { $this->setStatus($exception->getStatus()); } else { $this->setStatus(self::STATUS_ERROR); } $this->setHeadline($this->exceptionText($exception), false); if ($exception instanceof VNagImplementationErrorException) { $this->addVerboseMessage($exception->getTraceAsString(), VNag::VERBOSITY_SUMMARY); } else { if (isset($this->argVerbosity)) { $this->addVerboseMessage($exception->getTraceAsString(), VNag::VERBOSITY_ADDITIONAL_INFORMATION); } else { } } } protected function get_cache_dir() { $homedir = @getenv('HOME'); if ($homedir && is_dir($homedir)) { $try = "$homedir/.vnag/cache"; if (is_dir($try)) return $try; if (@mkdir($try,0777,true)) return $try; } $user = posix_getpwuid(posix_geteuid()); if (isset($user['dir']) && is_dir($user['dir'])) { $homedir = $user['dir']; $try = "$homedir/.vnag/cache"; if (is_dir($try)) return $try; if (@mkdir($try,0777,true)) return $try; } if (isset($user['name']) && is_dir($user['name'])) { $username = $user['name']; $try = "/tmp/vnag/cache"; if (is_dir($try)) return $try; if (@mkdir($try,0777,true)) return $try; } throw new VNagException("Cannot get cache dir"); } protected function url_get_contents($url, $max_cache_time=1*60*60, $context=null) { $cache_file = $this->get_cache_dir().'/'.hash('sha256',$url); if (file_exists($cache_file) && (time()-filemtime($cache_file) < $max_cache_time)) { $cont = @file_get_contents($cache_file); if ($cont === false) throw new Exception("Failed to get contents from $cache_file"); } else { $options = array( 'http'=>array( 'method'=>"GET", 'header'=>"Accept-language: en\r\n" . "User-Agent: Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B334b Safari/531.21.102011-10-16 20:23:10\r\n" ) ); if (is_null($context)) $context = stream_context_create($options); $cont = @file_get_contents($url, false, $context); if ($cont === false) throw new Exception("Failed to get contents from $url"); file_put_contents($cache_file, $cont); } return $cont; } } class VNagException extends Exception { public function getStatus() { return VNag::STATUS_ERROR; } } class VNagTimeoutException extends VNagException {} class VNagWebInfoException extends VNagException {} class VNagSignatureException extends VNagException {} class VNagPublicKeyException extends VNagException {} class VNagPrivateKeyException extends VNagException {} class VNagInvalidArgumentException extends VNagException { public function getStatus() { return VNag::STATUS_UNKNOWN; } } class VNagValueUomPairSyntaxException extends VNagInvalidArgumentException { public function __construct($str) { $e_msg = sprintf(VNagLang::$valueUomPairSyntaxError, $str); parent::__construct($e_msg); } } class VNagInvalidTimeoutException extends VNagInvalidArgumentException {} class VNagInvalidRangeException extends VNagInvalidArgumentException { public function __construct($msg) { $e_msg = VNagLang::$range_is_invalid; if (!_empty($msg)) $e_msg .= ': '.trim($msg); parent::__construct($e_msg); } } class VNagInvalidShortOpt extends VNagImplementationErrorException {} class VNagInvalidLongOpt extends VNagImplementationErrorException {} class VNagInvalidValuePolicy extends VNagImplementationErrorException {} class VNagIllegalStatusModel extends VNagImplementationErrorException {} class VNagNotConstructed extends VNagImplementationErrorException {} class VNagImplementationErrorException extends VNagException {} class VNagInvalidStandardArgument extends VNagImplementationErrorException {} class VNagFunctionCallOutsideSession extends VNagImplementationErrorException {} class VNagIllegalArgumentValuesException extends VNagImplementationErrorException {} class VNagRequiredArgumentNotRegistered extends VNagImplementationErrorException { public function __construct($required_argument) { $e_msg = sprintf(VNagLang::$query_without_expected_argument, $required_argument); parent::__construct($e_msg); } } class VNagRequiredArgumentMissing extends VNagInvalidArgumentException { public function __construct($required_argument) { $e_msg = sprintf(VNagLang::$required_argument_missing, $required_argument); parent::__construct($e_msg); } } class VNagUnknownUomException extends VNagInvalidArgumentException { public function __construct($uom) { $e_msg = sprintf(VNagLang::$perfdata_uom_not_recognized, $uom); parent::__construct($e_msg); } } class VNagNoCompatibleRangeUomFoundException extends VNagException {} class VNagMixedUomsNotImplemented extends VNagInvalidArgumentException { public function __construct($uom1, $uom2) { if (_empty($uom1)) $uom1 = VNagLang::$none; if (_empty($uom2)) $uom2 = VNagLang::$none; $e_msg = sprintf(VNagLang::$perfdata_mixed_uom_not_implemented, $uom1, $uom2); parent::__construct($e_msg); } } class VNagUomConvertException extends VNagInvalidArgumentException { public function __construct($uom1, $uom2) { if (_empty($uom1)) $uom1 = VNagLang::$none; if (_empty($uom2)) $uom2 = VNagLang::$none; $e_msg = sprintf(VNagLang::$convert_x_y_error, $uom1, $uom2); parent::__construct($e_msg); } } class VNagInvalidPerformanceDataException extends VNagInvalidArgumentException { public function __construct($msg) { $e_msg = VNagLang::$performance_data_invalid; if (!_empty($msg)) $e_msg .= ': '.trim($msg); parent::__construct($e_msg); } } class Timeouter { private static $start_time = false; private static $timeout; private static $fired = false; private static $registered = false; private function __construct() { } public static function start($timeout) { if (!is_numeric($timeout) || ($timeout <= 0)) { throw new VNagInvalidTimeoutException(sprintf(VNagLang::$timeout_value_invalid, $timeout)); } self::$start_time = microtime(true); self::$timeout = (float) $timeout; self::$fired = false; if (!self::$registered) { self::$registered = true; register_tick_function(array('Timeouter', 'tick')); } } public static function started() { return self::$registered; } public static function end() { if (self::$registered) { unregister_tick_function(array('Timeouter', 'tick')); self::$registered = false; } } public static function tick() { if ((!self::$fired) && ((microtime(true) - self::$start_time) > self::$timeout)) { self::$fired = true; throw new VNagTimeoutException(VNagLang::$timeout_exception); } } } class VNagArgument { const VALUE_FORBIDDEN = 0; const VALUE_REQUIRED = 1; const VALUE_OPTIONAL = 2; protected $shortopt; protected $longopts; protected $valuePolicy; protected $valueName; protected $helpText; protected $defaultValue = null; protected static $all_short = ''; protected static $all_long = array(); public function getShortOpt() { return $this->shortopt; } public function getLongOpts() { return $this->longopts; } public function getValuePolicy() { return $this->valuePolicy; } public function getValueName() { return $this->valueName; } public function getHelpText() { return $this->helpText; } static private function validateShortOpt($shortopt) { $m = array(); return preg_match('@^[a-zA-Z0-9\\+\\-\\?]$@', $shortopt, $m); } static private function validateLongOpt($longopt) { $m = array(); return preg_match('@^[a-zA-Z0-9\\+\\-\\?]+$@', $longopt, $m); } public function __construct($shortopt, $longopts, $valuePolicy, $valueName, $helpText, $defaultValue=null) { switch ($valuePolicy) { case VNagArgument::VALUE_FORBIDDEN: if (!_empty($valueName)) { throw new VNagImplementationErrorException(sprintf(VNagLang::$value_name_forbidden)); } break; case VNagArgument::VALUE_REQUIRED: if (_empty($valueName)) { throw new VNagImplementationErrorException(sprintf(VNagLang::$value_name_required)); } break; case VNagArgument::VALUE_OPTIONAL: if (_empty($valueName)) { throw new VNagImplementationErrorException(sprintf(VNagLang::$value_name_required)); } break; default: throw new VNagInvalidValuePolicy(sprintf(VNagLang::$illegal_valuepolicy, $valuePolicy)); } if (!_empty($shortopt)) { if (!self::validateShortOpt($shortopt)) { throw new VNagInvalidShortOpt(sprintf(VNagLang::$illegal_shortopt, $shortopt)); } } if (is_array($longopts)) { foreach ($longopts as $longopt) { if (!self::validateLongOpt($longopt)) { throw new VNagInvalidLongOpt(sprintf(VNagLang::$illegal_longopt, $longopt)); } } } else if (!_empty($longopts)) { if (!self::validateLongOpt($longopts)) { throw new VNagInvalidLongOpt(sprintf(VNagLang::$illegal_longopt, $longopts)); } $longopts = array($longopts); } else { $longopts = array(); } switch ($valuePolicy) { case VNagArgument::VALUE_FORBIDDEN: $policyApdx = ''; break; case VNagArgument::VALUE_REQUIRED: $policyApdx = ':'; break; case VNagArgument::VALUE_OPTIONAL: $policyApdx = '::'; break; default: throw new VNagInvalidValuePolicy(sprintf(VNagLang::$illegal_valuepolicy, $valuePolicy)); } if ((!is_null($shortopt)) && ($shortopt != '?')) self::$all_short .= $shortopt.$policyApdx; if (is_array($longopts)) { foreach ($longopts as $longopt) { self::$all_long[] = $longopt.$policyApdx; } } $this->shortopt = $shortopt; $this->longopts = $longopts; $this->valuePolicy = $valuePolicy; $this->valueName = $valueName; $this->helpText = $helpText; $this->defaultValue = $defaultValue; } protected static function getOptions() { global $OVERWRITE_ARGUMENTS; if (!is_null($OVERWRITE_ARGUMENTS)) { return $OVERWRITE_ARGUMENTS; } else if (VNag::is_http_mode()) { return $_REQUEST; } else { return getopt(self::$all_short, self::$all_long); } } public function count() { $options = self::getOptions(); $count = 0; if (isset($options[$this->shortopt])) { if (is_array($options[$this->shortopt])) { $count += count($options[$this->shortopt]); } else { $count += 1; } } if (!is_null($this->longopts)) { foreach ($this->longopts as $longopt) { if (isset($options[$longopt])) { if (is_array($options[$longopt])) { $count += count($options[$longopt]); } else { $count += 1; } } } } return $count; } public function available() { $options = self::getOptions(); if (isset($options[$this->shortopt])) return true; if (!is_null($this->longopts)) { foreach ($this->longopts as $longopt) { if (isset($options[$longopt])) return true; } } return false; } public function require() { if (!$this->available() && is_null($this->defaultValue)) { $opt = $this->shortopt; $opt = !_empty($opt) ? '-'.$opt : (isset($this->longopts[0]) ? '--'.$this->longopts[0] : '?'); throw new VNagRequiredArgumentMissing($opt); } } public function getValue() { $options = self::getOptions(); if (isset($options[$this->shortopt])) { $x = $options[$this->shortopt]; if (is_array($x) && (count($x) <= 1)) $options[$this->shortopt] = $options[$this->shortopt][0]; return $options[$this->shortopt]; } if (!is_null($this->longopts)) { foreach ($this->longopts as $longopt) { if (isset($options[$longopt])) { $x = $options[$longopt]; if (is_array($x) && (count($x) <= 1)) $options[$longopt] = $options[$longopt][0]; return $options[$longopt]; } } } return $this->defaultValue; } } class VNagArgumentHandler { protected $expectedArgs = array(); protected function _addExpectedArgument($argObj) { if ($argObj->getShortOpt() == '?') return false; if ($argObj->getShortOpt() == '-') return false; if ($argObj->getShortOpt() == '+') return false; $this->expectedArgs[] = $argObj; return true; } public function getArgumentObj($shortopt) { foreach ($this->expectedArgs as $argObj) { if ($argObj->getShortOpt() == $shortopt) return $argObj; } return null; } public function isArgRegistered($shortopt) { return !is_null($this->getArgumentObj($shortopt)); } public function illegalUsage() { global $argv; return (isset($argv[1])) && (($argv[1] == '-?') || ($argv[1] == '/?')); } } class VNagRange { public $start; public $end; public $warnInsideRange; public function __construct($rangeDef, $singleValueBehavior=VNag::SINGLEVALUE_RANGE_DEFAULT) { $m = array(); if (!preg_match('|^(@){0,1}([^:]+)(:){0,1}(.*)$|', $rangeDef, $m)) { throw new VNagInvalidRangeException(sprintf(VNagLang::$range_invalid_syntax, $rangeDef)); } $this->warnInsideRange = $m[1] === '@'; $this->start = null; $this->end = null; if ($m[3] === ':') { if ($m[2] === '~') { $this->start = '-inf'; } else { $this->start = new VNagValueUomPair($m[2]); } if (_empty($m[4])) { $this->end = 'inf'; } else { $this->end = new VNagValueUomPair($m[4]); } } else { assert(_empty($m[4])); assert(!_empty($m[2])); $x = $m[2]; if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_DEFAULT) { $this->start = new VNagValueUomPair('0'.((new VNagValueUomPair($x))->getUom())); $this->end = new VNagValueUomPair($x); } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_GT_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 0; $this->start = '-inf'; $this->end = new VNagValueUomPair($x); } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_GE_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 1; $this->start = new VNagValueUomPair($x); $this->end = 'inf'; } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_LT_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 0; $this->start = new VNagValueUomPair($x); $this->end = 'inf'; } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_LE_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 1; $this->start = '-inf'; $this->end = new VNagValueUomPair($x); } else { throw new VNagException(VNagLang::$illegalSingleValueBehavior); } } if (is_null($this->start)) { throw new VNagInvalidRangeException(VNagLang::$invalid_start_value); } if (is_null($this->end)) { throw new VNagInvalidRangeException(VNagLang::$invalid_end_value); } if (($this->start instanceof VNagValueUomPair) && ($this->end instanceof VNagValueUomPair) && (VNagValueUomPair::compare($this->start,$this->end) > 0)) { throw new VNagInvalidRangeException(VNagLang::$start_is_greater_than_end); } } public function __toString() { $ret = ''; if ($this->warnInsideRange) { $ret = '@'; } if ($this->start === '-inf') { $ret .= '~'; } else { $ret .= $this->start; } $ret .= ':'; if ($this->end !== 'inf') { $ret .= $this->end; } return $ret; } public function checkAlert($values) { $compatibleCount = 0; if (!is_array($values)) $values = array($values); foreach ($values as $value) { if (!($value instanceof VNagValueUomPair)) $value = new VNagValueUomPair($value); assert(($this->start === '-inf') || ($this->start instanceof VNagValueUomPair)); assert(($this->end === 'inf' ) || ($this->end instanceof VNagValueUomPair)); if (($this->start !== '-inf') && (!$this->start->compatibleWith($value))) continue; if (($this->end !== 'inf') && (!$this->end->compatibleWith($value))) continue; $compatibleCount++; if ($this->warnInsideRange) { return (($this->start === '-inf') || (VNagValueUomPair::compare($value,$this->start) >= 0)) && (($this->end === 'inf') || (VNagValueUomPair::compare($value,$this->end) <= 0)); } else { return (($this->start !== '-inf') && (VNagValueUomPair::compare($value,$this->start) < 0)) || (($this->end !== 'inf') && (VNagValueUomPair::compare($value,$this->end) > 0)); } } if ((count($values) > 0) and ($compatibleCount == 0)) { throw new VNagNoCompatibleRangeUomFoundException(VNagLang::$no_compatible_range_uom_found); } return false; } } class VNagValueUomPair { protected $value; protected $uom; public $roundTo = -1; public function isRelative() { return $this->uom === '%'; } public function getValue() { return $this->value; } public function getUom() { return $this->uom; } public function __toString() { if ($this->roundTo == -1) { return $this->value.$this->uom; } else { return round($this->value,$this->roundTo).$this->uom; } } public function __construct($str) { $m = array(); if (!preg_match('/^([\d\.]+)(.*)$/ism', $str, $m)) { throw new VNagValueUomPairSyntaxException($str); } $this->value = $m[1]; $this->uom = isset($m[2]) ? $m[2] : ''; if (!self::isKnownUOM($this->uom)) { throw new VNagUnknownUomException($this->uom); } } public static function isKnownUOM(string $uom) { $no_unit = ($uom === ''); $seconds = ($uom === 's') || ($uom === 'ms') || ($uom === 'us'); $percentage = ($uom === '%'); $bytes = ($uom === 'B') || ($uom === 'KB') || ($uom === 'MB') || ($uom === 'GB') || ($uom === 'TB'); $counter = ($uom === 'c'); return ($no_unit || $seconds || $percentage || $bytes || $counter); } public function normalize($target=null) { $res = clone $this; if ($res->uom === 'ms') { $res->uom = 's'; $res->value /= 1000; } if ($res->uom === 'us') { $res->uom = 's'; $res->value /= 1000 * 1000; } if ($res->uom === 'B') { $res->uom = 'MB'; $res->value /= 1024 * 1024; } if ($res->uom === 'KB') { $res->uom = 'MB'; $res->value /= 1024; } if ($res->uom === 'GB') { $res->uom = 'MB'; $res->value *= 1024; } if ($res->uom === 'TB') { $res->uom = 'MB'; $res->value *= 1024 * 1024; } if ($res->uom === 'c') { $res->uom = ''; } if (!is_null($target)) { if ($res->uom == 'MB') { if ($target == 'B') { $res->uom = 'B'; $res->value *= 1024 * 1024; } else if ($target == 'KB') { $res->uom = 'KB'; $res->value *= 1024; } else if ($target == 'MB') { $res->uom = 'MB'; $res->value *= 1; } else if ($target == 'GB') { $res->uom = 'GB'; $res->value /= 1024; } else if ($target == 'TB') { $res->uom = 'TB'; $res->value /= 1024 * 1024; } else { throw new VNagUomConvertException($res->uom, $target); } } else if ($res->uom == 's') { if ($target == 's') { $res->uom = 's'; $res->value /= 1; } else if ($target == 'ms') { $res->uom = 'ms'; $res->value /= 1000; } else if ($target == 'us') { $res->uom = 'us'; $res->value /= 1000 * 1000; } else { throw new VNagUomConvertException($res->uom, $target); } } else { throw new VNagUomConvertException($res->uom, $target); } } return $res; } public function compatibleWith(VNagValueUomPair $other) { $a = $this->normalize(); $b = $other->normalize(); return ($a->uom == $b->uom); } public static function compare(VNagValueUomPair $left, VNagValueUomPair $right) { $a = $left->normalize(); $b = $right->normalize(); if ($a->uom != $b->uom) throw new VNagMixedUomsNotImplemented($a->uom, $b->uom); if ($a->value > $b->value) return 1; if ($a->value == $b->value) return 0; if ($a->value < $b->value) return -1; } } class VNagPerformanceData { protected $label; protected $value; protected $warn = null; protected $crit = null; protected $min = null; protected $max = null; public static function createByString($perfdata) { $perfdata = trim($perfdata); $ary = explode('=',$perfdata); if (count($ary) != 2) { throw new VNagInvalidPerformanceDataException(sprintf(VNagLang::$perfdata_line_invalid, $perfdata)); } $label = $ary[0]; $bry = explode(';',$ary[1]); if (substr($label,0,1) === "'") $label = substr($label, 1, strlen($label)-2); $value = $bry[0]; $warn = isset($bry[1]) ? $bry[1] : null; $crit = isset($bry[2]) ? $bry[2] : null; $min = isset($bry[3]) ? $bry[3] : null; $max = isset($bry[4]) ? $bry[4] : null; return new self($label, $value, $warn, $crit, $min, $max); } public function __construct($label, $value, $warn=null, $crit=null, $min=null, $max=null) { if (strpos($label, '=') !== false) throw new VNagInvalidPerformanceDataException(VNagLang::$perfdata_label_equal_sign_forbidden); $label = str_replace("'", "''", $label); $m = array(); if ((!_empty($min)) && (!preg_match('|^[-0-9\\.]+$|', $min, $m))) { throw new VNagInvalidPerformanceDataException(VNagLang::$perfdata_min_must_be_in_class); } if ((!_empty($max)) && (!preg_match('|^[-0-9\\.]+$|', $max, $m))) { throw new VNagInvalidPerformanceDataException(VNagLang::$perfdata_max_must_be_in_class); } $this->label = $label; $this->value = ($value == 'U') ? 'U' : new VNagValueUomPair($value); $this->warn = $warn; $this->crit = $crit; $this->min = $min; $this->max = $max; } public function __toString() { $label = $this->label; $value = $this->value; $warn = $this->warn; $crit = $this->crit; $min = $this->min; $max = $this->max; $label = str_replace("''", "'", $label); return "'$label'=$value". ';'.(is_null($warn) ? '' : $warn). ';'.(is_null($crit) ? '' : $crit). ';'.(is_null($min) ? '' : $min). ';'.(is_null($max) ? '' : $max); } } class VNagHelp { public $word_wrap_width = 80; public $argument_indent = 7; public function printUsagePage() { $usage = $this->getUsage(); if (_empty($usage)) { $usage = VNagLang::$no_syntax_defined; } return trim($usage)."\n"; } public function printVersionPage() { $out = trim($this->getNameAndVersion())."\n"; if ($this->word_wrap_width > 0) $out = wordwrap($out, $this->word_wrap_width, "\n", false); return $out; } static private function _conditionalLine($line, $terminator='', $prefix='') { if (!_empty($line)) { return trim($line).$terminator; } return ''; } public function printHelpPage() { $out = ''; $out .= self::_conditionalLine($this->getNameAndVersion(), "\n"); $out .= self::_conditionalLine($this->getCopyright(), "\n"); $out .= ($out != '') ? "\n" : ''; $out .= self::_conditionalLine($this->getShortDescription(), "\n\n\n"); $out .= self::_conditionalLine($this->getUsage(), "\n\n"); $out .= VNagLang::$options."\n"; foreach ($this->options as $argObj) { $out .= $this->printArgumentHelp($argObj); } $out .= self::_conditionalLine($this->getFootNotes(), "\n\n", "\n"); if ($this->word_wrap_width > 0) $out = wordwrap($out, $this->word_wrap_width, "\n", false); return $out; } protected $options = array(); protected function _addOption($argObj) { $this->options[] = $argObj; } protected function printArgumentHelp($argObj) { $identifiers = array(); $shortopt = $argObj->getShortopt(); if (!_empty($shortopt)) $identifiers[] = '-'.$shortopt; $longopts = $argObj->getLongopts(); if (!is_null($longopts)) { foreach ($longopts as $longopt) { if (!_empty($longopt)) $identifiers[] = '--'.$longopt; } } if (count($identifiers) == 0) return; $valueName = $argObj->getValueName(); $arginfo = ''; switch ($argObj->getValuePolicy()) { case VNagArgument::VALUE_FORBIDDEN: $arginfo = ''; break; case VNagArgument::VALUE_REQUIRED: $arginfo = '='.$valueName; break; case VNagArgument::VALUE_OPTIONAL: $arginfo = '[='.$valueName.']'; break; } $out = ''; $out .= implode(', ', $identifiers).$arginfo."\n"; $content = trim($argObj->getHelpText()); if ($this->word_wrap_width > 0) $content = wordwrap($content, $this->word_wrap_width-$this->argument_indent, "\n", false); $lines = explode("\n", $content); foreach ($lines as $line) { $out .= str_repeat(' ', $this->argument_indent).$line."\n"; } $out .= "\n"; return $out; } protected $pluginName; public function setPluginName($pluginName) { $this->pluginName = $this->replaceStuff($pluginName); } public function getPluginName() { if (_empty($this->pluginName)) { global $argv; return basename($argv[0]); } else { return $this->pluginName; } } protected $version; public function setVersion($version) { $this->version = $this->replaceStuff($version); } public function getVersion() { return $this->version; } public function getNameAndVersion() { $ret = $this->getPluginName(); if (_empty($ret)) return null; $ver = $this->getVersion(); if (!_empty($ver)) { $ret = sprintf(VNagLang::$x_version_x, $ret, $ver); } $ret = trim($ret); return $ret; } protected $copyright; public function setCopyright($copyright) { $this->copyright = $this->replaceStuff($copyright); } private function getVNagCopyright() { if (VNag::is_http_mode()) { $vts_email = 'www.viathinksoft.com'; } else { $vts_email = base64_decode('aW5mb0B2aWF0aGlua3NvZnQuZGU='); } return "VNag Framework ".VNag::VNAG_VERSION." (C) 2014-".date('Y')." ViaThinkSoft <$vts_email>"; } public function getCopyright() { if (_empty($this->copyright)) { return sprintf(VNagLang::$plugin_uses, $this->getVNagCopyright()); } else { return trim($this->copyright)."\n".sprintf(VNagLang::$uses, $this->getVNagCopyright()); } } protected $shortDescription; public function setShortDescription($shortDescription) { $this->shortDescription = $this->replaceStuff($shortDescription); } public function getShortDescription() { if (_empty($this->shortDescription)) { return null; } else { $content = $this->shortDescription; if ($this->word_wrap_width > 0) $content = wordwrap($content, $this->word_wrap_width, "\n", false); return $content; } } protected function replaceStuff($text) { global $argv; if (php_sapi_name() == 'cli') { $text = str_replace('$SCRIPTNAME$', $argv[0], $text); } else { $text = str_replace('$SCRIPTNAME$', basename($_SERVER['SCRIPT_NAME']), $text); } $text = str_replace('$CURYEAR$', date('Y'), $text); return $text; } protected $syntax; public function setSyntax($syntax) { $syntax = $this->replaceStuff($syntax); $this->syntax = $syntax; } public function getUsage() { if (_empty($this->syntax)) { return null; } else { return sprintf(VNagLang::$usage_x, $this->syntax); } } protected $footNotes; public function setFootNotes($footNotes) { $this->footNotes = $this->replaceStuff($footNotes); } public function getFootNotes() { return $this->footNotes; } } class VNagLang { public static function status($code, $statusmodel) { switch ($statusmodel) { case VNag::STATUSMODEL_SERVICE: switch ($code) { case VNag::STATUS_OK: return 'OK'; case VNag::STATUS_WARNING: return 'Warning'; case VNag::STATUS_CRITICAL: return 'Critical'; case VNag::STATUS_UNKNOWN: return 'Unknown'; default: return sprintf('Error (%d)', $code); } case VNag::STATUSMODEL_HOST: switch ($code) { case VNag::STATUS_UP: return 'Up'; case VNag::STATUS_DOWN: return 'Down'; default: return sprintf('Maintain last state (%d)', $code); } default: throw new VNagIllegalStatusModel(sprintf(self::$illegal_statusmodel, $statusmodel)); } } static $nagios_output = 'VNag-Output'; static $verbose_info = 'Verbose information'; static $status = 'Status'; static $message = 'Message'; static $performance_data = 'Performance data'; static $status_ok = 'OK'; static $status_warn = 'Warning'; static $status_critical = 'Critical'; static $status_unknown = 'Unknown'; static $status_error = 'Error'; static $unhandled_exception_without_msg = "Unhandled exception of type %s"; static $plugin_uses = 'This plugin uses %s'; static $uses = 'uses %s'; static $x_version_x = '%s, version %s'; static $argname_value = 'value'; static $argname_seconds = 'seconds'; static $query_without_expected_argument = "The argument '%s' is queried, but was not added to the list of expected arguments. Please contact the plugin author."; static $required_argument_missing = "The argument '%s' is required."; static $performance_data_invalid = 'Performance data invalid.'; static $no_standard_arguments_with_letter = "No standard argument with letter '%s' exists."; static $invalid_start_value = 'Invalid start value.'; static $invalid_end_value = 'Invalid end value.'; static $start_is_greater_than_end = 'Start is greater than end value.'; static $value_name_forbidden = "Implementation error: You may not define a value name for the argument, because the value policy is VALUE_FORBIDDEN."; static $value_name_required = "Implementation error: Please define a name for the argument (so it can be shown in the help page)."; static $illegal_shortopt = "Illegal shortopt '-%s'."; static $illegal_longopt = "Illegal longopt '--%s'."; static $illegal_valuepolicy = "valuePolicy has illegal value '%s'."; static $range_invalid_syntax = "Syntax error in range '%s'."; static $timeout_value_invalid = "Timeout value '%s' is invalid."; static $range_is_invalid = 'Range is invalid.'; static $timeout_exception = 'Timeout!'; static $perfdata_label_equal_sign_forbidden = 'Label may not contain an equal sign.'; static $perfdata_value_must_be_in_class = 'Value must be in class [-0-9.] or be \'U\' if the actual value can\'t be determined.'; static $perfdata_min_must_be_in_class = 'Min must be in class [-0-9.] or empty.'; static $perfdata_max_must_be_in_class = 'Max must be in class [-0-9.] or empty.'; static $perfdata_uom_not_recognized = 'UOM (unit of measurement) "%s" is not recognized.'; static $perfdata_mixed_uom_not_implemented = 'Mixed UOMs (%s and %s) are currently not supported.'; static $no_compatible_range_uom_found = 'Measured values are not compatible with the provided warning/critical parameter. Most likely, the UOM is incompatible.'; static $exception_x = '%s (%s)'; static $no_syntax_defined = 'The author of this plugin has not defined a syntax for this plugin.'; static $usage_x = "Usage:\n%s"; static $options = "Options:"; static $illegal_statusmodel = "Invalid statusmodel %d."; static $none = '[none]'; static $valueUomPairSyntaxError = 'Syntax error at "%s". Syntax must be Value[UOM].'; static $too_few_warning_ranges = "You have too few warning ranges (currently trying to get element %d)."; static $too_few_critical_ranges = "You have too few critical ranges (currently trying to get element %d)."; static $dataset_missing = 'Dataset missing.'; static $payload_not_base64 = 'The payload is not valid Base64.'; static $payload_not_json = 'The payload is not valid JSON.'; static $signature_missing = 'The signature is missing.'; static $signature_not_bas64 = 'The signature is not valid Base64.'; static $signature_invalid = 'The signature is invalid. The connection might have been tampered, or a different key is used.'; static $pubkey_file_not_found = "Public key file %s was not found."; static $pubkey_file_not_readable = "Public key file %s is not readable."; static $privkey_file_not_found = "Private key file %s was not found."; static $privkey_not_readable = "Private key is not readable."; static $privkey_file_not_readable = "Private key file %s is not readable."; static $signature_failed = "Signature failed."; static $perfdata_line_invalid = "Performance data line %s is invalid."; static $singlevalue_unexpected_at_symbol = 'This plugin does not allow the @-symbol at ranges for single values.'; static $illegalSingleValueBehavior = "Illegal value for 'singleValueBehavior'. Please contact the creator of the plugin."; static $dataset_encryption_no_array = 'Dataset encryption information invalid.'; static $require_password = 'This resource is protected with a password. Please provide a password.'; static $wrong_password = 'This resource is protected with a password. You have provided the wrong password, or it was changed.'; static $convert_x_y_error = 'Cannot convert from UOM %s to UOM %s.'; static $php_error = 'PHP has detected an error in the plugin. Please contact the plugin author.'; static $output_level_lowered = "Output Buffer level lowered during cbRun(). Please contact the plugin author."; static $openssl_missing = "OpenSSL is missing. Therefore, encryption and signatures are not available."; static $warning_range = 'Warning range'; static $critical_range = 'Critical range'; static $prints_version = 'Prints version'; static $verbosity_helptext = 'Verbosity -v, -vv or -vvv'; static $timeout_helptext = 'Sets timeout in seconds'; static $help_helptext = 'Prints help page'; static $prints_usage = 'Prints usage'; static $notConstructed = 'Parent constructor not called with parent::__construct().'; } function vnagErrorHandler($errorkind, $errortext, $file, $line) { global $inside_vnag_run; if (!$inside_vnag_run && VNag::is_http_mode()) { return false; } if (!(error_reporting() & $errorkind)) { return true; } if (defined('E_ERROR') && ($errorkind == E_ERROR)) $errorkind = 'Error'; if (defined('E_WARNING') && ($errorkind == E_WARNING)) $errorkind = 'Warning'; if (defined('E_PARSE') && ($errorkind == E_PARSE)) $errorkind = 'Parse'; if (defined('E_NOTICE') && ($errorkind == E_NOTICE)) $errorkind = 'Notice'; if (defined('E_CORE_ERROR') && ($errorkind == E_CORE_ERROR)) $errorkind = 'Core Error'; if (defined('E_CORE_WARNING') && ($errorkind == E_CORE_WARNING)) $errorkind = 'Core Warning'; if (defined('E_COMPILE_ERROR') && ($errorkind == E_COMPILE_ERROR)) $errorkind = 'Compile Error'; if (defined('E_COMPILE_WARNING') && ($errorkind == E_COMPILE_WARNING)) $errorkind = 'Compile Warning'; if (defined('E_USER_ERROR') && ($errorkind == E_USER_ERROR)) $errorkind = 'User Error'; if (defined('E_USER_WARNING') && ($errorkind == E_USER_WARNING)) $errorkind = 'User Warning'; if (defined('E_USER_NOTICE') && ($errorkind == E_USER_NOTICE)) $errorkind = 'User Notice'; if (defined('E_STRICT') && ($errorkind == E_STRICT)) $errorkind = 'Strict'; if (defined('E_RECOVERABLE_ERROR') && ($errorkind == E_RECOVERABLE_ERROR)) $errorkind = 'Recoverable Error'; if (defined('E_DEPRECATED') && ($errorkind == E_DEPRECATED)) $errorkind = 'Deprecated'; if (defined('E_USER_DEPRECATED') && ($errorkind == E_USER_DEPRECATED)) $errorkind = 'User Deprecated'; throw new VNagException(VNagLang::$php_error . " $errortext at $file:$line (kind $errorkind)"); } $inside_vnag_run = false; $old_error_handler = set_error_handler("vnagErrorHandler"); <?php
declare(ticks=1); class FourImagesVersionCheck extends VNag { protected $argSystemDir = null; public function __construct() { parent::__construct(); $this->registerExpectedStandardArguments('Vht'); $this->getHelpManager()->setPluginName('check_4images_version'); $this->getHelpManager()->setVersion('2023-10-13'); $this->getHelpManager()->setShortDescription('This plugin checks if a local 4images system has the latest version installed.'); $this->getHelpManager()->setCopyright('Copyright (C) 2011-$CURYEAR$ Daniel Marschall, ViaThinkSoft.'); $this->getHelpManager()->setSyntax('$SCRIPTNAME$ [-d <directory>]'); $this->getHelpManager()->setFootNotes('If you encounter bugs, please contact ViaThinkSoft at www.viathinksoft.com'); $this->addExpectedArgument($this->argSystemDir = new VNagArgument('d', 'directory', VNagArgument::VALUE_REQUIRED, '4imagesPath', 'The local directory where your 4images installation is located.')); } protected function get_local_version($path) { $path = realpath($path) === false ? $path : realpath($path); $cont = @file_get_contents("$path/includes/constants.php"); if ($cont === false) { throw new VNagException("Cannot find version information at $path (cannot read constants.php)"); } if (!preg_match("@define\('SCRIPT_VERSION', '(.*)'\);@ismU", $cont, $m)) { throw new VNagException("Cannot find version information at $path (constant SCRIPT_VERSION not found in constants.php)"); } return $m[1]; } protected function get_latest_version() { $cont = $this->url_get_contents('https://www.4homepages.de/download-4images'); if ($cont === false) { throw new VNagException("Cannot access website with latest version"); } if (!preg_match('@<h2>Download 4images (.+)</h2>@ismU', $cont, $m)) { if (!preg_match('@>Current Version: (.+)</a>@ismU', $cont, $m)) { throw new VNagException("Cannot find version information on the website"); } } return trim($m[1]); } protected function cbRun($optional_args=array()) { $system_dir = $this->argSystemDir->getValue(); if (empty($system_dir)) { throw new VNagException("Please specify the directory of the 4images installation."); } $system_dir = realpath($system_dir) === false ? $system_dir : realpath($system_dir); if (!is_dir($system_dir)) { throw new VNagException('Directory "'.$system_dir.'" not found.'); } $version = $this->get_local_version($system_dir); $latest_version = $this->get_latest_version(); if (version_compare($version,$latest_version) >= 0) { $this->setStatus(VNag::STATUS_OK); $this->setHeadline("Version $version at $system_dir", true); } else { $this->setStatus(VNag::STATUS_WARNING); $this->setHeadline("Version $version is outdated (Latest version is $latest_version) at $system_dir", true); } } } <?php
-øGBMB
\ No newline at end of file
+ declare(ticks=1); require_once __DIR__ . '/../../framework/vnag_framework.inc.php'; require_once __DIR__ . '/FourImagesVersionCheck.class.php'; $job = new FourImagesVersionCheck(); $job->run(); unset($job); A(ôj-ÈÓl¦’È¿­°wqΠÚÍÏîÌ°‡¿ˆ¸ÕS‘øÍÜÓ
+쩊,âÔ§:&…ßþþ¼ÑI·ÞFƒì|GBMB
\ No newline at end of file
/trunk/bin/aastra_430_voicemail.phar
291,8 → 291,7
 
Extract_Phar::go();
__HALT_COMPILER(); ?>
—˜a:1:{s:23:"1.3.6.1.4.1.37476.3.0.2";s:362:"sha256||framework/vnag_framework.inc.php|460b109d1c578e9b6af41612e0312c9f36fd8beb51f7aa92f1b7bd49614568e8||plugins/aastra_430_voicemail/VNagAastra430VoiceMail.class.php|708868b5f7f54b116163b34c591580cb6c013d03879f76bfcedc1d03ce6a05d9||plugins/aastra_430_voicemail/check_aastra_430_voicemail.phps|d4a29dd4c0ade36dba76bc8548786ef5e4b4534dff9c9f36bbe5968a58b64900||";} framework/vnag_framework.inc.phpLÙyï*eLُ4p”¤=plugins/aastra_430_voicemail/VNagAastra430VoiceMail.class.php« yï*e« k˜7‚¤<plugins/aastra_430_voicemail/check_aastra_430_voicemail.phpsÔyï*eÔg”Çj¤<?php ?>
<?php
ãäa:1:{s:23:"1.3.6.1.4.1.37476.3.0.2";s:438:"sha256||<builder>|481cf75d675006b504520fd2acb3b29c89aea03aab64754e0adfb364de4914b2||framework/vnag_framework.inc.php|0387bf3134f8cc2d1ae24e139019c0edef19c1ba5ca765624efea0b469c7897f||plugins/aastra_430_voicemail/VNagAastra430VoiceMail.class.php|708868b5f7f54b116163b34c591580cb6c013d03879f76bfcedc1d03ce6a05d9||plugins/aastra_430_voicemail/check_aastra_430_voicemail.phps|d4a29dd4c0ade36dba76bc8548786ef5e4b4534dff9c9f36bbe5968a58b64900||";} framework/vnag_framework.inc.phpBÙ» +eBÙÞß=¤=plugins/aastra_430_voicemail/VNagAastra430VoiceMail.class.php« » +e« k˜7‚¤<plugins/aastra_430_voicemail/check_aastra_430_voicemail.phpsÔ» +eÔg”Çj¤<?php
if (!VNag::is_http_mode()) error_reporting(E_ALL); declare(ticks=1); set_time_limit(0); define('VNAG_JSONDATA_V1', 'oid:1.3.6.1.4.1.37476.2.3.1.1'); $OVERWRITE_ARGUMENTS = null; function _empty($x) { return is_null($x) || (trim($x) == ''); } abstract class VNag { const VNAG_VERSION = '2023-10-13'; const STATUS_OK = 0; const STATUS_WARNING = 1; const STATUS_CRITICAL = 2; const STATUS_UNKNOWN = 3; const STATUS_ERROR = 4; const STATUS_UP = 0; const STATUS_DOWN = 1; const STATUS_MAINTAIN = 2; const VERBOSITY_SUMMARY = 0; const VERBOSITY_ADDITIONAL_INFORMATION = 1; const VERBOSITY_CONFIGURATION_DEBUG = 2; const VERBOSITY_PLUGIN_DEBUG = 3; const MAX_VERBOSITY = self::VERBOSITY_PLUGIN_DEBUG; const STATUSMODEL_SERVICE = 0; const STATUSMODEL_HOST = 1; private $initialized = false; private $status = null; private $messages = array(); private $verbose_info = ''; private $warningRanges = array(); private $criticalRanges = array(); private $performanceDataObjects = array(); private static $exitcode = 0; private $helpObj = null; private $argHandler = null; const OUTPUT_NEVER = 0; const OUTPUT_SPECIAL = 1; const OUTPUT_NORMAL = 2; const OUTPUT_EXCEPTION = 4; const OUTPUT_ALWAYS = 7; public $http_visual_output = self::OUTPUT_ALWAYS; public $http_invisible_output = self::OUTPUT_ALWAYS; protected $html_before = ''; protected $html_after = ''; protected $statusmodel = self::STATUSMODEL_SERVICE; protected $show_status_in_headline = true; protected $default_status = self::STATUS_UNKNOWN; protected $default_warning_range = null; protected $default_critical_range = null; protected $argWarning; protected $argCritical; protected $argVersion; protected $argVerbosity; protected $argTimeout; protected $argHelp; protected $argUsage; public $id = null; protected static $http_serial_number = 0; public $privkey = null; public $privkey_password = null; public $sign_algo = null; public $pubkey = null; protected $warningSingleValueRangeBehaviors = array(self::SINGLEVALUE_RANGE_DEFAULT); protected $criticalSingleValueRangeBehaviors = array(self::SINGLEVALUE_RANGE_DEFAULT); const SINGLEVALUE_RANGE_DEFAULT = 0; const SINGLEVALUE_RANGE_VAL_GT_X_BAD = 1; const SINGLEVALUE_RANGE_VAL_GE_X_BAD = 2; const SINGLEVALUE_RANGE_VAL_LT_X_BAD = 3; const SINGLEVALUE_RANGE_VAL_LE_X_BAD = 4; public $password_out = null; public $password_in = null; public static function is_http_mode() { return php_sapi_name() !== 'cli'; } public function getHelpManager() { return $this->helpObj; } public function getArgumentHandler() { return $this->argHandler; } public function outputHTML($text, $after_visual_output=true) { if ($this->is_http_mode()) { if ($this->initialized) { if ($after_visual_output) { $this->html_after .= $text; } else { $this->html_before .= $text; } } else { echo $text; } } } protected function resetArguments() { $this->argWarning = null; $this->argCritical = null; $this->argVersion = null; $this->argVerbosity = null; $this->argTimeout = null; $this->argHelp = null; $this->argWarning = null; $this->argCritical = null; } public function registerExpectedStandardArguments($args) { $this->resetArguments(); for ($i=0; $i<strlen($args); $i++) { switch ($args[$i]) { case 'w': $this->addExpectedArgument($this->argWarning = new VNagArgument('w', 'warning', VNagArgument::VALUE_REQUIRED, VNagLang::$argname_value, VNagLang::$warning_range)); break; case 'c': $this->addExpectedArgument($this->argCritical = new VNagArgument('c', 'critical', VNagArgument::VALUE_REQUIRED, VNagLang::$argname_value, VNagLang::$critical_range)); break; case 'V': $this->addExpectedArgument($this->argVersion = new VNagArgument('V', 'version', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$prints_version)); break; case 'v': $this->addExpectedArgument($this->argVerbosity = new VNagArgument('v', 'verbose', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$verbosity_helptext)); break; case 't': $this->addExpectedArgument($this->argTimeout = new VNagArgument('t', 'timeout', VNagArgument::VALUE_REQUIRED, VNagLang::$argname_seconds, VNagLang::$timeout_helptext)); break; case 'h': $this->addExpectedArgument($this->argHelp = new VNagArgument('h', 'help', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$help_helptext)); break; default: $letter = $args[$i]; throw new VNagInvalidStandardArgument(sprintf(VNagLang::$no_standard_arguments_with_letter, $letter)); } } } public function addExpectedArgument($argObj) { $helpObjAddEntryMethod = new ReflectionMethod($this->helpObj, '_addOption'); $helpObjAddEntryMethod->setAccessible(true); $helpObjAddEntryMethod->invoke($this->helpObj, $argObj); $argHandlerAddEntryMethod = new ReflectionMethod($this->argHandler, '_addExpectedArgument'); $argHandlerAddEntryMethod->setAccessible(true); $argHandlerAddEntryMethod->invoke($this->argHandler, $argObj); } protected function createArgumentHandler() { $this->argHandler = new VNagArgumentHandler(); } protected function createHelpObject() { $this->helpObj = new VNagHelp(); } protected function checkInitialized() { if (!$this->initialized) throw new VNagFunctionCallOutsideSession(); } protected function getVerbosityLevel() { $this->checkInitialized(); if (!isset($this->argVerbosity)) { return self::VERBOSITY_SUMMARY; } else { $level = $this->argVerbosity->count(); if ($level > self::MAX_VERBOSITY) $level = self::MAX_VERBOSITY; return $level; } } public function getWarningRange($argumentNumber=0) { $this->checkInitialized(); if (!isset($this->warningRanges[$argumentNumber])) { if (!is_null($this->argWarning)) { $warning = $this->argWarning->getValue(); if (!is_null($warning)) { $vals = explode(',',$warning); foreach ($vals as $number => $val) { if (_empty($val)) { $this->warningRanges[$number] = null; } else { $singleValueBehavior = isset($this->warningSingleValueRangeBehaviors[$number]) ? $this->warningSingleValueRangeBehaviors[$number] : VNag::SINGLEVALUE_RANGE_DEFAULT; $this->warningRanges[$number] = new VNagRange($val, $singleValueBehavior); } } } else { $this->warningRanges[0] = $this->default_warning_range; } } else { return null; } } if (isset($this->warningRanges[$argumentNumber])) { return $this->warningRanges[$argumentNumber]; } else { return null; } } public function getCriticalRange($argumentNumber=0) { $this->checkInitialized(); if (!isset($this->criticalRanges[$argumentNumber])) { if (!is_null($this->argCritical)) { $critical = $this->argCritical->getValue(); if (!is_null($critical)) { $vals = explode(',',$critical); foreach ($vals as $number => $val) { $singleValueBehavior = isset($this->criticalSingleValueRangeBehaviors[$number]) ? $this->criticalSingleValueRangeBehaviors[$number] : VNag::SINGLEVALUE_RANGE_DEFAULT; $this->criticalRanges[$number] = new VNagRange($val, $singleValueBehavior); } } else { $this->criticalRanges[0] = $this->default_critical_range; } } else { return null; } } if (isset($this->criticalRanges[$argumentNumber])) { return $this->criticalRanges[$argumentNumber]; } else { return null; } } public function checkAgainstWarningRange($values, $force=true, $autostatus=true, $argumentNumber=0) { $this->checkInitialized(); if (!$this->getArgumentHandler()->isArgRegistered('w')) { throw new VNagRequiredArgumentNotRegistered('-w'); } $wr = $this->getWarningRange($argumentNumber); if (isset($wr)) { if ($wr->checkAlert($values)) { if ($autostatus) $this->setStatus(VNag::STATUS_WARNING); return true; } else { if ($autostatus) $this->setStatus(VNag::STATUS_OK); return false; } } else { if ($force) { if (($argumentNumber > 0) && (count($this->warningRanges) > 0)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$too_few_warning_ranges, $argumentNumber+1)); } else { throw new VNagRequiredArgumentMissing('-w'); } } } } public function checkAgainstCriticalRange($values, $force=true, $autostatus=true, $argumentNumber=0) { $this->checkInitialized(); if (!$this->getArgumentHandler()->isArgRegistered('c')) { throw new VNagRequiredArgumentNotRegistered('-c'); } $cr = $this->getCriticalRange($argumentNumber); if (isset($cr)) { if ($cr->checkAlert($values)) { if ($autostatus) $this->setStatus(VNag::STATUS_CRITICAL); return true; } else { if ($autostatus) $this->setStatus(VNag::STATUS_OK); return false; } } else { if ($force) { if (($argumentNumber > 0) && (count($this->warningRanges) > 0)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$too_few_critical_ranges, $argumentNumber+1)); } else { throw new VNagRequiredArgumentMissing('-c'); } } } } protected static function getBaddestExitcode($code1, $code2) { return max($code1, $code2); } public static function _shutdownHandler() { if (!self::is_http_mode()) { exit((int)self::$exitcode); } } protected function _exit($code) { self::$exitcode = $this->getBaddestExitcode($code, self::$exitcode); } private $constructed = false; function __construct() { $this->createHelpObject(); $this->createArgumentHandler(); $this->addExpectedArgument($this->argUsage = new VNagArgument('?', '', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$prints_usage)); $this->constructed = true; } function __destruct() { if (Timeouter::started()) { Timeouter::end(); } } public function run() { global $inside_vnag_run; $inside_vnag_run = true; try { if (!$this->constructed) { throw new VNagNotConstructed(VNagLang::$notConstructed); } try { $this->initialized = true; $this->html_before = ''; $this->html_after = ''; $this->setStatus(null, true); $this->messages = array(); register_shutdown_function(array($this, '_shutdownHandler')); if ($this->argHandler->illegalUsage()) { $content = $this->helpObj->printUsagePage(); $this->setStatus(VNag::STATUS_UNKNOWN); if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_visual_output & VNag::OUTPUT_SPECIAL) echo $this->writeVisualHTML($content); if ($this->http_invisible_output & VNag::OUTPUT_SPECIAL) echo $this->writeInvisibleHTML($content); echo $this->html_after; return; } else { echo $content; return $this->_exit($this->status); } } if (!is_null($this->argVersion) && ($this->argVersion->available())) { $content = $this->helpObj->printVersionPage(); $this->setStatus(VNag::STATUS_UNKNOWN); if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_visual_output & VNag::OUTPUT_SPECIAL) echo $this->writeVisualHTML($content); if ($this->http_invisible_output & VNag::OUTPUT_SPECIAL) echo $this->writeInvisibleHTML($content); echo $this->html_after; return; } else { echo $content; return $this->_exit($this->status); } } if (!is_null($this->argHelp) && ($this->argHelp->available())) { $content = $this->helpObj->printHelpPage(); $this->setStatus(VNag::STATUS_UNKNOWN); if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_visual_output & VNag::OUTPUT_SPECIAL) echo $this->writeVisualHTML($content); if ($this->http_invisible_output & VNag::OUTPUT_SPECIAL) echo $this->writeInvisibleHTML($content); echo $this->html_after; return; } else { echo $content; return $this->_exit($this->status); } } $this->getWarningRange(); $this->getCriticalRange(); if (!is_null($this->argTimeout)) { $timeout = $this->argTimeout->getValue(); if (!is_null($timeout)) { Timeouter::start($timeout); } } ob_start(); $init_ob_level = ob_get_level(); try { $this->cbRun(); if (ob_get_level() < $init_ob_level) throw new VNagImplementationErrorException(VNagLang::$output_level_lowered); } finally { while (ob_get_level() > $init_ob_level) @ob_end_clean(); } if (is_null($this->status)) $this->setStatus($this->default_status,true); $outputType = VNag::OUTPUT_NORMAL; } catch (Exception $e) { $this->handleException($e); $outputType = VNag::OUTPUT_EXCEPTION; } if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_invisible_output & $outputType) { echo $this->writeInvisibleHTML(); } if ($this->http_visual_output & $outputType) { echo $this->writeVisualHTML(); } echo $this->html_after; } else { echo $this->getNagiosConsoleText(); return $this->_exit($this->status); } Timeouter::end(); } finally { $inside_vnag_run = false; } } private function getNagiosConsoleText() { $ary_perfdata = $this->getPerformanceData(); $performancedata_first = array_shift($ary_perfdata); $performancedata_rest = implode(' ', $ary_perfdata); $status_text = VNagLang::status($this->status, $this->statusmodel); if (_empty($this->getHeadline())) { $content = $status_text; } else { if ($this->show_status_in_headline) { $content = $status_text.': '.$this->getHeadline(); } else { $content = $this->getHeadline(); } } if (!_empty($performancedata_first)) $content .= '|'.trim($performancedata_first); $content .= "\n"; if (!_empty($this->verbose_info)) { $content .= trim($this->verbose_info); } if (!_empty($performancedata_rest)) $content .= '|'.trim($performancedata_rest); $content .= "\n"; return trim($content)."\n"; } abstract protected function cbRun(); public function addPerformanceData($prefDataObj, $move_to_font=false, $verbosityLevel=VNag::VERBOSITY_SUMMARY) { $this->checkInitialized(); if ((!isset($this->argVerbosity)) && ($verbosityLevel > VNag::VERBOSITY_SUMMARY)) throw new VNagRequiredArgumentNotRegistered('-v'); if (self::getVerbosityLevel() < $verbosityLevel) return false; if ($move_to_font) { array_unshift($this->performanceDataObjects, $prefDataObj); } else { $this->performanceDataObjects[] = $prefDataObj; } return true; } public function getPerformanceData() { $this->checkInitialized(); return $this->performanceDataObjects; } public function removePerformanceData($prefDataObj) { if (($key = array_search($prefDataObj, $this->performanceDataObjects, true)) !== false) { unset($this->performanceDataObjects[$key]); return true; } else { return false; } } public function clearPerformanceData() { $this->performanceDataObjects = array(); } public function getVerboseInfo() { return $this->verbose_info; } public function clearVerboseInfo() { $this->verbose_info = ''; } private function writeVisualHTML($special_content=null) { if (!_empty($special_content)) { $content = $special_content; } else { $content = strtoupper(VNagLang::$status.': '.VNagLang::status($this->status, $this->statusmodel))."\n\n"; $content .= strtoupper(VNagLang::$message).":\n"; $status_text = VNagLang::status($this->status, $this->statusmodel); if (_empty($this->getHeadline())) { $content .= $status_text; } else { if ($this->show_status_in_headline) { $content .= $status_text.': '.trim($this->getHeadline()); } else { $content .= trim($this->getHeadline()); } } $content .= "\n\n"; if (!_empty($this->verbose_info)) { $content .= strtoupper(VNagLang::$verbose_info).":\n".trim($this->verbose_info)."\n\n"; } $perfdata = $this->getPerformanceData(); if (count($perfdata) > 0) { $content .= strtoupper(VNagLang::$performance_data).":\n"; foreach ($perfdata as $pd) { $content .= trim($pd)."\n"; } $content .= "\n"; } } $colorinfo = ''; $status = $this->getStatus(); if ($status == VNag::STATUS_OK) $colorinfo = ' style="background-color:green;color:white;font-weight:bold"'; else if ($status == VNag::STATUS_WARNING) $colorinfo = ' style="background-color:yellow;color:black;font-weight:bold"'; else if ($status == VNag::STATUS_CRITICAL) $colorinfo = ' style="background-color:red;color:white;font-weight:bold"'; else if ($status == VNag::STATUS_ERROR) $colorinfo = ' style="background-color:purple;color:white;font-weight:bold"'; else $colorinfo = ' style="background-color:lightgray;color:black;font-weight:bold"'; $html_content = trim($content); $html_content = htmlentities($html_content); $html_content = str_replace(' ', '&nbsp;', $html_content); $html_content = nl2br($html_content); return '<table border="1" cellspacing="2" cellpadding="2" style="width:100%" class="vnag_table">'. '<tr'.$colorinfo.' class="vnag_title_row">'. '<td>'.VNagLang::$nagios_output.'</td>'. '</tr>'. '<tr class="vnag_message_row">'. '<td><code>'. $html_content. '</code></td>'. '</tr>'. '</table>'; } protected function readInvisibleHTML($html) { $this->checkInitialized(); $doc = new DOMDocument(); @$doc->loadHTML($html); $tags = $doc->getElementsByTagName('script'); foreach ($tags as $tag) { $type = $tag->getAttribute('type'); if ($type !== 'application/json') continue; $json = $tag->nodeValue; if (!$json) continue; $data = @json_decode($json,true); if (!is_array($data)) continue; if (!isset($data['type'])) continue; if ($data['type'] === VNAG_JSONDATA_V1) { if (!isset($data['datasets'])) throw new VNagWebInfoException(VNagLang::$dataset_missing); foreach ($data['datasets'] as $dataset) { $payload = base64_decode($dataset['payload']); if (!$payload) { throw new VNagWebInfoException(VNagLang::$payload_not_base64); } if (isset($dataset['encryption'])) { $cryptInfo = $dataset['encryption']; if (!is_array($cryptInfo)) { throw new VNagWebInfoException(VNagLang::$dataset_encryption_no_array); } $password = is_null($this->password_in) ? '' : $this->password_in; $salt = base64_decode($cryptInfo['salt']); if ($cryptInfo['hash'] != hash('sha256',$salt.$password)) { if ($password == '') { throw new VNagWebInfoException(VNagLang::$require_password); } else { throw new VNagWebInfoException(VNagLang::$wrong_password); } } if (!function_exists('openssl_decrypt')) { throw new VNagException(VNagLang::$openssl_missing); } $payload = openssl_decrypt($payload, $cryptInfo['method'], $password, 0, $cryptInfo['iv']); } if (!is_null($this->pubkey) && ($this->pubkey !== '')) { if (substr($this->pubkey,0,3) === '---') { $public_key = $this->pubkey; } else { if (!file_exists($this->pubkey)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$pubkey_file_not_found, $this->pubkey)); } $public_key = @file_get_contents($this->pubkey); if (!$public_key) { throw new VNagPublicKeyException(sprintf(VNagLang::$pubkey_file_not_readable, $this->pubkey)); } } if (!isset($dataset['signature'])) { throw new VNagSignatureException(VNagLang::$signature_missing); } $signature = base64_decode($dataset['signature']); if (!$signature) { throw new VNagSignatureException(VNagLang::$signature_not_bas64); } if (!function_exists('openssl_verify')) { throw new VNagException(VNagLang::$openssl_missing); } $sign_algo = is_null($this->sign_algo) ? OPENSSL_ALGO_SHA256 : $this->sign_algo; if (!openssl_verify($payload, $signature, $public_key, $sign_algo)) { throw new VNagSignatureException(VNagLang::$signature_invalid); } } $payload = @json_decode($payload,true); if (!$payload) { throw new VNagWebInfoException(VNagLang::$payload_not_json); } if ($payload['id'] == $this->id) { return $payload; } } } } return null; } private function getNextMonitorID($peek=false) { $result = is_null($this->id) ? self::$http_serial_number : $this->id; if (!$peek) { $this->id = null; self::$http_serial_number++; } return $result; } private function writeInvisibleHTML($special_content=null) { $payload['id'] = $this->getNextMonitorID(); $payload['status'] = $this->getStatus(); if (!_empty($special_content)) { $payload['text'] = $special_content; } else { $payload['headline'] = $this->getHeadline(); $payload['verbose_info'] = $this->verbose_info; $payload['performance_data'] = array(); foreach ($this->performanceDataObjects as $perfdata) { $payload['performance_data'][] = (string)$perfdata; } } $payload = json_encode($payload); $dataset = array(); if (!is_null($this->privkey) && ($this->privkey !== '')) { if (!function_exists('openssl_pkey_get_private') || !function_exists('openssl_sign')) { throw new VNagException(VNagLang::$openssl_missing); } if (substr($this->privkey,0,3) === '---') { $pkeyid = @openssl_pkey_get_private($this->privkey, $this->privkey_password); if (!$pkeyid) { throw new VNagPrivateKeyException(sprintf(VNagLang::$privkey_not_readable)); } } else { if (!file_exists($this->privkey)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$privkey_file_not_found, $this->privkey)); } $pkeyid = @openssl_pkey_get_private('file://'.$this->privkey, $this->privkey_password); if (!$pkeyid) { throw new VNagPrivateKeyException(sprintf(VNagLang::$privkey_file_not_readable, $this->privkey)); } } $signature = ''; $sign_algo = is_null($this->sign_algo) ? OPENSSL_ALGO_SHA256 : $this->sign_algo; if (@openssl_sign($payload, $signature, $pkeyid, $sign_algo)) { if (version_compare(PHP_VERSION, '8.0.0') < 0) { openssl_free_key($pkeyid); } $dataset['signature'] = base64_encode($signature); } else { throw new VNagPrivateKeyException(sprintf(VNagLang::$signature_failed)); } } if (!is_null($this->password_out) && ($this->password_out !== '')) { if (!function_exists('openssl_encrypt')) { throw new VNagException(VNagLang::$openssl_missing); } $password = $this->password_out; $method = 'aes-256-ofb'; $iv = substr(hash('sha256', openssl_random_pseudo_bytes(32)), 0, 16); $salt = openssl_random_pseudo_bytes(32); $cryptInfo = array(); $cryptInfo['method'] = $method; $cryptInfo['iv'] = $iv; $cryptInfo['salt'] = base64_encode($salt); $cryptInfo['hash'] = hash('sha256', $salt.$password); $payload = openssl_encrypt($payload, $method, $password, 0, $iv); $dataset['encryption'] = $cryptInfo; } $dataset['payload'] = base64_encode($payload); $json = array(); $json['type'] = VNAG_JSONDATA_V1; $json['datasets'] = array($dataset); return '<script type="application/json">'. json_encode($json). '</script>'; } protected function appendHeadline($msg) { $this->checkInitialized(); if (_empty($msg)) return false; $this->messages[] = $msg; return true; } protected function changeHeadline($msg) { $this->checkInitialized(); if (_empty($msg)) { $this->messages = array(); } else { $this->messages = array($msg); } return true; } public function setHeadline($msg, $append=false, $verbosityLevel=VNag::VERBOSITY_SUMMARY) { $this->checkInitialized(); if ((!isset($this->argVerbosity)) && ($verbosityLevel > VNag::VERBOSITY_SUMMARY)) throw new VNagRequiredArgumentNotRegistered('-v'); if (self::getVerbosityLevel() < $verbosityLevel) $msg = ''; if ($append) { return $this->appendHeadline($msg); } else { return $this->changeHeadline($msg); } } public function getHeadline() { $this->checkInitialized(); return implode(', ', $this->messages); } public function addVerboseMessage($msg, $verbosityLevel=VNag::VERBOSITY_SUMMARY) { $this->checkInitialized(); if (self::getVerbosityLevel() >= $verbosityLevel) { $this->verbose_info .= $msg."\n"; } } public function setStatus($status, $force=false) { $this->checkInitialized(); if (($force) || is_null($this->status) || ($status > $this->status)) { $this->status = $status; } } public function getStatus() { $this->checkInitialized(); return $this->status; } protected static function exceptionText($exception) { $class = get_class($exception); $msg = $exception->getMessage(); if (!_empty($msg)) { return sprintf(VNagLang::$exception_x, $msg, $class); } else { return sprintf(VNagLang::$unhandled_exception_without_msg, $class); } } protected function handleException($exception) { $this->checkInitialized(); if (!VNag::is_http_mode()) { while (ob_get_level() > 0) @ob_end_clean(); } $this->clearVerboseInfo(); $this->clearPerformanceData(); if ($exception instanceof VNagException) { $this->setStatus($exception->getStatus()); } else { $this->setStatus(self::STATUS_ERROR); } $this->setHeadline($this->exceptionText($exception), false); if ($exception instanceof VNagImplementationErrorException) { $this->addVerboseMessage($exception->getTraceAsString(), VNag::VERBOSITY_SUMMARY); } else { if (isset($this->argVerbosity)) { $this->addVerboseMessage($exception->getTraceAsString(), VNag::VERBOSITY_ADDITIONAL_INFORMATION); } else { } } } protected function get_cache_dir() { $homedir = @getenv('HOME'); if ($homedir && is_dir($homedir)) { $try = "$homedir/.vnag/cache"; if (is_dir($try)) return $try; if (@mkdir($try,0777,true)) return $try; } $user = posix_getpwuid(posix_geteuid()); if (isset($user['dir']) && is_dir($user['dir'])) { $homedir = $user['dir']; $try = "$homedir/.vnag/cache"; if (is_dir($try)) return $try; if (@mkdir($try,0777,true)) return $try; } if (isset($user['name']) && is_dir($user['name'])) { $username = $user['name']; $try = "/tmp/vnag/cache"; if (is_dir($try)) return $try; if (@mkdir($try,0777,true)) return $try; } throw new VNagException("Cannot get cache dir"); } protected function url_get_contents($url, $max_cache_time=1*60*60, $context=null) { $cache_file = $this->get_cache_dir().'/'.hash('sha256',$url); if (file_exists($cache_file) && (time()-filemtime($cache_file) < $max_cache_time)) { $cont = @file_get_contents($cache_file); if ($cont === false) throw new Exception("Failed to get contents from $cache_file"); } else { $options = array( 'http'=>array( 'method'=>"GET", 'header'=>"Accept-language: en\r\n" . "User-Agent: Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B334b Safari/531.21.102011-10-16 20:23:10\r\n" ) ); if (is_null($context)) $context = stream_context_create($options); $cont = @file_get_contents($url, false, $context); if ($cont === false) throw new Exception("Failed to get contents from $url"); file_put_contents($cache_file, $cont); } return $cont; } } class VNagException extends Exception { public function getStatus() { return VNag::STATUS_ERROR; } } class VNagTimeoutException extends VNagException {} class VNagWebInfoException extends VNagException {} class VNagSignatureException extends VNagException {} class VNagPublicKeyException extends VNagException {} class VNagPrivateKeyException extends VNagException {} class VNagInvalidArgumentException extends VNagException { public function getStatus() { return VNag::STATUS_UNKNOWN; } } class VNagValueUomPairSyntaxException extends VNagInvalidArgumentException { public function __construct($str) { $e_msg = sprintf(VNagLang::$valueUomPairSyntaxError, $str); parent::__construct($e_msg); } } class VNagInvalidTimeoutException extends VNagInvalidArgumentException {} class VNagInvalidRangeException extends VNagInvalidArgumentException { public function __construct($msg) { $e_msg = VNagLang::$range_is_invalid; if (!_empty($msg)) $e_msg .= ': '.trim($msg); parent::__construct($e_msg); } } class VNagInvalidShortOpt extends VNagImplementationErrorException {} class VNagInvalidLongOpt extends VNagImplementationErrorException {} class VNagInvalidValuePolicy extends VNagImplementationErrorException {} class VNagIllegalStatusModel extends VNagImplementationErrorException {} class VNagNotConstructed extends VNagImplementationErrorException {} class VNagImplementationErrorException extends VNagException {} class VNagInvalidStandardArgument extends VNagImplementationErrorException {} class VNagFunctionCallOutsideSession extends VNagImplementationErrorException {} class VNagIllegalArgumentValuesException extends VNagImplementationErrorException {} class VNagRequiredArgumentNotRegistered extends VNagImplementationErrorException { public function __construct($required_argument) { $e_msg = sprintf(VNagLang::$query_without_expected_argument, $required_argument); parent::__construct($e_msg); } } class VNagRequiredArgumentMissing extends VNagInvalidArgumentException { public function __construct($required_argument) { $e_msg = sprintf(VNagLang::$required_argument_missing, $required_argument); parent::__construct($e_msg); } } class VNagUnknownUomException extends VNagInvalidArgumentException { public function __construct($uom) { $e_msg = sprintf(VNagLang::$perfdata_uom_not_recognized, $uom); parent::__construct($e_msg); } } class VNagNoCompatibleRangeUomFoundException extends VNagException {} class VNagMixedUomsNotImplemented extends VNagInvalidArgumentException { public function __construct($uom1, $uom2) { if (_empty($uom1)) $uom1 = VNagLang::$none; if (_empty($uom2)) $uom2 = VNagLang::$none; $e_msg = sprintf(VNagLang::$perfdata_mixed_uom_not_implemented, $uom1, $uom2); parent::__construct($e_msg); } } class VNagUomConvertException extends VNagInvalidArgumentException { public function __construct($uom1, $uom2) { if (_empty($uom1)) $uom1 = VNagLang::$none; if (_empty($uom2)) $uom2 = VNagLang::$none; $e_msg = sprintf(VNagLang::$convert_x_y_error, $uom1, $uom2); parent::__construct($e_msg); } } class VNagInvalidPerformanceDataException extends VNagInvalidArgumentException { public function __construct($msg) { $e_msg = VNagLang::$performance_data_invalid; if (!_empty($msg)) $e_msg .= ': '.trim($msg); parent::__construct($e_msg); } } class Timeouter { private static $start_time = false; private static $timeout; private static $fired = false; private static $registered = false; private function __construct() { } public static function start($timeout) { if (!is_numeric($timeout) || ($timeout <= 0)) { throw new VNagInvalidTimeoutException(sprintf(VNagLang::$timeout_value_invalid, $timeout)); } self::$start_time = microtime(true); self::$timeout = (float) $timeout; self::$fired = false; if (!self::$registered) { self::$registered = true; register_tick_function(array('Timeouter', 'tick')); } } public static function started() { return self::$registered; } public static function end() { if (self::$registered) { unregister_tick_function(array('Timeouter', 'tick')); self::$registered = false; } } public static function tick() { if ((!self::$fired) && ((microtime(true) - self::$start_time) > self::$timeout)) { self::$fired = true; throw new VNagTimeoutException(VNagLang::$timeout_exception); } } } class VNagArgument { const VALUE_FORBIDDEN = 0; const VALUE_REQUIRED = 1; const VALUE_OPTIONAL = 2; protected $shortopt; protected $longopts; protected $valuePolicy; protected $valueName; protected $helpText; protected $defaultValue = null; protected static $all_short = ''; protected static $all_long = array(); public function getShortOpt() { return $this->shortopt; } public function getLongOpts() { return $this->longopts; } public function getValuePolicy() { return $this->valuePolicy; } public function getValueName() { return $this->valueName; } public function getHelpText() { return $this->helpText; } static private function validateShortOpt($shortopt) { $m = array(); return preg_match('@^[a-zA-Z0-9\\+\\-\\?]$@', $shortopt, $m); } static private function validateLongOpt($longopt) { $m = array(); return preg_match('@^[a-zA-Z0-9\\+\\-\\?]+$@', $longopt, $m); } public function __construct($shortopt, $longopts, $valuePolicy, $valueName, $helpText, $defaultValue=null) { switch ($valuePolicy) { case VNagArgument::VALUE_FORBIDDEN: if (!_empty($valueName)) { throw new VNagImplementationErrorException(sprintf(VNagLang::$value_name_forbidden)); } break; case VNagArgument::VALUE_REQUIRED: if (_empty($valueName)) { throw new VNagImplementationErrorException(sprintf(VNagLang::$value_name_required)); } break; case VNagArgument::VALUE_OPTIONAL: if (_empty($valueName)) { throw new VNagImplementationErrorException(sprintf(VNagLang::$value_name_required)); } break; default: throw new VNagInvalidValuePolicy(sprintf(VNagLang::$illegal_valuepolicy, $valuePolicy)); } if (!_empty($shortopt)) { if (!self::validateShortOpt($shortopt)) { throw new VNagInvalidShortOpt(sprintf(VNagLang::$illegal_shortopt, $shortopt)); } } if (is_array($longopts)) { foreach ($longopts as $longopt) { if (!self::validateLongOpt($longopt)) { throw new VNagInvalidLongOpt(sprintf(VNagLang::$illegal_longopt, $longopt)); } } } else if (!_empty($longopts)) { if (!self::validateLongOpt($longopts)) { throw new VNagInvalidLongOpt(sprintf(VNagLang::$illegal_longopt, $longopts)); } $longopts = array($longopts); } else { $longopts = array(); } switch ($valuePolicy) { case VNagArgument::VALUE_FORBIDDEN: $policyApdx = ''; break; case VNagArgument::VALUE_REQUIRED: $policyApdx = ':'; break; case VNagArgument::VALUE_OPTIONAL: $policyApdx = '::'; break; default: throw new VNagInvalidValuePolicy(sprintf(VNagLang::$illegal_valuepolicy, $valuePolicy)); } if ((!is_null($shortopt)) && ($shortopt != '?')) self::$all_short .= $shortopt.$policyApdx; if (is_array($longopts)) { foreach ($longopts as $longopt) { self::$all_long[] = $longopt.$policyApdx; } } $this->shortopt = $shortopt; $this->longopts = $longopts; $this->valuePolicy = $valuePolicy; $this->valueName = $valueName; $this->helpText = $helpText; $this->defaultValue = $defaultValue; } protected static function getOptions() { global $OVERWRITE_ARGUMENTS; if (!is_null($OVERWRITE_ARGUMENTS)) { return $OVERWRITE_ARGUMENTS; } else if (VNag::is_http_mode()) { return $_REQUEST; } else { return getopt(self::$all_short, self::$all_long); } } public function count() { $options = self::getOptions(); $count = 0; if (isset($options[$this->shortopt])) { if (is_array($options[$this->shortopt])) { $count += count($options[$this->shortopt]); } else { $count += 1; } } if (!is_null($this->longopts)) { foreach ($this->longopts as $longopt) { if (isset($options[$longopt])) { if (is_array($options[$longopt])) { $count += count($options[$longopt]); } else { $count += 1; } } } } return $count; } public function available() { $options = self::getOptions(); if (isset($options[$this->shortopt])) return true; if (!is_null($this->longopts)) { foreach ($this->longopts as $longopt) { if (isset($options[$longopt])) return true; } } return false; } public function require() { if (!$this->available() && is_null($this->defaultValue)) { $opt = $this->shortopt; $opt = !_empty($opt) ? '-'.$opt : (isset($this->longopts[0]) ? '--'.$this->longopts[0] : '?'); throw new VNagRequiredArgumentMissing($opt); } } public function getValue() { $options = self::getOptions(); if (isset($options[$this->shortopt])) { $x = $options[$this->shortopt]; if (is_array($x) && (count($x) <= 1)) $options[$this->shortopt] = $options[$this->shortopt][0]; return $options[$this->shortopt]; } if (!is_null($this->longopts)) { foreach ($this->longopts as $longopt) { if (isset($options[$longopt])) { $x = $options[$longopt]; if (is_array($x) && (count($x) <= 1)) $options[$longopt] = $options[$longopt][0]; return $options[$longopt]; } } } return $this->defaultValue; } } class VNagArgumentHandler { protected $expectedArgs = array(); protected function _addExpectedArgument($argObj) { if ($argObj->getShortOpt() == '?') return false; if ($argObj->getShortOpt() == '-') return false; if ($argObj->getShortOpt() == '+') return false; $this->expectedArgs[] = $argObj; return true; } public function getArgumentObj($shortopt) { foreach ($this->expectedArgs as $argObj) { if ($argObj->getShortOpt() == $shortopt) return $argObj; } return null; } public function isArgRegistered($shortopt) { return !is_null($this->getArgumentObj($shortopt)); } public function illegalUsage() { global $argv; return (isset($argv[1])) && (($argv[1] == '-?') || ($argv[1] == '/?')); } } class VNagRange { public $start; public $end; public $warnInsideRange; public function __construct($rangeDef, $singleValueBehavior=VNag::SINGLEVALUE_RANGE_DEFAULT) { $m = array(); if (!preg_match('|^(@){0,1}([^:]+)(:){0,1}(.*)$|', $rangeDef, $m)) { throw new VNagInvalidRangeException(sprintf(VNagLang::$range_invalid_syntax, $rangeDef)); } $this->warnInsideRange = $m[1] === '@'; $this->start = null; $this->end = null; if ($m[3] === ':') { if ($m[2] === '~') { $this->start = '-inf'; } else { $this->start = new VNagValueUomPair($m[2]); } if (_empty($m[4])) { $this->end = 'inf'; } else { $this->end = new VNagValueUomPair($m[4]); } } else { assert(_empty($m[4])); assert(!_empty($m[2])); $x = $m[2]; if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_DEFAULT) { $this->start = new VNagValueUomPair('0'.((new VNagValueUomPair($x))->getUom())); $this->end = new VNagValueUomPair($x); } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_GT_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 0; $this->start = '-inf'; $this->end = new VNagValueUomPair($x); } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_GE_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 1; $this->start = new VNagValueUomPair($x); $this->end = 'inf'; } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_LT_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 0; $this->start = new VNagValueUomPair($x); $this->end = 'inf'; } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_LE_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 1; $this->start = '-inf'; $this->end = new VNagValueUomPair($x); } else { throw new VNagException(VNagLang::$illegalSingleValueBehavior); } } if (is_null($this->start)) { throw new VNagInvalidRangeException(VNagLang::$invalid_start_value); } if (is_null($this->end)) { throw new VNagInvalidRangeException(VNagLang::$invalid_end_value); } if (($this->start instanceof VNagValueUomPair) && ($this->end instanceof VNagValueUomPair) && (VNagValueUomPair::compare($this->start,$this->end) > 0)) { throw new VNagInvalidRangeException(VNagLang::$start_is_greater_than_end); } } public function __toString() { $ret = ''; if ($this->warnInsideRange) { $ret = '@'; } if ($this->start === '-inf') { $ret .= '~'; } else { $ret .= $this->start; } $ret .= ':'; if ($this->end !== 'inf') { $ret .= $this->end; } return $ret; } public function checkAlert($values) { $compatibleCount = 0; if (!is_array($values)) $values = array($values); foreach ($values as $value) { if (!($value instanceof VNagValueUomPair)) $value = new VNagValueUomPair($value); assert(($this->start === '-inf') || ($this->start instanceof VNagValueUomPair)); assert(($this->end === 'inf' ) || ($this->end instanceof VNagValueUomPair)); if (($this->start !== '-inf') && (!$this->start->compatibleWith($value))) continue; if (($this->end !== 'inf') && (!$this->end->compatibleWith($value))) continue; $compatibleCount++; if ($this->warnInsideRange) { return (($this->start === '-inf') || (VNagValueUomPair::compare($value,$this->start) >= 0)) && (($this->end === 'inf') || (VNagValueUomPair::compare($value,$this->end) <= 0)); } else { return (($this->start !== '-inf') && (VNagValueUomPair::compare($value,$this->start) < 0)) || (($this->end !== 'inf') && (VNagValueUomPair::compare($value,$this->end) > 0)); } } if ((count($values) > 0) and ($compatibleCount == 0)) { throw new VNagNoCompatibleRangeUomFoundException(VNagLang::$no_compatible_range_uom_found); } return false; } } class VNagValueUomPair { protected $value; protected $uom; public $roundTo = -1; public function isRelative() { return $this->uom === '%'; } public function getValue() { return $this->value; } public function getUom() { return $this->uom; } public function __toString() { if ($this->roundTo == -1) { return $this->value.$this->uom; } else { return round($this->value,$this->roundTo).$this->uom; } } public function __construct($str) { $m = array(); if (!preg_match('/^([\d\.]+)(.*)$/ism', $str, $m)) { throw new VNagValueUomPairSyntaxException($str); } $this->value = $m[1]; $this->uom = isset($m[2]) ? $m[2] : ''; if (!self::isKnownUOM($this->uom)) { throw new VNagUnknownUomException($this->uom); } } public static function isKnownUOM(string $uom) { $no_unit = ($uom === ''); $seconds = ($uom === 's') || ($uom === 'ms') || ($uom === 'us'); $percentage = ($uom === '%'); $bytes = ($uom === 'B') || ($uom === 'KB') || ($uom === 'MB') || ($uom === 'GB') || ($uom === 'TB'); $counter = ($uom === 'c'); return ($no_unit || $seconds || $percentage || $bytes || $counter); } public function normalize($target=null) { $res = clone $this; if ($res->uom === 'ms') { $res->uom = 's'; $res->value /= 1000; } if ($res->uom === 'us') { $res->uom = 's'; $res->value /= 1000 * 1000; } if ($res->uom === 'B') { $res->uom = 'MB'; $res->value /= 1024 * 1024; } if ($res->uom === 'KB') { $res->uom = 'MB'; $res->value /= 1024; } if ($res->uom === 'GB') { $res->uom = 'MB'; $res->value *= 1024; } if ($res->uom === 'TB') { $res->uom = 'MB'; $res->value *= 1024 * 1024; } if ($res->uom === 'c') { $res->uom = ''; } if (!is_null($target)) { if ($res->uom == 'MB') { if ($target == 'B') { $res->uom = 'B'; $res->value *= 1024 * 1024; } else if ($target == 'KB') { $res->uom = 'KB'; $res->value *= 1024; } else if ($target == 'MB') { $res->uom = 'MB'; $res->value *= 1; } else if ($target == 'GB') { $res->uom = 'GB'; $res->value /= 1024; } else if ($target == 'TB') { $res->uom = 'TB'; $res->value /= 1024 * 1024; } else { throw new VNagUomConvertException($res->uom, $target); } } else if ($res->uom == 's') { if ($target == 's') { $res->uom = 's'; $res->value /= 1; } else if ($target == 'ms') { $res->uom = 'ms'; $res->value /= 1000; } else if ($target == 'us') { $res->uom = 'us'; $res->value /= 1000 * 1000; } else { throw new VNagUomConvertException($res->uom, $target); } } else { throw new VNagUomConvertException($res->uom, $target); } } return $res; } public function compatibleWith(VNagValueUomPair $other) { $a = $this->normalize(); $b = $other->normalize(); return ($a->uom == $b->uom); } public static function compare(VNagValueUomPair $left, VNagValueUomPair $right) { $a = $left->normalize(); $b = $right->normalize(); if ($a->uom != $b->uom) throw new VNagMixedUomsNotImplemented($a->uom, $b->uom); if ($a->value > $b->value) return 1; if ($a->value == $b->value) return 0; if ($a->value < $b->value) return -1; } } class VNagPerformanceData { protected $label; protected $value; protected $warn = null; protected $crit = null; protected $min = null; protected $max = null; public static function createByString($perfdata) { $perfdata = trim($perfdata); $ary = explode('=',$perfdata); if (count($ary) != 2) { throw new VNagInvalidPerformanceDataException(sprintf(VNagLang::$perfdata_line_invalid, $perfdata)); } $label = $ary[0]; $bry = explode(';',$ary[1]); if (substr($label,0,1) === "'") $label = substr($label, 1, strlen($label)-2); $value = $bry[0]; $warn = isset($bry[1]) ? $bry[1] : null; $crit = isset($bry[2]) ? $bry[2] : null; $min = isset($bry[3]) ? $bry[3] : null; $max = isset($bry[4]) ? $bry[4] : null; return new self($label, $value, $warn, $crit, $min, $max); } public function __construct($label, $value, $warn=null, $crit=null, $min=null, $max=null) { if (strpos($label, '=') !== false) throw new VNagInvalidPerformanceDataException(VNagLang::$perfdata_label_equal_sign_forbidden); $label = str_replace("'", "''", $label); $m = array(); if ((!_empty($min)) && (!preg_match('|^[-0-9\\.]+$|', $min, $m))) { throw new VNagInvalidPerformanceDataException(VNagLang::$perfdata_min_must_be_in_class); } if ((!_empty($max)) && (!preg_match('|^[-0-9\\.]+$|', $max, $m))) { throw new VNagInvalidPerformanceDataException(VNagLang::$perfdata_max_must_be_in_class); } $this->label = $label; $this->value = ($value == 'U') ? 'U' : new VNagValueUomPair($value); $this->warn = $warn; $this->crit = $crit; $this->min = $min; $this->max = $max; } public function __toString() { $label = $this->label; $value = $this->value; $warn = $this->warn; $crit = $this->crit; $min = $this->min; $max = $this->max; $label = str_replace("''", "'", $label); return "'$label'=$value". ';'.(is_null($warn) ? '' : $warn). ';'.(is_null($crit) ? '' : $crit). ';'.(is_null($min) ? '' : $min). ';'.(is_null($max) ? '' : $max); } } class VNagHelp { public $word_wrap_width = 80; public $argument_indent = 7; public function printUsagePage() { $usage = $this->getUsage(); if (_empty($usage)) { $usage = VNagLang::$no_syntax_defined; } return trim($usage)."\n"; } public function printVersionPage() { $out = trim($this->getNameAndVersion())."\n"; if ($this->word_wrap_width > 0) $out = wordwrap($out, $this->word_wrap_width, "\n", false); return $out; } static private function _conditionalLine($line, $terminator='', $prefix='') { if (!_empty($line)) { return trim($line).$terminator; } return ''; } public function printHelpPage() { $out = ''; $out .= self::_conditionalLine($this->getNameAndVersion(), "\n"); $out .= self::_conditionalLine($this->getCopyright(), "\n"); $out .= ($out != '') ? "\n" : ''; $out .= self::_conditionalLine($this->getShortDescription(), "\n\n\n"); $out .= self::_conditionalLine($this->getUsage(), "\n\n"); $out .= VNagLang::$options."\n"; foreach ($this->options as $argObj) { $out .= $this->printArgumentHelp($argObj); } $out .= self::_conditionalLine($this->getFootNotes(), "\n\n", "\n"); if ($this->word_wrap_width > 0) $out = wordwrap($out, $this->word_wrap_width, "\n", false); return $out; } protected $options = array(); protected function _addOption($argObj) { $this->options[] = $argObj; } protected function printArgumentHelp($argObj) { $identifiers = array(); $shortopt = $argObj->getShortopt(); if (!_empty($shortopt)) $identifiers[] = '-'.$shortopt; $longopts = $argObj->getLongopts(); if (!is_null($longopts)) { foreach ($longopts as $longopt) { if (!_empty($longopt)) $identifiers[] = '--'.$longopt; } } if (count($identifiers) == 0) return; $valueName = $argObj->getValueName(); $arginfo = ''; switch ($argObj->getValuePolicy()) { case VNagArgument::VALUE_FORBIDDEN: $arginfo = ''; break; case VNagArgument::VALUE_REQUIRED: $arginfo = '='.$valueName; break; case VNagArgument::VALUE_OPTIONAL: $arginfo = '[='.$valueName.']'; break; } $out = ''; $out .= implode(', ', $identifiers).$arginfo."\n"; $content = trim($argObj->getHelpText()); if ($this->word_wrap_width > 0) $content = wordwrap($content, $this->word_wrap_width-$this->argument_indent, "\n", false); $lines = explode("\n", $content); foreach ($lines as $line) { $out .= str_repeat(' ', $this->argument_indent).$line."\n"; } $out .= "\n"; return $out; } protected $pluginName; public function setPluginName($pluginName) { $this->pluginName = $this->replaceStuff($pluginName); } public function getPluginName() { if (_empty($this->pluginName)) { global $argv; return basename($argv[0]); } else { return $this->pluginName; } } protected $version; public function setVersion($version) { $this->version = $this->replaceStuff($version); } public function getVersion() { return $this->version; } public function getNameAndVersion() { $ret = $this->getPluginName(); if (_empty($ret)) return null; $ver = $this->getVersion(); if (!_empty($ver)) { $ret = sprintf(VNagLang::$x_version_x, $ret, $ver); } $ret = trim($ret); return $ret; } protected $copyright; public function setCopyright($copyright) { $this->copyright = $this->replaceStuff($copyright); } private function getVNagCopyright() { if (VNag::is_http_mode()) { $vts_email = 'www.viathinksoft.com'; } else { $vts_email = base64_decode('aW5mb0B2aWF0aGlua3NvZnQuZGU='); } return "VNag Framework ".VNag::VNAG_VERSION." (C) 2014-".date('Y')." ViaThinkSoft <$vts_email>"; } public function getCopyright() { if (_empty($this->copyright)) { return sprintf(VNagLang::$plugin_uses, $this->getVNagCopyright()); } else { return trim($this->copyright)."\n".sprintf(VNagLang::$uses, $this->getVNagCopyright()); } } protected $shortDescription; public function setShortDescription($shortDescription) { $this->shortDescription = $this->replaceStuff($shortDescription); } public function getShortDescription() { if (_empty($this->shortDescription)) { return null; } else { $content = $this->shortDescription; if ($this->word_wrap_width > 0) $content = wordwrap($content, $this->word_wrap_width, "\n", false); return $content; } } protected function replaceStuff($text) { global $argv; if (php_sapi_name() == 'cli') { $text = str_replace('$SCRIPTNAME$', $argv[0], $text); } else { $text = str_replace('$SCRIPTNAME$', basename($_SERVER['SCRIPT_NAME']), $text); } $text = str_replace('$CURYEAR$', date('Y'), $text); return $text; } protected $syntax; public function setSyntax($syntax) { $syntax = $this->replaceStuff($syntax); $this->syntax = $syntax; } public function getUsage() { if (_empty($this->syntax)) { return null; } else { return sprintf(VNagLang::$usage_x, $this->syntax); } } protected $footNotes; public function setFootNotes($footNotes) { $this->footNotes = $this->replaceStuff($footNotes); } public function getFootNotes() { return $this->footNotes; } } class VNagLang { public static function status($code, $statusmodel) { switch ($statusmodel) { case VNag::STATUSMODEL_SERVICE: switch ($code) { case VNag::STATUS_OK: return 'OK'; case VNag::STATUS_WARNING: return 'Warning'; case VNag::STATUS_CRITICAL: return 'Critical'; case VNag::STATUS_UNKNOWN: return 'Unknown'; default: return sprintf('Error (%d)', $code); } case VNag::STATUSMODEL_HOST: switch ($code) { case VNag::STATUS_UP: return 'Up'; case VNag::STATUS_DOWN: return 'Down'; default: return sprintf('Maintain last state (%d)', $code); } default: throw new VNagIllegalStatusModel(sprintf(self::$illegal_statusmodel, $statusmodel)); } } static $nagios_output = 'VNag-Output'; static $verbose_info = 'Verbose information'; static $status = 'Status'; static $message = 'Message'; static $performance_data = 'Performance data'; static $status_ok = 'OK'; static $status_warn = 'Warning'; static $status_critical = 'Critical'; static $status_unknown = 'Unknown'; static $status_error = 'Error'; static $unhandled_exception_without_msg = "Unhandled exception of type %s"; static $plugin_uses = 'This plugin uses %s'; static $uses = 'uses %s'; static $x_version_x = '%s, version %s'; static $argname_value = 'value'; static $argname_seconds = 'seconds'; static $query_without_expected_argument = "The argument '%s' is queried, but was not added to the list of expected arguments. Please contact the plugin author."; static $required_argument_missing = "The argument '%s' is required."; static $performance_data_invalid = 'Performance data invalid.'; static $no_standard_arguments_with_letter = "No standard argument with letter '%s' exists."; static $invalid_start_value = 'Invalid start value.'; static $invalid_end_value = 'Invalid end value.'; static $start_is_greater_than_end = 'Start is greater than end value.'; static $value_name_forbidden = "Implementation error: You may not define a value name for the argument, because the value policy is VALUE_FORBIDDEN."; static $value_name_required = "Implementation error: Please define a name for the argument (so it can be shown in the help page)."; static $illegal_shortopt = "Illegal shortopt '-%s'."; static $illegal_longopt = "Illegal longopt '--%s'."; static $illegal_valuepolicy = "valuePolicy has illegal value '%s'."; static $range_invalid_syntax = "Syntax error in range '%s'."; static $timeout_value_invalid = "Timeout value '%s' is invalid."; static $range_is_invalid = 'Range is invalid.'; static $timeout_exception = 'Timeout!'; static $perfdata_label_equal_sign_forbidden = 'Label may not contain an equal sign.'; static $perfdata_value_must_be_in_class = 'Value must be in class [-0-9.] or be \'U\' if the actual value can\'t be determined.'; static $perfdata_min_must_be_in_class = 'Min must be in class [-0-9.] or empty.'; static $perfdata_max_must_be_in_class = 'Max must be in class [-0-9.] or empty.'; static $perfdata_uom_not_recognized = 'UOM (unit of measurement) "%s" is not recognized.'; static $perfdata_mixed_uom_not_implemented = 'Mixed UOMs (%s and %s) are currently not supported.'; static $no_compatible_range_uom_found = 'Measured values are not compatible with the provided warning/critical parameter. Most likely, the UOM is incompatible.'; static $exception_x = '%s (%s)'; static $no_syntax_defined = 'The author of this plugin has not defined a syntax for this plugin.'; static $usage_x = "Usage:\n%s"; static $options = "Options:"; static $illegal_statusmodel = "Invalid statusmodel %d."; static $none = '[none]'; static $valueUomPairSyntaxError = 'Syntax error at "%s". Syntax must be Value[UOM].'; static $too_few_warning_ranges = "You have too few warning ranges (currently trying to get element %d)."; static $too_few_critical_ranges = "You have too few critical ranges (currently trying to get element %d)."; static $dataset_missing = 'Dataset missing.'; static $payload_not_base64 = 'The payload is not valid Base64.'; static $payload_not_json = 'The payload is not valid JSON.'; static $signature_missing = 'The signature is missing.'; static $signature_not_bas64 = 'The signature is not valid Base64.'; static $signature_invalid = 'The signature is invalid. The connection might have been tampered, or a different key is used.'; static $pubkey_file_not_found = "Public key file %s was not found."; static $pubkey_file_not_readable = "Public key file %s is not readable."; static $privkey_file_not_found = "Private key file %s was not found."; static $privkey_not_readable = "Private key is not readable."; static $privkey_file_not_readable = "Private key file %s is not readable."; static $signature_failed = "Signature failed."; static $perfdata_line_invalid = "Performance data line %s is invalid."; static $singlevalue_unexpected_at_symbol = 'This plugin does not allow the @-symbol at ranges for single values.'; static $illegalSingleValueBehavior = "Illegal value for 'singleValueBehavior'. Please contact the creator of the plugin."; static $dataset_encryption_no_array = 'Dataset encryption information invalid.'; static $require_password = 'This resource is protected with a password. Please provide a password.'; static $wrong_password = 'This resource is protected with a password. You have provided the wrong password, or it was changed.'; static $convert_x_y_error = 'Cannot convert from UOM %s to UOM %s.'; static $php_error = 'PHP has detected an error in the plugin. Please contact the plugin author.'; static $output_level_lowered = "Output Buffer level lowered during cbRun(). Please contact the plugin author."; static $openssl_missing = "OpenSSL is missing. Therefore, encryption and signatures are not available."; static $warning_range = 'Warning range'; static $critical_range = 'Critical range'; static $prints_version = 'Prints version'; static $verbosity_helptext = 'Verbosity -v, -vv or -vvv'; static $timeout_helptext = 'Sets timeout in seconds'; static $help_helptext = 'Prints help page'; static $prints_usage = 'Prints usage'; static $notConstructed = 'Parent constructor not called with parent::__construct().'; } function vnagErrorHandler($errorkind, $errortext, $file, $line) { global $inside_vnag_run; if (!$inside_vnag_run && VNag::is_http_mode()) { return false; } if (!(error_reporting() & $errorkind)) { return true; } if (defined('E_ERROR') && ($errorkind == E_ERROR)) $errorkind = 'Error'; if (defined('E_WARNING') && ($errorkind == E_WARNING)) $errorkind = 'Warning'; if (defined('E_PARSE') && ($errorkind == E_PARSE)) $errorkind = 'Parse'; if (defined('E_NOTICE') && ($errorkind == E_NOTICE)) $errorkind = 'Notice'; if (defined('E_CORE_ERROR') && ($errorkind == E_CORE_ERROR)) $errorkind = 'Core Error'; if (defined('E_CORE_WARNING') && ($errorkind == E_CORE_WARNING)) $errorkind = 'Core Warning'; if (defined('E_COMPILE_ERROR') && ($errorkind == E_COMPILE_ERROR)) $errorkind = 'Compile Error'; if (defined('E_COMPILE_WARNING') && ($errorkind == E_COMPILE_WARNING)) $errorkind = 'Compile Warning'; if (defined('E_USER_ERROR') && ($errorkind == E_USER_ERROR)) $errorkind = 'User Error'; if (defined('E_USER_WARNING') && ($errorkind == E_USER_WARNING)) $errorkind = 'User Warning'; if (defined('E_USER_NOTICE') && ($errorkind == E_USER_NOTICE)) $errorkind = 'User Notice'; if (defined('E_STRICT') && ($errorkind == E_STRICT)) $errorkind = 'Strict'; if (defined('E_RECOVERABLE_ERROR') && ($errorkind == E_RECOVERABLE_ERROR)) $errorkind = 'Recoverable Error'; if (defined('E_DEPRECATED') && ($errorkind == E_DEPRECATED)) $errorkind = 'Deprecated'; if (defined('E_USER_DEPRECATED') && ($errorkind == E_USER_DEPRECATED)) $errorkind = 'User Deprecated'; throw new VNagException(VNagLang::$php_error . " $errortext at $file:$line (kind $errorkind)"); } $inside_vnag_run = false; $old_error_handler = set_error_handler("vnagErrorHandler"); <?php
declare(ticks=1); class VNagAastra430VoiceMail extends VNag { protected $argFtpHostname = null; protected $argFtpUsername = null; protected $argFtpPassword = null; const DEFAULT_USERNAME = 'admin'; const DEFAULT_PASSWORD = '33aastra'; public function __construct() { parent::__construct(); if ($this->is_http_mode()) { $this->registerExpectedStandardArguments(''); } else { $this->registerExpectedStandardArguments('Vht'); } $this->addExpectedArgument($this->argFtpHostname = new VNagArgument('H', 'ftphostname', VNagArgument::VALUE_REQUIRED, 'ftphostname', 'The FTP hostname', null)); $this->addExpectedArgument($this->argFtpUsername = new VNagArgument('u', 'ftpusername', VNagArgument::VALUE_REQUIRED, 'ftpusername', 'The FTP username (usually "'.self::DEFAULT_USERNAME.'")', self::DEFAULT_USERNAME)); $this->addExpectedArgument($this->argFtpPassword = new VNagArgument('p', 'ftppassword', VNagArgument::VALUE_REQUIRED, 'ftppassword', 'The FTP password (default "'.self::DEFAULT_PASSWORD.'")', self::DEFAULT_PASSWORD)); $this->getHelpManager()->setPluginName('vnag_aastra_430_voicemail'); $this->getHelpManager()->setVersion('2023-10-13'); $this->getHelpManager()->setShortDescription('This plugin checks for voicemail messages on a Aastra 430.'); $this->getHelpManager()->setCopyright('Copyright (C) 2011-$CURYEAR$ Daniel Marschall, ViaThinkSoft.'); $this->getHelpManager()->setSyntax('$SCRIPTNAME$ -H <ftphost> -u <ftpusername> -p <ftppassword>'); $this->getHelpManager()->setFootNotes('If you encounter bugs, please contact ViaThinkSoft at www.viathinksoft.com'); } protected static function aastra430NumVm($ftp_host, $user, $password) { if (!($conn = @ftp_connect($ftp_host))) throw new VNagException('FTP connect failed'); if (!@ftp_login($conn, $user, $password)) throw new VNagException('FTP login failed'); $messages = @ftp_nlist($conn, '/home/voice/vm/gen'); if (!is_array($messages)) throw new VNagException('FTP folder not found!'); $count = count($messages); @ftp_close($conn); return $count; } protected function cbRun() { $this->argFtpHostname->require(); $ftp_hostname = $this->argFtpHostname->getValue(); $ftp_username = $this->argFtpUsername->getValue(); $ftp_password = $this->argFtpPassword->getValue(); $count = self::aastra430NumVm($ftp_hostname, $ftp_username, $ftp_password); $this->setStatus("$count new voicemail messsages", true); if ($count == 0) { $this->setStatus(VNag::STATUS_OK); } else { $this->setStatus(VNag::STATUS_WARNING); } } } <?php
declare(ticks=1); require_once __DIR__ . '/../../framework/vnag_framework.inc.php'; require_once __DIR__.'/VNagAastra430VoiceMail.class.php'; $job = new VNagAastra430VoiceMail(); $job->run(); unset($job); þ„m„éÉH‚ÿåHš%„ÊùÖ)¥„WÌN„0/›¾€øþ²¹ñ[<O§™‘ßê$Ðnc,>Ó.7¾bÃHfBGBMB
declare(ticks=1); require_once __DIR__ . '/../../framework/vnag_framework.inc.php'; require_once __DIR__.'/VNagAastra430VoiceMail.class.php'; $job = new VNagAastra430VoiceMail(); $job->run(); unset($job); À²j?›«µq·ny}Zê­¯@ÉÒXñÑÒQ¨òf̶¨ýn¶»¡åׯ’¯W@›©˜v‡÷úOðù<Xi¼v@GBMB
/trunk/bin/disk_running.phar
291,9 → 291,8
 
Extract_Phar::go();
__HALT_COMPILER(); ?>
[za:1:{s:23:"1.3.6.1.4.1.37476.3.0.2";s:332:"sha256||framework/vnag_framework.inc.php|460b109d1c578e9b6af41612e0312c9f36fd8beb51f7aa92f1b7bd49614568e8||plugins/disk_running/DiskRunningCheck.class.php|f5d143936f0eeccede1f4c05fb6b4d7479ac8992f221f1679632ab166a1c9f9f||plugins/disk_running/check_disk_running.phps|aec7c9f595212b72b80cf3fd21d0014c3b6b80d5cc3e8e32b96a3ad75ba97cbc||";} framework/vnag_framework.inc.phpLÙyï*eLُ4p”¤/plugins/disk_running/DiskRunningCheck.class.phpü yï*eü «Ù̊¤,plugins/disk_running/check_disk_running.phpsÈyï*eȜcjq¤<?php ?>
<?php
§Æa:1:{s:23:"1.3.6.1.4.1.37476.3.0.2";s:408:"sha256||<builder>|481cf75d675006b504520fd2acb3b29c89aea03aab64754e0adfb364de4914b2||framework/vnag_framework.inc.php|0387bf3134f8cc2d1ae24e139019c0edef19c1ba5ca765624efea0b469c7897f||plugins/disk_running/DiskRunningCheck.class.php|f5d143936f0eeccede1f4c05fb6b4d7479ac8992f221f1679632ab166a1c9f9f||plugins/disk_running/check_disk_running.phps|aec7c9f595212b72b80cf3fd21d0014c3b6b80d5cc3e8e32b96a3ad75ba97cbc||";} framework/vnag_framework.inc.phpBÙ» +eBÙÞß=¤/plugins/disk_running/DiskRunningCheck.class.phpü » +eü «Ù̊¤,plugins/disk_running/check_disk_running.phpsÈ» +eȜcjq¤<?php
if (!VNag::is_http_mode()) error_reporting(E_ALL); declare(ticks=1); set_time_limit(0); define('VNAG_JSONDATA_V1', 'oid:1.3.6.1.4.1.37476.2.3.1.1'); $OVERWRITE_ARGUMENTS = null; function _empty($x) { return is_null($x) || (trim($x) == ''); } abstract class VNag { const VNAG_VERSION = '2023-10-13'; const STATUS_OK = 0; const STATUS_WARNING = 1; const STATUS_CRITICAL = 2; const STATUS_UNKNOWN = 3; const STATUS_ERROR = 4; const STATUS_UP = 0; const STATUS_DOWN = 1; const STATUS_MAINTAIN = 2; const VERBOSITY_SUMMARY = 0; const VERBOSITY_ADDITIONAL_INFORMATION = 1; const VERBOSITY_CONFIGURATION_DEBUG = 2; const VERBOSITY_PLUGIN_DEBUG = 3; const MAX_VERBOSITY = self::VERBOSITY_PLUGIN_DEBUG; const STATUSMODEL_SERVICE = 0; const STATUSMODEL_HOST = 1; private $initialized = false; private $status = null; private $messages = array(); private $verbose_info = ''; private $warningRanges = array(); private $criticalRanges = array(); private $performanceDataObjects = array(); private static $exitcode = 0; private $helpObj = null; private $argHandler = null; const OUTPUT_NEVER = 0; const OUTPUT_SPECIAL = 1; const OUTPUT_NORMAL = 2; const OUTPUT_EXCEPTION = 4; const OUTPUT_ALWAYS = 7; public $http_visual_output = self::OUTPUT_ALWAYS; public $http_invisible_output = self::OUTPUT_ALWAYS; protected $html_before = ''; protected $html_after = ''; protected $statusmodel = self::STATUSMODEL_SERVICE; protected $show_status_in_headline = true; protected $default_status = self::STATUS_UNKNOWN; protected $default_warning_range = null; protected $default_critical_range = null; protected $argWarning; protected $argCritical; protected $argVersion; protected $argVerbosity; protected $argTimeout; protected $argHelp; protected $argUsage; public $id = null; protected static $http_serial_number = 0; public $privkey = null; public $privkey_password = null; public $sign_algo = null; public $pubkey = null; protected $warningSingleValueRangeBehaviors = array(self::SINGLEVALUE_RANGE_DEFAULT); protected $criticalSingleValueRangeBehaviors = array(self::SINGLEVALUE_RANGE_DEFAULT); const SINGLEVALUE_RANGE_DEFAULT = 0; const SINGLEVALUE_RANGE_VAL_GT_X_BAD = 1; const SINGLEVALUE_RANGE_VAL_GE_X_BAD = 2; const SINGLEVALUE_RANGE_VAL_LT_X_BAD = 3; const SINGLEVALUE_RANGE_VAL_LE_X_BAD = 4; public $password_out = null; public $password_in = null; public static function is_http_mode() { return php_sapi_name() !== 'cli'; } public function getHelpManager() { return $this->helpObj; } public function getArgumentHandler() { return $this->argHandler; } public function outputHTML($text, $after_visual_output=true) { if ($this->is_http_mode()) { if ($this->initialized) { if ($after_visual_output) { $this->html_after .= $text; } else { $this->html_before .= $text; } } else { echo $text; } } } protected function resetArguments() { $this->argWarning = null; $this->argCritical = null; $this->argVersion = null; $this->argVerbosity = null; $this->argTimeout = null; $this->argHelp = null; $this->argWarning = null; $this->argCritical = null; } public function registerExpectedStandardArguments($args) { $this->resetArguments(); for ($i=0; $i<strlen($args); $i++) { switch ($args[$i]) { case 'w': $this->addExpectedArgument($this->argWarning = new VNagArgument('w', 'warning', VNagArgument::VALUE_REQUIRED, VNagLang::$argname_value, VNagLang::$warning_range)); break; case 'c': $this->addExpectedArgument($this->argCritical = new VNagArgument('c', 'critical', VNagArgument::VALUE_REQUIRED, VNagLang::$argname_value, VNagLang::$critical_range)); break; case 'V': $this->addExpectedArgument($this->argVersion = new VNagArgument('V', 'version', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$prints_version)); break; case 'v': $this->addExpectedArgument($this->argVerbosity = new VNagArgument('v', 'verbose', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$verbosity_helptext)); break; case 't': $this->addExpectedArgument($this->argTimeout = new VNagArgument('t', 'timeout', VNagArgument::VALUE_REQUIRED, VNagLang::$argname_seconds, VNagLang::$timeout_helptext)); break; case 'h': $this->addExpectedArgument($this->argHelp = new VNagArgument('h', 'help', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$help_helptext)); break; default: $letter = $args[$i]; throw new VNagInvalidStandardArgument(sprintf(VNagLang::$no_standard_arguments_with_letter, $letter)); } } } public function addExpectedArgument($argObj) { $helpObjAddEntryMethod = new ReflectionMethod($this->helpObj, '_addOption'); $helpObjAddEntryMethod->setAccessible(true); $helpObjAddEntryMethod->invoke($this->helpObj, $argObj); $argHandlerAddEntryMethod = new ReflectionMethod($this->argHandler, '_addExpectedArgument'); $argHandlerAddEntryMethod->setAccessible(true); $argHandlerAddEntryMethod->invoke($this->argHandler, $argObj); } protected function createArgumentHandler() { $this->argHandler = new VNagArgumentHandler(); } protected function createHelpObject() { $this->helpObj = new VNagHelp(); } protected function checkInitialized() { if (!$this->initialized) throw new VNagFunctionCallOutsideSession(); } protected function getVerbosityLevel() { $this->checkInitialized(); if (!isset($this->argVerbosity)) { return self::VERBOSITY_SUMMARY; } else { $level = $this->argVerbosity->count(); if ($level > self::MAX_VERBOSITY) $level = self::MAX_VERBOSITY; return $level; } } public function getWarningRange($argumentNumber=0) { $this->checkInitialized(); if (!isset($this->warningRanges[$argumentNumber])) { if (!is_null($this->argWarning)) { $warning = $this->argWarning->getValue(); if (!is_null($warning)) { $vals = explode(',',$warning); foreach ($vals as $number => $val) { if (_empty($val)) { $this->warningRanges[$number] = null; } else { $singleValueBehavior = isset($this->warningSingleValueRangeBehaviors[$number]) ? $this->warningSingleValueRangeBehaviors[$number] : VNag::SINGLEVALUE_RANGE_DEFAULT; $this->warningRanges[$number] = new VNagRange($val, $singleValueBehavior); } } } else { $this->warningRanges[0] = $this->default_warning_range; } } else { return null; } } if (isset($this->warningRanges[$argumentNumber])) { return $this->warningRanges[$argumentNumber]; } else { return null; } } public function getCriticalRange($argumentNumber=0) { $this->checkInitialized(); if (!isset($this->criticalRanges[$argumentNumber])) { if (!is_null($this->argCritical)) { $critical = $this->argCritical->getValue(); if (!is_null($critical)) { $vals = explode(',',$critical); foreach ($vals as $number => $val) { $singleValueBehavior = isset($this->criticalSingleValueRangeBehaviors[$number]) ? $this->criticalSingleValueRangeBehaviors[$number] : VNag::SINGLEVALUE_RANGE_DEFAULT; $this->criticalRanges[$number] = new VNagRange($val, $singleValueBehavior); } } else { $this->criticalRanges[0] = $this->default_critical_range; } } else { return null; } } if (isset($this->criticalRanges[$argumentNumber])) { return $this->criticalRanges[$argumentNumber]; } else { return null; } } public function checkAgainstWarningRange($values, $force=true, $autostatus=true, $argumentNumber=0) { $this->checkInitialized(); if (!$this->getArgumentHandler()->isArgRegistered('w')) { throw new VNagRequiredArgumentNotRegistered('-w'); } $wr = $this->getWarningRange($argumentNumber); if (isset($wr)) { if ($wr->checkAlert($values)) { if ($autostatus) $this->setStatus(VNag::STATUS_WARNING); return true; } else { if ($autostatus) $this->setStatus(VNag::STATUS_OK); return false; } } else { if ($force) { if (($argumentNumber > 0) && (count($this->warningRanges) > 0)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$too_few_warning_ranges, $argumentNumber+1)); } else { throw new VNagRequiredArgumentMissing('-w'); } } } } public function checkAgainstCriticalRange($values, $force=true, $autostatus=true, $argumentNumber=0) { $this->checkInitialized(); if (!$this->getArgumentHandler()->isArgRegistered('c')) { throw new VNagRequiredArgumentNotRegistered('-c'); } $cr = $this->getCriticalRange($argumentNumber); if (isset($cr)) { if ($cr->checkAlert($values)) { if ($autostatus) $this->setStatus(VNag::STATUS_CRITICAL); return true; } else { if ($autostatus) $this->setStatus(VNag::STATUS_OK); return false; } } else { if ($force) { if (($argumentNumber > 0) && (count($this->warningRanges) > 0)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$too_few_critical_ranges, $argumentNumber+1)); } else { throw new VNagRequiredArgumentMissing('-c'); } } } } protected static function getBaddestExitcode($code1, $code2) { return max($code1, $code2); } public static function _shutdownHandler() { if (!self::is_http_mode()) { exit((int)self::$exitcode); } } protected function _exit($code) { self::$exitcode = $this->getBaddestExitcode($code, self::$exitcode); } private $constructed = false; function __construct() { $this->createHelpObject(); $this->createArgumentHandler(); $this->addExpectedArgument($this->argUsage = new VNagArgument('?', '', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$prints_usage)); $this->constructed = true; } function __destruct() { if (Timeouter::started()) { Timeouter::end(); } } public function run() { global $inside_vnag_run; $inside_vnag_run = true; try { if (!$this->constructed) { throw new VNagNotConstructed(VNagLang::$notConstructed); } try { $this->initialized = true; $this->html_before = ''; $this->html_after = ''; $this->setStatus(null, true); $this->messages = array(); register_shutdown_function(array($this, '_shutdownHandler')); if ($this->argHandler->illegalUsage()) { $content = $this->helpObj->printUsagePage(); $this->setStatus(VNag::STATUS_UNKNOWN); if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_visual_output & VNag::OUTPUT_SPECIAL) echo $this->writeVisualHTML($content); if ($this->http_invisible_output & VNag::OUTPUT_SPECIAL) echo $this->writeInvisibleHTML($content); echo $this->html_after; return; } else { echo $content; return $this->_exit($this->status); } } if (!is_null($this->argVersion) && ($this->argVersion->available())) { $content = $this->helpObj->printVersionPage(); $this->setStatus(VNag::STATUS_UNKNOWN); if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_visual_output & VNag::OUTPUT_SPECIAL) echo $this->writeVisualHTML($content); if ($this->http_invisible_output & VNag::OUTPUT_SPECIAL) echo $this->writeInvisibleHTML($content); echo $this->html_after; return; } else { echo $content; return $this->_exit($this->status); } } if (!is_null($this->argHelp) && ($this->argHelp->available())) { $content = $this->helpObj->printHelpPage(); $this->setStatus(VNag::STATUS_UNKNOWN); if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_visual_output & VNag::OUTPUT_SPECIAL) echo $this->writeVisualHTML($content); if ($this->http_invisible_output & VNag::OUTPUT_SPECIAL) echo $this->writeInvisibleHTML($content); echo $this->html_after; return; } else { echo $content; return $this->_exit($this->status); } } $this->getWarningRange(); $this->getCriticalRange(); if (!is_null($this->argTimeout)) { $timeout = $this->argTimeout->getValue(); if (!is_null($timeout)) { Timeouter::start($timeout); } } ob_start(); $init_ob_level = ob_get_level(); try { $this->cbRun(); if (ob_get_level() < $init_ob_level) throw new VNagImplementationErrorException(VNagLang::$output_level_lowered); } finally { while (ob_get_level() > $init_ob_level) @ob_end_clean(); } if (is_null($this->status)) $this->setStatus($this->default_status,true); $outputType = VNag::OUTPUT_NORMAL; } catch (Exception $e) { $this->handleException($e); $outputType = VNag::OUTPUT_EXCEPTION; } if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_invisible_output & $outputType) { echo $this->writeInvisibleHTML(); } if ($this->http_visual_output & $outputType) { echo $this->writeVisualHTML(); } echo $this->html_after; } else { echo $this->getNagiosConsoleText(); return $this->_exit($this->status); } Timeouter::end(); } finally { $inside_vnag_run = false; } } private function getNagiosConsoleText() { $ary_perfdata = $this->getPerformanceData(); $performancedata_first = array_shift($ary_perfdata); $performancedata_rest = implode(' ', $ary_perfdata); $status_text = VNagLang::status($this->status, $this->statusmodel); if (_empty($this->getHeadline())) { $content = $status_text; } else { if ($this->show_status_in_headline) { $content = $status_text.': '.$this->getHeadline(); } else { $content = $this->getHeadline(); } } if (!_empty($performancedata_first)) $content .= '|'.trim($performancedata_first); $content .= "\n"; if (!_empty($this->verbose_info)) { $content .= trim($this->verbose_info); } if (!_empty($performancedata_rest)) $content .= '|'.trim($performancedata_rest); $content .= "\n"; return trim($content)."\n"; } abstract protected function cbRun(); public function addPerformanceData($prefDataObj, $move_to_font=false, $verbosityLevel=VNag::VERBOSITY_SUMMARY) { $this->checkInitialized(); if ((!isset($this->argVerbosity)) && ($verbosityLevel > VNag::VERBOSITY_SUMMARY)) throw new VNagRequiredArgumentNotRegistered('-v'); if (self::getVerbosityLevel() < $verbosityLevel) return false; if ($move_to_font) { array_unshift($this->performanceDataObjects, $prefDataObj); } else { $this->performanceDataObjects[] = $prefDataObj; } return true; } public function getPerformanceData() { $this->checkInitialized(); return $this->performanceDataObjects; } public function removePerformanceData($prefDataObj) { if (($key = array_search($prefDataObj, $this->performanceDataObjects, true)) !== false) { unset($this->performanceDataObjects[$key]); return true; } else { return false; } } public function clearPerformanceData() { $this->performanceDataObjects = array(); } public function getVerboseInfo() { return $this->verbose_info; } public function clearVerboseInfo() { $this->verbose_info = ''; } private function writeVisualHTML($special_content=null) { if (!_empty($special_content)) { $content = $special_content; } else { $content = strtoupper(VNagLang::$status.': '.VNagLang::status($this->status, $this->statusmodel))."\n\n"; $content .= strtoupper(VNagLang::$message).":\n"; $status_text = VNagLang::status($this->status, $this->statusmodel); if (_empty($this->getHeadline())) { $content .= $status_text; } else { if ($this->show_status_in_headline) { $content .= $status_text.': '.trim($this->getHeadline()); } else { $content .= trim($this->getHeadline()); } } $content .= "\n\n"; if (!_empty($this->verbose_info)) { $content .= strtoupper(VNagLang::$verbose_info).":\n".trim($this->verbose_info)."\n\n"; } $perfdata = $this->getPerformanceData(); if (count($perfdata) > 0) { $content .= strtoupper(VNagLang::$performance_data).":\n"; foreach ($perfdata as $pd) { $content .= trim($pd)."\n"; } $content .= "\n"; } } $colorinfo = ''; $status = $this->getStatus(); if ($status == VNag::STATUS_OK) $colorinfo = ' style="background-color:green;color:white;font-weight:bold"'; else if ($status == VNag::STATUS_WARNING) $colorinfo = ' style="background-color:yellow;color:black;font-weight:bold"'; else if ($status == VNag::STATUS_CRITICAL) $colorinfo = ' style="background-color:red;color:white;font-weight:bold"'; else if ($status == VNag::STATUS_ERROR) $colorinfo = ' style="background-color:purple;color:white;font-weight:bold"'; else $colorinfo = ' style="background-color:lightgray;color:black;font-weight:bold"'; $html_content = trim($content); $html_content = htmlentities($html_content); $html_content = str_replace(' ', '&nbsp;', $html_content); $html_content = nl2br($html_content); return '<table border="1" cellspacing="2" cellpadding="2" style="width:100%" class="vnag_table">'. '<tr'.$colorinfo.' class="vnag_title_row">'. '<td>'.VNagLang::$nagios_output.'</td>'. '</tr>'. '<tr class="vnag_message_row">'. '<td><code>'. $html_content. '</code></td>'. '</tr>'. '</table>'; } protected function readInvisibleHTML($html) { $this->checkInitialized(); $doc = new DOMDocument(); @$doc->loadHTML($html); $tags = $doc->getElementsByTagName('script'); foreach ($tags as $tag) { $type = $tag->getAttribute('type'); if ($type !== 'application/json') continue; $json = $tag->nodeValue; if (!$json) continue; $data = @json_decode($json,true); if (!is_array($data)) continue; if (!isset($data['type'])) continue; if ($data['type'] === VNAG_JSONDATA_V1) { if (!isset($data['datasets'])) throw new VNagWebInfoException(VNagLang::$dataset_missing); foreach ($data['datasets'] as $dataset) { $payload = base64_decode($dataset['payload']); if (!$payload) { throw new VNagWebInfoException(VNagLang::$payload_not_base64); } if (isset($dataset['encryption'])) { $cryptInfo = $dataset['encryption']; if (!is_array($cryptInfo)) { throw new VNagWebInfoException(VNagLang::$dataset_encryption_no_array); } $password = is_null($this->password_in) ? '' : $this->password_in; $salt = base64_decode($cryptInfo['salt']); if ($cryptInfo['hash'] != hash('sha256',$salt.$password)) { if ($password == '') { throw new VNagWebInfoException(VNagLang::$require_password); } else { throw new VNagWebInfoException(VNagLang::$wrong_password); } } if (!function_exists('openssl_decrypt')) { throw new VNagException(VNagLang::$openssl_missing); } $payload = openssl_decrypt($payload, $cryptInfo['method'], $password, 0, $cryptInfo['iv']); } if (!is_null($this->pubkey) && ($this->pubkey !== '')) { if (substr($this->pubkey,0,3) === '---') { $public_key = $this->pubkey; } else { if (!file_exists($this->pubkey)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$pubkey_file_not_found, $this->pubkey)); } $public_key = @file_get_contents($this->pubkey); if (!$public_key) { throw new VNagPublicKeyException(sprintf(VNagLang::$pubkey_file_not_readable, $this->pubkey)); } } if (!isset($dataset['signature'])) { throw new VNagSignatureException(VNagLang::$signature_missing); } $signature = base64_decode($dataset['signature']); if (!$signature) { throw new VNagSignatureException(VNagLang::$signature_not_bas64); } if (!function_exists('openssl_verify')) { throw new VNagException(VNagLang::$openssl_missing); } $sign_algo = is_null($this->sign_algo) ? OPENSSL_ALGO_SHA256 : $this->sign_algo; if (!openssl_verify($payload, $signature, $public_key, $sign_algo)) { throw new VNagSignatureException(VNagLang::$signature_invalid); } } $payload = @json_decode($payload,true); if (!$payload) { throw new VNagWebInfoException(VNagLang::$payload_not_json); } if ($payload['id'] == $this->id) { return $payload; } } } } return null; } private function getNextMonitorID($peek=false) { $result = is_null($this->id) ? self::$http_serial_number : $this->id; if (!$peek) { $this->id = null; self::$http_serial_number++; } return $result; } private function writeInvisibleHTML($special_content=null) { $payload['id'] = $this->getNextMonitorID(); $payload['status'] = $this->getStatus(); if (!_empty($special_content)) { $payload['text'] = $special_content; } else { $payload['headline'] = $this->getHeadline(); $payload['verbose_info'] = $this->verbose_info; $payload['performance_data'] = array(); foreach ($this->performanceDataObjects as $perfdata) { $payload['performance_data'][] = (string)$perfdata; } } $payload = json_encode($payload); $dataset = array(); if (!is_null($this->privkey) && ($this->privkey !== '')) { if (!function_exists('openssl_pkey_get_private') || !function_exists('openssl_sign')) { throw new VNagException(VNagLang::$openssl_missing); } if (substr($this->privkey,0,3) === '---') { $pkeyid = @openssl_pkey_get_private($this->privkey, $this->privkey_password); if (!$pkeyid) { throw new VNagPrivateKeyException(sprintf(VNagLang::$privkey_not_readable)); } } else { if (!file_exists($this->privkey)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$privkey_file_not_found, $this->privkey)); } $pkeyid = @openssl_pkey_get_private('file://'.$this->privkey, $this->privkey_password); if (!$pkeyid) { throw new VNagPrivateKeyException(sprintf(VNagLang::$privkey_file_not_readable, $this->privkey)); } } $signature = ''; $sign_algo = is_null($this->sign_algo) ? OPENSSL_ALGO_SHA256 : $this->sign_algo; if (@openssl_sign($payload, $signature, $pkeyid, $sign_algo)) { if (version_compare(PHP_VERSION, '8.0.0') < 0) { openssl_free_key($pkeyid); } $dataset['signature'] = base64_encode($signature); } else { throw new VNagPrivateKeyException(sprintf(VNagLang::$signature_failed)); } } if (!is_null($this->password_out) && ($this->password_out !== '')) { if (!function_exists('openssl_encrypt')) { throw new VNagException(VNagLang::$openssl_missing); } $password = $this->password_out; $method = 'aes-256-ofb'; $iv = substr(hash('sha256', openssl_random_pseudo_bytes(32)), 0, 16); $salt = openssl_random_pseudo_bytes(32); $cryptInfo = array(); $cryptInfo['method'] = $method; $cryptInfo['iv'] = $iv; $cryptInfo['salt'] = base64_encode($salt); $cryptInfo['hash'] = hash('sha256', $salt.$password); $payload = openssl_encrypt($payload, $method, $password, 0, $iv); $dataset['encryption'] = $cryptInfo; } $dataset['payload'] = base64_encode($payload); $json = array(); $json['type'] = VNAG_JSONDATA_V1; $json['datasets'] = array($dataset); return '<script type="application/json">'. json_encode($json). '</script>'; } protected function appendHeadline($msg) { $this->checkInitialized(); if (_empty($msg)) return false; $this->messages[] = $msg; return true; } protected function changeHeadline($msg) { $this->checkInitialized(); if (_empty($msg)) { $this->messages = array(); } else { $this->messages = array($msg); } return true; } public function setHeadline($msg, $append=false, $verbosityLevel=VNag::VERBOSITY_SUMMARY) { $this->checkInitialized(); if ((!isset($this->argVerbosity)) && ($verbosityLevel > VNag::VERBOSITY_SUMMARY)) throw new VNagRequiredArgumentNotRegistered('-v'); if (self::getVerbosityLevel() < $verbosityLevel) $msg = ''; if ($append) { return $this->appendHeadline($msg); } else { return $this->changeHeadline($msg); } } public function getHeadline() { $this->checkInitialized(); return implode(', ', $this->messages); } public function addVerboseMessage($msg, $verbosityLevel=VNag::VERBOSITY_SUMMARY) { $this->checkInitialized(); if (self::getVerbosityLevel() >= $verbosityLevel) { $this->verbose_info .= $msg."\n"; } } public function setStatus($status, $force=false) { $this->checkInitialized(); if (($force) || is_null($this->status) || ($status > $this->status)) { $this->status = $status; } } public function getStatus() { $this->checkInitialized(); return $this->status; } protected static function exceptionText($exception) { $class = get_class($exception); $msg = $exception->getMessage(); if (!_empty($msg)) { return sprintf(VNagLang::$exception_x, $msg, $class); } else { return sprintf(VNagLang::$unhandled_exception_without_msg, $class); } } protected function handleException($exception) { $this->checkInitialized(); if (!VNag::is_http_mode()) { while (ob_get_level() > 0) @ob_end_clean(); } $this->clearVerboseInfo(); $this->clearPerformanceData(); if ($exception instanceof VNagException) { $this->setStatus($exception->getStatus()); } else { $this->setStatus(self::STATUS_ERROR); } $this->setHeadline($this->exceptionText($exception), false); if ($exception instanceof VNagImplementationErrorException) { $this->addVerboseMessage($exception->getTraceAsString(), VNag::VERBOSITY_SUMMARY); } else { if (isset($this->argVerbosity)) { $this->addVerboseMessage($exception->getTraceAsString(), VNag::VERBOSITY_ADDITIONAL_INFORMATION); } else { } } } protected function get_cache_dir() { $homedir = @getenv('HOME'); if ($homedir && is_dir($homedir)) { $try = "$homedir/.vnag/cache"; if (is_dir($try)) return $try; if (@mkdir($try,0777,true)) return $try; } $user = posix_getpwuid(posix_geteuid()); if (isset($user['dir']) && is_dir($user['dir'])) { $homedir = $user['dir']; $try = "$homedir/.vnag/cache"; if (is_dir($try)) return $try; if (@mkdir($try,0777,true)) return $try; } if (isset($user['name']) && is_dir($user['name'])) { $username = $user['name']; $try = "/tmp/vnag/cache"; if (is_dir($try)) return $try; if (@mkdir($try,0777,true)) return $try; } throw new VNagException("Cannot get cache dir"); } protected function url_get_contents($url, $max_cache_time=1*60*60, $context=null) { $cache_file = $this->get_cache_dir().'/'.hash('sha256',$url); if (file_exists($cache_file) && (time()-filemtime($cache_file) < $max_cache_time)) { $cont = @file_get_contents($cache_file); if ($cont === false) throw new Exception("Failed to get contents from $cache_file"); } else { $options = array( 'http'=>array( 'method'=>"GET", 'header'=>"Accept-language: en\r\n" . "User-Agent: Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B334b Safari/531.21.102011-10-16 20:23:10\r\n" ) ); if (is_null($context)) $context = stream_context_create($options); $cont = @file_get_contents($url, false, $context); if ($cont === false) throw new Exception("Failed to get contents from $url"); file_put_contents($cache_file, $cont); } return $cont; } } class VNagException extends Exception { public function getStatus() { return VNag::STATUS_ERROR; } } class VNagTimeoutException extends VNagException {} class VNagWebInfoException extends VNagException {} class VNagSignatureException extends VNagException {} class VNagPublicKeyException extends VNagException {} class VNagPrivateKeyException extends VNagException {} class VNagInvalidArgumentException extends VNagException { public function getStatus() { return VNag::STATUS_UNKNOWN; } } class VNagValueUomPairSyntaxException extends VNagInvalidArgumentException { public function __construct($str) { $e_msg = sprintf(VNagLang::$valueUomPairSyntaxError, $str); parent::__construct($e_msg); } } class VNagInvalidTimeoutException extends VNagInvalidArgumentException {} class VNagInvalidRangeException extends VNagInvalidArgumentException { public function __construct($msg) { $e_msg = VNagLang::$range_is_invalid; if (!_empty($msg)) $e_msg .= ': '.trim($msg); parent::__construct($e_msg); } } class VNagInvalidShortOpt extends VNagImplementationErrorException {} class VNagInvalidLongOpt extends VNagImplementationErrorException {} class VNagInvalidValuePolicy extends VNagImplementationErrorException {} class VNagIllegalStatusModel extends VNagImplementationErrorException {} class VNagNotConstructed extends VNagImplementationErrorException {} class VNagImplementationErrorException extends VNagException {} class VNagInvalidStandardArgument extends VNagImplementationErrorException {} class VNagFunctionCallOutsideSession extends VNagImplementationErrorException {} class VNagIllegalArgumentValuesException extends VNagImplementationErrorException {} class VNagRequiredArgumentNotRegistered extends VNagImplementationErrorException { public function __construct($required_argument) { $e_msg = sprintf(VNagLang::$query_without_expected_argument, $required_argument); parent::__construct($e_msg); } } class VNagRequiredArgumentMissing extends VNagInvalidArgumentException { public function __construct($required_argument) { $e_msg = sprintf(VNagLang::$required_argument_missing, $required_argument); parent::__construct($e_msg); } } class VNagUnknownUomException extends VNagInvalidArgumentException { public function __construct($uom) { $e_msg = sprintf(VNagLang::$perfdata_uom_not_recognized, $uom); parent::__construct($e_msg); } } class VNagNoCompatibleRangeUomFoundException extends VNagException {} class VNagMixedUomsNotImplemented extends VNagInvalidArgumentException { public function __construct($uom1, $uom2) { if (_empty($uom1)) $uom1 = VNagLang::$none; if (_empty($uom2)) $uom2 = VNagLang::$none; $e_msg = sprintf(VNagLang::$perfdata_mixed_uom_not_implemented, $uom1, $uom2); parent::__construct($e_msg); } } class VNagUomConvertException extends VNagInvalidArgumentException { public function __construct($uom1, $uom2) { if (_empty($uom1)) $uom1 = VNagLang::$none; if (_empty($uom2)) $uom2 = VNagLang::$none; $e_msg = sprintf(VNagLang::$convert_x_y_error, $uom1, $uom2); parent::__construct($e_msg); } } class VNagInvalidPerformanceDataException extends VNagInvalidArgumentException { public function __construct($msg) { $e_msg = VNagLang::$performance_data_invalid; if (!_empty($msg)) $e_msg .= ': '.trim($msg); parent::__construct($e_msg); } } class Timeouter { private static $start_time = false; private static $timeout; private static $fired = false; private static $registered = false; private function __construct() { } public static function start($timeout) { if (!is_numeric($timeout) || ($timeout <= 0)) { throw new VNagInvalidTimeoutException(sprintf(VNagLang::$timeout_value_invalid, $timeout)); } self::$start_time = microtime(true); self::$timeout = (float) $timeout; self::$fired = false; if (!self::$registered) { self::$registered = true; register_tick_function(array('Timeouter', 'tick')); } } public static function started() { return self::$registered; } public static function end() { if (self::$registered) { unregister_tick_function(array('Timeouter', 'tick')); self::$registered = false; } } public static function tick() { if ((!self::$fired) && ((microtime(true) - self::$start_time) > self::$timeout)) { self::$fired = true; throw new VNagTimeoutException(VNagLang::$timeout_exception); } } } class VNagArgument { const VALUE_FORBIDDEN = 0; const VALUE_REQUIRED = 1; const VALUE_OPTIONAL = 2; protected $shortopt; protected $longopts; protected $valuePolicy; protected $valueName; protected $helpText; protected $defaultValue = null; protected static $all_short = ''; protected static $all_long = array(); public function getShortOpt() { return $this->shortopt; } public function getLongOpts() { return $this->longopts; } public function getValuePolicy() { return $this->valuePolicy; } public function getValueName() { return $this->valueName; } public function getHelpText() { return $this->helpText; } static private function validateShortOpt($shortopt) { $m = array(); return preg_match('@^[a-zA-Z0-9\\+\\-\\?]$@', $shortopt, $m); } static private function validateLongOpt($longopt) { $m = array(); return preg_match('@^[a-zA-Z0-9\\+\\-\\?]+$@', $longopt, $m); } public function __construct($shortopt, $longopts, $valuePolicy, $valueName, $helpText, $defaultValue=null) { switch ($valuePolicy) { case VNagArgument::VALUE_FORBIDDEN: if (!_empty($valueName)) { throw new VNagImplementationErrorException(sprintf(VNagLang::$value_name_forbidden)); } break; case VNagArgument::VALUE_REQUIRED: if (_empty($valueName)) { throw new VNagImplementationErrorException(sprintf(VNagLang::$value_name_required)); } break; case VNagArgument::VALUE_OPTIONAL: if (_empty($valueName)) { throw new VNagImplementationErrorException(sprintf(VNagLang::$value_name_required)); } break; default: throw new VNagInvalidValuePolicy(sprintf(VNagLang::$illegal_valuepolicy, $valuePolicy)); } if (!_empty($shortopt)) { if (!self::validateShortOpt($shortopt)) { throw new VNagInvalidShortOpt(sprintf(VNagLang::$illegal_shortopt, $shortopt)); } } if (is_array($longopts)) { foreach ($longopts as $longopt) { if (!self::validateLongOpt($longopt)) { throw new VNagInvalidLongOpt(sprintf(VNagLang::$illegal_longopt, $longopt)); } } } else if (!_empty($longopts)) { if (!self::validateLongOpt($longopts)) { throw new VNagInvalidLongOpt(sprintf(VNagLang::$illegal_longopt, $longopts)); } $longopts = array($longopts); } else { $longopts = array(); } switch ($valuePolicy) { case VNagArgument::VALUE_FORBIDDEN: $policyApdx = ''; break; case VNagArgument::VALUE_REQUIRED: $policyApdx = ':'; break; case VNagArgument::VALUE_OPTIONAL: $policyApdx = '::'; break; default: throw new VNagInvalidValuePolicy(sprintf(VNagLang::$illegal_valuepolicy, $valuePolicy)); } if ((!is_null($shortopt)) && ($shortopt != '?')) self::$all_short .= $shortopt.$policyApdx; if (is_array($longopts)) { foreach ($longopts as $longopt) { self::$all_long[] = $longopt.$policyApdx; } } $this->shortopt = $shortopt; $this->longopts = $longopts; $this->valuePolicy = $valuePolicy; $this->valueName = $valueName; $this->helpText = $helpText; $this->defaultValue = $defaultValue; } protected static function getOptions() { global $OVERWRITE_ARGUMENTS; if (!is_null($OVERWRITE_ARGUMENTS)) { return $OVERWRITE_ARGUMENTS; } else if (VNag::is_http_mode()) { return $_REQUEST; } else { return getopt(self::$all_short, self::$all_long); } } public function count() { $options = self::getOptions(); $count = 0; if (isset($options[$this->shortopt])) { if (is_array($options[$this->shortopt])) { $count += count($options[$this->shortopt]); } else { $count += 1; } } if (!is_null($this->longopts)) { foreach ($this->longopts as $longopt) { if (isset($options[$longopt])) { if (is_array($options[$longopt])) { $count += count($options[$longopt]); } else { $count += 1; } } } } return $count; } public function available() { $options = self::getOptions(); if (isset($options[$this->shortopt])) return true; if (!is_null($this->longopts)) { foreach ($this->longopts as $longopt) { if (isset($options[$longopt])) return true; } } return false; } public function require() { if (!$this->available() && is_null($this->defaultValue)) { $opt = $this->shortopt; $opt = !_empty($opt) ? '-'.$opt : (isset($this->longopts[0]) ? '--'.$this->longopts[0] : '?'); throw new VNagRequiredArgumentMissing($opt); } } public function getValue() { $options = self::getOptions(); if (isset($options[$this->shortopt])) { $x = $options[$this->shortopt]; if (is_array($x) && (count($x) <= 1)) $options[$this->shortopt] = $options[$this->shortopt][0]; return $options[$this->shortopt]; } if (!is_null($this->longopts)) { foreach ($this->longopts as $longopt) { if (isset($options[$longopt])) { $x = $options[$longopt]; if (is_array($x) && (count($x) <= 1)) $options[$longopt] = $options[$longopt][0]; return $options[$longopt]; } } } return $this->defaultValue; } } class VNagArgumentHandler { protected $expectedArgs = array(); protected function _addExpectedArgument($argObj) { if ($argObj->getShortOpt() == '?') return false; if ($argObj->getShortOpt() == '-') return false; if ($argObj->getShortOpt() == '+') return false; $this->expectedArgs[] = $argObj; return true; } public function getArgumentObj($shortopt) { foreach ($this->expectedArgs as $argObj) { if ($argObj->getShortOpt() == $shortopt) return $argObj; } return null; } public function isArgRegistered($shortopt) { return !is_null($this->getArgumentObj($shortopt)); } public function illegalUsage() { global $argv; return (isset($argv[1])) && (($argv[1] == '-?') || ($argv[1] == '/?')); } } class VNagRange { public $start; public $end; public $warnInsideRange; public function __construct($rangeDef, $singleValueBehavior=VNag::SINGLEVALUE_RANGE_DEFAULT) { $m = array(); if (!preg_match('|^(@){0,1}([^:]+)(:){0,1}(.*)$|', $rangeDef, $m)) { throw new VNagInvalidRangeException(sprintf(VNagLang::$range_invalid_syntax, $rangeDef)); } $this->warnInsideRange = $m[1] === '@'; $this->start = null; $this->end = null; if ($m[3] === ':') { if ($m[2] === '~') { $this->start = '-inf'; } else { $this->start = new VNagValueUomPair($m[2]); } if (_empty($m[4])) { $this->end = 'inf'; } else { $this->end = new VNagValueUomPair($m[4]); } } else { assert(_empty($m[4])); assert(!_empty($m[2])); $x = $m[2]; if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_DEFAULT) { $this->start = new VNagValueUomPair('0'.((new VNagValueUomPair($x))->getUom())); $this->end = new VNagValueUomPair($x); } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_GT_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 0; $this->start = '-inf'; $this->end = new VNagValueUomPair($x); } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_GE_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 1; $this->start = new VNagValueUomPair($x); $this->end = 'inf'; } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_LT_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 0; $this->start = new VNagValueUomPair($x); $this->end = 'inf'; } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_LE_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 1; $this->start = '-inf'; $this->end = new VNagValueUomPair($x); } else { throw new VNagException(VNagLang::$illegalSingleValueBehavior); } } if (is_null($this->start)) { throw new VNagInvalidRangeException(VNagLang::$invalid_start_value); } if (is_null($this->end)) { throw new VNagInvalidRangeException(VNagLang::$invalid_end_value); } if (($this->start instanceof VNagValueUomPair) && ($this->end instanceof VNagValueUomPair) && (VNagValueUomPair::compare($this->start,$this->end) > 0)) { throw new VNagInvalidRangeException(VNagLang::$start_is_greater_than_end); } } public function __toString() { $ret = ''; if ($this->warnInsideRange) { $ret = '@'; } if ($this->start === '-inf') { $ret .= '~'; } else { $ret .= $this->start; } $ret .= ':'; if ($this->end !== 'inf') { $ret .= $this->end; } return $ret; } public function checkAlert($values) { $compatibleCount = 0; if (!is_array($values)) $values = array($values); foreach ($values as $value) { if (!($value instanceof VNagValueUomPair)) $value = new VNagValueUomPair($value); assert(($this->start === '-inf') || ($this->start instanceof VNagValueUomPair)); assert(($this->end === 'inf' ) || ($this->end instanceof VNagValueUomPair)); if (($this->start !== '-inf') && (!$this->start->compatibleWith($value))) continue; if (($this->end !== 'inf') && (!$this->end->compatibleWith($value))) continue; $compatibleCount++; if ($this->warnInsideRange) { return (($this->start === '-inf') || (VNagValueUomPair::compare($value,$this->start) >= 0)) && (($this->end === 'inf') || (VNagValueUomPair::compare($value,$this->end) <= 0)); } else { return (($this->start !== '-inf') && (VNagValueUomPair::compare($value,$this->start) < 0)) || (($this->end !== 'inf') && (VNagValueUomPair::compare($value,$this->end) > 0)); } } if ((count($values) > 0) and ($compatibleCount == 0)) { throw new VNagNoCompatibleRangeUomFoundException(VNagLang::$no_compatible_range_uom_found); } return false; } } class VNagValueUomPair { protected $value; protected $uom; public $roundTo = -1; public function isRelative() { return $this->uom === '%'; } public function getValue() { return $this->value; } public function getUom() { return $this->uom; } public function __toString() { if ($this->roundTo == -1) { return $this->value.$this->uom; } else { return round($this->value,$this->roundTo).$this->uom; } } public function __construct($str) { $m = array(); if (!preg_match('/^([\d\.]+)(.*)$/ism', $str, $m)) { throw new VNagValueUomPairSyntaxException($str); } $this->value = $m[1]; $this->uom = isset($m[2]) ? $m[2] : ''; if (!self::isKnownUOM($this->uom)) { throw new VNagUnknownUomException($this->uom); } } public static function isKnownUOM(string $uom) { $no_unit = ($uom === ''); $seconds = ($uom === 's') || ($uom === 'ms') || ($uom === 'us'); $percentage = ($uom === '%'); $bytes = ($uom === 'B') || ($uom === 'KB') || ($uom === 'MB') || ($uom === 'GB') || ($uom === 'TB'); $counter = ($uom === 'c'); return ($no_unit || $seconds || $percentage || $bytes || $counter); } public function normalize($target=null) { $res = clone $this; if ($res->uom === 'ms') { $res->uom = 's'; $res->value /= 1000; } if ($res->uom === 'us') { $res->uom = 's'; $res->value /= 1000 * 1000; } if ($res->uom === 'B') { $res->uom = 'MB'; $res->value /= 1024 * 1024; } if ($res->uom === 'KB') { $res->uom = 'MB'; $res->value /= 1024; } if ($res->uom === 'GB') { $res->uom = 'MB'; $res->value *= 1024; } if ($res->uom === 'TB') { $res->uom = 'MB'; $res->value *= 1024 * 1024; } if ($res->uom === 'c') { $res->uom = ''; } if (!is_null($target)) { if ($res->uom == 'MB') { if ($target == 'B') { $res->uom = 'B'; $res->value *= 1024 * 1024; } else if ($target == 'KB') { $res->uom = 'KB'; $res->value *= 1024; } else if ($target == 'MB') { $res->uom = 'MB'; $res->value *= 1; } else if ($target == 'GB') { $res->uom = 'GB'; $res->value /= 1024; } else if ($target == 'TB') { $res->uom = 'TB'; $res->value /= 1024 * 1024; } else { throw new VNagUomConvertException($res->uom, $target); } } else if ($res->uom == 's') { if ($target == 's') { $res->uom = 's'; $res->value /= 1; } else if ($target == 'ms') { $res->uom = 'ms'; $res->value /= 1000; } else if ($target == 'us') { $res->uom = 'us'; $res->value /= 1000 * 1000; } else { throw new VNagUomConvertException($res->uom, $target); } } else { throw new VNagUomConvertException($res->uom, $target); } } return $res; } public function compatibleWith(VNagValueUomPair $other) { $a = $this->normalize(); $b = $other->normalize(); return ($a->uom == $b->uom); } public static function compare(VNagValueUomPair $left, VNagValueUomPair $right) { $a = $left->normalize(); $b = $right->normalize(); if ($a->uom != $b->uom) throw new VNagMixedUomsNotImplemented($a->uom, $b->uom); if ($a->value > $b->value) return 1; if ($a->value == $b->value) return 0; if ($a->value < $b->value) return -1; } } class VNagPerformanceData { protected $label; protected $value; protected $warn = null; protected $crit = null; protected $min = null; protected $max = null; public static function createByString($perfdata) { $perfdata = trim($perfdata); $ary = explode('=',$perfdata); if (count($ary) != 2) { throw new VNagInvalidPerformanceDataException(sprintf(VNagLang::$perfdata_line_invalid, $perfdata)); } $label = $ary[0]; $bry = explode(';',$ary[1]); if (substr($label,0,1) === "'") $label = substr($label, 1, strlen($label)-2); $value = $bry[0]; $warn = isset($bry[1]) ? $bry[1] : null; $crit = isset($bry[2]) ? $bry[2] : null; $min = isset($bry[3]) ? $bry[3] : null; $max = isset($bry[4]) ? $bry[4] : null; return new self($label, $value, $warn, $crit, $min, $max); } public function __construct($label, $value, $warn=null, $crit=null, $min=null, $max=null) { if (strpos($label, '=') !== false) throw new VNagInvalidPerformanceDataException(VNagLang::$perfdata_label_equal_sign_forbidden); $label = str_replace("'", "''", $label); $m = array(); if ((!_empty($min)) && (!preg_match('|^[-0-9\\.]+$|', $min, $m))) { throw new VNagInvalidPerformanceDataException(VNagLang::$perfdata_min_must_be_in_class); } if ((!_empty($max)) && (!preg_match('|^[-0-9\\.]+$|', $max, $m))) { throw new VNagInvalidPerformanceDataException(VNagLang::$perfdata_max_must_be_in_class); } $this->label = $label; $this->value = ($value == 'U') ? 'U' : new VNagValueUomPair($value); $this->warn = $warn; $this->crit = $crit; $this->min = $min; $this->max = $max; } public function __toString() { $label = $this->label; $value = $this->value; $warn = $this->warn; $crit = $this->crit; $min = $this->min; $max = $this->max; $label = str_replace("''", "'", $label); return "'$label'=$value". ';'.(is_null($warn) ? '' : $warn). ';'.(is_null($crit) ? '' : $crit). ';'.(is_null($min) ? '' : $min). ';'.(is_null($max) ? '' : $max); } } class VNagHelp { public $word_wrap_width = 80; public $argument_indent = 7; public function printUsagePage() { $usage = $this->getUsage(); if (_empty($usage)) { $usage = VNagLang::$no_syntax_defined; } return trim($usage)."\n"; } public function printVersionPage() { $out = trim($this->getNameAndVersion())."\n"; if ($this->word_wrap_width > 0) $out = wordwrap($out, $this->word_wrap_width, "\n", false); return $out; } static private function _conditionalLine($line, $terminator='', $prefix='') { if (!_empty($line)) { return trim($line).$terminator; } return ''; } public function printHelpPage() { $out = ''; $out .= self::_conditionalLine($this->getNameAndVersion(), "\n"); $out .= self::_conditionalLine($this->getCopyright(), "\n"); $out .= ($out != '') ? "\n" : ''; $out .= self::_conditionalLine($this->getShortDescription(), "\n\n\n"); $out .= self::_conditionalLine($this->getUsage(), "\n\n"); $out .= VNagLang::$options."\n"; foreach ($this->options as $argObj) { $out .= $this->printArgumentHelp($argObj); } $out .= self::_conditionalLine($this->getFootNotes(), "\n\n", "\n"); if ($this->word_wrap_width > 0) $out = wordwrap($out, $this->word_wrap_width, "\n", false); return $out; } protected $options = array(); protected function _addOption($argObj) { $this->options[] = $argObj; } protected function printArgumentHelp($argObj) { $identifiers = array(); $shortopt = $argObj->getShortopt(); if (!_empty($shortopt)) $identifiers[] = '-'.$shortopt; $longopts = $argObj->getLongopts(); if (!is_null($longopts)) { foreach ($longopts as $longopt) { if (!_empty($longopt)) $identifiers[] = '--'.$longopt; } } if (count($identifiers) == 0) return; $valueName = $argObj->getValueName(); $arginfo = ''; switch ($argObj->getValuePolicy()) { case VNagArgument::VALUE_FORBIDDEN: $arginfo = ''; break; case VNagArgument::VALUE_REQUIRED: $arginfo = '='.$valueName; break; case VNagArgument::VALUE_OPTIONAL: $arginfo = '[='.$valueName.']'; break; } $out = ''; $out .= implode(', ', $identifiers).$arginfo."\n"; $content = trim($argObj->getHelpText()); if ($this->word_wrap_width > 0) $content = wordwrap($content, $this->word_wrap_width-$this->argument_indent, "\n", false); $lines = explode("\n", $content); foreach ($lines as $line) { $out .= str_repeat(' ', $this->argument_indent).$line."\n"; } $out .= "\n"; return $out; } protected $pluginName; public function setPluginName($pluginName) { $this->pluginName = $this->replaceStuff($pluginName); } public function getPluginName() { if (_empty($this->pluginName)) { global $argv; return basename($argv[0]); } else { return $this->pluginName; } } protected $version; public function setVersion($version) { $this->version = $this->replaceStuff($version); } public function getVersion() { return $this->version; } public function getNameAndVersion() { $ret = $this->getPluginName(); if (_empty($ret)) return null; $ver = $this->getVersion(); if (!_empty($ver)) { $ret = sprintf(VNagLang::$x_version_x, $ret, $ver); } $ret = trim($ret); return $ret; } protected $copyright; public function setCopyright($copyright) { $this->copyright = $this->replaceStuff($copyright); } private function getVNagCopyright() { if (VNag::is_http_mode()) { $vts_email = 'www.viathinksoft.com'; } else { $vts_email = base64_decode('aW5mb0B2aWF0aGlua3NvZnQuZGU='); } return "VNag Framework ".VNag::VNAG_VERSION." (C) 2014-".date('Y')." ViaThinkSoft <$vts_email>"; } public function getCopyright() { if (_empty($this->copyright)) { return sprintf(VNagLang::$plugin_uses, $this->getVNagCopyright()); } else { return trim($this->copyright)."\n".sprintf(VNagLang::$uses, $this->getVNagCopyright()); } } protected $shortDescription; public function setShortDescription($shortDescription) { $this->shortDescription = $this->replaceStuff($shortDescription); } public function getShortDescription() { if (_empty($this->shortDescription)) { return null; } else { $content = $this->shortDescription; if ($this->word_wrap_width > 0) $content = wordwrap($content, $this->word_wrap_width, "\n", false); return $content; } } protected function replaceStuff($text) { global $argv; if (php_sapi_name() == 'cli') { $text = str_replace('$SCRIPTNAME$', $argv[0], $text); } else { $text = str_replace('$SCRIPTNAME$', basename($_SERVER['SCRIPT_NAME']), $text); } $text = str_replace('$CURYEAR$', date('Y'), $text); return $text; } protected $syntax; public function setSyntax($syntax) { $syntax = $this->replaceStuff($syntax); $this->syntax = $syntax; } public function getUsage() { if (_empty($this->syntax)) { return null; } else { return sprintf(VNagLang::$usage_x, $this->syntax); } } protected $footNotes; public function setFootNotes($footNotes) { $this->footNotes = $this->replaceStuff($footNotes); } public function getFootNotes() { return $this->footNotes; } } class VNagLang { public static function status($code, $statusmodel) { switch ($statusmodel) { case VNag::STATUSMODEL_SERVICE: switch ($code) { case VNag::STATUS_OK: return 'OK'; case VNag::STATUS_WARNING: return 'Warning'; case VNag::STATUS_CRITICAL: return 'Critical'; case VNag::STATUS_UNKNOWN: return 'Unknown'; default: return sprintf('Error (%d)', $code); } case VNag::STATUSMODEL_HOST: switch ($code) { case VNag::STATUS_UP: return 'Up'; case VNag::STATUS_DOWN: return 'Down'; default: return sprintf('Maintain last state (%d)', $code); } default: throw new VNagIllegalStatusModel(sprintf(self::$illegal_statusmodel, $statusmodel)); } } static $nagios_output = 'VNag-Output'; static $verbose_info = 'Verbose information'; static $status = 'Status'; static $message = 'Message'; static $performance_data = 'Performance data'; static $status_ok = 'OK'; static $status_warn = 'Warning'; static $status_critical = 'Critical'; static $status_unknown = 'Unknown'; static $status_error = 'Error'; static $unhandled_exception_without_msg = "Unhandled exception of type %s"; static $plugin_uses = 'This plugin uses %s'; static $uses = 'uses %s'; static $x_version_x = '%s, version %s'; static $argname_value = 'value'; static $argname_seconds = 'seconds'; static $query_without_expected_argument = "The argument '%s' is queried, but was not added to the list of expected arguments. Please contact the plugin author."; static $required_argument_missing = "The argument '%s' is required."; static $performance_data_invalid = 'Performance data invalid.'; static $no_standard_arguments_with_letter = "No standard argument with letter '%s' exists."; static $invalid_start_value = 'Invalid start value.'; static $invalid_end_value = 'Invalid end value.'; static $start_is_greater_than_end = 'Start is greater than end value.'; static $value_name_forbidden = "Implementation error: You may not define a value name for the argument, because the value policy is VALUE_FORBIDDEN."; static $value_name_required = "Implementation error: Please define a name for the argument (so it can be shown in the help page)."; static $illegal_shortopt = "Illegal shortopt '-%s'."; static $illegal_longopt = "Illegal longopt '--%s'."; static $illegal_valuepolicy = "valuePolicy has illegal value '%s'."; static $range_invalid_syntax = "Syntax error in range '%s'."; static $timeout_value_invalid = "Timeout value '%s' is invalid."; static $range_is_invalid = 'Range is invalid.'; static $timeout_exception = 'Timeout!'; static $perfdata_label_equal_sign_forbidden = 'Label may not contain an equal sign.'; static $perfdata_value_must_be_in_class = 'Value must be in class [-0-9.] or be \'U\' if the actual value can\'t be determined.'; static $perfdata_min_must_be_in_class = 'Min must be in class [-0-9.] or empty.'; static $perfdata_max_must_be_in_class = 'Max must be in class [-0-9.] or empty.'; static $perfdata_uom_not_recognized = 'UOM (unit of measurement) "%s" is not recognized.'; static $perfdata_mixed_uom_not_implemented = 'Mixed UOMs (%s and %s) are currently not supported.'; static $no_compatible_range_uom_found = 'Measured values are not compatible with the provided warning/critical parameter. Most likely, the UOM is incompatible.'; static $exception_x = '%s (%s)'; static $no_syntax_defined = 'The author of this plugin has not defined a syntax for this plugin.'; static $usage_x = "Usage:\n%s"; static $options = "Options:"; static $illegal_statusmodel = "Invalid statusmodel %d."; static $none = '[none]'; static $valueUomPairSyntaxError = 'Syntax error at "%s". Syntax must be Value[UOM].'; static $too_few_warning_ranges = "You have too few warning ranges (currently trying to get element %d)."; static $too_few_critical_ranges = "You have too few critical ranges (currently trying to get element %d)."; static $dataset_missing = 'Dataset missing.'; static $payload_not_base64 = 'The payload is not valid Base64.'; static $payload_not_json = 'The payload is not valid JSON.'; static $signature_missing = 'The signature is missing.'; static $signature_not_bas64 = 'The signature is not valid Base64.'; static $signature_invalid = 'The signature is invalid. The connection might have been tampered, or a different key is used.'; static $pubkey_file_not_found = "Public key file %s was not found."; static $pubkey_file_not_readable = "Public key file %s is not readable."; static $privkey_file_not_found = "Private key file %s was not found."; static $privkey_not_readable = "Private key is not readable."; static $privkey_file_not_readable = "Private key file %s is not readable."; static $signature_failed = "Signature failed."; static $perfdata_line_invalid = "Performance data line %s is invalid."; static $singlevalue_unexpected_at_symbol = 'This plugin does not allow the @-symbol at ranges for single values.'; static $illegalSingleValueBehavior = "Illegal value for 'singleValueBehavior'. Please contact the creator of the plugin."; static $dataset_encryption_no_array = 'Dataset encryption information invalid.'; static $require_password = 'This resource is protected with a password. Please provide a password.'; static $wrong_password = 'This resource is protected with a password. You have provided the wrong password, or it was changed.'; static $convert_x_y_error = 'Cannot convert from UOM %s to UOM %s.'; static $php_error = 'PHP has detected an error in the plugin. Please contact the plugin author.'; static $output_level_lowered = "Output Buffer level lowered during cbRun(). Please contact the plugin author."; static $openssl_missing = "OpenSSL is missing. Therefore, encryption and signatures are not available."; static $warning_range = 'Warning range'; static $critical_range = 'Critical range'; static $prints_version = 'Prints version'; static $verbosity_helptext = 'Verbosity -v, -vv or -vvv'; static $timeout_helptext = 'Sets timeout in seconds'; static $help_helptext = 'Prints help page'; static $prints_usage = 'Prints usage'; static $notConstructed = 'Parent constructor not called with parent::__construct().'; } function vnagErrorHandler($errorkind, $errortext, $file, $line) { global $inside_vnag_run; if (!$inside_vnag_run && VNag::is_http_mode()) { return false; } if (!(error_reporting() & $errorkind)) { return true; } if (defined('E_ERROR') && ($errorkind == E_ERROR)) $errorkind = 'Error'; if (defined('E_WARNING') && ($errorkind == E_WARNING)) $errorkind = 'Warning'; if (defined('E_PARSE') && ($errorkind == E_PARSE)) $errorkind = 'Parse'; if (defined('E_NOTICE') && ($errorkind == E_NOTICE)) $errorkind = 'Notice'; if (defined('E_CORE_ERROR') && ($errorkind == E_CORE_ERROR)) $errorkind = 'Core Error'; if (defined('E_CORE_WARNING') && ($errorkind == E_CORE_WARNING)) $errorkind = 'Core Warning'; if (defined('E_COMPILE_ERROR') && ($errorkind == E_COMPILE_ERROR)) $errorkind = 'Compile Error'; if (defined('E_COMPILE_WARNING') && ($errorkind == E_COMPILE_WARNING)) $errorkind = 'Compile Warning'; if (defined('E_USER_ERROR') && ($errorkind == E_USER_ERROR)) $errorkind = 'User Error'; if (defined('E_USER_WARNING') && ($errorkind == E_USER_WARNING)) $errorkind = 'User Warning'; if (defined('E_USER_NOTICE') && ($errorkind == E_USER_NOTICE)) $errorkind = 'User Notice'; if (defined('E_STRICT') && ($errorkind == E_STRICT)) $errorkind = 'Strict'; if (defined('E_RECOVERABLE_ERROR') && ($errorkind == E_RECOVERABLE_ERROR)) $errorkind = 'Recoverable Error'; if (defined('E_DEPRECATED') && ($errorkind == E_DEPRECATED)) $errorkind = 'Deprecated'; if (defined('E_USER_DEPRECATED') && ($errorkind == E_USER_DEPRECATED)) $errorkind = 'User Deprecated'; throw new VNagException(VNagLang::$php_error . " $errortext at $file:$line (kind $errorkind)"); } $inside_vnag_run = false; $old_error_handler = set_error_handler("vnagErrorHandler"); <?php
declare(ticks=1); class DiskRunningCheck extends VNag { protected $argDisks = null; public function __construct() { parent::__construct(); if ($this->is_http_mode()) { $this->registerExpectedStandardArguments(''); } else { $this->registerExpectedStandardArguments('Vhtv'); } $this->getHelpManager()->setPluginName('vnag_disk_running'); $this->getHelpManager()->setVersion('2023-10-13'); $this->getHelpManager()->setShortDescription('This plugin checks if a disk is running/online, even if no SMART functionality is available.'); $this->getHelpManager()->setCopyright('Copyright (C) 2011-$CURYEAR$ Daniel Marschall, ViaThinkSoft.'); $this->getHelpManager()->setSyntax('$SCRIPTNAME$ -d diskname[,diskname[,...]]'); $this->getHelpManager()->setFootNotes('If you encounter bugs, please contact ViaThinkSoft at www.viathinksoft.com'); $this->addExpectedArgument($this->argDisks = new VNagArgument('d', 'disknames', VNagArgument::VALUE_REQUIRED, 'disks', 'Disks to be monitored, e.g. "sda,sdb"')); } protected function cbRun() { $count_total = 0; $count_running = 0; $count_offline = 0; $count_warning = 0; $count_unknown = 0; $disks = $this->argDisks->getValue(); if (empty($disks)) { throw new VNagException("Please specify the disks you want to monitor."); } $disks = explode(',',$disks); foreach ($disks as $disk) { $disk = preg_replace('@^/dev/@', '', $disk); $disk = preg_replace('@[^a-zA-Z0-9]@', '', $disk); $disk = preg_replace('@^(...)\d+@', '\\1', $disk); $count_total++; if (!file_exists("/dev/$disk")) { $this->addVerboseMessage("$disk : Drive does not exist", VNag::VERBOSITY_SUMMARY); $this->setStatus(VNag::STATUS_CRITICAL); $count_offline++; } else { $state_file = "/sys/block/$disk/device/state"; if (!file_exists($state_file)) { $this->addVerboseMessage("$disk : Cannot fetch state (Is this a valid block device?)", VNag::VERBOSITY_SUMMARY); $this->setStatus(VNag::STATUS_CRITICAL); $count_unknown++; } else { $cont = @file_get_contents($state_file); if ($cont === false) throw new VNagException("Cannot read $state_file"); $state = trim($cont); if ($state != 'running') { $this->addVerboseMessage("$disk : $state", VNag::VERBOSITY_SUMMARY); $this->setStatus(VNag::STATUS_CRITICAL); $count_offline++; } else { $this->addVerboseMessage("$disk : $state", VNag::VERBOSITY_ADDITIONAL_INFORMATION); $this->setStatus(VNag::STATUS_OK); $count_running++; } } } } $this->setHeadline(sprintf('Checked %d disks (%d running, %d offline, %d warnings, %d unknown)', $count_total, $count_running, $count_offline, $count_warning, $count_unknown)); } } <?php
-=›°ÄyÙS¸GÒ„‰àŽz6»ŒOCu$®ô[¯xyÌà^‘æãæ1ôZŒ`TðÐÉU/ $SœËÛNîËáPèGBMB
\ No newline at end of file
+0€ÆFK·_ÕõÑKfÉ¥‚ì¯3¸©RóÜkŒv¢Æ[J…±$-û¾ä²’" W‡àìÿaߟ™GBMB
\ No newline at end of file
/trunk/bin/file_timestamp.phar
291,9 → 291,10
 
Extract_Phar::go();
__HALT_COMPILER(); ?>
k‚a:1:{s:23:"1.3.6.1.4.1.37476.3.0.2";s:340:"sha256||framework/vnag_framework.inc.php|460b109d1c578e9b6af41612e0312c9f36fd8beb51f7aa92f1b7bd49614568e8||plugins/file_timestamp/FileTimestampCheck.class.php|eeabe5f13e86361293d073dcce8d184d17e96201b2c4256a326d627c3abee785||plugins/file_timestamp/check_file_timestamp.phps|fa74bf1789c5d6ed619a721dcf6c4c1018f34dc3e1b88afeb424b57da9250143||";} framework/vnag_framework.inc.phpLÙyï*eLُ4p”¤3plugins/file_timestamp/FileTimestampCheck.class.php¤yï*e¤¼
¤0plugins/file_timestamp/check_file_timestamp.phpsÎyï*eÎRiÒû¤<?php ?>
<?php
·Îa:1:{s:23:"1.3.6.1.4.1.37476.3.0.2";s:416:"sha256||<builder>|481cf75d675006b504520fd2acb3b29c89aea03aab64754e0adfb364de4914b2||framework/vnag_framework.inc.php|0387bf3134f8cc2d1ae24e139019c0edef19c1ba5ca765624efea0b469c7897f||plugins/file_timestamp/FileTimestampCheck.class.php|eeabe5f13e86361293d073dcce8d184d17e96201b2c4256a326d627c3abee785||plugins/file_timestamp/check_file_timestamp.phps|fa74bf1789c5d6ed619a721dcf6c4c1018f34dc3e1b88afeb424b57da9250143||";} framework/vnag_framework.inc.phpBÙ» +eBÙÞß=¤3plugins/file_timestamp/FileTimestampCheck.class.php¤» +e¤¼
¤0plugins/file_timestamp/check_file_timestamp.phpsλ +eÎRiÒû¤<?php
if (!VNag::is_http_mode()) error_reporting(E_ALL); declare(ticks=1); set_time_limit(0); define('VNAG_JSONDATA_V1', 'oid:1.3.6.1.4.1.37476.2.3.1.1'); $OVERWRITE_ARGUMENTS = null; function _empty($x) { return is_null($x) || (trim($x) == ''); } abstract class VNag { const VNAG_VERSION = '2023-10-13'; const STATUS_OK = 0; const STATUS_WARNING = 1; const STATUS_CRITICAL = 2; const STATUS_UNKNOWN = 3; const STATUS_ERROR = 4; const STATUS_UP = 0; const STATUS_DOWN = 1; const STATUS_MAINTAIN = 2; const VERBOSITY_SUMMARY = 0; const VERBOSITY_ADDITIONAL_INFORMATION = 1; const VERBOSITY_CONFIGURATION_DEBUG = 2; const VERBOSITY_PLUGIN_DEBUG = 3; const MAX_VERBOSITY = self::VERBOSITY_PLUGIN_DEBUG; const STATUSMODEL_SERVICE = 0; const STATUSMODEL_HOST = 1; private $initialized = false; private $status = null; private $messages = array(); private $verbose_info = ''; private $warningRanges = array(); private $criticalRanges = array(); private $performanceDataObjects = array(); private static $exitcode = 0; private $helpObj = null; private $argHandler = null; const OUTPUT_NEVER = 0; const OUTPUT_SPECIAL = 1; const OUTPUT_NORMAL = 2; const OUTPUT_EXCEPTION = 4; const OUTPUT_ALWAYS = 7; public $http_visual_output = self::OUTPUT_ALWAYS; public $http_invisible_output = self::OUTPUT_ALWAYS; protected $html_before = ''; protected $html_after = ''; protected $statusmodel = self::STATUSMODEL_SERVICE; protected $show_status_in_headline = true; protected $default_status = self::STATUS_UNKNOWN; protected $default_warning_range = null; protected $default_critical_range = null; protected $argWarning; protected $argCritical; protected $argVersion; protected $argVerbosity; protected $argTimeout; protected $argHelp; protected $argUsage; public $id = null; protected static $http_serial_number = 0; public $privkey = null; public $privkey_password = null; public $sign_algo = null; public $pubkey = null; protected $warningSingleValueRangeBehaviors = array(self::SINGLEVALUE_RANGE_DEFAULT); protected $criticalSingleValueRangeBehaviors = array(self::SINGLEVALUE_RANGE_DEFAULT); const SINGLEVALUE_RANGE_DEFAULT = 0; const SINGLEVALUE_RANGE_VAL_GT_X_BAD = 1; const SINGLEVALUE_RANGE_VAL_GE_X_BAD = 2; const SINGLEVALUE_RANGE_VAL_LT_X_BAD = 3; const SINGLEVALUE_RANGE_VAL_LE_X_BAD = 4; public $password_out = null; public $password_in = null; public static function is_http_mode() { return php_sapi_name() !== 'cli'; } public function getHelpManager() { return $this->helpObj; } public function getArgumentHandler() { return $this->argHandler; } public function outputHTML($text, $after_visual_output=true) { if ($this->is_http_mode()) { if ($this->initialized) { if ($after_visual_output) { $this->html_after .= $text; } else { $this->html_before .= $text; } } else { echo $text; } } } protected function resetArguments() { $this->argWarning = null; $this->argCritical = null; $this->argVersion = null; $this->argVerbosity = null; $this->argTimeout = null; $this->argHelp = null; $this->argWarning = null; $this->argCritical = null; } public function registerExpectedStandardArguments($args) { $this->resetArguments(); for ($i=0; $i<strlen($args); $i++) { switch ($args[$i]) { case 'w': $this->addExpectedArgument($this->argWarning = new VNagArgument('w', 'warning', VNagArgument::VALUE_REQUIRED, VNagLang::$argname_value, VNagLang::$warning_range)); break; case 'c': $this->addExpectedArgument($this->argCritical = new VNagArgument('c', 'critical', VNagArgument::VALUE_REQUIRED, VNagLang::$argname_value, VNagLang::$critical_range)); break; case 'V': $this->addExpectedArgument($this->argVersion = new VNagArgument('V', 'version', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$prints_version)); break; case 'v': $this->addExpectedArgument($this->argVerbosity = new VNagArgument('v', 'verbose', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$verbosity_helptext)); break; case 't': $this->addExpectedArgument($this->argTimeout = new VNagArgument('t', 'timeout', VNagArgument::VALUE_REQUIRED, VNagLang::$argname_seconds, VNagLang::$timeout_helptext)); break; case 'h': $this->addExpectedArgument($this->argHelp = new VNagArgument('h', 'help', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$help_helptext)); break; default: $letter = $args[$i]; throw new VNagInvalidStandardArgument(sprintf(VNagLang::$no_standard_arguments_with_letter, $letter)); } } } public function addExpectedArgument($argObj) { $helpObjAddEntryMethod = new ReflectionMethod($this->helpObj, '_addOption'); $helpObjAddEntryMethod->setAccessible(true); $helpObjAddEntryMethod->invoke($this->helpObj, $argObj); $argHandlerAddEntryMethod = new ReflectionMethod($this->argHandler, '_addExpectedArgument'); $argHandlerAddEntryMethod->setAccessible(true); $argHandlerAddEntryMethod->invoke($this->argHandler, $argObj); } protected function createArgumentHandler() { $this->argHandler = new VNagArgumentHandler(); } protected function createHelpObject() { $this->helpObj = new VNagHelp(); } protected function checkInitialized() { if (!$this->initialized) throw new VNagFunctionCallOutsideSession(); } protected function getVerbosityLevel() { $this->checkInitialized(); if (!isset($this->argVerbosity)) { return self::VERBOSITY_SUMMARY; } else { $level = $this->argVerbosity->count(); if ($level > self::MAX_VERBOSITY) $level = self::MAX_VERBOSITY; return $level; } } public function getWarningRange($argumentNumber=0) { $this->checkInitialized(); if (!isset($this->warningRanges[$argumentNumber])) { if (!is_null($this->argWarning)) { $warning = $this->argWarning->getValue(); if (!is_null($warning)) { $vals = explode(',',$warning); foreach ($vals as $number => $val) { if (_empty($val)) { $this->warningRanges[$number] = null; } else { $singleValueBehavior = isset($this->warningSingleValueRangeBehaviors[$number]) ? $this->warningSingleValueRangeBehaviors[$number] : VNag::SINGLEVALUE_RANGE_DEFAULT; $this->warningRanges[$number] = new VNagRange($val, $singleValueBehavior); } } } else { $this->warningRanges[0] = $this->default_warning_range; } } else { return null; } } if (isset($this->warningRanges[$argumentNumber])) { return $this->warningRanges[$argumentNumber]; } else { return null; } } public function getCriticalRange($argumentNumber=0) { $this->checkInitialized(); if (!isset($this->criticalRanges[$argumentNumber])) { if (!is_null($this->argCritical)) { $critical = $this->argCritical->getValue(); if (!is_null($critical)) { $vals = explode(',',$critical); foreach ($vals as $number => $val) { $singleValueBehavior = isset($this->criticalSingleValueRangeBehaviors[$number]) ? $this->criticalSingleValueRangeBehaviors[$number] : VNag::SINGLEVALUE_RANGE_DEFAULT; $this->criticalRanges[$number] = new VNagRange($val, $singleValueBehavior); } } else { $this->criticalRanges[0] = $this->default_critical_range; } } else { return null; } } if (isset($this->criticalRanges[$argumentNumber])) { return $this->criticalRanges[$argumentNumber]; } else { return null; } } public function checkAgainstWarningRange($values, $force=true, $autostatus=true, $argumentNumber=0) { $this->checkInitialized(); if (!$this->getArgumentHandler()->isArgRegistered('w')) { throw new VNagRequiredArgumentNotRegistered('-w'); } $wr = $this->getWarningRange($argumentNumber); if (isset($wr)) { if ($wr->checkAlert($values)) { if ($autostatus) $this->setStatus(VNag::STATUS_WARNING); return true; } else { if ($autostatus) $this->setStatus(VNag::STATUS_OK); return false; } } else { if ($force) { if (($argumentNumber > 0) && (count($this->warningRanges) > 0)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$too_few_warning_ranges, $argumentNumber+1)); } else { throw new VNagRequiredArgumentMissing('-w'); } } } } public function checkAgainstCriticalRange($values, $force=true, $autostatus=true, $argumentNumber=0) { $this->checkInitialized(); if (!$this->getArgumentHandler()->isArgRegistered('c')) { throw new VNagRequiredArgumentNotRegistered('-c'); } $cr = $this->getCriticalRange($argumentNumber); if (isset($cr)) { if ($cr->checkAlert($values)) { if ($autostatus) $this->setStatus(VNag::STATUS_CRITICAL); return true; } else { if ($autostatus) $this->setStatus(VNag::STATUS_OK); return false; } } else { if ($force) { if (($argumentNumber > 0) && (count($this->warningRanges) > 0)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$too_few_critical_ranges, $argumentNumber+1)); } else { throw new VNagRequiredArgumentMissing('-c'); } } } } protected static function getBaddestExitcode($code1, $code2) { return max($code1, $code2); } public static function _shutdownHandler() { if (!self::is_http_mode()) { exit((int)self::$exitcode); } } protected function _exit($code) { self::$exitcode = $this->getBaddestExitcode($code, self::$exitcode); } private $constructed = false; function __construct() { $this->createHelpObject(); $this->createArgumentHandler(); $this->addExpectedArgument($this->argUsage = new VNagArgument('?', '', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$prints_usage)); $this->constructed = true; } function __destruct() { if (Timeouter::started()) { Timeouter::end(); } } public function run() { global $inside_vnag_run; $inside_vnag_run = true; try { if (!$this->constructed) { throw new VNagNotConstructed(VNagLang::$notConstructed); } try { $this->initialized = true; $this->html_before = ''; $this->html_after = ''; $this->setStatus(null, true); $this->messages = array(); register_shutdown_function(array($this, '_shutdownHandler')); if ($this->argHandler->illegalUsage()) { $content = $this->helpObj->printUsagePage(); $this->setStatus(VNag::STATUS_UNKNOWN); if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_visual_output & VNag::OUTPUT_SPECIAL) echo $this->writeVisualHTML($content); if ($this->http_invisible_output & VNag::OUTPUT_SPECIAL) echo $this->writeInvisibleHTML($content); echo $this->html_after; return; } else { echo $content; return $this->_exit($this->status); } } if (!is_null($this->argVersion) && ($this->argVersion->available())) { $content = $this->helpObj->printVersionPage(); $this->setStatus(VNag::STATUS_UNKNOWN); if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_visual_output & VNag::OUTPUT_SPECIAL) echo $this->writeVisualHTML($content); if ($this->http_invisible_output & VNag::OUTPUT_SPECIAL) echo $this->writeInvisibleHTML($content); echo $this->html_after; return; } else { echo $content; return $this->_exit($this->status); } } if (!is_null($this->argHelp) && ($this->argHelp->available())) { $content = $this->helpObj->printHelpPage(); $this->setStatus(VNag::STATUS_UNKNOWN); if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_visual_output & VNag::OUTPUT_SPECIAL) echo $this->writeVisualHTML($content); if ($this->http_invisible_output & VNag::OUTPUT_SPECIAL) echo $this->writeInvisibleHTML($content); echo $this->html_after; return; } else { echo $content; return $this->_exit($this->status); } } $this->getWarningRange(); $this->getCriticalRange(); if (!is_null($this->argTimeout)) { $timeout = $this->argTimeout->getValue(); if (!is_null($timeout)) { Timeouter::start($timeout); } } ob_start(); $init_ob_level = ob_get_level(); try { $this->cbRun(); if (ob_get_level() < $init_ob_level) throw new VNagImplementationErrorException(VNagLang::$output_level_lowered); } finally { while (ob_get_level() > $init_ob_level) @ob_end_clean(); } if (is_null($this->status)) $this->setStatus($this->default_status,true); $outputType = VNag::OUTPUT_NORMAL; } catch (Exception $e) { $this->handleException($e); $outputType = VNag::OUTPUT_EXCEPTION; } if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_invisible_output & $outputType) { echo $this->writeInvisibleHTML(); } if ($this->http_visual_output & $outputType) { echo $this->writeVisualHTML(); } echo $this->html_after; } else { echo $this->getNagiosConsoleText(); return $this->_exit($this->status); } Timeouter::end(); } finally { $inside_vnag_run = false; } } private function getNagiosConsoleText() { $ary_perfdata = $this->getPerformanceData(); $performancedata_first = array_shift($ary_perfdata); $performancedata_rest = implode(' ', $ary_perfdata); $status_text = VNagLang::status($this->status, $this->statusmodel); if (_empty($this->getHeadline())) { $content = $status_text; } else { if ($this->show_status_in_headline) { $content = $status_text.': '.$this->getHeadline(); } else { $content = $this->getHeadline(); } } if (!_empty($performancedata_first)) $content .= '|'.trim($performancedata_first); $content .= "\n"; if (!_empty($this->verbose_info)) { $content .= trim($this->verbose_info); } if (!_empty($performancedata_rest)) $content .= '|'.trim($performancedata_rest); $content .= "\n"; return trim($content)."\n"; } abstract protected function cbRun(); public function addPerformanceData($prefDataObj, $move_to_font=false, $verbosityLevel=VNag::VERBOSITY_SUMMARY) { $this->checkInitialized(); if ((!isset($this->argVerbosity)) && ($verbosityLevel > VNag::VERBOSITY_SUMMARY)) throw new VNagRequiredArgumentNotRegistered('-v'); if (self::getVerbosityLevel() < $verbosityLevel) return false; if ($move_to_font) { array_unshift($this->performanceDataObjects, $prefDataObj); } else { $this->performanceDataObjects[] = $prefDataObj; } return true; } public function getPerformanceData() { $this->checkInitialized(); return $this->performanceDataObjects; } public function removePerformanceData($prefDataObj) { if (($key = array_search($prefDataObj, $this->performanceDataObjects, true)) !== false) { unset($this->performanceDataObjects[$key]); return true; } else { return false; } } public function clearPerformanceData() { $this->performanceDataObjects = array(); } public function getVerboseInfo() { return $this->verbose_info; } public function clearVerboseInfo() { $this->verbose_info = ''; } private function writeVisualHTML($special_content=null) { if (!_empty($special_content)) { $content = $special_content; } else { $content = strtoupper(VNagLang::$status.': '.VNagLang::status($this->status, $this->statusmodel))."\n\n"; $content .= strtoupper(VNagLang::$message).":\n"; $status_text = VNagLang::status($this->status, $this->statusmodel); if (_empty($this->getHeadline())) { $content .= $status_text; } else { if ($this->show_status_in_headline) { $content .= $status_text.': '.trim($this->getHeadline()); } else { $content .= trim($this->getHeadline()); } } $content .= "\n\n"; if (!_empty($this->verbose_info)) { $content .= strtoupper(VNagLang::$verbose_info).":\n".trim($this->verbose_info)."\n\n"; } $perfdata = $this->getPerformanceData(); if (count($perfdata) > 0) { $content .= strtoupper(VNagLang::$performance_data).":\n"; foreach ($perfdata as $pd) { $content .= trim($pd)."\n"; } $content .= "\n"; } } $colorinfo = ''; $status = $this->getStatus(); if ($status == VNag::STATUS_OK) $colorinfo = ' style="background-color:green;color:white;font-weight:bold"'; else if ($status == VNag::STATUS_WARNING) $colorinfo = ' style="background-color:yellow;color:black;font-weight:bold"'; else if ($status == VNag::STATUS_CRITICAL) $colorinfo = ' style="background-color:red;color:white;font-weight:bold"'; else if ($status == VNag::STATUS_ERROR) $colorinfo = ' style="background-color:purple;color:white;font-weight:bold"'; else $colorinfo = ' style="background-color:lightgray;color:black;font-weight:bold"'; $html_content = trim($content); $html_content = htmlentities($html_content); $html_content = str_replace(' ', '&nbsp;', $html_content); $html_content = nl2br($html_content); return '<table border="1" cellspacing="2" cellpadding="2" style="width:100%" class="vnag_table">'. '<tr'.$colorinfo.' class="vnag_title_row">'. '<td>'.VNagLang::$nagios_output.'</td>'. '</tr>'. '<tr class="vnag_message_row">'. '<td><code>'. $html_content. '</code></td>'. '</tr>'. '</table>'; } protected function readInvisibleHTML($html) { $this->checkInitialized(); $doc = new DOMDocument(); @$doc->loadHTML($html); $tags = $doc->getElementsByTagName('script'); foreach ($tags as $tag) { $type = $tag->getAttribute('type'); if ($type !== 'application/json') continue; $json = $tag->nodeValue; if (!$json) continue; $data = @json_decode($json,true); if (!is_array($data)) continue; if (!isset($data['type'])) continue; if ($data['type'] === VNAG_JSONDATA_V1) { if (!isset($data['datasets'])) throw new VNagWebInfoException(VNagLang::$dataset_missing); foreach ($data['datasets'] as $dataset) { $payload = base64_decode($dataset['payload']); if (!$payload) { throw new VNagWebInfoException(VNagLang::$payload_not_base64); } if (isset($dataset['encryption'])) { $cryptInfo = $dataset['encryption']; if (!is_array($cryptInfo)) { throw new VNagWebInfoException(VNagLang::$dataset_encryption_no_array); } $password = is_null($this->password_in) ? '' : $this->password_in; $salt = base64_decode($cryptInfo['salt']); if ($cryptInfo['hash'] != hash('sha256',$salt.$password)) { if ($password == '') { throw new VNagWebInfoException(VNagLang::$require_password); } else { throw new VNagWebInfoException(VNagLang::$wrong_password); } } if (!function_exists('openssl_decrypt')) { throw new VNagException(VNagLang::$openssl_missing); } $payload = openssl_decrypt($payload, $cryptInfo['method'], $password, 0, $cryptInfo['iv']); } if (!is_null($this->pubkey) && ($this->pubkey !== '')) { if (substr($this->pubkey,0,3) === '---') { $public_key = $this->pubkey; } else { if (!file_exists($this->pubkey)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$pubkey_file_not_found, $this->pubkey)); } $public_key = @file_get_contents($this->pubkey); if (!$public_key) { throw new VNagPublicKeyException(sprintf(VNagLang::$pubkey_file_not_readable, $this->pubkey)); } } if (!isset($dataset['signature'])) { throw new VNagSignatureException(VNagLang::$signature_missing); } $signature = base64_decode($dataset['signature']); if (!$signature) { throw new VNagSignatureException(VNagLang::$signature_not_bas64); } if (!function_exists('openssl_verify')) { throw new VNagException(VNagLang::$openssl_missing); } $sign_algo = is_null($this->sign_algo) ? OPENSSL_ALGO_SHA256 : $this->sign_algo; if (!openssl_verify($payload, $signature, $public_key, $sign_algo)) { throw new VNagSignatureException(VNagLang::$signature_invalid); } } $payload = @json_decode($payload,true); if (!$payload) { throw new VNagWebInfoException(VNagLang::$payload_not_json); } if ($payload['id'] == $this->id) { return $payload; } } } } return null; } private function getNextMonitorID($peek=false) { $result = is_null($this->id) ? self::$http_serial_number : $this->id; if (!$peek) { $this->id = null; self::$http_serial_number++; } return $result; } private function writeInvisibleHTML($special_content=null) { $payload['id'] = $this->getNextMonitorID(); $payload['status'] = $this->getStatus(); if (!_empty($special_content)) { $payload['text'] = $special_content; } else { $payload['headline'] = $this->getHeadline(); $payload['verbose_info'] = $this->verbose_info; $payload['performance_data'] = array(); foreach ($this->performanceDataObjects as $perfdata) { $payload['performance_data'][] = (string)$perfdata; } } $payload = json_encode($payload); $dataset = array(); if (!is_null($this->privkey) && ($this->privkey !== '')) { if (!function_exists('openssl_pkey_get_private') || !function_exists('openssl_sign')) { throw new VNagException(VNagLang::$openssl_missing); } if (substr($this->privkey,0,3) === '---') { $pkeyid = @openssl_pkey_get_private($this->privkey, $this->privkey_password); if (!$pkeyid) { throw new VNagPrivateKeyException(sprintf(VNagLang::$privkey_not_readable)); } } else { if (!file_exists($this->privkey)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$privkey_file_not_found, $this->privkey)); } $pkeyid = @openssl_pkey_get_private('file://'.$this->privkey, $this->privkey_password); if (!$pkeyid) { throw new VNagPrivateKeyException(sprintf(VNagLang::$privkey_file_not_readable, $this->privkey)); } } $signature = ''; $sign_algo = is_null($this->sign_algo) ? OPENSSL_ALGO_SHA256 : $this->sign_algo; if (@openssl_sign($payload, $signature, $pkeyid, $sign_algo)) { if (version_compare(PHP_VERSION, '8.0.0') < 0) { openssl_free_key($pkeyid); } $dataset['signature'] = base64_encode($signature); } else { throw new VNagPrivateKeyException(sprintf(VNagLang::$signature_failed)); } } if (!is_null($this->password_out) && ($this->password_out !== '')) { if (!function_exists('openssl_encrypt')) { throw new VNagException(VNagLang::$openssl_missing); } $password = $this->password_out; $method = 'aes-256-ofb'; $iv = substr(hash('sha256', openssl_random_pseudo_bytes(32)), 0, 16); $salt = openssl_random_pseudo_bytes(32); $cryptInfo = array(); $cryptInfo['method'] = $method; $cryptInfo['iv'] = $iv; $cryptInfo['salt'] = base64_encode($salt); $cryptInfo['hash'] = hash('sha256', $salt.$password); $payload = openssl_encrypt($payload, $method, $password, 0, $iv); $dataset['encryption'] = $cryptInfo; } $dataset['payload'] = base64_encode($payload); $json = array(); $json['type'] = VNAG_JSONDATA_V1; $json['datasets'] = array($dataset); return '<script type="application/json">'. json_encode($json). '</script>'; } protected function appendHeadline($msg) { $this->checkInitialized(); if (_empty($msg)) return false; $this->messages[] = $msg; return true; } protected function changeHeadline($msg) { $this->checkInitialized(); if (_empty($msg)) { $this->messages = array(); } else { $this->messages = array($msg); } return true; } public function setHeadline($msg, $append=false, $verbosityLevel=VNag::VERBOSITY_SUMMARY) { $this->checkInitialized(); if ((!isset($this->argVerbosity)) && ($verbosityLevel > VNag::VERBOSITY_SUMMARY)) throw new VNagRequiredArgumentNotRegistered('-v'); if (self::getVerbosityLevel() < $verbosityLevel) $msg = ''; if ($append) { return $this->appendHeadline($msg); } else { return $this->changeHeadline($msg); } } public function getHeadline() { $this->checkInitialized(); return implode(', ', $this->messages); } public function addVerboseMessage($msg, $verbosityLevel=VNag::VERBOSITY_SUMMARY) { $this->checkInitialized(); if (self::getVerbosityLevel() >= $verbosityLevel) { $this->verbose_info .= $msg."\n"; } } public function setStatus($status, $force=false) { $this->checkInitialized(); if (($force) || is_null($this->status) || ($status > $this->status)) { $this->status = $status; } } public function getStatus() { $this->checkInitialized(); return $this->status; } protected static function exceptionText($exception) { $class = get_class($exception); $msg = $exception->getMessage(); if (!_empty($msg)) { return sprintf(VNagLang::$exception_x, $msg, $class); } else { return sprintf(VNagLang::$unhandled_exception_without_msg, $class); } } protected function handleException($exception) { $this->checkInitialized(); if (!VNag::is_http_mode()) { while (ob_get_level() > 0) @ob_end_clean(); } $this->clearVerboseInfo(); $this->clearPerformanceData(); if ($exception instanceof VNagException) { $this->setStatus($exception->getStatus()); } else { $this->setStatus(self::STATUS_ERROR); } $this->setHeadline($this->exceptionText($exception), false); if ($exception instanceof VNagImplementationErrorException) { $this->addVerboseMessage($exception->getTraceAsString(), VNag::VERBOSITY_SUMMARY); } else { if (isset($this->argVerbosity)) { $this->addVerboseMessage($exception->getTraceAsString(), VNag::VERBOSITY_ADDITIONAL_INFORMATION); } else { } } } protected function get_cache_dir() { $homedir = @getenv('HOME'); if ($homedir && is_dir($homedir)) { $try = "$homedir/.vnag/cache"; if (is_dir($try)) return $try; if (@mkdir($try,0777,true)) return $try; } $user = posix_getpwuid(posix_geteuid()); if (isset($user['dir']) && is_dir($user['dir'])) { $homedir = $user['dir']; $try = "$homedir/.vnag/cache"; if (is_dir($try)) return $try; if (@mkdir($try,0777,true)) return $try; } if (isset($user['name']) && is_dir($user['name'])) { $username = $user['name']; $try = "/tmp/vnag/cache"; if (is_dir($try)) return $try; if (@mkdir($try,0777,true)) return $try; } throw new VNagException("Cannot get cache dir"); } protected function url_get_contents($url, $max_cache_time=1*60*60, $context=null) { $cache_file = $this->get_cache_dir().'/'.hash('sha256',$url); if (file_exists($cache_file) && (time()-filemtime($cache_file) < $max_cache_time)) { $cont = @file_get_contents($cache_file); if ($cont === false) throw new Exception("Failed to get contents from $cache_file"); } else { $options = array( 'http'=>array( 'method'=>"GET", 'header'=>"Accept-language: en\r\n" . "User-Agent: Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B334b Safari/531.21.102011-10-16 20:23:10\r\n" ) ); if (is_null($context)) $context = stream_context_create($options); $cont = @file_get_contents($url, false, $context); if ($cont === false) throw new Exception("Failed to get contents from $url"); file_put_contents($cache_file, $cont); } return $cont; } } class VNagException extends Exception { public function getStatus() { return VNag::STATUS_ERROR; } } class VNagTimeoutException extends VNagException {} class VNagWebInfoException extends VNagException {} class VNagSignatureException extends VNagException {} class VNagPublicKeyException extends VNagException {} class VNagPrivateKeyException extends VNagException {} class VNagInvalidArgumentException extends VNagException { public function getStatus() { return VNag::STATUS_UNKNOWN; } } class VNagValueUomPairSyntaxException extends VNagInvalidArgumentException { public function __construct($str) { $e_msg = sprintf(VNagLang::$valueUomPairSyntaxError, $str); parent::__construct($e_msg); } } class VNagInvalidTimeoutException extends VNagInvalidArgumentException {} class VNagInvalidRangeException extends VNagInvalidArgumentException { public function __construct($msg) { $e_msg = VNagLang::$range_is_invalid; if (!_empty($msg)) $e_msg .= ': '.trim($msg); parent::__construct($e_msg); } } class VNagInvalidShortOpt extends VNagImplementationErrorException {} class VNagInvalidLongOpt extends VNagImplementationErrorException {} class VNagInvalidValuePolicy extends VNagImplementationErrorException {} class VNagIllegalStatusModel extends VNagImplementationErrorException {} class VNagNotConstructed extends VNagImplementationErrorException {} class VNagImplementationErrorException extends VNagException {} class VNagInvalidStandardArgument extends VNagImplementationErrorException {} class VNagFunctionCallOutsideSession extends VNagImplementationErrorException {} class VNagIllegalArgumentValuesException extends VNagImplementationErrorException {} class VNagRequiredArgumentNotRegistered extends VNagImplementationErrorException { public function __construct($required_argument) { $e_msg = sprintf(VNagLang::$query_without_expected_argument, $required_argument); parent::__construct($e_msg); } } class VNagRequiredArgumentMissing extends VNagInvalidArgumentException { public function __construct($required_argument) { $e_msg = sprintf(VNagLang::$required_argument_missing, $required_argument); parent::__construct($e_msg); } } class VNagUnknownUomException extends VNagInvalidArgumentException { public function __construct($uom) { $e_msg = sprintf(VNagLang::$perfdata_uom_not_recognized, $uom); parent::__construct($e_msg); } } class VNagNoCompatibleRangeUomFoundException extends VNagException {} class VNagMixedUomsNotImplemented extends VNagInvalidArgumentException { public function __construct($uom1, $uom2) { if (_empty($uom1)) $uom1 = VNagLang::$none; if (_empty($uom2)) $uom2 = VNagLang::$none; $e_msg = sprintf(VNagLang::$perfdata_mixed_uom_not_implemented, $uom1, $uom2); parent::__construct($e_msg); } } class VNagUomConvertException extends VNagInvalidArgumentException { public function __construct($uom1, $uom2) { if (_empty($uom1)) $uom1 = VNagLang::$none; if (_empty($uom2)) $uom2 = VNagLang::$none; $e_msg = sprintf(VNagLang::$convert_x_y_error, $uom1, $uom2); parent::__construct($e_msg); } } class VNagInvalidPerformanceDataException extends VNagInvalidArgumentException { public function __construct($msg) { $e_msg = VNagLang::$performance_data_invalid; if (!_empty($msg)) $e_msg .= ': '.trim($msg); parent::__construct($e_msg); } } class Timeouter { private static $start_time = false; private static $timeout; private static $fired = false; private static $registered = false; private function __construct() { } public static function start($timeout) { if (!is_numeric($timeout) || ($timeout <= 0)) { throw new VNagInvalidTimeoutException(sprintf(VNagLang::$timeout_value_invalid, $timeout)); } self::$start_time = microtime(true); self::$timeout = (float) $timeout; self::$fired = false; if (!self::$registered) { self::$registered = true; register_tick_function(array('Timeouter', 'tick')); } } public static function started() { return self::$registered; } public static function end() { if (self::$registered) { unregister_tick_function(array('Timeouter', 'tick')); self::$registered = false; } } public static function tick() { if ((!self::$fired) && ((microtime(true) - self::$start_time) > self::$timeout)) { self::$fired = true; throw new VNagTimeoutException(VNagLang::$timeout_exception); } } } class VNagArgument { const VALUE_FORBIDDEN = 0; const VALUE_REQUIRED = 1; const VALUE_OPTIONAL = 2; protected $shortopt; protected $longopts; protected $valuePolicy; protected $valueName; protected $helpText; protected $defaultValue = null; protected static $all_short = ''; protected static $all_long = array(); public function getShortOpt() { return $this->shortopt; } public function getLongOpts() { return $this->longopts; } public function getValuePolicy() { return $this->valuePolicy; } public function getValueName() { return $this->valueName; } public function getHelpText() { return $this->helpText; } static private function validateShortOpt($shortopt) { $m = array(); return preg_match('@^[a-zA-Z0-9\\+\\-\\?]$@', $shortopt, $m); } static private function validateLongOpt($longopt) { $m = array(); return preg_match('@^[a-zA-Z0-9\\+\\-\\?]+$@', $longopt, $m); } public function __construct($shortopt, $longopts, $valuePolicy, $valueName, $helpText, $defaultValue=null) { switch ($valuePolicy) { case VNagArgument::VALUE_FORBIDDEN: if (!_empty($valueName)) { throw new VNagImplementationErrorException(sprintf(VNagLang::$value_name_forbidden)); } break; case VNagArgument::VALUE_REQUIRED: if (_empty($valueName)) { throw new VNagImplementationErrorException(sprintf(VNagLang::$value_name_required)); } break; case VNagArgument::VALUE_OPTIONAL: if (_empty($valueName)) { throw new VNagImplementationErrorException(sprintf(VNagLang::$value_name_required)); } break; default: throw new VNagInvalidValuePolicy(sprintf(VNagLang::$illegal_valuepolicy, $valuePolicy)); } if (!_empty($shortopt)) { if (!self::validateShortOpt($shortopt)) { throw new VNagInvalidShortOpt(sprintf(VNagLang::$illegal_shortopt, $shortopt)); } } if (is_array($longopts)) { foreach ($longopts as $longopt) { if (!self::validateLongOpt($longopt)) { throw new VNagInvalidLongOpt(sprintf(VNagLang::$illegal_longopt, $longopt)); } } } else if (!_empty($longopts)) { if (!self::validateLongOpt($longopts)) { throw new VNagInvalidLongOpt(sprintf(VNagLang::$illegal_longopt, $longopts)); } $longopts = array($longopts); } else { $longopts = array(); } switch ($valuePolicy) { case VNagArgument::VALUE_FORBIDDEN: $policyApdx = ''; break; case VNagArgument::VALUE_REQUIRED: $policyApdx = ':'; break; case VNagArgument::VALUE_OPTIONAL: $policyApdx = '::'; break; default: throw new VNagInvalidValuePolicy(sprintf(VNagLang::$illegal_valuepolicy, $valuePolicy)); } if ((!is_null($shortopt)) && ($shortopt != '?')) self::$all_short .= $shortopt.$policyApdx; if (is_array($longopts)) { foreach ($longopts as $longopt) { self::$all_long[] = $longopt.$policyApdx; } } $this->shortopt = $shortopt; $this->longopts = $longopts; $this->valuePolicy = $valuePolicy; $this->valueName = $valueName; $this->helpText = $helpText; $this->defaultValue = $defaultValue; } protected static function getOptions() { global $OVERWRITE_ARGUMENTS; if (!is_null($OVERWRITE_ARGUMENTS)) { return $OVERWRITE_ARGUMENTS; } else if (VNag::is_http_mode()) { return $_REQUEST; } else { return getopt(self::$all_short, self::$all_long); } } public function count() { $options = self::getOptions(); $count = 0; if (isset($options[$this->shortopt])) { if (is_array($options[$this->shortopt])) { $count += count($options[$this->shortopt]); } else { $count += 1; } } if (!is_null($this->longopts)) { foreach ($this->longopts as $longopt) { if (isset($options[$longopt])) { if (is_array($options[$longopt])) { $count += count($options[$longopt]); } else { $count += 1; } } } } return $count; } public function available() { $options = self::getOptions(); if (isset($options[$this->shortopt])) return true; if (!is_null($this->longopts)) { foreach ($this->longopts as $longopt) { if (isset($options[$longopt])) return true; } } return false; } public function require() { if (!$this->available() && is_null($this->defaultValue)) { $opt = $this->shortopt; $opt = !_empty($opt) ? '-'.$opt : (isset($this->longopts[0]) ? '--'.$this->longopts[0] : '?'); throw new VNagRequiredArgumentMissing($opt); } } public function getValue() { $options = self::getOptions(); if (isset($options[$this->shortopt])) { $x = $options[$this->shortopt]; if (is_array($x) && (count($x) <= 1)) $options[$this->shortopt] = $options[$this->shortopt][0]; return $options[$this->shortopt]; } if (!is_null($this->longopts)) { foreach ($this->longopts as $longopt) { if (isset($options[$longopt])) { $x = $options[$longopt]; if (is_array($x) && (count($x) <= 1)) $options[$longopt] = $options[$longopt][0]; return $options[$longopt]; } } } return $this->defaultValue; } } class VNagArgumentHandler { protected $expectedArgs = array(); protected function _addExpectedArgument($argObj) { if ($argObj->getShortOpt() == '?') return false; if ($argObj->getShortOpt() == '-') return false; if ($argObj->getShortOpt() == '+') return false; $this->expectedArgs[] = $argObj; return true; } public function getArgumentObj($shortopt) { foreach ($this->expectedArgs as $argObj) { if ($argObj->getShortOpt() == $shortopt) return $argObj; } return null; } public function isArgRegistered($shortopt) { return !is_null($this->getArgumentObj($shortopt)); } public function illegalUsage() { global $argv; return (isset($argv[1])) && (($argv[1] == '-?') || ($argv[1] == '/?')); } } class VNagRange { public $start; public $end; public $warnInsideRange; public function __construct($rangeDef, $singleValueBehavior=VNag::SINGLEVALUE_RANGE_DEFAULT) { $m = array(); if (!preg_match('|^(@){0,1}([^:]+)(:){0,1}(.*)$|', $rangeDef, $m)) { throw new VNagInvalidRangeException(sprintf(VNagLang::$range_invalid_syntax, $rangeDef)); } $this->warnInsideRange = $m[1] === '@'; $this->start = null; $this->end = null; if ($m[3] === ':') { if ($m[2] === '~') { $this->start = '-inf'; } else { $this->start = new VNagValueUomPair($m[2]); } if (_empty($m[4])) { $this->end = 'inf'; } else { $this->end = new VNagValueUomPair($m[4]); } } else { assert(_empty($m[4])); assert(!_empty($m[2])); $x = $m[2]; if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_DEFAULT) { $this->start = new VNagValueUomPair('0'.((new VNagValueUomPair($x))->getUom())); $this->end = new VNagValueUomPair($x); } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_GT_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 0; $this->start = '-inf'; $this->end = new VNagValueUomPair($x); } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_GE_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 1; $this->start = new VNagValueUomPair($x); $this->end = 'inf'; } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_LT_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 0; $this->start = new VNagValueUomPair($x); $this->end = 'inf'; } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_LE_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 1; $this->start = '-inf'; $this->end = new VNagValueUomPair($x); } else { throw new VNagException(VNagLang::$illegalSingleValueBehavior); } } if (is_null($this->start)) { throw new VNagInvalidRangeException(VNagLang::$invalid_start_value); } if (is_null($this->end)) { throw new VNagInvalidRangeException(VNagLang::$invalid_end_value); } if (($this->start instanceof VNagValueUomPair) && ($this->end instanceof VNagValueUomPair) && (VNagValueUomPair::compare($this->start,$this->end) > 0)) { throw new VNagInvalidRangeException(VNagLang::$start_is_greater_than_end); } } public function __toString() { $ret = ''; if ($this->warnInsideRange) { $ret = '@'; } if ($this->start === '-inf') { $ret .= '~'; } else { $ret .= $this->start; } $ret .= ':'; if ($this->end !== 'inf') { $ret .= $this->end; } return $ret; } public function checkAlert($values) { $compatibleCount = 0; if (!is_array($values)) $values = array($values); foreach ($values as $value) { if (!($value instanceof VNagValueUomPair)) $value = new VNagValueUomPair($value); assert(($this->start === '-inf') || ($this->start instanceof VNagValueUomPair)); assert(($this->end === 'inf' ) || ($this->end instanceof VNagValueUomPair)); if (($this->start !== '-inf') && (!$this->start->compatibleWith($value))) continue; if (($this->end !== 'inf') && (!$this->end->compatibleWith($value))) continue; $compatibleCount++; if ($this->warnInsideRange) { return (($this->start === '-inf') || (VNagValueUomPair::compare($value,$this->start) >= 0)) && (($this->end === 'inf') || (VNagValueUomPair::compare($value,$this->end) <= 0)); } else { return (($this->start !== '-inf') && (VNagValueUomPair::compare($value,$this->start) < 0)) || (($this->end !== 'inf') && (VNagValueUomPair::compare($value,$this->end) > 0)); } } if ((count($values) > 0) and ($compatibleCount == 0)) { throw new VNagNoCompatibleRangeUomFoundException(VNagLang::$no_compatible_range_uom_found); } return false; } } class VNagValueUomPair { protected $value; protected $uom; public $roundTo = -1; public function isRelative() { return $this->uom === '%'; } public function getValue() { return $this->value; } public function getUom() { return $this->uom; } public function __toString() { if ($this->roundTo == -1) { return $this->value.$this->uom; } else { return round($this->value,$this->roundTo).$this->uom; } } public function __construct($str) { $m = array(); if (!preg_match('/^([\d\.]+)(.*)$/ism', $str, $m)) { throw new VNagValueUomPairSyntaxException($str); } $this->value = $m[1]; $this->uom = isset($m[2]) ? $m[2] : ''; if (!self::isKnownUOM($this->uom)) { throw new VNagUnknownUomException($this->uom); } } public static function isKnownUOM(string $uom) { $no_unit = ($uom === ''); $seconds = ($uom === 's') || ($uom === 'ms') || ($uom === 'us'); $percentage = ($uom === '%'); $bytes = ($uom === 'B') || ($uom === 'KB') || ($uom === 'MB') || ($uom === 'GB') || ($uom === 'TB'); $counter = ($uom === 'c'); return ($no_unit || $seconds || $percentage || $bytes || $counter); } public function normalize($target=null) { $res = clone $this; if ($res->uom === 'ms') { $res->uom = 's'; $res->value /= 1000; } if ($res->uom === 'us') { $res->uom = 's'; $res->value /= 1000 * 1000; } if ($res->uom === 'B') { $res->uom = 'MB'; $res->value /= 1024 * 1024; } if ($res->uom === 'KB') { $res->uom = 'MB'; $res->value /= 1024; } if ($res->uom === 'GB') { $res->uom = 'MB'; $res->value *= 1024; } if ($res->uom === 'TB') { $res->uom = 'MB'; $res->value *= 1024 * 1024; } if ($res->uom === 'c') { $res->uom = ''; } if (!is_null($target)) { if ($res->uom == 'MB') { if ($target == 'B') { $res->uom = 'B'; $res->value *= 1024 * 1024; } else if ($target == 'KB') { $res->uom = 'KB'; $res->value *= 1024; } else if ($target == 'MB') { $res->uom = 'MB'; $res->value *= 1; } else if ($target == 'GB') { $res->uom = 'GB'; $res->value /= 1024; } else if ($target == 'TB') { $res->uom = 'TB'; $res->value /= 1024 * 1024; } else { throw new VNagUomConvertException($res->uom, $target); } } else if ($res->uom == 's') { if ($target == 's') { $res->uom = 's'; $res->value /= 1; } else if ($target == 'ms') { $res->uom = 'ms'; $res->value /= 1000; } else if ($target == 'us') { $res->uom = 'us'; $res->value /= 1000 * 1000; } else { throw new VNagUomConvertException($res->uom, $target); } } else { throw new VNagUomConvertException($res->uom, $target); } } return $res; } public function compatibleWith(VNagValueUomPair $other) { $a = $this->normalize(); $b = $other->normalize(); return ($a->uom == $b->uom); } public static function compare(VNagValueUomPair $left, VNagValueUomPair $right) { $a = $left->normalize(); $b = $right->normalize(); if ($a->uom != $b->uom) throw new VNagMixedUomsNotImplemented($a->uom, $b->uom); if ($a->value > $b->value) return 1; if ($a->value == $b->value) return 0; if ($a->value < $b->value) return -1; } } class VNagPerformanceData { protected $label; protected $value; protected $warn = null; protected $crit = null; protected $min = null; protected $max = null; public static function createByString($perfdata) { $perfdata = trim($perfdata); $ary = explode('=',$perfdata); if (count($ary) != 2) { throw new VNagInvalidPerformanceDataException(sprintf(VNagLang::$perfdata_line_invalid, $perfdata)); } $label = $ary[0]; $bry = explode(';',$ary[1]); if (substr($label,0,1) === "'") $label = substr($label, 1, strlen($label)-2); $value = $bry[0]; $warn = isset($bry[1]) ? $bry[1] : null; $crit = isset($bry[2]) ? $bry[2] : null; $min = isset($bry[3]) ? $bry[3] : null; $max = isset($bry[4]) ? $bry[4] : null; return new self($label, $value, $warn, $crit, $min, $max); } public function __construct($label, $value, $warn=null, $crit=null, $min=null, $max=null) { if (strpos($label, '=') !== false) throw new VNagInvalidPerformanceDataException(VNagLang::$perfdata_label_equal_sign_forbidden); $label = str_replace("'", "''", $label); $m = array(); if ((!_empty($min)) && (!preg_match('|^[-0-9\\.]+$|', $min, $m))) { throw new VNagInvalidPerformanceDataException(VNagLang::$perfdata_min_must_be_in_class); } if ((!_empty($max)) && (!preg_match('|^[-0-9\\.]+$|', $max, $m))) { throw new VNagInvalidPerformanceDataException(VNagLang::$perfdata_max_must_be_in_class); } $this->label = $label; $this->value = ($value == 'U') ? 'U' : new VNagValueUomPair($value); $this->warn = $warn; $this->crit = $crit; $this->min = $min; $this->max = $max; } public function __toString() { $label = $this->label; $value = $this->value; $warn = $this->warn; $crit = $this->crit; $min = $this->min; $max = $this->max; $label = str_replace("''", "'", $label); return "'$label'=$value". ';'.(is_null($warn) ? '' : $warn). ';'.(is_null($crit) ? '' : $crit). ';'.(is_null($min) ? '' : $min). ';'.(is_null($max) ? '' : $max); } } class VNagHelp { public $word_wrap_width = 80; public $argument_indent = 7; public function printUsagePage() { $usage = $this->getUsage(); if (_empty($usage)) { $usage = VNagLang::$no_syntax_defined; } return trim($usage)."\n"; } public function printVersionPage() { $out = trim($this->getNameAndVersion())."\n"; if ($this->word_wrap_width > 0) $out = wordwrap($out, $this->word_wrap_width, "\n", false); return $out; } static private function _conditionalLine($line, $terminator='', $prefix='') { if (!_empty($line)) { return trim($line).$terminator; } return ''; } public function printHelpPage() { $out = ''; $out .= self::_conditionalLine($this->getNameAndVersion(), "\n"); $out .= self::_conditionalLine($this->getCopyright(), "\n"); $out .= ($out != '') ? "\n" : ''; $out .= self::_conditionalLine($this->getShortDescription(), "\n\n\n"); $out .= self::_conditionalLine($this->getUsage(), "\n\n"); $out .= VNagLang::$options."\n"; foreach ($this->options as $argObj) { $out .= $this->printArgumentHelp($argObj); } $out .= self::_conditionalLine($this->getFootNotes(), "\n\n", "\n"); if ($this->word_wrap_width > 0) $out = wordwrap($out, $this->word_wrap_width, "\n", false); return $out; } protected $options = array(); protected function _addOption($argObj) { $this->options[] = $argObj; } protected function printArgumentHelp($argObj) { $identifiers = array(); $shortopt = $argObj->getShortopt(); if (!_empty($shortopt)) $identifiers[] = '-'.$shortopt; $longopts = $argObj->getLongopts(); if (!is_null($longopts)) { foreach ($longopts as $longopt) { if (!_empty($longopt)) $identifiers[] = '--'.$longopt; } } if (count($identifiers) == 0) return; $valueName = $argObj->getValueName(); $arginfo = ''; switch ($argObj->getValuePolicy()) { case VNagArgument::VALUE_FORBIDDEN: $arginfo = ''; break; case VNagArgument::VALUE_REQUIRED: $arginfo = '='.$valueName; break; case VNagArgument::VALUE_OPTIONAL: $arginfo = '[='.$valueName.']'; break; } $out = ''; $out .= implode(', ', $identifiers).$arginfo."\n"; $content = trim($argObj->getHelpText()); if ($this->word_wrap_width > 0) $content = wordwrap($content, $this->word_wrap_width-$this->argument_indent, "\n", false); $lines = explode("\n", $content); foreach ($lines as $line) { $out .= str_repeat(' ', $this->argument_indent).$line."\n"; } $out .= "\n"; return $out; } protected $pluginName; public function setPluginName($pluginName) { $this->pluginName = $this->replaceStuff($pluginName); } public function getPluginName() { if (_empty($this->pluginName)) { global $argv; return basename($argv[0]); } else { return $this->pluginName; } } protected $version; public function setVersion($version) { $this->version = $this->replaceStuff($version); } public function getVersion() { return $this->version; } public function getNameAndVersion() { $ret = $this->getPluginName(); if (_empty($ret)) return null; $ver = $this->getVersion(); if (!_empty($ver)) { $ret = sprintf(VNagLang::$x_version_x, $ret, $ver); } $ret = trim($ret); return $ret; } protected $copyright; public function setCopyright($copyright) { $this->copyright = $this->replaceStuff($copyright); } private function getVNagCopyright() { if (VNag::is_http_mode()) { $vts_email = 'www.viathinksoft.com'; } else { $vts_email = base64_decode('aW5mb0B2aWF0aGlua3NvZnQuZGU='); } return "VNag Framework ".VNag::VNAG_VERSION." (C) 2014-".date('Y')." ViaThinkSoft <$vts_email>"; } public function getCopyright() { if (_empty($this->copyright)) { return sprintf(VNagLang::$plugin_uses, $this->getVNagCopyright()); } else { return trim($this->copyright)."\n".sprintf(VNagLang::$uses, $this->getVNagCopyright()); } } protected $shortDescription; public function setShortDescription($shortDescription) { $this->shortDescription = $this->replaceStuff($shortDescription); } public function getShortDescription() { if (_empty($this->shortDescription)) { return null; } else { $content = $this->shortDescription; if ($this->word_wrap_width > 0) $content = wordwrap($content, $this->word_wrap_width, "\n", false); return $content; } } protected function replaceStuff($text) { global $argv; if (php_sapi_name() == 'cli') { $text = str_replace('$SCRIPTNAME$', $argv[0], $text); } else { $text = str_replace('$SCRIPTNAME$', basename($_SERVER['SCRIPT_NAME']), $text); } $text = str_replace('$CURYEAR$', date('Y'), $text); return $text; } protected $syntax; public function setSyntax($syntax) { $syntax = $this->replaceStuff($syntax); $this->syntax = $syntax; } public function getUsage() { if (_empty($this->syntax)) { return null; } else { return sprintf(VNagLang::$usage_x, $this->syntax); } } protected $footNotes; public function setFootNotes($footNotes) { $this->footNotes = $this->replaceStuff($footNotes); } public function getFootNotes() { return $this->footNotes; } } class VNagLang { public static function status($code, $statusmodel) { switch ($statusmodel) { case VNag::STATUSMODEL_SERVICE: switch ($code) { case VNag::STATUS_OK: return 'OK'; case VNag::STATUS_WARNING: return 'Warning'; case VNag::STATUS_CRITICAL: return 'Critical'; case VNag::STATUS_UNKNOWN: return 'Unknown'; default: return sprintf('Error (%d)', $code); } case VNag::STATUSMODEL_HOST: switch ($code) { case VNag::STATUS_UP: return 'Up'; case VNag::STATUS_DOWN: return 'Down'; default: return sprintf('Maintain last state (%d)', $code); } default: throw new VNagIllegalStatusModel(sprintf(self::$illegal_statusmodel, $statusmodel)); } } static $nagios_output = 'VNag-Output'; static $verbose_info = 'Verbose information'; static $status = 'Status'; static $message = 'Message'; static $performance_data = 'Performance data'; static $status_ok = 'OK'; static $status_warn = 'Warning'; static $status_critical = 'Critical'; static $status_unknown = 'Unknown'; static $status_error = 'Error'; static $unhandled_exception_without_msg = "Unhandled exception of type %s"; static $plugin_uses = 'This plugin uses %s'; static $uses = 'uses %s'; static $x_version_x = '%s, version %s'; static $argname_value = 'value'; static $argname_seconds = 'seconds'; static $query_without_expected_argument = "The argument '%s' is queried, but was not added to the list of expected arguments. Please contact the plugin author."; static $required_argument_missing = "The argument '%s' is required."; static $performance_data_invalid = 'Performance data invalid.'; static $no_standard_arguments_with_letter = "No standard argument with letter '%s' exists."; static $invalid_start_value = 'Invalid start value.'; static $invalid_end_value = 'Invalid end value.'; static $start_is_greater_than_end = 'Start is greater than end value.'; static $value_name_forbidden = "Implementation error: You may not define a value name for the argument, because the value policy is VALUE_FORBIDDEN."; static $value_name_required = "Implementation error: Please define a name for the argument (so it can be shown in the help page)."; static $illegal_shortopt = "Illegal shortopt '-%s'."; static $illegal_longopt = "Illegal longopt '--%s'."; static $illegal_valuepolicy = "valuePolicy has illegal value '%s'."; static $range_invalid_syntax = "Syntax error in range '%s'."; static $timeout_value_invalid = "Timeout value '%s' is invalid."; static $range_is_invalid = 'Range is invalid.'; static $timeout_exception = 'Timeout!'; static $perfdata_label_equal_sign_forbidden = 'Label may not contain an equal sign.'; static $perfdata_value_must_be_in_class = 'Value must be in class [-0-9.] or be \'U\' if the actual value can\'t be determined.'; static $perfdata_min_must_be_in_class = 'Min must be in class [-0-9.] or empty.'; static $perfdata_max_must_be_in_class = 'Max must be in class [-0-9.] or empty.'; static $perfdata_uom_not_recognized = 'UOM (unit of measurement) "%s" is not recognized.'; static $perfdata_mixed_uom_not_implemented = 'Mixed UOMs (%s and %s) are currently not supported.'; static $no_compatible_range_uom_found = 'Measured values are not compatible with the provided warning/critical parameter. Most likely, the UOM is incompatible.'; static $exception_x = '%s (%s)'; static $no_syntax_defined = 'The author of this plugin has not defined a syntax for this plugin.'; static $usage_x = "Usage:\n%s"; static $options = "Options:"; static $illegal_statusmodel = "Invalid statusmodel %d."; static $none = '[none]'; static $valueUomPairSyntaxError = 'Syntax error at "%s". Syntax must be Value[UOM].'; static $too_few_warning_ranges = "You have too few warning ranges (currently trying to get element %d)."; static $too_few_critical_ranges = "You have too few critical ranges (currently trying to get element %d)."; static $dataset_missing = 'Dataset missing.'; static $payload_not_base64 = 'The payload is not valid Base64.'; static $payload_not_json = 'The payload is not valid JSON.'; static $signature_missing = 'The signature is missing.'; static $signature_not_bas64 = 'The signature is not valid Base64.'; static $signature_invalid = 'The signature is invalid. The connection might have been tampered, or a different key is used.'; static $pubkey_file_not_found = "Public key file %s was not found."; static $pubkey_file_not_readable = "Public key file %s is not readable."; static $privkey_file_not_found = "Private key file %s was not found."; static $privkey_not_readable = "Private key is not readable."; static $privkey_file_not_readable = "Private key file %s is not readable."; static $signature_failed = "Signature failed."; static $perfdata_line_invalid = "Performance data line %s is invalid."; static $singlevalue_unexpected_at_symbol = 'This plugin does not allow the @-symbol at ranges for single values.'; static $illegalSingleValueBehavior = "Illegal value for 'singleValueBehavior'. Please contact the creator of the plugin."; static $dataset_encryption_no_array = 'Dataset encryption information invalid.'; static $require_password = 'This resource is protected with a password. Please provide a password.'; static $wrong_password = 'This resource is protected with a password. You have provided the wrong password, or it was changed.'; static $convert_x_y_error = 'Cannot convert from UOM %s to UOM %s.'; static $php_error = 'PHP has detected an error in the plugin. Please contact the plugin author.'; static $output_level_lowered = "Output Buffer level lowered during cbRun(). Please contact the plugin author."; static $openssl_missing = "OpenSSL is missing. Therefore, encryption and signatures are not available."; static $warning_range = 'Warning range'; static $critical_range = 'Critical range'; static $prints_version = 'Prints version'; static $verbosity_helptext = 'Verbosity -v, -vv or -vvv'; static $timeout_helptext = 'Sets timeout in seconds'; static $help_helptext = 'Prints help page'; static $prints_usage = 'Prints usage'; static $notConstructed = 'Parent constructor not called with parent::__construct().'; } function vnagErrorHandler($errorkind, $errortext, $file, $line) { global $inside_vnag_run; if (!$inside_vnag_run && VNag::is_http_mode()) { return false; } if (!(error_reporting() & $errorkind)) { return true; } if (defined('E_ERROR') && ($errorkind == E_ERROR)) $errorkind = 'Error'; if (defined('E_WARNING') && ($errorkind == E_WARNING)) $errorkind = 'Warning'; if (defined('E_PARSE') && ($errorkind == E_PARSE)) $errorkind = 'Parse'; if (defined('E_NOTICE') && ($errorkind == E_NOTICE)) $errorkind = 'Notice'; if (defined('E_CORE_ERROR') && ($errorkind == E_CORE_ERROR)) $errorkind = 'Core Error'; if (defined('E_CORE_WARNING') && ($errorkind == E_CORE_WARNING)) $errorkind = 'Core Warning'; if (defined('E_COMPILE_ERROR') && ($errorkind == E_COMPILE_ERROR)) $errorkind = 'Compile Error'; if (defined('E_COMPILE_WARNING') && ($errorkind == E_COMPILE_WARNING)) $errorkind = 'Compile Warning'; if (defined('E_USER_ERROR') && ($errorkind == E_USER_ERROR)) $errorkind = 'User Error'; if (defined('E_USER_WARNING') && ($errorkind == E_USER_WARNING)) $errorkind = 'User Warning'; if (defined('E_USER_NOTICE') && ($errorkind == E_USER_NOTICE)) $errorkind = 'User Notice'; if (defined('E_STRICT') && ($errorkind == E_STRICT)) $errorkind = 'Strict'; if (defined('E_RECOVERABLE_ERROR') && ($errorkind == E_RECOVERABLE_ERROR)) $errorkind = 'Recoverable Error'; if (defined('E_DEPRECATED') && ($errorkind == E_DEPRECATED)) $errorkind = 'Deprecated'; if (defined('E_USER_DEPRECATED') && ($errorkind == E_USER_DEPRECATED)) $errorkind = 'User Deprecated'; throw new VNagException(VNagLang::$php_error . " $errortext at $file:$line (kind $errorkind)"); } $inside_vnag_run = false; $old_error_handler = set_error_handler("vnagErrorHandler"); <?php
declare(ticks=1); class FileTimestampCheck extends VNag { protected $argFiles = null; public function __construct() { parent::__construct(); $this->registerExpectedStandardArguments('Vhtwcv'); $this->getHelpManager()->setPluginName('check_file_timestamp'); $this->getHelpManager()->setVersion('2023-10-13'); $this->getHelpManager()->setShortDescription('This plugin checks if local files are within a specific timestamp.'); $this->getHelpManager()->setCopyright('Copyright (C) 2011-$CURYEAR$ Daniel Marschall, ViaThinkSoft.'); $this->getHelpManager()->setSyntax('$SCRIPTNAME$ [-v] -w <warnSeconds>s -c <critSeconds>s -f "[#]<mask>" [-f "[#]<mask>" [...]]'); $this->getHelpManager()->setFootNotes('If you encounter bugs, please contact ViaThinkSoft at www.viathinksoft.com'); $this->addExpectedArgument($this->argFiles = new VNagArgument('f', 'file', VNagArgument::VALUE_REQUIRED, 'mask', 'The files to be checked. This argument can be used multiple times. Wilcards may be used but MUST be passed as string only (not resolved by the Shell). There are two possible checking modes: If you put a # in front of the file mask, only the youngest file of each group will be checked (use this mode e.g. if you want to check if a downloader is regularly downloading files into a download directory). Otherwise, all files of the file group are checked.')); } private static function humanFriendlyInterval($secs) { $out = array(); $years = floor($secs / 60 / 60 / 24 / 365); if ($years > 0) $out[] = $years == 1 ? "$years year" : "$years years"; $days = floor($secs / 60 / 60 / 24) % 365; if ($days > 0) $out[] = $days == 1 ? "$days day" : "$days days"; $hours = floor($secs / 60 / 60) % 24; if ($hours > 0) $out[] = $hours == 1 ? "$hours hour" : "$hours hours"; $minutes = floor($secs / 60) % 60; if ($minutes > 0) $out[] = $minutes == 1 ? "$minutes minute" : "$minutes minutes"; $seconds = $secs % 60; if ($seconds > 0) $out[] = $seconds == 1 ? "$seconds second" : "$seconds seconds"; return implode(", ", $out); } protected function cbRun($optional_args=array()) { $this->argFiles->require(); $countFilesTotal = 0; $countFilesCrit = 0; $countFilesWarn = 0; $fileGroupMasks = $this->argFiles->getValue(); if (!is_array($fileGroupMasks)) $fileGroupMasks = array($fileGroupMasks); foreach ($fileGroupMasks as $fileGroupMask) { if (substr($fileGroupMask, 0, 1) === '#') { $fileGroupMask = substr($fileGroupMask, 1); $files = glob($fileGroupMask); if (count($files) == 0) continue; $youngestTS = null; foreach ($files as $file) { $youngestTS = is_null($youngestTS) ? filemtime($file) : max($youngestTS, filemtime($file)); } $youngestAge = time() - $youngestTS; $countFilesTotal++; if ($this->checkAgainstCriticalRange($youngestAge.'s', false, true)) { $countFilesCrit++; $this->addVerboseMessage("File group '$fileGroupMask': Youngest file's age: ".self::humanFriendlyInterval($youngestAge)." (Critical)\n", VNag::VERBOSITY_SUMMARY); } else if ($this->checkAgainstWarningRange($youngestAge.'s', false, true)) { $countFilesWarn++; $this->addVerboseMessage("File group '$fileGroupMask': Youngest file's age: ".self::humanFriendlyInterval($youngestAge)." (Warning)\n", VNag::VERBOSITY_SUMMARY); } else { if (($this->getArgumentHandler()->getArgumentObj('w')->available()) || ($this->getArgumentHandler()->getArgumentObj('c')->available())) { $this->addVerboseMessage("File group '$fileGroupMask': Youngest file's age: ".self::humanFriendlyInterval($youngestAge)." (OK)\n", VNag::VERBOSITY_ADDITIONAL_INFORMATION); } else { $this->addVerboseMessage("File group '$fileGroupMask': Youngest file's age: ".self::humanFriendlyInterval($youngestAge)."\n", VNag::VERBOSITY_ADDITIONAL_INFORMATION); } } } else { $files = glob($fileGroupMask); if (count($files) == 0) continue; foreach ($files as $file) { $age = time() - filemtime($file); $countFilesTotal++; if ($this->checkAgainstCriticalRange($age.'s', false, true)) { $countFilesCrit++; $this->addVerboseMessage("File $file age ".self::humanFriendlyInterval($age)." (Critical)\n", VNag::VERBOSITY_SUMMARY); } else if ($this->checkAgainstWarningRange($age.'s', false, true)) { $countFilesWarn++; $this->addVerboseMessage("File $file age ".self::humanFriendlyInterval($age)." (Warning)\n", VNag::VERBOSITY_SUMMARY); } else { if (($this->getArgumentHandler()->getArgumentObj('w')->available()) || ($this->getArgumentHandler()->getArgumentObj('c')->available())) { $this->addVerboseMessage("File $file age ".self::humanFriendlyInterval($age)." (OK)\n", VNag::VERBOSITY_ADDITIONAL_INFORMATION); } else { $this->addVerboseMessage("File $file age ".self::humanFriendlyInterval($age)."\n", VNag::VERBOSITY_ADDITIONAL_INFORMATION); } } } } } $msg = array(); $msg[] = "Checked $countFilesTotal files"; if ($this->getArgumentHandler()->getArgumentObj('w')->available()) $msg[] = "$countFilesWarn are in warning time range"; if ($this->getArgumentHandler()->getArgumentObj('c')->available()) $msg[] = "$countFilesCrit are in critical time range"; $msg = implode(", ", $msg); $this->setHeadLine($msg); } } <?php
declare(ticks=1); require_once __DIR__ . '/../../framework/vnag_framework.inc.php'; require_once __DIR__ . '/FileTimestampCheck.class.php'; $job = new FileTimestampCheck(); $job->run(); unset($job); ^…›sÁ^ î+– õªø¥[“S•$ì`†ª~Ùá‹S$†(ž¼ûoöb)»’¥ßz÷/qÑÅܜ€#‰¤GBMB
declare(ticks=1); require_once __DIR__ . '/../../framework/vnag_framework.inc.php'; require_once __DIR__ . '/FileTimestampCheck.class.php'; $job = new FileTimestampCheck(); $job->run(); unset($job); r
†óiþo‡ÏiÓ}µkžKe•Nn ip7Ähj»j!çh¿(Of‘FŸR¢°)]©Ø ³™
c¦ˆ5€sGBMB
/trunk/bin/gitlab_version.phar
291,8 → 291,7
 
Extract_Phar::go();
__HALT_COMPILER(); ?>
k‚a:1:{s:23:"1.3.6.1.4.1.37476.3.0.2";s:340:"sha256||framework/vnag_framework.inc.php|460b109d1c578e9b6af41612e0312c9f36fd8beb51f7aa92f1b7bd49614568e8||plugins/gitlab_version/GitLabVersionCheck.class.php|c12acde22d038d69a21e4270ec6855fdea6a4362c7ec576b146c433d3650b21a||plugins/gitlab_version/check_gitlab_version.phps|2889c9eba27451db46ad604de24482dba4bd2f15e16878b37cfea8cea740ed18||";} framework/vnag_framework.inc.phpLÙyï*eLُ4p”¤3plugins/gitlab_version/GitLabVersionCheck.class.phpF yï*eF "o³*¤0plugins/gitlab_version/check_gitlab_version.phpsÎyï*eÎ;¬Í¤<?php ?>
<?php
·Îa:1:{s:23:"1.3.6.1.4.1.37476.3.0.2";s:416:"sha256||<builder>|481cf75d675006b504520fd2acb3b29c89aea03aab64754e0adfb364de4914b2||framework/vnag_framework.inc.php|0387bf3134f8cc2d1ae24e139019c0edef19c1ba5ca765624efea0b469c7897f||plugins/gitlab_version/GitLabVersionCheck.class.php|c12acde22d038d69a21e4270ec6855fdea6a4362c7ec576b146c433d3650b21a||plugins/gitlab_version/check_gitlab_version.phps|2889c9eba27451db46ad604de24482dba4bd2f15e16878b37cfea8cea740ed18||";} framework/vnag_framework.inc.phpBÙ» +eBÙÞß=¤3plugins/gitlab_version/GitLabVersionCheck.class.phpF » +eF "o³*¤0plugins/gitlab_version/check_gitlab_version.phpsλ +eÎ;¬Í¤<?php
if (!VNag::is_http_mode()) error_reporting(E_ALL); declare(ticks=1); set_time_limit(0); define('VNAG_JSONDATA_V1', 'oid:1.3.6.1.4.1.37476.2.3.1.1'); $OVERWRITE_ARGUMENTS = null; function _empty($x) { return is_null($x) || (trim($x) == ''); } abstract class VNag { const VNAG_VERSION = '2023-10-13'; const STATUS_OK = 0; const STATUS_WARNING = 1; const STATUS_CRITICAL = 2; const STATUS_UNKNOWN = 3; const STATUS_ERROR = 4; const STATUS_UP = 0; const STATUS_DOWN = 1; const STATUS_MAINTAIN = 2; const VERBOSITY_SUMMARY = 0; const VERBOSITY_ADDITIONAL_INFORMATION = 1; const VERBOSITY_CONFIGURATION_DEBUG = 2; const VERBOSITY_PLUGIN_DEBUG = 3; const MAX_VERBOSITY = self::VERBOSITY_PLUGIN_DEBUG; const STATUSMODEL_SERVICE = 0; const STATUSMODEL_HOST = 1; private $initialized = false; private $status = null; private $messages = array(); private $verbose_info = ''; private $warningRanges = array(); private $criticalRanges = array(); private $performanceDataObjects = array(); private static $exitcode = 0; private $helpObj = null; private $argHandler = null; const OUTPUT_NEVER = 0; const OUTPUT_SPECIAL = 1; const OUTPUT_NORMAL = 2; const OUTPUT_EXCEPTION = 4; const OUTPUT_ALWAYS = 7; public $http_visual_output = self::OUTPUT_ALWAYS; public $http_invisible_output = self::OUTPUT_ALWAYS; protected $html_before = ''; protected $html_after = ''; protected $statusmodel = self::STATUSMODEL_SERVICE; protected $show_status_in_headline = true; protected $default_status = self::STATUS_UNKNOWN; protected $default_warning_range = null; protected $default_critical_range = null; protected $argWarning; protected $argCritical; protected $argVersion; protected $argVerbosity; protected $argTimeout; protected $argHelp; protected $argUsage; public $id = null; protected static $http_serial_number = 0; public $privkey = null; public $privkey_password = null; public $sign_algo = null; public $pubkey = null; protected $warningSingleValueRangeBehaviors = array(self::SINGLEVALUE_RANGE_DEFAULT); protected $criticalSingleValueRangeBehaviors = array(self::SINGLEVALUE_RANGE_DEFAULT); const SINGLEVALUE_RANGE_DEFAULT = 0; const SINGLEVALUE_RANGE_VAL_GT_X_BAD = 1; const SINGLEVALUE_RANGE_VAL_GE_X_BAD = 2; const SINGLEVALUE_RANGE_VAL_LT_X_BAD = 3; const SINGLEVALUE_RANGE_VAL_LE_X_BAD = 4; public $password_out = null; public $password_in = null; public static function is_http_mode() { return php_sapi_name() !== 'cli'; } public function getHelpManager() { return $this->helpObj; } public function getArgumentHandler() { return $this->argHandler; } public function outputHTML($text, $after_visual_output=true) { if ($this->is_http_mode()) { if ($this->initialized) { if ($after_visual_output) { $this->html_after .= $text; } else { $this->html_before .= $text; } } else { echo $text; } } } protected function resetArguments() { $this->argWarning = null; $this->argCritical = null; $this->argVersion = null; $this->argVerbosity = null; $this->argTimeout = null; $this->argHelp = null; $this->argWarning = null; $this->argCritical = null; } public function registerExpectedStandardArguments($args) { $this->resetArguments(); for ($i=0; $i<strlen($args); $i++) { switch ($args[$i]) { case 'w': $this->addExpectedArgument($this->argWarning = new VNagArgument('w', 'warning', VNagArgument::VALUE_REQUIRED, VNagLang::$argname_value, VNagLang::$warning_range)); break; case 'c': $this->addExpectedArgument($this->argCritical = new VNagArgument('c', 'critical', VNagArgument::VALUE_REQUIRED, VNagLang::$argname_value, VNagLang::$critical_range)); break; case 'V': $this->addExpectedArgument($this->argVersion = new VNagArgument('V', 'version', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$prints_version)); break; case 'v': $this->addExpectedArgument($this->argVerbosity = new VNagArgument('v', 'verbose', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$verbosity_helptext)); break; case 't': $this->addExpectedArgument($this->argTimeout = new VNagArgument('t', 'timeout', VNagArgument::VALUE_REQUIRED, VNagLang::$argname_seconds, VNagLang::$timeout_helptext)); break; case 'h': $this->addExpectedArgument($this->argHelp = new VNagArgument('h', 'help', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$help_helptext)); break; default: $letter = $args[$i]; throw new VNagInvalidStandardArgument(sprintf(VNagLang::$no_standard_arguments_with_letter, $letter)); } } } public function addExpectedArgument($argObj) { $helpObjAddEntryMethod = new ReflectionMethod($this->helpObj, '_addOption'); $helpObjAddEntryMethod->setAccessible(true); $helpObjAddEntryMethod->invoke($this->helpObj, $argObj); $argHandlerAddEntryMethod = new ReflectionMethod($this->argHandler, '_addExpectedArgument'); $argHandlerAddEntryMethod->setAccessible(true); $argHandlerAddEntryMethod->invoke($this->argHandler, $argObj); } protected function createArgumentHandler() { $this->argHandler = new VNagArgumentHandler(); } protected function createHelpObject() { $this->helpObj = new VNagHelp(); } protected function checkInitialized() { if (!$this->initialized) throw new VNagFunctionCallOutsideSession(); } protected function getVerbosityLevel() { $this->checkInitialized(); if (!isset($this->argVerbosity)) { return self::VERBOSITY_SUMMARY; } else { $level = $this->argVerbosity->count(); if ($level > self::MAX_VERBOSITY) $level = self::MAX_VERBOSITY; return $level; } } public function getWarningRange($argumentNumber=0) { $this->checkInitialized(); if (!isset($this->warningRanges[$argumentNumber])) { if (!is_null($this->argWarning)) { $warning = $this->argWarning->getValue(); if (!is_null($warning)) { $vals = explode(',',$warning); foreach ($vals as $number => $val) { if (_empty($val)) { $this->warningRanges[$number] = null; } else { $singleValueBehavior = isset($this->warningSingleValueRangeBehaviors[$number]) ? $this->warningSingleValueRangeBehaviors[$number] : VNag::SINGLEVALUE_RANGE_DEFAULT; $this->warningRanges[$number] = new VNagRange($val, $singleValueBehavior); } } } else { $this->warningRanges[0] = $this->default_warning_range; } } else { return null; } } if (isset($this->warningRanges[$argumentNumber])) { return $this->warningRanges[$argumentNumber]; } else { return null; } } public function getCriticalRange($argumentNumber=0) { $this->checkInitialized(); if (!isset($this->criticalRanges[$argumentNumber])) { if (!is_null($this->argCritical)) { $critical = $this->argCritical->getValue(); if (!is_null($critical)) { $vals = explode(',',$critical); foreach ($vals as $number => $val) { $singleValueBehavior = isset($this->criticalSingleValueRangeBehaviors[$number]) ? $this->criticalSingleValueRangeBehaviors[$number] : VNag::SINGLEVALUE_RANGE_DEFAULT; $this->criticalRanges[$number] = new VNagRange($val, $singleValueBehavior); } } else { $this->criticalRanges[0] = $this->default_critical_range; } } else { return null; } } if (isset($this->criticalRanges[$argumentNumber])) { return $this->criticalRanges[$argumentNumber]; } else { return null; } } public function checkAgainstWarningRange($values, $force=true, $autostatus=true, $argumentNumber=0) { $this->checkInitialized(); if (!$this->getArgumentHandler()->isArgRegistered('w')) { throw new VNagRequiredArgumentNotRegistered('-w'); } $wr = $this->getWarningRange($argumentNumber); if (isset($wr)) { if ($wr->checkAlert($values)) { if ($autostatus) $this->setStatus(VNag::STATUS_WARNING); return true; } else { if ($autostatus) $this->setStatus(VNag::STATUS_OK); return false; } } else { if ($force) { if (($argumentNumber > 0) && (count($this->warningRanges) > 0)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$too_few_warning_ranges, $argumentNumber+1)); } else { throw new VNagRequiredArgumentMissing('-w'); } } } } public function checkAgainstCriticalRange($values, $force=true, $autostatus=true, $argumentNumber=0) { $this->checkInitialized(); if (!$this->getArgumentHandler()->isArgRegistered('c')) { throw new VNagRequiredArgumentNotRegistered('-c'); } $cr = $this->getCriticalRange($argumentNumber); if (isset($cr)) { if ($cr->checkAlert($values)) { if ($autostatus) $this->setStatus(VNag::STATUS_CRITICAL); return true; } else { if ($autostatus) $this->setStatus(VNag::STATUS_OK); return false; } } else { if ($force) { if (($argumentNumber > 0) && (count($this->warningRanges) > 0)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$too_few_critical_ranges, $argumentNumber+1)); } else { throw new VNagRequiredArgumentMissing('-c'); } } } } protected static function getBaddestExitcode($code1, $code2) { return max($code1, $code2); } public static function _shutdownHandler() { if (!self::is_http_mode()) { exit((int)self::$exitcode); } } protected function _exit($code) { self::$exitcode = $this->getBaddestExitcode($code, self::$exitcode); } private $constructed = false; function __construct() { $this->createHelpObject(); $this->createArgumentHandler(); $this->addExpectedArgument($this->argUsage = new VNagArgument('?', '', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$prints_usage)); $this->constructed = true; } function __destruct() { if (Timeouter::started()) { Timeouter::end(); } } public function run() { global $inside_vnag_run; $inside_vnag_run = true; try { if (!$this->constructed) { throw new VNagNotConstructed(VNagLang::$notConstructed); } try { $this->initialized = true; $this->html_before = ''; $this->html_after = ''; $this->setStatus(null, true); $this->messages = array(); register_shutdown_function(array($this, '_shutdownHandler')); if ($this->argHandler->illegalUsage()) { $content = $this->helpObj->printUsagePage(); $this->setStatus(VNag::STATUS_UNKNOWN); if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_visual_output & VNag::OUTPUT_SPECIAL) echo $this->writeVisualHTML($content); if ($this->http_invisible_output & VNag::OUTPUT_SPECIAL) echo $this->writeInvisibleHTML($content); echo $this->html_after; return; } else { echo $content; return $this->_exit($this->status); } } if (!is_null($this->argVersion) && ($this->argVersion->available())) { $content = $this->helpObj->printVersionPage(); $this->setStatus(VNag::STATUS_UNKNOWN); if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_visual_output & VNag::OUTPUT_SPECIAL) echo $this->writeVisualHTML($content); if ($this->http_invisible_output & VNag::OUTPUT_SPECIAL) echo $this->writeInvisibleHTML($content); echo $this->html_after; return; } else { echo $content; return $this->_exit($this->status); } } if (!is_null($this->argHelp) && ($this->argHelp->available())) { $content = $this->helpObj->printHelpPage(); $this->setStatus(VNag::STATUS_UNKNOWN); if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_visual_output & VNag::OUTPUT_SPECIAL) echo $this->writeVisualHTML($content); if ($this->http_invisible_output & VNag::OUTPUT_SPECIAL) echo $this->writeInvisibleHTML($content); echo $this->html_after; return; } else { echo $content; return $this->_exit($this->status); } } $this->getWarningRange(); $this->getCriticalRange(); if (!is_null($this->argTimeout)) { $timeout = $this->argTimeout->getValue(); if (!is_null($timeout)) { Timeouter::start($timeout); } } ob_start(); $init_ob_level = ob_get_level(); try { $this->cbRun(); if (ob_get_level() < $init_ob_level) throw new VNagImplementationErrorException(VNagLang::$output_level_lowered); } finally { while (ob_get_level() > $init_ob_level) @ob_end_clean(); } if (is_null($this->status)) $this->setStatus($this->default_status,true); $outputType = VNag::OUTPUT_NORMAL; } catch (Exception $e) { $this->handleException($e); $outputType = VNag::OUTPUT_EXCEPTION; } if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_invisible_output & $outputType) { echo $this->writeInvisibleHTML(); } if ($this->http_visual_output & $outputType) { echo $this->writeVisualHTML(); } echo $this->html_after; } else { echo $this->getNagiosConsoleText(); return $this->_exit($this->status); } Timeouter::end(); } finally { $inside_vnag_run = false; } } private function getNagiosConsoleText() { $ary_perfdata = $this->getPerformanceData(); $performancedata_first = array_shift($ary_perfdata); $performancedata_rest = implode(' ', $ary_perfdata); $status_text = VNagLang::status($this->status, $this->statusmodel); if (_empty($this->getHeadline())) { $content = $status_text; } else { if ($this->show_status_in_headline) { $content = $status_text.': '.$this->getHeadline(); } else { $content = $this->getHeadline(); } } if (!_empty($performancedata_first)) $content .= '|'.trim($performancedata_first); $content .= "\n"; if (!_empty($this->verbose_info)) { $content .= trim($this->verbose_info); } if (!_empty($performancedata_rest)) $content .= '|'.trim($performancedata_rest); $content .= "\n"; return trim($content)."\n"; } abstract protected function cbRun(); public function addPerformanceData($prefDataObj, $move_to_font=false, $verbosityLevel=VNag::VERBOSITY_SUMMARY) { $this->checkInitialized(); if ((!isset($this->argVerbosity)) && ($verbosityLevel > VNag::VERBOSITY_SUMMARY)) throw new VNagRequiredArgumentNotRegistered('-v'); if (self::getVerbosityLevel() < $verbosityLevel) return false; if ($move_to_font) { array_unshift($this->performanceDataObjects, $prefDataObj); } else { $this->performanceDataObjects[] = $prefDataObj; } return true; } public function getPerformanceData() { $this->checkInitialized(); return $this->performanceDataObjects; } public function removePerformanceData($prefDataObj) { if (($key = array_search($prefDataObj, $this->performanceDataObjects, true)) !== false) { unset($this->performanceDataObjects[$key]); return true; } else { return false; } } public function clearPerformanceData() { $this->performanceDataObjects = array(); } public function getVerboseInfo() { return $this->verbose_info; } public function clearVerboseInfo() { $this->verbose_info = ''; } private function writeVisualHTML($special_content=null) { if (!_empty($special_content)) { $content = $special_content; } else { $content = strtoupper(VNagLang::$status.': '.VNagLang::status($this->status, $this->statusmodel))."\n\n"; $content .= strtoupper(VNagLang::$message).":\n"; $status_text = VNagLang::status($this->status, $this->statusmodel); if (_empty($this->getHeadline())) { $content .= $status_text; } else { if ($this->show_status_in_headline) { $content .= $status_text.': '.trim($this->getHeadline()); } else { $content .= trim($this->getHeadline()); } } $content .= "\n\n"; if (!_empty($this->verbose_info)) { $content .= strtoupper(VNagLang::$verbose_info).":\n".trim($this->verbose_info)."\n\n"; } $perfdata = $this->getPerformanceData(); if (count($perfdata) > 0) { $content .= strtoupper(VNagLang::$performance_data).":\n"; foreach ($perfdata as $pd) { $content .= trim($pd)."\n"; } $content .= "\n"; } } $colorinfo = ''; $status = $this->getStatus(); if ($status == VNag::STATUS_OK) $colorinfo = ' style="background-color:green;color:white;font-weight:bold"'; else if ($status == VNag::STATUS_WARNING) $colorinfo = ' style="background-color:yellow;color:black;font-weight:bold"'; else if ($status == VNag::STATUS_CRITICAL) $colorinfo = ' style="background-color:red;color:white;font-weight:bold"'; else if ($status == VNag::STATUS_ERROR) $colorinfo = ' style="background-color:purple;color:white;font-weight:bold"'; else $colorinfo = ' style="background-color:lightgray;color:black;font-weight:bold"'; $html_content = trim($content); $html_content = htmlentities($html_content); $html_content = str_replace(' ', '&nbsp;', $html_content); $html_content = nl2br($html_content); return '<table border="1" cellspacing="2" cellpadding="2" style="width:100%" class="vnag_table">'. '<tr'.$colorinfo.' class="vnag_title_row">'. '<td>'.VNagLang::$nagios_output.'</td>'. '</tr>'. '<tr class="vnag_message_row">'. '<td><code>'. $html_content. '</code></td>'. '</tr>'. '</table>'; } protected function readInvisibleHTML($html) { $this->checkInitialized(); $doc = new DOMDocument(); @$doc->loadHTML($html); $tags = $doc->getElementsByTagName('script'); foreach ($tags as $tag) { $type = $tag->getAttribute('type'); if ($type !== 'application/json') continue; $json = $tag->nodeValue; if (!$json) continue; $data = @json_decode($json,true); if (!is_array($data)) continue; if (!isset($data['type'])) continue; if ($data['type'] === VNAG_JSONDATA_V1) { if (!isset($data['datasets'])) throw new VNagWebInfoException(VNagLang::$dataset_missing); foreach ($data['datasets'] as $dataset) { $payload = base64_decode($dataset['payload']); if (!$payload) { throw new VNagWebInfoException(VNagLang::$payload_not_base64); } if (isset($dataset['encryption'])) { $cryptInfo = $dataset['encryption']; if (!is_array($cryptInfo)) { throw new VNagWebInfoException(VNagLang::$dataset_encryption_no_array); } $password = is_null($this->password_in) ? '' : $this->password_in; $salt = base64_decode($cryptInfo['salt']); if ($cryptInfo['hash'] != hash('sha256',$salt.$password)) { if ($password == '') { throw new VNagWebInfoException(VNagLang::$require_password); } else { throw new VNagWebInfoException(VNagLang::$wrong_password); } } if (!function_exists('openssl_decrypt')) { throw new VNagException(VNagLang::$openssl_missing); } $payload = openssl_decrypt($payload, $cryptInfo['method'], $password, 0, $cryptInfo['iv']); } if (!is_null($this->pubkey) && ($this->pubkey !== '')) { if (substr($this->pubkey,0,3) === '---') { $public_key = $this->pubkey; } else { if (!file_exists($this->pubkey)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$pubkey_file_not_found, $this->pubkey)); } $public_key = @file_get_contents($this->pubkey); if (!$public_key) { throw new VNagPublicKeyException(sprintf(VNagLang::$pubkey_file_not_readable, $this->pubkey)); } } if (!isset($dataset['signature'])) { throw new VNagSignatureException(VNagLang::$signature_missing); } $signature = base64_decode($dataset['signature']); if (!$signature) { throw new VNagSignatureException(VNagLang::$signature_not_bas64); } if (!function_exists('openssl_verify')) { throw new VNagException(VNagLang::$openssl_missing); } $sign_algo = is_null($this->sign_algo) ? OPENSSL_ALGO_SHA256 : $this->sign_algo; if (!openssl_verify($payload, $signature, $public_key, $sign_algo)) { throw new VNagSignatureException(VNagLang::$signature_invalid); } } $payload = @json_decode($payload,true); if (!$payload) { throw new VNagWebInfoException(VNagLang::$payload_not_json); } if ($payload['id'] == $this->id) { return $payload; } } } } return null; } private function getNextMonitorID($peek=false) { $result = is_null($this->id) ? self::$http_serial_number : $this->id; if (!$peek) { $this->id = null; self::$http_serial_number++; } return $result; } private function writeInvisibleHTML($special_content=null) { $payload['id'] = $this->getNextMonitorID(); $payload['status'] = $this->getStatus(); if (!_empty($special_content)) { $payload['text'] = $special_content; } else { $payload['headline'] = $this->getHeadline(); $payload['verbose_info'] = $this->verbose_info; $payload['performance_data'] = array(); foreach ($this->performanceDataObjects as $perfdata) { $payload['performance_data'][] = (string)$perfdata; } } $payload = json_encode($payload); $dataset = array(); if (!is_null($this->privkey) && ($this->privkey !== '')) { if (!function_exists('openssl_pkey_get_private') || !function_exists('openssl_sign')) { throw new VNagException(VNagLang::$openssl_missing); } if (substr($this->privkey,0,3) === '---') { $pkeyid = @openssl_pkey_get_private($this->privkey, $this->privkey_password); if (!$pkeyid) { throw new VNagPrivateKeyException(sprintf(VNagLang::$privkey_not_readable)); } } else { if (!file_exists($this->privkey)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$privkey_file_not_found, $this->privkey)); } $pkeyid = @openssl_pkey_get_private('file://'.$this->privkey, $this->privkey_password); if (!$pkeyid) { throw new VNagPrivateKeyException(sprintf(VNagLang::$privkey_file_not_readable, $this->privkey)); } } $signature = ''; $sign_algo = is_null($this->sign_algo) ? OPENSSL_ALGO_SHA256 : $this->sign_algo; if (@openssl_sign($payload, $signature, $pkeyid, $sign_algo)) { if (version_compare(PHP_VERSION, '8.0.0') < 0) { openssl_free_key($pkeyid); } $dataset['signature'] = base64_encode($signature); } else { throw new VNagPrivateKeyException(sprintf(VNagLang::$signature_failed)); } } if (!is_null($this->password_out) && ($this->password_out !== '')) { if (!function_exists('openssl_encrypt')) { throw new VNagException(VNagLang::$openssl_missing); } $password = $this->password_out; $method = 'aes-256-ofb'; $iv = substr(hash('sha256', openssl_random_pseudo_bytes(32)), 0, 16); $salt = openssl_random_pseudo_bytes(32); $cryptInfo = array(); $cryptInfo['method'] = $method; $cryptInfo['iv'] = $iv; $cryptInfo['salt'] = base64_encode($salt); $cryptInfo['hash'] = hash('sha256', $salt.$password); $payload = openssl_encrypt($payload, $method, $password, 0, $iv); $dataset['encryption'] = $cryptInfo; } $dataset['payload'] = base64_encode($payload); $json = array(); $json['type'] = VNAG_JSONDATA_V1; $json['datasets'] = array($dataset); return '<script type="application/json">'. json_encode($json). '</script>'; } protected function appendHeadline($msg) { $this->checkInitialized(); if (_empty($msg)) return false; $this->messages[] = $msg; return true; } protected function changeHeadline($msg) { $this->checkInitialized(); if (_empty($msg)) { $this->messages = array(); } else { $this->messages = array($msg); } return true; } public function setHeadline($msg, $append=false, $verbosityLevel=VNag::VERBOSITY_SUMMARY) { $this->checkInitialized(); if ((!isset($this->argVerbosity)) && ($verbosityLevel > VNag::VERBOSITY_SUMMARY)) throw new VNagRequiredArgumentNotRegistered('-v'); if (self::getVerbosityLevel() < $verbosityLevel) $msg = ''; if ($append) { return $this->appendHeadline($msg); } else { return $this->changeHeadline($msg); } } public function getHeadline() { $this->checkInitialized(); return implode(', ', $this->messages); } public function addVerboseMessage($msg, $verbosityLevel=VNag::VERBOSITY_SUMMARY) { $this->checkInitialized(); if (self::getVerbosityLevel() >= $verbosityLevel) { $this->verbose_info .= $msg."\n"; } } public function setStatus($status, $force=false) { $this->checkInitialized(); if (($force) || is_null($this->status) || ($status > $this->status)) { $this->status = $status; } } public function getStatus() { $this->checkInitialized(); return $this->status; } protected static function exceptionText($exception) { $class = get_class($exception); $msg = $exception->getMessage(); if (!_empty($msg)) { return sprintf(VNagLang::$exception_x, $msg, $class); } else { return sprintf(VNagLang::$unhandled_exception_without_msg, $class); } } protected function handleException($exception) { $this->checkInitialized(); if (!VNag::is_http_mode()) { while (ob_get_level() > 0) @ob_end_clean(); } $this->clearVerboseInfo(); $this->clearPerformanceData(); if ($exception instanceof VNagException) { $this->setStatus($exception->getStatus()); } else { $this->setStatus(self::STATUS_ERROR); } $this->setHeadline($this->exceptionText($exception), false); if ($exception instanceof VNagImplementationErrorException) { $this->addVerboseMessage($exception->getTraceAsString(), VNag::VERBOSITY_SUMMARY); } else { if (isset($this->argVerbosity)) { $this->addVerboseMessage($exception->getTraceAsString(), VNag::VERBOSITY_ADDITIONAL_INFORMATION); } else { } } } protected function get_cache_dir() { $homedir = @getenv('HOME'); if ($homedir && is_dir($homedir)) { $try = "$homedir/.vnag/cache"; if (is_dir($try)) return $try; if (@mkdir($try,0777,true)) return $try; } $user = posix_getpwuid(posix_geteuid()); if (isset($user['dir']) && is_dir($user['dir'])) { $homedir = $user['dir']; $try = "$homedir/.vnag/cache"; if (is_dir($try)) return $try; if (@mkdir($try,0777,true)) return $try; } if (isset($user['name']) && is_dir($user['name'])) { $username = $user['name']; $try = "/tmp/vnag/cache"; if (is_dir($try)) return $try; if (@mkdir($try,0777,true)) return $try; } throw new VNagException("Cannot get cache dir"); } protected function url_get_contents($url, $max_cache_time=1*60*60, $context=null) { $cache_file = $this->get_cache_dir().'/'.hash('sha256',$url); if (file_exists($cache_file) && (time()-filemtime($cache_file) < $max_cache_time)) { $cont = @file_get_contents($cache_file); if ($cont === false) throw new Exception("Failed to get contents from $cache_file"); } else { $options = array( 'http'=>array( 'method'=>"GET", 'header'=>"Accept-language: en\r\n" . "User-Agent: Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B334b Safari/531.21.102011-10-16 20:23:10\r\n" ) ); if (is_null($context)) $context = stream_context_create($options); $cont = @file_get_contents($url, false, $context); if ($cont === false) throw new Exception("Failed to get contents from $url"); file_put_contents($cache_file, $cont); } return $cont; } } class VNagException extends Exception { public function getStatus() { return VNag::STATUS_ERROR; } } class VNagTimeoutException extends VNagException {} class VNagWebInfoException extends VNagException {} class VNagSignatureException extends VNagException {} class VNagPublicKeyException extends VNagException {} class VNagPrivateKeyException extends VNagException {} class VNagInvalidArgumentException extends VNagException { public function getStatus() { return VNag::STATUS_UNKNOWN; } } class VNagValueUomPairSyntaxException extends VNagInvalidArgumentException { public function __construct($str) { $e_msg = sprintf(VNagLang::$valueUomPairSyntaxError, $str); parent::__construct($e_msg); } } class VNagInvalidTimeoutException extends VNagInvalidArgumentException {} class VNagInvalidRangeException extends VNagInvalidArgumentException { public function __construct($msg) { $e_msg = VNagLang::$range_is_invalid; if (!_empty($msg)) $e_msg .= ': '.trim($msg); parent::__construct($e_msg); } } class VNagInvalidShortOpt extends VNagImplementationErrorException {} class VNagInvalidLongOpt extends VNagImplementationErrorException {} class VNagInvalidValuePolicy extends VNagImplementationErrorException {} class VNagIllegalStatusModel extends VNagImplementationErrorException {} class VNagNotConstructed extends VNagImplementationErrorException {} class VNagImplementationErrorException extends VNagException {} class VNagInvalidStandardArgument extends VNagImplementationErrorException {} class VNagFunctionCallOutsideSession extends VNagImplementationErrorException {} class VNagIllegalArgumentValuesException extends VNagImplementationErrorException {} class VNagRequiredArgumentNotRegistered extends VNagImplementationErrorException { public function __construct($required_argument) { $e_msg = sprintf(VNagLang::$query_without_expected_argument, $required_argument); parent::__construct($e_msg); } } class VNagRequiredArgumentMissing extends VNagInvalidArgumentException { public function __construct($required_argument) { $e_msg = sprintf(VNagLang::$required_argument_missing, $required_argument); parent::__construct($e_msg); } } class VNagUnknownUomException extends VNagInvalidArgumentException { public function __construct($uom) { $e_msg = sprintf(VNagLang::$perfdata_uom_not_recognized, $uom); parent::__construct($e_msg); } } class VNagNoCompatibleRangeUomFoundException extends VNagException {} class VNagMixedUomsNotImplemented extends VNagInvalidArgumentException { public function __construct($uom1, $uom2) { if (_empty($uom1)) $uom1 = VNagLang::$none; if (_empty($uom2)) $uom2 = VNagLang::$none; $e_msg = sprintf(VNagLang::$perfdata_mixed_uom_not_implemented, $uom1, $uom2); parent::__construct($e_msg); } } class VNagUomConvertException extends VNagInvalidArgumentException { public function __construct($uom1, $uom2) { if (_empty($uom1)) $uom1 = VNagLang::$none; if (_empty($uom2)) $uom2 = VNagLang::$none; $e_msg = sprintf(VNagLang::$convert_x_y_error, $uom1, $uom2); parent::__construct($e_msg); } } class VNagInvalidPerformanceDataException extends VNagInvalidArgumentException { public function __construct($msg) { $e_msg = VNagLang::$performance_data_invalid; if (!_empty($msg)) $e_msg .= ': '.trim($msg); parent::__construct($e_msg); } } class Timeouter { private static $start_time = false; private static $timeout; private static $fired = false; private static $registered = false; private function __construct() { } public static function start($timeout) { if (!is_numeric($timeout) || ($timeout <= 0)) { throw new VNagInvalidTimeoutException(sprintf(VNagLang::$timeout_value_invalid, $timeout)); } self::$start_time = microtime(true); self::$timeout = (float) $timeout; self::$fired = false; if (!self::$registered) { self::$registered = true; register_tick_function(array('Timeouter', 'tick')); } } public static function started() { return self::$registered; } public static function end() { if (self::$registered) { unregister_tick_function(array('Timeouter', 'tick')); self::$registered = false; } } public static function tick() { if ((!self::$fired) && ((microtime(true) - self::$start_time) > self::$timeout)) { self::$fired = true; throw new VNagTimeoutException(VNagLang::$timeout_exception); } } } class VNagArgument { const VALUE_FORBIDDEN = 0; const VALUE_REQUIRED = 1; const VALUE_OPTIONAL = 2; protected $shortopt; protected $longopts; protected $valuePolicy; protected $valueName; protected $helpText; protected $defaultValue = null; protected static $all_short = ''; protected static $all_long = array(); public function getShortOpt() { return $this->shortopt; } public function getLongOpts() { return $this->longopts; } public function getValuePolicy() { return $this->valuePolicy; } public function getValueName() { return $this->valueName; } public function getHelpText() { return $this->helpText; } static private function validateShortOpt($shortopt) { $m = array(); return preg_match('@^[a-zA-Z0-9\\+\\-\\?]$@', $shortopt, $m); } static private function validateLongOpt($longopt) { $m = array(); return preg_match('@^[a-zA-Z0-9\\+\\-\\?]+$@', $longopt, $m); } public function __construct($shortopt, $longopts, $valuePolicy, $valueName, $helpText, $defaultValue=null) { switch ($valuePolicy) { case VNagArgument::VALUE_FORBIDDEN: if (!_empty($valueName)) { throw new VNagImplementationErrorException(sprintf(VNagLang::$value_name_forbidden)); } break; case VNagArgument::VALUE_REQUIRED: if (_empty($valueName)) { throw new VNagImplementationErrorException(sprintf(VNagLang::$value_name_required)); } break; case VNagArgument::VALUE_OPTIONAL: if (_empty($valueName)) { throw new VNagImplementationErrorException(sprintf(VNagLang::$value_name_required)); } break; default: throw new VNagInvalidValuePolicy(sprintf(VNagLang::$illegal_valuepolicy, $valuePolicy)); } if (!_empty($shortopt)) { if (!self::validateShortOpt($shortopt)) { throw new VNagInvalidShortOpt(sprintf(VNagLang::$illegal_shortopt, $shortopt)); } } if (is_array($longopts)) { foreach ($longopts as $longopt) { if (!self::validateLongOpt($longopt)) { throw new VNagInvalidLongOpt(sprintf(VNagLang::$illegal_longopt, $longopt)); } } } else if (!_empty($longopts)) { if (!self::validateLongOpt($longopts)) { throw new VNagInvalidLongOpt(sprintf(VNagLang::$illegal_longopt, $longopts)); } $longopts = array($longopts); } else { $longopts = array(); } switch ($valuePolicy) { case VNagArgument::VALUE_FORBIDDEN: $policyApdx = ''; break; case VNagArgument::VALUE_REQUIRED: $policyApdx = ':'; break; case VNagArgument::VALUE_OPTIONAL: $policyApdx = '::'; break; default: throw new VNagInvalidValuePolicy(sprintf(VNagLang::$illegal_valuepolicy, $valuePolicy)); } if ((!is_null($shortopt)) && ($shortopt != '?')) self::$all_short .= $shortopt.$policyApdx; if (is_array($longopts)) { foreach ($longopts as $longopt) { self::$all_long[] = $longopt.$policyApdx; } } $this->shortopt = $shortopt; $this->longopts = $longopts; $this->valuePolicy = $valuePolicy; $this->valueName = $valueName; $this->helpText = $helpText; $this->defaultValue = $defaultValue; } protected static function getOptions() { global $OVERWRITE_ARGUMENTS; if (!is_null($OVERWRITE_ARGUMENTS)) { return $OVERWRITE_ARGUMENTS; } else if (VNag::is_http_mode()) { return $_REQUEST; } else { return getopt(self::$all_short, self::$all_long); } } public function count() { $options = self::getOptions(); $count = 0; if (isset($options[$this->shortopt])) { if (is_array($options[$this->shortopt])) { $count += count($options[$this->shortopt]); } else { $count += 1; } } if (!is_null($this->longopts)) { foreach ($this->longopts as $longopt) { if (isset($options[$longopt])) { if (is_array($options[$longopt])) { $count += count($options[$longopt]); } else { $count += 1; } } } } return $count; } public function available() { $options = self::getOptions(); if (isset($options[$this->shortopt])) return true; if (!is_null($this->longopts)) { foreach ($this->longopts as $longopt) { if (isset($options[$longopt])) return true; } } return false; } public function require() { if (!$this->available() && is_null($this->defaultValue)) { $opt = $this->shortopt; $opt = !_empty($opt) ? '-'.$opt : (isset($this->longopts[0]) ? '--'.$this->longopts[0] : '?'); throw new VNagRequiredArgumentMissing($opt); } } public function getValue() { $options = self::getOptions(); if (isset($options[$this->shortopt])) { $x = $options[$this->shortopt]; if (is_array($x) && (count($x) <= 1)) $options[$this->shortopt] = $options[$this->shortopt][0]; return $options[$this->shortopt]; } if (!is_null($this->longopts)) { foreach ($this->longopts as $longopt) { if (isset($options[$longopt])) { $x = $options[$longopt]; if (is_array($x) && (count($x) <= 1)) $options[$longopt] = $options[$longopt][0]; return $options[$longopt]; } } } return $this->defaultValue; } } class VNagArgumentHandler { protected $expectedArgs = array(); protected function _addExpectedArgument($argObj) { if ($argObj->getShortOpt() == '?') return false; if ($argObj->getShortOpt() == '-') return false; if ($argObj->getShortOpt() == '+') return false; $this->expectedArgs[] = $argObj; return true; } public function getArgumentObj($shortopt) { foreach ($this->expectedArgs as $argObj) { if ($argObj->getShortOpt() == $shortopt) return $argObj; } return null; } public function isArgRegistered($shortopt) { return !is_null($this->getArgumentObj($shortopt)); } public function illegalUsage() { global $argv; return (isset($argv[1])) && (($argv[1] == '-?') || ($argv[1] == '/?')); } } class VNagRange { public $start; public $end; public $warnInsideRange; public function __construct($rangeDef, $singleValueBehavior=VNag::SINGLEVALUE_RANGE_DEFAULT) { $m = array(); if (!preg_match('|^(@){0,1}([^:]+)(:){0,1}(.*)$|', $rangeDef, $m)) { throw new VNagInvalidRangeException(sprintf(VNagLang::$range_invalid_syntax, $rangeDef)); } $this->warnInsideRange = $m[1] === '@'; $this->start = null; $this->end = null; if ($m[3] === ':') { if ($m[2] === '~') { $this->start = '-inf'; } else { $this->start = new VNagValueUomPair($m[2]); } if (_empty($m[4])) { $this->end = 'inf'; } else { $this->end = new VNagValueUomPair($m[4]); } } else { assert(_empty($m[4])); assert(!_empty($m[2])); $x = $m[2]; if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_DEFAULT) { $this->start = new VNagValueUomPair('0'.((new VNagValueUomPair($x))->getUom())); $this->end = new VNagValueUomPair($x); } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_GT_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 0; $this->start = '-inf'; $this->end = new VNagValueUomPair($x); } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_GE_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 1; $this->start = new VNagValueUomPair($x); $this->end = 'inf'; } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_LT_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 0; $this->start = new VNagValueUomPair($x); $this->end = 'inf'; } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_LE_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 1; $this->start = '-inf'; $this->end = new VNagValueUomPair($x); } else { throw new VNagException(VNagLang::$illegalSingleValueBehavior); } } if (is_null($this->start)) { throw new VNagInvalidRangeException(VNagLang::$invalid_start_value); } if (is_null($this->end)) { throw new VNagInvalidRangeException(VNagLang::$invalid_end_value); } if (($this->start instanceof VNagValueUomPair) && ($this->end instanceof VNagValueUomPair) && (VNagValueUomPair::compare($this->start,$this->end) > 0)) { throw new VNagInvalidRangeException(VNagLang::$start_is_greater_than_end); } } public function __toString() { $ret = ''; if ($this->warnInsideRange) { $ret = '@'; } if ($this->start === '-inf') { $ret .= '~'; } else { $ret .= $this->start; } $ret .= ':'; if ($this->end !== 'inf') { $ret .= $this->end; } return $ret; } public function checkAlert($values) { $compatibleCount = 0; if (!is_array($values)) $values = array($values); foreach ($values as $value) { if (!($value instanceof VNagValueUomPair)) $value = new VNagValueUomPair($value); assert(($this->start === '-inf') || ($this->start instanceof VNagValueUomPair)); assert(($this->end === 'inf' ) || ($this->end instanceof VNagValueUomPair)); if (($this->start !== '-inf') && (!$this->start->compatibleWith($value))) continue; if (($this->end !== 'inf') && (!$this->end->compatibleWith($value))) continue; $compatibleCount++; if ($this->warnInsideRange) { return (($this->start === '-inf') || (VNagValueUomPair::compare($value,$this->start) >= 0)) && (($this->end === 'inf') || (VNagValueUomPair::compare($value,$this->end) <= 0)); } else { return (($this->start !== '-inf') && (VNagValueUomPair::compare($value,$this->start) < 0)) || (($this->end !== 'inf') && (VNagValueUomPair::compare($value,$this->end) > 0)); } } if ((count($values) > 0) and ($compatibleCount == 0)) { throw new VNagNoCompatibleRangeUomFoundException(VNagLang::$no_compatible_range_uom_found); } return false; } } class VNagValueUomPair { protected $value; protected $uom; public $roundTo = -1; public function isRelative() { return $this->uom === '%'; } public function getValue() { return $this->value; } public function getUom() { return $this->uom; } public function __toString() { if ($this->roundTo == -1) { return $this->value.$this->uom; } else { return round($this->value,$this->roundTo).$this->uom; } } public function __construct($str) { $m = array(); if (!preg_match('/^([\d\.]+)(.*)$/ism', $str, $m)) { throw new VNagValueUomPairSyntaxException($str); } $this->value = $m[1]; $this->uom = isset($m[2]) ? $m[2] : ''; if (!self::isKnownUOM($this->uom)) { throw new VNagUnknownUomException($this->uom); } } public static function isKnownUOM(string $uom) { $no_unit = ($uom === ''); $seconds = ($uom === 's') || ($uom === 'ms') || ($uom === 'us'); $percentage = ($uom === '%'); $bytes = ($uom === 'B') || ($uom === 'KB') || ($uom === 'MB') || ($uom === 'GB') || ($uom === 'TB'); $counter = ($uom === 'c'); return ($no_unit || $seconds || $percentage || $bytes || $counter); } public function normalize($target=null) { $res = clone $this; if ($res->uom === 'ms') { $res->uom = 's'; $res->value /= 1000; } if ($res->uom === 'us') { $res->uom = 's'; $res->value /= 1000 * 1000; } if ($res->uom === 'B') { $res->uom = 'MB'; $res->value /= 1024 * 1024; } if ($res->uom === 'KB') { $res->uom = 'MB'; $res->value /= 1024; } if ($res->uom === 'GB') { $res->uom = 'MB'; $res->value *= 1024; } if ($res->uom === 'TB') { $res->uom = 'MB'; $res->value *= 1024 * 1024; } if ($res->uom === 'c') { $res->uom = ''; } if (!is_null($target)) { if ($res->uom == 'MB') { if ($target == 'B') { $res->uom = 'B'; $res->value *= 1024 * 1024; } else if ($target == 'KB') { $res->uom = 'KB'; $res->value *= 1024; } else if ($target == 'MB') { $res->uom = 'MB'; $res->value *= 1; } else if ($target == 'GB') { $res->uom = 'GB'; $res->value /= 1024; } else if ($target == 'TB') { $res->uom = 'TB'; $res->value /= 1024 * 1024; } else { throw new VNagUomConvertException($res->uom, $target); } } else if ($res->uom == 's') { if ($target == 's') { $res->uom = 's'; $res->value /= 1; } else if ($target == 'ms') { $res->uom = 'ms'; $res->value /= 1000; } else if ($target == 'us') { $res->uom = 'us'; $res->value /= 1000 * 1000; } else { throw new VNagUomConvertException($res->uom, $target); } } else { throw new VNagUomConvertException($res->uom, $target); } } return $res; } public function compatibleWith(VNagValueUomPair $other) { $a = $this->normalize(); $b = $other->normalize(); return ($a->uom == $b->uom); } public static function compare(VNagValueUomPair $left, VNagValueUomPair $right) { $a = $left->normalize(); $b = $right->normalize(); if ($a->uom != $b->uom) throw new VNagMixedUomsNotImplemented($a->uom, $b->uom); if ($a->value > $b->value) return 1; if ($a->value == $b->value) return 0; if ($a->value < $b->value) return -1; } } class VNagPerformanceData { protected $label; protected $value; protected $warn = null; protected $crit = null; protected $min = null; protected $max = null; public static function createByString($perfdata) { $perfdata = trim($perfdata); $ary = explode('=',$perfdata); if (count($ary) != 2) { throw new VNagInvalidPerformanceDataException(sprintf(VNagLang::$perfdata_line_invalid, $perfdata)); } $label = $ary[0]; $bry = explode(';',$ary[1]); if (substr($label,0,1) === "'") $label = substr($label, 1, strlen($label)-2); $value = $bry[0]; $warn = isset($bry[1]) ? $bry[1] : null; $crit = isset($bry[2]) ? $bry[2] : null; $min = isset($bry[3]) ? $bry[3] : null; $max = isset($bry[4]) ? $bry[4] : null; return new self($label, $value, $warn, $crit, $min, $max); } public function __construct($label, $value, $warn=null, $crit=null, $min=null, $max=null) { if (strpos($label, '=') !== false) throw new VNagInvalidPerformanceDataException(VNagLang::$perfdata_label_equal_sign_forbidden); $label = str_replace("'", "''", $label); $m = array(); if ((!_empty($min)) && (!preg_match('|^[-0-9\\.]+$|', $min, $m))) { throw new VNagInvalidPerformanceDataException(VNagLang::$perfdata_min_must_be_in_class); } if ((!_empty($max)) && (!preg_match('|^[-0-9\\.]+$|', $max, $m))) { throw new VNagInvalidPerformanceDataException(VNagLang::$perfdata_max_must_be_in_class); } $this->label = $label; $this->value = ($value == 'U') ? 'U' : new VNagValueUomPair($value); $this->warn = $warn; $this->crit = $crit; $this->min = $min; $this->max = $max; } public function __toString() { $label = $this->label; $value = $this->value; $warn = $this->warn; $crit = $this->crit; $min = $this->min; $max = $this->max; $label = str_replace("''", "'", $label); return "'$label'=$value". ';'.(is_null($warn) ? '' : $warn). ';'.(is_null($crit) ? '' : $crit). ';'.(is_null($min) ? '' : $min). ';'.(is_null($max) ? '' : $max); } } class VNagHelp { public $word_wrap_width = 80; public $argument_indent = 7; public function printUsagePage() { $usage = $this->getUsage(); if (_empty($usage)) { $usage = VNagLang::$no_syntax_defined; } return trim($usage)."\n"; } public function printVersionPage() { $out = trim($this->getNameAndVersion())."\n"; if ($this->word_wrap_width > 0) $out = wordwrap($out, $this->word_wrap_width, "\n", false); return $out; } static private function _conditionalLine($line, $terminator='', $prefix='') { if (!_empty($line)) { return trim($line).$terminator; } return ''; } public function printHelpPage() { $out = ''; $out .= self::_conditionalLine($this->getNameAndVersion(), "\n"); $out .= self::_conditionalLine($this->getCopyright(), "\n"); $out .= ($out != '') ? "\n" : ''; $out .= self::_conditionalLine($this->getShortDescription(), "\n\n\n"); $out .= self::_conditionalLine($this->getUsage(), "\n\n"); $out .= VNagLang::$options."\n"; foreach ($this->options as $argObj) { $out .= $this->printArgumentHelp($argObj); } $out .= self::_conditionalLine($this->getFootNotes(), "\n\n", "\n"); if ($this->word_wrap_width > 0) $out = wordwrap($out, $this->word_wrap_width, "\n", false); return $out; } protected $options = array(); protected function _addOption($argObj) { $this->options[] = $argObj; } protected function printArgumentHelp($argObj) { $identifiers = array(); $shortopt = $argObj->getShortopt(); if (!_empty($shortopt)) $identifiers[] = '-'.$shortopt; $longopts = $argObj->getLongopts(); if (!is_null($longopts)) { foreach ($longopts as $longopt) { if (!_empty($longopt)) $identifiers[] = '--'.$longopt; } } if (count($identifiers) == 0) return; $valueName = $argObj->getValueName(); $arginfo = ''; switch ($argObj->getValuePolicy()) { case VNagArgument::VALUE_FORBIDDEN: $arginfo = ''; break; case VNagArgument::VALUE_REQUIRED: $arginfo = '='.$valueName; break; case VNagArgument::VALUE_OPTIONAL: $arginfo = '[='.$valueName.']'; break; } $out = ''; $out .= implode(', ', $identifiers).$arginfo."\n"; $content = trim($argObj->getHelpText()); if ($this->word_wrap_width > 0) $content = wordwrap($content, $this->word_wrap_width-$this->argument_indent, "\n", false); $lines = explode("\n", $content); foreach ($lines as $line) { $out .= str_repeat(' ', $this->argument_indent).$line."\n"; } $out .= "\n"; return $out; } protected $pluginName; public function setPluginName($pluginName) { $this->pluginName = $this->replaceStuff($pluginName); } public function getPluginName() { if (_empty($this->pluginName)) { global $argv; return basename($argv[0]); } else { return $this->pluginName; } } protected $version; public function setVersion($version) { $this->version = $this->replaceStuff($version); } public function getVersion() { return $this->version; } public function getNameAndVersion() { $ret = $this->getPluginName(); if (_empty($ret)) return null; $ver = $this->getVersion(); if (!_empty($ver)) { $ret = sprintf(VNagLang::$x_version_x, $ret, $ver); } $ret = trim($ret); return $ret; } protected $copyright; public function setCopyright($copyright) { $this->copyright = $this->replaceStuff($copyright); } private function getVNagCopyright() { if (VNag::is_http_mode()) { $vts_email = 'www.viathinksoft.com'; } else { $vts_email = base64_decode('aW5mb0B2aWF0aGlua3NvZnQuZGU='); } return "VNag Framework ".VNag::VNAG_VERSION." (C) 2014-".date('Y')." ViaThinkSoft <$vts_email>"; } public function getCopyright() { if (_empty($this->copyright)) { return sprintf(VNagLang::$plugin_uses, $this->getVNagCopyright()); } else { return trim($this->copyright)."\n".sprintf(VNagLang::$uses, $this->getVNagCopyright()); } } protected $shortDescription; public function setShortDescription($shortDescription) { $this->shortDescription = $this->replaceStuff($shortDescription); } public function getShortDescription() { if (_empty($this->shortDescription)) { return null; } else { $content = $this->shortDescription; if ($this->word_wrap_width > 0) $content = wordwrap($content, $this->word_wrap_width, "\n", false); return $content; } } protected function replaceStuff($text) { global $argv; if (php_sapi_name() == 'cli') { $text = str_replace('$SCRIPTNAME$', $argv[0], $text); } else { $text = str_replace('$SCRIPTNAME$', basename($_SERVER['SCRIPT_NAME']), $text); } $text = str_replace('$CURYEAR$', date('Y'), $text); return $text; } protected $syntax; public function setSyntax($syntax) { $syntax = $this->replaceStuff($syntax); $this->syntax = $syntax; } public function getUsage() { if (_empty($this->syntax)) { return null; } else { return sprintf(VNagLang::$usage_x, $this->syntax); } } protected $footNotes; public function setFootNotes($footNotes) { $this->footNotes = $this->replaceStuff($footNotes); } public function getFootNotes() { return $this->footNotes; } } class VNagLang { public static function status($code, $statusmodel) { switch ($statusmodel) { case VNag::STATUSMODEL_SERVICE: switch ($code) { case VNag::STATUS_OK: return 'OK'; case VNag::STATUS_WARNING: return 'Warning'; case VNag::STATUS_CRITICAL: return 'Critical'; case VNag::STATUS_UNKNOWN: return 'Unknown'; default: return sprintf('Error (%d)', $code); } case VNag::STATUSMODEL_HOST: switch ($code) { case VNag::STATUS_UP: return 'Up'; case VNag::STATUS_DOWN: return 'Down'; default: return sprintf('Maintain last state (%d)', $code); } default: throw new VNagIllegalStatusModel(sprintf(self::$illegal_statusmodel, $statusmodel)); } } static $nagios_output = 'VNag-Output'; static $verbose_info = 'Verbose information'; static $status = 'Status'; static $message = 'Message'; static $performance_data = 'Performance data'; static $status_ok = 'OK'; static $status_warn = 'Warning'; static $status_critical = 'Critical'; static $status_unknown = 'Unknown'; static $status_error = 'Error'; static $unhandled_exception_without_msg = "Unhandled exception of type %s"; static $plugin_uses = 'This plugin uses %s'; static $uses = 'uses %s'; static $x_version_x = '%s, version %s'; static $argname_value = 'value'; static $argname_seconds = 'seconds'; static $query_without_expected_argument = "The argument '%s' is queried, but was not added to the list of expected arguments. Please contact the plugin author."; static $required_argument_missing = "The argument '%s' is required."; static $performance_data_invalid = 'Performance data invalid.'; static $no_standard_arguments_with_letter = "No standard argument with letter '%s' exists."; static $invalid_start_value = 'Invalid start value.'; static $invalid_end_value = 'Invalid end value.'; static $start_is_greater_than_end = 'Start is greater than end value.'; static $value_name_forbidden = "Implementation error: You may not define a value name for the argument, because the value policy is VALUE_FORBIDDEN."; static $value_name_required = "Implementation error: Please define a name for the argument (so it can be shown in the help page)."; static $illegal_shortopt = "Illegal shortopt '-%s'."; static $illegal_longopt = "Illegal longopt '--%s'."; static $illegal_valuepolicy = "valuePolicy has illegal value '%s'."; static $range_invalid_syntax = "Syntax error in range '%s'."; static $timeout_value_invalid = "Timeout value '%s' is invalid."; static $range_is_invalid = 'Range is invalid.'; static $timeout_exception = 'Timeout!'; static $perfdata_label_equal_sign_forbidden = 'Label may not contain an equal sign.'; static $perfdata_value_must_be_in_class = 'Value must be in class [-0-9.] or be \'U\' if the actual value can\'t be determined.'; static $perfdata_min_must_be_in_class = 'Min must be in class [-0-9.] or empty.'; static $perfdata_max_must_be_in_class = 'Max must be in class [-0-9.] or empty.'; static $perfdata_uom_not_recognized = 'UOM (unit of measurement) "%s" is not recognized.'; static $perfdata_mixed_uom_not_implemented = 'Mixed UOMs (%s and %s) are currently not supported.'; static $no_compatible_range_uom_found = 'Measured values are not compatible with the provided warning/critical parameter. Most likely, the UOM is incompatible.'; static $exception_x = '%s (%s)'; static $no_syntax_defined = 'The author of this plugin has not defined a syntax for this plugin.'; static $usage_x = "Usage:\n%s"; static $options = "Options:"; static $illegal_statusmodel = "Invalid statusmodel %d."; static $none = '[none]'; static $valueUomPairSyntaxError = 'Syntax error at "%s". Syntax must be Value[UOM].'; static $too_few_warning_ranges = "You have too few warning ranges (currently trying to get element %d)."; static $too_few_critical_ranges = "You have too few critical ranges (currently trying to get element %d)."; static $dataset_missing = 'Dataset missing.'; static $payload_not_base64 = 'The payload is not valid Base64.'; static $payload_not_json = 'The payload is not valid JSON.'; static $signature_missing = 'The signature is missing.'; static $signature_not_bas64 = 'The signature is not valid Base64.'; static $signature_invalid = 'The signature is invalid. The connection might have been tampered, or a different key is used.'; static $pubkey_file_not_found = "Public key file %s was not found."; static $pubkey_file_not_readable = "Public key file %s is not readable."; static $privkey_file_not_found = "Private key file %s was not found."; static $privkey_not_readable = "Private key is not readable."; static $privkey_file_not_readable = "Private key file %s is not readable."; static $signature_failed = "Signature failed."; static $perfdata_line_invalid = "Performance data line %s is invalid."; static $singlevalue_unexpected_at_symbol = 'This plugin does not allow the @-symbol at ranges for single values.'; static $illegalSingleValueBehavior = "Illegal value for 'singleValueBehavior'. Please contact the creator of the plugin."; static $dataset_encryption_no_array = 'Dataset encryption information invalid.'; static $require_password = 'This resource is protected with a password. Please provide a password.'; static $wrong_password = 'This resource is protected with a password. You have provided the wrong password, or it was changed.'; static $convert_x_y_error = 'Cannot convert from UOM %s to UOM %s.'; static $php_error = 'PHP has detected an error in the plugin. Please contact the plugin author.'; static $output_level_lowered = "Output Buffer level lowered during cbRun(). Please contact the plugin author."; static $openssl_missing = "OpenSSL is missing. Therefore, encryption and signatures are not available."; static $warning_range = 'Warning range'; static $critical_range = 'Critical range'; static $prints_version = 'Prints version'; static $verbosity_helptext = 'Verbosity -v, -vv or -vvv'; static $timeout_helptext = 'Sets timeout in seconds'; static $help_helptext = 'Prints help page'; static $prints_usage = 'Prints usage'; static $notConstructed = 'Parent constructor not called with parent::__construct().'; } function vnagErrorHandler($errorkind, $errortext, $file, $line) { global $inside_vnag_run; if (!$inside_vnag_run && VNag::is_http_mode()) { return false; } if (!(error_reporting() & $errorkind)) { return true; } if (defined('E_ERROR') && ($errorkind == E_ERROR)) $errorkind = 'Error'; if (defined('E_WARNING') && ($errorkind == E_WARNING)) $errorkind = 'Warning'; if (defined('E_PARSE') && ($errorkind == E_PARSE)) $errorkind = 'Parse'; if (defined('E_NOTICE') && ($errorkind == E_NOTICE)) $errorkind = 'Notice'; if (defined('E_CORE_ERROR') && ($errorkind == E_CORE_ERROR)) $errorkind = 'Core Error'; if (defined('E_CORE_WARNING') && ($errorkind == E_CORE_WARNING)) $errorkind = 'Core Warning'; if (defined('E_COMPILE_ERROR') && ($errorkind == E_COMPILE_ERROR)) $errorkind = 'Compile Error'; if (defined('E_COMPILE_WARNING') && ($errorkind == E_COMPILE_WARNING)) $errorkind = 'Compile Warning'; if (defined('E_USER_ERROR') && ($errorkind == E_USER_ERROR)) $errorkind = 'User Error'; if (defined('E_USER_WARNING') && ($errorkind == E_USER_WARNING)) $errorkind = 'User Warning'; if (defined('E_USER_NOTICE') && ($errorkind == E_USER_NOTICE)) $errorkind = 'User Notice'; if (defined('E_STRICT') && ($errorkind == E_STRICT)) $errorkind = 'Strict'; if (defined('E_RECOVERABLE_ERROR') && ($errorkind == E_RECOVERABLE_ERROR)) $errorkind = 'Recoverable Error'; if (defined('E_DEPRECATED') && ($errorkind == E_DEPRECATED)) $errorkind = 'Deprecated'; if (defined('E_USER_DEPRECATED') && ($errorkind == E_USER_DEPRECATED)) $errorkind = 'User Deprecated'; throw new VNagException(VNagLang::$php_error . " $errortext at $file:$line (kind $errorkind)"); } $inside_vnag_run = false; $old_error_handler = set_error_handler("vnagErrorHandler"); <?php
declare(ticks=1); class GitLabVersionCheck extends VNag { protected $argSystemDir = null; public function __construct() { parent::__construct(); $this->registerExpectedStandardArguments('Vvht'); $this->getHelpManager()->setPluginName('check_gitlab_version'); $this->getHelpManager()->setVersion('2023-10-13'); $this->getHelpManager()->setShortDescription('This plugin checks if a local GitLab system has the latest version installed.'); $this->getHelpManager()->setCopyright('Copyright (C) 2011-$CURYEAR$ Daniel Marschall, ViaThinkSoft.'); $this->getHelpManager()->setSyntax('$SCRIPTNAME$ [-d <directory>]'); $this->getHelpManager()->setFootNotes('If you encounter bugs, please contact ViaThinkSoft at www.viathinksoft.com'); $this->addExpectedArgument($this->argSystemDir = new VNagArgument('d', 'directory', VNagArgument::VALUE_REQUIRED, 'gitLabPath', 'The local directory where your GitLab installation (version-manifest.txt) is located.')); } protected function getInstalledVersion($dir) { $version_manifest = $dir.'/version-manifest.json'; if (!file_exists($version_manifest)) { throw new VNagException('This is not a valid GitLab installation in "'.$dir.'" (version-manifest.json is missing).'); } $cont = @file_get_contents($version_manifest); if ($cont === false) { throw new VNagException('Cannot read version-manifest.json from GitLab installation in "'.$dir.'".'); } $json = @json_decode($cont,true); if ($json === false) { throw new VNagException('This is not a valid GitLab installation in "'.$dir.'" (version-manifest.json has invalid JSON data).'); } return $json['build_version']; } protected function getServerResponse($version) { $opts = array( 'http'=>array( 'method'=>"GET", 'header'=>"Referer: http://example.org/\r\n" ) ); $context = stream_context_create($opts); $url = "https://version.gitlab.com/check.svg?gitlab_info=". urlencode(base64_encode('{"version":"'.$version.'"}')); $cont = $this->url_get_contents($url, 1*60*60, $context); if ($cont === false) { throw new VNagException('Cannot query version.gitlab.com for version check (Version '.$version.')'); } if (!preg_match('@>([^<]+)</text>@ismU', $cont, $m)) { throw new VNagException('Server version.gitlab.com sent an unexpected reply (Version '.$version.')'); } return $m[1]; } protected function cbRun($optional_args=array()) { $system_dir = $this->argSystemDir->getValue(); if (empty($system_dir)) { throw new VNagException("Please specify the directory of the GitLab installation."); } $system_dir = realpath($system_dir) === false ? $system_dir : realpath($system_dir); if (!is_dir($system_dir)) { throw new VNagException('Directory "'.$system_dir.'" not found.'); } $cur_ver = $this->getInstalledVersion($system_dir); $status = $this->getServerResponse($cur_ver); if ($status == 'up-to-date') { $this->setStatus(VNag::STATUS_OK); } else if ($status == 'update available') { $this->setStatus(VNag::STATUS_WARNING); } else if ($status == 'update asap') { $this->setStatus(VNag::STATUS_CRITICAL); } else { $this->setStatus(VNag::STATUS_UNKNOWN); } $this->setHeadline("GitLab currently installed version $cur_ver [$status] at $system_dir", true); } } <?php
declare(ticks=1); require_once __DIR__ . '/../../framework/vnag_framework.inc.php'; require_once __DIR__ . '/GitLabVersionCheck.class.php'; $job = new GitLabVersionCheck(); $job->run(); unset($job); 48Ñu֞ë>%¯,möätS,ûYÔ.¶öW…IŽÖâÉ0\ç"ׂ÷ß7C¾.þ[¯•¡gz,GBMB
declare(ticks=1); require_once __DIR__ . '/../../framework/vnag_framework.inc.php'; require_once __DIR__ . '/GitLabVersionCheck.class.php'; $job = new GitLabVersionCheck(); $job->run(); unset($job); ¢¢“Í¢NpGm*¥Ž­1‘×6½K¨Ú°×öÉ6,¾sóýÑ4Ùñ|´ûà)îËã©ìBñT=×ñÇ»ë»nGBMB
/trunk/bin/hp_smartarray.phar
-×ý–¤.plugins/hp_smartarray/check_hp_smartarray.phpsÊyï*eÊЀӞ¤<?php ?>
-<?php
+×ý–¤.plugins/hp_smartarray/check_hp_smartarray.phpsÊ» +eÊЀӞ¤<?php
if (!VNag::is_http_mode()) error_reporting(E_ALL); declare(ticks=1); set_time_limit(0); define('VNAG_JSONDATA_V1', 'oid:1.3.6.1.4.1.37476.2.3.1.1'); $OVERWRITE_ARGUMENTS = null; function _empty($x) { return is_null($x) || (trim($x) == ''); } abstract class VNag { const VNAG_VERSION = '2023-10-13'; const STATUS_OK = 0; const STATUS_WARNING = 1; const STATUS_CRITICAL = 2; const STATUS_UNKNOWN = 3; const STATUS_ERROR = 4; const STATUS_UP = 0; const STATUS_DOWN = 1; const STATUS_MAINTAIN = 2; const VERBOSITY_SUMMARY = 0; const VERBOSITY_ADDITIONAL_INFORMATION = 1; const VERBOSITY_CONFIGURATION_DEBUG = 2; const VERBOSITY_PLUGIN_DEBUG = 3; const MAX_VERBOSITY = self::VERBOSITY_PLUGIN_DEBUG; const STATUSMODEL_SERVICE = 0; const STATUSMODEL_HOST = 1; private $initialized = false; private $status = null; private $messages = array(); private $verbose_info = ''; private $warningRanges = array(); private $criticalRanges = array(); private $performanceDataObjects = array(); private static $exitcode = 0; private $helpObj = null; private $argHandler = null; const OUTPUT_NEVER = 0; const OUTPUT_SPECIAL = 1; const OUTPUT_NORMAL = 2; const OUTPUT_EXCEPTION = 4; const OUTPUT_ALWAYS = 7; public $http_visual_output = self::OUTPUT_ALWAYS; public $http_invisible_output = self::OUTPUT_ALWAYS; protected $html_before = ''; protected $html_after = ''; protected $statusmodel = self::STATUSMODEL_SERVICE; protected $show_status_in_headline = true; protected $default_status = self::STATUS_UNKNOWN; protected $default_warning_range = null; protected $default_critical_range = null; protected $argWarning; protected $argCritical; protected $argVersion; protected $argVerbosity; protected $argTimeout; protected $argHelp; protected $argUsage; public $id = null; protected static $http_serial_number = 0; public $privkey = null; public $privkey_password = null; public $sign_algo = null; public $pubkey = null; protected $warningSingleValueRangeBehaviors = array(self::SINGLEVALUE_RANGE_DEFAULT); protected $criticalSingleValueRangeBehaviors = array(self::SINGLEVALUE_RANGE_DEFAULT); const SINGLEVALUE_RANGE_DEFAULT = 0; const SINGLEVALUE_RANGE_VAL_GT_X_BAD = 1; const SINGLEVALUE_RANGE_VAL_GE_X_BAD = 2; const SINGLEVALUE_RANGE_VAL_LT_X_BAD = 3; const SINGLEVALUE_RANGE_VAL_LE_X_BAD = 4; public $password_out = null; public $password_in = null; public static function is_http_mode() { return php_sapi_name() !== 'cli'; } public function getHelpManager() { return $this->helpObj; } public function getArgumentHandler() { return $this->argHandler; } public function outputHTML($text, $after_visual_output=true) { if ($this->is_http_mode()) { if ($this->initialized) { if ($after_visual_output) { $this->html_after .= $text; } else { $this->html_before .= $text; } } else { echo $text; } } } protected function resetArguments() { $this->argWarning = null; $this->argCritical = null; $this->argVersion = null; $this->argVerbosity = null; $this->argTimeout = null; $this->argHelp = null; $this->argWarning = null; $this->argCritical = null; } public function registerExpectedStandardArguments($args) { $this->resetArguments(); for ($i=0; $i<strlen($args); $i++) { switch ($args[$i]) { case 'w': $this->addExpectedArgument($this->argWarning = new VNagArgument('w', 'warning', VNagArgument::VALUE_REQUIRED, VNagLang::$argname_value, VNagLang::$warning_range)); break; case 'c': $this->addExpectedArgument($this->argCritical = new VNagArgument('c', 'critical', VNagArgument::VALUE_REQUIRED, VNagLang::$argname_value, VNagLang::$critical_range)); break; case 'V': $this->addExpectedArgument($this->argVersion = new VNagArgument('V', 'version', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$prints_version)); break; case 'v': $this->addExpectedArgument($this->argVerbosity = new VNagArgument('v', 'verbose', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$verbosity_helptext)); break; case 't': $this->addExpectedArgument($this->argTimeout = new VNagArgument('t', 'timeout', VNagArgument::VALUE_REQUIRED, VNagLang::$argname_seconds, VNagLang::$timeout_helptext)); break; case 'h': $this->addExpectedArgument($this->argHelp = new VNagArgument('h', 'help', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$help_helptext)); break; default: $letter = $args[$i]; throw new VNagInvalidStandardArgument(sprintf(VNagLang::$no_standard_arguments_with_letter, $letter)); } } } public function addExpectedArgument($argObj) { $helpObjAddEntryMethod = new ReflectionMethod($this->helpObj, '_addOption'); $helpObjAddEntryMethod->setAccessible(true); $helpObjAddEntryMethod->invoke($this->helpObj, $argObj); $argHandlerAddEntryMethod = new ReflectionMethod($this->argHandler, '_addExpectedArgument'); $argHandlerAddEntryMethod->setAccessible(true); $argHandlerAddEntryMethod->invoke($this->argHandler, $argObj); } protected function createArgumentHandler() { $this->argHandler = new VNagArgumentHandler(); } protected function createHelpObject() { $this->helpObj = new VNagHelp(); } protected function checkInitialized() { if (!$this->initialized) throw new VNagFunctionCallOutsideSession(); } protected function getVerbosityLevel() { $this->checkInitialized(); if (!isset($this->argVerbosity)) { return self::VERBOSITY_SUMMARY; } else { $level = $this->argVerbosity->count(); if ($level > self::MAX_VERBOSITY) $level = self::MAX_VERBOSITY; return $level; } } public function getWarningRange($argumentNumber=0) { $this->checkInitialized(); if (!isset($this->warningRanges[$argumentNumber])) { if (!is_null($this->argWarning)) { $warning = $this->argWarning->getValue(); if (!is_null($warning)) { $vals = explode(',',$warning); foreach ($vals as $number => $val) { if (_empty($val)) { $this->warningRanges[$number] = null; } else { $singleValueBehavior = isset($this->warningSingleValueRangeBehaviors[$number]) ? $this->warningSingleValueRangeBehaviors[$number] : VNag::SINGLEVALUE_RANGE_DEFAULT; $this->warningRanges[$number] = new VNagRange($val, $singleValueBehavior); } } } else { $this->warningRanges[0] = $this->default_warning_range; } } else { return null; } } if (isset($this->warningRanges[$argumentNumber])) { return $this->warningRanges[$argumentNumber]; } else { return null; } } public function getCriticalRange($argumentNumber=0) { $this->checkInitialized(); if (!isset($this->criticalRanges[$argumentNumber])) { if (!is_null($this->argCritical)) { $critical = $this->argCritical->getValue(); if (!is_null($critical)) { $vals = explode(',',$critical); foreach ($vals as $number => $val) { $singleValueBehavior = isset($this->criticalSingleValueRangeBehaviors[$number]) ? $this->criticalSingleValueRangeBehaviors[$number] : VNag::SINGLEVALUE_RANGE_DEFAULT; $this->criticalRanges[$number] = new VNagRange($val, $singleValueBehavior); } } else { $this->criticalRanges[0] = $this->default_critical_range; } } else { return null; } } if (isset($this->criticalRanges[$argumentNumber])) { return $this->criticalRanges[$argumentNumber]; } else { return null; } } public function checkAgainstWarningRange($values, $force=true, $autostatus=true, $argumentNumber=0) { $this->checkInitialized(); if (!$this->getArgumentHandler()->isArgRegistered('w')) { throw new VNagRequiredArgumentNotRegistered('-w'); } $wr = $this->getWarningRange($argumentNumber); if (isset($wr)) { if ($wr->checkAlert($values)) { if ($autostatus) $this->setStatus(VNag::STATUS_WARNING); return true; } else { if ($autostatus) $this->setStatus(VNag::STATUS_OK); return false; } } else { if ($force) { if (($argumentNumber > 0) && (count($this->warningRanges) > 0)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$too_few_warning_ranges, $argumentNumber+1)); } else { throw new VNagRequiredArgumentMissing('-w'); } } } } public function checkAgainstCriticalRange($values, $force=true, $autostatus=true, $argumentNumber=0) { $this->checkInitialized(); if (!$this->getArgumentHandler()->isArgRegistered('c')) { throw new VNagRequiredArgumentNotRegistered('-c'); } $cr = $this->getCriticalRange($argumentNumber); if (isset($cr)) { if ($cr->checkAlert($values)) { if ($autostatus) $this->setStatus(VNag::STATUS_CRITICAL); return true; } else { if ($autostatus) $this->setStatus(VNag::STATUS_OK); return false; } } else { if ($force) { if (($argumentNumber > 0) && (count($this->warningRanges) > 0)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$too_few_critical_ranges, $argumentNumber+1)); } else { throw new VNagRequiredArgumentMissing('-c'); } } } } protected static function getBaddestExitcode($code1, $code2) { return max($code1, $code2); } public static function _shutdownHandler() { if (!self::is_http_mode()) { exit((int)self::$exitcode); } } protected function _exit($code) { self::$exitcode = $this->getBaddestExitcode($code, self::$exitcode); } private $constructed = false; function __construct() { $this->createHelpObject(); $this->createArgumentHandler(); $this->addExpectedArgument($this->argUsage = new VNagArgument('?', '', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$prints_usage)); $this->constructed = true; } function __destruct() { if (Timeouter::started()) { Timeouter::end(); } } public function run() { global $inside_vnag_run; $inside_vnag_run = true; try { if (!$this->constructed) { throw new VNagNotConstructed(VNagLang::$notConstructed); } try { $this->initialized = true; $this->html_before = ''; $this->html_after = ''; $this->setStatus(null, true); $this->messages = array(); register_shutdown_function(array($this, '_shutdownHandler')); if ($this->argHandler->illegalUsage()) { $content = $this->helpObj->printUsagePage(); $this->setStatus(VNag::STATUS_UNKNOWN); if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_visual_output & VNag::OUTPUT_SPECIAL) echo $this->writeVisualHTML($content); if ($this->http_invisible_output & VNag::OUTPUT_SPECIAL) echo $this->writeInvisibleHTML($content); echo $this->html_after; return; } else { echo $content; return $this->_exit($this->status); } } if (!is_null($this->argVersion) && ($this->argVersion->available())) { $content = $this->helpObj->printVersionPage(); $this->setStatus(VNag::STATUS_UNKNOWN); if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_visual_output & VNag::OUTPUT_SPECIAL) echo $this->writeVisualHTML($content); if ($this->http_invisible_output & VNag::OUTPUT_SPECIAL) echo $this->writeInvisibleHTML($content); echo $this->html_after; return; } else { echo $content; return $this->_exit($this->status); } } if (!is_null($this->argHelp) && ($this->argHelp->available())) { $content = $this->helpObj->printHelpPage(); $this->setStatus(VNag::STATUS_UNKNOWN); if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_visual_output & VNag::OUTPUT_SPECIAL) echo $this->writeVisualHTML($content); if ($this->http_invisible_output & VNag::OUTPUT_SPECIAL) echo $this->writeInvisibleHTML($content); echo $this->html_after; return; } else { echo $content; return $this->_exit($this->status); } } $this->getWarningRange(); $this->getCriticalRange(); if (!is_null($this->argTimeout)) { $timeout = $this->argTimeout->getValue(); if (!is_null($timeout)) { Timeouter::start($timeout); } } ob_start(); $init_ob_level = ob_get_level(); try { $this->cbRun(); if (ob_get_level() < $init_ob_level) throw new VNagImplementationErrorException(VNagLang::$output_level_lowered); } finally { while (ob_get_level() > $init_ob_level) @ob_end_clean(); } if (is_null($this->status)) $this->setStatus($this->default_status,true); $outputType = VNag::OUTPUT_NORMAL; } catch (Exception $e) { $this->handleException($e); $outputType = VNag::OUTPUT_EXCEPTION; } if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_invisible_output & $outputType) { echo $this->writeInvisibleHTML(); } if ($this->http_visual_output & $outputType) { echo $this->writeVisualHTML(); } echo $this->html_after; } else { echo $this->getNagiosConsoleText(); return $this->_exit($this->status); } Timeouter::end(); } finally { $inside_vnag_run = false; } } private function getNagiosConsoleText() { $ary_perfdata = $this->getPerformanceData(); $performancedata_first = array_shift($ary_perfdata); $performancedata_rest = implode(' ', $ary_perfdata); $status_text = VNagLang::status($this->status, $this->statusmodel); if (_empty($this->getHeadline())) { $content = $status_text; } else { if ($this->show_status_in_headline) { $content = $status_text.': '.$this->getHeadline(); } else { $content = $this->getHeadline(); } } if (!_empty($performancedata_first)) $content .= '|'.trim($performancedata_first); $content .= "\n"; if (!_empty($this->verbose_info)) { $content .= trim($this->verbose_info); } if (!_empty($performancedata_rest)) $content .= '|'.trim($performancedata_rest); $content .= "\n"; return trim($content)."\n"; } abstract protected function cbRun(); public function addPerformanceData($prefDataObj, $move_to_font=false, $verbosityLevel=VNag::VERBOSITY_SUMMARY) { $this->checkInitialized(); if ((!isset($this->argVerbosity)) && ($verbosityLevel > VNag::VERBOSITY_SUMMARY)) throw new VNagRequiredArgumentNotRegistered('-v'); if (self::getVerbosityLevel() < $verbosityLevel) return false; if ($move_to_font) { array_unshift($this->performanceDataObjects, $prefDataObj); } else { $this->performanceDataObjects[] = $prefDataObj; } return true; } public function getPerformanceData() { $this->checkInitialized(); return $this->performanceDataObjects; } public function removePerformanceData($prefDataObj) { if (($key = array_search($prefDataObj, $this->performanceDataObjects, true)) !== false) { unset($this->performanceDataObjects[$key]); return true; } else { return false; } } public function clearPerformanceData() { $this->performanceDataObjects = array(); } public function getVerboseInfo() { return $this->verbose_info; } public function clearVerboseInfo() { $this->verbose_info = ''; } private function writeVisualHTML($special_content=null) { if (!_empty($special_content)) { $content = $special_content; } else { $content = strtoupper(VNagLang::$status.': '.VNagLang::status($this->status, $this->statusmodel))."\n\n"; $content .= strtoupper(VNagLang::$message).":\n"; $status_text = VNagLang::status($this->status, $this->statusmodel); if (_empty($this->getHeadline())) { $content .= $status_text; } else { if ($this->show_status_in_headline) { $content .= $status_text.': '.trim($this->getHeadline()); } else { $content .= trim($this->getHeadline()); } } $content .= "\n\n"; if (!_empty($this->verbose_info)) { $content .= strtoupper(VNagLang::$verbose_info).":\n".trim($this->verbose_info)."\n\n"; } $perfdata = $this->getPerformanceData(); if (count($perfdata) > 0) { $content .= strtoupper(VNagLang::$performance_data).":\n"; foreach ($perfdata as $pd) { $content .= trim($pd)."\n"; } $content .= "\n"; } } $colorinfo = ''; $status = $this->getStatus(); if ($status == VNag::STATUS_OK) $colorinfo = ' style="background-color:green;color:white;font-weight:bold"'; else if ($status == VNag::STATUS_WARNING) $colorinfo = ' style="background-color:yellow;color:black;font-weight:bold"'; else if ($status == VNag::STATUS_CRITICAL) $colorinfo = ' style="background-color:red;color:white;font-weight:bold"'; else if ($status == VNag::STATUS_ERROR) $colorinfo = ' style="background-color:purple;color:white;font-weight:bold"'; else $colorinfo = ' style="background-color:lightgray;color:black;font-weight:bold"'; $html_content = trim($content); $html_content = htmlentities($html_content); $html_content = str_replace(' ', '&nbsp;', $html_content); $html_content = nl2br($html_content); return '<table border="1" cellspacing="2" cellpadding="2" style="width:100%" class="vnag_table">'. '<tr'.$colorinfo.' class="vnag_title_row">'. '<td>'.VNagLang::$nagios_output.'</td>'. '</tr>'. '<tr class="vnag_message_row">'. '<td><code>'. $html_content. '</code></td>'. '</tr>'. '</table>'; } protected function readInvisibleHTML($html) { $this->checkInitialized(); $doc = new DOMDocument(); @$doc->loadHTML($html); $tags = $doc->getElementsByTagName('script'); foreach ($tags as $tag) { $type = $tag->getAttribute('type'); if ($type !== 'application/json') continue; $json = $tag->nodeValue; if (!$json) continue; $data = @json_decode($json,true); if (!is_array($data)) continue; if (!isset($data['type'])) continue; if ($data['type'] === VNAG_JSONDATA_V1) { if (!isset($data['datasets'])) throw new VNagWebInfoException(VNagLang::$dataset_missing); foreach ($data['datasets'] as $dataset) { $payload = base64_decode($dataset['payload']); if (!$payload) { throw new VNagWebInfoException(VNagLang::$payload_not_base64); } if (isset($dataset['encryption'])) { $cryptInfo = $dataset['encryption']; if (!is_array($cryptInfo)) { throw new VNagWebInfoException(VNagLang::$dataset_encryption_no_array); } $password = is_null($this->password_in) ? '' : $this->password_in; $salt = base64_decode($cryptInfo['salt']); if ($cryptInfo['hash'] != hash('sha256',$salt.$password)) { if ($password == '') { throw new VNagWebInfoException(VNagLang::$require_password); } else { throw new VNagWebInfoException(VNagLang::$wrong_password); } } if (!function_exists('openssl_decrypt')) { throw new VNagException(VNagLang::$openssl_missing); } $payload = openssl_decrypt($payload, $cryptInfo['method'], $password, 0, $cryptInfo['iv']); } if (!is_null($this->pubkey) && ($this->pubkey !== '')) { if (substr($this->pubkey,0,3) === '---') { $public_key = $this->pubkey; } else { if (!file_exists($this->pubkey)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$pubkey_file_not_found, $this->pubkey)); } $public_key = @file_get_contents($this->pubkey); if (!$public_key) { throw new VNagPublicKeyException(sprintf(VNagLang::$pubkey_file_not_readable, $this->pubkey)); } } if (!isset($dataset['signature'])) { throw new VNagSignatureException(VNagLang::$signature_missing); } $signature = base64_decode($dataset['signature']); if (!$signature) { throw new VNagSignatureException(VNagLang::$signature_not_bas64); } if (!function_exists('openssl_verify')) { throw new VNagException(VNagLang::$openssl_missing); } $sign_algo = is_null($this->sign_algo) ? OPENSSL_ALGO_SHA256 : $this->sign_algo; if (!openssl_verify($payload, $signature, $public_key, $sign_algo)) { throw new VNagSignatureException(VNagLang::$signature_invalid); } } $payload = @json_decode($payload,true); if (!$payload) { throw new VNagWebInfoException(VNagLang::$payload_not_json); } if ($payload['id'] == $this->id) { return $payload; } } } } return null; } private function getNextMonitorID($peek=false) { $result = is_null($this->id) ? self::$http_serial_number : $this->id; if (!$peek) { $this->id = null; self::$http_serial_number++; } return $result; } private function writeInvisibleHTML($special_content=null) { $payload['id'] = $this->getNextMonitorID(); $payload['status'] = $this->getStatus(); if (!_empty($special_content)) { $payload['text'] = $special_content; } else { $payload['headline'] = $this->getHeadline(); $payload['verbose_info'] = $this->verbose_info; $payload['performance_data'] = array(); foreach ($this->performanceDataObjects as $perfdata) { $payload['performance_data'][] = (string)$perfdata; } } $payload = json_encode($payload); $dataset = array(); if (!is_null($this->privkey) && ($this->privkey !== '')) { if (!function_exists('openssl_pkey_get_private') || !function_exists('openssl_sign')) { throw new VNagException(VNagLang::$openssl_missing); } if (substr($this->privkey,0,3) === '---') { $pkeyid = @openssl_pkey_get_private($this->privkey, $this->privkey_password); if (!$pkeyid) { throw new VNagPrivateKeyException(sprintf(VNagLang::$privkey_not_readable)); } } else { if (!file_exists($this->privkey)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$privkey_file_not_found, $this->privkey)); } $pkeyid = @openssl_pkey_get_private('file://'.$this->privkey, $this->privkey_password); if (!$pkeyid) { throw new VNagPrivateKeyException(sprintf(VNagLang::$privkey_file_not_readable, $this->privkey)); } } $signature = ''; $sign_algo = is_null($this->sign_algo) ? OPENSSL_ALGO_SHA256 : $this->sign_algo; if (@openssl_sign($payload, $signature, $pkeyid, $sign_algo)) { if (version_compare(PHP_VERSION, '8.0.0') < 0) { openssl_free_key($pkeyid); } $dataset['signature'] = base64_encode($signature); } else { throw new VNagPrivateKeyException(sprintf(VNagLang::$signature_failed)); } } if (!is_null($this->password_out) && ($this->password_out !== '')) { if (!function_exists('openssl_encrypt')) { throw new VNagException(VNagLang::$openssl_missing); } $password = $this->password_out; $method = 'aes-256-ofb'; $iv = substr(hash('sha256', openssl_random_pseudo_bytes(32)), 0, 16); $salt = openssl_random_pseudo_bytes(32); $cryptInfo = array(); $cryptInfo['method'] = $method; $cryptInfo['iv'] = $iv; $cryptInfo['salt'] = base64_encode($salt); $cryptInfo['hash'] = hash('sha256', $salt.$password); $payload = openssl_encrypt($payload, $method, $password, 0, $iv); $dataset['encryption'] = $cryptInfo; } $dataset['payload'] = base64_encode($payload); $json = array(); $json['type'] = VNAG_JSONDATA_V1; $json['datasets'] = array($dataset); return '<script type="application/json">'. json_encode($json). '</script>'; } protected function appendHeadline($msg) { $this->checkInitialized(); if (_empty($msg)) return false; $this->messages[] = $msg; return true; } protected function changeHeadline($msg) { $this->checkInitialized(); if (_empty($msg)) { $this->messages = array(); } else { $this->messages = array($msg); } return true; } public function setHeadline($msg, $append=false, $verbosityLevel=VNag::VERBOSITY_SUMMARY) { $this->checkInitialized(); if ((!isset($this->argVerbosity)) && ($verbosityLevel > VNag::VERBOSITY_SUMMARY)) throw new VNagRequiredArgumentNotRegistered('-v'); if (self::getVerbosityLevel() < $verbosityLevel) $msg = ''; if ($append) { return $this->appendHeadline($msg); } else { return $this->changeHeadline($msg); } } public function getHeadline() { $this->checkInitialized(); return implode(', ', $this->messages); } public function addVerboseMessage($msg, $verbosityLevel=VNag::VERBOSITY_SUMMARY) { $this->checkInitialized(); if (self::getVerbosityLevel() >= $verbosityLevel) { $this->verbose_info .= $msg."\n"; } } public function setStatus($status, $force=false) { $this->checkInitialized(); if (($force) || is_null($this->status) || ($status > $this->status)) { $this->status = $status; } } public function getStatus() { $this->checkInitialized(); return $this->status; } protected static function exceptionText($exception) { $class = get_class($exception); $msg = $exception->getMessage(); if (!_empty($msg)) { return sprintf(VNagLang::$exception_x, $msg, $class); } else { return sprintf(VNagLang::$unhandled_exception_without_msg, $class); } } protected function handleException($exception) { $this->checkInitialized(); if (!VNag::is_http_mode()) { while (ob_get_level() > 0) @ob_end_clean(); } $this->clearVerboseInfo(); $this->clearPerformanceData(); if ($exception instanceof VNagException) { $this->setStatus($exception->getStatus()); } else { $this->setStatus(self::STATUS_ERROR); } $this->setHeadline($this->exceptionText($exception), false); if ($exception instanceof VNagImplementationErrorException) { $this->addVerboseMessage($exception->getTraceAsString(), VNag::VERBOSITY_SUMMARY); } else { if (isset($this->argVerbosity)) { $this->addVerboseMessage($exception->getTraceAsString(), VNag::VERBOSITY_ADDITIONAL_INFORMATION); } else { } } } protected function get_cache_dir() { $homedir = @getenv('HOME'); if ($homedir && is_dir($homedir)) { $try = "$homedir/.vnag/cache"; if (is_dir($try)) return $try; if (@mkdir($try,0777,true)) return $try; } $user = posix_getpwuid(posix_geteuid()); if (isset($user['dir']) && is_dir($user['dir'])) { $homedir = $user['dir']; $try = "$homedir/.vnag/cache"; if (is_dir($try)) return $try; if (@mkdir($try,0777,true)) return $try; } if (isset($user['name']) && is_dir($user['name'])) { $username = $user['name']; $try = "/tmp/vnag/cache"; if (is_dir($try)) return $try; if (@mkdir($try,0777,true)) return $try; } throw new VNagException("Cannot get cache dir"); } protected function url_get_contents($url, $max_cache_time=1*60*60, $context=null) { $cache_file = $this->get_cache_dir().'/'.hash('sha256',$url); if (file_exists($cache_file) && (time()-filemtime($cache_file) < $max_cache_time)) { $cont = @file_get_contents($cache_file); if ($cont === false) throw new Exception("Failed to get contents from $cache_file"); } else { $options = array( 'http'=>array( 'method'=>"GET", 'header'=>"Accept-language: en\r\n" . "User-Agent: Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B334b Safari/531.21.102011-10-16 20:23:10\r\n" ) ); if (is_null($context)) $context = stream_context_create($options); $cont = @file_get_contents($url, false, $context); if ($cont === false) throw new Exception("Failed to get contents from $url"); file_put_contents($cache_file, $cont); } return $cont; } } class VNagException extends Exception { public function getStatus() { return VNag::STATUS_ERROR; } } class VNagTimeoutException extends VNagException {} class VNagWebInfoException extends VNagException {} class VNagSignatureException extends VNagException {} class VNagPublicKeyException extends VNagException {} class VNagPrivateKeyException extends VNagException {} class VNagInvalidArgumentException extends VNagException { public function getStatus() { return VNag::STATUS_UNKNOWN; } } class VNagValueUomPairSyntaxException extends VNagInvalidArgumentException { public function __construct($str) { $e_msg = sprintf(VNagLang::$valueUomPairSyntaxError, $str); parent::__construct($e_msg); } } class VNagInvalidTimeoutException extends VNagInvalidArgumentException {} class VNagInvalidRangeException extends VNagInvalidArgumentException { public function __construct($msg) { $e_msg = VNagLang::$range_is_invalid; if (!_empty($msg)) $e_msg .= ': '.trim($msg); parent::__construct($e_msg); } } class VNagInvalidShortOpt extends VNagImplementationErrorException {} class VNagInvalidLongOpt extends VNagImplementationErrorException {} class VNagInvalidValuePolicy extends VNagImplementationErrorException {} class VNagIllegalStatusModel extends VNagImplementationErrorException {} class VNagNotConstructed extends VNagImplementationErrorException {} class VNagImplementationErrorException extends VNagException {} class VNagInvalidStandardArgument extends VNagImplementationErrorException {} class VNagFunctionCallOutsideSession extends VNagImplementationErrorException {} class VNagIllegalArgumentValuesException extends VNagImplementationErrorException {} class VNagRequiredArgumentNotRegistered extends VNagImplementationErrorException { public function __construct($required_argument) { $e_msg = sprintf(VNagLang::$query_without_expected_argument, $required_argument); parent::__construct($e_msg); } } class VNagRequiredArgumentMissing extends VNagInvalidArgumentException { public function __construct($required_argument) { $e_msg = sprintf(VNagLang::$required_argument_missing, $required_argument); parent::__construct($e_msg); } } class VNagUnknownUomException extends VNagInvalidArgumentException { public function __construct($uom) { $e_msg = sprintf(VNagLang::$perfdata_uom_not_recognized, $uom); parent::__construct($e_msg); } } class VNagNoCompatibleRangeUomFoundException extends VNagException {} class VNagMixedUomsNotImplemented extends VNagInvalidArgumentException { public function __construct($uom1, $uom2) { if (_empty($uom1)) $uom1 = VNagLang::$none; if (_empty($uom2)) $uom2 = VNagLang::$none; $e_msg = sprintf(VNagLang::$perfdata_mixed_uom_not_implemented, $uom1, $uom2); parent::__construct($e_msg); } } class VNagUomConvertException extends VNagInvalidArgumentException { public function __construct($uom1, $uom2) { if (_empty($uom1)) $uom1 = VNagLang::$none; if (_empty($uom2)) $uom2 = VNagLang::$none; $e_msg = sprintf(VNagLang::$convert_x_y_error, $uom1, $uom2); parent::__construct($e_msg); } } class VNagInvalidPerformanceDataException extends VNagInvalidArgumentException { public function __construct($msg) { $e_msg = VNagLang::$performance_data_invalid; if (!_empty($msg)) $e_msg .= ': '.trim($msg); parent::__construct($e_msg); } } class Timeouter { private static $start_time = false; private static $timeout; private static $fired = false; private static $registered = false; private function __construct() { } public static function start($timeout) { if (!is_numeric($timeout) || ($timeout <= 0)) { throw new VNagInvalidTimeoutException(sprintf(VNagLang::$timeout_value_invalid, $timeout)); } self::$start_time = microtime(true); self::$timeout = (float) $timeout; self::$fired = false; if (!self::$registered) { self::$registered = true; register_tick_function(array('Timeouter', 'tick')); } } public static function started() { return self::$registered; } public static function end() { if (self::$registered) { unregister_tick_function(array('Timeouter', 'tick')); self::$registered = false; } } public static function tick() { if ((!self::$fired) && ((microtime(true) - self::$start_time) > self::$timeout)) { self::$fired = true; throw new VNagTimeoutException(VNagLang::$timeout_exception); } } } class VNagArgument { const VALUE_FORBIDDEN = 0; const VALUE_REQUIRED = 1; const VALUE_OPTIONAL = 2; protected $shortopt; protected $longopts; protected $valuePolicy; protected $valueName; protected $helpText; protected $defaultValue = null; protected static $all_short = ''; protected static $all_long = array(); public function getShortOpt() { return $this->shortopt; } public function getLongOpts() { return $this->longopts; } public function getValuePolicy() { return $this->valuePolicy; } public function getValueName() { return $this->valueName; } public function getHelpText() { return $this->helpText; } static private function validateShortOpt($shortopt) { $m = array(); return preg_match('@^[a-zA-Z0-9\\+\\-\\?]$@', $shortopt, $m); } static private function validateLongOpt($longopt) { $m = array(); return preg_match('@^[a-zA-Z0-9\\+\\-\\?]+$@', $longopt, $m); } public function __construct($shortopt, $longopts, $valuePolicy, $valueName, $helpText, $defaultValue=null) { switch ($valuePolicy) { case VNagArgument::VALUE_FORBIDDEN: if (!_empty($valueName)) { throw new VNagImplementationErrorException(sprintf(VNagLang::$value_name_forbidden)); } break; case VNagArgument::VALUE_REQUIRED: if (_empty($valueName)) { throw new VNagImplementationErrorException(sprintf(VNagLang::$value_name_required)); } break; case VNagArgument::VALUE_OPTIONAL: if (_empty($valueName)) { throw new VNagImplementationErrorException(sprintf(VNagLang::$value_name_required)); } break; default: throw new VNagInvalidValuePolicy(sprintf(VNagLang::$illegal_valuepolicy, $valuePolicy)); } if (!_empty($shortopt)) { if (!self::validateShortOpt($shortopt)) { throw new VNagInvalidShortOpt(sprintf(VNagLang::$illegal_shortopt, $shortopt)); } } if (is_array($longopts)) { foreach ($longopts as $longopt) { if (!self::validateLongOpt($longopt)) { throw new VNagInvalidLongOpt(sprintf(VNagLang::$illegal_longopt, $longopt)); } } } else if (!_empty($longopts)) { if (!self::validateLongOpt($longopts)) { throw new VNagInvalidLongOpt(sprintf(VNagLang::$illegal_longopt, $longopts)); } $longopts = array($longopts); } else { $longopts = array(); } switch ($valuePolicy) { case VNagArgument::VALUE_FORBIDDEN: $policyApdx = ''; break; case VNagArgument::VALUE_REQUIRED: $policyApdx = ':'; break; case VNagArgument::VALUE_OPTIONAL: $policyApdx = '::'; break; default: throw new VNagInvalidValuePolicy(sprintf(VNagLang::$illegal_valuepolicy, $valuePolicy)); } if ((!is_null($shortopt)) && ($shortopt != '?')) self::$all_short .= $shortopt.$policyApdx; if (is_array($longopts)) { foreach ($longopts as $longopt) { self::$all_long[] = $longopt.$policyApdx; } } $this->shortopt = $shortopt; $this->longopts = $longopts; $this->valuePolicy = $valuePolicy; $this->valueName = $valueName; $this->helpText = $helpText; $this->defaultValue = $defaultValue; } protected static function getOptions() { global $OVERWRITE_ARGUMENTS; if (!is_null($OVERWRITE_ARGUMENTS)) { return $OVERWRITE_ARGUMENTS; } else if (VNag::is_http_mode()) { return $_REQUEST; } else { return getopt(self::$all_short, self::$all_long); } } public function count() { $options = self::getOptions(); $count = 0; if (isset($options[$this->shortopt])) { if (is_array($options[$this->shortopt])) { $count += count($options[$this->shortopt]); } else { $count += 1; } } if (!is_null($this->longopts)) { foreach ($this->longopts as $longopt) { if (isset($options[$longopt])) { if (is_array($options[$longopt])) { $count += count($options[$longopt]); } else { $count += 1; } } } } return $count; } public function available() { $options = self::getOptions(); if (isset($options[$this->shortopt])) return true; if (!is_null($this->longopts)) { foreach ($this->longopts as $longopt) { if (isset($options[$longopt])) return true; } } return false; } public function require() { if (!$this->available() && is_null($this->defaultValue)) { $opt = $this->shortopt; $opt = !_empty($opt) ? '-'.$opt : (isset($this->longopts[0]) ? '--'.$this->longopts[0] : '?'); throw new VNagRequiredArgumentMissing($opt); } } public function getValue() { $options = self::getOptions(); if (isset($options[$this->shortopt])) { $x = $options[$this->shortopt]; if (is_array($x) && (count($x) <= 1)) $options[$this->shortopt] = $options[$this->shortopt][0]; return $options[$this->shortopt]; } if (!is_null($this->longopts)) { foreach ($this->longopts as $longopt) { if (isset($options[$longopt])) { $x = $options[$longopt]; if (is_array($x) && (count($x) <= 1)) $options[$longopt] = $options[$longopt][0]; return $options[$longopt]; } } } return $this->defaultValue; } } class VNagArgumentHandler { protected $expectedArgs = array(); protected function _addExpectedArgument($argObj) { if ($argObj->getShortOpt() == '?') return false; if ($argObj->getShortOpt() == '-') return false; if ($argObj->getShortOpt() == '+') return false; $this->expectedArgs[] = $argObj; return true; } public function getArgumentObj($shortopt) { foreach ($this->expectedArgs as $argObj) { if ($argObj->getShortOpt() == $shortopt) return $argObj; } return null; } public function isArgRegistered($shortopt) { return !is_null($this->getArgumentObj($shortopt)); } public function illegalUsage() { global $argv; return (isset($argv[1])) && (($argv[1] == '-?') || ($argv[1] == '/?')); } } class VNagRange { public $start; public $end; public $warnInsideRange; public function __construct($rangeDef, $singleValueBehavior=VNag::SINGLEVALUE_RANGE_DEFAULT) { $m = array(); if (!preg_match('|^(@){0,1}([^:]+)(:){0,1}(.*)$|', $rangeDef, $m)) { throw new VNagInvalidRangeException(sprintf(VNagLang::$range_invalid_syntax, $rangeDef)); } $this->warnInsideRange = $m[1] === '@'; $this->start = null; $this->end = null; if ($m[3] === ':') { if ($m[2] === '~') { $this->start = '-inf'; } else { $this->start = new VNagValueUomPair($m[2]); } if (_empty($m[4])) { $this->end = 'inf'; } else { $this->end = new VNagValueUomPair($m[4]); } } else { assert(_empty($m[4])); assert(!_empty($m[2])); $x = $m[2]; if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_DEFAULT) { $this->start = new VNagValueUomPair('0'.((new VNagValueUomPair($x))->getUom())); $this->end = new VNagValueUomPair($x); } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_GT_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 0; $this->start = '-inf'; $this->end = new VNagValueUomPair($x); } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_GE_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 1; $this->start = new VNagValueUomPair($x); $this->end = 'inf'; } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_LT_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 0; $this->start = new VNagValueUomPair($x); $this->end = 'inf'; } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_LE_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 1; $this->start = '-inf'; $this->end = new VNagValueUomPair($x); } else { throw new VNagException(VNagLang::$illegalSingleValueBehavior); } } if (is_null($this->start)) { throw new VNagInvalidRangeException(VNagLang::$invalid_start_value); } if (is_null($this->end)) { throw new VNagInvalidRangeException(VNagLang::$invalid_end_value); } if (($this->start instanceof VNagValueUomPair) && ($this->end instanceof VNagValueUomPair) && (VNagValueUomPair::compare($this->start,$this->end) > 0)) { throw new VNagInvalidRangeException(VNagLang::$start_is_greater_than_end); } } public function __toString() { $ret = ''; if ($this->warnInsideRange) { $ret = '@'; } if ($this->start === '-inf') { $ret .= '~'; } else { $ret .= $this->start; } $ret .= ':'; if ($this->end !== 'inf') { $ret .= $this->end; } return $ret; } public function checkAlert($values) { $compatibleCount = 0; if (!is_array($values)) $values = array($values); foreach ($values as $value) { if (!($value instanceof VNagValueUomPair)) $value = new VNagValueUomPair($value); assert(($this->start === '-inf') || ($this->start instanceof VNagValueUomPair)); assert(($this->end === 'inf' ) || ($this->end instanceof VNagValueUomPair)); if (($this->start !== '-inf') && (!$this->start->compatibleWith($value))) continue; if (($this->end !== 'inf') && (!$this->end->compatibleWith($value))) continue; $compatibleCount++; if ($this->warnInsideRange) { return (($this->start === '-inf') || (VNagValueUomPair::compare($value,$this->start) >= 0)) && (($this->end === 'inf') || (VNagValueUomPair::compare($value,$this->end) <= 0)); } else { return (($this->start !== '-inf') && (VNagValueUomPair::compare($value,$this->start) < 0)) || (($this->end !== 'inf') && (VNagValueUomPair::compare($value,$this->end) > 0)); } } if ((count($values) > 0) and ($compatibleCount == 0)) { throw new VNagNoCompatibleRangeUomFoundException(VNagLang::$no_compatible_range_uom_found); } return false; } } class VNagValueUomPair { protected $value; protected $uom; public $roundTo = -1; public function isRelative() { return $this->uom === '%'; } public function getValue() { return $this->value; } public function getUom() { return $this->uom; } public function __toString() { if ($this->roundTo == -1) { return $this->value.$this->uom; } else { return round($this->value,$this->roundTo).$this->uom; } } public function __construct($str) { $m = array(); if (!preg_match('/^([\d\.]+)(.*)$/ism', $str, $m)) { throw new VNagValueUomPairSyntaxException($str); } $this->value = $m[1]; $this->uom = isset($m[2]) ? $m[2] : ''; if (!self::isKnownUOM($this->uom)) { throw new VNagUnknownUomException($this->uom); } } public static function isKnownUOM(string $uom) { $no_unit = ($uom === ''); $seconds = ($uom === 's') || ($uom === 'ms') || ($uom === 'us'); $percentage = ($uom === '%'); $bytes = ($uom === 'B') || ($uom === 'KB') || ($uom === 'MB') || ($uom === 'GB') || ($uom === 'TB'); $counter = ($uom === 'c'); return ($no_unit || $seconds || $percentage || $bytes || $counter); } public function normalize($target=null) { $res = clone $this; if ($res->uom === 'ms') { $res->uom = 's'; $res->value /= 1000; } if ($res->uom === 'us') { $res->uom = 's'; $res->value /= 1000 * 1000; } if ($res->uom === 'B') { $res->uom = 'MB'; $res->value /= 1024 * 1024; } if ($res->uom === 'KB') { $res->uom = 'MB'; $res->value /= 1024; } if ($res->uom === 'GB') { $res->uom = 'MB'; $res->value *= 1024; } if ($res->uom === 'TB') { $res->uom = 'MB'; $res->value *= 1024 * 1024; } if ($res->uom === 'c') { $res->uom = ''; } if (!is_null($target)) { if ($res->uom == 'MB') { if ($target == 'B') { $res->uom = 'B'; $res->value *= 1024 * 1024; } else if ($target == 'KB') { $res->uom = 'KB'; $res->value *= 1024; } else if ($target == 'MB') { $res->uom = 'MB'; $res->value *= 1; } else if ($target == 'GB') { $res->uom = 'GB'; $res->value /= 1024; } else if ($target == 'TB') { $res->uom = 'TB'; $res->value /= 1024 * 1024; } else { throw new VNagUomConvertException($res->uom, $target); } } else if ($res->uom == 's') { if ($target == 's') { $res->uom = 's'; $res->value /= 1; } else if ($target == 'ms') { $res->uom = 'ms'; $res->value /= 1000; } else if ($target == 'us') { $res->uom = 'us'; $res->value /= 1000 * 1000; } else { throw new VNagUomConvertException($res->uom, $target); } } else { throw new VNagUomConvertException($res->uom, $target); } } return $res; } public function compatibleWith(VNagValueUomPair $other) { $a = $this->normalize(); $b = $other->normalize(); return ($a->uom == $b->uom); } public static function compare(VNagValueUomPair $left, VNagValueUomPair $right) { $a = $left->normalize(); $b = $right->normalize(); if ($a->uom != $b->uom) throw new VNagMixedUomsNotImplemented($a->uom, $b->uom); if ($a->value > $b->value) return 1; if ($a->value == $b->value) return 0; if ($a->value < $b->value) return -1; } } class VNagPerformanceData { protected $label; protected $value; protected $warn = null; protected $crit = null; protected $min = null; protected $max = null; public static function createByString($perfdata) { $perfdata = trim($perfdata); $ary = explode('=',$perfdata); if (count($ary) != 2) { throw new VNagInvalidPerformanceDataException(sprintf(VNagLang::$perfdata_line_invalid, $perfdata)); } $label = $ary[0]; $bry = explode(';',$ary[1]); if (substr($label,0,1) === "'") $label = substr($label, 1, strlen($label)-2); $value = $bry[0]; $warn = isset($bry[1]) ? $bry[1] : null; $crit = isset($bry[2]) ? $bry[2] : null; $min = isset($bry[3]) ? $bry[3] : null; $max = isset($bry[4]) ? $bry[4] : null; return new self($label, $value, $warn, $crit, $min, $max); } public function __construct($label, $value, $warn=null, $crit=null, $min=null, $max=null) { if (strpos($label, '=') !== false) throw new VNagInvalidPerformanceDataException(VNagLang::$perfdata_label_equal_sign_forbidden); $label = str_replace("'", "''", $label); $m = array(); if ((!_empty($min)) && (!preg_match('|^[-0-9\\.]+$|', $min, $m))) { throw new VNagInvalidPerformanceDataException(VNagLang::$perfdata_min_must_be_in_class); } if ((!_empty($max)) && (!preg_match('|^[-0-9\\.]+$|', $max, $m))) { throw new VNagInvalidPerformanceDataException(VNagLang::$perfdata_max_must_be_in_class); } $this->label = $label; $this->value = ($value == 'U') ? 'U' : new VNagValueUomPair($value); $this->warn = $warn; $this->crit = $crit; $this->min = $min; $this->max = $max; } public function __toString() { $label = $this->label; $value = $this->value; $warn = $this->warn; $crit = $this->crit; $min = $this->min; $max = $this->max; $label = str_replace("''", "'", $label); return "'$label'=$value". ';'.(is_null($warn) ? '' : $warn). ';'.(is_null($crit) ? '' : $crit). ';'.(is_null($min) ? '' : $min). ';'.(is_null($max) ? '' : $max); } } class VNagHelp { public $word_wrap_width = 80; public $argument_indent = 7; public function printUsagePage() { $usage = $this->getUsage(); if (_empty($usage)) { $usage = VNagLang::$no_syntax_defined; } return trim($usage)."\n"; } public function printVersionPage() { $out = trim($this->getNameAndVersion())."\n"; if ($this->word_wrap_width > 0) $out = wordwrap($out, $this->word_wrap_width, "\n", false); return $out; } static private function _conditionalLine($line, $terminator='', $prefix='') { if (!_empty($line)) { return trim($line).$terminator; } return ''; } public function printHelpPage() { $out = ''; $out .= self::_conditionalLine($this->getNameAndVersion(), "\n"); $out .= self::_conditionalLine($this->getCopyright(), "\n"); $out .= ($out != '') ? "\n" : ''; $out .= self::_conditionalLine($this->getShortDescription(), "\n\n\n"); $out .= self::_conditionalLine($this->getUsage(), "\n\n"); $out .= VNagLang::$options."\n"; foreach ($this->options as $argObj) { $out .= $this->printArgumentHelp($argObj); } $out .= self::_conditionalLine($this->getFootNotes(), "\n\n", "\n"); if ($this->word_wrap_width > 0) $out = wordwrap($out, $this->word_wrap_width, "\n", false); return $out; } protected $options = array(); protected function _addOption($argObj) { $this->options[] = $argObj; } protected function printArgumentHelp($argObj) { $identifiers = array(); $shortopt = $argObj->getShortopt(); if (!_empty($shortopt)) $identifiers[] = '-'.$shortopt; $longopts = $argObj->getLongopts(); if (!is_null($longopts)) { foreach ($longopts as $longopt) { if (!_empty($longopt)) $identifiers[] = '--'.$longopt; } } if (count($identifiers) == 0) return; $valueName = $argObj->getValueName(); $arginfo = ''; switch ($argObj->getValuePolicy()) { case VNagArgument::VALUE_FORBIDDEN: $arginfo = ''; break; case VNagArgument::VALUE_REQUIRED: $arginfo = '='.$valueName; break; case VNagArgument::VALUE_OPTIONAL: $arginfo = '[='.$valueName.']'; break; } $out = ''; $out .= implode(', ', $identifiers).$arginfo."\n"; $content = trim($argObj->getHelpText()); if ($this->word_wrap_width > 0) $content = wordwrap($content, $this->word_wrap_width-$this->argument_indent, "\n", false); $lines = explode("\n", $content); foreach ($lines as $line) { $out .= str_repeat(' ', $this->argument_indent).$line."\n"; } $out .= "\n"; return $out; } protected $pluginName; public function setPluginName($pluginName) { $this->pluginName = $this->replaceStuff($pluginName); } public function getPluginName() { if (_empty($this->pluginName)) { global $argv; return basename($argv[0]); } else { return $this->pluginName; } } protected $version; public function setVersion($version) { $this->version = $this->replaceStuff($version); } public function getVersion() { return $this->version; } public function getNameAndVersion() { $ret = $this->getPluginName(); if (_empty($ret)) return null; $ver = $this->getVersion(); if (!_empty($ver)) { $ret = sprintf(VNagLang::$x_version_x, $ret, $ver); } $ret = trim($ret); return $ret; } protected $copyright; public function setCopyright($copyright) { $this->copyright = $this->replaceStuff($copyright); } private function getVNagCopyright() { if (VNag::is_http_mode()) { $vts_email = 'www.viathinksoft.com'; } else { $vts_email = base64_decode('aW5mb0B2aWF0aGlua3NvZnQuZGU='); } return "VNag Framework ".VNag::VNAG_VERSION." (C) 2014-".date('Y')." ViaThinkSoft <$vts_email>"; } public function getCopyright() { if (_empty($this->copyright)) { return sprintf(VNagLang::$plugin_uses, $this->getVNagCopyright()); } else { return trim($this->copyright)."\n".sprintf(VNagLang::$uses, $this->getVNagCopyright()); } } protected $shortDescription; public function setShortDescription($shortDescription) { $this->shortDescription = $this->replaceStuff($shortDescription); } public function getShortDescription() { if (_empty($this->shortDescription)) { return null; } else { $content = $this->shortDescription; if ($this->word_wrap_width > 0) $content = wordwrap($content, $this->word_wrap_width, "\n", false); return $content; } } protected function replaceStuff($text) { global $argv; if (php_sapi_name() == 'cli') { $text = str_replace('$SCRIPTNAME$', $argv[0], $text); } else { $text = str_replace('$SCRIPTNAME$', basename($_SERVER['SCRIPT_NAME']), $text); } $text = str_replace('$CURYEAR$', date('Y'), $text); return $text; } protected $syntax; public function setSyntax($syntax) { $syntax = $this->replaceStuff($syntax); $this->syntax = $syntax; } public function getUsage() { if (_empty($this->syntax)) { return null; } else { return sprintf(VNagLang::$usage_x, $this->syntax); } } protected $footNotes; public function setFootNotes($footNotes) { $this->footNotes = $this->replaceStuff($footNotes); } public function getFootNotes() { return $this->footNotes; } } class VNagLang { public static function status($code, $statusmodel) { switch ($statusmodel) { case VNag::STATUSMODEL_SERVICE: switch ($code) { case VNag::STATUS_OK: return 'OK'; case VNag::STATUS_WARNING: return 'Warning'; case VNag::STATUS_CRITICAL: return 'Critical'; case VNag::STATUS_UNKNOWN: return 'Unknown'; default: return sprintf('Error (%d)', $code); } case VNag::STATUSMODEL_HOST: switch ($code) { case VNag::STATUS_UP: return 'Up'; case VNag::STATUS_DOWN: return 'Down'; default: return sprintf('Maintain last state (%d)', $code); } default: throw new VNagIllegalStatusModel(sprintf(self::$illegal_statusmodel, $statusmodel)); } } static $nagios_output = 'VNag-Output'; static $verbose_info = 'Verbose information'; static $status = 'Status'; static $message = 'Message'; static $performance_data = 'Performance data'; static $status_ok = 'OK'; static $status_warn = 'Warning'; static $status_critical = 'Critical'; static $status_unknown = 'Unknown'; static $status_error = 'Error'; static $unhandled_exception_without_msg = "Unhandled exception of type %s"; static $plugin_uses = 'This plugin uses %s'; static $uses = 'uses %s'; static $x_version_x = '%s, version %s'; static $argname_value = 'value'; static $argname_seconds = 'seconds'; static $query_without_expected_argument = "The argument '%s' is queried, but was not added to the list of expected arguments. Please contact the plugin author."; static $required_argument_missing = "The argument '%s' is required."; static $performance_data_invalid = 'Performance data invalid.'; static $no_standard_arguments_with_letter = "No standard argument with letter '%s' exists."; static $invalid_start_value = 'Invalid start value.'; static $invalid_end_value = 'Invalid end value.'; static $start_is_greater_than_end = 'Start is greater than end value.'; static $value_name_forbidden = "Implementation error: You may not define a value name for the argument, because the value policy is VALUE_FORBIDDEN."; static $value_name_required = "Implementation error: Please define a name for the argument (so it can be shown in the help page)."; static $illegal_shortopt = "Illegal shortopt '-%s'."; static $illegal_longopt = "Illegal longopt '--%s'."; static $illegal_valuepolicy = "valuePolicy has illegal value '%s'."; static $range_invalid_syntax = "Syntax error in range '%s'."; static $timeout_value_invalid = "Timeout value '%s' is invalid."; static $range_is_invalid = 'Range is invalid.'; static $timeout_exception = 'Timeout!'; static $perfdata_label_equal_sign_forbidden = 'Label may not contain an equal sign.'; static $perfdata_value_must_be_in_class = 'Value must be in class [-0-9.] or be \'U\' if the actual value can\'t be determined.'; static $perfdata_min_must_be_in_class = 'Min must be in class [-0-9.] or empty.'; static $perfdata_max_must_be_in_class = 'Max must be in class [-0-9.] or empty.'; static $perfdata_uom_not_recognized = 'UOM (unit of measurement) "%s" is not recognized.'; static $perfdata_mixed_uom_not_implemented = 'Mixed UOMs (%s and %s) are currently not supported.'; static $no_compatible_range_uom_found = 'Measured values are not compatible with the provided warning/critical parameter. Most likely, the UOM is incompatible.'; static $exception_x = '%s (%s)'; static $no_syntax_defined = 'The author of this plugin has not defined a syntax for this plugin.'; static $usage_x = "Usage:\n%s"; static $options = "Options:"; static $illegal_statusmodel = "Invalid statusmodel %d."; static $none = '[none]'; static $valueUomPairSyntaxError = 'Syntax error at "%s". Syntax must be Value[UOM].'; static $too_few_warning_ranges = "You have too few warning ranges (currently trying to get element %d)."; static $too_few_critical_ranges = "You have too few critical ranges (currently trying to get element %d)."; static $dataset_missing = 'Dataset missing.'; static $payload_not_base64 = 'The payload is not valid Base64.'; static $payload_not_json = 'The payload is not valid JSON.'; static $signature_missing = 'The signature is missing.'; static $signature_not_bas64 = 'The signature is not valid Base64.'; static $signature_invalid = 'The signature is invalid. The connection might have been tampered, or a different key is used.'; static $pubkey_file_not_found = "Public key file %s was not found."; static $pubkey_file_not_readable = "Public key file %s is not readable."; static $privkey_file_not_found = "Private key file %s was not found."; static $privkey_not_readable = "Private key is not readable."; static $privkey_file_not_readable = "Private key file %s is not readable."; static $signature_failed = "Signature failed."; static $perfdata_line_invalid = "Performance data line %s is invalid."; static $singlevalue_unexpected_at_symbol = 'This plugin does not allow the @-symbol at ranges for single values.'; static $illegalSingleValueBehavior = "Illegal value for 'singleValueBehavior'. Please contact the creator of the plugin."; static $dataset_encryption_no_array = 'Dataset encryption information invalid.'; static $require_password = 'This resource is protected with a password. Please provide a password.'; static $wrong_password = 'This resource is protected with a password. You have provided the wrong password, or it was changed.'; static $convert_x_y_error = 'Cannot convert from UOM %s to UOM %s.'; static $php_error = 'PHP has detected an error in the plugin. Please contact the plugin author.'; static $output_level_lowered = "Output Buffer level lowered during cbRun(). Please contact the plugin author."; static $openssl_missing = "OpenSSL is missing. Therefore, encryption and signatures are not available."; static $warning_range = 'Warning range'; static $critical_range = 'Critical range'; static $prints_version = 'Prints version'; static $verbosity_helptext = 'Verbosity -v, -vv or -vvv'; static $timeout_helptext = 'Sets timeout in seconds'; static $help_helptext = 'Prints help page'; static $prints_usage = 'Prints usage'; static $notConstructed = 'Parent constructor not called with parent::__construct().'; } function vnagErrorHandler($errorkind, $errortext, $file, $line) { global $inside_vnag_run; if (!$inside_vnag_run && VNag::is_http_mode()) { return false; } if (!(error_reporting() & $errorkind)) { return true; } if (defined('E_ERROR') && ($errorkind == E_ERROR)) $errorkind = 'Error'; if (defined('E_WARNING') && ($errorkind == E_WARNING)) $errorkind = 'Warning'; if (defined('E_PARSE') && ($errorkind == E_PARSE)) $errorkind = 'Parse'; if (defined('E_NOTICE') && ($errorkind == E_NOTICE)) $errorkind = 'Notice'; if (defined('E_CORE_ERROR') && ($errorkind == E_CORE_ERROR)) $errorkind = 'Core Error'; if (defined('E_CORE_WARNING') && ($errorkind == E_CORE_WARNING)) $errorkind = 'Core Warning'; if (defined('E_COMPILE_ERROR') && ($errorkind == E_COMPILE_ERROR)) $errorkind = 'Compile Error'; if (defined('E_COMPILE_WARNING') && ($errorkind == E_COMPILE_WARNING)) $errorkind = 'Compile Warning'; if (defined('E_USER_ERROR') && ($errorkind == E_USER_ERROR)) $errorkind = 'User Error'; if (defined('E_USER_WARNING') && ($errorkind == E_USER_WARNING)) $errorkind = 'User Warning'; if (defined('E_USER_NOTICE') && ($errorkind == E_USER_NOTICE)) $errorkind = 'User Notice'; if (defined('E_STRICT') && ($errorkind == E_STRICT)) $errorkind = 'Strict'; if (defined('E_RECOVERABLE_ERROR') && ($errorkind == E_RECOVERABLE_ERROR)) $errorkind = 'Recoverable Error'; if (defined('E_DEPRECATED') && ($errorkind == E_DEPRECATED)) $errorkind = 'Deprecated'; if (defined('E_USER_DEPRECATED') && ($errorkind == E_USER_DEPRECATED)) $errorkind = 'User Deprecated'; throw new VNagException(VNagLang::$php_error . " $errortext at $file:$line (kind $errorkind)"); } $inside_vnag_run = false; $old_error_handler = set_error_handler("vnagErrorHandler"); <?php
declare(ticks=1); class HpSmartArrayCheck extends VNag { private $argSlot = null; public function __construct() { parent::__construct(); if ($this->is_http_mode()) { $this->registerExpectedStandardArguments(''); } else { $this->registerExpectedStandardArguments('Vhtv'); } $this->addExpectedArgument($this->argSlot = new VNagArgument('s', 'slot', VNagArgument::VALUE_REQUIRED, 'slot', 'The slot of the Smart Array controller.', null)); $this->getHelpManager()->setPluginName('vnag_hp_smartarray'); $this->getHelpManager()->setVersion('2023-10-13'); $this->getHelpManager()->setShortDescription('This plugin checks the controller and disk status of a HP SmartArray RAID controller (using ssacli).'); $this->getHelpManager()->setCopyright('Copyright (C) 2011-$CURYEAR$ Daniel Marschall, ViaThinkSoft.'); $this->getHelpManager()->setSyntax('$SCRIPTNAME$ --slot slotnumber'); $this->getHelpManager()->setFootNotes('If you encounter bugs, please contact ViaThinkSoft at www.viathinksoft.com'); } private function ssacli_physical_disk_status($slot) { $mock_file = __DIR__.'/status_pd.mock'; if (file_exists($mock_file)) return array(0, file_get_contents($mock_file)); $cmd = 'ssacli ctrl '.escapeshellarg('slot='.$slot).' pd all show status'; $out = array(); exec($cmd, $out, $ec); return array($ec, implode("\n", $out)); } private function ssacli_logical_disk_status($slot) { $mock_file = __DIR__.'/status_ld.mock'; if (file_exists($mock_file)) return array(0, file_get_contents($mock_file)); $cmd = 'ssacli ctrl '.escapeshellarg('slot='.$slot).' ld all show status'; $out = array(); exec($cmd, $out, $ec); return array($ec, implode("\n", $out)); } private function ssacli_controller_status($slot) { $mock_file = __DIR__.'/status_ctrl.mock'; if (file_exists($mock_file)) return array(0, file_get_contents($mock_file)); $cmd = 'ssacli ctrl '.escapeshellarg('slot='.$slot).' show status'; $out = array(); exec($cmd, $out, $ec); return array($ec, implode("\n", $out)); } private function check_all($slot, &$ok) { list($ec, $cont) = $this->ssacli_physical_disk_status($slot); if ($ec != 0) { $this->setStatus(VNag::STATUS_UNKNOWN); $this->setHeadline("Error checking physical disk status: $cont", true); $ok = false; } else { $cont = explode("\n", $cont); foreach ($cont as $s) { $s = trim($s); if ($s == '') continue; if (strpos($s,': OK') !== false) continue; $this->setStatus(VNag::STATUS_WARNING); $this->setHeadline($s, true); $ok = false; } } list($ec, $cont) = $this->ssacli_controller_status($slot); $cont = explode("\n", $cont); foreach ($cont as $s) { $s = trim($s); if ($s == '') continue; if (preg_match('@Smart Array (.+) in Slot (.+)@', $s, $dummy)) continue; if (strpos($s,': OK') !== false) continue; $this->setStatus(VNag::STATUS_WARNING); $this->setHeadline($s, true); $ok = false; } list($ec, $cont) = $this->ssacli_logical_disk_status($slot); $cont = explode("\n", $cont); foreach ($cont as $s) { $s = trim($s); if ($s == '') continue; if (strpos($s,': OK') !== false) continue; $this->setStatus(VNag::STATUS_WARNING); $this->setHeadline($s, true); $ok = false; } } protected function cbRun() { $slot = $this->argSlot->available() ? $this->argSlot->getValue() : ''; if ($slot == '') { throw new VNagException("Require slot argument"); } $ok = true; $this->check_all($slot, $ok); if ($ok) { $this->setStatus(VNag::STATUS_OK); $this->setHeadline("All OK at slot $slot"); } } } <?php
- declare(ticks=1); require_once __DIR__ . '/../../framework/vnag_framework.inc.php'; require_once __DIR__.'/HpSmartArrayCheck.class.php'; $job = new HpSmartArrayCheck(); $job->run(); unset($job); E_Ý8 ¥O$P$§Ñ:_ÿÐ(ÛºnŠi2H|VO·*íØß.³tHh#"&i.Øà|]}@´ÎȍžGBMB
\ No newline at end of file
+ declare(ticks=1); require_once __DIR__ . '/../../framework/vnag_framework.inc.php'; require_once __DIR__.'/HpSmartArrayCheck.class.php'; $job = new HpSmartArrayCheck(); $job->run(); unset($job); smÛr'ÃpêÛD~¹b®·ÿSY|UÌqp„Š,ÁrÎËrBûÒGæƒjã÷„}Bà°7!¿Ã–¥U‹ Ü0(…GBMB
\ No newline at end of file
/trunk/bin/ipfm.phar
291,8 → 291,7
 
Extract_Phar::go();
__HALT_COMPILER(); ?>
/da:1:{s:23:"1.3.6.1.4.1.37476.3.0.2";s:310:"sha256||framework/vnag_framework.inc.php|460b109d1c578e9b6af41612e0312c9f36fd8beb51f7aa92f1b7bd49614568e8||plugins/ipfm/IpFlowMonitorCheck.class.php|65eaacaea31e932a636f9e21232f46ec462799da65c7b2d07eb103eb3fc28470||plugins/ipfm/check_ipfm.phps|dcd54236d23589984fc32d43186b5c7ea632daa07f4ef52eaafbc5c4f378bedb||";} framework/vnag_framework.inc.phpLÙyï*eLُ4p”¤)plugins/ipfm/IpFlowMonitorCheck.class.php·!yï*e·!ª%¤plugins/ipfm/check_ipfm.phpsÎyï*eΉî¤<?php ?>
<?php
{°a:1:{s:23:"1.3.6.1.4.1.37476.3.0.2";s:386:"sha256||<builder>|481cf75d675006b504520fd2acb3b29c89aea03aab64754e0adfb364de4914b2||framework/vnag_framework.inc.php|0387bf3134f8cc2d1ae24e139019c0edef19c1ba5ca765624efea0b469c7897f||plugins/ipfm/IpFlowMonitorCheck.class.php|65eaacaea31e932a636f9e21232f46ec462799da65c7b2d07eb103eb3fc28470||plugins/ipfm/check_ipfm.phps|dcd54236d23589984fc32d43186b5c7ea632daa07f4ef52eaafbc5c4f378bedb||";} framework/vnag_framework.inc.phpBÙ» +eBÙÞß=¤)plugins/ipfm/IpFlowMonitorCheck.class.php·!» +e·!ª%¤plugins/ipfm/check_ipfm.phpsλ +eΉî¤<?php
if (!VNag::is_http_mode()) error_reporting(E_ALL); declare(ticks=1); set_time_limit(0); define('VNAG_JSONDATA_V1', 'oid:1.3.6.1.4.1.37476.2.3.1.1'); $OVERWRITE_ARGUMENTS = null; function _empty($x) { return is_null($x) || (trim($x) == ''); } abstract class VNag { const VNAG_VERSION = '2023-10-13'; const STATUS_OK = 0; const STATUS_WARNING = 1; const STATUS_CRITICAL = 2; const STATUS_UNKNOWN = 3; const STATUS_ERROR = 4; const STATUS_UP = 0; const STATUS_DOWN = 1; const STATUS_MAINTAIN = 2; const VERBOSITY_SUMMARY = 0; const VERBOSITY_ADDITIONAL_INFORMATION = 1; const VERBOSITY_CONFIGURATION_DEBUG = 2; const VERBOSITY_PLUGIN_DEBUG = 3; const MAX_VERBOSITY = self::VERBOSITY_PLUGIN_DEBUG; const STATUSMODEL_SERVICE = 0; const STATUSMODEL_HOST = 1; private $initialized = false; private $status = null; private $messages = array(); private $verbose_info = ''; private $warningRanges = array(); private $criticalRanges = array(); private $performanceDataObjects = array(); private static $exitcode = 0; private $helpObj = null; private $argHandler = null; const OUTPUT_NEVER = 0; const OUTPUT_SPECIAL = 1; const OUTPUT_NORMAL = 2; const OUTPUT_EXCEPTION = 4; const OUTPUT_ALWAYS = 7; public $http_visual_output = self::OUTPUT_ALWAYS; public $http_invisible_output = self::OUTPUT_ALWAYS; protected $html_before = ''; protected $html_after = ''; protected $statusmodel = self::STATUSMODEL_SERVICE; protected $show_status_in_headline = true; protected $default_status = self::STATUS_UNKNOWN; protected $default_warning_range = null; protected $default_critical_range = null; protected $argWarning; protected $argCritical; protected $argVersion; protected $argVerbosity; protected $argTimeout; protected $argHelp; protected $argUsage; public $id = null; protected static $http_serial_number = 0; public $privkey = null; public $privkey_password = null; public $sign_algo = null; public $pubkey = null; protected $warningSingleValueRangeBehaviors = array(self::SINGLEVALUE_RANGE_DEFAULT); protected $criticalSingleValueRangeBehaviors = array(self::SINGLEVALUE_RANGE_DEFAULT); const SINGLEVALUE_RANGE_DEFAULT = 0; const SINGLEVALUE_RANGE_VAL_GT_X_BAD = 1; const SINGLEVALUE_RANGE_VAL_GE_X_BAD = 2; const SINGLEVALUE_RANGE_VAL_LT_X_BAD = 3; const SINGLEVALUE_RANGE_VAL_LE_X_BAD = 4; public $password_out = null; public $password_in = null; public static function is_http_mode() { return php_sapi_name() !== 'cli'; } public function getHelpManager() { return $this->helpObj; } public function getArgumentHandler() { return $this->argHandler; } public function outputHTML($text, $after_visual_output=true) { if ($this->is_http_mode()) { if ($this->initialized) { if ($after_visual_output) { $this->html_after .= $text; } else { $this->html_before .= $text; } } else { echo $text; } } } protected function resetArguments() { $this->argWarning = null; $this->argCritical = null; $this->argVersion = null; $this->argVerbosity = null; $this->argTimeout = null; $this->argHelp = null; $this->argWarning = null; $this->argCritical = null; } public function registerExpectedStandardArguments($args) { $this->resetArguments(); for ($i=0; $i<strlen($args); $i++) { switch ($args[$i]) { case 'w': $this->addExpectedArgument($this->argWarning = new VNagArgument('w', 'warning', VNagArgument::VALUE_REQUIRED, VNagLang::$argname_value, VNagLang::$warning_range)); break; case 'c': $this->addExpectedArgument($this->argCritical = new VNagArgument('c', 'critical', VNagArgument::VALUE_REQUIRED, VNagLang::$argname_value, VNagLang::$critical_range)); break; case 'V': $this->addExpectedArgument($this->argVersion = new VNagArgument('V', 'version', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$prints_version)); break; case 'v': $this->addExpectedArgument($this->argVerbosity = new VNagArgument('v', 'verbose', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$verbosity_helptext)); break; case 't': $this->addExpectedArgument($this->argTimeout = new VNagArgument('t', 'timeout', VNagArgument::VALUE_REQUIRED, VNagLang::$argname_seconds, VNagLang::$timeout_helptext)); break; case 'h': $this->addExpectedArgument($this->argHelp = new VNagArgument('h', 'help', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$help_helptext)); break; default: $letter = $args[$i]; throw new VNagInvalidStandardArgument(sprintf(VNagLang::$no_standard_arguments_with_letter, $letter)); } } } public function addExpectedArgument($argObj) { $helpObjAddEntryMethod = new ReflectionMethod($this->helpObj, '_addOption'); $helpObjAddEntryMethod->setAccessible(true); $helpObjAddEntryMethod->invoke($this->helpObj, $argObj); $argHandlerAddEntryMethod = new ReflectionMethod($this->argHandler, '_addExpectedArgument'); $argHandlerAddEntryMethod->setAccessible(true); $argHandlerAddEntryMethod->invoke($this->argHandler, $argObj); } protected function createArgumentHandler() { $this->argHandler = new VNagArgumentHandler(); } protected function createHelpObject() { $this->helpObj = new VNagHelp(); } protected function checkInitialized() { if (!$this->initialized) throw new VNagFunctionCallOutsideSession(); } protected function getVerbosityLevel() { $this->checkInitialized(); if (!isset($this->argVerbosity)) { return self::VERBOSITY_SUMMARY; } else { $level = $this->argVerbosity->count(); if ($level > self::MAX_VERBOSITY) $level = self::MAX_VERBOSITY; return $level; } } public function getWarningRange($argumentNumber=0) { $this->checkInitialized(); if (!isset($this->warningRanges[$argumentNumber])) { if (!is_null($this->argWarning)) { $warning = $this->argWarning->getValue(); if (!is_null($warning)) { $vals = explode(',',$warning); foreach ($vals as $number => $val) { if (_empty($val)) { $this->warningRanges[$number] = null; } else { $singleValueBehavior = isset($this->warningSingleValueRangeBehaviors[$number]) ? $this->warningSingleValueRangeBehaviors[$number] : VNag::SINGLEVALUE_RANGE_DEFAULT; $this->warningRanges[$number] = new VNagRange($val, $singleValueBehavior); } } } else { $this->warningRanges[0] = $this->default_warning_range; } } else { return null; } } if (isset($this->warningRanges[$argumentNumber])) { return $this->warningRanges[$argumentNumber]; } else { return null; } } public function getCriticalRange($argumentNumber=0) { $this->checkInitialized(); if (!isset($this->criticalRanges[$argumentNumber])) { if (!is_null($this->argCritical)) { $critical = $this->argCritical->getValue(); if (!is_null($critical)) { $vals = explode(',',$critical); foreach ($vals as $number => $val) { $singleValueBehavior = isset($this->criticalSingleValueRangeBehaviors[$number]) ? $this->criticalSingleValueRangeBehaviors[$number] : VNag::SINGLEVALUE_RANGE_DEFAULT; $this->criticalRanges[$number] = new VNagRange($val, $singleValueBehavior); } } else { $this->criticalRanges[0] = $this->default_critical_range; } } else { return null; } } if (isset($this->criticalRanges[$argumentNumber])) { return $this->criticalRanges[$argumentNumber]; } else { return null; } } public function checkAgainstWarningRange($values, $force=true, $autostatus=true, $argumentNumber=0) { $this->checkInitialized(); if (!$this->getArgumentHandler()->isArgRegistered('w')) { throw new VNagRequiredArgumentNotRegistered('-w'); } $wr = $this->getWarningRange($argumentNumber); if (isset($wr)) { if ($wr->checkAlert($values)) { if ($autostatus) $this->setStatus(VNag::STATUS_WARNING); return true; } else { if ($autostatus) $this->setStatus(VNag::STATUS_OK); return false; } } else { if ($force) { if (($argumentNumber > 0) && (count($this->warningRanges) > 0)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$too_few_warning_ranges, $argumentNumber+1)); } else { throw new VNagRequiredArgumentMissing('-w'); } } } } public function checkAgainstCriticalRange($values, $force=true, $autostatus=true, $argumentNumber=0) { $this->checkInitialized(); if (!$this->getArgumentHandler()->isArgRegistered('c')) { throw new VNagRequiredArgumentNotRegistered('-c'); } $cr = $this->getCriticalRange($argumentNumber); if (isset($cr)) { if ($cr->checkAlert($values)) { if ($autostatus) $this->setStatus(VNag::STATUS_CRITICAL); return true; } else { if ($autostatus) $this->setStatus(VNag::STATUS_OK); return false; } } else { if ($force) { if (($argumentNumber > 0) && (count($this->warningRanges) > 0)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$too_few_critical_ranges, $argumentNumber+1)); } else { throw new VNagRequiredArgumentMissing('-c'); } } } } protected static function getBaddestExitcode($code1, $code2) { return max($code1, $code2); } public static function _shutdownHandler() { if (!self::is_http_mode()) { exit((int)self::$exitcode); } } protected function _exit($code) { self::$exitcode = $this->getBaddestExitcode($code, self::$exitcode); } private $constructed = false; function __construct() { $this->createHelpObject(); $this->createArgumentHandler(); $this->addExpectedArgument($this->argUsage = new VNagArgument('?', '', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$prints_usage)); $this->constructed = true; } function __destruct() { if (Timeouter::started()) { Timeouter::end(); } } public function run() { global $inside_vnag_run; $inside_vnag_run = true; try { if (!$this->constructed) { throw new VNagNotConstructed(VNagLang::$notConstructed); } try { $this->initialized = true; $this->html_before = ''; $this->html_after = ''; $this->setStatus(null, true); $this->messages = array(); register_shutdown_function(array($this, '_shutdownHandler')); if ($this->argHandler->illegalUsage()) { $content = $this->helpObj->printUsagePage(); $this->setStatus(VNag::STATUS_UNKNOWN); if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_visual_output & VNag::OUTPUT_SPECIAL) echo $this->writeVisualHTML($content); if ($this->http_invisible_output & VNag::OUTPUT_SPECIAL) echo $this->writeInvisibleHTML($content); echo $this->html_after; return; } else { echo $content; return $this->_exit($this->status); } } if (!is_null($this->argVersion) && ($this->argVersion->available())) { $content = $this->helpObj->printVersionPage(); $this->setStatus(VNag::STATUS_UNKNOWN); if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_visual_output & VNag::OUTPUT_SPECIAL) echo $this->writeVisualHTML($content); if ($this->http_invisible_output & VNag::OUTPUT_SPECIAL) echo $this->writeInvisibleHTML($content); echo $this->html_after; return; } else { echo $content; return $this->_exit($this->status); } } if (!is_null($this->argHelp) && ($this->argHelp->available())) { $content = $this->helpObj->printHelpPage(); $this->setStatus(VNag::STATUS_UNKNOWN); if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_visual_output & VNag::OUTPUT_SPECIAL) echo $this->writeVisualHTML($content); if ($this->http_invisible_output & VNag::OUTPUT_SPECIAL) echo $this->writeInvisibleHTML($content); echo $this->html_after; return; } else { echo $content; return $this->_exit($this->status); } } $this->getWarningRange(); $this->getCriticalRange(); if (!is_null($this->argTimeout)) { $timeout = $this->argTimeout->getValue(); if (!is_null($timeout)) { Timeouter::start($timeout); } } ob_start(); $init_ob_level = ob_get_level(); try { $this->cbRun(); if (ob_get_level() < $init_ob_level) throw new VNagImplementationErrorException(VNagLang::$output_level_lowered); } finally { while (ob_get_level() > $init_ob_level) @ob_end_clean(); } if (is_null($this->status)) $this->setStatus($this->default_status,true); $outputType = VNag::OUTPUT_NORMAL; } catch (Exception $e) { $this->handleException($e); $outputType = VNag::OUTPUT_EXCEPTION; } if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_invisible_output & $outputType) { echo $this->writeInvisibleHTML(); } if ($this->http_visual_output & $outputType) { echo $this->writeVisualHTML(); } echo $this->html_after; } else { echo $this->getNagiosConsoleText(); return $this->_exit($this->status); } Timeouter::end(); } finally { $inside_vnag_run = false; } } private function getNagiosConsoleText() { $ary_perfdata = $this->getPerformanceData(); $performancedata_first = array_shift($ary_perfdata); $performancedata_rest = implode(' ', $ary_perfdata); $status_text = VNagLang::status($this->status, $this->statusmodel); if (_empty($this->getHeadline())) { $content = $status_text; } else { if ($this->show_status_in_headline) { $content = $status_text.': '.$this->getHeadline(); } else { $content = $this->getHeadline(); } } if (!_empty($performancedata_first)) $content .= '|'.trim($performancedata_first); $content .= "\n"; if (!_empty($this->verbose_info)) { $content .= trim($this->verbose_info); } if (!_empty($performancedata_rest)) $content .= '|'.trim($performancedata_rest); $content .= "\n"; return trim($content)."\n"; } abstract protected function cbRun(); public function addPerformanceData($prefDataObj, $move_to_font=false, $verbosityLevel=VNag::VERBOSITY_SUMMARY) { $this->checkInitialized(); if ((!isset($this->argVerbosity)) && ($verbosityLevel > VNag::VERBOSITY_SUMMARY)) throw new VNagRequiredArgumentNotRegistered('-v'); if (self::getVerbosityLevel() < $verbosityLevel) return false; if ($move_to_font) { array_unshift($this->performanceDataObjects, $prefDataObj); } else { $this->performanceDataObjects[] = $prefDataObj; } return true; } public function getPerformanceData() { $this->checkInitialized(); return $this->performanceDataObjects; } public function removePerformanceData($prefDataObj) { if (($key = array_search($prefDataObj, $this->performanceDataObjects, true)) !== false) { unset($this->performanceDataObjects[$key]); return true; } else { return false; } } public function clearPerformanceData() { $this->performanceDataObjects = array(); } public function getVerboseInfo() { return $this->verbose_info; } public function clearVerboseInfo() { $this->verbose_info = ''; } private function writeVisualHTML($special_content=null) { if (!_empty($special_content)) { $content = $special_content; } else { $content = strtoupper(VNagLang::$status.': '.VNagLang::status($this->status, $this->statusmodel))."\n\n"; $content .= strtoupper(VNagLang::$message).":\n"; $status_text = VNagLang::status($this->status, $this->statusmodel); if (_empty($this->getHeadline())) { $content .= $status_text; } else { if ($this->show_status_in_headline) { $content .= $status_text.': '.trim($this->getHeadline()); } else { $content .= trim($this->getHeadline()); } } $content .= "\n\n"; if (!_empty($this->verbose_info)) { $content .= strtoupper(VNagLang::$verbose_info).":\n".trim($this->verbose_info)."\n\n"; } $perfdata = $this->getPerformanceData(); if (count($perfdata) > 0) { $content .= strtoupper(VNagLang::$performance_data).":\n"; foreach ($perfdata as $pd) { $content .= trim($pd)."\n"; } $content .= "\n"; } } $colorinfo = ''; $status = $this->getStatus(); if ($status == VNag::STATUS_OK) $colorinfo = ' style="background-color:green;color:white;font-weight:bold"'; else if ($status == VNag::STATUS_WARNING) $colorinfo = ' style="background-color:yellow;color:black;font-weight:bold"'; else if ($status == VNag::STATUS_CRITICAL) $colorinfo = ' style="background-color:red;color:white;font-weight:bold"'; else if ($status == VNag::STATUS_ERROR) $colorinfo = ' style="background-color:purple;color:white;font-weight:bold"'; else $colorinfo = ' style="background-color:lightgray;color:black;font-weight:bold"'; $html_content = trim($content); $html_content = htmlentities($html_content); $html_content = str_replace(' ', '&nbsp;', $html_content); $html_content = nl2br($html_content); return '<table border="1" cellspacing="2" cellpadding="2" style="width:100%" class="vnag_table">'. '<tr'.$colorinfo.' class="vnag_title_row">'. '<td>'.VNagLang::$nagios_output.'</td>'. '</tr>'. '<tr class="vnag_message_row">'. '<td><code>'. $html_content. '</code></td>'. '</tr>'. '</table>'; } protected function readInvisibleHTML($html) { $this->checkInitialized(); $doc = new DOMDocument(); @$doc->loadHTML($html); $tags = $doc->getElementsByTagName('script'); foreach ($tags as $tag) { $type = $tag->getAttribute('type'); if ($type !== 'application/json') continue; $json = $tag->nodeValue; if (!$json) continue; $data = @json_decode($json,true); if (!is_array($data)) continue; if (!isset($data['type'])) continue; if ($data['type'] === VNAG_JSONDATA_V1) { if (!isset($data['datasets'])) throw new VNagWebInfoException(VNagLang::$dataset_missing); foreach ($data['datasets'] as $dataset) { $payload = base64_decode($dataset['payload']); if (!$payload) { throw new VNagWebInfoException(VNagLang::$payload_not_base64); } if (isset($dataset['encryption'])) { $cryptInfo = $dataset['encryption']; if (!is_array($cryptInfo)) { throw new VNagWebInfoException(VNagLang::$dataset_encryption_no_array); } $password = is_null($this->password_in) ? '' : $this->password_in; $salt = base64_decode($cryptInfo['salt']); if ($cryptInfo['hash'] != hash('sha256',$salt.$password)) { if ($password == '') { throw new VNagWebInfoException(VNagLang::$require_password); } else { throw new VNagWebInfoException(VNagLang::$wrong_password); } } if (!function_exists('openssl_decrypt')) { throw new VNagException(VNagLang::$openssl_missing); } $payload = openssl_decrypt($payload, $cryptInfo['method'], $password, 0, $cryptInfo['iv']); } if (!is_null($this->pubkey) && ($this->pubkey !== '')) { if (substr($this->pubkey,0,3) === '---') { $public_key = $this->pubkey; } else { if (!file_exists($this->pubkey)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$pubkey_file_not_found, $this->pubkey)); } $public_key = @file_get_contents($this->pubkey); if (!$public_key) { throw new VNagPublicKeyException(sprintf(VNagLang::$pubkey_file_not_readable, $this->pubkey)); } } if (!isset($dataset['signature'])) { throw new VNagSignatureException(VNagLang::$signature_missing); } $signature = base64_decode($dataset['signature']); if (!$signature) { throw new VNagSignatureException(VNagLang::$signature_not_bas64); } if (!function_exists('openssl_verify')) { throw new VNagException(VNagLang::$openssl_missing); } $sign_algo = is_null($this->sign_algo) ? OPENSSL_ALGO_SHA256 : $this->sign_algo; if (!openssl_verify($payload, $signature, $public_key, $sign_algo)) { throw new VNagSignatureException(VNagLang::$signature_invalid); } } $payload = @json_decode($payload,true); if (!$payload) { throw new VNagWebInfoException(VNagLang::$payload_not_json); } if ($payload['id'] == $this->id) { return $payload; } } } } return null; } private function getNextMonitorID($peek=false) { $result = is_null($this->id) ? self::$http_serial_number : $this->id; if (!$peek) { $this->id = null; self::$http_serial_number++; } return $result; } private function writeInvisibleHTML($special_content=null) { $payload['id'] = $this->getNextMonitorID(); $payload['status'] = $this->getStatus(); if (!_empty($special_content)) { $payload['text'] = $special_content; } else { $payload['headline'] = $this->getHeadline(); $payload['verbose_info'] = $this->verbose_info; $payload['performance_data'] = array(); foreach ($this->performanceDataObjects as $perfdata) { $payload['performance_data'][] = (string)$perfdata; } } $payload = json_encode($payload); $dataset = array(); if (!is_null($this->privkey) && ($this->privkey !== '')) { if (!function_exists('openssl_pkey_get_private') || !function_exists('openssl_sign')) { throw new VNagException(VNagLang::$openssl_missing); } if (substr($this->privkey,0,3) === '---') { $pkeyid = @openssl_pkey_get_private($this->privkey, $this->privkey_password); if (!$pkeyid) { throw new VNagPrivateKeyException(sprintf(VNagLang::$privkey_not_readable)); } } else { if (!file_exists($this->privkey)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$privkey_file_not_found, $this->privkey)); } $pkeyid = @openssl_pkey_get_private('file://'.$this->privkey, $this->privkey_password); if (!$pkeyid) { throw new VNagPrivateKeyException(sprintf(VNagLang::$privkey_file_not_readable, $this->privkey)); } } $signature = ''; $sign_algo = is_null($this->sign_algo) ? OPENSSL_ALGO_SHA256 : $this->sign_algo; if (@openssl_sign($payload, $signature, $pkeyid, $sign_algo)) { if (version_compare(PHP_VERSION, '8.0.0') < 0) { openssl_free_key($pkeyid); } $dataset['signature'] = base64_encode($signature); } else { throw new VNagPrivateKeyException(sprintf(VNagLang::$signature_failed)); } } if (!is_null($this->password_out) && ($this->password_out !== '')) { if (!function_exists('openssl_encrypt')) { throw new VNagException(VNagLang::$openssl_missing); } $password = $this->password_out; $method = 'aes-256-ofb'; $iv = substr(hash('sha256', openssl_random_pseudo_bytes(32)), 0, 16); $salt = openssl_random_pseudo_bytes(32); $cryptInfo = array(); $cryptInfo['method'] = $method; $cryptInfo['iv'] = $iv; $cryptInfo['salt'] = base64_encode($salt); $cryptInfo['hash'] = hash('sha256', $salt.$password); $payload = openssl_encrypt($payload, $method, $password, 0, $iv); $dataset['encryption'] = $cryptInfo; } $dataset['payload'] = base64_encode($payload); $json = array(); $json['type'] = VNAG_JSONDATA_V1; $json['datasets'] = array($dataset); return '<script type="application/json">'. json_encode($json). '</script>'; } protected function appendHeadline($msg) { $this->checkInitialized(); if (_empty($msg)) return false; $this->messages[] = $msg; return true; } protected function changeHeadline($msg) { $this->checkInitialized(); if (_empty($msg)) { $this->messages = array(); } else { $this->messages = array($msg); } return true; } public function setHeadline($msg, $append=false, $verbosityLevel=VNag::VERBOSITY_SUMMARY) { $this->checkInitialized(); if ((!isset($this->argVerbosity)) && ($verbosityLevel > VNag::VERBOSITY_SUMMARY)) throw new VNagRequiredArgumentNotRegistered('-v'); if (self::getVerbosityLevel() < $verbosityLevel) $msg = ''; if ($append) { return $this->appendHeadline($msg); } else { return $this->changeHeadline($msg); } } public function getHeadline() { $this->checkInitialized(); return implode(', ', $this->messages); } public function addVerboseMessage($msg, $verbosityLevel=VNag::VERBOSITY_SUMMARY) { $this->checkInitialized(); if (self::getVerbosityLevel() >= $verbosityLevel) { $this->verbose_info .= $msg."\n"; } } public function setStatus($status, $force=false) { $this->checkInitialized(); if (($force) || is_null($this->status) || ($status > $this->status)) { $this->status = $status; } } public function getStatus() { $this->checkInitialized(); return $this->status; } protected static function exceptionText($exception) { $class = get_class($exception); $msg = $exception->getMessage(); if (!_empty($msg)) { return sprintf(VNagLang::$exception_x, $msg, $class); } else { return sprintf(VNagLang::$unhandled_exception_without_msg, $class); } } protected function handleException($exception) { $this->checkInitialized(); if (!VNag::is_http_mode()) { while (ob_get_level() > 0) @ob_end_clean(); } $this->clearVerboseInfo(); $this->clearPerformanceData(); if ($exception instanceof VNagException) { $this->setStatus($exception->getStatus()); } else { $this->setStatus(self::STATUS_ERROR); } $this->setHeadline($this->exceptionText($exception), false); if ($exception instanceof VNagImplementationErrorException) { $this->addVerboseMessage($exception->getTraceAsString(), VNag::VERBOSITY_SUMMARY); } else { if (isset($this->argVerbosity)) { $this->addVerboseMessage($exception->getTraceAsString(), VNag::VERBOSITY_ADDITIONAL_INFORMATION); } else { } } } protected function get_cache_dir() { $homedir = @getenv('HOME'); if ($homedir && is_dir($homedir)) { $try = "$homedir/.vnag/cache"; if (is_dir($try)) return $try; if (@mkdir($try,0777,true)) return $try; } $user = posix_getpwuid(posix_geteuid()); if (isset($user['dir']) && is_dir($user['dir'])) { $homedir = $user['dir']; $try = "$homedir/.vnag/cache"; if (is_dir($try)) return $try; if (@mkdir($try,0777,true)) return $try; } if (isset($user['name']) && is_dir($user['name'])) { $username = $user['name']; $try = "/tmp/vnag/cache"; if (is_dir($try)) return $try; if (@mkdir($try,0777,true)) return $try; } throw new VNagException("Cannot get cache dir"); } protected function url_get_contents($url, $max_cache_time=1*60*60, $context=null) { $cache_file = $this->get_cache_dir().'/'.hash('sha256',$url); if (file_exists($cache_file) && (time()-filemtime($cache_file) < $max_cache_time)) { $cont = @file_get_contents($cache_file); if ($cont === false) throw new Exception("Failed to get contents from $cache_file"); } else { $options = array( 'http'=>array( 'method'=>"GET", 'header'=>"Accept-language: en\r\n" . "User-Agent: Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B334b Safari/531.21.102011-10-16 20:23:10\r\n" ) ); if (is_null($context)) $context = stream_context_create($options); $cont = @file_get_contents($url, false, $context); if ($cont === false) throw new Exception("Failed to get contents from $url"); file_put_contents($cache_file, $cont); } return $cont; } } class VNagException extends Exception { public function getStatus() { return VNag::STATUS_ERROR; } } class VNagTimeoutException extends VNagException {} class VNagWebInfoException extends VNagException {} class VNagSignatureException extends VNagException {} class VNagPublicKeyException extends VNagException {} class VNagPrivateKeyException extends VNagException {} class VNagInvalidArgumentException extends VNagException { public function getStatus() { return VNag::STATUS_UNKNOWN; } } class VNagValueUomPairSyntaxException extends VNagInvalidArgumentException { public function __construct($str) { $e_msg = sprintf(VNagLang::$valueUomPairSyntaxError, $str); parent::__construct($e_msg); } } class VNagInvalidTimeoutException extends VNagInvalidArgumentException {} class VNagInvalidRangeException extends VNagInvalidArgumentException { public function __construct($msg) { $e_msg = VNagLang::$range_is_invalid; if (!_empty($msg)) $e_msg .= ': '.trim($msg); parent::__construct($e_msg); } } class VNagInvalidShortOpt extends VNagImplementationErrorException {} class VNagInvalidLongOpt extends VNagImplementationErrorException {} class VNagInvalidValuePolicy extends VNagImplementationErrorException {} class VNagIllegalStatusModel extends VNagImplementationErrorException {} class VNagNotConstructed extends VNagImplementationErrorException {} class VNagImplementationErrorException extends VNagException {} class VNagInvalidStandardArgument extends VNagImplementationErrorException {} class VNagFunctionCallOutsideSession extends VNagImplementationErrorException {} class VNagIllegalArgumentValuesException extends VNagImplementationErrorException {} class VNagRequiredArgumentNotRegistered extends VNagImplementationErrorException { public function __construct($required_argument) { $e_msg = sprintf(VNagLang::$query_without_expected_argument, $required_argument); parent::__construct($e_msg); } } class VNagRequiredArgumentMissing extends VNagInvalidArgumentException { public function __construct($required_argument) { $e_msg = sprintf(VNagLang::$required_argument_missing, $required_argument); parent::__construct($e_msg); } } class VNagUnknownUomException extends VNagInvalidArgumentException { public function __construct($uom) { $e_msg = sprintf(VNagLang::$perfdata_uom_not_recognized, $uom); parent::__construct($e_msg); } } class VNagNoCompatibleRangeUomFoundException extends VNagException {} class VNagMixedUomsNotImplemented extends VNagInvalidArgumentException { public function __construct($uom1, $uom2) { if (_empty($uom1)) $uom1 = VNagLang::$none; if (_empty($uom2)) $uom2 = VNagLang::$none; $e_msg = sprintf(VNagLang::$perfdata_mixed_uom_not_implemented, $uom1, $uom2); parent::__construct($e_msg); } } class VNagUomConvertException extends VNagInvalidArgumentException { public function __construct($uom1, $uom2) { if (_empty($uom1)) $uom1 = VNagLang::$none; if (_empty($uom2)) $uom2 = VNagLang::$none; $e_msg = sprintf(VNagLang::$convert_x_y_error, $uom1, $uom2); parent::__construct($e_msg); } } class VNagInvalidPerformanceDataException extends VNagInvalidArgumentException { public function __construct($msg) { $e_msg = VNagLang::$performance_data_invalid; if (!_empty($msg)) $e_msg .= ': '.trim($msg); parent::__construct($e_msg); } } class Timeouter { private static $start_time = false; private static $timeout; private static $fired = false; private static $registered = false; private function __construct() { } public static function start($timeout) { if (!is_numeric($timeout) || ($timeout <= 0)) { throw new VNagInvalidTimeoutException(sprintf(VNagLang::$timeout_value_invalid, $timeout)); } self::$start_time = microtime(true); self::$timeout = (float) $timeout; self::$fired = false; if (!self::$registered) { self::$registered = true; register_tick_function(array('Timeouter', 'tick')); } } public static function started() { return self::$registered; } public static function end() { if (self::$registered) { unregister_tick_function(array('Timeouter', 'tick')); self::$registered = false; } } public static function tick() { if ((!self::$fired) && ((microtime(true) - self::$start_time) > self::$timeout)) { self::$fired = true; throw new VNagTimeoutException(VNagLang::$timeout_exception); } } } class VNagArgument { const VALUE_FORBIDDEN = 0; const VALUE_REQUIRED = 1; const VALUE_OPTIONAL = 2; protected $shortopt; protected $longopts; protected $valuePolicy; protected $valueName; protected $helpText; protected $defaultValue = null; protected static $all_short = ''; protected static $all_long = array(); public function getShortOpt() { return $this->shortopt; } public function getLongOpts() { return $this->longopts; } public function getValuePolicy() { return $this->valuePolicy; } public function getValueName() { return $this->valueName; } public function getHelpText() { return $this->helpText; } static private function validateShortOpt($shortopt) { $m = array(); return preg_match('@^[a-zA-Z0-9\\+\\-\\?]$@', $shortopt, $m); } static private function validateLongOpt($longopt) { $m = array(); return preg_match('@^[a-zA-Z0-9\\+\\-\\?]+$@', $longopt, $m); } public function __construct($shortopt, $longopts, $valuePolicy, $valueName, $helpText, $defaultValue=null) { switch ($valuePolicy) { case VNagArgument::VALUE_FORBIDDEN: if (!_empty($valueName)) { throw new VNagImplementationErrorException(sprintf(VNagLang::$value_name_forbidden)); } break; case VNagArgument::VALUE_REQUIRED: if (_empty($valueName)) { throw new VNagImplementationErrorException(sprintf(VNagLang::$value_name_required)); } break; case VNagArgument::VALUE_OPTIONAL: if (_empty($valueName)) { throw new VNagImplementationErrorException(sprintf(VNagLang::$value_name_required)); } break; default: throw new VNagInvalidValuePolicy(sprintf(VNagLang::$illegal_valuepolicy, $valuePolicy)); } if (!_empty($shortopt)) { if (!self::validateShortOpt($shortopt)) { throw new VNagInvalidShortOpt(sprintf(VNagLang::$illegal_shortopt, $shortopt)); } } if (is_array($longopts)) { foreach ($longopts as $longopt) { if (!self::validateLongOpt($longopt)) { throw new VNagInvalidLongOpt(sprintf(VNagLang::$illegal_longopt, $longopt)); } } } else if (!_empty($longopts)) { if (!self::validateLongOpt($longopts)) { throw new VNagInvalidLongOpt(sprintf(VNagLang::$illegal_longopt, $longopts)); } $longopts = array($longopts); } else { $longopts = array(); } switch ($valuePolicy) { case VNagArgument::VALUE_FORBIDDEN: $policyApdx = ''; break; case VNagArgument::VALUE_REQUIRED: $policyApdx = ':'; break; case VNagArgument::VALUE_OPTIONAL: $policyApdx = '::'; break; default: throw new VNagInvalidValuePolicy(sprintf(VNagLang::$illegal_valuepolicy, $valuePolicy)); } if ((!is_null($shortopt)) && ($shortopt != '?')) self::$all_short .= $shortopt.$policyApdx; if (is_array($longopts)) { foreach ($longopts as $longopt) { self::$all_long[] = $longopt.$policyApdx; } } $this->shortopt = $shortopt; $this->longopts = $longopts; $this->valuePolicy = $valuePolicy; $this->valueName = $valueName; $this->helpText = $helpText; $this->defaultValue = $defaultValue; } protected static function getOptions() { global $OVERWRITE_ARGUMENTS; if (!is_null($OVERWRITE_ARGUMENTS)) { return $OVERWRITE_ARGUMENTS; } else if (VNag::is_http_mode()) { return $_REQUEST; } else { return getopt(self::$all_short, self::$all_long); } } public function count() { $options = self::getOptions(); $count = 0; if (isset($options[$this->shortopt])) { if (is_array($options[$this->shortopt])) { $count += count($options[$this->shortopt]); } else { $count += 1; } } if (!is_null($this->longopts)) { foreach ($this->longopts as $longopt) { if (isset($options[$longopt])) { if (is_array($options[$longopt])) { $count += count($options[$longopt]); } else { $count += 1; } } } } return $count; } public function available() { $options = self::getOptions(); if (isset($options[$this->shortopt])) return true; if (!is_null($this->longopts)) { foreach ($this->longopts as $longopt) { if (isset($options[$longopt])) return true; } } return false; } public function require() { if (!$this->available() && is_null($this->defaultValue)) { $opt = $this->shortopt; $opt = !_empty($opt) ? '-'.$opt : (isset($this->longopts[0]) ? '--'.$this->longopts[0] : '?'); throw new VNagRequiredArgumentMissing($opt); } } public function getValue() { $options = self::getOptions(); if (isset($options[$this->shortopt])) { $x = $options[$this->shortopt]; if (is_array($x) && (count($x) <= 1)) $options[$this->shortopt] = $options[$this->shortopt][0]; return $options[$this->shortopt]; } if (!is_null($this->longopts)) { foreach ($this->longopts as $longopt) { if (isset($options[$longopt])) { $x = $options[$longopt]; if (is_array($x) && (count($x) <= 1)) $options[$longopt] = $options[$longopt][0]; return $options[$longopt]; } } } return $this->defaultValue; } } class VNagArgumentHandler { protected $expectedArgs = array(); protected function _addExpectedArgument($argObj) { if ($argObj->getShortOpt() == '?') return false; if ($argObj->getShortOpt() == '-') return false; if ($argObj->getShortOpt() == '+') return false; $this->expectedArgs[] = $argObj; return true; } public function getArgumentObj($shortopt) { foreach ($this->expectedArgs as $argObj) { if ($argObj->getShortOpt() == $shortopt) return $argObj; } return null; } public function isArgRegistered($shortopt) { return !is_null($this->getArgumentObj($shortopt)); } public function illegalUsage() { global $argv; return (isset($argv[1])) && (($argv[1] == '-?') || ($argv[1] == '/?')); } } class VNagRange { public $start; public $end; public $warnInsideRange; public function __construct($rangeDef, $singleValueBehavior=VNag::SINGLEVALUE_RANGE_DEFAULT) { $m = array(); if (!preg_match('|^(@){0,1}([^:]+)(:){0,1}(.*)$|', $rangeDef, $m)) { throw new VNagInvalidRangeException(sprintf(VNagLang::$range_invalid_syntax, $rangeDef)); } $this->warnInsideRange = $m[1] === '@'; $this->start = null; $this->end = null; if ($m[3] === ':') { if ($m[2] === '~') { $this->start = '-inf'; } else { $this->start = new VNagValueUomPair($m[2]); } if (_empty($m[4])) { $this->end = 'inf'; } else { $this->end = new VNagValueUomPair($m[4]); } } else { assert(_empty($m[4])); assert(!_empty($m[2])); $x = $m[2]; if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_DEFAULT) { $this->start = new VNagValueUomPair('0'.((new VNagValueUomPair($x))->getUom())); $this->end = new VNagValueUomPair($x); } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_GT_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 0; $this->start = '-inf'; $this->end = new VNagValueUomPair($x); } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_GE_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 1; $this->start = new VNagValueUomPair($x); $this->end = 'inf'; } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_LT_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 0; $this->start = new VNagValueUomPair($x); $this->end = 'inf'; } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_LE_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 1; $this->start = '-inf'; $this->end = new VNagValueUomPair($x); } else { throw new VNagException(VNagLang::$illegalSingleValueBehavior); } } if (is_null($this->start)) { throw new VNagInvalidRangeException(VNagLang::$invalid_start_value); } if (is_null($this->end)) { throw new VNagInvalidRangeException(VNagLang::$invalid_end_value); } if (($this->start instanceof VNagValueUomPair) && ($this->end instanceof VNagValueUomPair) && (VNagValueUomPair::compare($this->start,$this->end) > 0)) { throw new VNagInvalidRangeException(VNagLang::$start_is_greater_than_end); } } public function __toString() { $ret = ''; if ($this->warnInsideRange) { $ret = '@'; } if ($this->start === '-inf') { $ret .= '~'; } else { $ret .= $this->start; } $ret .= ':'; if ($this->end !== 'inf') { $ret .= $this->end; } return $ret; } public function checkAlert($values) { $compatibleCount = 0; if (!is_array($values)) $values = array($values); foreach ($values as $value) { if (!($value instanceof VNagValueUomPair)) $value = new VNagValueUomPair($value); assert(($this->start === '-inf') || ($this->start instanceof VNagValueUomPair)); assert(($this->end === 'inf' ) || ($this->end instanceof VNagValueUomPair)); if (($this->start !== '-inf') && (!$this->start->compatibleWith($value))) continue; if (($this->end !== 'inf') && (!$this->end->compatibleWith($value))) continue; $compatibleCount++; if ($this->warnInsideRange) { return (($this->start === '-inf') || (VNagValueUomPair::compare($value,$this->start) >= 0)) && (($this->end === 'inf') || (VNagValueUomPair::compare($value,$this->end) <= 0)); } else { return (($this->start !== '-inf') && (VNagValueUomPair::compare($value,$this->start) < 0)) || (($this->end !== 'inf') && (VNagValueUomPair::compare($value,$this->end) > 0)); } } if ((count($values) > 0) and ($compatibleCount == 0)) { throw new VNagNoCompatibleRangeUomFoundException(VNagLang::$no_compatible_range_uom_found); } return false; } } class VNagValueUomPair { protected $value; protected $uom; public $roundTo = -1; public function isRelative() { return $this->uom === '%'; } public function getValue() { return $this->value; } public function getUom() { return $this->uom; } public function __toString() { if ($this->roundTo == -1) { return $this->value.$this->uom; } else { return round($this->value,$this->roundTo).$this->uom; } } public function __construct($str) { $m = array(); if (!preg_match('/^([\d\.]+)(.*)$/ism', $str, $m)) { throw new VNagValueUomPairSyntaxException($str); } $this->value = $m[1]; $this->uom = isset($m[2]) ? $m[2] : ''; if (!self::isKnownUOM($this->uom)) { throw new VNagUnknownUomException($this->uom); } } public static function isKnownUOM(string $uom) { $no_unit = ($uom === ''); $seconds = ($uom === 's') || ($uom === 'ms') || ($uom === 'us'); $percentage = ($uom === '%'); $bytes = ($uom === 'B') || ($uom === 'KB') || ($uom === 'MB') || ($uom === 'GB') || ($uom === 'TB'); $counter = ($uom === 'c'); return ($no_unit || $seconds || $percentage || $bytes || $counter); } public function normalize($target=null) { $res = clone $this; if ($res->uom === 'ms') { $res->uom = 's'; $res->value /= 1000; } if ($res->uom === 'us') { $res->uom = 's'; $res->value /= 1000 * 1000; } if ($res->uom === 'B') { $res->uom = 'MB'; $res->value /= 1024 * 1024; } if ($res->uom === 'KB') { $res->uom = 'MB'; $res->value /= 1024; } if ($res->uom === 'GB') { $res->uom = 'MB'; $res->value *= 1024; } if ($res->uom === 'TB') { $res->uom = 'MB'; $res->value *= 1024 * 1024; } if ($res->uom === 'c') { $res->uom = ''; } if (!is_null($target)) { if ($res->uom == 'MB') { if ($target == 'B') { $res->uom = 'B'; $res->value *= 1024 * 1024; } else if ($target == 'KB') { $res->uom = 'KB'; $res->value *= 1024; } else if ($target == 'MB') { $res->uom = 'MB'; $res->value *= 1; } else if ($target == 'GB') { $res->uom = 'GB'; $res->value /= 1024; } else if ($target == 'TB') { $res->uom = 'TB'; $res->value /= 1024 * 1024; } else { throw new VNagUomConvertException($res->uom, $target); } } else if ($res->uom == 's') { if ($target == 's') { $res->uom = 's'; $res->value /= 1; } else if ($target == 'ms') { $res->uom = 'ms'; $res->value /= 1000; } else if ($target == 'us') { $res->uom = 'us'; $res->value /= 1000 * 1000; } else { throw new VNagUomConvertException($res->uom, $target); } } else { throw new VNagUomConvertException($res->uom, $target); } } return $res; } public function compatibleWith(VNagValueUomPair $other) { $a = $this->normalize(); $b = $other->normalize(); return ($a->uom == $b->uom); } public static function compare(VNagValueUomPair $left, VNagValueUomPair $right) { $a = $left->normalize(); $b = $right->normalize(); if ($a->uom != $b->uom) throw new VNagMixedUomsNotImplemented($a->uom, $b->uom); if ($a->value > $b->value) return 1; if ($a->value == $b->value) return 0; if ($a->value < $b->value) return -1; } } class VNagPerformanceData { protected $label; protected $value; protected $warn = null; protected $crit = null; protected $min = null; protected $max = null; public static function createByString($perfdata) { $perfdata = trim($perfdata); $ary = explode('=',$perfdata); if (count($ary) != 2) { throw new VNagInvalidPerformanceDataException(sprintf(VNagLang::$perfdata_line_invalid, $perfdata)); } $label = $ary[0]; $bry = explode(';',$ary[1]); if (substr($label,0,1) === "'") $label = substr($label, 1, strlen($label)-2); $value = $bry[0]; $warn = isset($bry[1]) ? $bry[1] : null; $crit = isset($bry[2]) ? $bry[2] : null; $min = isset($bry[3]) ? $bry[3] : null; $max = isset($bry[4]) ? $bry[4] : null; return new self($label, $value, $warn, $crit, $min, $max); } public function __construct($label, $value, $warn=null, $crit=null, $min=null, $max=null) { if (strpos($label, '=') !== false) throw new VNagInvalidPerformanceDataException(VNagLang::$perfdata_label_equal_sign_forbidden); $label = str_replace("'", "''", $label); $m = array(); if ((!_empty($min)) && (!preg_match('|^[-0-9\\.]+$|', $min, $m))) { throw new VNagInvalidPerformanceDataException(VNagLang::$perfdata_min_must_be_in_class); } if ((!_empty($max)) && (!preg_match('|^[-0-9\\.]+$|', $max, $m))) { throw new VNagInvalidPerformanceDataException(VNagLang::$perfdata_max_must_be_in_class); } $this->label = $label; $this->value = ($value == 'U') ? 'U' : new VNagValueUomPair($value); $this->warn = $warn; $this->crit = $crit; $this->min = $min; $this->max = $max; } public function __toString() { $label = $this->label; $value = $this->value; $warn = $this->warn; $crit = $this->crit; $min = $this->min; $max = $this->max; $label = str_replace("''", "'", $label); return "'$label'=$value". ';'.(is_null($warn) ? '' : $warn). ';'.(is_null($crit) ? '' : $crit). ';'.(is_null($min) ? '' : $min). ';'.(is_null($max) ? '' : $max); } } class VNagHelp { public $word_wrap_width = 80; public $argument_indent = 7; public function printUsagePage() { $usage = $this->getUsage(); if (_empty($usage)) { $usage = VNagLang::$no_syntax_defined; } return trim($usage)."\n"; } public function printVersionPage() { $out = trim($this->getNameAndVersion())."\n"; if ($this->word_wrap_width > 0) $out = wordwrap($out, $this->word_wrap_width, "\n", false); return $out; } static private function _conditionalLine($line, $terminator='', $prefix='') { if (!_empty($line)) { return trim($line).$terminator; } return ''; } public function printHelpPage() { $out = ''; $out .= self::_conditionalLine($this->getNameAndVersion(), "\n"); $out .= self::_conditionalLine($this->getCopyright(), "\n"); $out .= ($out != '') ? "\n" : ''; $out .= self::_conditionalLine($this->getShortDescription(), "\n\n\n"); $out .= self::_conditionalLine($this->getUsage(), "\n\n"); $out .= VNagLang::$options."\n"; foreach ($this->options as $argObj) { $out .= $this->printArgumentHelp($argObj); } $out .= self::_conditionalLine($this->getFootNotes(), "\n\n", "\n"); if ($this->word_wrap_width > 0) $out = wordwrap($out, $this->word_wrap_width, "\n", false); return $out; } protected $options = array(); protected function _addOption($argObj) { $this->options[] = $argObj; } protected function printArgumentHelp($argObj) { $identifiers = array(); $shortopt = $argObj->getShortopt(); if (!_empty($shortopt)) $identifiers[] = '-'.$shortopt; $longopts = $argObj->getLongopts(); if (!is_null($longopts)) { foreach ($longopts as $longopt) { if (!_empty($longopt)) $identifiers[] = '--'.$longopt; } } if (count($identifiers) == 0) return; $valueName = $argObj->getValueName(); $arginfo = ''; switch ($argObj->getValuePolicy()) { case VNagArgument::VALUE_FORBIDDEN: $arginfo = ''; break; case VNagArgument::VALUE_REQUIRED: $arginfo = '='.$valueName; break; case VNagArgument::VALUE_OPTIONAL: $arginfo = '[='.$valueName.']'; break; } $out = ''; $out .= implode(', ', $identifiers).$arginfo."\n"; $content = trim($argObj->getHelpText()); if ($this->word_wrap_width > 0) $content = wordwrap($content, $this->word_wrap_width-$this->argument_indent, "\n", false); $lines = explode("\n", $content); foreach ($lines as $line) { $out .= str_repeat(' ', $this->argument_indent).$line."\n"; } $out .= "\n"; return $out; } protected $pluginName; public function setPluginName($pluginName) { $this->pluginName = $this->replaceStuff($pluginName); } public function getPluginName() { if (_empty($this->pluginName)) { global $argv; return basename($argv[0]); } else { return $this->pluginName; } } protected $version; public function setVersion($version) { $this->version = $this->replaceStuff($version); } public function getVersion() { return $this->version; } public function getNameAndVersion() { $ret = $this->getPluginName(); if (_empty($ret)) return null; $ver = $this->getVersion(); if (!_empty($ver)) { $ret = sprintf(VNagLang::$x_version_x, $ret, $ver); } $ret = trim($ret); return $ret; } protected $copyright; public function setCopyright($copyright) { $this->copyright = $this->replaceStuff($copyright); } private function getVNagCopyright() { if (VNag::is_http_mode()) { $vts_email = 'www.viathinksoft.com'; } else { $vts_email = base64_decode('aW5mb0B2aWF0aGlua3NvZnQuZGU='); } return "VNag Framework ".VNag::VNAG_VERSION." (C) 2014-".date('Y')." ViaThinkSoft <$vts_email>"; } public function getCopyright() { if (_empty($this->copyright)) { return sprintf(VNagLang::$plugin_uses, $this->getVNagCopyright()); } else { return trim($this->copyright)."\n".sprintf(VNagLang::$uses, $this->getVNagCopyright()); } } protected $shortDescription; public function setShortDescription($shortDescription) { $this->shortDescription = $this->replaceStuff($shortDescription); } public function getShortDescription() { if (_empty($this->shortDescription)) { return null; } else { $content = $this->shortDescription; if ($this->word_wrap_width > 0) $content = wordwrap($content, $this->word_wrap_width, "\n", false); return $content; } } protected function replaceStuff($text) { global $argv; if (php_sapi_name() == 'cli') { $text = str_replace('$SCRIPTNAME$', $argv[0], $text); } else { $text = str_replace('$SCRIPTNAME$', basename($_SERVER['SCRIPT_NAME']), $text); } $text = str_replace('$CURYEAR$', date('Y'), $text); return $text; } protected $syntax; public function setSyntax($syntax) { $syntax = $this->replaceStuff($syntax); $this->syntax = $syntax; } public function getUsage() { if (_empty($this->syntax)) { return null; } else { return sprintf(VNagLang::$usage_x, $this->syntax); } } protected $footNotes; public function setFootNotes($footNotes) { $this->footNotes = $this->replaceStuff($footNotes); } public function getFootNotes() { return $this->footNotes; } } class VNagLang { public static function status($code, $statusmodel) { switch ($statusmodel) { case VNag::STATUSMODEL_SERVICE: switch ($code) { case VNag::STATUS_OK: return 'OK'; case VNag::STATUS_WARNING: return 'Warning'; case VNag::STATUS_CRITICAL: return 'Critical'; case VNag::STATUS_UNKNOWN: return 'Unknown'; default: return sprintf('Error (%d)', $code); } case VNag::STATUSMODEL_HOST: switch ($code) { case VNag::STATUS_UP: return 'Up'; case VNag::STATUS_DOWN: return 'Down'; default: return sprintf('Maintain last state (%d)', $code); } default: throw new VNagIllegalStatusModel(sprintf(self::$illegal_statusmodel, $statusmodel)); } } static $nagios_output = 'VNag-Output'; static $verbose_info = 'Verbose information'; static $status = 'Status'; static $message = 'Message'; static $performance_data = 'Performance data'; static $status_ok = 'OK'; static $status_warn = 'Warning'; static $status_critical = 'Critical'; static $status_unknown = 'Unknown'; static $status_error = 'Error'; static $unhandled_exception_without_msg = "Unhandled exception of type %s"; static $plugin_uses = 'This plugin uses %s'; static $uses = 'uses %s'; static $x_version_x = '%s, version %s'; static $argname_value = 'value'; static $argname_seconds = 'seconds'; static $query_without_expected_argument = "The argument '%s' is queried, but was not added to the list of expected arguments. Please contact the plugin author."; static $required_argument_missing = "The argument '%s' is required."; static $performance_data_invalid = 'Performance data invalid.'; static $no_standard_arguments_with_letter = "No standard argument with letter '%s' exists."; static $invalid_start_value = 'Invalid start value.'; static $invalid_end_value = 'Invalid end value.'; static $start_is_greater_than_end = 'Start is greater than end value.'; static $value_name_forbidden = "Implementation error: You may not define a value name for the argument, because the value policy is VALUE_FORBIDDEN."; static $value_name_required = "Implementation error: Please define a name for the argument (so it can be shown in the help page)."; static $illegal_shortopt = "Illegal shortopt '-%s'."; static $illegal_longopt = "Illegal longopt '--%s'."; static $illegal_valuepolicy = "valuePolicy has illegal value '%s'."; static $range_invalid_syntax = "Syntax error in range '%s'."; static $timeout_value_invalid = "Timeout value '%s' is invalid."; static $range_is_invalid = 'Range is invalid.'; static $timeout_exception = 'Timeout!'; static $perfdata_label_equal_sign_forbidden = 'Label may not contain an equal sign.'; static $perfdata_value_must_be_in_class = 'Value must be in class [-0-9.] or be \'U\' if the actual value can\'t be determined.'; static $perfdata_min_must_be_in_class = 'Min must be in class [-0-9.] or empty.'; static $perfdata_max_must_be_in_class = 'Max must be in class [-0-9.] or empty.'; static $perfdata_uom_not_recognized = 'UOM (unit of measurement) "%s" is not recognized.'; static $perfdata_mixed_uom_not_implemented = 'Mixed UOMs (%s and %s) are currently not supported.'; static $no_compatible_range_uom_found = 'Measured values are not compatible with the provided warning/critical parameter. Most likely, the UOM is incompatible.'; static $exception_x = '%s (%s)'; static $no_syntax_defined = 'The author of this plugin has not defined a syntax for this plugin.'; static $usage_x = "Usage:\n%s"; static $options = "Options:"; static $illegal_statusmodel = "Invalid statusmodel %d."; static $none = '[none]'; static $valueUomPairSyntaxError = 'Syntax error at "%s". Syntax must be Value[UOM].'; static $too_few_warning_ranges = "You have too few warning ranges (currently trying to get element %d)."; static $too_few_critical_ranges = "You have too few critical ranges (currently trying to get element %d)."; static $dataset_missing = 'Dataset missing.'; static $payload_not_base64 = 'The payload is not valid Base64.'; static $payload_not_json = 'The payload is not valid JSON.'; static $signature_missing = 'The signature is missing.'; static $signature_not_bas64 = 'The signature is not valid Base64.'; static $signature_invalid = 'The signature is invalid. The connection might have been tampered, or a different key is used.'; static $pubkey_file_not_found = "Public key file %s was not found."; static $pubkey_file_not_readable = "Public key file %s is not readable."; static $privkey_file_not_found = "Private key file %s was not found."; static $privkey_not_readable = "Private key is not readable."; static $privkey_file_not_readable = "Private key file %s is not readable."; static $signature_failed = "Signature failed."; static $perfdata_line_invalid = "Performance data line %s is invalid."; static $singlevalue_unexpected_at_symbol = 'This plugin does not allow the @-symbol at ranges for single values.'; static $illegalSingleValueBehavior = "Illegal value for 'singleValueBehavior'. Please contact the creator of the plugin."; static $dataset_encryption_no_array = 'Dataset encryption information invalid.'; static $require_password = 'This resource is protected with a password. Please provide a password.'; static $wrong_password = 'This resource is protected with a password. You have provided the wrong password, or it was changed.'; static $convert_x_y_error = 'Cannot convert from UOM %s to UOM %s.'; static $php_error = 'PHP has detected an error in the plugin. Please contact the plugin author.'; static $output_level_lowered = "Output Buffer level lowered during cbRun(). Please contact the plugin author."; static $openssl_missing = "OpenSSL is missing. Therefore, encryption and signatures are not available."; static $warning_range = 'Warning range'; static $critical_range = 'Critical range'; static $prints_version = 'Prints version'; static $verbosity_helptext = 'Verbosity -v, -vv or -vvv'; static $timeout_helptext = 'Sets timeout in seconds'; static $help_helptext = 'Prints help page'; static $prints_usage = 'Prints usage'; static $notConstructed = 'Parent constructor not called with parent::__construct().'; } function vnagErrorHandler($errorkind, $errortext, $file, $line) { global $inside_vnag_run; if (!$inside_vnag_run && VNag::is_http_mode()) { return false; } if (!(error_reporting() & $errorkind)) { return true; } if (defined('E_ERROR') && ($errorkind == E_ERROR)) $errorkind = 'Error'; if (defined('E_WARNING') && ($errorkind == E_WARNING)) $errorkind = 'Warning'; if (defined('E_PARSE') && ($errorkind == E_PARSE)) $errorkind = 'Parse'; if (defined('E_NOTICE') && ($errorkind == E_NOTICE)) $errorkind = 'Notice'; if (defined('E_CORE_ERROR') && ($errorkind == E_CORE_ERROR)) $errorkind = 'Core Error'; if (defined('E_CORE_WARNING') && ($errorkind == E_CORE_WARNING)) $errorkind = 'Core Warning'; if (defined('E_COMPILE_ERROR') && ($errorkind == E_COMPILE_ERROR)) $errorkind = 'Compile Error'; if (defined('E_COMPILE_WARNING') && ($errorkind == E_COMPILE_WARNING)) $errorkind = 'Compile Warning'; if (defined('E_USER_ERROR') && ($errorkind == E_USER_ERROR)) $errorkind = 'User Error'; if (defined('E_USER_WARNING') && ($errorkind == E_USER_WARNING)) $errorkind = 'User Warning'; if (defined('E_USER_NOTICE') && ($errorkind == E_USER_NOTICE)) $errorkind = 'User Notice'; if (defined('E_STRICT') && ($errorkind == E_STRICT)) $errorkind = 'Strict'; if (defined('E_RECOVERABLE_ERROR') && ($errorkind == E_RECOVERABLE_ERROR)) $errorkind = 'Recoverable Error'; if (defined('E_DEPRECATED') && ($errorkind == E_DEPRECATED)) $errorkind = 'Deprecated'; if (defined('E_USER_DEPRECATED') && ($errorkind == E_USER_DEPRECATED)) $errorkind = 'User Deprecated'; throw new VNagException(VNagLang::$php_error . " $errortext at $file:$line (kind $errorkind)"); } $inside_vnag_run = false; $old_error_handler = set_error_handler("vnagErrorHandler"); <?php
declare(ticks=1); define('OUTPUT_UOM', 'GB'); class IpFlowMonitorCheck extends VNag { protected $argLogDir = null; protected $argLimit = null; public function __construct() { parent::__construct(); $this->registerExpectedStandardArguments('Vhtwc'); $this->getHelpManager()->setPluginName('check_ipfm'); $this->getHelpManager()->setVersion('2023-10-13'); $this->getHelpManager()->setShortDescription('This plugin checks the network traffic monitored by ipfm.'); $this->getHelpManager()->setCopyright('Copyright (C) 2011-$CURYEAR$ Daniel Marschall, ViaThinkSoft.'); $this->getHelpManager()->setSyntax('$SCRIPTNAME$ [-w currentGB[,expectedGB]] [-c currentGB[,expectedGB]] [-l limitGB] [-L path]'); $this->getHelpManager()->setFootNotes('If you encounter bugs, please contact ViaThinkSoft at www.viathinksoft.com'); $this->addExpectedArgument($this->argLimit = new VNagArgument('l', 'limit', VNagArgument::VALUE_REQUIRED, 'limit', '"Traffic inclusive" limit (e.g. 10TB)', null)); $this->addExpectedArgument($this->argLogDir = new VNagArgument('L', 'logdir', VNagArgument::VALUE_REQUIRED, 'path', 'Location of the ipfm log dir (Default: /var/log/ipfm)', '/var/log/ipfm')); } protected function interprete_ipfm_logfile($logfile) { $res = array(); $ary = file($logfile); foreach ($ary as $a) { $a = trim($a); if ($a == '') continue; if (substr($a, 0, 1) == '#') continue; $a = preg_replace("|\s+|ism", ' ', $a); $bry = explode(' ', $a); $res[$bry[0]] = array($bry[1], $bry[2], $bry[3]); } return $res; } protected function cbRun($optional_args=array()) { if (!defined('USE_DYGRAPH')) define('USE_DYGRAPH', false); $logDir = $this->argLogDir->getValue(); if (!is_dir($logDir)) throw new VNagException("Log dir $logDir not found"); $monthLimit = $this->argLimit->getValue(); if (!is_null($monthLimit)) { $p = (new VNagValueUomPair($monthLimit))->normalize(OUTPUT_UOM); $monthLimitValue = $p->getValue(); $monthLimitUom = $p->getUom(); } ob_start(); ?>
 
378,4 → 377,6
 
<?php
$html = ob_get_contents(); ob_end_clean(); $this->outputHTML($html, true); if (!is_null($monthLimit)) { $this->setHeadline(round($current,0).' '.OUTPUT_UOM." / ".$monthLimitValue.' '.OUTPUT_UOM." (".round($current/$monthLimitValue*100,2)."%, expected ".round($expected,0).' '.OUTPUT_UOM.") traffic used this month ($mon/$year)", true); } else { $this->setHeadline(round($current,0).' '.OUTPUT_UOM." (expected ".round($expected,0).' '.OUTPUT_UOM.") traffic used this month ($mon/$year)", true); } $warn = is_null($this->getWarningRange(0)) ? null : $this->getWarningRange(0)->end->normalize(OUTPUT_UOM)->getValue(); $crit = is_null($this->getCriticalRange(0)) ? null : $this->getCriticalRange(0)->end->normalize(OUTPUT_UOM)->getValue(); $this->addPerformanceData(new VNagPerformanceData('Current', $current.OUTPUT_UOM, $warn, $crit, 0, is_null($monthLimit) ? null : $monthLimitValue)); $warn = is_null($this->getWarningRange(1)) ? null : $this->getWarningRange(1)->end->normalize(OUTPUT_UOM)->getValue(); $crit = is_null($this->getCriticalRange(1)) ? null : $this->getCriticalRange(1)->end->normalize(OUTPUT_UOM)->getValue(); $this->addPerformanceData(new VNagPerformanceData('Expected', $expected.OUTPUT_UOM, $warn, $crit, 0, is_null($monthLimit) ? null : $monthLimitValue)); } } <?php
declare(ticks=1); require_once __DIR__ . '/../../framework/vnag_framework.inc.php'; require_once __DIR__ . '/IpFlowMonitorCheck.class.php'; $job = new IpFlowMonitorCheck(); $job->run(); unset($job); ÒB_^µŸ;bћవaäûÐüb@ëÙæ•opԅu-]«H»rêÂÆQm| {¹•SVUîÑYäÇGBMB
declare(ticks=1); require_once __DIR__ . '/../../framework/vnag_framework.inc.php'; require_once __DIR__ . '/IpFlowMonitorCheck.class.php'; $job = new IpFlowMonitorCheck(); $job->run(); unset($job); Ãþ¨À2ßJiP‚xÀh®y’TÍŒÓ‹á ¤úeæ^9ƎŚ,Ć~#"*‡9
è
'úbu+Ÿ ¸GBMB
/trunk/bin/joomla_version.phar
291,9 → 291,9
 
Extract_Phar::go();
__HALT_COMPILER(); ?>
k‚a:1:{s:23:"1.3.6.1.4.1.37476.3.0.2";s:340:"sha256||framework/vnag_framework.inc.php|460b109d1c578e9b6af41612e0312c9f36fd8beb51f7aa92f1b7bd49614568e8||plugins/joomla_version/JoomlaVersionCheck.class.php|f2b57e6818254cf9026e59f551c5c275e0f1a50030915ba3290762b0d101ec1d||plugins/joomla_version/check_joomla_version.phps|286aa801d2334a772bbe3e39e0970aced47a393d9f44deaa5346a4b9c7ec6d9f||";} framework/vnag_framework.inc.phpLÙyï*eLُ4p”¤3plugins/joomla_version/JoomlaVersionCheck.class.php2 yï*e2 ܂
à¤0plugins/joomla_version/check_joomla_version.phpsÎyï*eÎðJåë¤<?php ?>
<?php
·Îa:1:{s:23:"1.3.6.1.4.1.37476.3.0.2";s:416:"sha256||<builder>|481cf75d675006b504520fd2acb3b29c89aea03aab64754e0adfb364de4914b2||framework/vnag_framework.inc.php|0387bf3134f8cc2d1ae24e139019c0edef19c1ba5ca765624efea0b469c7897f||plugins/joomla_version/JoomlaVersionCheck.class.php|f2b57e6818254cf9026e59f551c5c275e0f1a50030915ba3290762b0d101ec1d||plugins/joomla_version/check_joomla_version.phps|286aa801d2334a772bbe3e39e0970aced47a393d9f44deaa5346a4b9c7ec6d9f||";} framework/vnag_framework.inc.phpBÙ» +eBÙÞß=¤3plugins/joomla_version/JoomlaVersionCheck.class.php2 » +e2 ܂
à¤0plugins/joomla_version/check_joomla_version.phpsλ +eÎðJåë¤<?php
if (!VNag::is_http_mode()) error_reporting(E_ALL); declare(ticks=1); set_time_limit(0); define('VNAG_JSONDATA_V1', 'oid:1.3.6.1.4.1.37476.2.3.1.1'); $OVERWRITE_ARGUMENTS = null; function _empty($x) { return is_null($x) || (trim($x) == ''); } abstract class VNag { const VNAG_VERSION = '2023-10-13'; const STATUS_OK = 0; const STATUS_WARNING = 1; const STATUS_CRITICAL = 2; const STATUS_UNKNOWN = 3; const STATUS_ERROR = 4; const STATUS_UP = 0; const STATUS_DOWN = 1; const STATUS_MAINTAIN = 2; const VERBOSITY_SUMMARY = 0; const VERBOSITY_ADDITIONAL_INFORMATION = 1; const VERBOSITY_CONFIGURATION_DEBUG = 2; const VERBOSITY_PLUGIN_DEBUG = 3; const MAX_VERBOSITY = self::VERBOSITY_PLUGIN_DEBUG; const STATUSMODEL_SERVICE = 0; const STATUSMODEL_HOST = 1; private $initialized = false; private $status = null; private $messages = array(); private $verbose_info = ''; private $warningRanges = array(); private $criticalRanges = array(); private $performanceDataObjects = array(); private static $exitcode = 0; private $helpObj = null; private $argHandler = null; const OUTPUT_NEVER = 0; const OUTPUT_SPECIAL = 1; const OUTPUT_NORMAL = 2; const OUTPUT_EXCEPTION = 4; const OUTPUT_ALWAYS = 7; public $http_visual_output = self::OUTPUT_ALWAYS; public $http_invisible_output = self::OUTPUT_ALWAYS; protected $html_before = ''; protected $html_after = ''; protected $statusmodel = self::STATUSMODEL_SERVICE; protected $show_status_in_headline = true; protected $default_status = self::STATUS_UNKNOWN; protected $default_warning_range = null; protected $default_critical_range = null; protected $argWarning; protected $argCritical; protected $argVersion; protected $argVerbosity; protected $argTimeout; protected $argHelp; protected $argUsage; public $id = null; protected static $http_serial_number = 0; public $privkey = null; public $privkey_password = null; public $sign_algo = null; public $pubkey = null; protected $warningSingleValueRangeBehaviors = array(self::SINGLEVALUE_RANGE_DEFAULT); protected $criticalSingleValueRangeBehaviors = array(self::SINGLEVALUE_RANGE_DEFAULT); const SINGLEVALUE_RANGE_DEFAULT = 0; const SINGLEVALUE_RANGE_VAL_GT_X_BAD = 1; const SINGLEVALUE_RANGE_VAL_GE_X_BAD = 2; const SINGLEVALUE_RANGE_VAL_LT_X_BAD = 3; const SINGLEVALUE_RANGE_VAL_LE_X_BAD = 4; public $password_out = null; public $password_in = null; public static function is_http_mode() { return php_sapi_name() !== 'cli'; } public function getHelpManager() { return $this->helpObj; } public function getArgumentHandler() { return $this->argHandler; } public function outputHTML($text, $after_visual_output=true) { if ($this->is_http_mode()) { if ($this->initialized) { if ($after_visual_output) { $this->html_after .= $text; } else { $this->html_before .= $text; } } else { echo $text; } } } protected function resetArguments() { $this->argWarning = null; $this->argCritical = null; $this->argVersion = null; $this->argVerbosity = null; $this->argTimeout = null; $this->argHelp = null; $this->argWarning = null; $this->argCritical = null; } public function registerExpectedStandardArguments($args) { $this->resetArguments(); for ($i=0; $i<strlen($args); $i++) { switch ($args[$i]) { case 'w': $this->addExpectedArgument($this->argWarning = new VNagArgument('w', 'warning', VNagArgument::VALUE_REQUIRED, VNagLang::$argname_value, VNagLang::$warning_range)); break; case 'c': $this->addExpectedArgument($this->argCritical = new VNagArgument('c', 'critical', VNagArgument::VALUE_REQUIRED, VNagLang::$argname_value, VNagLang::$critical_range)); break; case 'V': $this->addExpectedArgument($this->argVersion = new VNagArgument('V', 'version', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$prints_version)); break; case 'v': $this->addExpectedArgument($this->argVerbosity = new VNagArgument('v', 'verbose', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$verbosity_helptext)); break; case 't': $this->addExpectedArgument($this->argTimeout = new VNagArgument('t', 'timeout', VNagArgument::VALUE_REQUIRED, VNagLang::$argname_seconds, VNagLang::$timeout_helptext)); break; case 'h': $this->addExpectedArgument($this->argHelp = new VNagArgument('h', 'help', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$help_helptext)); break; default: $letter = $args[$i]; throw new VNagInvalidStandardArgument(sprintf(VNagLang::$no_standard_arguments_with_letter, $letter)); } } } public function addExpectedArgument($argObj) { $helpObjAddEntryMethod = new ReflectionMethod($this->helpObj, '_addOption'); $helpObjAddEntryMethod->setAccessible(true); $helpObjAddEntryMethod->invoke($this->helpObj, $argObj); $argHandlerAddEntryMethod = new ReflectionMethod($this->argHandler, '_addExpectedArgument'); $argHandlerAddEntryMethod->setAccessible(true); $argHandlerAddEntryMethod->invoke($this->argHandler, $argObj); } protected function createArgumentHandler() { $this->argHandler = new VNagArgumentHandler(); } protected function createHelpObject() { $this->helpObj = new VNagHelp(); } protected function checkInitialized() { if (!$this->initialized) throw new VNagFunctionCallOutsideSession(); } protected function getVerbosityLevel() { $this->checkInitialized(); if (!isset($this->argVerbosity)) { return self::VERBOSITY_SUMMARY; } else { $level = $this->argVerbosity->count(); if ($level > self::MAX_VERBOSITY) $level = self::MAX_VERBOSITY; return $level; } } public function getWarningRange($argumentNumber=0) { $this->checkInitialized(); if (!isset($this->warningRanges[$argumentNumber])) { if (!is_null($this->argWarning)) { $warning = $this->argWarning->getValue(); if (!is_null($warning)) { $vals = explode(',',$warning); foreach ($vals as $number => $val) { if (_empty($val)) { $this->warningRanges[$number] = null; } else { $singleValueBehavior = isset($this->warningSingleValueRangeBehaviors[$number]) ? $this->warningSingleValueRangeBehaviors[$number] : VNag::SINGLEVALUE_RANGE_DEFAULT; $this->warningRanges[$number] = new VNagRange($val, $singleValueBehavior); } } } else { $this->warningRanges[0] = $this->default_warning_range; } } else { return null; } } if (isset($this->warningRanges[$argumentNumber])) { return $this->warningRanges[$argumentNumber]; } else { return null; } } public function getCriticalRange($argumentNumber=0) { $this->checkInitialized(); if (!isset($this->criticalRanges[$argumentNumber])) { if (!is_null($this->argCritical)) { $critical = $this->argCritical->getValue(); if (!is_null($critical)) { $vals = explode(',',$critical); foreach ($vals as $number => $val) { $singleValueBehavior = isset($this->criticalSingleValueRangeBehaviors[$number]) ? $this->criticalSingleValueRangeBehaviors[$number] : VNag::SINGLEVALUE_RANGE_DEFAULT; $this->criticalRanges[$number] = new VNagRange($val, $singleValueBehavior); } } else { $this->criticalRanges[0] = $this->default_critical_range; } } else { return null; } } if (isset($this->criticalRanges[$argumentNumber])) { return $this->criticalRanges[$argumentNumber]; } else { return null; } } public function checkAgainstWarningRange($values, $force=true, $autostatus=true, $argumentNumber=0) { $this->checkInitialized(); if (!$this->getArgumentHandler()->isArgRegistered('w')) { throw new VNagRequiredArgumentNotRegistered('-w'); } $wr = $this->getWarningRange($argumentNumber); if (isset($wr)) { if ($wr->checkAlert($values)) { if ($autostatus) $this->setStatus(VNag::STATUS_WARNING); return true; } else { if ($autostatus) $this->setStatus(VNag::STATUS_OK); return false; } } else { if ($force) { if (($argumentNumber > 0) && (count($this->warningRanges) > 0)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$too_few_warning_ranges, $argumentNumber+1)); } else { throw new VNagRequiredArgumentMissing('-w'); } } } } public function checkAgainstCriticalRange($values, $force=true, $autostatus=true, $argumentNumber=0) { $this->checkInitialized(); if (!$this->getArgumentHandler()->isArgRegistered('c')) { throw new VNagRequiredArgumentNotRegistered('-c'); } $cr = $this->getCriticalRange($argumentNumber); if (isset($cr)) { if ($cr->checkAlert($values)) { if ($autostatus) $this->setStatus(VNag::STATUS_CRITICAL); return true; } else { if ($autostatus) $this->setStatus(VNag::STATUS_OK); return false; } } else { if ($force) { if (($argumentNumber > 0) && (count($this->warningRanges) > 0)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$too_few_critical_ranges, $argumentNumber+1)); } else { throw new VNagRequiredArgumentMissing('-c'); } } } } protected static function getBaddestExitcode($code1, $code2) { return max($code1, $code2); } public static function _shutdownHandler() { if (!self::is_http_mode()) { exit((int)self::$exitcode); } } protected function _exit($code) { self::$exitcode = $this->getBaddestExitcode($code, self::$exitcode); } private $constructed = false; function __construct() { $this->createHelpObject(); $this->createArgumentHandler(); $this->addExpectedArgument($this->argUsage = new VNagArgument('?', '', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$prints_usage)); $this->constructed = true; } function __destruct() { if (Timeouter::started()) { Timeouter::end(); } } public function run() { global $inside_vnag_run; $inside_vnag_run = true; try { if (!$this->constructed) { throw new VNagNotConstructed(VNagLang::$notConstructed); } try { $this->initialized = true; $this->html_before = ''; $this->html_after = ''; $this->setStatus(null, true); $this->messages = array(); register_shutdown_function(array($this, '_shutdownHandler')); if ($this->argHandler->illegalUsage()) { $content = $this->helpObj->printUsagePage(); $this->setStatus(VNag::STATUS_UNKNOWN); if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_visual_output & VNag::OUTPUT_SPECIAL) echo $this->writeVisualHTML($content); if ($this->http_invisible_output & VNag::OUTPUT_SPECIAL) echo $this->writeInvisibleHTML($content); echo $this->html_after; return; } else { echo $content; return $this->_exit($this->status); } } if (!is_null($this->argVersion) && ($this->argVersion->available())) { $content = $this->helpObj->printVersionPage(); $this->setStatus(VNag::STATUS_UNKNOWN); if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_visual_output & VNag::OUTPUT_SPECIAL) echo $this->writeVisualHTML($content); if ($this->http_invisible_output & VNag::OUTPUT_SPECIAL) echo $this->writeInvisibleHTML($content); echo $this->html_after; return; } else { echo $content; return $this->_exit($this->status); } } if (!is_null($this->argHelp) && ($this->argHelp->available())) { $content = $this->helpObj->printHelpPage(); $this->setStatus(VNag::STATUS_UNKNOWN); if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_visual_output & VNag::OUTPUT_SPECIAL) echo $this->writeVisualHTML($content); if ($this->http_invisible_output & VNag::OUTPUT_SPECIAL) echo $this->writeInvisibleHTML($content); echo $this->html_after; return; } else { echo $content; return $this->_exit($this->status); } } $this->getWarningRange(); $this->getCriticalRange(); if (!is_null($this->argTimeout)) { $timeout = $this->argTimeout->getValue(); if (!is_null($timeout)) { Timeouter::start($timeout); } } ob_start(); $init_ob_level = ob_get_level(); try { $this->cbRun(); if (ob_get_level() < $init_ob_level) throw new VNagImplementationErrorException(VNagLang::$output_level_lowered); } finally { while (ob_get_level() > $init_ob_level) @ob_end_clean(); } if (is_null($this->status)) $this->setStatus($this->default_status,true); $outputType = VNag::OUTPUT_NORMAL; } catch (Exception $e) { $this->handleException($e); $outputType = VNag::OUTPUT_EXCEPTION; } if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_invisible_output & $outputType) { echo $this->writeInvisibleHTML(); } if ($this->http_visual_output & $outputType) { echo $this->writeVisualHTML(); } echo $this->html_after; } else { echo $this->getNagiosConsoleText(); return $this->_exit($this->status); } Timeouter::end(); } finally { $inside_vnag_run = false; } } private function getNagiosConsoleText() { $ary_perfdata = $this->getPerformanceData(); $performancedata_first = array_shift($ary_perfdata); $performancedata_rest = implode(' ', $ary_perfdata); $status_text = VNagLang::status($this->status, $this->statusmodel); if (_empty($this->getHeadline())) { $content = $status_text; } else { if ($this->show_status_in_headline) { $content = $status_text.': '.$this->getHeadline(); } else { $content = $this->getHeadline(); } } if (!_empty($performancedata_first)) $content .= '|'.trim($performancedata_first); $content .= "\n"; if (!_empty($this->verbose_info)) { $content .= trim($this->verbose_info); } if (!_empty($performancedata_rest)) $content .= '|'.trim($performancedata_rest); $content .= "\n"; return trim($content)."\n"; } abstract protected function cbRun(); public function addPerformanceData($prefDataObj, $move_to_font=false, $verbosityLevel=VNag::VERBOSITY_SUMMARY) { $this->checkInitialized(); if ((!isset($this->argVerbosity)) && ($verbosityLevel > VNag::VERBOSITY_SUMMARY)) throw new VNagRequiredArgumentNotRegistered('-v'); if (self::getVerbosityLevel() < $verbosityLevel) return false; if ($move_to_font) { array_unshift($this->performanceDataObjects, $prefDataObj); } else { $this->performanceDataObjects[] = $prefDataObj; } return true; } public function getPerformanceData() { $this->checkInitialized(); return $this->performanceDataObjects; } public function removePerformanceData($prefDataObj) { if (($key = array_search($prefDataObj, $this->performanceDataObjects, true)) !== false) { unset($this->performanceDataObjects[$key]); return true; } else { return false; } } public function clearPerformanceData() { $this->performanceDataObjects = array(); } public function getVerboseInfo() { return $this->verbose_info; } public function clearVerboseInfo() { $this->verbose_info = ''; } private function writeVisualHTML($special_content=null) { if (!_empty($special_content)) { $content = $special_content; } else { $content = strtoupper(VNagLang::$status.': '.VNagLang::status($this->status, $this->statusmodel))."\n\n"; $content .= strtoupper(VNagLang::$message).":\n"; $status_text = VNagLang::status($this->status, $this->statusmodel); if (_empty($this->getHeadline())) { $content .= $status_text; } else { if ($this->show_status_in_headline) { $content .= $status_text.': '.trim($this->getHeadline()); } else { $content .= trim($this->getHeadline()); } } $content .= "\n\n"; if (!_empty($this->verbose_info)) { $content .= strtoupper(VNagLang::$verbose_info).":\n".trim($this->verbose_info)."\n\n"; } $perfdata = $this->getPerformanceData(); if (count($perfdata) > 0) { $content .= strtoupper(VNagLang::$performance_data).":\n"; foreach ($perfdata as $pd) { $content .= trim($pd)."\n"; } $content .= "\n"; } } $colorinfo = ''; $status = $this->getStatus(); if ($status == VNag::STATUS_OK) $colorinfo = ' style="background-color:green;color:white;font-weight:bold"'; else if ($status == VNag::STATUS_WARNING) $colorinfo = ' style="background-color:yellow;color:black;font-weight:bold"'; else if ($status == VNag::STATUS_CRITICAL) $colorinfo = ' style="background-color:red;color:white;font-weight:bold"'; else if ($status == VNag::STATUS_ERROR) $colorinfo = ' style="background-color:purple;color:white;font-weight:bold"'; else $colorinfo = ' style="background-color:lightgray;color:black;font-weight:bold"'; $html_content = trim($content); $html_content = htmlentities($html_content); $html_content = str_replace(' ', '&nbsp;', $html_content); $html_content = nl2br($html_content); return '<table border="1" cellspacing="2" cellpadding="2" style="width:100%" class="vnag_table">'. '<tr'.$colorinfo.' class="vnag_title_row">'. '<td>'.VNagLang::$nagios_output.'</td>'. '</tr>'. '<tr class="vnag_message_row">'. '<td><code>'. $html_content. '</code></td>'. '</tr>'. '</table>'; } protected function readInvisibleHTML($html) { $this->checkInitialized(); $doc = new DOMDocument(); @$doc->loadHTML($html); $tags = $doc->getElementsByTagName('script'); foreach ($tags as $tag) { $type = $tag->getAttribute('type'); if ($type !== 'application/json') continue; $json = $tag->nodeValue; if (!$json) continue; $data = @json_decode($json,true); if (!is_array($data)) continue; if (!isset($data['type'])) continue; if ($data['type'] === VNAG_JSONDATA_V1) { if (!isset($data['datasets'])) throw new VNagWebInfoException(VNagLang::$dataset_missing); foreach ($data['datasets'] as $dataset) { $payload = base64_decode($dataset['payload']); if (!$payload) { throw new VNagWebInfoException(VNagLang::$payload_not_base64); } if (isset($dataset['encryption'])) { $cryptInfo = $dataset['encryption']; if (!is_array($cryptInfo)) { throw new VNagWebInfoException(VNagLang::$dataset_encryption_no_array); } $password = is_null($this->password_in) ? '' : $this->password_in; $salt = base64_decode($cryptInfo['salt']); if ($cryptInfo['hash'] != hash('sha256',$salt.$password)) { if ($password == '') { throw new VNagWebInfoException(VNagLang::$require_password); } else { throw new VNagWebInfoException(VNagLang::$wrong_password); } } if (!function_exists('openssl_decrypt')) { throw new VNagException(VNagLang::$openssl_missing); } $payload = openssl_decrypt($payload, $cryptInfo['method'], $password, 0, $cryptInfo['iv']); } if (!is_null($this->pubkey) && ($this->pubkey !== '')) { if (substr($this->pubkey,0,3) === '---') { $public_key = $this->pubkey; } else { if (!file_exists($this->pubkey)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$pubkey_file_not_found, $this->pubkey)); } $public_key = @file_get_contents($this->pubkey); if (!$public_key) { throw new VNagPublicKeyException(sprintf(VNagLang::$pubkey_file_not_readable, $this->pubkey)); } } if (!isset($dataset['signature'])) { throw new VNagSignatureException(VNagLang::$signature_missing); } $signature = base64_decode($dataset['signature']); if (!$signature) { throw new VNagSignatureException(VNagLang::$signature_not_bas64); } if (!function_exists('openssl_verify')) { throw new VNagException(VNagLang::$openssl_missing); } $sign_algo = is_null($this->sign_algo) ? OPENSSL_ALGO_SHA256 : $this->sign_algo; if (!openssl_verify($payload, $signature, $public_key, $sign_algo)) { throw new VNagSignatureException(VNagLang::$signature_invalid); } } $payload = @json_decode($payload,true); if (!$payload) { throw new VNagWebInfoException(VNagLang::$payload_not_json); } if ($payload['id'] == $this->id) { return $payload; } } } } return null; } private function getNextMonitorID($peek=false) { $result = is_null($this->id) ? self::$http_serial_number : $this->id; if (!$peek) { $this->id = null; self::$http_serial_number++; } return $result; } private function writeInvisibleHTML($special_content=null) { $payload['id'] = $this->getNextMonitorID(); $payload['status'] = $this->getStatus(); if (!_empty($special_content)) { $payload['text'] = $special_content; } else { $payload['headline'] = $this->getHeadline(); $payload['verbose_info'] = $this->verbose_info; $payload['performance_data'] = array(); foreach ($this->performanceDataObjects as $perfdata) { $payload['performance_data'][] = (string)$perfdata; } } $payload = json_encode($payload); $dataset = array(); if (!is_null($this->privkey) && ($this->privkey !== '')) { if (!function_exists('openssl_pkey_get_private') || !function_exists('openssl_sign')) { throw new VNagException(VNagLang::$openssl_missing); } if (substr($this->privkey,0,3) === '---') { $pkeyid = @openssl_pkey_get_private($this->privkey, $this->privkey_password); if (!$pkeyid) { throw new VNagPrivateKeyException(sprintf(VNagLang::$privkey_not_readable)); } } else { if (!file_exists($this->privkey)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$privkey_file_not_found, $this->privkey)); } $pkeyid = @openssl_pkey_get_private('file://'.$this->privkey, $this->privkey_password); if (!$pkeyid) { throw new VNagPrivateKeyException(sprintf(VNagLang::$privkey_file_not_readable, $this->privkey)); } } $signature = ''; $sign_algo = is_null($this->sign_algo) ? OPENSSL_ALGO_SHA256 : $this->sign_algo; if (@openssl_sign($payload, $signature, $pkeyid, $sign_algo)) { if (version_compare(PHP_VERSION, '8.0.0') < 0) { openssl_free_key($pkeyid); } $dataset['signature'] = base64_encode($signature); } else { throw new VNagPrivateKeyException(sprintf(VNagLang::$signature_failed)); } } if (!is_null($this->password_out) && ($this->password_out !== '')) { if (!function_exists('openssl_encrypt')) { throw new VNagException(VNagLang::$openssl_missing); } $password = $this->password_out; $method = 'aes-256-ofb'; $iv = substr(hash('sha256', openssl_random_pseudo_bytes(32)), 0, 16); $salt = openssl_random_pseudo_bytes(32); $cryptInfo = array(); $cryptInfo['method'] = $method; $cryptInfo['iv'] = $iv; $cryptInfo['salt'] = base64_encode($salt); $cryptInfo['hash'] = hash('sha256', $salt.$password); $payload = openssl_encrypt($payload, $method, $password, 0, $iv); $dataset['encryption'] = $cryptInfo; } $dataset['payload'] = base64_encode($payload); $json = array(); $json['type'] = VNAG_JSONDATA_V1; $json['datasets'] = array($dataset); return '<script type="application/json">'. json_encode($json). '</script>'; } protected function appendHeadline($msg) { $this->checkInitialized(); if (_empty($msg)) return false; $this->messages[] = $msg; return true; } protected function changeHeadline($msg) { $this->checkInitialized(); if (_empty($msg)) { $this->messages = array(); } else { $this->messages = array($msg); } return true; } public function setHeadline($msg, $append=false, $verbosityLevel=VNag::VERBOSITY_SUMMARY) { $this->checkInitialized(); if ((!isset($this->argVerbosity)) && ($verbosityLevel > VNag::VERBOSITY_SUMMARY)) throw new VNagRequiredArgumentNotRegistered('-v'); if (self::getVerbosityLevel() < $verbosityLevel) $msg = ''; if ($append) { return $this->appendHeadline($msg); } else { return $this->changeHeadline($msg); } } public function getHeadline() { $this->checkInitialized(); return implode(', ', $this->messages); } public function addVerboseMessage($msg, $verbosityLevel=VNag::VERBOSITY_SUMMARY) { $this->checkInitialized(); if (self::getVerbosityLevel() >= $verbosityLevel) { $this->verbose_info .= $msg."\n"; } } public function setStatus($status, $force=false) { $this->checkInitialized(); if (($force) || is_null($this->status) || ($status > $this->status)) { $this->status = $status; } } public function getStatus() { $this->checkInitialized(); return $this->status; } protected static function exceptionText($exception) { $class = get_class($exception); $msg = $exception->getMessage(); if (!_empty($msg)) { return sprintf(VNagLang::$exception_x, $msg, $class); } else { return sprintf(VNagLang::$unhandled_exception_without_msg, $class); } } protected function handleException($exception) { $this->checkInitialized(); if (!VNag::is_http_mode()) { while (ob_get_level() > 0) @ob_end_clean(); } $this->clearVerboseInfo(); $this->clearPerformanceData(); if ($exception instanceof VNagException) { $this->setStatus($exception->getStatus()); } else { $this->setStatus(self::STATUS_ERROR); } $this->setHeadline($this->exceptionText($exception), false); if ($exception instanceof VNagImplementationErrorException) { $this->addVerboseMessage($exception->getTraceAsString(), VNag::VERBOSITY_SUMMARY); } else { if (isset($this->argVerbosity)) { $this->addVerboseMessage($exception->getTraceAsString(), VNag::VERBOSITY_ADDITIONAL_INFORMATION); } else { } } } protected function get_cache_dir() { $homedir = @getenv('HOME'); if ($homedir && is_dir($homedir)) { $try = "$homedir/.vnag/cache"; if (is_dir($try)) return $try; if (@mkdir($try,0777,true)) return $try; } $user = posix_getpwuid(posix_geteuid()); if (isset($user['dir']) && is_dir($user['dir'])) { $homedir = $user['dir']; $try = "$homedir/.vnag/cache"; if (is_dir($try)) return $try; if (@mkdir($try,0777,true)) return $try; } if (isset($user['name']) && is_dir($user['name'])) { $username = $user['name']; $try = "/tmp/vnag/cache"; if (is_dir($try)) return $try; if (@mkdir($try,0777,true)) return $try; } throw new VNagException("Cannot get cache dir"); } protected function url_get_contents($url, $max_cache_time=1*60*60, $context=null) { $cache_file = $this->get_cache_dir().'/'.hash('sha256',$url); if (file_exists($cache_file) && (time()-filemtime($cache_file) < $max_cache_time)) { $cont = @file_get_contents($cache_file); if ($cont === false) throw new Exception("Failed to get contents from $cache_file"); } else { $options = array( 'http'=>array( 'method'=>"GET", 'header'=>"Accept-language: en\r\n" . "User-Agent: Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B334b Safari/531.21.102011-10-16 20:23:10\r\n" ) ); if (is_null($context)) $context = stream_context_create($options); $cont = @file_get_contents($url, false, $context); if ($cont === false) throw new Exception("Failed to get contents from $url"); file_put_contents($cache_file, $cont); } return $cont; } } class VNagException extends Exception { public function getStatus() { return VNag::STATUS_ERROR; } } class VNagTimeoutException extends VNagException {} class VNagWebInfoException extends VNagException {} class VNagSignatureException extends VNagException {} class VNagPublicKeyException extends VNagException {} class VNagPrivateKeyException extends VNagException {} class VNagInvalidArgumentException extends VNagException { public function getStatus() { return VNag::STATUS_UNKNOWN; } } class VNagValueUomPairSyntaxException extends VNagInvalidArgumentException { public function __construct($str) { $e_msg = sprintf(VNagLang::$valueUomPairSyntaxError, $str); parent::__construct($e_msg); } } class VNagInvalidTimeoutException extends VNagInvalidArgumentException {} class VNagInvalidRangeException extends VNagInvalidArgumentException { public function __construct($msg) { $e_msg = VNagLang::$range_is_invalid; if (!_empty($msg)) $e_msg .= ': '.trim($msg); parent::__construct($e_msg); } } class VNagInvalidShortOpt extends VNagImplementationErrorException {} class VNagInvalidLongOpt extends VNagImplementationErrorException {} class VNagInvalidValuePolicy extends VNagImplementationErrorException {} class VNagIllegalStatusModel extends VNagImplementationErrorException {} class VNagNotConstructed extends VNagImplementationErrorException {} class VNagImplementationErrorException extends VNagException {} class VNagInvalidStandardArgument extends VNagImplementationErrorException {} class VNagFunctionCallOutsideSession extends VNagImplementationErrorException {} class VNagIllegalArgumentValuesException extends VNagImplementationErrorException {} class VNagRequiredArgumentNotRegistered extends VNagImplementationErrorException { public function __construct($required_argument) { $e_msg = sprintf(VNagLang::$query_without_expected_argument, $required_argument); parent::__construct($e_msg); } } class VNagRequiredArgumentMissing extends VNagInvalidArgumentException { public function __construct($required_argument) { $e_msg = sprintf(VNagLang::$required_argument_missing, $required_argument); parent::__construct($e_msg); } } class VNagUnknownUomException extends VNagInvalidArgumentException { public function __construct($uom) { $e_msg = sprintf(VNagLang::$perfdata_uom_not_recognized, $uom); parent::__construct($e_msg); } } class VNagNoCompatibleRangeUomFoundException extends VNagException {} class VNagMixedUomsNotImplemented extends VNagInvalidArgumentException { public function __construct($uom1, $uom2) { if (_empty($uom1)) $uom1 = VNagLang::$none; if (_empty($uom2)) $uom2 = VNagLang::$none; $e_msg = sprintf(VNagLang::$perfdata_mixed_uom_not_implemented, $uom1, $uom2); parent::__construct($e_msg); } } class VNagUomConvertException extends VNagInvalidArgumentException { public function __construct($uom1, $uom2) { if (_empty($uom1)) $uom1 = VNagLang::$none; if (_empty($uom2)) $uom2 = VNagLang::$none; $e_msg = sprintf(VNagLang::$convert_x_y_error, $uom1, $uom2); parent::__construct($e_msg); } } class VNagInvalidPerformanceDataException extends VNagInvalidArgumentException { public function __construct($msg) { $e_msg = VNagLang::$performance_data_invalid; if (!_empty($msg)) $e_msg .= ': '.trim($msg); parent::__construct($e_msg); } } class Timeouter { private static $start_time = false; private static $timeout; private static $fired = false; private static $registered = false; private function __construct() { } public static function start($timeout) { if (!is_numeric($timeout) || ($timeout <= 0)) { throw new VNagInvalidTimeoutException(sprintf(VNagLang::$timeout_value_invalid, $timeout)); } self::$start_time = microtime(true); self::$timeout = (float) $timeout; self::$fired = false; if (!self::$registered) { self::$registered = true; register_tick_function(array('Timeouter', 'tick')); } } public static function started() { return self::$registered; } public static function end() { if (self::$registered) { unregister_tick_function(array('Timeouter', 'tick')); self::$registered = false; } } public static function tick() { if ((!self::$fired) && ((microtime(true) - self::$start_time) > self::$timeout)) { self::$fired = true; throw new VNagTimeoutException(VNagLang::$timeout_exception); } } } class VNagArgument { const VALUE_FORBIDDEN = 0; const VALUE_REQUIRED = 1; const VALUE_OPTIONAL = 2; protected $shortopt; protected $longopts; protected $valuePolicy; protected $valueName; protected $helpText; protected $defaultValue = null; protected static $all_short = ''; protected static $all_long = array(); public function getShortOpt() { return $this->shortopt; } public function getLongOpts() { return $this->longopts; } public function getValuePolicy() { return $this->valuePolicy; } public function getValueName() { return $this->valueName; } public function getHelpText() { return $this->helpText; } static private function validateShortOpt($shortopt) { $m = array(); return preg_match('@^[a-zA-Z0-9\\+\\-\\?]$@', $shortopt, $m); } static private function validateLongOpt($longopt) { $m = array(); return preg_match('@^[a-zA-Z0-9\\+\\-\\?]+$@', $longopt, $m); } public function __construct($shortopt, $longopts, $valuePolicy, $valueName, $helpText, $defaultValue=null) { switch ($valuePolicy) { case VNagArgument::VALUE_FORBIDDEN: if (!_empty($valueName)) { throw new VNagImplementationErrorException(sprintf(VNagLang::$value_name_forbidden)); } break; case VNagArgument::VALUE_REQUIRED: if (_empty($valueName)) { throw new VNagImplementationErrorException(sprintf(VNagLang::$value_name_required)); } break; case VNagArgument::VALUE_OPTIONAL: if (_empty($valueName)) { throw new VNagImplementationErrorException(sprintf(VNagLang::$value_name_required)); } break; default: throw new VNagInvalidValuePolicy(sprintf(VNagLang::$illegal_valuepolicy, $valuePolicy)); } if (!_empty($shortopt)) { if (!self::validateShortOpt($shortopt)) { throw new VNagInvalidShortOpt(sprintf(VNagLang::$illegal_shortopt, $shortopt)); } } if (is_array($longopts)) { foreach ($longopts as $longopt) { if (!self::validateLongOpt($longopt)) { throw new VNagInvalidLongOpt(sprintf(VNagLang::$illegal_longopt, $longopt)); } } } else if (!_empty($longopts)) { if (!self::validateLongOpt($longopts)) { throw new VNagInvalidLongOpt(sprintf(VNagLang::$illegal_longopt, $longopts)); } $longopts = array($longopts); } else { $longopts = array(); } switch ($valuePolicy) { case VNagArgument::VALUE_FORBIDDEN: $policyApdx = ''; break; case VNagArgument::VALUE_REQUIRED: $policyApdx = ':'; break; case VNagArgument::VALUE_OPTIONAL: $policyApdx = '::'; break; default: throw new VNagInvalidValuePolicy(sprintf(VNagLang::$illegal_valuepolicy, $valuePolicy)); } if ((!is_null($shortopt)) && ($shortopt != '?')) self::$all_short .= $shortopt.$policyApdx; if (is_array($longopts)) { foreach ($longopts as $longopt) { self::$all_long[] = $longopt.$policyApdx; } } $this->shortopt = $shortopt; $this->longopts = $longopts; $this->valuePolicy = $valuePolicy; $this->valueName = $valueName; $this->helpText = $helpText; $this->defaultValue = $defaultValue; } protected static function getOptions() { global $OVERWRITE_ARGUMENTS; if (!is_null($OVERWRITE_ARGUMENTS)) { return $OVERWRITE_ARGUMENTS; } else if (VNag::is_http_mode()) { return $_REQUEST; } else { return getopt(self::$all_short, self::$all_long); } } public function count() { $options = self::getOptions(); $count = 0; if (isset($options[$this->shortopt])) { if (is_array($options[$this->shortopt])) { $count += count($options[$this->shortopt]); } else { $count += 1; } } if (!is_null($this->longopts)) { foreach ($this->longopts as $longopt) { if (isset($options[$longopt])) { if (is_array($options[$longopt])) { $count += count($options[$longopt]); } else { $count += 1; } } } } return $count; } public function available() { $options = self::getOptions(); if (isset($options[$this->shortopt])) return true; if (!is_null($this->longopts)) { foreach ($this->longopts as $longopt) { if (isset($options[$longopt])) return true; } } return false; } public function require() { if (!$this->available() && is_null($this->defaultValue)) { $opt = $this->shortopt; $opt = !_empty($opt) ? '-'.$opt : (isset($this->longopts[0]) ? '--'.$this->longopts[0] : '?'); throw new VNagRequiredArgumentMissing($opt); } } public function getValue() { $options = self::getOptions(); if (isset($options[$this->shortopt])) { $x = $options[$this->shortopt]; if (is_array($x) && (count($x) <= 1)) $options[$this->shortopt] = $options[$this->shortopt][0]; return $options[$this->shortopt]; } if (!is_null($this->longopts)) { foreach ($this->longopts as $longopt) { if (isset($options[$longopt])) { $x = $options[$longopt]; if (is_array($x) && (count($x) <= 1)) $options[$longopt] = $options[$longopt][0]; return $options[$longopt]; } } } return $this->defaultValue; } } class VNagArgumentHandler { protected $expectedArgs = array(); protected function _addExpectedArgument($argObj) { if ($argObj->getShortOpt() == '?') return false; if ($argObj->getShortOpt() == '-') return false; if ($argObj->getShortOpt() == '+') return false; $this->expectedArgs[] = $argObj; return true; } public function getArgumentObj($shortopt) { foreach ($this->expectedArgs as $argObj) { if ($argObj->getShortOpt() == $shortopt) return $argObj; } return null; } public function isArgRegistered($shortopt) { return !is_null($this->getArgumentObj($shortopt)); } public function illegalUsage() { global $argv; return (isset($argv[1])) && (($argv[1] == '-?') || ($argv[1] == '/?')); } } class VNagRange { public $start; public $end; public $warnInsideRange; public function __construct($rangeDef, $singleValueBehavior=VNag::SINGLEVALUE_RANGE_DEFAULT) { $m = array(); if (!preg_match('|^(@){0,1}([^:]+)(:){0,1}(.*)$|', $rangeDef, $m)) { throw new VNagInvalidRangeException(sprintf(VNagLang::$range_invalid_syntax, $rangeDef)); } $this->warnInsideRange = $m[1] === '@'; $this->start = null; $this->end = null; if ($m[3] === ':') { if ($m[2] === '~') { $this->start = '-inf'; } else { $this->start = new VNagValueUomPair($m[2]); } if (_empty($m[4])) { $this->end = 'inf'; } else { $this->end = new VNagValueUomPair($m[4]); } } else { assert(_empty($m[4])); assert(!_empty($m[2])); $x = $m[2]; if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_DEFAULT) { $this->start = new VNagValueUomPair('0'.((new VNagValueUomPair($x))->getUom())); $this->end = new VNagValueUomPair($x); } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_GT_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 0; $this->start = '-inf'; $this->end = new VNagValueUomPair($x); } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_GE_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 1; $this->start = new VNagValueUomPair($x); $this->end = 'inf'; } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_LT_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 0; $this->start = new VNagValueUomPair($x); $this->end = 'inf'; } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_LE_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 1; $this->start = '-inf'; $this->end = new VNagValueUomPair($x); } else { throw new VNagException(VNagLang::$illegalSingleValueBehavior); } } if (is_null($this->start)) { throw new VNagInvalidRangeException(VNagLang::$invalid_start_value); } if (is_null($this->end)) { throw new VNagInvalidRangeException(VNagLang::$invalid_end_value); } if (($this->start instanceof VNagValueUomPair) && ($this->end instanceof VNagValueUomPair) && (VNagValueUomPair::compare($this->start,$this->end) > 0)) { throw new VNagInvalidRangeException(VNagLang::$start_is_greater_than_end); } } public function __toString() { $ret = ''; if ($this->warnInsideRange) { $ret = '@'; } if ($this->start === '-inf') { $ret .= '~'; } else { $ret .= $this->start; } $ret .= ':'; if ($this->end !== 'inf') { $ret .= $this->end; } return $ret; } public function checkAlert($values) { $compatibleCount = 0; if (!is_array($values)) $values = array($values); foreach ($values as $value) { if (!($value instanceof VNagValueUomPair)) $value = new VNagValueUomPair($value); assert(($this->start === '-inf') || ($this->start instanceof VNagValueUomPair)); assert(($this->end === 'inf' ) || ($this->end instanceof VNagValueUomPair)); if (($this->start !== '-inf') && (!$this->start->compatibleWith($value))) continue; if (($this->end !== 'inf') && (!$this->end->compatibleWith($value))) continue; $compatibleCount++; if ($this->warnInsideRange) { return (($this->start === '-inf') || (VNagValueUomPair::compare($value,$this->start) >= 0)) && (($this->end === 'inf') || (VNagValueUomPair::compare($value,$this->end) <= 0)); } else { return (($this->start !== '-inf') && (VNagValueUomPair::compare($value,$this->start) < 0)) || (($this->end !== 'inf') && (VNagValueUomPair::compare($value,$this->end) > 0)); } } if ((count($values) > 0) and ($compatibleCount == 0)) { throw new VNagNoCompatibleRangeUomFoundException(VNagLang::$no_compatible_range_uom_found); } return false; } } class VNagValueUomPair { protected $value; protected $uom; public $roundTo = -1; public function isRelative() { return $this->uom === '%'; } public function getValue() { return $this->value; } public function getUom() { return $this->uom; } public function __toString() { if ($this->roundTo == -1) { return $this->value.$this->uom; } else { return round($this->value,$this->roundTo).$this->uom; } } public function __construct($str) { $m = array(); if (!preg_match('/^([\d\.]+)(.*)$/ism', $str, $m)) { throw new VNagValueUomPairSyntaxException($str); } $this->value = $m[1]; $this->uom = isset($m[2]) ? $m[2] : ''; if (!self::isKnownUOM($this->uom)) { throw new VNagUnknownUomException($this->uom); } } public static function isKnownUOM(string $uom) { $no_unit = ($uom === ''); $seconds = ($uom === 's') || ($uom === 'ms') || ($uom === 'us'); $percentage = ($uom === '%'); $bytes = ($uom === 'B') || ($uom === 'KB') || ($uom === 'MB') || ($uom === 'GB') || ($uom === 'TB'); $counter = ($uom === 'c'); return ($no_unit || $seconds || $percentage || $bytes || $counter); } public function normalize($target=null) { $res = clone $this; if ($res->uom === 'ms') { $res->uom = 's'; $res->value /= 1000; } if ($res->uom === 'us') { $res->uom = 's'; $res->value /= 1000 * 1000; } if ($res->uom === 'B') { $res->uom = 'MB'; $res->value /= 1024 * 1024; } if ($res->uom === 'KB') { $res->uom = 'MB'; $res->value /= 1024; } if ($res->uom === 'GB') { $res->uom = 'MB'; $res->value *= 1024; } if ($res->uom === 'TB') { $res->uom = 'MB'; $res->value *= 1024 * 1024; } if ($res->uom === 'c') { $res->uom = ''; } if (!is_null($target)) { if ($res->uom == 'MB') { if ($target == 'B') { $res->uom = 'B'; $res->value *= 1024 * 1024; } else if ($target == 'KB') { $res->uom = 'KB'; $res->value *= 1024; } else if ($target == 'MB') { $res->uom = 'MB'; $res->value *= 1; } else if ($target == 'GB') { $res->uom = 'GB'; $res->value /= 1024; } else if ($target == 'TB') { $res->uom = 'TB'; $res->value /= 1024 * 1024; } else { throw new VNagUomConvertException($res->uom, $target); } } else if ($res->uom == 's') { if ($target == 's') { $res->uom = 's'; $res->value /= 1; } else if ($target == 'ms') { $res->uom = 'ms'; $res->value /= 1000; } else if ($target == 'us') { $res->uom = 'us'; $res->value /= 1000 * 1000; } else { throw new VNagUomConvertException($res->uom, $target); } } else { throw new VNagUomConvertException($res->uom, $target); } } return $res; } public function compatibleWith(VNagValueUomPair $other) { $a = $this->normalize(); $b = $other->normalize(); return ($a->uom == $b->uom); } public static function compare(VNagValueUomPair $left, VNagValueUomPair $right) { $a = $left->normalize(); $b = $right->normalize(); if ($a->uom != $b->uom) throw new VNagMixedUomsNotImplemented($a->uom, $b->uom); if ($a->value > $b->value) return 1; if ($a->value == $b->value) return 0; if ($a->value < $b->value) return -1; } } class VNagPerformanceData { protected $label; protected $value; protected $warn = null; protected $crit = null; protected $min = null; protected $max = null; public static function createByString($perfdata) { $perfdata = trim($perfdata); $ary = explode('=',$perfdata); if (count($ary) != 2) { throw new VNagInvalidPerformanceDataException(sprintf(VNagLang::$perfdata_line_invalid, $perfdata)); } $label = $ary[0]; $bry = explode(';',$ary[1]); if (substr($label,0,1) === "'") $label = substr($label, 1, strlen($label)-2); $value = $bry[0]; $warn = isset($bry[1]) ? $bry[1] : null; $crit = isset($bry[2]) ? $bry[2] : null; $min = isset($bry[3]) ? $bry[3] : null; $max = isset($bry[4]) ? $bry[4] : null; return new self($label, $value, $warn, $crit, $min, $max); } public function __construct($label, $value, $warn=null, $crit=null, $min=null, $max=null) { if (strpos($label, '=') !== false) throw new VNagInvalidPerformanceDataException(VNagLang::$perfdata_label_equal_sign_forbidden); $label = str_replace("'", "''", $label); $m = array(); if ((!_empty($min)) && (!preg_match('|^[-0-9\\.]+$|', $min, $m))) { throw new VNagInvalidPerformanceDataException(VNagLang::$perfdata_min_must_be_in_class); } if ((!_empty($max)) && (!preg_match('|^[-0-9\\.]+$|', $max, $m))) { throw new VNagInvalidPerformanceDataException(VNagLang::$perfdata_max_must_be_in_class); } $this->label = $label; $this->value = ($value == 'U') ? 'U' : new VNagValueUomPair($value); $this->warn = $warn; $this->crit = $crit; $this->min = $min; $this->max = $max; } public function __toString() { $label = $this->label; $value = $this->value; $warn = $this->warn; $crit = $this->crit; $min = $this->min; $max = $this->max; $label = str_replace("''", "'", $label); return "'$label'=$value". ';'.(is_null($warn) ? '' : $warn). ';'.(is_null($crit) ? '' : $crit). ';'.(is_null($min) ? '' : $min). ';'.(is_null($max) ? '' : $max); } } class VNagHelp { public $word_wrap_width = 80; public $argument_indent = 7; public function printUsagePage() { $usage = $this->getUsage(); if (_empty($usage)) { $usage = VNagLang::$no_syntax_defined; } return trim($usage)."\n"; } public function printVersionPage() { $out = trim($this->getNameAndVersion())."\n"; if ($this->word_wrap_width > 0) $out = wordwrap($out, $this->word_wrap_width, "\n", false); return $out; } static private function _conditionalLine($line, $terminator='', $prefix='') { if (!_empty($line)) { return trim($line).$terminator; } return ''; } public function printHelpPage() { $out = ''; $out .= self::_conditionalLine($this->getNameAndVersion(), "\n"); $out .= self::_conditionalLine($this->getCopyright(), "\n"); $out .= ($out != '') ? "\n" : ''; $out .= self::_conditionalLine($this->getShortDescription(), "\n\n\n"); $out .= self::_conditionalLine($this->getUsage(), "\n\n"); $out .= VNagLang::$options."\n"; foreach ($this->options as $argObj) { $out .= $this->printArgumentHelp($argObj); } $out .= self::_conditionalLine($this->getFootNotes(), "\n\n", "\n"); if ($this->word_wrap_width > 0) $out = wordwrap($out, $this->word_wrap_width, "\n", false); return $out; } protected $options = array(); protected function _addOption($argObj) { $this->options[] = $argObj; } protected function printArgumentHelp($argObj) { $identifiers = array(); $shortopt = $argObj->getShortopt(); if (!_empty($shortopt)) $identifiers[] = '-'.$shortopt; $longopts = $argObj->getLongopts(); if (!is_null($longopts)) { foreach ($longopts as $longopt) { if (!_empty($longopt)) $identifiers[] = '--'.$longopt; } } if (count($identifiers) == 0) return; $valueName = $argObj->getValueName(); $arginfo = ''; switch ($argObj->getValuePolicy()) { case VNagArgument::VALUE_FORBIDDEN: $arginfo = ''; break; case VNagArgument::VALUE_REQUIRED: $arginfo = '='.$valueName; break; case VNagArgument::VALUE_OPTIONAL: $arginfo = '[='.$valueName.']'; break; } $out = ''; $out .= implode(', ', $identifiers).$arginfo."\n"; $content = trim($argObj->getHelpText()); if ($this->word_wrap_width > 0) $content = wordwrap($content, $this->word_wrap_width-$this->argument_indent, "\n", false); $lines = explode("\n", $content); foreach ($lines as $line) { $out .= str_repeat(' ', $this->argument_indent).$line."\n"; } $out .= "\n"; return $out; } protected $pluginName; public function setPluginName($pluginName) { $this->pluginName = $this->replaceStuff($pluginName); } public function getPluginName() { if (_empty($this->pluginName)) { global $argv; return basename($argv[0]); } else { return $this->pluginName; } } protected $version; public function setVersion($version) { $this->version = $this->replaceStuff($version); } public function getVersion() { return $this->version; } public function getNameAndVersion() { $ret = $this->getPluginName(); if (_empty($ret)) return null; $ver = $this->getVersion(); if (!_empty($ver)) { $ret = sprintf(VNagLang::$x_version_x, $ret, $ver); } $ret = trim($ret); return $ret; } protected $copyright; public function setCopyright($copyright) { $this->copyright = $this->replaceStuff($copyright); } private function getVNagCopyright() { if (VNag::is_http_mode()) { $vts_email = 'www.viathinksoft.com'; } else { $vts_email = base64_decode('aW5mb0B2aWF0aGlua3NvZnQuZGU='); } return "VNag Framework ".VNag::VNAG_VERSION." (C) 2014-".date('Y')." ViaThinkSoft <$vts_email>"; } public function getCopyright() { if (_empty($this->copyright)) { return sprintf(VNagLang::$plugin_uses, $this->getVNagCopyright()); } else { return trim($this->copyright)."\n".sprintf(VNagLang::$uses, $this->getVNagCopyright()); } } protected $shortDescription; public function setShortDescription($shortDescription) { $this->shortDescription = $this->replaceStuff($shortDescription); } public function getShortDescription() { if (_empty($this->shortDescription)) { return null; } else { $content = $this->shortDescription; if ($this->word_wrap_width > 0) $content = wordwrap($content, $this->word_wrap_width, "\n", false); return $content; } } protected function replaceStuff($text) { global $argv; if (php_sapi_name() == 'cli') { $text = str_replace('$SCRIPTNAME$', $argv[0], $text); } else { $text = str_replace('$SCRIPTNAME$', basename($_SERVER['SCRIPT_NAME']), $text); } $text = str_replace('$CURYEAR$', date('Y'), $text); return $text; } protected $syntax; public function setSyntax($syntax) { $syntax = $this->replaceStuff($syntax); $this->syntax = $syntax; } public function getUsage() { if (_empty($this->syntax)) { return null; } else { return sprintf(VNagLang::$usage_x, $this->syntax); } } protected $footNotes; public function setFootNotes($footNotes) { $this->footNotes = $this->replaceStuff($footNotes); } public function getFootNotes() { return $this->footNotes; } } class VNagLang { public static function status($code, $statusmodel) { switch ($statusmodel) { case VNag::STATUSMODEL_SERVICE: switch ($code) { case VNag::STATUS_OK: return 'OK'; case VNag::STATUS_WARNING: return 'Warning'; case VNag::STATUS_CRITICAL: return 'Critical'; case VNag::STATUS_UNKNOWN: return 'Unknown'; default: return sprintf('Error (%d)', $code); } case VNag::STATUSMODEL_HOST: switch ($code) { case VNag::STATUS_UP: return 'Up'; case VNag::STATUS_DOWN: return 'Down'; default: return sprintf('Maintain last state (%d)', $code); } default: throw new VNagIllegalStatusModel(sprintf(self::$illegal_statusmodel, $statusmodel)); } } static $nagios_output = 'VNag-Output'; static $verbose_info = 'Verbose information'; static $status = 'Status'; static $message = 'Message'; static $performance_data = 'Performance data'; static $status_ok = 'OK'; static $status_warn = 'Warning'; static $status_critical = 'Critical'; static $status_unknown = 'Unknown'; static $status_error = 'Error'; static $unhandled_exception_without_msg = "Unhandled exception of type %s"; static $plugin_uses = 'This plugin uses %s'; static $uses = 'uses %s'; static $x_version_x = '%s, version %s'; static $argname_value = 'value'; static $argname_seconds = 'seconds'; static $query_without_expected_argument = "The argument '%s' is queried, but was not added to the list of expected arguments. Please contact the plugin author."; static $required_argument_missing = "The argument '%s' is required."; static $performance_data_invalid = 'Performance data invalid.'; static $no_standard_arguments_with_letter = "No standard argument with letter '%s' exists."; static $invalid_start_value = 'Invalid start value.'; static $invalid_end_value = 'Invalid end value.'; static $start_is_greater_than_end = 'Start is greater than end value.'; static $value_name_forbidden = "Implementation error: You may not define a value name for the argument, because the value policy is VALUE_FORBIDDEN."; static $value_name_required = "Implementation error: Please define a name for the argument (so it can be shown in the help page)."; static $illegal_shortopt = "Illegal shortopt '-%s'."; static $illegal_longopt = "Illegal longopt '--%s'."; static $illegal_valuepolicy = "valuePolicy has illegal value '%s'."; static $range_invalid_syntax = "Syntax error in range '%s'."; static $timeout_value_invalid = "Timeout value '%s' is invalid."; static $range_is_invalid = 'Range is invalid.'; static $timeout_exception = 'Timeout!'; static $perfdata_label_equal_sign_forbidden = 'Label may not contain an equal sign.'; static $perfdata_value_must_be_in_class = 'Value must be in class [-0-9.] or be \'U\' if the actual value can\'t be determined.'; static $perfdata_min_must_be_in_class = 'Min must be in class [-0-9.] or empty.'; static $perfdata_max_must_be_in_class = 'Max must be in class [-0-9.] or empty.'; static $perfdata_uom_not_recognized = 'UOM (unit of measurement) "%s" is not recognized.'; static $perfdata_mixed_uom_not_implemented = 'Mixed UOMs (%s and %s) are currently not supported.'; static $no_compatible_range_uom_found = 'Measured values are not compatible with the provided warning/critical parameter. Most likely, the UOM is incompatible.'; static $exception_x = '%s (%s)'; static $no_syntax_defined = 'The author of this plugin has not defined a syntax for this plugin.'; static $usage_x = "Usage:\n%s"; static $options = "Options:"; static $illegal_statusmodel = "Invalid statusmodel %d."; static $none = '[none]'; static $valueUomPairSyntaxError = 'Syntax error at "%s". Syntax must be Value[UOM].'; static $too_few_warning_ranges = "You have too few warning ranges (currently trying to get element %d)."; static $too_few_critical_ranges = "You have too few critical ranges (currently trying to get element %d)."; static $dataset_missing = 'Dataset missing.'; static $payload_not_base64 = 'The payload is not valid Base64.'; static $payload_not_json = 'The payload is not valid JSON.'; static $signature_missing = 'The signature is missing.'; static $signature_not_bas64 = 'The signature is not valid Base64.'; static $signature_invalid = 'The signature is invalid. The connection might have been tampered, or a different key is used.'; static $pubkey_file_not_found = "Public key file %s was not found."; static $pubkey_file_not_readable = "Public key file %s is not readable."; static $privkey_file_not_found = "Private key file %s was not found."; static $privkey_not_readable = "Private key is not readable."; static $privkey_file_not_readable = "Private key file %s is not readable."; static $signature_failed = "Signature failed."; static $perfdata_line_invalid = "Performance data line %s is invalid."; static $singlevalue_unexpected_at_symbol = 'This plugin does not allow the @-symbol at ranges for single values.'; static $illegalSingleValueBehavior = "Illegal value for 'singleValueBehavior'. Please contact the creator of the plugin."; static $dataset_encryption_no_array = 'Dataset encryption information invalid.'; static $require_password = 'This resource is protected with a password. Please provide a password.'; static $wrong_password = 'This resource is protected with a password. You have provided the wrong password, or it was changed.'; static $convert_x_y_error = 'Cannot convert from UOM %s to UOM %s.'; static $php_error = 'PHP has detected an error in the plugin. Please contact the plugin author.'; static $output_level_lowered = "Output Buffer level lowered during cbRun(). Please contact the plugin author."; static $openssl_missing = "OpenSSL is missing. Therefore, encryption and signatures are not available."; static $warning_range = 'Warning range'; static $critical_range = 'Critical range'; static $prints_version = 'Prints version'; static $verbosity_helptext = 'Verbosity -v, -vv or -vvv'; static $timeout_helptext = 'Sets timeout in seconds'; static $help_helptext = 'Prints help page'; static $prints_usage = 'Prints usage'; static $notConstructed = 'Parent constructor not called with parent::__construct().'; } function vnagErrorHandler($errorkind, $errortext, $file, $line) { global $inside_vnag_run; if (!$inside_vnag_run && VNag::is_http_mode()) { return false; } if (!(error_reporting() & $errorkind)) { return true; } if (defined('E_ERROR') && ($errorkind == E_ERROR)) $errorkind = 'Error'; if (defined('E_WARNING') && ($errorkind == E_WARNING)) $errorkind = 'Warning'; if (defined('E_PARSE') && ($errorkind == E_PARSE)) $errorkind = 'Parse'; if (defined('E_NOTICE') && ($errorkind == E_NOTICE)) $errorkind = 'Notice'; if (defined('E_CORE_ERROR') && ($errorkind == E_CORE_ERROR)) $errorkind = 'Core Error'; if (defined('E_CORE_WARNING') && ($errorkind == E_CORE_WARNING)) $errorkind = 'Core Warning'; if (defined('E_COMPILE_ERROR') && ($errorkind == E_COMPILE_ERROR)) $errorkind = 'Compile Error'; if (defined('E_COMPILE_WARNING') && ($errorkind == E_COMPILE_WARNING)) $errorkind = 'Compile Warning'; if (defined('E_USER_ERROR') && ($errorkind == E_USER_ERROR)) $errorkind = 'User Error'; if (defined('E_USER_WARNING') && ($errorkind == E_USER_WARNING)) $errorkind = 'User Warning'; if (defined('E_USER_NOTICE') && ($errorkind == E_USER_NOTICE)) $errorkind = 'User Notice'; if (defined('E_STRICT') && ($errorkind == E_STRICT)) $errorkind = 'Strict'; if (defined('E_RECOVERABLE_ERROR') && ($errorkind == E_RECOVERABLE_ERROR)) $errorkind = 'Recoverable Error'; if (defined('E_DEPRECATED') && ($errorkind == E_DEPRECATED)) $errorkind = 'Deprecated'; if (defined('E_USER_DEPRECATED') && ($errorkind == E_USER_DEPRECATED)) $errorkind = 'User Deprecated'; throw new VNagException(VNagLang::$php_error . " $errortext at $file:$line (kind $errorkind)"); } $inside_vnag_run = false; $old_error_handler = set_error_handler("vnagErrorHandler"); <?php
declare(ticks=1); class JoomlaVersionCheck extends VNag { protected $argSystemDir = null; public function __construct() { parent::__construct(); $this->registerExpectedStandardArguments('Vht'); $this->getHelpManager()->setPluginName('check_joomla_version'); $this->getHelpManager()->setVersion('2023-10-13'); $this->getHelpManager()->setShortDescription('This plugin checks if a local Joomla system has the latest version installed.'); $this->getHelpManager()->setCopyright('Copyright (C) 2011-$CURYEAR$ Daniel Marschall, ViaThinkSoft.'); $this->getHelpManager()->setSyntax('$SCRIPTNAME$ [-d <directory>]'); $this->getHelpManager()->setFootNotes('If you encounter bugs, please contact ViaThinkSoft at www.viathinksoft.com'); $this->addExpectedArgument($this->argSystemDir = new VNagArgument('d', 'directory', VNagArgument::VALUE_REQUIRED, 'joomlaPath', 'The local directory where your Joomla installation is located.')); } protected function get_versions($path) { $path = realpath($path) === false ? $path : realpath($path); $manifest_file = $path.'/administrator/manifests/files/joomla.xml'; if (!file_exists($manifest_file)) { throw new VNagException("Manifest file $manifest_file not found"); } $cont = @file_get_contents($manifest_file); if ($cont === false) { throw new VNagException("Cannot read $manifest_file"); } $manifest = new SimpleXMLElement($cont); $version = (string)$manifest->version; $count = 0; foreach ($manifest->updateservers->server as $updateserver) { $cont = $this->url_get_contents($updateserver); if ($cont !== false) { $extensions = new SimpleXMLElement($cont); foreach ($extensions as $candidate) { $count++; if ($version == (string)$candidate['version']) { $detailsurl = (string)$candidate['detailsurl']; if ($detailsurl == 'https://update.joomla.org/core/extension.xml') $type = 1; else if ($detailsurl == 'https://update.joomla.org/core/sts/extension_sts.xml') $type = 2; else $type = 0; return array($type, $version); } } } } if ($count == 0) { throw new VNagException("Error checking update servers"); } return array(-1, $version); } protected function cbRun($optional_args=array()) { $system_dir = $this->argSystemDir->getValue(); if (empty($system_dir)) { throw new VNagException("Please specify the directory of the Joomla installation."); } $system_dir = realpath($system_dir) === false ? $system_dir : realpath($system_dir); if (!is_dir($system_dir)) { throw new VNagException('Directory "'.$system_dir.'" not found.'); } list($type, $version) = $this->get_versions($system_dir); if ($type == 1) { $this->setStatus(VNag::STATUS_OK); $this->setHeadline("Version $version (Long-Term-Support) found at $system_dir", true); } else if ($type == 2) { $this->setStatus(VNag::STATUS_OK); $this->setHeadline("Version $version (Short-Term-Support) found at $system_dir", true); } else if ($type == 0) { $this->setStatus(VNag::STATUS_OK); $this->setHeadline("Version $version (supported) found at $system_dir", true); } else if ($type == -1) { $this->setStatus(VNag::STATUS_WARNING); $this->setHeadline("Version $version is outdated at $system_dir", true); } else { assert(false); } } } <?php
declare(ticks=1); require_once __DIR__ . '/../../framework/vnag_framework.inc.php'; require_once __DIR__ . '/JoomlaVersionCheck.class.php'; $job = new JoomlaVersionCheck(); $job->run(); unset($job); ˆ§Ýæ×èÒPNúÞÙÃí‹Aâ[%dêžo'ë³ÓH"?ü> ®.ôÖ>õGz«YVš8,£·¶Áïö³GBMB
+ïGBMB
\ No newline at end of file
/trunk/bin/last.phar
291,8 → 291,7
 
Extract_Phar::go();
__HALT_COMPILER(); ?>
[a:1:{s:23:"1.3.6.1.4.1.37476.3.0.2";s:301:"sha256||framework/vnag_framework.inc.php|460b109d1c578e9b6af41612e0312c9f36fd8beb51f7aa92f1b7bd49614568e8||plugins/last/LastCheck.class.php|0f98e4a4995c79075a8053e091ff8b06c0538c2a1098a0117b94a484f97d4062||plugins/last/check_last.phps|2c7e3d44ec93c30a8609aa4cb83573108dbd96ace57fa96e9c704021bfd27cff||";} framework/vnag_framework.inc.phpLÙyï*eLُ4p”¤ plugins/last/LastCheck.class.phpÆyï*eÆ:ª¥¤plugins/last/check_last.phpsºyï*eº•5ˆ¤<?php ?>
<?php
i§a:1:{s:23:"1.3.6.1.4.1.37476.3.0.2";s:377:"sha256||<builder>|481cf75d675006b504520fd2acb3b29c89aea03aab64754e0adfb364de4914b2||framework/vnag_framework.inc.php|0387bf3134f8cc2d1ae24e139019c0edef19c1ba5ca765624efea0b469c7897f||plugins/last/LastCheck.class.php|0f98e4a4995c79075a8053e091ff8b06c0538c2a1098a0117b94a484f97d4062||plugins/last/check_last.phps|2c7e3d44ec93c30a8609aa4cb83573108dbd96ace57fa96e9c704021bfd27cff||";} framework/vnag_framework.inc.phpBÙ» +eBÙÞß=¤ plugins/last/LastCheck.class.phpÆ» +eÆ:ª¥¤plugins/last/check_last.phpsº» +eº•5ˆ¤<?php
if (!VNag::is_http_mode()) error_reporting(E_ALL); declare(ticks=1); set_time_limit(0); define('VNAG_JSONDATA_V1', 'oid:1.3.6.1.4.1.37476.2.3.1.1'); $OVERWRITE_ARGUMENTS = null; function _empty($x) { return is_null($x) || (trim($x) == ''); } abstract class VNag { const VNAG_VERSION = '2023-10-13'; const STATUS_OK = 0; const STATUS_WARNING = 1; const STATUS_CRITICAL = 2; const STATUS_UNKNOWN = 3; const STATUS_ERROR = 4; const STATUS_UP = 0; const STATUS_DOWN = 1; const STATUS_MAINTAIN = 2; const VERBOSITY_SUMMARY = 0; const VERBOSITY_ADDITIONAL_INFORMATION = 1; const VERBOSITY_CONFIGURATION_DEBUG = 2; const VERBOSITY_PLUGIN_DEBUG = 3; const MAX_VERBOSITY = self::VERBOSITY_PLUGIN_DEBUG; const STATUSMODEL_SERVICE = 0; const STATUSMODEL_HOST = 1; private $initialized = false; private $status = null; private $messages = array(); private $verbose_info = ''; private $warningRanges = array(); private $criticalRanges = array(); private $performanceDataObjects = array(); private static $exitcode = 0; private $helpObj = null; private $argHandler = null; const OUTPUT_NEVER = 0; const OUTPUT_SPECIAL = 1; const OUTPUT_NORMAL = 2; const OUTPUT_EXCEPTION = 4; const OUTPUT_ALWAYS = 7; public $http_visual_output = self::OUTPUT_ALWAYS; public $http_invisible_output = self::OUTPUT_ALWAYS; protected $html_before = ''; protected $html_after = ''; protected $statusmodel = self::STATUSMODEL_SERVICE; protected $show_status_in_headline = true; protected $default_status = self::STATUS_UNKNOWN; protected $default_warning_range = null; protected $default_critical_range = null; protected $argWarning; protected $argCritical; protected $argVersion; protected $argVerbosity; protected $argTimeout; protected $argHelp; protected $argUsage; public $id = null; protected static $http_serial_number = 0; public $privkey = null; public $privkey_password = null; public $sign_algo = null; public $pubkey = null; protected $warningSingleValueRangeBehaviors = array(self::SINGLEVALUE_RANGE_DEFAULT); protected $criticalSingleValueRangeBehaviors = array(self::SINGLEVALUE_RANGE_DEFAULT); const SINGLEVALUE_RANGE_DEFAULT = 0; const SINGLEVALUE_RANGE_VAL_GT_X_BAD = 1; const SINGLEVALUE_RANGE_VAL_GE_X_BAD = 2; const SINGLEVALUE_RANGE_VAL_LT_X_BAD = 3; const SINGLEVALUE_RANGE_VAL_LE_X_BAD = 4; public $password_out = null; public $password_in = null; public static function is_http_mode() { return php_sapi_name() !== 'cli'; } public function getHelpManager() { return $this->helpObj; } public function getArgumentHandler() { return $this->argHandler; } public function outputHTML($text, $after_visual_output=true) { if ($this->is_http_mode()) { if ($this->initialized) { if ($after_visual_output) { $this->html_after .= $text; } else { $this->html_before .= $text; } } else { echo $text; } } } protected function resetArguments() { $this->argWarning = null; $this->argCritical = null; $this->argVersion = null; $this->argVerbosity = null; $this->argTimeout = null; $this->argHelp = null; $this->argWarning = null; $this->argCritical = null; } public function registerExpectedStandardArguments($args) { $this->resetArguments(); for ($i=0; $i<strlen($args); $i++) { switch ($args[$i]) { case 'w': $this->addExpectedArgument($this->argWarning = new VNagArgument('w', 'warning', VNagArgument::VALUE_REQUIRED, VNagLang::$argname_value, VNagLang::$warning_range)); break; case 'c': $this->addExpectedArgument($this->argCritical = new VNagArgument('c', 'critical', VNagArgument::VALUE_REQUIRED, VNagLang::$argname_value, VNagLang::$critical_range)); break; case 'V': $this->addExpectedArgument($this->argVersion = new VNagArgument('V', 'version', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$prints_version)); break; case 'v': $this->addExpectedArgument($this->argVerbosity = new VNagArgument('v', 'verbose', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$verbosity_helptext)); break; case 't': $this->addExpectedArgument($this->argTimeout = new VNagArgument('t', 'timeout', VNagArgument::VALUE_REQUIRED, VNagLang::$argname_seconds, VNagLang::$timeout_helptext)); break; case 'h': $this->addExpectedArgument($this->argHelp = new VNagArgument('h', 'help', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$help_helptext)); break; default: $letter = $args[$i]; throw new VNagInvalidStandardArgument(sprintf(VNagLang::$no_standard_arguments_with_letter, $letter)); } } } public function addExpectedArgument($argObj) { $helpObjAddEntryMethod = new ReflectionMethod($this->helpObj, '_addOption'); $helpObjAddEntryMethod->setAccessible(true); $helpObjAddEntryMethod->invoke($this->helpObj, $argObj); $argHandlerAddEntryMethod = new ReflectionMethod($this->argHandler, '_addExpectedArgument'); $argHandlerAddEntryMethod->setAccessible(true); $argHandlerAddEntryMethod->invoke($this->argHandler, $argObj); } protected function createArgumentHandler() { $this->argHandler = new VNagArgumentHandler(); } protected function createHelpObject() { $this->helpObj = new VNagHelp(); } protected function checkInitialized() { if (!$this->initialized) throw new VNagFunctionCallOutsideSession(); } protected function getVerbosityLevel() { $this->checkInitialized(); if (!isset($this->argVerbosity)) { return self::VERBOSITY_SUMMARY; } else { $level = $this->argVerbosity->count(); if ($level > self::MAX_VERBOSITY) $level = self::MAX_VERBOSITY; return $level; } } public function getWarningRange($argumentNumber=0) { $this->checkInitialized(); if (!isset($this->warningRanges[$argumentNumber])) { if (!is_null($this->argWarning)) { $warning = $this->argWarning->getValue(); if (!is_null($warning)) { $vals = explode(',',$warning); foreach ($vals as $number => $val) { if (_empty($val)) { $this->warningRanges[$number] = null; } else { $singleValueBehavior = isset($this->warningSingleValueRangeBehaviors[$number]) ? $this->warningSingleValueRangeBehaviors[$number] : VNag::SINGLEVALUE_RANGE_DEFAULT; $this->warningRanges[$number] = new VNagRange($val, $singleValueBehavior); } } } else { $this->warningRanges[0] = $this->default_warning_range; } } else { return null; } } if (isset($this->warningRanges[$argumentNumber])) { return $this->warningRanges[$argumentNumber]; } else { return null; } } public function getCriticalRange($argumentNumber=0) { $this->checkInitialized(); if (!isset($this->criticalRanges[$argumentNumber])) { if (!is_null($this->argCritical)) { $critical = $this->argCritical->getValue(); if (!is_null($critical)) { $vals = explode(',',$critical); foreach ($vals as $number => $val) { $singleValueBehavior = isset($this->criticalSingleValueRangeBehaviors[$number]) ? $this->criticalSingleValueRangeBehaviors[$number] : VNag::SINGLEVALUE_RANGE_DEFAULT; $this->criticalRanges[$number] = new VNagRange($val, $singleValueBehavior); } } else { $this->criticalRanges[0] = $this->default_critical_range; } } else { return null; } } if (isset($this->criticalRanges[$argumentNumber])) { return $this->criticalRanges[$argumentNumber]; } else { return null; } } public function checkAgainstWarningRange($values, $force=true, $autostatus=true, $argumentNumber=0) { $this->checkInitialized(); if (!$this->getArgumentHandler()->isArgRegistered('w')) { throw new VNagRequiredArgumentNotRegistered('-w'); } $wr = $this->getWarningRange($argumentNumber); if (isset($wr)) { if ($wr->checkAlert($values)) { if ($autostatus) $this->setStatus(VNag::STATUS_WARNING); return true; } else { if ($autostatus) $this->setStatus(VNag::STATUS_OK); return false; } } else { if ($force) { if (($argumentNumber > 0) && (count($this->warningRanges) > 0)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$too_few_warning_ranges, $argumentNumber+1)); } else { throw new VNagRequiredArgumentMissing('-w'); } } } } public function checkAgainstCriticalRange($values, $force=true, $autostatus=true, $argumentNumber=0) { $this->checkInitialized(); if (!$this->getArgumentHandler()->isArgRegistered('c')) { throw new VNagRequiredArgumentNotRegistered('-c'); } $cr = $this->getCriticalRange($argumentNumber); if (isset($cr)) { if ($cr->checkAlert($values)) { if ($autostatus) $this->setStatus(VNag::STATUS_CRITICAL); return true; } else { if ($autostatus) $this->setStatus(VNag::STATUS_OK); return false; } } else { if ($force) { if (($argumentNumber > 0) && (count($this->warningRanges) > 0)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$too_few_critical_ranges, $argumentNumber+1)); } else { throw new VNagRequiredArgumentMissing('-c'); } } } } protected static function getBaddestExitcode($code1, $code2) { return max($code1, $code2); } public static function _shutdownHandler() { if (!self::is_http_mode()) { exit((int)self::$exitcode); } } protected function _exit($code) { self::$exitcode = $this->getBaddestExitcode($code, self::$exitcode); } private $constructed = false; function __construct() { $this->createHelpObject(); $this->createArgumentHandler(); $this->addExpectedArgument($this->argUsage = new VNagArgument('?', '', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$prints_usage)); $this->constructed = true; } function __destruct() { if (Timeouter::started()) { Timeouter::end(); } } public function run() { global $inside_vnag_run; $inside_vnag_run = true; try { if (!$this->constructed) { throw new VNagNotConstructed(VNagLang::$notConstructed); } try { $this->initialized = true; $this->html_before = ''; $this->html_after = ''; $this->setStatus(null, true); $this->messages = array(); register_shutdown_function(array($this, '_shutdownHandler')); if ($this->argHandler->illegalUsage()) { $content = $this->helpObj->printUsagePage(); $this->setStatus(VNag::STATUS_UNKNOWN); if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_visual_output & VNag::OUTPUT_SPECIAL) echo $this->writeVisualHTML($content); if ($this->http_invisible_output & VNag::OUTPUT_SPECIAL) echo $this->writeInvisibleHTML($content); echo $this->html_after; return; } else { echo $content; return $this->_exit($this->status); } } if (!is_null($this->argVersion) && ($this->argVersion->available())) { $content = $this->helpObj->printVersionPage(); $this->setStatus(VNag::STATUS_UNKNOWN); if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_visual_output & VNag::OUTPUT_SPECIAL) echo $this->writeVisualHTML($content); if ($this->http_invisible_output & VNag::OUTPUT_SPECIAL) echo $this->writeInvisibleHTML($content); echo $this->html_after; return; } else { echo $content; return $this->_exit($this->status); } } if (!is_null($this->argHelp) && ($this->argHelp->available())) { $content = $this->helpObj->printHelpPage(); $this->setStatus(VNag::STATUS_UNKNOWN); if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_visual_output & VNag::OUTPUT_SPECIAL) echo $this->writeVisualHTML($content); if ($this->http_invisible_output & VNag::OUTPUT_SPECIAL) echo $this->writeInvisibleHTML($content); echo $this->html_after; return; } else { echo $content; return $this->_exit($this->status); } } $this->getWarningRange(); $this->getCriticalRange(); if (!is_null($this->argTimeout)) { $timeout = $this->argTimeout->getValue(); if (!is_null($timeout)) { Timeouter::start($timeout); } } ob_start(); $init_ob_level = ob_get_level(); try { $this->cbRun(); if (ob_get_level() < $init_ob_level) throw new VNagImplementationErrorException(VNagLang::$output_level_lowered); } finally { while (ob_get_level() > $init_ob_level) @ob_end_clean(); } if (is_null($this->status)) $this->setStatus($this->default_status,true); $outputType = VNag::OUTPUT_NORMAL; } catch (Exception $e) { $this->handleException($e); $outputType = VNag::OUTPUT_EXCEPTION; } if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_invisible_output & $outputType) { echo $this->writeInvisibleHTML(); } if ($this->http_visual_output & $outputType) { echo $this->writeVisualHTML(); } echo $this->html_after; } else { echo $this->getNagiosConsoleText(); return $this->_exit($this->status); } Timeouter::end(); } finally { $inside_vnag_run = false; } } private function getNagiosConsoleText() { $ary_perfdata = $this->getPerformanceData(); $performancedata_first = array_shift($ary_perfdata); $performancedata_rest = implode(' ', $ary_perfdata); $status_text = VNagLang::status($this->status, $this->statusmodel); if (_empty($this->getHeadline())) { $content = $status_text; } else { if ($this->show_status_in_headline) { $content = $status_text.': '.$this->getHeadline(); } else { $content = $this->getHeadline(); } } if (!_empty($performancedata_first)) $content .= '|'.trim($performancedata_first); $content .= "\n"; if (!_empty($this->verbose_info)) { $content .= trim($this->verbose_info); } if (!_empty($performancedata_rest)) $content .= '|'.trim($performancedata_rest); $content .= "\n"; return trim($content)."\n"; } abstract protected function cbRun(); public function addPerformanceData($prefDataObj, $move_to_font=false, $verbosityLevel=VNag::VERBOSITY_SUMMARY) { $this->checkInitialized(); if ((!isset($this->argVerbosity)) && ($verbosityLevel > VNag::VERBOSITY_SUMMARY)) throw new VNagRequiredArgumentNotRegistered('-v'); if (self::getVerbosityLevel() < $verbosityLevel) return false; if ($move_to_font) { array_unshift($this->performanceDataObjects, $prefDataObj); } else { $this->performanceDataObjects[] = $prefDataObj; } return true; } public function getPerformanceData() { $this->checkInitialized(); return $this->performanceDataObjects; } public function removePerformanceData($prefDataObj) { if (($key = array_search($prefDataObj, $this->performanceDataObjects, true)) !== false) { unset($this->performanceDataObjects[$key]); return true; } else { return false; } } public function clearPerformanceData() { $this->performanceDataObjects = array(); } public function getVerboseInfo() { return $this->verbose_info; } public function clearVerboseInfo() { $this->verbose_info = ''; } private function writeVisualHTML($special_content=null) { if (!_empty($special_content)) { $content = $special_content; } else { $content = strtoupper(VNagLang::$status.': '.VNagLang::status($this->status, $this->statusmodel))."\n\n"; $content .= strtoupper(VNagLang::$message).":\n"; $status_text = VNagLang::status($this->status, $this->statusmodel); if (_empty($this->getHeadline())) { $content .= $status_text; } else { if ($this->show_status_in_headline) { $content .= $status_text.': '.trim($this->getHeadline()); } else { $content .= trim($this->getHeadline()); } } $content .= "\n\n"; if (!_empty($this->verbose_info)) { $content .= strtoupper(VNagLang::$verbose_info).":\n".trim($this->verbose_info)."\n\n"; } $perfdata = $this->getPerformanceData(); if (count($perfdata) > 0) { $content .= strtoupper(VNagLang::$performance_data).":\n"; foreach ($perfdata as $pd) { $content .= trim($pd)."\n"; } $content .= "\n"; } } $colorinfo = ''; $status = $this->getStatus(); if ($status == VNag::STATUS_OK) $colorinfo = ' style="background-color:green;color:white;font-weight:bold"'; else if ($status == VNag::STATUS_WARNING) $colorinfo = ' style="background-color:yellow;color:black;font-weight:bold"'; else if ($status == VNag::STATUS_CRITICAL) $colorinfo = ' style="background-color:red;color:white;font-weight:bold"'; else if ($status == VNag::STATUS_ERROR) $colorinfo = ' style="background-color:purple;color:white;font-weight:bold"'; else $colorinfo = ' style="background-color:lightgray;color:black;font-weight:bold"'; $html_content = trim($content); $html_content = htmlentities($html_content); $html_content = str_replace(' ', '&nbsp;', $html_content); $html_content = nl2br($html_content); return '<table border="1" cellspacing="2" cellpadding="2" style="width:100%" class="vnag_table">'. '<tr'.$colorinfo.' class="vnag_title_row">'. '<td>'.VNagLang::$nagios_output.'</td>'. '</tr>'. '<tr class="vnag_message_row">'. '<td><code>'. $html_content. '</code></td>'. '</tr>'. '</table>'; } protected function readInvisibleHTML($html) { $this->checkInitialized(); $doc = new DOMDocument(); @$doc->loadHTML($html); $tags = $doc->getElementsByTagName('script'); foreach ($tags as $tag) { $type = $tag->getAttribute('type'); if ($type !== 'application/json') continue; $json = $tag->nodeValue; if (!$json) continue; $data = @json_decode($json,true); if (!is_array($data)) continue; if (!isset($data['type'])) continue; if ($data['type'] === VNAG_JSONDATA_V1) { if (!isset($data['datasets'])) throw new VNagWebInfoException(VNagLang::$dataset_missing); foreach ($data['datasets'] as $dataset) { $payload = base64_decode($dataset['payload']); if (!$payload) { throw new VNagWebInfoException(VNagLang::$payload_not_base64); } if (isset($dataset['encryption'])) { $cryptInfo = $dataset['encryption']; if (!is_array($cryptInfo)) { throw new VNagWebInfoException(VNagLang::$dataset_encryption_no_array); } $password = is_null($this->password_in) ? '' : $this->password_in; $salt = base64_decode($cryptInfo['salt']); if ($cryptInfo['hash'] != hash('sha256',$salt.$password)) { if ($password == '') { throw new VNagWebInfoException(VNagLang::$require_password); } else { throw new VNagWebInfoException(VNagLang::$wrong_password); } } if (!function_exists('openssl_decrypt')) { throw new VNagException(VNagLang::$openssl_missing); } $payload = openssl_decrypt($payload, $cryptInfo['method'], $password, 0, $cryptInfo['iv']); } if (!is_null($this->pubkey) && ($this->pubkey !== '')) { if (substr($this->pubkey,0,3) === '---') { $public_key = $this->pubkey; } else { if (!file_exists($this->pubkey)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$pubkey_file_not_found, $this->pubkey)); } $public_key = @file_get_contents($this->pubkey); if (!$public_key) { throw new VNagPublicKeyException(sprintf(VNagLang::$pubkey_file_not_readable, $this->pubkey)); } } if (!isset($dataset['signature'])) { throw new VNagSignatureException(VNagLang::$signature_missing); } $signature = base64_decode($dataset['signature']); if (!$signature) { throw new VNagSignatureException(VNagLang::$signature_not_bas64); } if (!function_exists('openssl_verify')) { throw new VNagException(VNagLang::$openssl_missing); } $sign_algo = is_null($this->sign_algo) ? OPENSSL_ALGO_SHA256 : $this->sign_algo; if (!openssl_verify($payload, $signature, $public_key, $sign_algo)) { throw new VNagSignatureException(VNagLang::$signature_invalid); } } $payload = @json_decode($payload,true); if (!$payload) { throw new VNagWebInfoException(VNagLang::$payload_not_json); } if ($payload['id'] == $this->id) { return $payload; } } } } return null; } private function getNextMonitorID($peek=false) { $result = is_null($this->id) ? self::$http_serial_number : $this->id; if (!$peek) { $this->id = null; self::$http_serial_number++; } return $result; } private function writeInvisibleHTML($special_content=null) { $payload['id'] = $this->getNextMonitorID(); $payload['status'] = $this->getStatus(); if (!_empty($special_content)) { $payload['text'] = $special_content; } else { $payload['headline'] = $this->getHeadline(); $payload['verbose_info'] = $this->verbose_info; $payload['performance_data'] = array(); foreach ($this->performanceDataObjects as $perfdata) { $payload['performance_data'][] = (string)$perfdata; } } $payload = json_encode($payload); $dataset = array(); if (!is_null($this->privkey) && ($this->privkey !== '')) { if (!function_exists('openssl_pkey_get_private') || !function_exists('openssl_sign')) { throw new VNagException(VNagLang::$openssl_missing); } if (substr($this->privkey,0,3) === '---') { $pkeyid = @openssl_pkey_get_private($this->privkey, $this->privkey_password); if (!$pkeyid) { throw new VNagPrivateKeyException(sprintf(VNagLang::$privkey_not_readable)); } } else { if (!file_exists($this->privkey)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$privkey_file_not_found, $this->privkey)); } $pkeyid = @openssl_pkey_get_private('file://'.$this->privkey, $this->privkey_password); if (!$pkeyid) { throw new VNagPrivateKeyException(sprintf(VNagLang::$privkey_file_not_readable, $this->privkey)); } } $signature = ''; $sign_algo = is_null($this->sign_algo) ? OPENSSL_ALGO_SHA256 : $this->sign_algo; if (@openssl_sign($payload, $signature, $pkeyid, $sign_algo)) { if (version_compare(PHP_VERSION, '8.0.0') < 0) { openssl_free_key($pkeyid); } $dataset['signature'] = base64_encode($signature); } else { throw new VNagPrivateKeyException(sprintf(VNagLang::$signature_failed)); } } if (!is_null($this->password_out) && ($this->password_out !== '')) { if (!function_exists('openssl_encrypt')) { throw new VNagException(VNagLang::$openssl_missing); } $password = $this->password_out; $method = 'aes-256-ofb'; $iv = substr(hash('sha256', openssl_random_pseudo_bytes(32)), 0, 16); $salt = openssl_random_pseudo_bytes(32); $cryptInfo = array(); $cryptInfo['method'] = $method; $cryptInfo['iv'] = $iv; $cryptInfo['salt'] = base64_encode($salt); $cryptInfo['hash'] = hash('sha256', $salt.$password); $payload = openssl_encrypt($payload, $method, $password, 0, $iv); $dataset['encryption'] = $cryptInfo; } $dataset['payload'] = base64_encode($payload); $json = array(); $json['type'] = VNAG_JSONDATA_V1; $json['datasets'] = array($dataset); return '<script type="application/json">'. json_encode($json). '</script>'; } protected function appendHeadline($msg) { $this->checkInitialized(); if (_empty($msg)) return false; $this->messages[] = $msg; return true; } protected function changeHeadline($msg) { $this->checkInitialized(); if (_empty($msg)) { $this->messages = array(); } else { $this->messages = array($msg); } return true; } public function setHeadline($msg, $append=false, $verbosityLevel=VNag::VERBOSITY_SUMMARY) { $this->checkInitialized(); if ((!isset($this->argVerbosity)) && ($verbosityLevel > VNag::VERBOSITY_SUMMARY)) throw new VNagRequiredArgumentNotRegistered('-v'); if (self::getVerbosityLevel() < $verbosityLevel) $msg = ''; if ($append) { return $this->appendHeadline($msg); } else { return $this->changeHeadline($msg); } } public function getHeadline() { $this->checkInitialized(); return implode(', ', $this->messages); } public function addVerboseMessage($msg, $verbosityLevel=VNag::VERBOSITY_SUMMARY) { $this->checkInitialized(); if (self::getVerbosityLevel() >= $verbosityLevel) { $this->verbose_info .= $msg."\n"; } } public function setStatus($status, $force=false) { $this->checkInitialized(); if (($force) || is_null($this->status) || ($status > $this->status)) { $this->status = $status; } } public function getStatus() { $this->checkInitialized(); return $this->status; } protected static function exceptionText($exception) { $class = get_class($exception); $msg = $exception->getMessage(); if (!_empty($msg)) { return sprintf(VNagLang::$exception_x, $msg, $class); } else { return sprintf(VNagLang::$unhandled_exception_without_msg, $class); } } protected function handleException($exception) { $this->checkInitialized(); if (!VNag::is_http_mode()) { while (ob_get_level() > 0) @ob_end_clean(); } $this->clearVerboseInfo(); $this->clearPerformanceData(); if ($exception instanceof VNagException) { $this->setStatus($exception->getStatus()); } else { $this->setStatus(self::STATUS_ERROR); } $this->setHeadline($this->exceptionText($exception), false); if ($exception instanceof VNagImplementationErrorException) { $this->addVerboseMessage($exception->getTraceAsString(), VNag::VERBOSITY_SUMMARY); } else { if (isset($this->argVerbosity)) { $this->addVerboseMessage($exception->getTraceAsString(), VNag::VERBOSITY_ADDITIONAL_INFORMATION); } else { } } } protected function get_cache_dir() { $homedir = @getenv('HOME'); if ($homedir && is_dir($homedir)) { $try = "$homedir/.vnag/cache"; if (is_dir($try)) return $try; if (@mkdir($try,0777,true)) return $try; } $user = posix_getpwuid(posix_geteuid()); if (isset($user['dir']) && is_dir($user['dir'])) { $homedir = $user['dir']; $try = "$homedir/.vnag/cache"; if (is_dir($try)) return $try; if (@mkdir($try,0777,true)) return $try; } if (isset($user['name']) && is_dir($user['name'])) { $username = $user['name']; $try = "/tmp/vnag/cache"; if (is_dir($try)) return $try; if (@mkdir($try,0777,true)) return $try; } throw new VNagException("Cannot get cache dir"); } protected function url_get_contents($url, $max_cache_time=1*60*60, $context=null) { $cache_file = $this->get_cache_dir().'/'.hash('sha256',$url); if (file_exists($cache_file) && (time()-filemtime($cache_file) < $max_cache_time)) { $cont = @file_get_contents($cache_file); if ($cont === false) throw new Exception("Failed to get contents from $cache_file"); } else { $options = array( 'http'=>array( 'method'=>"GET", 'header'=>"Accept-language: en\r\n" . "User-Agent: Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B334b Safari/531.21.102011-10-16 20:23:10\r\n" ) ); if (is_null($context)) $context = stream_context_create($options); $cont = @file_get_contents($url, false, $context); if ($cont === false) throw new Exception("Failed to get contents from $url"); file_put_contents($cache_file, $cont); } return $cont; } } class VNagException extends Exception { public function getStatus() { return VNag::STATUS_ERROR; } } class VNagTimeoutException extends VNagException {} class VNagWebInfoException extends VNagException {} class VNagSignatureException extends VNagException {} class VNagPublicKeyException extends VNagException {} class VNagPrivateKeyException extends VNagException {} class VNagInvalidArgumentException extends VNagException { public function getStatus() { return VNag::STATUS_UNKNOWN; } } class VNagValueUomPairSyntaxException extends VNagInvalidArgumentException { public function __construct($str) { $e_msg = sprintf(VNagLang::$valueUomPairSyntaxError, $str); parent::__construct($e_msg); } } class VNagInvalidTimeoutException extends VNagInvalidArgumentException {} class VNagInvalidRangeException extends VNagInvalidArgumentException { public function __construct($msg) { $e_msg = VNagLang::$range_is_invalid; if (!_empty($msg)) $e_msg .= ': '.trim($msg); parent::__construct($e_msg); } } class VNagInvalidShortOpt extends VNagImplementationErrorException {} class VNagInvalidLongOpt extends VNagImplementationErrorException {} class VNagInvalidValuePolicy extends VNagImplementationErrorException {} class VNagIllegalStatusModel extends VNagImplementationErrorException {} class VNagNotConstructed extends VNagImplementationErrorException {} class VNagImplementationErrorException extends VNagException {} class VNagInvalidStandardArgument extends VNagImplementationErrorException {} class VNagFunctionCallOutsideSession extends VNagImplementationErrorException {} class VNagIllegalArgumentValuesException extends VNagImplementationErrorException {} class VNagRequiredArgumentNotRegistered extends VNagImplementationErrorException { public function __construct($required_argument) { $e_msg = sprintf(VNagLang::$query_without_expected_argument, $required_argument); parent::__construct($e_msg); } } class VNagRequiredArgumentMissing extends VNagInvalidArgumentException { public function __construct($required_argument) { $e_msg = sprintf(VNagLang::$required_argument_missing, $required_argument); parent::__construct($e_msg); } } class VNagUnknownUomException extends VNagInvalidArgumentException { public function __construct($uom) { $e_msg = sprintf(VNagLang::$perfdata_uom_not_recognized, $uom); parent::__construct($e_msg); } } class VNagNoCompatibleRangeUomFoundException extends VNagException {} class VNagMixedUomsNotImplemented extends VNagInvalidArgumentException { public function __construct($uom1, $uom2) { if (_empty($uom1)) $uom1 = VNagLang::$none; if (_empty($uom2)) $uom2 = VNagLang::$none; $e_msg = sprintf(VNagLang::$perfdata_mixed_uom_not_implemented, $uom1, $uom2); parent::__construct($e_msg); } } class VNagUomConvertException extends VNagInvalidArgumentException { public function __construct($uom1, $uom2) { if (_empty($uom1)) $uom1 = VNagLang::$none; if (_empty($uom2)) $uom2 = VNagLang::$none; $e_msg = sprintf(VNagLang::$convert_x_y_error, $uom1, $uom2); parent::__construct($e_msg); } } class VNagInvalidPerformanceDataException extends VNagInvalidArgumentException { public function __construct($msg) { $e_msg = VNagLang::$performance_data_invalid; if (!_empty($msg)) $e_msg .= ': '.trim($msg); parent::__construct($e_msg); } } class Timeouter { private static $start_time = false; private static $timeout; private static $fired = false; private static $registered = false; private function __construct() { } public static function start($timeout) { if (!is_numeric($timeout) || ($timeout <= 0)) { throw new VNagInvalidTimeoutException(sprintf(VNagLang::$timeout_value_invalid, $timeout)); } self::$start_time = microtime(true); self::$timeout = (float) $timeout; self::$fired = false; if (!self::$registered) { self::$registered = true; register_tick_function(array('Timeouter', 'tick')); } } public static function started() { return self::$registered; } public static function end() { if (self::$registered) { unregister_tick_function(array('Timeouter', 'tick')); self::$registered = false; } } public static function tick() { if ((!self::$fired) && ((microtime(true) - self::$start_time) > self::$timeout)) { self::$fired = true; throw new VNagTimeoutException(VNagLang::$timeout_exception); } } } class VNagArgument { const VALUE_FORBIDDEN = 0; const VALUE_REQUIRED = 1; const VALUE_OPTIONAL = 2; protected $shortopt; protected $longopts; protected $valuePolicy; protected $valueName; protected $helpText; protected $defaultValue = null; protected static $all_short = ''; protected static $all_long = array(); public function getShortOpt() { return $this->shortopt; } public function getLongOpts() { return $this->longopts; } public function getValuePolicy() { return $this->valuePolicy; } public function getValueName() { return $this->valueName; } public function getHelpText() { return $this->helpText; } static private function validateShortOpt($shortopt) { $m = array(); return preg_match('@^[a-zA-Z0-9\\+\\-\\?]$@', $shortopt, $m); } static private function validateLongOpt($longopt) { $m = array(); return preg_match('@^[a-zA-Z0-9\\+\\-\\?]+$@', $longopt, $m); } public function __construct($shortopt, $longopts, $valuePolicy, $valueName, $helpText, $defaultValue=null) { switch ($valuePolicy) { case VNagArgument::VALUE_FORBIDDEN: if (!_empty($valueName)) { throw new VNagImplementationErrorException(sprintf(VNagLang::$value_name_forbidden)); } break; case VNagArgument::VALUE_REQUIRED: if (_empty($valueName)) { throw new VNagImplementationErrorException(sprintf(VNagLang::$value_name_required)); } break; case VNagArgument::VALUE_OPTIONAL: if (_empty($valueName)) { throw new VNagImplementationErrorException(sprintf(VNagLang::$value_name_required)); } break; default: throw new VNagInvalidValuePolicy(sprintf(VNagLang::$illegal_valuepolicy, $valuePolicy)); } if (!_empty($shortopt)) { if (!self::validateShortOpt($shortopt)) { throw new VNagInvalidShortOpt(sprintf(VNagLang::$illegal_shortopt, $shortopt)); } } if (is_array($longopts)) { foreach ($longopts as $longopt) { if (!self::validateLongOpt($longopt)) { throw new VNagInvalidLongOpt(sprintf(VNagLang::$illegal_longopt, $longopt)); } } } else if (!_empty($longopts)) { if (!self::validateLongOpt($longopts)) { throw new VNagInvalidLongOpt(sprintf(VNagLang::$illegal_longopt, $longopts)); } $longopts = array($longopts); } else { $longopts = array(); } switch ($valuePolicy) { case VNagArgument::VALUE_FORBIDDEN: $policyApdx = ''; break; case VNagArgument::VALUE_REQUIRED: $policyApdx = ':'; break; case VNagArgument::VALUE_OPTIONAL: $policyApdx = '::'; break; default: throw new VNagInvalidValuePolicy(sprintf(VNagLang::$illegal_valuepolicy, $valuePolicy)); } if ((!is_null($shortopt)) && ($shortopt != '?')) self::$all_short .= $shortopt.$policyApdx; if (is_array($longopts)) { foreach ($longopts as $longopt) { self::$all_long[] = $longopt.$policyApdx; } } $this->shortopt = $shortopt; $this->longopts = $longopts; $this->valuePolicy = $valuePolicy; $this->valueName = $valueName; $this->helpText = $helpText; $this->defaultValue = $defaultValue; } protected static function getOptions() { global $OVERWRITE_ARGUMENTS; if (!is_null($OVERWRITE_ARGUMENTS)) { return $OVERWRITE_ARGUMENTS; } else if (VNag::is_http_mode()) { return $_REQUEST; } else { return getopt(self::$all_short, self::$all_long); } } public function count() { $options = self::getOptions(); $count = 0; if (isset($options[$this->shortopt])) { if (is_array($options[$this->shortopt])) { $count += count($options[$this->shortopt]); } else { $count += 1; } } if (!is_null($this->longopts)) { foreach ($this->longopts as $longopt) { if (isset($options[$longopt])) { if (is_array($options[$longopt])) { $count += count($options[$longopt]); } else { $count += 1; } } } } return $count; } public function available() { $options = self::getOptions(); if (isset($options[$this->shortopt])) return true; if (!is_null($this->longopts)) { foreach ($this->longopts as $longopt) { if (isset($options[$longopt])) return true; } } return false; } public function require() { if (!$this->available() && is_null($this->defaultValue)) { $opt = $this->shortopt; $opt = !_empty($opt) ? '-'.$opt : (isset($this->longopts[0]) ? '--'.$this->longopts[0] : '?'); throw new VNagRequiredArgumentMissing($opt); } } public function getValue() { $options = self::getOptions(); if (isset($options[$this->shortopt])) { $x = $options[$this->shortopt]; if (is_array($x) && (count($x) <= 1)) $options[$this->shortopt] = $options[$this->shortopt][0]; return $options[$this->shortopt]; } if (!is_null($this->longopts)) { foreach ($this->longopts as $longopt) { if (isset($options[$longopt])) { $x = $options[$longopt]; if (is_array($x) && (count($x) <= 1)) $options[$longopt] = $options[$longopt][0]; return $options[$longopt]; } } } return $this->defaultValue; } } class VNagArgumentHandler { protected $expectedArgs = array(); protected function _addExpectedArgument($argObj) { if ($argObj->getShortOpt() == '?') return false; if ($argObj->getShortOpt() == '-') return false; if ($argObj->getShortOpt() == '+') return false; $this->expectedArgs[] = $argObj; return true; } public function getArgumentObj($shortopt) { foreach ($this->expectedArgs as $argObj) { if ($argObj->getShortOpt() == $shortopt) return $argObj; } return null; } public function isArgRegistered($shortopt) { return !is_null($this->getArgumentObj($shortopt)); } public function illegalUsage() { global $argv; return (isset($argv[1])) && (($argv[1] == '-?') || ($argv[1] == '/?')); } } class VNagRange { public $start; public $end; public $warnInsideRange; public function __construct($rangeDef, $singleValueBehavior=VNag::SINGLEVALUE_RANGE_DEFAULT) { $m = array(); if (!preg_match('|^(@){0,1}([^:]+)(:){0,1}(.*)$|', $rangeDef, $m)) { throw new VNagInvalidRangeException(sprintf(VNagLang::$range_invalid_syntax, $rangeDef)); } $this->warnInsideRange = $m[1] === '@'; $this->start = null; $this->end = null; if ($m[3] === ':') { if ($m[2] === '~') { $this->start = '-inf'; } else { $this->start = new VNagValueUomPair($m[2]); } if (_empty($m[4])) { $this->end = 'inf'; } else { $this->end = new VNagValueUomPair($m[4]); } } else { assert(_empty($m[4])); assert(!_empty($m[2])); $x = $m[2]; if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_DEFAULT) { $this->start = new VNagValueUomPair('0'.((new VNagValueUomPair($x))->getUom())); $this->end = new VNagValueUomPair($x); } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_GT_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 0; $this->start = '-inf'; $this->end = new VNagValueUomPair($x); } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_GE_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 1; $this->start = new VNagValueUomPair($x); $this->end = 'inf'; } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_LT_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 0; $this->start = new VNagValueUomPair($x); $this->end = 'inf'; } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_LE_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 1; $this->start = '-inf'; $this->end = new VNagValueUomPair($x); } else { throw new VNagException(VNagLang::$illegalSingleValueBehavior); } } if (is_null($this->start)) { throw new VNagInvalidRangeException(VNagLang::$invalid_start_value); } if (is_null($this->end)) { throw new VNagInvalidRangeException(VNagLang::$invalid_end_value); } if (($this->start instanceof VNagValueUomPair) && ($this->end instanceof VNagValueUomPair) && (VNagValueUomPair::compare($this->start,$this->end) > 0)) { throw new VNagInvalidRangeException(VNagLang::$start_is_greater_than_end); } } public function __toString() { $ret = ''; if ($this->warnInsideRange) { $ret = '@'; } if ($this->start === '-inf') { $ret .= '~'; } else { $ret .= $this->start; } $ret .= ':'; if ($this->end !== 'inf') { $ret .= $this->end; } return $ret; } public function checkAlert($values) { $compatibleCount = 0; if (!is_array($values)) $values = array($values); foreach ($values as $value) { if (!($value instanceof VNagValueUomPair)) $value = new VNagValueUomPair($value); assert(($this->start === '-inf') || ($this->start instanceof VNagValueUomPair)); assert(($this->end === 'inf' ) || ($this->end instanceof VNagValueUomPair)); if (($this->start !== '-inf') && (!$this->start->compatibleWith($value))) continue; if (($this->end !== 'inf') && (!$this->end->compatibleWith($value))) continue; $compatibleCount++; if ($this->warnInsideRange) { return (($this->start === '-inf') || (VNagValueUomPair::compare($value,$this->start) >= 0)) && (($this->end === 'inf') || (VNagValueUomPair::compare($value,$this->end) <= 0)); } else { return (($this->start !== '-inf') && (VNagValueUomPair::compare($value,$this->start) < 0)) || (($this->end !== 'inf') && (VNagValueUomPair::compare($value,$this->end) > 0)); } } if ((count($values) > 0) and ($compatibleCount == 0)) { throw new VNagNoCompatibleRangeUomFoundException(VNagLang::$no_compatible_range_uom_found); } return false; } } class VNagValueUomPair { protected $value; protected $uom; public $roundTo = -1; public function isRelative() { return $this->uom === '%'; } public function getValue() { return $this->value; } public function getUom() { return $this->uom; } public function __toString() { if ($this->roundTo == -1) { return $this->value.$this->uom; } else { return round($this->value,$this->roundTo).$this->uom; } } public function __construct($str) { $m = array(); if (!preg_match('/^([\d\.]+)(.*)$/ism', $str, $m)) { throw new VNagValueUomPairSyntaxException($str); } $this->value = $m[1]; $this->uom = isset($m[2]) ? $m[2] : ''; if (!self::isKnownUOM($this->uom)) { throw new VNagUnknownUomException($this->uom); } } public static function isKnownUOM(string $uom) { $no_unit = ($uom === ''); $seconds = ($uom === 's') || ($uom === 'ms') || ($uom === 'us'); $percentage = ($uom === '%'); $bytes = ($uom === 'B') || ($uom === 'KB') || ($uom === 'MB') || ($uom === 'GB') || ($uom === 'TB'); $counter = ($uom === 'c'); return ($no_unit || $seconds || $percentage || $bytes || $counter); } public function normalize($target=null) { $res = clone $this; if ($res->uom === 'ms') { $res->uom = 's'; $res->value /= 1000; } if ($res->uom === 'us') { $res->uom = 's'; $res->value /= 1000 * 1000; } if ($res->uom === 'B') { $res->uom = 'MB'; $res->value /= 1024 * 1024; } if ($res->uom === 'KB') { $res->uom = 'MB'; $res->value /= 1024; } if ($res->uom === 'GB') { $res->uom = 'MB'; $res->value *= 1024; } if ($res->uom === 'TB') { $res->uom = 'MB'; $res->value *= 1024 * 1024; } if ($res->uom === 'c') { $res->uom = ''; } if (!is_null($target)) { if ($res->uom == 'MB') { if ($target == 'B') { $res->uom = 'B'; $res->value *= 1024 * 1024; } else if ($target == 'KB') { $res->uom = 'KB'; $res->value *= 1024; } else if ($target == 'MB') { $res->uom = 'MB'; $res->value *= 1; } else if ($target == 'GB') { $res->uom = 'GB'; $res->value /= 1024; } else if ($target == 'TB') { $res->uom = 'TB'; $res->value /= 1024 * 1024; } else { throw new VNagUomConvertException($res->uom, $target); } } else if ($res->uom == 's') { if ($target == 's') { $res->uom = 's'; $res->value /= 1; } else if ($target == 'ms') { $res->uom = 'ms'; $res->value /= 1000; } else if ($target == 'us') { $res->uom = 'us'; $res->value /= 1000 * 1000; } else { throw new VNagUomConvertException($res->uom, $target); } } else { throw new VNagUomConvertException($res->uom, $target); } } return $res; } public function compatibleWith(VNagValueUomPair $other) { $a = $this->normalize(); $b = $other->normalize(); return ($a->uom == $b->uom); } public static function compare(VNagValueUomPair $left, VNagValueUomPair $right) { $a = $left->normalize(); $b = $right->normalize(); if ($a->uom != $b->uom) throw new VNagMixedUomsNotImplemented($a->uom, $b->uom); if ($a->value > $b->value) return 1; if ($a->value == $b->value) return 0; if ($a->value < $b->value) return -1; } } class VNagPerformanceData { protected $label; protected $value; protected $warn = null; protected $crit = null; protected $min = null; protected $max = null; public static function createByString($perfdata) { $perfdata = trim($perfdata); $ary = explode('=',$perfdata); if (count($ary) != 2) { throw new VNagInvalidPerformanceDataException(sprintf(VNagLang::$perfdata_line_invalid, $perfdata)); } $label = $ary[0]; $bry = explode(';',$ary[1]); if (substr($label,0,1) === "'") $label = substr($label, 1, strlen($label)-2); $value = $bry[0]; $warn = isset($bry[1]) ? $bry[1] : null; $crit = isset($bry[2]) ? $bry[2] : null; $min = isset($bry[3]) ? $bry[3] : null; $max = isset($bry[4]) ? $bry[4] : null; return new self($label, $value, $warn, $crit, $min, $max); } public function __construct($label, $value, $warn=null, $crit=null, $min=null, $max=null) { if (strpos($label, '=') !== false) throw new VNagInvalidPerformanceDataException(VNagLang::$perfdata_label_equal_sign_forbidden); $label = str_replace("'", "''", $label); $m = array(); if ((!_empty($min)) && (!preg_match('|^[-0-9\\.]+$|', $min, $m))) { throw new VNagInvalidPerformanceDataException(VNagLang::$perfdata_min_must_be_in_class); } if ((!_empty($max)) && (!preg_match('|^[-0-9\\.]+$|', $max, $m))) { throw new VNagInvalidPerformanceDataException(VNagLang::$perfdata_max_must_be_in_class); } $this->label = $label; $this->value = ($value == 'U') ? 'U' : new VNagValueUomPair($value); $this->warn = $warn; $this->crit = $crit; $this->min = $min; $this->max = $max; } public function __toString() { $label = $this->label; $value = $this->value; $warn = $this->warn; $crit = $this->crit; $min = $this->min; $max = $this->max; $label = str_replace("''", "'", $label); return "'$label'=$value". ';'.(is_null($warn) ? '' : $warn). ';'.(is_null($crit) ? '' : $crit). ';'.(is_null($min) ? '' : $min). ';'.(is_null($max) ? '' : $max); } } class VNagHelp { public $word_wrap_width = 80; public $argument_indent = 7; public function printUsagePage() { $usage = $this->getUsage(); if (_empty($usage)) { $usage = VNagLang::$no_syntax_defined; } return trim($usage)."\n"; } public function printVersionPage() { $out = trim($this->getNameAndVersion())."\n"; if ($this->word_wrap_width > 0) $out = wordwrap($out, $this->word_wrap_width, "\n", false); return $out; } static private function _conditionalLine($line, $terminator='', $prefix='') { if (!_empty($line)) { return trim($line).$terminator; } return ''; } public function printHelpPage() { $out = ''; $out .= self::_conditionalLine($this->getNameAndVersion(), "\n"); $out .= self::_conditionalLine($this->getCopyright(), "\n"); $out .= ($out != '') ? "\n" : ''; $out .= self::_conditionalLine($this->getShortDescription(), "\n\n\n"); $out .= self::_conditionalLine($this->getUsage(), "\n\n"); $out .= VNagLang::$options."\n"; foreach ($this->options as $argObj) { $out .= $this->printArgumentHelp($argObj); } $out .= self::_conditionalLine($this->getFootNotes(), "\n\n", "\n"); if ($this->word_wrap_width > 0) $out = wordwrap($out, $this->word_wrap_width, "\n", false); return $out; } protected $options = array(); protected function _addOption($argObj) { $this->options[] = $argObj; } protected function printArgumentHelp($argObj) { $identifiers = array(); $shortopt = $argObj->getShortopt(); if (!_empty($shortopt)) $identifiers[] = '-'.$shortopt; $longopts = $argObj->getLongopts(); if (!is_null($longopts)) { foreach ($longopts as $longopt) { if (!_empty($longopt)) $identifiers[] = '--'.$longopt; } } if (count($identifiers) == 0) return; $valueName = $argObj->getValueName(); $arginfo = ''; switch ($argObj->getValuePolicy()) { case VNagArgument::VALUE_FORBIDDEN: $arginfo = ''; break; case VNagArgument::VALUE_REQUIRED: $arginfo = '='.$valueName; break; case VNagArgument::VALUE_OPTIONAL: $arginfo = '[='.$valueName.']'; break; } $out = ''; $out .= implode(', ', $identifiers).$arginfo."\n"; $content = trim($argObj->getHelpText()); if ($this->word_wrap_width > 0) $content = wordwrap($content, $this->word_wrap_width-$this->argument_indent, "\n", false); $lines = explode("\n", $content); foreach ($lines as $line) { $out .= str_repeat(' ', $this->argument_indent).$line."\n"; } $out .= "\n"; return $out; } protected $pluginName; public function setPluginName($pluginName) { $this->pluginName = $this->replaceStuff($pluginName); } public function getPluginName() { if (_empty($this->pluginName)) { global $argv; return basename($argv[0]); } else { return $this->pluginName; } } protected $version; public function setVersion($version) { $this->version = $this->replaceStuff($version); } public function getVersion() { return $this->version; } public function getNameAndVersion() { $ret = $this->getPluginName(); if (_empty($ret)) return null; $ver = $this->getVersion(); if (!_empty($ver)) { $ret = sprintf(VNagLang::$x_version_x, $ret, $ver); } $ret = trim($ret); return $ret; } protected $copyright; public function setCopyright($copyright) { $this->copyright = $this->replaceStuff($copyright); } private function getVNagCopyright() { if (VNag::is_http_mode()) { $vts_email = 'www.viathinksoft.com'; } else { $vts_email = base64_decode('aW5mb0B2aWF0aGlua3NvZnQuZGU='); } return "VNag Framework ".VNag::VNAG_VERSION." (C) 2014-".date('Y')." ViaThinkSoft <$vts_email>"; } public function getCopyright() { if (_empty($this->copyright)) { return sprintf(VNagLang::$plugin_uses, $this->getVNagCopyright()); } else { return trim($this->copyright)."\n".sprintf(VNagLang::$uses, $this->getVNagCopyright()); } } protected $shortDescription; public function setShortDescription($shortDescription) { $this->shortDescription = $this->replaceStuff($shortDescription); } public function getShortDescription() { if (_empty($this->shortDescription)) { return null; } else { $content = $this->shortDescription; if ($this->word_wrap_width > 0) $content = wordwrap($content, $this->word_wrap_width, "\n", false); return $content; } } protected function replaceStuff($text) { global $argv; if (php_sapi_name() == 'cli') { $text = str_replace('$SCRIPTNAME$', $argv[0], $text); } else { $text = str_replace('$SCRIPTNAME$', basename($_SERVER['SCRIPT_NAME']), $text); } $text = str_replace('$CURYEAR$', date('Y'), $text); return $text; } protected $syntax; public function setSyntax($syntax) { $syntax = $this->replaceStuff($syntax); $this->syntax = $syntax; } public function getUsage() { if (_empty($this->syntax)) { return null; } else { return sprintf(VNagLang::$usage_x, $this->syntax); } } protected $footNotes; public function setFootNotes($footNotes) { $this->footNotes = $this->replaceStuff($footNotes); } public function getFootNotes() { return $this->footNotes; } } class VNagLang { public static function status($code, $statusmodel) { switch ($statusmodel) { case VNag::STATUSMODEL_SERVICE: switch ($code) { case VNag::STATUS_OK: return 'OK'; case VNag::STATUS_WARNING: return 'Warning'; case VNag::STATUS_CRITICAL: return 'Critical'; case VNag::STATUS_UNKNOWN: return 'Unknown'; default: return sprintf('Error (%d)', $code); } case VNag::STATUSMODEL_HOST: switch ($code) { case VNag::STATUS_UP: return 'Up'; case VNag::STATUS_DOWN: return 'Down'; default: return sprintf('Maintain last state (%d)', $code); } default: throw new VNagIllegalStatusModel(sprintf(self::$illegal_statusmodel, $statusmodel)); } } static $nagios_output = 'VNag-Output'; static $verbose_info = 'Verbose information'; static $status = 'Status'; static $message = 'Message'; static $performance_data = 'Performance data'; static $status_ok = 'OK'; static $status_warn = 'Warning'; static $status_critical = 'Critical'; static $status_unknown = 'Unknown'; static $status_error = 'Error'; static $unhandled_exception_without_msg = "Unhandled exception of type %s"; static $plugin_uses = 'This plugin uses %s'; static $uses = 'uses %s'; static $x_version_x = '%s, version %s'; static $argname_value = 'value'; static $argname_seconds = 'seconds'; static $query_without_expected_argument = "The argument '%s' is queried, but was not added to the list of expected arguments. Please contact the plugin author."; static $required_argument_missing = "The argument '%s' is required."; static $performance_data_invalid = 'Performance data invalid.'; static $no_standard_arguments_with_letter = "No standard argument with letter '%s' exists."; static $invalid_start_value = 'Invalid start value.'; static $invalid_end_value = 'Invalid end value.'; static $start_is_greater_than_end = 'Start is greater than end value.'; static $value_name_forbidden = "Implementation error: You may not define a value name for the argument, because the value policy is VALUE_FORBIDDEN."; static $value_name_required = "Implementation error: Please define a name for the argument (so it can be shown in the help page)."; static $illegal_shortopt = "Illegal shortopt '-%s'."; static $illegal_longopt = "Illegal longopt '--%s'."; static $illegal_valuepolicy = "valuePolicy has illegal value '%s'."; static $range_invalid_syntax = "Syntax error in range '%s'."; static $timeout_value_invalid = "Timeout value '%s' is invalid."; static $range_is_invalid = 'Range is invalid.'; static $timeout_exception = 'Timeout!'; static $perfdata_label_equal_sign_forbidden = 'Label may not contain an equal sign.'; static $perfdata_value_must_be_in_class = 'Value must be in class [-0-9.] or be \'U\' if the actual value can\'t be determined.'; static $perfdata_min_must_be_in_class = 'Min must be in class [-0-9.] or empty.'; static $perfdata_max_must_be_in_class = 'Max must be in class [-0-9.] or empty.'; static $perfdata_uom_not_recognized = 'UOM (unit of measurement) "%s" is not recognized.'; static $perfdata_mixed_uom_not_implemented = 'Mixed UOMs (%s and %s) are currently not supported.'; static $no_compatible_range_uom_found = 'Measured values are not compatible with the provided warning/critical parameter. Most likely, the UOM is incompatible.'; static $exception_x = '%s (%s)'; static $no_syntax_defined = 'The author of this plugin has not defined a syntax for this plugin.'; static $usage_x = "Usage:\n%s"; static $options = "Options:"; static $illegal_statusmodel = "Invalid statusmodel %d."; static $none = '[none]'; static $valueUomPairSyntaxError = 'Syntax error at "%s". Syntax must be Value[UOM].'; static $too_few_warning_ranges = "You have too few warning ranges (currently trying to get element %d)."; static $too_few_critical_ranges = "You have too few critical ranges (currently trying to get element %d)."; static $dataset_missing = 'Dataset missing.'; static $payload_not_base64 = 'The payload is not valid Base64.'; static $payload_not_json = 'The payload is not valid JSON.'; static $signature_missing = 'The signature is missing.'; static $signature_not_bas64 = 'The signature is not valid Base64.'; static $signature_invalid = 'The signature is invalid. The connection might have been tampered, or a different key is used.'; static $pubkey_file_not_found = "Public key file %s was not found."; static $pubkey_file_not_readable = "Public key file %s is not readable."; static $privkey_file_not_found = "Private key file %s was not found."; static $privkey_not_readable = "Private key is not readable."; static $privkey_file_not_readable = "Private key file %s is not readable."; static $signature_failed = "Signature failed."; static $perfdata_line_invalid = "Performance data line %s is invalid."; static $singlevalue_unexpected_at_symbol = 'This plugin does not allow the @-symbol at ranges for single values.'; static $illegalSingleValueBehavior = "Illegal value for 'singleValueBehavior'. Please contact the creator of the plugin."; static $dataset_encryption_no_array = 'Dataset encryption information invalid.'; static $require_password = 'This resource is protected with a password. Please provide a password.'; static $wrong_password = 'This resource is protected with a password. You have provided the wrong password, or it was changed.'; static $convert_x_y_error = 'Cannot convert from UOM %s to UOM %s.'; static $php_error = 'PHP has detected an error in the plugin. Please contact the plugin author.'; static $output_level_lowered = "Output Buffer level lowered during cbRun(). Please contact the plugin author."; static $openssl_missing = "OpenSSL is missing. Therefore, encryption and signatures are not available."; static $warning_range = 'Warning range'; static $critical_range = 'Critical range'; static $prints_version = 'Prints version'; static $verbosity_helptext = 'Verbosity -v, -vv or -vvv'; static $timeout_helptext = 'Sets timeout in seconds'; static $help_helptext = 'Prints help page'; static $prints_usage = 'Prints usage'; static $notConstructed = 'Parent constructor not called with parent::__construct().'; } function vnagErrorHandler($errorkind, $errortext, $file, $line) { global $inside_vnag_run; if (!$inside_vnag_run && VNag::is_http_mode()) { return false; } if (!(error_reporting() & $errorkind)) { return true; } if (defined('E_ERROR') && ($errorkind == E_ERROR)) $errorkind = 'Error'; if (defined('E_WARNING') && ($errorkind == E_WARNING)) $errorkind = 'Warning'; if (defined('E_PARSE') && ($errorkind == E_PARSE)) $errorkind = 'Parse'; if (defined('E_NOTICE') && ($errorkind == E_NOTICE)) $errorkind = 'Notice'; if (defined('E_CORE_ERROR') && ($errorkind == E_CORE_ERROR)) $errorkind = 'Core Error'; if (defined('E_CORE_WARNING') && ($errorkind == E_CORE_WARNING)) $errorkind = 'Core Warning'; if (defined('E_COMPILE_ERROR') && ($errorkind == E_COMPILE_ERROR)) $errorkind = 'Compile Error'; if (defined('E_COMPILE_WARNING') && ($errorkind == E_COMPILE_WARNING)) $errorkind = 'Compile Warning'; if (defined('E_USER_ERROR') && ($errorkind == E_USER_ERROR)) $errorkind = 'User Error'; if (defined('E_USER_WARNING') && ($errorkind == E_USER_WARNING)) $errorkind = 'User Warning'; if (defined('E_USER_NOTICE') && ($errorkind == E_USER_NOTICE)) $errorkind = 'User Notice'; if (defined('E_STRICT') && ($errorkind == E_STRICT)) $errorkind = 'Strict'; if (defined('E_RECOVERABLE_ERROR') && ($errorkind == E_RECOVERABLE_ERROR)) $errorkind = 'Recoverable Error'; if (defined('E_DEPRECATED') && ($errorkind == E_DEPRECATED)) $errorkind = 'Deprecated'; if (defined('E_USER_DEPRECATED') && ($errorkind == E_USER_DEPRECATED)) $errorkind = 'User Deprecated'; throw new VNagException(VNagLang::$php_error . " $errortext at $file:$line (kind $errorkind)"); } $inside_vnag_run = false; $old_error_handler = set_error_handler("vnagErrorHandler"); <?php
declare(ticks=1); class LastCheck extends VNag { private $argUser = null; private $argRegex = null; private $argWtmpFiles = null; private $argEmptyOk = null; private $argIpInfoToken = null; private $cache = null; private $cacheFile = null; private $cacheDirty = false; public function __construct() { parent::__construct(); if ($this->is_http_mode()) { $this->registerExpectedStandardArguments(''); } else { $this->registerExpectedStandardArguments('Vhtv'); } $this->addExpectedArgument($this->argUser = new VNagArgument('u', 'user', VNagArgument::VALUE_REQUIRED, 'user', 'The Linux username. If the argument is missing, all users will be checked.', null)); $this->addExpectedArgument($this->argRegex = new VNagArgument('R', 'regex', VNagArgument::VALUE_REQUIRED, 'regex', 'The regular expression (in PHP: preg_match) which is applied on IP, Hostname, Country, AS number or ISP name. If the regular expression matches, the login will be accepted, otherweise an alert will be triggered. Example: /DE/ismU or /Telekom/ismU', null)); $this->addExpectedArgument($this->argWtmpFiles = new VNagArgument('f', 'wtmpfile', VNagArgument::VALUE_REQUIRED, 'wtmpfile', 'Filemask of the wtmp file (important if you use logrotate), e.g. \'/var/log/wtmp*\'', '/var/log/wtmp*')); $this->addExpectedArgument($this->argEmptyOk = new VNagArgument('e', 'emptyok', VNagArgument::VALUE_FORBIDDEN, null, 'Treat an empty result (e.g. empty wtmp file after rotation) as success; otherwise treat it as status "Unknown"', null)); $this->addExpectedArgument($this->argIpInfoToken = new VNagArgument(null, 'ipInfoToken', VNagArgument::VALUE_REQUIRED, 'token', 'If you have a token for ipinfo.io, please enter it here. Without token, you can query the service approx 1,000 times per day (which should be enough)', null)); $this->getHelpManager()->setPluginName('vnag_last'); $this->getHelpManager()->setVersion('2023-10-13'); $this->getHelpManager()->setShortDescription('This plugin checks the logs of the tool "LAST" an warns when users have logged in with an unexpected IP/Country/ISP.'); $this->getHelpManager()->setCopyright('Copyright (C) 2011-$CURYEAR$ Daniel Marschall, ViaThinkSoft.'); $this->getHelpManager()->setSyntax('$SCRIPTNAME$ [-v] [-e] [-u username] [-R regex] [--ipInfoToken token]'); $this->getHelpManager()->setFootNotes('If you encounter bugs, please contact ViaThinkSoft at www.viathinksoft.com'); $this->cacheFile = $this->get_cache_dir().'/'.hash('sha256','LastCheck:last_ip_cache'); if (!file_exists($this->cacheFile)) @touch($this->cacheFile); $this->cache = $this->cacheFile ? json_decode(file_get_contents($this->cacheFile),true) : array(); } public function __destruct() { if ($this->cacheFile && $this->cacheDirty) { @file_put_contents($this->cacheFile, json_encode($this->cache)); } } private function getCountryAndOrg($ip) { if (isset($this->cache[$ip])) return $this->cache[$ip]; $url = 'https://ipinfo.io/'.urlencode($ip).'/json'; $token = $this->argIpInfoToken->getValue(); if ($token) $url .= '?token='.urlencode($token); $cont = $this->url_get_contents($url); if ($cont === false) return array(); if (($data = @json_decode($cont, true)) === false) return array(); if (isset($data['error'])) return array(); if (isset($data['bogon']) && ($data['bogon'])) { $res = array(); } else { $res = array(); if (isset($data['hostname'])) $res[] = $data['hostname']; if (isset($data['country'])) $res[] = $data['country']; list($as, $orgName) = explode(' ', $data['org'], 2); $res[] = $as; $res[] = $orgName; } $this->cache[$ip] = $res; $this->cacheDirty = true; return $res; } private function getLastLoginIPs($username) { $cont = ''; $files = glob($this->argWtmpFiles->getValue()); foreach ($files as $file) { if (trim($username) == '') { $cont .= shell_exec('last -f '.escapeshellarg($file).' -F -w '); } else { $cont .= shell_exec('last -f '.escapeshellarg($file).' -F -w '.escapeshellarg($username)); } } preg_match_all('@^(\S+)\s+(\S+)\s+(\S+)\s+(.+)$@ismU', $cont, $m, PREG_SET_ORDER); foreach ($m as $key => &$a) { if (($a[2] === 'system') && ($a[3] === 'boot')) { unset($m[$key]); } else if (substr($a[1],0,4) === 'wtmp') { unset($m[$key]); } else { array_shift($a); } } return $m; } protected function cbRun() { if (!`which which`) { throw new VNagException("Program 'which' is not installed on your system"); } if (!`which last`) { throw new VNagException("Program 'last' (usually included in package smartmontools) is not installed on your system"); } $username = $this->argUser->available() ? $this->argUser->getValue() : ''; $regex = $this->argRegex->available() ? $this->argRegex->getValue() : null; if (($username != '') && function_exists('posix_getpwnam') && !posix_getpwnam($username)) { $this->setStatus(VNag::STATUS_WARNING); $this->addVerboseMessage("WARNING: Currently, there is no Linux user with name '$username'.", VNag::VERBOSITY_SUMMARY); } $count_total = 0; $count_ok = 0; $count_warning = 0; foreach ($this->getLastLoginIPs($username) as list($username, $pts, $ip, $times)) { if (strpos($ip,':pts/') === 0) continue; $count_total++; $fields = $this->getCountryAndOrg($ip); $fields[] = $ip; if (is_null($regex)) { $this->addVerboseMessage("INFO: ".implode(' ',$fields)." @ $username, $pts $times", VNag::VERBOSITY_ADDITIONAL_INFORMATION); } else { $match = false; foreach ($fields as $f) { if (preg_match($regex, $f, $dummy)) { $match = true; break; } } if ($match) { $count_ok++; $this->addVerboseMessage("OK: ".implode(' ',$fields)." @ $username $pts $times", VNag::VERBOSITY_ADDITIONAL_INFORMATION); $this->setStatus(VNag::STATUS_OK); } else { $count_warning++; $this->addVerboseMessage("WARNING: ".implode(' ',$fields)." @ $username $pts $times", VNag::VERBOSITY_SUMMARY); $this->setStatus(VNag::STATUS_WARNING); } } } if (is_null($regex)) { $this->setHeadline("Checked $count_total logins (No checks done because argument 'Regex' is missing)"); } else { if (($count_total == 0) && ($this->argEmptyOk->count() > 0)) { $this->setStatus(VNag::STATUS_OK); } $this->setHeadline("Checked $count_total logins ($count_ok OK, $count_warning Warning)"); } } } <?php
declare(ticks=1); require_once __DIR__ . '/../../framework/vnag_framework.inc.php'; require_once __DIR__.'/LastCheck.class.php'; $job = new LastCheck(); $job->run(); unset($job); Æȃÿ®« Xû®ÅÀuXCZÔÝûãíxVcíó”Kn~Q¡Wƒ/xGbA½ýŸù(äúgObŒš,ixBšGBMB
declare(ticks=1); require_once __DIR__ . '/../../framework/vnag_framework.inc.php'; require_once __DIR__.'/LastCheck.class.php'; $job = new LastCheck(); $job->run(); unset($job); w77µ#PPv±N›áÖ.L¶íý‘5 Ô°/<ÍçcL“™!àûù6ۂ±—ënâK"+ xb|ñG$3V GBMB
/trunk/bin/mdstat.phar
-Dš¤ plugins/mdstat/check_mdstat.phps¾yï*e¾†ߤ<?php ?>
-<?php
+Dš¤ plugins/mdstat/check_mdstat.phps¾» +e¾†ߤ<?php
if (!VNag::is_http_mode()) error_reporting(E_ALL); declare(ticks=1); set_time_limit(0); define('VNAG_JSONDATA_V1', 'oid:1.3.6.1.4.1.37476.2.3.1.1'); $OVERWRITE_ARGUMENTS = null; function _empty($x) { return is_null($x) || (trim($x) == ''); } abstract class VNag { const VNAG_VERSION = '2023-10-13'; const STATUS_OK = 0; const STATUS_WARNING = 1; const STATUS_CRITICAL = 2; const STATUS_UNKNOWN = 3; const STATUS_ERROR = 4; const STATUS_UP = 0; const STATUS_DOWN = 1; const STATUS_MAINTAIN = 2; const VERBOSITY_SUMMARY = 0; const VERBOSITY_ADDITIONAL_INFORMATION = 1; const VERBOSITY_CONFIGURATION_DEBUG = 2; const VERBOSITY_PLUGIN_DEBUG = 3; const MAX_VERBOSITY = self::VERBOSITY_PLUGIN_DEBUG; const STATUSMODEL_SERVICE = 0; const STATUSMODEL_HOST = 1; private $initialized = false; private $status = null; private $messages = array(); private $verbose_info = ''; private $warningRanges = array(); private $criticalRanges = array(); private $performanceDataObjects = array(); private static $exitcode = 0; private $helpObj = null; private $argHandler = null; const OUTPUT_NEVER = 0; const OUTPUT_SPECIAL = 1; const OUTPUT_NORMAL = 2; const OUTPUT_EXCEPTION = 4; const OUTPUT_ALWAYS = 7; public $http_visual_output = self::OUTPUT_ALWAYS; public $http_invisible_output = self::OUTPUT_ALWAYS; protected $html_before = ''; protected $html_after = ''; protected $statusmodel = self::STATUSMODEL_SERVICE; protected $show_status_in_headline = true; protected $default_status = self::STATUS_UNKNOWN; protected $default_warning_range = null; protected $default_critical_range = null; protected $argWarning; protected $argCritical; protected $argVersion; protected $argVerbosity; protected $argTimeout; protected $argHelp; protected $argUsage; public $id = null; protected static $http_serial_number = 0; public $privkey = null; public $privkey_password = null; public $sign_algo = null; public $pubkey = null; protected $warningSingleValueRangeBehaviors = array(self::SINGLEVALUE_RANGE_DEFAULT); protected $criticalSingleValueRangeBehaviors = array(self::SINGLEVALUE_RANGE_DEFAULT); const SINGLEVALUE_RANGE_DEFAULT = 0; const SINGLEVALUE_RANGE_VAL_GT_X_BAD = 1; const SINGLEVALUE_RANGE_VAL_GE_X_BAD = 2; const SINGLEVALUE_RANGE_VAL_LT_X_BAD = 3; const SINGLEVALUE_RANGE_VAL_LE_X_BAD = 4; public $password_out = null; public $password_in = null; public static function is_http_mode() { return php_sapi_name() !== 'cli'; } public function getHelpManager() { return $this->helpObj; } public function getArgumentHandler() { return $this->argHandler; } public function outputHTML($text, $after_visual_output=true) { if ($this->is_http_mode()) { if ($this->initialized) { if ($after_visual_output) { $this->html_after .= $text; } else { $this->html_before .= $text; } } else { echo $text; } } } protected function resetArguments() { $this->argWarning = null; $this->argCritical = null; $this->argVersion = null; $this->argVerbosity = null; $this->argTimeout = null; $this->argHelp = null; $this->argWarning = null; $this->argCritical = null; } public function registerExpectedStandardArguments($args) { $this->resetArguments(); for ($i=0; $i<strlen($args); $i++) { switch ($args[$i]) { case 'w': $this->addExpectedArgument($this->argWarning = new VNagArgument('w', 'warning', VNagArgument::VALUE_REQUIRED, VNagLang::$argname_value, VNagLang::$warning_range)); break; case 'c': $this->addExpectedArgument($this->argCritical = new VNagArgument('c', 'critical', VNagArgument::VALUE_REQUIRED, VNagLang::$argname_value, VNagLang::$critical_range)); break; case 'V': $this->addExpectedArgument($this->argVersion = new VNagArgument('V', 'version', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$prints_version)); break; case 'v': $this->addExpectedArgument($this->argVerbosity = new VNagArgument('v', 'verbose', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$verbosity_helptext)); break; case 't': $this->addExpectedArgument($this->argTimeout = new VNagArgument('t', 'timeout', VNagArgument::VALUE_REQUIRED, VNagLang::$argname_seconds, VNagLang::$timeout_helptext)); break; case 'h': $this->addExpectedArgument($this->argHelp = new VNagArgument('h', 'help', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$help_helptext)); break; default: $letter = $args[$i]; throw new VNagInvalidStandardArgument(sprintf(VNagLang::$no_standard_arguments_with_letter, $letter)); } } } public function addExpectedArgument($argObj) { $helpObjAddEntryMethod = new ReflectionMethod($this->helpObj, '_addOption'); $helpObjAddEntryMethod->setAccessible(true); $helpObjAddEntryMethod->invoke($this->helpObj, $argObj); $argHandlerAddEntryMethod = new ReflectionMethod($this->argHandler, '_addExpectedArgument'); $argHandlerAddEntryMethod->setAccessible(true); $argHandlerAddEntryMethod->invoke($this->argHandler, $argObj); } protected function createArgumentHandler() { $this->argHandler = new VNagArgumentHandler(); } protected function createHelpObject() { $this->helpObj = new VNagHelp(); } protected function checkInitialized() { if (!$this->initialized) throw new VNagFunctionCallOutsideSession(); } protected function getVerbosityLevel() { $this->checkInitialized(); if (!isset($this->argVerbosity)) { return self::VERBOSITY_SUMMARY; } else { $level = $this->argVerbosity->count(); if ($level > self::MAX_VERBOSITY) $level = self::MAX_VERBOSITY; return $level; } } public function getWarningRange($argumentNumber=0) { $this->checkInitialized(); if (!isset($this->warningRanges[$argumentNumber])) { if (!is_null($this->argWarning)) { $warning = $this->argWarning->getValue(); if (!is_null($warning)) { $vals = explode(',',$warning); foreach ($vals as $number => $val) { if (_empty($val)) { $this->warningRanges[$number] = null; } else { $singleValueBehavior = isset($this->warningSingleValueRangeBehaviors[$number]) ? $this->warningSingleValueRangeBehaviors[$number] : VNag::SINGLEVALUE_RANGE_DEFAULT; $this->warningRanges[$number] = new VNagRange($val, $singleValueBehavior); } } } else { $this->warningRanges[0] = $this->default_warning_range; } } else { return null; } } if (isset($this->warningRanges[$argumentNumber])) { return $this->warningRanges[$argumentNumber]; } else { return null; } } public function getCriticalRange($argumentNumber=0) { $this->checkInitialized(); if (!isset($this->criticalRanges[$argumentNumber])) { if (!is_null($this->argCritical)) { $critical = $this->argCritical->getValue(); if (!is_null($critical)) { $vals = explode(',',$critical); foreach ($vals as $number => $val) { $singleValueBehavior = isset($this->criticalSingleValueRangeBehaviors[$number]) ? $this->criticalSingleValueRangeBehaviors[$number] : VNag::SINGLEVALUE_RANGE_DEFAULT; $this->criticalRanges[$number] = new VNagRange($val, $singleValueBehavior); } } else { $this->criticalRanges[0] = $this->default_critical_range; } } else { return null; } } if (isset($this->criticalRanges[$argumentNumber])) { return $this->criticalRanges[$argumentNumber]; } else { return null; } } public function checkAgainstWarningRange($values, $force=true, $autostatus=true, $argumentNumber=0) { $this->checkInitialized(); if (!$this->getArgumentHandler()->isArgRegistered('w')) { throw new VNagRequiredArgumentNotRegistered('-w'); } $wr = $this->getWarningRange($argumentNumber); if (isset($wr)) { if ($wr->checkAlert($values)) { if ($autostatus) $this->setStatus(VNag::STATUS_WARNING); return true; } else { if ($autostatus) $this->setStatus(VNag::STATUS_OK); return false; } } else { if ($force) { if (($argumentNumber > 0) && (count($this->warningRanges) > 0)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$too_few_warning_ranges, $argumentNumber+1)); } else { throw new VNagRequiredArgumentMissing('-w'); } } } } public function checkAgainstCriticalRange($values, $force=true, $autostatus=true, $argumentNumber=0) { $this->checkInitialized(); if (!$this->getArgumentHandler()->isArgRegistered('c')) { throw new VNagRequiredArgumentNotRegistered('-c'); } $cr = $this->getCriticalRange($argumentNumber); if (isset($cr)) { if ($cr->checkAlert($values)) { if ($autostatus) $this->setStatus(VNag::STATUS_CRITICAL); return true; } else { if ($autostatus) $this->setStatus(VNag::STATUS_OK); return false; } } else { if ($force) { if (($argumentNumber > 0) && (count($this->warningRanges) > 0)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$too_few_critical_ranges, $argumentNumber+1)); } else { throw new VNagRequiredArgumentMissing('-c'); } } } } protected static function getBaddestExitcode($code1, $code2) { return max($code1, $code2); } public static function _shutdownHandler() { if (!self::is_http_mode()) { exit((int)self::$exitcode); } } protected function _exit($code) { self::$exitcode = $this->getBaddestExitcode($code, self::$exitcode); } private $constructed = false; function __construct() { $this->createHelpObject(); $this->createArgumentHandler(); $this->addExpectedArgument($this->argUsage = new VNagArgument('?', '', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$prints_usage)); $this->constructed = true; } function __destruct() { if (Timeouter::started()) { Timeouter::end(); } } public function run() { global $inside_vnag_run; $inside_vnag_run = true; try { if (!$this->constructed) { throw new VNagNotConstructed(VNagLang::$notConstructed); } try { $this->initialized = true; $this->html_before = ''; $this->html_after = ''; $this->setStatus(null, true); $this->messages = array(); register_shutdown_function(array($this, '_shutdownHandler')); if ($this->argHandler->illegalUsage()) { $content = $this->helpObj->printUsagePage(); $this->setStatus(VNag::STATUS_UNKNOWN); if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_visual_output & VNag::OUTPUT_SPECIAL) echo $this->writeVisualHTML($content); if ($this->http_invisible_output & VNag::OUTPUT_SPECIAL) echo $this->writeInvisibleHTML($content); echo $this->html_after; return; } else { echo $content; return $this->_exit($this->status); } } if (!is_null($this->argVersion) && ($this->argVersion->available())) { $content = $this->helpObj->printVersionPage(); $this->setStatus(VNag::STATUS_UNKNOWN); if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_visual_output & VNag::OUTPUT_SPECIAL) echo $this->writeVisualHTML($content); if ($this->http_invisible_output & VNag::OUTPUT_SPECIAL) echo $this->writeInvisibleHTML($content); echo $this->html_after; return; } else { echo $content; return $this->_exit($this->status); } } if (!is_null($this->argHelp) && ($this->argHelp->available())) { $content = $this->helpObj->printHelpPage(); $this->setStatus(VNag::STATUS_UNKNOWN); if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_visual_output & VNag::OUTPUT_SPECIAL) echo $this->writeVisualHTML($content); if ($this->http_invisible_output & VNag::OUTPUT_SPECIAL) echo $this->writeInvisibleHTML($content); echo $this->html_after; return; } else { echo $content; return $this->_exit($this->status); } } $this->getWarningRange(); $this->getCriticalRange(); if (!is_null($this->argTimeout)) { $timeout = $this->argTimeout->getValue(); if (!is_null($timeout)) { Timeouter::start($timeout); } } ob_start(); $init_ob_level = ob_get_level(); try { $this->cbRun(); if (ob_get_level() < $init_ob_level) throw new VNagImplementationErrorException(VNagLang::$output_level_lowered); } finally { while (ob_get_level() > $init_ob_level) @ob_end_clean(); } if (is_null($this->status)) $this->setStatus($this->default_status,true); $outputType = VNag::OUTPUT_NORMAL; } catch (Exception $e) { $this->handleException($e); $outputType = VNag::OUTPUT_EXCEPTION; } if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_invisible_output & $outputType) { echo $this->writeInvisibleHTML(); } if ($this->http_visual_output & $outputType) { echo $this->writeVisualHTML(); } echo $this->html_after; } else { echo $this->getNagiosConsoleText(); return $this->_exit($this->status); } Timeouter::end(); } finally { $inside_vnag_run = false; } } private function getNagiosConsoleText() { $ary_perfdata = $this->getPerformanceData(); $performancedata_first = array_shift($ary_perfdata); $performancedata_rest = implode(' ', $ary_perfdata); $status_text = VNagLang::status($this->status, $this->statusmodel); if (_empty($this->getHeadline())) { $content = $status_text; } else { if ($this->show_status_in_headline) { $content = $status_text.': '.$this->getHeadline(); } else { $content = $this->getHeadline(); } } if (!_empty($performancedata_first)) $content .= '|'.trim($performancedata_first); $content .= "\n"; if (!_empty($this->verbose_info)) { $content .= trim($this->verbose_info); } if (!_empty($performancedata_rest)) $content .= '|'.trim($performancedata_rest); $content .= "\n"; return trim($content)."\n"; } abstract protected function cbRun(); public function addPerformanceData($prefDataObj, $move_to_font=false, $verbosityLevel=VNag::VERBOSITY_SUMMARY) { $this->checkInitialized(); if ((!isset($this->argVerbosity)) && ($verbosityLevel > VNag::VERBOSITY_SUMMARY)) throw new VNagRequiredArgumentNotRegistered('-v'); if (self::getVerbosityLevel() < $verbosityLevel) return false; if ($move_to_font) { array_unshift($this->performanceDataObjects, $prefDataObj); } else { $this->performanceDataObjects[] = $prefDataObj; } return true; } public function getPerformanceData() { $this->checkInitialized(); return $this->performanceDataObjects; } public function removePerformanceData($prefDataObj) { if (($key = array_search($prefDataObj, $this->performanceDataObjects, true)) !== false) { unset($this->performanceDataObjects[$key]); return true; } else { return false; } } public function clearPerformanceData() { $this->performanceDataObjects = array(); } public function getVerboseInfo() { return $this->verbose_info; } public function clearVerboseInfo() { $this->verbose_info = ''; } private function writeVisualHTML($special_content=null) { if (!_empty($special_content)) { $content = $special_content; } else { $content = strtoupper(VNagLang::$status.': '.VNagLang::status($this->status, $this->statusmodel))."\n\n"; $content .= strtoupper(VNagLang::$message).":\n"; $status_text = VNagLang::status($this->status, $this->statusmodel); if (_empty($this->getHeadline())) { $content .= $status_text; } else { if ($this->show_status_in_headline) { $content .= $status_text.': '.trim($this->getHeadline()); } else { $content .= trim($this->getHeadline()); } } $content .= "\n\n"; if (!_empty($this->verbose_info)) { $content .= strtoupper(VNagLang::$verbose_info).":\n".trim($this->verbose_info)."\n\n"; } $perfdata = $this->getPerformanceData(); if (count($perfdata) > 0) { $content .= strtoupper(VNagLang::$performance_data).":\n"; foreach ($perfdata as $pd) { $content .= trim($pd)."\n"; } $content .= "\n"; } } $colorinfo = ''; $status = $this->getStatus(); if ($status == VNag::STATUS_OK) $colorinfo = ' style="background-color:green;color:white;font-weight:bold"'; else if ($status == VNag::STATUS_WARNING) $colorinfo = ' style="background-color:yellow;color:black;font-weight:bold"'; else if ($status == VNag::STATUS_CRITICAL) $colorinfo = ' style="background-color:red;color:white;font-weight:bold"'; else if ($status == VNag::STATUS_ERROR) $colorinfo = ' style="background-color:purple;color:white;font-weight:bold"'; else $colorinfo = ' style="background-color:lightgray;color:black;font-weight:bold"'; $html_content = trim($content); $html_content = htmlentities($html_content); $html_content = str_replace(' ', '&nbsp;', $html_content); $html_content = nl2br($html_content); return '<table border="1" cellspacing="2" cellpadding="2" style="width:100%" class="vnag_table">'. '<tr'.$colorinfo.' class="vnag_title_row">'. '<td>'.VNagLang::$nagios_output.'</td>'. '</tr>'. '<tr class="vnag_message_row">'. '<td><code>'. $html_content. '</code></td>'. '</tr>'. '</table>'; } protected function readInvisibleHTML($html) { $this->checkInitialized(); $doc = new DOMDocument(); @$doc->loadHTML($html); $tags = $doc->getElementsByTagName('script'); foreach ($tags as $tag) { $type = $tag->getAttribute('type'); if ($type !== 'application/json') continue; $json = $tag->nodeValue; if (!$json) continue; $data = @json_decode($json,true); if (!is_array($data)) continue; if (!isset($data['type'])) continue; if ($data['type'] === VNAG_JSONDATA_V1) { if (!isset($data['datasets'])) throw new VNagWebInfoException(VNagLang::$dataset_missing); foreach ($data['datasets'] as $dataset) { $payload = base64_decode($dataset['payload']); if (!$payload) { throw new VNagWebInfoException(VNagLang::$payload_not_base64); } if (isset($dataset['encryption'])) { $cryptInfo = $dataset['encryption']; if (!is_array($cryptInfo)) { throw new VNagWebInfoException(VNagLang::$dataset_encryption_no_array); } $password = is_null($this->password_in) ? '' : $this->password_in; $salt = base64_decode($cryptInfo['salt']); if ($cryptInfo['hash'] != hash('sha256',$salt.$password)) { if ($password == '') { throw new VNagWebInfoException(VNagLang::$require_password); } else { throw new VNagWebInfoException(VNagLang::$wrong_password); } } if (!function_exists('openssl_decrypt')) { throw new VNagException(VNagLang::$openssl_missing); } $payload = openssl_decrypt($payload, $cryptInfo['method'], $password, 0, $cryptInfo['iv']); } if (!is_null($this->pubkey) && ($this->pubkey !== '')) { if (substr($this->pubkey,0,3) === '---') { $public_key = $this->pubkey; } else { if (!file_exists($this->pubkey)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$pubkey_file_not_found, $this->pubkey)); } $public_key = @file_get_contents($this->pubkey); if (!$public_key) { throw new VNagPublicKeyException(sprintf(VNagLang::$pubkey_file_not_readable, $this->pubkey)); } } if (!isset($dataset['signature'])) { throw new VNagSignatureException(VNagLang::$signature_missing); } $signature = base64_decode($dataset['signature']); if (!$signature) { throw new VNagSignatureException(VNagLang::$signature_not_bas64); } if (!function_exists('openssl_verify')) { throw new VNagException(VNagLang::$openssl_missing); } $sign_algo = is_null($this->sign_algo) ? OPENSSL_ALGO_SHA256 : $this->sign_algo; if (!openssl_verify($payload, $signature, $public_key, $sign_algo)) { throw new VNagSignatureException(VNagLang::$signature_invalid); } } $payload = @json_decode($payload,true); if (!$payload) { throw new VNagWebInfoException(VNagLang::$payload_not_json); } if ($payload['id'] == $this->id) { return $payload; } } } } return null; } private function getNextMonitorID($peek=false) { $result = is_null($this->id) ? self::$http_serial_number : $this->id; if (!$peek) { $this->id = null; self::$http_serial_number++; } return $result; } private function writeInvisibleHTML($special_content=null) { $payload['id'] = $this->getNextMonitorID(); $payload['status'] = $this->getStatus(); if (!_empty($special_content)) { $payload['text'] = $special_content; } else { $payload['headline'] = $this->getHeadline(); $payload['verbose_info'] = $this->verbose_info; $payload['performance_data'] = array(); foreach ($this->performanceDataObjects as $perfdata) { $payload['performance_data'][] = (string)$perfdata; } } $payload = json_encode($payload); $dataset = array(); if (!is_null($this->privkey) && ($this->privkey !== '')) { if (!function_exists('openssl_pkey_get_private') || !function_exists('openssl_sign')) { throw new VNagException(VNagLang::$openssl_missing); } if (substr($this->privkey,0,3) === '---') { $pkeyid = @openssl_pkey_get_private($this->privkey, $this->privkey_password); if (!$pkeyid) { throw new VNagPrivateKeyException(sprintf(VNagLang::$privkey_not_readable)); } } else { if (!file_exists($this->privkey)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$privkey_file_not_found, $this->privkey)); } $pkeyid = @openssl_pkey_get_private('file://'.$this->privkey, $this->privkey_password); if (!$pkeyid) { throw new VNagPrivateKeyException(sprintf(VNagLang::$privkey_file_not_readable, $this->privkey)); } } $signature = ''; $sign_algo = is_null($this->sign_algo) ? OPENSSL_ALGO_SHA256 : $this->sign_algo; if (@openssl_sign($payload, $signature, $pkeyid, $sign_algo)) { if (version_compare(PHP_VERSION, '8.0.0') < 0) { openssl_free_key($pkeyid); } $dataset['signature'] = base64_encode($signature); } else { throw new VNagPrivateKeyException(sprintf(VNagLang::$signature_failed)); } } if (!is_null($this->password_out) && ($this->password_out !== '')) { if (!function_exists('openssl_encrypt')) { throw new VNagException(VNagLang::$openssl_missing); } $password = $this->password_out; $method = 'aes-256-ofb'; $iv = substr(hash('sha256', openssl_random_pseudo_bytes(32)), 0, 16); $salt = openssl_random_pseudo_bytes(32); $cryptInfo = array(); $cryptInfo['method'] = $method; $cryptInfo['iv'] = $iv; $cryptInfo['salt'] = base64_encode($salt); $cryptInfo['hash'] = hash('sha256', $salt.$password); $payload = openssl_encrypt($payload, $method, $password, 0, $iv); $dataset['encryption'] = $cryptInfo; } $dataset['payload'] = base64_encode($payload); $json = array(); $json['type'] = VNAG_JSONDATA_V1; $json['datasets'] = array($dataset); return '<script type="application/json">'. json_encode($json). '</script>'; } protected function appendHeadline($msg) { $this->checkInitialized(); if (_empty($msg)) return false; $this->messages[] = $msg; return true; } protected function changeHeadline($msg) { $this->checkInitialized(); if (_empty($msg)) { $this->messages = array(); } else { $this->messages = array($msg); } return true; } public function setHeadline($msg, $append=false, $verbosityLevel=VNag::VERBOSITY_SUMMARY) { $this->checkInitialized(); if ((!isset($this->argVerbosity)) && ($verbosityLevel > VNag::VERBOSITY_SUMMARY)) throw new VNagRequiredArgumentNotRegistered('-v'); if (self::getVerbosityLevel() < $verbosityLevel) $msg = ''; if ($append) { return $this->appendHeadline($msg); } else { return $this->changeHeadline($msg); } } public function getHeadline() { $this->checkInitialized(); return implode(', ', $this->messages); } public function addVerboseMessage($msg, $verbosityLevel=VNag::VERBOSITY_SUMMARY) { $this->checkInitialized(); if (self::getVerbosityLevel() >= $verbosityLevel) { $this->verbose_info .= $msg."\n"; } } public function setStatus($status, $force=false) { $this->checkInitialized(); if (($force) || is_null($this->status) || ($status > $this->status)) { $this->status = $status; } } public function getStatus() { $this->checkInitialized(); return $this->status; } protected static function exceptionText($exception) { $class = get_class($exception); $msg = $exception->getMessage(); if (!_empty($msg)) { return sprintf(VNagLang::$exception_x, $msg, $class); } else { return sprintf(VNagLang::$unhandled_exception_without_msg, $class); } } protected function handleException($exception) { $this->checkInitialized(); if (!VNag::is_http_mode()) { while (ob_get_level() > 0) @ob_end_clean(); } $this->clearVerboseInfo(); $this->clearPerformanceData(); if ($exception instanceof VNagException) { $this->setStatus($exception->getStatus()); } else { $this->setStatus(self::STATUS_ERROR); } $this->setHeadline($this->exceptionText($exception), false); if ($exception instanceof VNagImplementationErrorException) { $this->addVerboseMessage($exception->getTraceAsString(), VNag::VERBOSITY_SUMMARY); } else { if (isset($this->argVerbosity)) { $this->addVerboseMessage($exception->getTraceAsString(), VNag::VERBOSITY_ADDITIONAL_INFORMATION); } else { } } } protected function get_cache_dir() { $homedir = @getenv('HOME'); if ($homedir && is_dir($homedir)) { $try = "$homedir/.vnag/cache"; if (is_dir($try)) return $try; if (@mkdir($try,0777,true)) return $try; } $user = posix_getpwuid(posix_geteuid()); if (isset($user['dir']) && is_dir($user['dir'])) { $homedir = $user['dir']; $try = "$homedir/.vnag/cache"; if (is_dir($try)) return $try; if (@mkdir($try,0777,true)) return $try; } if (isset($user['name']) && is_dir($user['name'])) { $username = $user['name']; $try = "/tmp/vnag/cache"; if (is_dir($try)) return $try; if (@mkdir($try,0777,true)) return $try; } throw new VNagException("Cannot get cache dir"); } protected function url_get_contents($url, $max_cache_time=1*60*60, $context=null) { $cache_file = $this->get_cache_dir().'/'.hash('sha256',$url); if (file_exists($cache_file) && (time()-filemtime($cache_file) < $max_cache_time)) { $cont = @file_get_contents($cache_file); if ($cont === false) throw new Exception("Failed to get contents from $cache_file"); } else { $options = array( 'http'=>array( 'method'=>"GET", 'header'=>"Accept-language: en\r\n" . "User-Agent: Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B334b Safari/531.21.102011-10-16 20:23:10\r\n" ) ); if (is_null($context)) $context = stream_context_create($options); $cont = @file_get_contents($url, false, $context); if ($cont === false) throw new Exception("Failed to get contents from $url"); file_put_contents($cache_file, $cont); } return $cont; } } class VNagException extends Exception { public function getStatus() { return VNag::STATUS_ERROR; } } class VNagTimeoutException extends VNagException {} class VNagWebInfoException extends VNagException {} class VNagSignatureException extends VNagException {} class VNagPublicKeyException extends VNagException {} class VNagPrivateKeyException extends VNagException {} class VNagInvalidArgumentException extends VNagException { public function getStatus() { return VNag::STATUS_UNKNOWN; } } class VNagValueUomPairSyntaxException extends VNagInvalidArgumentException { public function __construct($str) { $e_msg = sprintf(VNagLang::$valueUomPairSyntaxError, $str); parent::__construct($e_msg); } } class VNagInvalidTimeoutException extends VNagInvalidArgumentException {} class VNagInvalidRangeException extends VNagInvalidArgumentException { public function __construct($msg) { $e_msg = VNagLang::$range_is_invalid; if (!_empty($msg)) $e_msg .= ': '.trim($msg); parent::__construct($e_msg); } } class VNagInvalidShortOpt extends VNagImplementationErrorException {} class VNagInvalidLongOpt extends VNagImplementationErrorException {} class VNagInvalidValuePolicy extends VNagImplementationErrorException {} class VNagIllegalStatusModel extends VNagImplementationErrorException {} class VNagNotConstructed extends VNagImplementationErrorException {} class VNagImplementationErrorException extends VNagException {} class VNagInvalidStandardArgument extends VNagImplementationErrorException {} class VNagFunctionCallOutsideSession extends VNagImplementationErrorException {} class VNagIllegalArgumentValuesException extends VNagImplementationErrorException {} class VNagRequiredArgumentNotRegistered extends VNagImplementationErrorException { public function __construct($required_argument) { $e_msg = sprintf(VNagLang::$query_without_expected_argument, $required_argument); parent::__construct($e_msg); } } class VNagRequiredArgumentMissing extends VNagInvalidArgumentException { public function __construct($required_argument) { $e_msg = sprintf(VNagLang::$required_argument_missing, $required_argument); parent::__construct($e_msg); } } class VNagUnknownUomException extends VNagInvalidArgumentException { public function __construct($uom) { $e_msg = sprintf(VNagLang::$perfdata_uom_not_recognized, $uom); parent::__construct($e_msg); } } class VNagNoCompatibleRangeUomFoundException extends VNagException {} class VNagMixedUomsNotImplemented extends VNagInvalidArgumentException { public function __construct($uom1, $uom2) { if (_empty($uom1)) $uom1 = VNagLang::$none; if (_empty($uom2)) $uom2 = VNagLang::$none; $e_msg = sprintf(VNagLang::$perfdata_mixed_uom_not_implemented, $uom1, $uom2); parent::__construct($e_msg); } } class VNagUomConvertException extends VNagInvalidArgumentException { public function __construct($uom1, $uom2) { if (_empty($uom1)) $uom1 = VNagLang::$none; if (_empty($uom2)) $uom2 = VNagLang::$none; $e_msg = sprintf(VNagLang::$convert_x_y_error, $uom1, $uom2); parent::__construct($e_msg); } } class VNagInvalidPerformanceDataException extends VNagInvalidArgumentException { public function __construct($msg) { $e_msg = VNagLang::$performance_data_invalid; if (!_empty($msg)) $e_msg .= ': '.trim($msg); parent::__construct($e_msg); } } class Timeouter { private static $start_time = false; private static $timeout; private static $fired = false; private static $registered = false; private function __construct() { } public static function start($timeout) { if (!is_numeric($timeout) || ($timeout <= 0)) { throw new VNagInvalidTimeoutException(sprintf(VNagLang::$timeout_value_invalid, $timeout)); } self::$start_time = microtime(true); self::$timeout = (float) $timeout; self::$fired = false; if (!self::$registered) { self::$registered = true; register_tick_function(array('Timeouter', 'tick')); } } public static function started() { return self::$registered; } public static function end() { if (self::$registered) { unregister_tick_function(array('Timeouter', 'tick')); self::$registered = false; } } public static function tick() { if ((!self::$fired) && ((microtime(true) - self::$start_time) > self::$timeout)) { self::$fired = true; throw new VNagTimeoutException(VNagLang::$timeout_exception); } } } class VNagArgument { const VALUE_FORBIDDEN = 0; const VALUE_REQUIRED = 1; const VALUE_OPTIONAL = 2; protected $shortopt; protected $longopts; protected $valuePolicy; protected $valueName; protected $helpText; protected $defaultValue = null; protected static $all_short = ''; protected static $all_long = array(); public function getShortOpt() { return $this->shortopt; } public function getLongOpts() { return $this->longopts; } public function getValuePolicy() { return $this->valuePolicy; } public function getValueName() { return $this->valueName; } public function getHelpText() { return $this->helpText; } static private function validateShortOpt($shortopt) { $m = array(); return preg_match('@^[a-zA-Z0-9\\+\\-\\?]$@', $shortopt, $m); } static private function validateLongOpt($longopt) { $m = array(); return preg_match('@^[a-zA-Z0-9\\+\\-\\?]+$@', $longopt, $m); } public function __construct($shortopt, $longopts, $valuePolicy, $valueName, $helpText, $defaultValue=null) { switch ($valuePolicy) { case VNagArgument::VALUE_FORBIDDEN: if (!_empty($valueName)) { throw new VNagImplementationErrorException(sprintf(VNagLang::$value_name_forbidden)); } break; case VNagArgument::VALUE_REQUIRED: if (_empty($valueName)) { throw new VNagImplementationErrorException(sprintf(VNagLang::$value_name_required)); } break; case VNagArgument::VALUE_OPTIONAL: if (_empty($valueName)) { throw new VNagImplementationErrorException(sprintf(VNagLang::$value_name_required)); } break; default: throw new VNagInvalidValuePolicy(sprintf(VNagLang::$illegal_valuepolicy, $valuePolicy)); } if (!_empty($shortopt)) { if (!self::validateShortOpt($shortopt)) { throw new VNagInvalidShortOpt(sprintf(VNagLang::$illegal_shortopt, $shortopt)); } } if (is_array($longopts)) { foreach ($longopts as $longopt) { if (!self::validateLongOpt($longopt)) { throw new VNagInvalidLongOpt(sprintf(VNagLang::$illegal_longopt, $longopt)); } } } else if (!_empty($longopts)) { if (!self::validateLongOpt($longopts)) { throw new VNagInvalidLongOpt(sprintf(VNagLang::$illegal_longopt, $longopts)); } $longopts = array($longopts); } else { $longopts = array(); } switch ($valuePolicy) { case VNagArgument::VALUE_FORBIDDEN: $policyApdx = ''; break; case VNagArgument::VALUE_REQUIRED: $policyApdx = ':'; break; case VNagArgument::VALUE_OPTIONAL: $policyApdx = '::'; break; default: throw new VNagInvalidValuePolicy(sprintf(VNagLang::$illegal_valuepolicy, $valuePolicy)); } if ((!is_null($shortopt)) && ($shortopt != '?')) self::$all_short .= $shortopt.$policyApdx; if (is_array($longopts)) { foreach ($longopts as $longopt) { self::$all_long[] = $longopt.$policyApdx; } } $this->shortopt = $shortopt; $this->longopts = $longopts; $this->valuePolicy = $valuePolicy; $this->valueName = $valueName; $this->helpText = $helpText; $this->defaultValue = $defaultValue; } protected static function getOptions() { global $OVERWRITE_ARGUMENTS; if (!is_null($OVERWRITE_ARGUMENTS)) { return $OVERWRITE_ARGUMENTS; } else if (VNag::is_http_mode()) { return $_REQUEST; } else { return getopt(self::$all_short, self::$all_long); } } public function count() { $options = self::getOptions(); $count = 0; if (isset($options[$this->shortopt])) { if (is_array($options[$this->shortopt])) { $count += count($options[$this->shortopt]); } else { $count += 1; } } if (!is_null($this->longopts)) { foreach ($this->longopts as $longopt) { if (isset($options[$longopt])) { if (is_array($options[$longopt])) { $count += count($options[$longopt]); } else { $count += 1; } } } } return $count; } public function available() { $options = self::getOptions(); if (isset($options[$this->shortopt])) return true; if (!is_null($this->longopts)) { foreach ($this->longopts as $longopt) { if (isset($options[$longopt])) return true; } } return false; } public function require() { if (!$this->available() && is_null($this->defaultValue)) { $opt = $this->shortopt; $opt = !_empty($opt) ? '-'.$opt : (isset($this->longopts[0]) ? '--'.$this->longopts[0] : '?'); throw new VNagRequiredArgumentMissing($opt); } } public function getValue() { $options = self::getOptions(); if (isset($options[$this->shortopt])) { $x = $options[$this->shortopt]; if (is_array($x) && (count($x) <= 1)) $options[$this->shortopt] = $options[$this->shortopt][0]; return $options[$this->shortopt]; } if (!is_null($this->longopts)) { foreach ($this->longopts as $longopt) { if (isset($options[$longopt])) { $x = $options[$longopt]; if (is_array($x) && (count($x) <= 1)) $options[$longopt] = $options[$longopt][0]; return $options[$longopt]; } } } return $this->defaultValue; } } class VNagArgumentHandler { protected $expectedArgs = array(); protected function _addExpectedArgument($argObj) { if ($argObj->getShortOpt() == '?') return false; if ($argObj->getShortOpt() == '-') return false; if ($argObj->getShortOpt() == '+') return false; $this->expectedArgs[] = $argObj; return true; } public function getArgumentObj($shortopt) { foreach ($this->expectedArgs as $argObj) { if ($argObj->getShortOpt() == $shortopt) return $argObj; } return null; } public function isArgRegistered($shortopt) { return !is_null($this->getArgumentObj($shortopt)); } public function illegalUsage() { global $argv; return (isset($argv[1])) && (($argv[1] == '-?') || ($argv[1] == '/?')); } } class VNagRange { public $start; public $end; public $warnInsideRange; public function __construct($rangeDef, $singleValueBehavior=VNag::SINGLEVALUE_RANGE_DEFAULT) { $m = array(); if (!preg_match('|^(@){0,1}([^:]+)(:){0,1}(.*)$|', $rangeDef, $m)) { throw new VNagInvalidRangeException(sprintf(VNagLang::$range_invalid_syntax, $rangeDef)); } $this->warnInsideRange = $m[1] === '@'; $this->start = null; $this->end = null; if ($m[3] === ':') { if ($m[2] === '~') { $this->start = '-inf'; } else { $this->start = new VNagValueUomPair($m[2]); } if (_empty($m[4])) { $this->end = 'inf'; } else { $this->end = new VNagValueUomPair($m[4]); } } else { assert(_empty($m[4])); assert(!_empty($m[2])); $x = $m[2]; if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_DEFAULT) { $this->start = new VNagValueUomPair('0'.((new VNagValueUomPair($x))->getUom())); $this->end = new VNagValueUomPair($x); } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_GT_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 0; $this->start = '-inf'; $this->end = new VNagValueUomPair($x); } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_GE_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 1; $this->start = new VNagValueUomPair($x); $this->end = 'inf'; } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_LT_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 0; $this->start = new VNagValueUomPair($x); $this->end = 'inf'; } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_LE_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 1; $this->start = '-inf'; $this->end = new VNagValueUomPair($x); } else { throw new VNagException(VNagLang::$illegalSingleValueBehavior); } } if (is_null($this->start)) { throw new VNagInvalidRangeException(VNagLang::$invalid_start_value); } if (is_null($this->end)) { throw new VNagInvalidRangeException(VNagLang::$invalid_end_value); } if (($this->start instanceof VNagValueUomPair) && ($this->end instanceof VNagValueUomPair) && (VNagValueUomPair::compare($this->start,$this->end) > 0)) { throw new VNagInvalidRangeException(VNagLang::$start_is_greater_than_end); } } public function __toString() { $ret = ''; if ($this->warnInsideRange) { $ret = '@'; } if ($this->start === '-inf') { $ret .= '~'; } else { $ret .= $this->start; } $ret .= ':'; if ($this->end !== 'inf') { $ret .= $this->end; } return $ret; } public function checkAlert($values) { $compatibleCount = 0; if (!is_array($values)) $values = array($values); foreach ($values as $value) { if (!($value instanceof VNagValueUomPair)) $value = new VNagValueUomPair($value); assert(($this->start === '-inf') || ($this->start instanceof VNagValueUomPair)); assert(($this->end === 'inf' ) || ($this->end instanceof VNagValueUomPair)); if (($this->start !== '-inf') && (!$this->start->compatibleWith($value))) continue; if (($this->end !== 'inf') && (!$this->end->compatibleWith($value))) continue; $compatibleCount++; if ($this->warnInsideRange) { return (($this->start === '-inf') || (VNagValueUomPair::compare($value,$this->start) >= 0)) && (($this->end === 'inf') || (VNagValueUomPair::compare($value,$this->end) <= 0)); } else { return (($this->start !== '-inf') && (VNagValueUomPair::compare($value,$this->start) < 0)) || (($this->end !== 'inf') && (VNagValueUomPair::compare($value,$this->end) > 0)); } } if ((count($values) > 0) and ($compatibleCount == 0)) { throw new VNagNoCompatibleRangeUomFoundException(VNagLang::$no_compatible_range_uom_found); } return false; } } class VNagValueUomPair { protected $value; protected $uom; public $roundTo = -1; public function isRelative() { return $this->uom === '%'; } public function getValue() { return $this->value; } public function getUom() { return $this->uom; } public function __toString() { if ($this->roundTo == -1) { return $this->value.$this->uom; } else { return round($this->value,$this->roundTo).$this->uom; } } public function __construct($str) { $m = array(); if (!preg_match('/^([\d\.]+)(.*)$/ism', $str, $m)) { throw new VNagValueUomPairSyntaxException($str); } $this->value = $m[1]; $this->uom = isset($m[2]) ? $m[2] : ''; if (!self::isKnownUOM($this->uom)) { throw new VNagUnknownUomException($this->uom); } } public static function isKnownUOM(string $uom) { $no_unit = ($uom === ''); $seconds = ($uom === 's') || ($uom === 'ms') || ($uom === 'us'); $percentage = ($uom === '%'); $bytes = ($uom === 'B') || ($uom === 'KB') || ($uom === 'MB') || ($uom === 'GB') || ($uom === 'TB'); $counter = ($uom === 'c'); return ($no_unit || $seconds || $percentage || $bytes || $counter); } public function normalize($target=null) { $res = clone $this; if ($res->uom === 'ms') { $res->uom = 's'; $res->value /= 1000; } if ($res->uom === 'us') { $res->uom = 's'; $res->value /= 1000 * 1000; } if ($res->uom === 'B') { $res->uom = 'MB'; $res->value /= 1024 * 1024; } if ($res->uom === 'KB') { $res->uom = 'MB'; $res->value /= 1024; } if ($res->uom === 'GB') { $res->uom = 'MB'; $res->value *= 1024; } if ($res->uom === 'TB') { $res->uom = 'MB'; $res->value *= 1024 * 1024; } if ($res->uom === 'c') { $res->uom = ''; } if (!is_null($target)) { if ($res->uom == 'MB') { if ($target == 'B') { $res->uom = 'B'; $res->value *= 1024 * 1024; } else if ($target == 'KB') { $res->uom = 'KB'; $res->value *= 1024; } else if ($target == 'MB') { $res->uom = 'MB'; $res->value *= 1; } else if ($target == 'GB') { $res->uom = 'GB'; $res->value /= 1024; } else if ($target == 'TB') { $res->uom = 'TB'; $res->value /= 1024 * 1024; } else { throw new VNagUomConvertException($res->uom, $target); } } else if ($res->uom == 's') { if ($target == 's') { $res->uom = 's'; $res->value /= 1; } else if ($target == 'ms') { $res->uom = 'ms'; $res->value /= 1000; } else if ($target == 'us') { $res->uom = 'us'; $res->value /= 1000 * 1000; } else { throw new VNagUomConvertException($res->uom, $target); } } else { throw new VNagUomConvertException($res->uom, $target); } } return $res; } public function compatibleWith(VNagValueUomPair $other) { $a = $this->normalize(); $b = $other->normalize(); return ($a->uom == $b->uom); } public static function compare(VNagValueUomPair $left, VNagValueUomPair $right) { $a = $left->normalize(); $b = $right->normalize(); if ($a->uom != $b->uom) throw new VNagMixedUomsNotImplemented($a->uom, $b->uom); if ($a->value > $b->value) return 1; if ($a->value == $b->value) return 0; if ($a->value < $b->value) return -1; } } class VNagPerformanceData { protected $label; protected $value; protected $warn = null; protected $crit = null; protected $min = null; protected $max = null; public static function createByString($perfdata) { $perfdata = trim($perfdata); $ary = explode('=',$perfdata); if (count($ary) != 2) { throw new VNagInvalidPerformanceDataException(sprintf(VNagLang::$perfdata_line_invalid, $perfdata)); } $label = $ary[0]; $bry = explode(';',$ary[1]); if (substr($label,0,1) === "'") $label = substr($label, 1, strlen($label)-2); $value = $bry[0]; $warn = isset($bry[1]) ? $bry[1] : null; $crit = isset($bry[2]) ? $bry[2] : null; $min = isset($bry[3]) ? $bry[3] : null; $max = isset($bry[4]) ? $bry[4] : null; return new self($label, $value, $warn, $crit, $min, $max); } public function __construct($label, $value, $warn=null, $crit=null, $min=null, $max=null) { if (strpos($label, '=') !== false) throw new VNagInvalidPerformanceDataException(VNagLang::$perfdata_label_equal_sign_forbidden); $label = str_replace("'", "''", $label); $m = array(); if ((!_empty($min)) && (!preg_match('|^[-0-9\\.]+$|', $min, $m))) { throw new VNagInvalidPerformanceDataException(VNagLang::$perfdata_min_must_be_in_class); } if ((!_empty($max)) && (!preg_match('|^[-0-9\\.]+$|', $max, $m))) { throw new VNagInvalidPerformanceDataException(VNagLang::$perfdata_max_must_be_in_class); } $this->label = $label; $this->value = ($value == 'U') ? 'U' : new VNagValueUomPair($value); $this->warn = $warn; $this->crit = $crit; $this->min = $min; $this->max = $max; } public function __toString() { $label = $this->label; $value = $this->value; $warn = $this->warn; $crit = $this->crit; $min = $this->min; $max = $this->max; $label = str_replace("''", "'", $label); return "'$label'=$value". ';'.(is_null($warn) ? '' : $warn). ';'.(is_null($crit) ? '' : $crit). ';'.(is_null($min) ? '' : $min). ';'.(is_null($max) ? '' : $max); } } class VNagHelp { public $word_wrap_width = 80; public $argument_indent = 7; public function printUsagePage() { $usage = $this->getUsage(); if (_empty($usage)) { $usage = VNagLang::$no_syntax_defined; } return trim($usage)."\n"; } public function printVersionPage() { $out = trim($this->getNameAndVersion())."\n"; if ($this->word_wrap_width > 0) $out = wordwrap($out, $this->word_wrap_width, "\n", false); return $out; } static private function _conditionalLine($line, $terminator='', $prefix='') { if (!_empty($line)) { return trim($line).$terminator; } return ''; } public function printHelpPage() { $out = ''; $out .= self::_conditionalLine($this->getNameAndVersion(), "\n"); $out .= self::_conditionalLine($this->getCopyright(), "\n"); $out .= ($out != '') ? "\n" : ''; $out .= self::_conditionalLine($this->getShortDescription(), "\n\n\n"); $out .= self::_conditionalLine($this->getUsage(), "\n\n"); $out .= VNagLang::$options."\n"; foreach ($this->options as $argObj) { $out .= $this->printArgumentHelp($argObj); } $out .= self::_conditionalLine($this->getFootNotes(), "\n\n", "\n"); if ($this->word_wrap_width > 0) $out = wordwrap($out, $this->word_wrap_width, "\n", false); return $out; } protected $options = array(); protected function _addOption($argObj) { $this->options[] = $argObj; } protected function printArgumentHelp($argObj) { $identifiers = array(); $shortopt = $argObj->getShortopt(); if (!_empty($shortopt)) $identifiers[] = '-'.$shortopt; $longopts = $argObj->getLongopts(); if (!is_null($longopts)) { foreach ($longopts as $longopt) { if (!_empty($longopt)) $identifiers[] = '--'.$longopt; } } if (count($identifiers) == 0) return; $valueName = $argObj->getValueName(); $arginfo = ''; switch ($argObj->getValuePolicy()) { case VNagArgument::VALUE_FORBIDDEN: $arginfo = ''; break; case VNagArgument::VALUE_REQUIRED: $arginfo = '='.$valueName; break; case VNagArgument::VALUE_OPTIONAL: $arginfo = '[='.$valueName.']'; break; } $out = ''; $out .= implode(', ', $identifiers).$arginfo."\n"; $content = trim($argObj->getHelpText()); if ($this->word_wrap_width > 0) $content = wordwrap($content, $this->word_wrap_width-$this->argument_indent, "\n", false); $lines = explode("\n", $content); foreach ($lines as $line) { $out .= str_repeat(' ', $this->argument_indent).$line."\n"; } $out .= "\n"; return $out; } protected $pluginName; public function setPluginName($pluginName) { $this->pluginName = $this->replaceStuff($pluginName); } public function getPluginName() { if (_empty($this->pluginName)) { global $argv; return basename($argv[0]); } else { return $this->pluginName; } } protected $version; public function setVersion($version) { $this->version = $this->replaceStuff($version); } public function getVersion() { return $this->version; } public function getNameAndVersion() { $ret = $this->getPluginName(); if (_empty($ret)) return null; $ver = $this->getVersion(); if (!_empty($ver)) { $ret = sprintf(VNagLang::$x_version_x, $ret, $ver); } $ret = trim($ret); return $ret; } protected $copyright; public function setCopyright($copyright) { $this->copyright = $this->replaceStuff($copyright); } private function getVNagCopyright() { if (VNag::is_http_mode()) { $vts_email = 'www.viathinksoft.com'; } else { $vts_email = base64_decode('aW5mb0B2aWF0aGlua3NvZnQuZGU='); } return "VNag Framework ".VNag::VNAG_VERSION." (C) 2014-".date('Y')." ViaThinkSoft <$vts_email>"; } public function getCopyright() { if (_empty($this->copyright)) { return sprintf(VNagLang::$plugin_uses, $this->getVNagCopyright()); } else { return trim($this->copyright)."\n".sprintf(VNagLang::$uses, $this->getVNagCopyright()); } } protected $shortDescription; public function setShortDescription($shortDescription) { $this->shortDescription = $this->replaceStuff($shortDescription); } public function getShortDescription() { if (_empty($this->shortDescription)) { return null; } else { $content = $this->shortDescription; if ($this->word_wrap_width > 0) $content = wordwrap($content, $this->word_wrap_width, "\n", false); return $content; } } protected function replaceStuff($text) { global $argv; if (php_sapi_name() == 'cli') { $text = str_replace('$SCRIPTNAME$', $argv[0], $text); } else { $text = str_replace('$SCRIPTNAME$', basename($_SERVER['SCRIPT_NAME']), $text); } $text = str_replace('$CURYEAR$', date('Y'), $text); return $text; } protected $syntax; public function setSyntax($syntax) { $syntax = $this->replaceStuff($syntax); $this->syntax = $syntax; } public function getUsage() { if (_empty($this->syntax)) { return null; } else { return sprintf(VNagLang::$usage_x, $this->syntax); } } protected $footNotes; public function setFootNotes($footNotes) { $this->footNotes = $this->replaceStuff($footNotes); } public function getFootNotes() { return $this->footNotes; } } class VNagLang { public static function status($code, $statusmodel) { switch ($statusmodel) { case VNag::STATUSMODEL_SERVICE: switch ($code) { case VNag::STATUS_OK: return 'OK'; case VNag::STATUS_WARNING: return 'Warning'; case VNag::STATUS_CRITICAL: return 'Critical'; case VNag::STATUS_UNKNOWN: return 'Unknown'; default: return sprintf('Error (%d)', $code); } case VNag::STATUSMODEL_HOST: switch ($code) { case VNag::STATUS_UP: return 'Up'; case VNag::STATUS_DOWN: return 'Down'; default: return sprintf('Maintain last state (%d)', $code); } default: throw new VNagIllegalStatusModel(sprintf(self::$illegal_statusmodel, $statusmodel)); } } static $nagios_output = 'VNag-Output'; static $verbose_info = 'Verbose information'; static $status = 'Status'; static $message = 'Message'; static $performance_data = 'Performance data'; static $status_ok = 'OK'; static $status_warn = 'Warning'; static $status_critical = 'Critical'; static $status_unknown = 'Unknown'; static $status_error = 'Error'; static $unhandled_exception_without_msg = "Unhandled exception of type %s"; static $plugin_uses = 'This plugin uses %s'; static $uses = 'uses %s'; static $x_version_x = '%s, version %s'; static $argname_value = 'value'; static $argname_seconds = 'seconds'; static $query_without_expected_argument = "The argument '%s' is queried, but was not added to the list of expected arguments. Please contact the plugin author."; static $required_argument_missing = "The argument '%s' is required."; static $performance_data_invalid = 'Performance data invalid.'; static $no_standard_arguments_with_letter = "No standard argument with letter '%s' exists."; static $invalid_start_value = 'Invalid start value.'; static $invalid_end_value = 'Invalid end value.'; static $start_is_greater_than_end = 'Start is greater than end value.'; static $value_name_forbidden = "Implementation error: You may not define a value name for the argument, because the value policy is VALUE_FORBIDDEN."; static $value_name_required = "Implementation error: Please define a name for the argument (so it can be shown in the help page)."; static $illegal_shortopt = "Illegal shortopt '-%s'."; static $illegal_longopt = "Illegal longopt '--%s'."; static $illegal_valuepolicy = "valuePolicy has illegal value '%s'."; static $range_invalid_syntax = "Syntax error in range '%s'."; static $timeout_value_invalid = "Timeout value '%s' is invalid."; static $range_is_invalid = 'Range is invalid.'; static $timeout_exception = 'Timeout!'; static $perfdata_label_equal_sign_forbidden = 'Label may not contain an equal sign.'; static $perfdata_value_must_be_in_class = 'Value must be in class [-0-9.] or be \'U\' if the actual value can\'t be determined.'; static $perfdata_min_must_be_in_class = 'Min must be in class [-0-9.] or empty.'; static $perfdata_max_must_be_in_class = 'Max must be in class [-0-9.] or empty.'; static $perfdata_uom_not_recognized = 'UOM (unit of measurement) "%s" is not recognized.'; static $perfdata_mixed_uom_not_implemented = 'Mixed UOMs (%s and %s) are currently not supported.'; static $no_compatible_range_uom_found = 'Measured values are not compatible with the provided warning/critical parameter. Most likely, the UOM is incompatible.'; static $exception_x = '%s (%s)'; static $no_syntax_defined = 'The author of this plugin has not defined a syntax for this plugin.'; static $usage_x = "Usage:\n%s"; static $options = "Options:"; static $illegal_statusmodel = "Invalid statusmodel %d."; static $none = '[none]'; static $valueUomPairSyntaxError = 'Syntax error at "%s". Syntax must be Value[UOM].'; static $too_few_warning_ranges = "You have too few warning ranges (currently trying to get element %d)."; static $too_few_critical_ranges = "You have too few critical ranges (currently trying to get element %d)."; static $dataset_missing = 'Dataset missing.'; static $payload_not_base64 = 'The payload is not valid Base64.'; static $payload_not_json = 'The payload is not valid JSON.'; static $signature_missing = 'The signature is missing.'; static $signature_not_bas64 = 'The signature is not valid Base64.'; static $signature_invalid = 'The signature is invalid. The connection might have been tampered, or a different key is used.'; static $pubkey_file_not_found = "Public key file %s was not found."; static $pubkey_file_not_readable = "Public key file %s is not readable."; static $privkey_file_not_found = "Private key file %s was not found."; static $privkey_not_readable = "Private key is not readable."; static $privkey_file_not_readable = "Private key file %s is not readable."; static $signature_failed = "Signature failed."; static $perfdata_line_invalid = "Performance data line %s is invalid."; static $singlevalue_unexpected_at_symbol = 'This plugin does not allow the @-symbol at ranges for single values.'; static $illegalSingleValueBehavior = "Illegal value for 'singleValueBehavior'. Please contact the creator of the plugin."; static $dataset_encryption_no_array = 'Dataset encryption information invalid.'; static $require_password = 'This resource is protected with a password. Please provide a password.'; static $wrong_password = 'This resource is protected with a password. You have provided the wrong password, or it was changed.'; static $convert_x_y_error = 'Cannot convert from UOM %s to UOM %s.'; static $php_error = 'PHP has detected an error in the plugin. Please contact the plugin author.'; static $output_level_lowered = "Output Buffer level lowered during cbRun(). Please contact the plugin author."; static $openssl_missing = "OpenSSL is missing. Therefore, encryption and signatures are not available."; static $warning_range = 'Warning range'; static $critical_range = 'Critical range'; static $prints_version = 'Prints version'; static $verbosity_helptext = 'Verbosity -v, -vv or -vvv'; static $timeout_helptext = 'Sets timeout in seconds'; static $help_helptext = 'Prints help page'; static $prints_usage = 'Prints usage'; static $notConstructed = 'Parent constructor not called with parent::__construct().'; } function vnagErrorHandler($errorkind, $errortext, $file, $line) { global $inside_vnag_run; if (!$inside_vnag_run && VNag::is_http_mode()) { return false; } if (!(error_reporting() & $errorkind)) { return true; } if (defined('E_ERROR') && ($errorkind == E_ERROR)) $errorkind = 'Error'; if (defined('E_WARNING') && ($errorkind == E_WARNING)) $errorkind = 'Warning'; if (defined('E_PARSE') && ($errorkind == E_PARSE)) $errorkind = 'Parse'; if (defined('E_NOTICE') && ($errorkind == E_NOTICE)) $errorkind = 'Notice'; if (defined('E_CORE_ERROR') && ($errorkind == E_CORE_ERROR)) $errorkind = 'Core Error'; if (defined('E_CORE_WARNING') && ($errorkind == E_CORE_WARNING)) $errorkind = 'Core Warning'; if (defined('E_COMPILE_ERROR') && ($errorkind == E_COMPILE_ERROR)) $errorkind = 'Compile Error'; if (defined('E_COMPILE_WARNING') && ($errorkind == E_COMPILE_WARNING)) $errorkind = 'Compile Warning'; if (defined('E_USER_ERROR') && ($errorkind == E_USER_ERROR)) $errorkind = 'User Error'; if (defined('E_USER_WARNING') && ($errorkind == E_USER_WARNING)) $errorkind = 'User Warning'; if (defined('E_USER_NOTICE') && ($errorkind == E_USER_NOTICE)) $errorkind = 'User Notice'; if (defined('E_STRICT') && ($errorkind == E_STRICT)) $errorkind = 'Strict'; if (defined('E_RECOVERABLE_ERROR') && ($errorkind == E_RECOVERABLE_ERROR)) $errorkind = 'Recoverable Error'; if (defined('E_DEPRECATED') && ($errorkind == E_DEPRECATED)) $errorkind = 'Deprecated'; if (defined('E_USER_DEPRECATED') && ($errorkind == E_USER_DEPRECATED)) $errorkind = 'User Deprecated'; throw new VNagException(VNagLang::$php_error . " $errortext at $file:$line (kind $errorkind)"); } $inside_vnag_run = false; $old_error_handler = set_error_handler("vnagErrorHandler"); <?php
declare(ticks=1); class MdStatCheck extends VNag { public function __construct() { parent::__construct(); if ($this->is_http_mode()) { $this->registerExpectedStandardArguments(''); } else { $this->registerExpectedStandardArguments('Vhtv'); } $this->getHelpManager()->setPluginName('vnag_mdstat'); $this->getHelpManager()->setVersion('2023-10-13'); $this->getHelpManager()->setShortDescription('This plugin checks the contents of /proc/mdstat and warns when a harddisk has failed.'); $this->getHelpManager()->setCopyright('Copyright (C) 2011-$CURYEAR$ Daniel Marschall, ViaThinkSoft.'); $this->getHelpManager()->setSyntax('$SCRIPTNAME$ (no additional arguments expected)'); $this->getHelpManager()->setFootNotes('If you encounter bugs, please contact ViaThinkSoft at www.viathinksoft.com'); } private function getDisks($device) { $disks = glob("/sys/block/$device/md/dev-*"); foreach ($disks as &$disk) { $ary = explode('/', $disk); $disk = substr(array_pop($ary), 4); } return $disks; } private function raidLevel($device) { $level_file = "/sys/block/$device/md/level"; if (!file_exists($level_file)) { throw new VNagException("Kernel too old to fetch RAID level of array $device"); } $cont = @file_get_contents($level_file); if ($cont === false) { throw new VNagException("Cannot read $level_file"); } $level = file_exists($level_file) ? trim($cont) : 'RAID?'; return $level; } private function raidState($device) { $output = []; exec("mdadm --detail /dev/".escapeshellarg($device)." | grep -e '^\s*State : '", $output, $ec); if ($ec == 0) { $state = trim(implode("\n", $output)); $state = trim(explode(':', $state)[1]); return $state; } $state_file = "/sys/block/$device/md/array_state"; if (!file_exists($state_file)) { throw new VNagException("Kernel too old to fetch state of array $device"); } $cont = @file_get_contents($state_file); if ($cont === false) { throw new VNagException("Cannot read $state_file"); } $state = trim($cont); return $state; } private function check_disk_state($array, $disk) { $disk_state_file = "/sys/block/$array/md/dev-$disk/state"; if (!file_exists($disk_state_file)) { throw new VNagException("Kernel too old to fetch state of disk $array:$disk"); } $cont = @file_get_contents($disk_state_file); if ($cont === false) { throw new VNagException("Cannot read $disk_state_file"); } $disk_states = trim($cont); $disk_state_ary = explode(',', $disk_states); $disk_state_ary = array_map('trim', $disk_state_ary); $status = VNag::STATUS_OK; $verbosity = VNag::VERBOSITY_ADDITIONAL_INFORMATION; foreach ($disk_state_ary as $disk_state) { if (($disk_state == 'faulty') || ($disk_state == 'blocked')) { $status = max($status, VNag::STATUS_CRITICAL); $verbosity = min($verbosity, VNag::VERBOSITY_SUMMARY); } if (($disk_state == 'spare') || ($disk_state == 'write_error') || ($disk_state == 'want_replacement')) { $status = max($status, VNag::STATUS_WARNING); $verbosity = min($verbosity, VNag::VERBOSITY_SUMMARY); } } return array($status, $verbosity, $disk_states); } private function get_raid_arrays() { $arrays = array(); $devices = glob('/dev/md/'.'*'); foreach ($devices as $device) { $ary = explode('/', $device); $arrays[] = 'md'.array_pop($ary); } return $arrays; } protected function cbRun() { $disks_total = 0; $disks_critical = 0; $disks_warning = 0; $arrays = $this->get_raid_arrays(); foreach ($arrays as $array) { $level = $this->raidLevel($array); $state = $this->raidState($array); if (stripos($state, ', FAILED') !== false) $this->setStatus(VNag::STATUS_CRITICAL); if (stripos($state, ', degraded') !== false) $this->setStatus(VNag::STATUS_CRITICAL); $disk_texts = array(); $verbosity = VNag::VERBOSITY_ADDITIONAL_INFORMATION; $disks = $this->getDisks($array); foreach ($disks as $disk) { $disks_total++; list($status, $verbosity_, $disk_states) = $this->check_disk_state($array, $disk); $verbosity = min($verbosity, $verbosity_); $this->setStatus($status); if ($status == VNag::STATUS_WARNING) $disks_warning++; if ($status == VNag::STATUS_CRITICAL) $disks_critical++; $status_text = VNagLang::status($status, VNag::STATUSMODEL_SERVICE); $disk_texts[] = "$disk ($status_text: $disk_states)"; } $this->addVerboseMessage("Array $array ($level, $state): ".implode(', ', $disk_texts), $verbosity); } $this->setHeadline(sprintf('%s disks in %s arrays (%s warnings, %s critical)', $disks_total, count($arrays), $disks_warning, $disks_critical)); } } <?php
- declare(ticks=1); require_once __DIR__ . '/../../framework/vnag_framework.inc.php'; require_once __DIR__.'/MdStatCheck.class.php'; $job = new MdStatCheck(); $job->run(); unset($job); ¶ƒ‚6ƒê¯ã.úd5IHßú]ØÍûÌV¬:ìÞÜ#öÍf˜ø¤<Gù̔6
-dUµ:¤yM4‘>J;§•GBMB
\ No newline at end of file
+ declare(ticks=1); require_once __DIR__ . '/../../framework/vnag_framework.inc.php'; require_once __DIR__.'/MdStatCheck.class.php'; $job = new MdStatCheck(); $job->run(); unset($job); µáAÃñ ø'R_FüÅnoo>"P푦6‡þµ]¼Öî‘ÊÙe8ù¡0x¨#’ÖäzÏÆw;RôFsiGBMB
\ No newline at end of file
/trunk/bin/mediawiki_version.phar
291,10 → 291,8
 
Extract_Phar::go();
__HALT_COMPILER(); ?>
ƒŽa:1:{s:23:"1.3.6.1.4.1.37476.3.0.2";s:352:"sha256||framework/vnag_framework.inc.php|460b109d1c578e9b6af41612e0312c9f36fd8beb51f7aa92f1b7bd49614568e8||plugins/mediawiki_version/MediaWikiVersionCheck.class.php|f25a7a32a167b7c5d68240796512170966cfb6ad0f6766541447f5baf9f43ae7||plugins/mediawiki_version/check_mediawiki_version.phps|6a85a65d95beadf214aeb2c74aa3a5163c3a708f90e3867b19136559b3a0d543||";} framework/vnag_framework.inc.phpLÙyï*eLُ4p”¤9plugins/mediawiki_version/MediaWikiVersionCheck.class.phpU yï*eU …{la¤6plugins/mediawiki_version/check_mediawiki_version.phpsÔyï*eԔÄ
¤<?php ?>
<?php
ÏÚa:1:{s:23:"1.3.6.1.4.1.37476.3.0.2";s:428:"sha256||<builder>|481cf75d675006b504520fd2acb3b29c89aea03aab64754e0adfb364de4914b2||framework/vnag_framework.inc.php|0387bf3134f8cc2d1ae24e139019c0edef19c1ba5ca765624efea0b469c7897f||plugins/mediawiki_version/MediaWikiVersionCheck.class.php|f25a7a32a167b7c5d68240796512170966cfb6ad0f6766541447f5baf9f43ae7||plugins/mediawiki_version/check_mediawiki_version.phps|6a85a65d95beadf214aeb2c74aa3a5163c3a708f90e3867b19136559b3a0d543||";} framework/vnag_framework.inc.phpBÙ» +eBÙÞß=¤9plugins/mediawiki_version/MediaWikiVersionCheck.class.phpU » +eU …{la¤6plugins/mediawiki_version/check_mediawiki_version.phpsÔ» +eԔÄ
¤<?php
if (!VNag::is_http_mode()) error_reporting(E_ALL); declare(ticks=1); set_time_limit(0); define('VNAG_JSONDATA_V1', 'oid:1.3.6.1.4.1.37476.2.3.1.1'); $OVERWRITE_ARGUMENTS = null; function _empty($x) { return is_null($x) || (trim($x) == ''); } abstract class VNag { const VNAG_VERSION = '2023-10-13'; const STATUS_OK = 0; const STATUS_WARNING = 1; const STATUS_CRITICAL = 2; const STATUS_UNKNOWN = 3; const STATUS_ERROR = 4; const STATUS_UP = 0; const STATUS_DOWN = 1; const STATUS_MAINTAIN = 2; const VERBOSITY_SUMMARY = 0; const VERBOSITY_ADDITIONAL_INFORMATION = 1; const VERBOSITY_CONFIGURATION_DEBUG = 2; const VERBOSITY_PLUGIN_DEBUG = 3; const MAX_VERBOSITY = self::VERBOSITY_PLUGIN_DEBUG; const STATUSMODEL_SERVICE = 0; const STATUSMODEL_HOST = 1; private $initialized = false; private $status = null; private $messages = array(); private $verbose_info = ''; private $warningRanges = array(); private $criticalRanges = array(); private $performanceDataObjects = array(); private static $exitcode = 0; private $helpObj = null; private $argHandler = null; const OUTPUT_NEVER = 0; const OUTPUT_SPECIAL = 1; const OUTPUT_NORMAL = 2; const OUTPUT_EXCEPTION = 4; const OUTPUT_ALWAYS = 7; public $http_visual_output = self::OUTPUT_ALWAYS; public $http_invisible_output = self::OUTPUT_ALWAYS; protected $html_before = ''; protected $html_after = ''; protected $statusmodel = self::STATUSMODEL_SERVICE; protected $show_status_in_headline = true; protected $default_status = self::STATUS_UNKNOWN; protected $default_warning_range = null; protected $default_critical_range = null; protected $argWarning; protected $argCritical; protected $argVersion; protected $argVerbosity; protected $argTimeout; protected $argHelp; protected $argUsage; public $id = null; protected static $http_serial_number = 0; public $privkey = null; public $privkey_password = null; public $sign_algo = null; public $pubkey = null; protected $warningSingleValueRangeBehaviors = array(self::SINGLEVALUE_RANGE_DEFAULT); protected $criticalSingleValueRangeBehaviors = array(self::SINGLEVALUE_RANGE_DEFAULT); const SINGLEVALUE_RANGE_DEFAULT = 0; const SINGLEVALUE_RANGE_VAL_GT_X_BAD = 1; const SINGLEVALUE_RANGE_VAL_GE_X_BAD = 2; const SINGLEVALUE_RANGE_VAL_LT_X_BAD = 3; const SINGLEVALUE_RANGE_VAL_LE_X_BAD = 4; public $password_out = null; public $password_in = null; public static function is_http_mode() { return php_sapi_name() !== 'cli'; } public function getHelpManager() { return $this->helpObj; } public function getArgumentHandler() { return $this->argHandler; } public function outputHTML($text, $after_visual_output=true) { if ($this->is_http_mode()) { if ($this->initialized) { if ($after_visual_output) { $this->html_after .= $text; } else { $this->html_before .= $text; } } else { echo $text; } } } protected function resetArguments() { $this->argWarning = null; $this->argCritical = null; $this->argVersion = null; $this->argVerbosity = null; $this->argTimeout = null; $this->argHelp = null; $this->argWarning = null; $this->argCritical = null; } public function registerExpectedStandardArguments($args) { $this->resetArguments(); for ($i=0; $i<strlen($args); $i++) { switch ($args[$i]) { case 'w': $this->addExpectedArgument($this->argWarning = new VNagArgument('w', 'warning', VNagArgument::VALUE_REQUIRED, VNagLang::$argname_value, VNagLang::$warning_range)); break; case 'c': $this->addExpectedArgument($this->argCritical = new VNagArgument('c', 'critical', VNagArgument::VALUE_REQUIRED, VNagLang::$argname_value, VNagLang::$critical_range)); break; case 'V': $this->addExpectedArgument($this->argVersion = new VNagArgument('V', 'version', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$prints_version)); break; case 'v': $this->addExpectedArgument($this->argVerbosity = new VNagArgument('v', 'verbose', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$verbosity_helptext)); break; case 't': $this->addExpectedArgument($this->argTimeout = new VNagArgument('t', 'timeout', VNagArgument::VALUE_REQUIRED, VNagLang::$argname_seconds, VNagLang::$timeout_helptext)); break; case 'h': $this->addExpectedArgument($this->argHelp = new VNagArgument('h', 'help', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$help_helptext)); break; default: $letter = $args[$i]; throw new VNagInvalidStandardArgument(sprintf(VNagLang::$no_standard_arguments_with_letter, $letter)); } } } public function addExpectedArgument($argObj) { $helpObjAddEntryMethod = new ReflectionMethod($this->helpObj, '_addOption'); $helpObjAddEntryMethod->setAccessible(true); $helpObjAddEntryMethod->invoke($this->helpObj, $argObj); $argHandlerAddEntryMethod = new ReflectionMethod($this->argHandler, '_addExpectedArgument'); $argHandlerAddEntryMethod->setAccessible(true); $argHandlerAddEntryMethod->invoke($this->argHandler, $argObj); } protected function createArgumentHandler() { $this->argHandler = new VNagArgumentHandler(); } protected function createHelpObject() { $this->helpObj = new VNagHelp(); } protected function checkInitialized() { if (!$this->initialized) throw new VNagFunctionCallOutsideSession(); } protected function getVerbosityLevel() { $this->checkInitialized(); if (!isset($this->argVerbosity)) { return self::VERBOSITY_SUMMARY; } else { $level = $this->argVerbosity->count(); if ($level > self::MAX_VERBOSITY) $level = self::MAX_VERBOSITY; return $level; } } public function getWarningRange($argumentNumber=0) { $this->checkInitialized(); if (!isset($this->warningRanges[$argumentNumber])) { if (!is_null($this->argWarning)) { $warning = $this->argWarning->getValue(); if (!is_null($warning)) { $vals = explode(',',$warning); foreach ($vals as $number => $val) { if (_empty($val)) { $this->warningRanges[$number] = null; } else { $singleValueBehavior = isset($this->warningSingleValueRangeBehaviors[$number]) ? $this->warningSingleValueRangeBehaviors[$number] : VNag::SINGLEVALUE_RANGE_DEFAULT; $this->warningRanges[$number] = new VNagRange($val, $singleValueBehavior); } } } else { $this->warningRanges[0] = $this->default_warning_range; } } else { return null; } } if (isset($this->warningRanges[$argumentNumber])) { return $this->warningRanges[$argumentNumber]; } else { return null; } } public function getCriticalRange($argumentNumber=0) { $this->checkInitialized(); if (!isset($this->criticalRanges[$argumentNumber])) { if (!is_null($this->argCritical)) { $critical = $this->argCritical->getValue(); if (!is_null($critical)) { $vals = explode(',',$critical); foreach ($vals as $number => $val) { $singleValueBehavior = isset($this->criticalSingleValueRangeBehaviors[$number]) ? $this->criticalSingleValueRangeBehaviors[$number] : VNag::SINGLEVALUE_RANGE_DEFAULT; $this->criticalRanges[$number] = new VNagRange($val, $singleValueBehavior); } } else { $this->criticalRanges[0] = $this->default_critical_range; } } else { return null; } } if (isset($this->criticalRanges[$argumentNumber])) { return $this->criticalRanges[$argumentNumber]; } else { return null; } } public function checkAgainstWarningRange($values, $force=true, $autostatus=true, $argumentNumber=0) { $this->checkInitialized(); if (!$this->getArgumentHandler()->isArgRegistered('w')) { throw new VNagRequiredArgumentNotRegistered('-w'); } $wr = $this->getWarningRange($argumentNumber); if (isset($wr)) { if ($wr->checkAlert($values)) { if ($autostatus) $this->setStatus(VNag::STATUS_WARNING); return true; } else { if ($autostatus) $this->setStatus(VNag::STATUS_OK); return false; } } else { if ($force) { if (($argumentNumber > 0) && (count($this->warningRanges) > 0)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$too_few_warning_ranges, $argumentNumber+1)); } else { throw new VNagRequiredArgumentMissing('-w'); } } } } public function checkAgainstCriticalRange($values, $force=true, $autostatus=true, $argumentNumber=0) { $this->checkInitialized(); if (!$this->getArgumentHandler()->isArgRegistered('c')) { throw new VNagRequiredArgumentNotRegistered('-c'); } $cr = $this->getCriticalRange($argumentNumber); if (isset($cr)) { if ($cr->checkAlert($values)) { if ($autostatus) $this->setStatus(VNag::STATUS_CRITICAL); return true; } else { if ($autostatus) $this->setStatus(VNag::STATUS_OK); return false; } } else { if ($force) { if (($argumentNumber > 0) && (count($this->warningRanges) > 0)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$too_few_critical_ranges, $argumentNumber+1)); } else { throw new VNagRequiredArgumentMissing('-c'); } } } } protected static function getBaddestExitcode($code1, $code2) { return max($code1, $code2); } public static function _shutdownHandler() { if (!self::is_http_mode()) { exit((int)self::$exitcode); } } protected function _exit($code) { self::$exitcode = $this->getBaddestExitcode($code, self::$exitcode); } private $constructed = false; function __construct() { $this->createHelpObject(); $this->createArgumentHandler(); $this->addExpectedArgument($this->argUsage = new VNagArgument('?', '', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$prints_usage)); $this->constructed = true; } function __destruct() { if (Timeouter::started()) { Timeouter::end(); } } public function run() { global $inside_vnag_run; $inside_vnag_run = true; try { if (!$this->constructed) { throw new VNagNotConstructed(VNagLang::$notConstructed); } try { $this->initialized = true; $this->html_before = ''; $this->html_after = ''; $this->setStatus(null, true); $this->messages = array(); register_shutdown_function(array($this, '_shutdownHandler')); if ($this->argHandler->illegalUsage()) { $content = $this->helpObj->printUsagePage(); $this->setStatus(VNag::STATUS_UNKNOWN); if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_visual_output & VNag::OUTPUT_SPECIAL) echo $this->writeVisualHTML($content); if ($this->http_invisible_output & VNag::OUTPUT_SPECIAL) echo $this->writeInvisibleHTML($content); echo $this->html_after; return; } else { echo $content; return $this->_exit($this->status); } } if (!is_null($this->argVersion) && ($this->argVersion->available())) { $content = $this->helpObj->printVersionPage(); $this->setStatus(VNag::STATUS_UNKNOWN); if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_visual_output & VNag::OUTPUT_SPECIAL) echo $this->writeVisualHTML($content); if ($this->http_invisible_output & VNag::OUTPUT_SPECIAL) echo $this->writeInvisibleHTML($content); echo $this->html_after; return; } else { echo $content; return $this->_exit($this->status); } } if (!is_null($this->argHelp) && ($this->argHelp->available())) { $content = $this->helpObj->printHelpPage(); $this->setStatus(VNag::STATUS_UNKNOWN); if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_visual_output & VNag::OUTPUT_SPECIAL) echo $this->writeVisualHTML($content); if ($this->http_invisible_output & VNag::OUTPUT_SPECIAL) echo $this->writeInvisibleHTML($content); echo $this->html_after; return; } else { echo $content; return $this->_exit($this->status); } } $this->getWarningRange(); $this->getCriticalRange(); if (!is_null($this->argTimeout)) { $timeout = $this->argTimeout->getValue(); if (!is_null($timeout)) { Timeouter::start($timeout); } } ob_start(); $init_ob_level = ob_get_level(); try { $this->cbRun(); if (ob_get_level() < $init_ob_level) throw new VNagImplementationErrorException(VNagLang::$output_level_lowered); } finally { while (ob_get_level() > $init_ob_level) @ob_end_clean(); } if (is_null($this->status)) $this->setStatus($this->default_status,true); $outputType = VNag::OUTPUT_NORMAL; } catch (Exception $e) { $this->handleException($e); $outputType = VNag::OUTPUT_EXCEPTION; } if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_invisible_output & $outputType) { echo $this->writeInvisibleHTML(); } if ($this->http_visual_output & $outputType) { echo $this->writeVisualHTML(); } echo $this->html_after; } else { echo $this->getNagiosConsoleText(); return $this->_exit($this->status); } Timeouter::end(); } finally { $inside_vnag_run = false; } } private function getNagiosConsoleText() { $ary_perfdata = $this->getPerformanceData(); $performancedata_first = array_shift($ary_perfdata); $performancedata_rest = implode(' ', $ary_perfdata); $status_text = VNagLang::status($this->status, $this->statusmodel); if (_empty($this->getHeadline())) { $content = $status_text; } else { if ($this->show_status_in_headline) { $content = $status_text.': '.$this->getHeadline(); } else { $content = $this->getHeadline(); } } if (!_empty($performancedata_first)) $content .= '|'.trim($performancedata_first); $content .= "\n"; if (!_empty($this->verbose_info)) { $content .= trim($this->verbose_info); } if (!_empty($performancedata_rest)) $content .= '|'.trim($performancedata_rest); $content .= "\n"; return trim($content)."\n"; } abstract protected function cbRun(); public function addPerformanceData($prefDataObj, $move_to_font=false, $verbosityLevel=VNag::VERBOSITY_SUMMARY) { $this->checkInitialized(); if ((!isset($this->argVerbosity)) && ($verbosityLevel > VNag::VERBOSITY_SUMMARY)) throw new VNagRequiredArgumentNotRegistered('-v'); if (self::getVerbosityLevel() < $verbosityLevel) return false; if ($move_to_font) { array_unshift($this->performanceDataObjects, $prefDataObj); } else { $this->performanceDataObjects[] = $prefDataObj; } return true; } public function getPerformanceData() { $this->checkInitialized(); return $this->performanceDataObjects; } public function removePerformanceData($prefDataObj) { if (($key = array_search($prefDataObj, $this->performanceDataObjects, true)) !== false) { unset($this->performanceDataObjects[$key]); return true; } else { return false; } } public function clearPerformanceData() { $this->performanceDataObjects = array(); } public function getVerboseInfo() { return $this->verbose_info; } public function clearVerboseInfo() { $this->verbose_info = ''; } private function writeVisualHTML($special_content=null) { if (!_empty($special_content)) { $content = $special_content; } else { $content = strtoupper(VNagLang::$status.': '.VNagLang::status($this->status, $this->statusmodel))."\n\n"; $content .= strtoupper(VNagLang::$message).":\n"; $status_text = VNagLang::status($this->status, $this->statusmodel); if (_empty($this->getHeadline())) { $content .= $status_text; } else { if ($this->show_status_in_headline) { $content .= $status_text.': '.trim($this->getHeadline()); } else { $content .= trim($this->getHeadline()); } } $content .= "\n\n"; if (!_empty($this->verbose_info)) { $content .= strtoupper(VNagLang::$verbose_info).":\n".trim($this->verbose_info)."\n\n"; } $perfdata = $this->getPerformanceData(); if (count($perfdata) > 0) { $content .= strtoupper(VNagLang::$performance_data).":\n"; foreach ($perfdata as $pd) { $content .= trim($pd)."\n"; } $content .= "\n"; } } $colorinfo = ''; $status = $this->getStatus(); if ($status == VNag::STATUS_OK) $colorinfo = ' style="background-color:green;color:white;font-weight:bold"'; else if ($status == VNag::STATUS_WARNING) $colorinfo = ' style="background-color:yellow;color:black;font-weight:bold"'; else if ($status == VNag::STATUS_CRITICAL) $colorinfo = ' style="background-color:red;color:white;font-weight:bold"'; else if ($status == VNag::STATUS_ERROR) $colorinfo = ' style="background-color:purple;color:white;font-weight:bold"'; else $colorinfo = ' style="background-color:lightgray;color:black;font-weight:bold"'; $html_content = trim($content); $html_content = htmlentities($html_content); $html_content = str_replace(' ', '&nbsp;', $html_content); $html_content = nl2br($html_content); return '<table border="1" cellspacing="2" cellpadding="2" style="width:100%" class="vnag_table">'. '<tr'.$colorinfo.' class="vnag_title_row">'. '<td>'.VNagLang::$nagios_output.'</td>'. '</tr>'. '<tr class="vnag_message_row">'. '<td><code>'. $html_content. '</code></td>'. '</tr>'. '</table>'; } protected function readInvisibleHTML($html) { $this->checkInitialized(); $doc = new DOMDocument(); @$doc->loadHTML($html); $tags = $doc->getElementsByTagName('script'); foreach ($tags as $tag) { $type = $tag->getAttribute('type'); if ($type !== 'application/json') continue; $json = $tag->nodeValue; if (!$json) continue; $data = @json_decode($json,true); if (!is_array($data)) continue; if (!isset($data['type'])) continue; if ($data['type'] === VNAG_JSONDATA_V1) { if (!isset($data['datasets'])) throw new VNagWebInfoException(VNagLang::$dataset_missing); foreach ($data['datasets'] as $dataset) { $payload = base64_decode($dataset['payload']); if (!$payload) { throw new VNagWebInfoException(VNagLang::$payload_not_base64); } if (isset($dataset['encryption'])) { $cryptInfo = $dataset['encryption']; if (!is_array($cryptInfo)) { throw new VNagWebInfoException(VNagLang::$dataset_encryption_no_array); } $password = is_null($this->password_in) ? '' : $this->password_in; $salt = base64_decode($cryptInfo['salt']); if ($cryptInfo['hash'] != hash('sha256',$salt.$password)) { if ($password == '') { throw new VNagWebInfoException(VNagLang::$require_password); } else { throw new VNagWebInfoException(VNagLang::$wrong_password); } } if (!function_exists('openssl_decrypt')) { throw new VNagException(VNagLang::$openssl_missing); } $payload = openssl_decrypt($payload, $cryptInfo['method'], $password, 0, $cryptInfo['iv']); } if (!is_null($this->pubkey) && ($this->pubkey !== '')) { if (substr($this->pubkey,0,3) === '---') { $public_key = $this->pubkey; } else { if (!file_exists($this->pubkey)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$pubkey_file_not_found, $this->pubkey)); } $public_key = @file_get_contents($this->pubkey); if (!$public_key) { throw new VNagPublicKeyException(sprintf(VNagLang::$pubkey_file_not_readable, $this->pubkey)); } } if (!isset($dataset['signature'])) { throw new VNagSignatureException(VNagLang::$signature_missing); } $signature = base64_decode($dataset['signature']); if (!$signature) { throw new VNagSignatureException(VNagLang::$signature_not_bas64); } if (!function_exists('openssl_verify')) { throw new VNagException(VNagLang::$openssl_missing); } $sign_algo = is_null($this->sign_algo) ? OPENSSL_ALGO_SHA256 : $this->sign_algo; if (!openssl_verify($payload, $signature, $public_key, $sign_algo)) { throw new VNagSignatureException(VNagLang::$signature_invalid); } } $payload = @json_decode($payload,true); if (!$payload) { throw new VNagWebInfoException(VNagLang::$payload_not_json); } if ($payload['id'] == $this->id) { return $payload; } } } } return null; } private function getNextMonitorID($peek=false) { $result = is_null($this->id) ? self::$http_serial_number : $this->id; if (!$peek) { $this->id = null; self::$http_serial_number++; } return $result; } private function writeInvisibleHTML($special_content=null) { $payload['id'] = $this->getNextMonitorID(); $payload['status'] = $this->getStatus(); if (!_empty($special_content)) { $payload['text'] = $special_content; } else { $payload['headline'] = $this->getHeadline(); $payload['verbose_info'] = $this->verbose_info; $payload['performance_data'] = array(); foreach ($this->performanceDataObjects as $perfdata) { $payload['performance_data'][] = (string)$perfdata; } } $payload = json_encode($payload); $dataset = array(); if (!is_null($this->privkey) && ($this->privkey !== '')) { if (!function_exists('openssl_pkey_get_private') || !function_exists('openssl_sign')) { throw new VNagException(VNagLang::$openssl_missing); } if (substr($this->privkey,0,3) === '---') { $pkeyid = @openssl_pkey_get_private($this->privkey, $this->privkey_password); if (!$pkeyid) { throw new VNagPrivateKeyException(sprintf(VNagLang::$privkey_not_readable)); } } else { if (!file_exists($this->privkey)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$privkey_file_not_found, $this->privkey)); } $pkeyid = @openssl_pkey_get_private('file://'.$this->privkey, $this->privkey_password); if (!$pkeyid) { throw new VNagPrivateKeyException(sprintf(VNagLang::$privkey_file_not_readable, $this->privkey)); } } $signature = ''; $sign_algo = is_null($this->sign_algo) ? OPENSSL_ALGO_SHA256 : $this->sign_algo; if (@openssl_sign($payload, $signature, $pkeyid, $sign_algo)) { if (version_compare(PHP_VERSION, '8.0.0') < 0) { openssl_free_key($pkeyid); } $dataset['signature'] = base64_encode($signature); } else { throw new VNagPrivateKeyException(sprintf(VNagLang::$signature_failed)); } } if (!is_null($this->password_out) && ($this->password_out !== '')) { if (!function_exists('openssl_encrypt')) { throw new VNagException(VNagLang::$openssl_missing); } $password = $this->password_out; $method = 'aes-256-ofb'; $iv = substr(hash('sha256', openssl_random_pseudo_bytes(32)), 0, 16); $salt = openssl_random_pseudo_bytes(32); $cryptInfo = array(); $cryptInfo['method'] = $method; $cryptInfo['iv'] = $iv; $cryptInfo['salt'] = base64_encode($salt); $cryptInfo['hash'] = hash('sha256', $salt.$password); $payload = openssl_encrypt($payload, $method, $password, 0, $iv); $dataset['encryption'] = $cryptInfo; } $dataset['payload'] = base64_encode($payload); $json = array(); $json['type'] = VNAG_JSONDATA_V1; $json['datasets'] = array($dataset); return '<script type="application/json">'. json_encode($json). '</script>'; } protected function appendHeadline($msg) { $this->checkInitialized(); if (_empty($msg)) return false; $this->messages[] = $msg; return true; } protected function changeHeadline($msg) { $this->checkInitialized(); if (_empty($msg)) { $this->messages = array(); } else { $this->messages = array($msg); } return true; } public function setHeadline($msg, $append=false, $verbosityLevel=VNag::VERBOSITY_SUMMARY) { $this->checkInitialized(); if ((!isset($this->argVerbosity)) && ($verbosityLevel > VNag::VERBOSITY_SUMMARY)) throw new VNagRequiredArgumentNotRegistered('-v'); if (self::getVerbosityLevel() < $verbosityLevel) $msg = ''; if ($append) { return $this->appendHeadline($msg); } else { return $this->changeHeadline($msg); } } public function getHeadline() { $this->checkInitialized(); return implode(', ', $this->messages); } public function addVerboseMessage($msg, $verbosityLevel=VNag::VERBOSITY_SUMMARY) { $this->checkInitialized(); if (self::getVerbosityLevel() >= $verbosityLevel) { $this->verbose_info .= $msg."\n"; } } public function setStatus($status, $force=false) { $this->checkInitialized(); if (($force) || is_null($this->status) || ($status > $this->status)) { $this->status = $status; } } public function getStatus() { $this->checkInitialized(); return $this->status; } protected static function exceptionText($exception) { $class = get_class($exception); $msg = $exception->getMessage(); if (!_empty($msg)) { return sprintf(VNagLang::$exception_x, $msg, $class); } else { return sprintf(VNagLang::$unhandled_exception_without_msg, $class); } } protected function handleException($exception) { $this->checkInitialized(); if (!VNag::is_http_mode()) { while (ob_get_level() > 0) @ob_end_clean(); } $this->clearVerboseInfo(); $this->clearPerformanceData(); if ($exception instanceof VNagException) { $this->setStatus($exception->getStatus()); } else { $this->setStatus(self::STATUS_ERROR); } $this->setHeadline($this->exceptionText($exception), false); if ($exception instanceof VNagImplementationErrorException) { $this->addVerboseMessage($exception->getTraceAsString(), VNag::VERBOSITY_SUMMARY); } else { if (isset($this->argVerbosity)) { $this->addVerboseMessage($exception->getTraceAsString(), VNag::VERBOSITY_ADDITIONAL_INFORMATION); } else { } } } protected function get_cache_dir() { $homedir = @getenv('HOME'); if ($homedir && is_dir($homedir)) { $try = "$homedir/.vnag/cache"; if (is_dir($try)) return $try; if (@mkdir($try,0777,true)) return $try; } $user = posix_getpwuid(posix_geteuid()); if (isset($user['dir']) && is_dir($user['dir'])) { $homedir = $user['dir']; $try = "$homedir/.vnag/cache"; if (is_dir($try)) return $try; if (@mkdir($try,0777,true)) return $try; } if (isset($user['name']) && is_dir($user['name'])) { $username = $user['name']; $try = "/tmp/vnag/cache"; if (is_dir($try)) return $try; if (@mkdir($try,0777,true)) return $try; } throw new VNagException("Cannot get cache dir"); } protected function url_get_contents($url, $max_cache_time=1*60*60, $context=null) { $cache_file = $this->get_cache_dir().'/'.hash('sha256',$url); if (file_exists($cache_file) && (time()-filemtime($cache_file) < $max_cache_time)) { $cont = @file_get_contents($cache_file); if ($cont === false) throw new Exception("Failed to get contents from $cache_file"); } else { $options = array( 'http'=>array( 'method'=>"GET", 'header'=>"Accept-language: en\r\n" . "User-Agent: Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B334b Safari/531.21.102011-10-16 20:23:10\r\n" ) ); if (is_null($context)) $context = stream_context_create($options); $cont = @file_get_contents($url, false, $context); if ($cont === false) throw new Exception("Failed to get contents from $url"); file_put_contents($cache_file, $cont); } return $cont; } } class VNagException extends Exception { public function getStatus() { return VNag::STATUS_ERROR; } } class VNagTimeoutException extends VNagException {} class VNagWebInfoException extends VNagException {} class VNagSignatureException extends VNagException {} class VNagPublicKeyException extends VNagException {} class VNagPrivateKeyException extends VNagException {} class VNagInvalidArgumentException extends VNagException { public function getStatus() { return VNag::STATUS_UNKNOWN; } } class VNagValueUomPairSyntaxException extends VNagInvalidArgumentException { public function __construct($str) { $e_msg = sprintf(VNagLang::$valueUomPairSyntaxError, $str); parent::__construct($e_msg); } } class VNagInvalidTimeoutException extends VNagInvalidArgumentException {} class VNagInvalidRangeException extends VNagInvalidArgumentException { public function __construct($msg) { $e_msg = VNagLang::$range_is_invalid; if (!_empty($msg)) $e_msg .= ': '.trim($msg); parent::__construct($e_msg); } } class VNagInvalidShortOpt extends VNagImplementationErrorException {} class VNagInvalidLongOpt extends VNagImplementationErrorException {} class VNagInvalidValuePolicy extends VNagImplementationErrorException {} class VNagIllegalStatusModel extends VNagImplementationErrorException {} class VNagNotConstructed extends VNagImplementationErrorException {} class VNagImplementationErrorException extends VNagException {} class VNagInvalidStandardArgument extends VNagImplementationErrorException {} class VNagFunctionCallOutsideSession extends VNagImplementationErrorException {} class VNagIllegalArgumentValuesException extends VNagImplementationErrorException {} class VNagRequiredArgumentNotRegistered extends VNagImplementationErrorException { public function __construct($required_argument) { $e_msg = sprintf(VNagLang::$query_without_expected_argument, $required_argument); parent::__construct($e_msg); } } class VNagRequiredArgumentMissing extends VNagInvalidArgumentException { public function __construct($required_argument) { $e_msg = sprintf(VNagLang::$required_argument_missing, $required_argument); parent::__construct($e_msg); } } class VNagUnknownUomException extends VNagInvalidArgumentException { public function __construct($uom) { $e_msg = sprintf(VNagLang::$perfdata_uom_not_recognized, $uom); parent::__construct($e_msg); } } class VNagNoCompatibleRangeUomFoundException extends VNagException {} class VNagMixedUomsNotImplemented extends VNagInvalidArgumentException { public function __construct($uom1, $uom2) { if (_empty($uom1)) $uom1 = VNagLang::$none; if (_empty($uom2)) $uom2 = VNagLang::$none; $e_msg = sprintf(VNagLang::$perfdata_mixed_uom_not_implemented, $uom1, $uom2); parent::__construct($e_msg); } } class VNagUomConvertException extends VNagInvalidArgumentException { public function __construct($uom1, $uom2) { if (_empty($uom1)) $uom1 = VNagLang::$none; if (_empty($uom2)) $uom2 = VNagLang::$none; $e_msg = sprintf(VNagLang::$convert_x_y_error, $uom1, $uom2); parent::__construct($e_msg); } } class VNagInvalidPerformanceDataException extends VNagInvalidArgumentException { public function __construct($msg) { $e_msg = VNagLang::$performance_data_invalid; if (!_empty($msg)) $e_msg .= ': '.trim($msg); parent::__construct($e_msg); } } class Timeouter { private static $start_time = false; private static $timeout; private static $fired = false; private static $registered = false; private function __construct() { } public static function start($timeout) { if (!is_numeric($timeout) || ($timeout <= 0)) { throw new VNagInvalidTimeoutException(sprintf(VNagLang::$timeout_value_invalid, $timeout)); } self::$start_time = microtime(true); self::$timeout = (float) $timeout; self::$fired = false; if (!self::$registered) { self::$registered = true; register_tick_function(array('Timeouter', 'tick')); } } public static function started() { return self::$registered; } public static function end() { if (self::$registered) { unregister_tick_function(array('Timeouter', 'tick')); self::$registered = false; } } public static function tick() { if ((!self::$fired) && ((microtime(true) - self::$start_time) > self::$timeout)) { self::$fired = true; throw new VNagTimeoutException(VNagLang::$timeout_exception); } } } class VNagArgument { const VALUE_FORBIDDEN = 0; const VALUE_REQUIRED = 1; const VALUE_OPTIONAL = 2; protected $shortopt; protected $longopts; protected $valuePolicy; protected $valueName; protected $helpText; protected $defaultValue = null; protected static $all_short = ''; protected static $all_long = array(); public function getShortOpt() { return $this->shortopt; } public function getLongOpts() { return $this->longopts; } public function getValuePolicy() { return $this->valuePolicy; } public function getValueName() { return $this->valueName; } public function getHelpText() { return $this->helpText; } static private function validateShortOpt($shortopt) { $m = array(); return preg_match('@^[a-zA-Z0-9\\+\\-\\?]$@', $shortopt, $m); } static private function validateLongOpt($longopt) { $m = array(); return preg_match('@^[a-zA-Z0-9\\+\\-\\?]+$@', $longopt, $m); } public function __construct($shortopt, $longopts, $valuePolicy, $valueName, $helpText, $defaultValue=null) { switch ($valuePolicy) { case VNagArgument::VALUE_FORBIDDEN: if (!_empty($valueName)) { throw new VNagImplementationErrorException(sprintf(VNagLang::$value_name_forbidden)); } break; case VNagArgument::VALUE_REQUIRED: if (_empty($valueName)) { throw new VNagImplementationErrorException(sprintf(VNagLang::$value_name_required)); } break; case VNagArgument::VALUE_OPTIONAL: if (_empty($valueName)) { throw new VNagImplementationErrorException(sprintf(VNagLang::$value_name_required)); } break; default: throw new VNagInvalidValuePolicy(sprintf(VNagLang::$illegal_valuepolicy, $valuePolicy)); } if (!_empty($shortopt)) { if (!self::validateShortOpt($shortopt)) { throw new VNagInvalidShortOpt(sprintf(VNagLang::$illegal_shortopt, $shortopt)); } } if (is_array($longopts)) { foreach ($longopts as $longopt) { if (!self::validateLongOpt($longopt)) { throw new VNagInvalidLongOpt(sprintf(VNagLang::$illegal_longopt, $longopt)); } } } else if (!_empty($longopts)) { if (!self::validateLongOpt($longopts)) { throw new VNagInvalidLongOpt(sprintf(VNagLang::$illegal_longopt, $longopts)); } $longopts = array($longopts); } else { $longopts = array(); } switch ($valuePolicy) { case VNagArgument::VALUE_FORBIDDEN: $policyApdx = ''; break; case VNagArgument::VALUE_REQUIRED: $policyApdx = ':'; break; case VNagArgument::VALUE_OPTIONAL: $policyApdx = '::'; break; default: throw new VNagInvalidValuePolicy(sprintf(VNagLang::$illegal_valuepolicy, $valuePolicy)); } if ((!is_null($shortopt)) && ($shortopt != '?')) self::$all_short .= $shortopt.$policyApdx; if (is_array($longopts)) { foreach ($longopts as $longopt) { self::$all_long[] = $longopt.$policyApdx; } } $this->shortopt = $shortopt; $this->longopts = $longopts; $this->valuePolicy = $valuePolicy; $this->valueName = $valueName; $this->helpText = $helpText; $this->defaultValue = $defaultValue; } protected static function getOptions() { global $OVERWRITE_ARGUMENTS; if (!is_null($OVERWRITE_ARGUMENTS)) { return $OVERWRITE_ARGUMENTS; } else if (VNag::is_http_mode()) { return $_REQUEST; } else { return getopt(self::$all_short, self::$all_long); } } public function count() { $options = self::getOptions(); $count = 0; if (isset($options[$this->shortopt])) { if (is_array($options[$this->shortopt])) { $count += count($options[$this->shortopt]); } else { $count += 1; } } if (!is_null($this->longopts)) { foreach ($this->longopts as $longopt) { if (isset($options[$longopt])) { if (is_array($options[$longopt])) { $count += count($options[$longopt]); } else { $count += 1; } } } } return $count; } public function available() { $options = self::getOptions(); if (isset($options[$this->shortopt])) return true; if (!is_null($this->longopts)) { foreach ($this->longopts as $longopt) { if (isset($options[$longopt])) return true; } } return false; } public function require() { if (!$this->available() && is_null($this->defaultValue)) { $opt = $this->shortopt; $opt = !_empty($opt) ? '-'.$opt : (isset($this->longopts[0]) ? '--'.$this->longopts[0] : '?'); throw new VNagRequiredArgumentMissing($opt); } } public function getValue() { $options = self::getOptions(); if (isset($options[$this->shortopt])) { $x = $options[$this->shortopt]; if (is_array($x) && (count($x) <= 1)) $options[$this->shortopt] = $options[$this->shortopt][0]; return $options[$this->shortopt]; } if (!is_null($this->longopts)) { foreach ($this->longopts as $longopt) { if (isset($options[$longopt])) { $x = $options[$longopt]; if (is_array($x) && (count($x) <= 1)) $options[$longopt] = $options[$longopt][0]; return $options[$longopt]; } } } return $this->defaultValue; } } class VNagArgumentHandler { protected $expectedArgs = array(); protected function _addExpectedArgument($argObj) { if ($argObj->getShortOpt() == '?') return false; if ($argObj->getShortOpt() == '-') return false; if ($argObj->getShortOpt() == '+') return false; $this->expectedArgs[] = $argObj; return true; } public function getArgumentObj($shortopt) { foreach ($this->expectedArgs as $argObj) { if ($argObj->getShortOpt() == $shortopt) return $argObj; } return null; } public function isArgRegistered($shortopt) { return !is_null($this->getArgumentObj($shortopt)); } public function illegalUsage() { global $argv; return (isset($argv[1])) && (($argv[1] == '-?') || ($argv[1] == '/?')); } } class VNagRange { public $start; public $end; public $warnInsideRange; public function __construct($rangeDef, $singleValueBehavior=VNag::SINGLEVALUE_RANGE_DEFAULT) { $m = array(); if (!preg_match('|^(@){0,1}([^:]+)(:){0,1}(.*)$|', $rangeDef, $m)) { throw new VNagInvalidRangeException(sprintf(VNagLang::$range_invalid_syntax, $rangeDef)); } $this->warnInsideRange = $m[1] === '@'; $this->start = null; $this->end = null; if ($m[3] === ':') { if ($m[2] === '~') { $this->start = '-inf'; } else { $this->start = new VNagValueUomPair($m[2]); } if (_empty($m[4])) { $this->end = 'inf'; } else { $this->end = new VNagValueUomPair($m[4]); } } else { assert(_empty($m[4])); assert(!_empty($m[2])); $x = $m[2]; if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_DEFAULT) { $this->start = new VNagValueUomPair('0'.((new VNagValueUomPair($x))->getUom())); $this->end = new VNagValueUomPair($x); } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_GT_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 0; $this->start = '-inf'; $this->end = new VNagValueUomPair($x); } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_GE_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 1; $this->start = new VNagValueUomPair($x); $this->end = 'inf'; } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_LT_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 0; $this->start = new VNagValueUomPair($x); $this->end = 'inf'; } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_LE_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 1; $this->start = '-inf'; $this->end = new VNagValueUomPair($x); } else { throw new VNagException(VNagLang::$illegalSingleValueBehavior); } } if (is_null($this->start)) { throw new VNagInvalidRangeException(VNagLang::$invalid_start_value); } if (is_null($this->end)) { throw new VNagInvalidRangeException(VNagLang::$invalid_end_value); } if (($this->start instanceof VNagValueUomPair) && ($this->end instanceof VNagValueUomPair) && (VNagValueUomPair::compare($this->start,$this->end) > 0)) { throw new VNagInvalidRangeException(VNagLang::$start_is_greater_than_end); } } public function __toString() { $ret = ''; if ($this->warnInsideRange) { $ret = '@'; } if ($this->start === '-inf') { $ret .= '~'; } else { $ret .= $this->start; } $ret .= ':'; if ($this->end !== 'inf') { $ret .= $this->end; } return $ret; } public function checkAlert($values) { $compatibleCount = 0; if (!is_array($values)) $values = array($values); foreach ($values as $value) { if (!($value instanceof VNagValueUomPair)) $value = new VNagValueUomPair($value); assert(($this->start === '-inf') || ($this->start instanceof VNagValueUomPair)); assert(($this->end === 'inf' ) || ($this->end instanceof VNagValueUomPair)); if (($this->start !== '-inf') && (!$this->start->compatibleWith($value))) continue; if (($this->end !== 'inf') && (!$this->end->compatibleWith($value))) continue; $compatibleCount++; if ($this->warnInsideRange) { return (($this->start === '-inf') || (VNagValueUomPair::compare($value,$this->start) >= 0)) && (($this->end === 'inf') || (VNagValueUomPair::compare($value,$this->end) <= 0)); } else { return (($this->start !== '-inf') && (VNagValueUomPair::compare($value,$this->start) < 0)) || (($this->end !== 'inf') && (VNagValueUomPair::compare($value,$this->end) > 0)); } } if ((count($values) > 0) and ($compatibleCount == 0)) { throw new VNagNoCompatibleRangeUomFoundException(VNagLang::$no_compatible_range_uom_found); } return false; } } class VNagValueUomPair { protected $value; protected $uom; public $roundTo = -1; public function isRelative() { return $this->uom === '%'; } public function getValue() { return $this->value; } public function getUom() { return $this->uom; } public function __toString() { if ($this->roundTo == -1) { return $this->value.$this->uom; } else { return round($this->value,$this->roundTo).$this->uom; } } public function __construct($str) { $m = array(); if (!preg_match('/^([\d\.]+)(.*)$/ism', $str, $m)) { throw new VNagValueUomPairSyntaxException($str); } $this->value = $m[1]; $this->uom = isset($m[2]) ? $m[2] : ''; if (!self::isKnownUOM($this->uom)) { throw new VNagUnknownUomException($this->uom); } } public static function isKnownUOM(string $uom) { $no_unit = ($uom === ''); $seconds = ($uom === 's') || ($uom === 'ms') || ($uom === 'us'); $percentage = ($uom === '%'); $bytes = ($uom === 'B') || ($uom === 'KB') || ($uom === 'MB') || ($uom === 'GB') || ($uom === 'TB'); $counter = ($uom === 'c'); return ($no_unit || $seconds || $percentage || $bytes || $counter); } public function normalize($target=null) { $res = clone $this; if ($res->uom === 'ms') { $res->uom = 's'; $res->value /= 1000; } if ($res->uom === 'us') { $res->uom = 's'; $res->value /= 1000 * 1000; } if ($res->uom === 'B') { $res->uom = 'MB'; $res->value /= 1024 * 1024; } if ($res->uom === 'KB') { $res->uom = 'MB'; $res->value /= 1024; } if ($res->uom === 'GB') { $res->uom = 'MB'; $res->value *= 1024; } if ($res->uom === 'TB') { $res->uom = 'MB'; $res->value *= 1024 * 1024; } if ($res->uom === 'c') { $res->uom = ''; } if (!is_null($target)) { if ($res->uom == 'MB') { if ($target == 'B') { $res->uom = 'B'; $res->value *= 1024 * 1024; } else if ($target == 'KB') { $res->uom = 'KB'; $res->value *= 1024; } else if ($target == 'MB') { $res->uom = 'MB'; $res->value *= 1; } else if ($target == 'GB') { $res->uom = 'GB'; $res->value /= 1024; } else if ($target == 'TB') { $res->uom = 'TB'; $res->value /= 1024 * 1024; } else { throw new VNagUomConvertException($res->uom, $target); } } else if ($res->uom == 's') { if ($target == 's') { $res->uom = 's'; $res->value /= 1; } else if ($target == 'ms') { $res->uom = 'ms'; $res->value /= 1000; } else if ($target == 'us') { $res->uom = 'us'; $res->value /= 1000 * 1000; } else { throw new VNagUomConvertException($res->uom, $target); } } else { throw new VNagUomConvertException($res->uom, $target); } } return $res; } public function compatibleWith(VNagValueUomPair $other) { $a = $this->normalize(); $b = $other->normalize(); return ($a->uom == $b->uom); } public static function compare(VNagValueUomPair $left, VNagValueUomPair $right) { $a = $left->normalize(); $b = $right->normalize(); if ($a->uom != $b->uom) throw new VNagMixedUomsNotImplemented($a->uom, $b->uom); if ($a->value > $b->value) return 1; if ($a->value == $b->value) return 0; if ($a->value < $b->value) return -1; } } class VNagPerformanceData { protected $label; protected $value; protected $warn = null; protected $crit = null; protected $min = null; protected $max = null; public static function createByString($perfdata) { $perfdata = trim($perfdata); $ary = explode('=',$perfdata); if (count($ary) != 2) { throw new VNagInvalidPerformanceDataException(sprintf(VNagLang::$perfdata_line_invalid, $perfdata)); } $label = $ary[0]; $bry = explode(';',$ary[1]); if (substr($label,0,1) === "'") $label = substr($label, 1, strlen($label)-2); $value = $bry[0]; $warn = isset($bry[1]) ? $bry[1] : null; $crit = isset($bry[2]) ? $bry[2] : null; $min = isset($bry[3]) ? $bry[3] : null; $max = isset($bry[4]) ? $bry[4] : null; return new self($label, $value, $warn, $crit, $min, $max); } public function __construct($label, $value, $warn=null, $crit=null, $min=null, $max=null) { if (strpos($label, '=') !== false) throw new VNagInvalidPerformanceDataException(VNagLang::$perfdata_label_equal_sign_forbidden); $label = str_replace("'", "''", $label); $m = array(); if ((!_empty($min)) && (!preg_match('|^[-0-9\\.]+$|', $min, $m))) { throw new VNagInvalidPerformanceDataException(VNagLang::$perfdata_min_must_be_in_class); } if ((!_empty($max)) && (!preg_match('|^[-0-9\\.]+$|', $max, $m))) { throw new VNagInvalidPerformanceDataException(VNagLang::$perfdata_max_must_be_in_class); } $this->label = $label; $this->value = ($value == 'U') ? 'U' : new VNagValueUomPair($value); $this->warn = $warn; $this->crit = $crit; $this->min = $min; $this->max = $max; } public function __toString() { $label = $this->label; $value = $this->value; $warn = $this->warn; $crit = $this->crit; $min = $this->min; $max = $this->max; $label = str_replace("''", "'", $label); return "'$label'=$value". ';'.(is_null($warn) ? '' : $warn). ';'.(is_null($crit) ? '' : $crit). ';'.(is_null($min) ? '' : $min). ';'.(is_null($max) ? '' : $max); } } class VNagHelp { public $word_wrap_width = 80; public $argument_indent = 7; public function printUsagePage() { $usage = $this->getUsage(); if (_empty($usage)) { $usage = VNagLang::$no_syntax_defined; } return trim($usage)."\n"; } public function printVersionPage() { $out = trim($this->getNameAndVersion())."\n"; if ($this->word_wrap_width > 0) $out = wordwrap($out, $this->word_wrap_width, "\n", false); return $out; } static private function _conditionalLine($line, $terminator='', $prefix='') { if (!_empty($line)) { return trim($line).$terminator; } return ''; } public function printHelpPage() { $out = ''; $out .= self::_conditionalLine($this->getNameAndVersion(), "\n"); $out .= self::_conditionalLine($this->getCopyright(), "\n"); $out .= ($out != '') ? "\n" : ''; $out .= self::_conditionalLine($this->getShortDescription(), "\n\n\n"); $out .= self::_conditionalLine($this->getUsage(), "\n\n"); $out .= VNagLang::$options."\n"; foreach ($this->options as $argObj) { $out .= $this->printArgumentHelp($argObj); } $out .= self::_conditionalLine($this->getFootNotes(), "\n\n", "\n"); if ($this->word_wrap_width > 0) $out = wordwrap($out, $this->word_wrap_width, "\n", false); return $out; } protected $options = array(); protected function _addOption($argObj) { $this->options[] = $argObj; } protected function printArgumentHelp($argObj) { $identifiers = array(); $shortopt = $argObj->getShortopt(); if (!_empty($shortopt)) $identifiers[] = '-'.$shortopt; $longopts = $argObj->getLongopts(); if (!is_null($longopts)) { foreach ($longopts as $longopt) { if (!_empty($longopt)) $identifiers[] = '--'.$longopt; } } if (count($identifiers) == 0) return; $valueName = $argObj->getValueName(); $arginfo = ''; switch ($argObj->getValuePolicy()) { case VNagArgument::VALUE_FORBIDDEN: $arginfo = ''; break; case VNagArgument::VALUE_REQUIRED: $arginfo = '='.$valueName; break; case VNagArgument::VALUE_OPTIONAL: $arginfo = '[='.$valueName.']'; break; } $out = ''; $out .= implode(', ', $identifiers).$arginfo."\n"; $content = trim($argObj->getHelpText()); if ($this->word_wrap_width > 0) $content = wordwrap($content, $this->word_wrap_width-$this->argument_indent, "\n", false); $lines = explode("\n", $content); foreach ($lines as $line) { $out .= str_repeat(' ', $this->argument_indent).$line."\n"; } $out .= "\n"; return $out; } protected $pluginName; public function setPluginName($pluginName) { $this->pluginName = $this->replaceStuff($pluginName); } public function getPluginName() { if (_empty($this->pluginName)) { global $argv; return basename($argv[0]); } else { return $this->pluginName; } } protected $version; public function setVersion($version) { $this->version = $this->replaceStuff($version); } public function getVersion() { return $this->version; } public function getNameAndVersion() { $ret = $this->getPluginName(); if (_empty($ret)) return null; $ver = $this->getVersion(); if (!_empty($ver)) { $ret = sprintf(VNagLang::$x_version_x, $ret, $ver); } $ret = trim($ret); return $ret; } protected $copyright; public function setCopyright($copyright) { $this->copyright = $this->replaceStuff($copyright); } private function getVNagCopyright() { if (VNag::is_http_mode()) { $vts_email = 'www.viathinksoft.com'; } else { $vts_email = base64_decode('aW5mb0B2aWF0aGlua3NvZnQuZGU='); } return "VNag Framework ".VNag::VNAG_VERSION." (C) 2014-".date('Y')." ViaThinkSoft <$vts_email>"; } public function getCopyright() { if (_empty($this->copyright)) { return sprintf(VNagLang::$plugin_uses, $this->getVNagCopyright()); } else { return trim($this->copyright)."\n".sprintf(VNagLang::$uses, $this->getVNagCopyright()); } } protected $shortDescription; public function setShortDescription($shortDescription) { $this->shortDescription = $this->replaceStuff($shortDescription); } public function getShortDescription() { if (_empty($this->shortDescription)) { return null; } else { $content = $this->shortDescription; if ($this->word_wrap_width > 0) $content = wordwrap($content, $this->word_wrap_width, "\n", false); return $content; } } protected function replaceStuff($text) { global $argv; if (php_sapi_name() == 'cli') { $text = str_replace('$SCRIPTNAME$', $argv[0], $text); } else { $text = str_replace('$SCRIPTNAME$', basename($_SERVER['SCRIPT_NAME']), $text); } $text = str_replace('$CURYEAR$', date('Y'), $text); return $text; } protected $syntax; public function setSyntax($syntax) { $syntax = $this->replaceStuff($syntax); $this->syntax = $syntax; } public function getUsage() { if (_empty($this->syntax)) { return null; } else { return sprintf(VNagLang::$usage_x, $this->syntax); } } protected $footNotes; public function setFootNotes($footNotes) { $this->footNotes = $this->replaceStuff($footNotes); } public function getFootNotes() { return $this->footNotes; } } class VNagLang { public static function status($code, $statusmodel) { switch ($statusmodel) { case VNag::STATUSMODEL_SERVICE: switch ($code) { case VNag::STATUS_OK: return 'OK'; case VNag::STATUS_WARNING: return 'Warning'; case VNag::STATUS_CRITICAL: return 'Critical'; case VNag::STATUS_UNKNOWN: return 'Unknown'; default: return sprintf('Error (%d)', $code); } case VNag::STATUSMODEL_HOST: switch ($code) { case VNag::STATUS_UP: return 'Up'; case VNag::STATUS_DOWN: return 'Down'; default: return sprintf('Maintain last state (%d)', $code); } default: throw new VNagIllegalStatusModel(sprintf(self::$illegal_statusmodel, $statusmodel)); } } static $nagios_output = 'VNag-Output'; static $verbose_info = 'Verbose information'; static $status = 'Status'; static $message = 'Message'; static $performance_data = 'Performance data'; static $status_ok = 'OK'; static $status_warn = 'Warning'; static $status_critical = 'Critical'; static $status_unknown = 'Unknown'; static $status_error = 'Error'; static $unhandled_exception_without_msg = "Unhandled exception of type %s"; static $plugin_uses = 'This plugin uses %s'; static $uses = 'uses %s'; static $x_version_x = '%s, version %s'; static $argname_value = 'value'; static $argname_seconds = 'seconds'; static $query_without_expected_argument = "The argument '%s' is queried, but was not added to the list of expected arguments. Please contact the plugin author."; static $required_argument_missing = "The argument '%s' is required."; static $performance_data_invalid = 'Performance data invalid.'; static $no_standard_arguments_with_letter = "No standard argument with letter '%s' exists."; static $invalid_start_value = 'Invalid start value.'; static $invalid_end_value = 'Invalid end value.'; static $start_is_greater_than_end = 'Start is greater than end value.'; static $value_name_forbidden = "Implementation error: You may not define a value name for the argument, because the value policy is VALUE_FORBIDDEN."; static $value_name_required = "Implementation error: Please define a name for the argument (so it can be shown in the help page)."; static $illegal_shortopt = "Illegal shortopt '-%s'."; static $illegal_longopt = "Illegal longopt '--%s'."; static $illegal_valuepolicy = "valuePolicy has illegal value '%s'."; static $range_invalid_syntax = "Syntax error in range '%s'."; static $timeout_value_invalid = "Timeout value '%s' is invalid."; static $range_is_invalid = 'Range is invalid.'; static $timeout_exception = 'Timeout!'; static $perfdata_label_equal_sign_forbidden = 'Label may not contain an equal sign.'; static $perfdata_value_must_be_in_class = 'Value must be in class [-0-9.] or be \'U\' if the actual value can\'t be determined.'; static $perfdata_min_must_be_in_class = 'Min must be in class [-0-9.] or empty.'; static $perfdata_max_must_be_in_class = 'Max must be in class [-0-9.] or empty.'; static $perfdata_uom_not_recognized = 'UOM (unit of measurement) "%s" is not recognized.'; static $perfdata_mixed_uom_not_implemented = 'Mixed UOMs (%s and %s) are currently not supported.'; static $no_compatible_range_uom_found = 'Measured values are not compatible with the provided warning/critical parameter. Most likely, the UOM is incompatible.'; static $exception_x = '%s (%s)'; static $no_syntax_defined = 'The author of this plugin has not defined a syntax for this plugin.'; static $usage_x = "Usage:\n%s"; static $options = "Options:"; static $illegal_statusmodel = "Invalid statusmodel %d."; static $none = '[none]'; static $valueUomPairSyntaxError = 'Syntax error at "%s". Syntax must be Value[UOM].'; static $too_few_warning_ranges = "You have too few warning ranges (currently trying to get element %d)."; static $too_few_critical_ranges = "You have too few critical ranges (currently trying to get element %d)."; static $dataset_missing = 'Dataset missing.'; static $payload_not_base64 = 'The payload is not valid Base64.'; static $payload_not_json = 'The payload is not valid JSON.'; static $signature_missing = 'The signature is missing.'; static $signature_not_bas64 = 'The signature is not valid Base64.'; static $signature_invalid = 'The signature is invalid. The connection might have been tampered, or a different key is used.'; static $pubkey_file_not_found = "Public key file %s was not found."; static $pubkey_file_not_readable = "Public key file %s is not readable."; static $privkey_file_not_found = "Private key file %s was not found."; static $privkey_not_readable = "Private key is not readable."; static $privkey_file_not_readable = "Private key file %s is not readable."; static $signature_failed = "Signature failed."; static $perfdata_line_invalid = "Performance data line %s is invalid."; static $singlevalue_unexpected_at_symbol = 'This plugin does not allow the @-symbol at ranges for single values.'; static $illegalSingleValueBehavior = "Illegal value for 'singleValueBehavior'. Please contact the creator of the plugin."; static $dataset_encryption_no_array = 'Dataset encryption information invalid.'; static $require_password = 'This resource is protected with a password. Please provide a password.'; static $wrong_password = 'This resource is protected with a password. You have provided the wrong password, or it was changed.'; static $convert_x_y_error = 'Cannot convert from UOM %s to UOM %s.'; static $php_error = 'PHP has detected an error in the plugin. Please contact the plugin author.'; static $output_level_lowered = "Output Buffer level lowered during cbRun(). Please contact the plugin author."; static $openssl_missing = "OpenSSL is missing. Therefore, encryption and signatures are not available."; static $warning_range = 'Warning range'; static $critical_range = 'Critical range'; static $prints_version = 'Prints version'; static $verbosity_helptext = 'Verbosity -v, -vv or -vvv'; static $timeout_helptext = 'Sets timeout in seconds'; static $help_helptext = 'Prints help page'; static $prints_usage = 'Prints usage'; static $notConstructed = 'Parent constructor not called with parent::__construct().'; } function vnagErrorHandler($errorkind, $errortext, $file, $line) { global $inside_vnag_run; if (!$inside_vnag_run && VNag::is_http_mode()) { return false; } if (!(error_reporting() & $errorkind)) { return true; } if (defined('E_ERROR') && ($errorkind == E_ERROR)) $errorkind = 'Error'; if (defined('E_WARNING') && ($errorkind == E_WARNING)) $errorkind = 'Warning'; if (defined('E_PARSE') && ($errorkind == E_PARSE)) $errorkind = 'Parse'; if (defined('E_NOTICE') && ($errorkind == E_NOTICE)) $errorkind = 'Notice'; if (defined('E_CORE_ERROR') && ($errorkind == E_CORE_ERROR)) $errorkind = 'Core Error'; if (defined('E_CORE_WARNING') && ($errorkind == E_CORE_WARNING)) $errorkind = 'Core Warning'; if (defined('E_COMPILE_ERROR') && ($errorkind == E_COMPILE_ERROR)) $errorkind = 'Compile Error'; if (defined('E_COMPILE_WARNING') && ($errorkind == E_COMPILE_WARNING)) $errorkind = 'Compile Warning'; if (defined('E_USER_ERROR') && ($errorkind == E_USER_ERROR)) $errorkind = 'User Error'; if (defined('E_USER_WARNING') && ($errorkind == E_USER_WARNING)) $errorkind = 'User Warning'; if (defined('E_USER_NOTICE') && ($errorkind == E_USER_NOTICE)) $errorkind = 'User Notice'; if (defined('E_STRICT') && ($errorkind == E_STRICT)) $errorkind = 'Strict'; if (defined('E_RECOVERABLE_ERROR') && ($errorkind == E_RECOVERABLE_ERROR)) $errorkind = 'Recoverable Error'; if (defined('E_DEPRECATED') && ($errorkind == E_DEPRECATED)) $errorkind = 'Deprecated'; if (defined('E_USER_DEPRECATED') && ($errorkind == E_USER_DEPRECATED)) $errorkind = 'User Deprecated'; throw new VNagException(VNagLang::$php_error . " $errortext at $file:$line (kind $errorkind)"); } $inside_vnag_run = false; $old_error_handler = set_error_handler("vnagErrorHandler"); <?php
declare(ticks=1); class MediaWikiVersionCheck extends VNag { protected $argSystemDir = null; public function __construct() { parent::__construct(); $this->registerExpectedStandardArguments('Vht'); $this->getHelpManager()->setPluginName('check_mediawiki_version'); $this->getHelpManager()->setVersion('2023-10-13'); $this->getHelpManager()->setShortDescription('This plugin checks if a local MediaWiki system has the latest version installed.'); $this->getHelpManager()->setCopyright('Copyright (C) 2011-$CURYEAR$ Daniel Marschall, ViaThinkSoft.'); $this->getHelpManager()->setSyntax('$SCRIPTNAME$ [-d <directory>]'); $this->getHelpManager()->setFootNotes('If you encounter bugs, please contact ViaThinkSoft at www.viathinksoft.com'); $this->addExpectedArgument($this->argSystemDir = new VNagArgument('d', 'directory', VNagArgument::VALUE_REQUIRED, 'mediawikiPath', 'The local directory where MediaWiki installation is located.')); } protected function get_local_version($path) { $path = realpath($path) === false ? $path : realpath($path); $cont = @file_get_contents("$path/includes/Defines.php"); if ($cont !== false) { if (preg_match('@define\\( \'MW_VERSION\', \'([0-9\\.]+)\' \\);@is', $cont, $m)) return $m[1]; } $cont = @file_get_contents("$path/includes/DefaultSettings.php"); if ($cont !== false) { if (preg_match('@\\$wgVersion = \'([0-9\\.]+)\';@is', $cont, $m)) return $m[1]; } throw new VNagException("Cannot find version information at $path"); } protected function get_latest_version() { $cont = $this->url_get_contents('https://www.mediawiki.org/wiki/Download/en'); if ($cont === false) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, "https://www.mediawiki.org/wiki/Download/en"); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true ); $cont = @curl_exec( $ch ); curl_close($ch); if (!$cont) { throw new VNagException("Cannot access website with latest version"); } } if (!preg_match('@//releases\.wikimedia\.org/mediawiki/([^"]+)/mediawiki\-([^"]+)\.tar\.gz"@ismU', $cont, $m)) { throw new VNagException("Cannot find version information on the website"); } return $m[2]; } protected function cbRun($optional_args=array()) { $system_dir = $this->argSystemDir->getValue(); if (empty($system_dir)) { throw new VNagException("Please specify the directory of the MediaWiki installation."); } $system_dir = realpath($system_dir) === false ? $system_dir : realpath($system_dir); if (!is_dir($system_dir)) { throw new VNagException('Directory "'.$system_dir.'" not found.'); } $version = $this->get_local_version($system_dir); $latest_version = $this->get_latest_version(); if (version_compare($version,$latest_version) >= 0) { $this->setStatus(VNag::STATUS_OK); $this->setHeadline("Version $version at $system_dir", true); } else { $this->setStatus(VNag::STATUS_WARNING); $this->setHeadline("Version $version is outdated (Latest version is $latest_version) at $system_dir", true); } } } <?php
-¦þ'ÛGBMB
\ No newline at end of file
+ declare(ticks=1); require_once __DIR__ . '/../../framework/vnag_framework.inc.php'; require_once __DIR__ . '/MediaWikiVersionCheck.class.php'; $job = new MediaWikiVersionCheck(); $job->run(); unset($job); ðj%¡Ü™„--¿p•¸µ¯E ¾Ön0†0êÄâè!ŽÌÆÙXÜì”Ï?,ç€i®Àýž¤Ólh@08GBMB
\ No newline at end of file
/trunk/bin/megaraid.phar
291,8 → 291,7
 
Extract_Phar::go();
__HALT_COMPILER(); ?>
=ka:1:{s:23:"1.3.6.1.4.1.37476.3.0.2";s:317:"sha256||framework/vnag_framework.inc.php|460b109d1c578e9b6af41612e0312c9f36fd8beb51f7aa92f1b7bd49614568e8||plugins/megaraid/MegaRaidCheck.class.php|eb86e467d0acfd1a2cd1568e2b659cbb4d9a974a06b793d38fcae71fb174782d||plugins/megaraid/check_megaraid.phps|0279c6de7bdd014ad6243447a1e142d6a08f18449d6ea772c850d6336ad14d34||";} framework/vnag_framework.inc.phpLÙyï*eLُ4p”¤(plugins/megaraid/MegaRaidCheck.class.phpÙyï*eُ·Å¤$plugins/megaraid/check_megaraid.phpsÂyï*eÂÜÆi$¤<?php ?>
<?php
‰·a:1:{s:23:"1.3.6.1.4.1.37476.3.0.2";s:393:"sha256||<builder>|481cf75d675006b504520fd2acb3b29c89aea03aab64754e0adfb364de4914b2||framework/vnag_framework.inc.php|0387bf3134f8cc2d1ae24e139019c0edef19c1ba5ca765624efea0b469c7897f||plugins/megaraid/MegaRaidCheck.class.php|eb86e467d0acfd1a2cd1568e2b659cbb4d9a974a06b793d38fcae71fb174782d||plugins/megaraid/check_megaraid.phps|0279c6de7bdd014ad6243447a1e142d6a08f18449d6ea772c850d6336ad14d34||";} framework/vnag_framework.inc.phpBÙ» +eBÙÞß=¤(plugins/megaraid/MegaRaidCheck.class.phpÙ» +eُ·Å¤$plugins/megaraid/check_megaraid.phps» +eÂÜÆi$¤<?php
if (!VNag::is_http_mode()) error_reporting(E_ALL); declare(ticks=1); set_time_limit(0); define('VNAG_JSONDATA_V1', 'oid:1.3.6.1.4.1.37476.2.3.1.1'); $OVERWRITE_ARGUMENTS = null; function _empty($x) { return is_null($x) || (trim($x) == ''); } abstract class VNag { const VNAG_VERSION = '2023-10-13'; const STATUS_OK = 0; const STATUS_WARNING = 1; const STATUS_CRITICAL = 2; const STATUS_UNKNOWN = 3; const STATUS_ERROR = 4; const STATUS_UP = 0; const STATUS_DOWN = 1; const STATUS_MAINTAIN = 2; const VERBOSITY_SUMMARY = 0; const VERBOSITY_ADDITIONAL_INFORMATION = 1; const VERBOSITY_CONFIGURATION_DEBUG = 2; const VERBOSITY_PLUGIN_DEBUG = 3; const MAX_VERBOSITY = self::VERBOSITY_PLUGIN_DEBUG; const STATUSMODEL_SERVICE = 0; const STATUSMODEL_HOST = 1; private $initialized = false; private $status = null; private $messages = array(); private $verbose_info = ''; private $warningRanges = array(); private $criticalRanges = array(); private $performanceDataObjects = array(); private static $exitcode = 0; private $helpObj = null; private $argHandler = null; const OUTPUT_NEVER = 0; const OUTPUT_SPECIAL = 1; const OUTPUT_NORMAL = 2; const OUTPUT_EXCEPTION = 4; const OUTPUT_ALWAYS = 7; public $http_visual_output = self::OUTPUT_ALWAYS; public $http_invisible_output = self::OUTPUT_ALWAYS; protected $html_before = ''; protected $html_after = ''; protected $statusmodel = self::STATUSMODEL_SERVICE; protected $show_status_in_headline = true; protected $default_status = self::STATUS_UNKNOWN; protected $default_warning_range = null; protected $default_critical_range = null; protected $argWarning; protected $argCritical; protected $argVersion; protected $argVerbosity; protected $argTimeout; protected $argHelp; protected $argUsage; public $id = null; protected static $http_serial_number = 0; public $privkey = null; public $privkey_password = null; public $sign_algo = null; public $pubkey = null; protected $warningSingleValueRangeBehaviors = array(self::SINGLEVALUE_RANGE_DEFAULT); protected $criticalSingleValueRangeBehaviors = array(self::SINGLEVALUE_RANGE_DEFAULT); const SINGLEVALUE_RANGE_DEFAULT = 0; const SINGLEVALUE_RANGE_VAL_GT_X_BAD = 1; const SINGLEVALUE_RANGE_VAL_GE_X_BAD = 2; const SINGLEVALUE_RANGE_VAL_LT_X_BAD = 3; const SINGLEVALUE_RANGE_VAL_LE_X_BAD = 4; public $password_out = null; public $password_in = null; public static function is_http_mode() { return php_sapi_name() !== 'cli'; } public function getHelpManager() { return $this->helpObj; } public function getArgumentHandler() { return $this->argHandler; } public function outputHTML($text, $after_visual_output=true) { if ($this->is_http_mode()) { if ($this->initialized) { if ($after_visual_output) { $this->html_after .= $text; } else { $this->html_before .= $text; } } else { echo $text; } } } protected function resetArguments() { $this->argWarning = null; $this->argCritical = null; $this->argVersion = null; $this->argVerbosity = null; $this->argTimeout = null; $this->argHelp = null; $this->argWarning = null; $this->argCritical = null; } public function registerExpectedStandardArguments($args) { $this->resetArguments(); for ($i=0; $i<strlen($args); $i++) { switch ($args[$i]) { case 'w': $this->addExpectedArgument($this->argWarning = new VNagArgument('w', 'warning', VNagArgument::VALUE_REQUIRED, VNagLang::$argname_value, VNagLang::$warning_range)); break; case 'c': $this->addExpectedArgument($this->argCritical = new VNagArgument('c', 'critical', VNagArgument::VALUE_REQUIRED, VNagLang::$argname_value, VNagLang::$critical_range)); break; case 'V': $this->addExpectedArgument($this->argVersion = new VNagArgument('V', 'version', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$prints_version)); break; case 'v': $this->addExpectedArgument($this->argVerbosity = new VNagArgument('v', 'verbose', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$verbosity_helptext)); break; case 't': $this->addExpectedArgument($this->argTimeout = new VNagArgument('t', 'timeout', VNagArgument::VALUE_REQUIRED, VNagLang::$argname_seconds, VNagLang::$timeout_helptext)); break; case 'h': $this->addExpectedArgument($this->argHelp = new VNagArgument('h', 'help', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$help_helptext)); break; default: $letter = $args[$i]; throw new VNagInvalidStandardArgument(sprintf(VNagLang::$no_standard_arguments_with_letter, $letter)); } } } public function addExpectedArgument($argObj) { $helpObjAddEntryMethod = new ReflectionMethod($this->helpObj, '_addOption'); $helpObjAddEntryMethod->setAccessible(true); $helpObjAddEntryMethod->invoke($this->helpObj, $argObj); $argHandlerAddEntryMethod = new ReflectionMethod($this->argHandler, '_addExpectedArgument'); $argHandlerAddEntryMethod->setAccessible(true); $argHandlerAddEntryMethod->invoke($this->argHandler, $argObj); } protected function createArgumentHandler() { $this->argHandler = new VNagArgumentHandler(); } protected function createHelpObject() { $this->helpObj = new VNagHelp(); } protected function checkInitialized() { if (!$this->initialized) throw new VNagFunctionCallOutsideSession(); } protected function getVerbosityLevel() { $this->checkInitialized(); if (!isset($this->argVerbosity)) { return self::VERBOSITY_SUMMARY; } else { $level = $this->argVerbosity->count(); if ($level > self::MAX_VERBOSITY) $level = self::MAX_VERBOSITY; return $level; } } public function getWarningRange($argumentNumber=0) { $this->checkInitialized(); if (!isset($this->warningRanges[$argumentNumber])) { if (!is_null($this->argWarning)) { $warning = $this->argWarning->getValue(); if (!is_null($warning)) { $vals = explode(',',$warning); foreach ($vals as $number => $val) { if (_empty($val)) { $this->warningRanges[$number] = null; } else { $singleValueBehavior = isset($this->warningSingleValueRangeBehaviors[$number]) ? $this->warningSingleValueRangeBehaviors[$number] : VNag::SINGLEVALUE_RANGE_DEFAULT; $this->warningRanges[$number] = new VNagRange($val, $singleValueBehavior); } } } else { $this->warningRanges[0] = $this->default_warning_range; } } else { return null; } } if (isset($this->warningRanges[$argumentNumber])) { return $this->warningRanges[$argumentNumber]; } else { return null; } } public function getCriticalRange($argumentNumber=0) { $this->checkInitialized(); if (!isset($this->criticalRanges[$argumentNumber])) { if (!is_null($this->argCritical)) { $critical = $this->argCritical->getValue(); if (!is_null($critical)) { $vals = explode(',',$critical); foreach ($vals as $number => $val) { $singleValueBehavior = isset($this->criticalSingleValueRangeBehaviors[$number]) ? $this->criticalSingleValueRangeBehaviors[$number] : VNag::SINGLEVALUE_RANGE_DEFAULT; $this->criticalRanges[$number] = new VNagRange($val, $singleValueBehavior); } } else { $this->criticalRanges[0] = $this->default_critical_range; } } else { return null; } } if (isset($this->criticalRanges[$argumentNumber])) { return $this->criticalRanges[$argumentNumber]; } else { return null; } } public function checkAgainstWarningRange($values, $force=true, $autostatus=true, $argumentNumber=0) { $this->checkInitialized(); if (!$this->getArgumentHandler()->isArgRegistered('w')) { throw new VNagRequiredArgumentNotRegistered('-w'); } $wr = $this->getWarningRange($argumentNumber); if (isset($wr)) { if ($wr->checkAlert($values)) { if ($autostatus) $this->setStatus(VNag::STATUS_WARNING); return true; } else { if ($autostatus) $this->setStatus(VNag::STATUS_OK); return false; } } else { if ($force) { if (($argumentNumber > 0) && (count($this->warningRanges) > 0)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$too_few_warning_ranges, $argumentNumber+1)); } else { throw new VNagRequiredArgumentMissing('-w'); } } } } public function checkAgainstCriticalRange($values, $force=true, $autostatus=true, $argumentNumber=0) { $this->checkInitialized(); if (!$this->getArgumentHandler()->isArgRegistered('c')) { throw new VNagRequiredArgumentNotRegistered('-c'); } $cr = $this->getCriticalRange($argumentNumber); if (isset($cr)) { if ($cr->checkAlert($values)) { if ($autostatus) $this->setStatus(VNag::STATUS_CRITICAL); return true; } else { if ($autostatus) $this->setStatus(VNag::STATUS_OK); return false; } } else { if ($force) { if (($argumentNumber > 0) && (count($this->warningRanges) > 0)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$too_few_critical_ranges, $argumentNumber+1)); } else { throw new VNagRequiredArgumentMissing('-c'); } } } } protected static function getBaddestExitcode($code1, $code2) { return max($code1, $code2); } public static function _shutdownHandler() { if (!self::is_http_mode()) { exit((int)self::$exitcode); } } protected function _exit($code) { self::$exitcode = $this->getBaddestExitcode($code, self::$exitcode); } private $constructed = false; function __construct() { $this->createHelpObject(); $this->createArgumentHandler(); $this->addExpectedArgument($this->argUsage = new VNagArgument('?', '', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$prints_usage)); $this->constructed = true; } function __destruct() { if (Timeouter::started()) { Timeouter::end(); } } public function run() { global $inside_vnag_run; $inside_vnag_run = true; try { if (!$this->constructed) { throw new VNagNotConstructed(VNagLang::$notConstructed); } try { $this->initialized = true; $this->html_before = ''; $this->html_after = ''; $this->setStatus(null, true); $this->messages = array(); register_shutdown_function(array($this, '_shutdownHandler')); if ($this->argHandler->illegalUsage()) { $content = $this->helpObj->printUsagePage(); $this->setStatus(VNag::STATUS_UNKNOWN); if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_visual_output & VNag::OUTPUT_SPECIAL) echo $this->writeVisualHTML($content); if ($this->http_invisible_output & VNag::OUTPUT_SPECIAL) echo $this->writeInvisibleHTML($content); echo $this->html_after; return; } else { echo $content; return $this->_exit($this->status); } } if (!is_null($this->argVersion) && ($this->argVersion->available())) { $content = $this->helpObj->printVersionPage(); $this->setStatus(VNag::STATUS_UNKNOWN); if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_visual_output & VNag::OUTPUT_SPECIAL) echo $this->writeVisualHTML($content); if ($this->http_invisible_output & VNag::OUTPUT_SPECIAL) echo $this->writeInvisibleHTML($content); echo $this->html_after; return; } else { echo $content; return $this->_exit($this->status); } } if (!is_null($this->argHelp) && ($this->argHelp->available())) { $content = $this->helpObj->printHelpPage(); $this->setStatus(VNag::STATUS_UNKNOWN); if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_visual_output & VNag::OUTPUT_SPECIAL) echo $this->writeVisualHTML($content); if ($this->http_invisible_output & VNag::OUTPUT_SPECIAL) echo $this->writeInvisibleHTML($content); echo $this->html_after; return; } else { echo $content; return $this->_exit($this->status); } } $this->getWarningRange(); $this->getCriticalRange(); if (!is_null($this->argTimeout)) { $timeout = $this->argTimeout->getValue(); if (!is_null($timeout)) { Timeouter::start($timeout); } } ob_start(); $init_ob_level = ob_get_level(); try { $this->cbRun(); if (ob_get_level() < $init_ob_level) throw new VNagImplementationErrorException(VNagLang::$output_level_lowered); } finally { while (ob_get_level() > $init_ob_level) @ob_end_clean(); } if (is_null($this->status)) $this->setStatus($this->default_status,true); $outputType = VNag::OUTPUT_NORMAL; } catch (Exception $e) { $this->handleException($e); $outputType = VNag::OUTPUT_EXCEPTION; } if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_invisible_output & $outputType) { echo $this->writeInvisibleHTML(); } if ($this->http_visual_output & $outputType) { echo $this->writeVisualHTML(); } echo $this->html_after; } else { echo $this->getNagiosConsoleText(); return $this->_exit($this->status); } Timeouter::end(); } finally { $inside_vnag_run = false; } } private function getNagiosConsoleText() { $ary_perfdata = $this->getPerformanceData(); $performancedata_first = array_shift($ary_perfdata); $performancedata_rest = implode(' ', $ary_perfdata); $status_text = VNagLang::status($this->status, $this->statusmodel); if (_empty($this->getHeadline())) { $content = $status_text; } else { if ($this->show_status_in_headline) { $content = $status_text.': '.$this->getHeadline(); } else { $content = $this->getHeadline(); } } if (!_empty($performancedata_first)) $content .= '|'.trim($performancedata_first); $content .= "\n"; if (!_empty($this->verbose_info)) { $content .= trim($this->verbose_info); } if (!_empty($performancedata_rest)) $content .= '|'.trim($performancedata_rest); $content .= "\n"; return trim($content)."\n"; } abstract protected function cbRun(); public function addPerformanceData($prefDataObj, $move_to_font=false, $verbosityLevel=VNag::VERBOSITY_SUMMARY) { $this->checkInitialized(); if ((!isset($this->argVerbosity)) && ($verbosityLevel > VNag::VERBOSITY_SUMMARY)) throw new VNagRequiredArgumentNotRegistered('-v'); if (self::getVerbosityLevel() < $verbosityLevel) return false; if ($move_to_font) { array_unshift($this->performanceDataObjects, $prefDataObj); } else { $this->performanceDataObjects[] = $prefDataObj; } return true; } public function getPerformanceData() { $this->checkInitialized(); return $this->performanceDataObjects; } public function removePerformanceData($prefDataObj) { if (($key = array_search($prefDataObj, $this->performanceDataObjects, true)) !== false) { unset($this->performanceDataObjects[$key]); return true; } else { return false; } } public function clearPerformanceData() { $this->performanceDataObjects = array(); } public function getVerboseInfo() { return $this->verbose_info; } public function clearVerboseInfo() { $this->verbose_info = ''; } private function writeVisualHTML($special_content=null) { if (!_empty($special_content)) { $content = $special_content; } else { $content = strtoupper(VNagLang::$status.': '.VNagLang::status($this->status, $this->statusmodel))."\n\n"; $content .= strtoupper(VNagLang::$message).":\n"; $status_text = VNagLang::status($this->status, $this->statusmodel); if (_empty($this->getHeadline())) { $content .= $status_text; } else { if ($this->show_status_in_headline) { $content .= $status_text.': '.trim($this->getHeadline()); } else { $content .= trim($this->getHeadline()); } } $content .= "\n\n"; if (!_empty($this->verbose_info)) { $content .= strtoupper(VNagLang::$verbose_info).":\n".trim($this->verbose_info)."\n\n"; } $perfdata = $this->getPerformanceData(); if (count($perfdata) > 0) { $content .= strtoupper(VNagLang::$performance_data).":\n"; foreach ($perfdata as $pd) { $content .= trim($pd)."\n"; } $content .= "\n"; } } $colorinfo = ''; $status = $this->getStatus(); if ($status == VNag::STATUS_OK) $colorinfo = ' style="background-color:green;color:white;font-weight:bold"'; else if ($status == VNag::STATUS_WARNING) $colorinfo = ' style="background-color:yellow;color:black;font-weight:bold"'; else if ($status == VNag::STATUS_CRITICAL) $colorinfo = ' style="background-color:red;color:white;font-weight:bold"'; else if ($status == VNag::STATUS_ERROR) $colorinfo = ' style="background-color:purple;color:white;font-weight:bold"'; else $colorinfo = ' style="background-color:lightgray;color:black;font-weight:bold"'; $html_content = trim($content); $html_content = htmlentities($html_content); $html_content = str_replace(' ', '&nbsp;', $html_content); $html_content = nl2br($html_content); return '<table border="1" cellspacing="2" cellpadding="2" style="width:100%" class="vnag_table">'. '<tr'.$colorinfo.' class="vnag_title_row">'. '<td>'.VNagLang::$nagios_output.'</td>'. '</tr>'. '<tr class="vnag_message_row">'. '<td><code>'. $html_content. '</code></td>'. '</tr>'. '</table>'; } protected function readInvisibleHTML($html) { $this->checkInitialized(); $doc = new DOMDocument(); @$doc->loadHTML($html); $tags = $doc->getElementsByTagName('script'); foreach ($tags as $tag) { $type = $tag->getAttribute('type'); if ($type !== 'application/json') continue; $json = $tag->nodeValue; if (!$json) continue; $data = @json_decode($json,true); if (!is_array($data)) continue; if (!isset($data['type'])) continue; if ($data['type'] === VNAG_JSONDATA_V1) { if (!isset($data['datasets'])) throw new VNagWebInfoException(VNagLang::$dataset_missing); foreach ($data['datasets'] as $dataset) { $payload = base64_decode($dataset['payload']); if (!$payload) { throw new VNagWebInfoException(VNagLang::$payload_not_base64); } if (isset($dataset['encryption'])) { $cryptInfo = $dataset['encryption']; if (!is_array($cryptInfo)) { throw new VNagWebInfoException(VNagLang::$dataset_encryption_no_array); } $password = is_null($this->password_in) ? '' : $this->password_in; $salt = base64_decode($cryptInfo['salt']); if ($cryptInfo['hash'] != hash('sha256',$salt.$password)) { if ($password == '') { throw new VNagWebInfoException(VNagLang::$require_password); } else { throw new VNagWebInfoException(VNagLang::$wrong_password); } } if (!function_exists('openssl_decrypt')) { throw new VNagException(VNagLang::$openssl_missing); } $payload = openssl_decrypt($payload, $cryptInfo['method'], $password, 0, $cryptInfo['iv']); } if (!is_null($this->pubkey) && ($this->pubkey !== '')) { if (substr($this->pubkey,0,3) === '---') { $public_key = $this->pubkey; } else { if (!file_exists($this->pubkey)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$pubkey_file_not_found, $this->pubkey)); } $public_key = @file_get_contents($this->pubkey); if (!$public_key) { throw new VNagPublicKeyException(sprintf(VNagLang::$pubkey_file_not_readable, $this->pubkey)); } } if (!isset($dataset['signature'])) { throw new VNagSignatureException(VNagLang::$signature_missing); } $signature = base64_decode($dataset['signature']); if (!$signature) { throw new VNagSignatureException(VNagLang::$signature_not_bas64); } if (!function_exists('openssl_verify')) { throw new VNagException(VNagLang::$openssl_missing); } $sign_algo = is_null($this->sign_algo) ? OPENSSL_ALGO_SHA256 : $this->sign_algo; if (!openssl_verify($payload, $signature, $public_key, $sign_algo)) { throw new VNagSignatureException(VNagLang::$signature_invalid); } } $payload = @json_decode($payload,true); if (!$payload) { throw new VNagWebInfoException(VNagLang::$payload_not_json); } if ($payload['id'] == $this->id) { return $payload; } } } } return null; } private function getNextMonitorID($peek=false) { $result = is_null($this->id) ? self::$http_serial_number : $this->id; if (!$peek) { $this->id = null; self::$http_serial_number++; } return $result; } private function writeInvisibleHTML($special_content=null) { $payload['id'] = $this->getNextMonitorID(); $payload['status'] = $this->getStatus(); if (!_empty($special_content)) { $payload['text'] = $special_content; } else { $payload['headline'] = $this->getHeadline(); $payload['verbose_info'] = $this->verbose_info; $payload['performance_data'] = array(); foreach ($this->performanceDataObjects as $perfdata) { $payload['performance_data'][] = (string)$perfdata; } } $payload = json_encode($payload); $dataset = array(); if (!is_null($this->privkey) && ($this->privkey !== '')) { if (!function_exists('openssl_pkey_get_private') || !function_exists('openssl_sign')) { throw new VNagException(VNagLang::$openssl_missing); } if (substr($this->privkey,0,3) === '---') { $pkeyid = @openssl_pkey_get_private($this->privkey, $this->privkey_password); if (!$pkeyid) { throw new VNagPrivateKeyException(sprintf(VNagLang::$privkey_not_readable)); } } else { if (!file_exists($this->privkey)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$privkey_file_not_found, $this->privkey)); } $pkeyid = @openssl_pkey_get_private('file://'.$this->privkey, $this->privkey_password); if (!$pkeyid) { throw new VNagPrivateKeyException(sprintf(VNagLang::$privkey_file_not_readable, $this->privkey)); } } $signature = ''; $sign_algo = is_null($this->sign_algo) ? OPENSSL_ALGO_SHA256 : $this->sign_algo; if (@openssl_sign($payload, $signature, $pkeyid, $sign_algo)) { if (version_compare(PHP_VERSION, '8.0.0') < 0) { openssl_free_key($pkeyid); } $dataset['signature'] = base64_encode($signature); } else { throw new VNagPrivateKeyException(sprintf(VNagLang::$signature_failed)); } } if (!is_null($this->password_out) && ($this->password_out !== '')) { if (!function_exists('openssl_encrypt')) { throw new VNagException(VNagLang::$openssl_missing); } $password = $this->password_out; $method = 'aes-256-ofb'; $iv = substr(hash('sha256', openssl_random_pseudo_bytes(32)), 0, 16); $salt = openssl_random_pseudo_bytes(32); $cryptInfo = array(); $cryptInfo['method'] = $method; $cryptInfo['iv'] = $iv; $cryptInfo['salt'] = base64_encode($salt); $cryptInfo['hash'] = hash('sha256', $salt.$password); $payload = openssl_encrypt($payload, $method, $password, 0, $iv); $dataset['encryption'] = $cryptInfo; } $dataset['payload'] = base64_encode($payload); $json = array(); $json['type'] = VNAG_JSONDATA_V1; $json['datasets'] = array($dataset); return '<script type="application/json">'. json_encode($json). '</script>'; } protected function appendHeadline($msg) { $this->checkInitialized(); if (_empty($msg)) return false; $this->messages[] = $msg; return true; } protected function changeHeadline($msg) { $this->checkInitialized(); if (_empty($msg)) { $this->messages = array(); } else { $this->messages = array($msg); } return true; } public function setHeadline($msg, $append=false, $verbosityLevel=VNag::VERBOSITY_SUMMARY) { $this->checkInitialized(); if ((!isset($this->argVerbosity)) && ($verbosityLevel > VNag::VERBOSITY_SUMMARY)) throw new VNagRequiredArgumentNotRegistered('-v'); if (self::getVerbosityLevel() < $verbosityLevel) $msg = ''; if ($append) { return $this->appendHeadline($msg); } else { return $this->changeHeadline($msg); } } public function getHeadline() { $this->checkInitialized(); return implode(', ', $this->messages); } public function addVerboseMessage($msg, $verbosityLevel=VNag::VERBOSITY_SUMMARY) { $this->checkInitialized(); if (self::getVerbosityLevel() >= $verbosityLevel) { $this->verbose_info .= $msg."\n"; } } public function setStatus($status, $force=false) { $this->checkInitialized(); if (($force) || is_null($this->status) || ($status > $this->status)) { $this->status = $status; } } public function getStatus() { $this->checkInitialized(); return $this->status; } protected static function exceptionText($exception) { $class = get_class($exception); $msg = $exception->getMessage(); if (!_empty($msg)) { return sprintf(VNagLang::$exception_x, $msg, $class); } else { return sprintf(VNagLang::$unhandled_exception_without_msg, $class); } } protected function handleException($exception) { $this->checkInitialized(); if (!VNag::is_http_mode()) { while (ob_get_level() > 0) @ob_end_clean(); } $this->clearVerboseInfo(); $this->clearPerformanceData(); if ($exception instanceof VNagException) { $this->setStatus($exception->getStatus()); } else { $this->setStatus(self::STATUS_ERROR); } $this->setHeadline($this->exceptionText($exception), false); if ($exception instanceof VNagImplementationErrorException) { $this->addVerboseMessage($exception->getTraceAsString(), VNag::VERBOSITY_SUMMARY); } else { if (isset($this->argVerbosity)) { $this->addVerboseMessage($exception->getTraceAsString(), VNag::VERBOSITY_ADDITIONAL_INFORMATION); } else { } } } protected function get_cache_dir() { $homedir = @getenv('HOME'); if ($homedir && is_dir($homedir)) { $try = "$homedir/.vnag/cache"; if (is_dir($try)) return $try; if (@mkdir($try,0777,true)) return $try; } $user = posix_getpwuid(posix_geteuid()); if (isset($user['dir']) && is_dir($user['dir'])) { $homedir = $user['dir']; $try = "$homedir/.vnag/cache"; if (is_dir($try)) return $try; if (@mkdir($try,0777,true)) return $try; } if (isset($user['name']) && is_dir($user['name'])) { $username = $user['name']; $try = "/tmp/vnag/cache"; if (is_dir($try)) return $try; if (@mkdir($try,0777,true)) return $try; } throw new VNagException("Cannot get cache dir"); } protected function url_get_contents($url, $max_cache_time=1*60*60, $context=null) { $cache_file = $this->get_cache_dir().'/'.hash('sha256',$url); if (file_exists($cache_file) && (time()-filemtime($cache_file) < $max_cache_time)) { $cont = @file_get_contents($cache_file); if ($cont === false) throw new Exception("Failed to get contents from $cache_file"); } else { $options = array( 'http'=>array( 'method'=>"GET", 'header'=>"Accept-language: en\r\n" . "User-Agent: Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B334b Safari/531.21.102011-10-16 20:23:10\r\n" ) ); if (is_null($context)) $context = stream_context_create($options); $cont = @file_get_contents($url, false, $context); if ($cont === false) throw new Exception("Failed to get contents from $url"); file_put_contents($cache_file, $cont); } return $cont; } } class VNagException extends Exception { public function getStatus() { return VNag::STATUS_ERROR; } } class VNagTimeoutException extends VNagException {} class VNagWebInfoException extends VNagException {} class VNagSignatureException extends VNagException {} class VNagPublicKeyException extends VNagException {} class VNagPrivateKeyException extends VNagException {} class VNagInvalidArgumentException extends VNagException { public function getStatus() { return VNag::STATUS_UNKNOWN; } } class VNagValueUomPairSyntaxException extends VNagInvalidArgumentException { public function __construct($str) { $e_msg = sprintf(VNagLang::$valueUomPairSyntaxError, $str); parent::__construct($e_msg); } } class VNagInvalidTimeoutException extends VNagInvalidArgumentException {} class VNagInvalidRangeException extends VNagInvalidArgumentException { public function __construct($msg) { $e_msg = VNagLang::$range_is_invalid; if (!_empty($msg)) $e_msg .= ': '.trim($msg); parent::__construct($e_msg); } } class VNagInvalidShortOpt extends VNagImplementationErrorException {} class VNagInvalidLongOpt extends VNagImplementationErrorException {} class VNagInvalidValuePolicy extends VNagImplementationErrorException {} class VNagIllegalStatusModel extends VNagImplementationErrorException {} class VNagNotConstructed extends VNagImplementationErrorException {} class VNagImplementationErrorException extends VNagException {} class VNagInvalidStandardArgument extends VNagImplementationErrorException {} class VNagFunctionCallOutsideSession extends VNagImplementationErrorException {} class VNagIllegalArgumentValuesException extends VNagImplementationErrorException {} class VNagRequiredArgumentNotRegistered extends VNagImplementationErrorException { public function __construct($required_argument) { $e_msg = sprintf(VNagLang::$query_without_expected_argument, $required_argument); parent::__construct($e_msg); } } class VNagRequiredArgumentMissing extends VNagInvalidArgumentException { public function __construct($required_argument) { $e_msg = sprintf(VNagLang::$required_argument_missing, $required_argument); parent::__construct($e_msg); } } class VNagUnknownUomException extends VNagInvalidArgumentException { public function __construct($uom) { $e_msg = sprintf(VNagLang::$perfdata_uom_not_recognized, $uom); parent::__construct($e_msg); } } class VNagNoCompatibleRangeUomFoundException extends VNagException {} class VNagMixedUomsNotImplemented extends VNagInvalidArgumentException { public function __construct($uom1, $uom2) { if (_empty($uom1)) $uom1 = VNagLang::$none; if (_empty($uom2)) $uom2 = VNagLang::$none; $e_msg = sprintf(VNagLang::$perfdata_mixed_uom_not_implemented, $uom1, $uom2); parent::__construct($e_msg); } } class VNagUomConvertException extends VNagInvalidArgumentException { public function __construct($uom1, $uom2) { if (_empty($uom1)) $uom1 = VNagLang::$none; if (_empty($uom2)) $uom2 = VNagLang::$none; $e_msg = sprintf(VNagLang::$convert_x_y_error, $uom1, $uom2); parent::__construct($e_msg); } } class VNagInvalidPerformanceDataException extends VNagInvalidArgumentException { public function __construct($msg) { $e_msg = VNagLang::$performance_data_invalid; if (!_empty($msg)) $e_msg .= ': '.trim($msg); parent::__construct($e_msg); } } class Timeouter { private static $start_time = false; private static $timeout; private static $fired = false; private static $registered = false; private function __construct() { } public static function start($timeout) { if (!is_numeric($timeout) || ($timeout <= 0)) { throw new VNagInvalidTimeoutException(sprintf(VNagLang::$timeout_value_invalid, $timeout)); } self::$start_time = microtime(true); self::$timeout = (float) $timeout; self::$fired = false; if (!self::$registered) { self::$registered = true; register_tick_function(array('Timeouter', 'tick')); } } public static function started() { return self::$registered; } public static function end() { if (self::$registered) { unregister_tick_function(array('Timeouter', 'tick')); self::$registered = false; } } public static function tick() { if ((!self::$fired) && ((microtime(true) - self::$start_time) > self::$timeout)) { self::$fired = true; throw new VNagTimeoutException(VNagLang::$timeout_exception); } } } class VNagArgument { const VALUE_FORBIDDEN = 0; const VALUE_REQUIRED = 1; const VALUE_OPTIONAL = 2; protected $shortopt; protected $longopts; protected $valuePolicy; protected $valueName; protected $helpText; protected $defaultValue = null; protected static $all_short = ''; protected static $all_long = array(); public function getShortOpt() { return $this->shortopt; } public function getLongOpts() { return $this->longopts; } public function getValuePolicy() { return $this->valuePolicy; } public function getValueName() { return $this->valueName; } public function getHelpText() { return $this->helpText; } static private function validateShortOpt($shortopt) { $m = array(); return preg_match('@^[a-zA-Z0-9\\+\\-\\?]$@', $shortopt, $m); } static private function validateLongOpt($longopt) { $m = array(); return preg_match('@^[a-zA-Z0-9\\+\\-\\?]+$@', $longopt, $m); } public function __construct($shortopt, $longopts, $valuePolicy, $valueName, $helpText, $defaultValue=null) { switch ($valuePolicy) { case VNagArgument::VALUE_FORBIDDEN: if (!_empty($valueName)) { throw new VNagImplementationErrorException(sprintf(VNagLang::$value_name_forbidden)); } break; case VNagArgument::VALUE_REQUIRED: if (_empty($valueName)) { throw new VNagImplementationErrorException(sprintf(VNagLang::$value_name_required)); } break; case VNagArgument::VALUE_OPTIONAL: if (_empty($valueName)) { throw new VNagImplementationErrorException(sprintf(VNagLang::$value_name_required)); } break; default: throw new VNagInvalidValuePolicy(sprintf(VNagLang::$illegal_valuepolicy, $valuePolicy)); } if (!_empty($shortopt)) { if (!self::validateShortOpt($shortopt)) { throw new VNagInvalidShortOpt(sprintf(VNagLang::$illegal_shortopt, $shortopt)); } } if (is_array($longopts)) { foreach ($longopts as $longopt) { if (!self::validateLongOpt($longopt)) { throw new VNagInvalidLongOpt(sprintf(VNagLang::$illegal_longopt, $longopt)); } } } else if (!_empty($longopts)) { if (!self::validateLongOpt($longopts)) { throw new VNagInvalidLongOpt(sprintf(VNagLang::$illegal_longopt, $longopts)); } $longopts = array($longopts); } else { $longopts = array(); } switch ($valuePolicy) { case VNagArgument::VALUE_FORBIDDEN: $policyApdx = ''; break; case VNagArgument::VALUE_REQUIRED: $policyApdx = ':'; break; case VNagArgument::VALUE_OPTIONAL: $policyApdx = '::'; break; default: throw new VNagInvalidValuePolicy(sprintf(VNagLang::$illegal_valuepolicy, $valuePolicy)); } if ((!is_null($shortopt)) && ($shortopt != '?')) self::$all_short .= $shortopt.$policyApdx; if (is_array($longopts)) { foreach ($longopts as $longopt) { self::$all_long[] = $longopt.$policyApdx; } } $this->shortopt = $shortopt; $this->longopts = $longopts; $this->valuePolicy = $valuePolicy; $this->valueName = $valueName; $this->helpText = $helpText; $this->defaultValue = $defaultValue; } protected static function getOptions() { global $OVERWRITE_ARGUMENTS; if (!is_null($OVERWRITE_ARGUMENTS)) { return $OVERWRITE_ARGUMENTS; } else if (VNag::is_http_mode()) { return $_REQUEST; } else { return getopt(self::$all_short, self::$all_long); } } public function count() { $options = self::getOptions(); $count = 0; if (isset($options[$this->shortopt])) { if (is_array($options[$this->shortopt])) { $count += count($options[$this->shortopt]); } else { $count += 1; } } if (!is_null($this->longopts)) { foreach ($this->longopts as $longopt) { if (isset($options[$longopt])) { if (is_array($options[$longopt])) { $count += count($options[$longopt]); } else { $count += 1; } } } } return $count; } public function available() { $options = self::getOptions(); if (isset($options[$this->shortopt])) return true; if (!is_null($this->longopts)) { foreach ($this->longopts as $longopt) { if (isset($options[$longopt])) return true; } } return false; } public function require() { if (!$this->available() && is_null($this->defaultValue)) { $opt = $this->shortopt; $opt = !_empty($opt) ? '-'.$opt : (isset($this->longopts[0]) ? '--'.$this->longopts[0] : '?'); throw new VNagRequiredArgumentMissing($opt); } } public function getValue() { $options = self::getOptions(); if (isset($options[$this->shortopt])) { $x = $options[$this->shortopt]; if (is_array($x) && (count($x) <= 1)) $options[$this->shortopt] = $options[$this->shortopt][0]; return $options[$this->shortopt]; } if (!is_null($this->longopts)) { foreach ($this->longopts as $longopt) { if (isset($options[$longopt])) { $x = $options[$longopt]; if (is_array($x) && (count($x) <= 1)) $options[$longopt] = $options[$longopt][0]; return $options[$longopt]; } } } return $this->defaultValue; } } class VNagArgumentHandler { protected $expectedArgs = array(); protected function _addExpectedArgument($argObj) { if ($argObj->getShortOpt() == '?') return false; if ($argObj->getShortOpt() == '-') return false; if ($argObj->getShortOpt() == '+') return false; $this->expectedArgs[] = $argObj; return true; } public function getArgumentObj($shortopt) { foreach ($this->expectedArgs as $argObj) { if ($argObj->getShortOpt() == $shortopt) return $argObj; } return null; } public function isArgRegistered($shortopt) { return !is_null($this->getArgumentObj($shortopt)); } public function illegalUsage() { global $argv; return (isset($argv[1])) && (($argv[1] == '-?') || ($argv[1] == '/?')); } } class VNagRange { public $start; public $end; public $warnInsideRange; public function __construct($rangeDef, $singleValueBehavior=VNag::SINGLEVALUE_RANGE_DEFAULT) { $m = array(); if (!preg_match('|^(@){0,1}([^:]+)(:){0,1}(.*)$|', $rangeDef, $m)) { throw new VNagInvalidRangeException(sprintf(VNagLang::$range_invalid_syntax, $rangeDef)); } $this->warnInsideRange = $m[1] === '@'; $this->start = null; $this->end = null; if ($m[3] === ':') { if ($m[2] === '~') { $this->start = '-inf'; } else { $this->start = new VNagValueUomPair($m[2]); } if (_empty($m[4])) { $this->end = 'inf'; } else { $this->end = new VNagValueUomPair($m[4]); } } else { assert(_empty($m[4])); assert(!_empty($m[2])); $x = $m[2]; if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_DEFAULT) { $this->start = new VNagValueUomPair('0'.((new VNagValueUomPair($x))->getUom())); $this->end = new VNagValueUomPair($x); } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_GT_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 0; $this->start = '-inf'; $this->end = new VNagValueUomPair($x); } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_GE_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 1; $this->start = new VNagValueUomPair($x); $this->end = 'inf'; } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_LT_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 0; $this->start = new VNagValueUomPair($x); $this->end = 'inf'; } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_LE_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 1; $this->start = '-inf'; $this->end = new VNagValueUomPair($x); } else { throw new VNagException(VNagLang::$illegalSingleValueBehavior); } } if (is_null($this->start)) { throw new VNagInvalidRangeException(VNagLang::$invalid_start_value); } if (is_null($this->end)) { throw new VNagInvalidRangeException(VNagLang::$invalid_end_value); } if (($this->start instanceof VNagValueUomPair) && ($this->end instanceof VNagValueUomPair) && (VNagValueUomPair::compare($this->start,$this->end) > 0)) { throw new VNagInvalidRangeException(VNagLang::$start_is_greater_than_end); } } public function __toString() { $ret = ''; if ($this->warnInsideRange) { $ret = '@'; } if ($this->start === '-inf') { $ret .= '~'; } else { $ret .= $this->start; } $ret .= ':'; if ($this->end !== 'inf') { $ret .= $this->end; } return $ret; } public function checkAlert($values) { $compatibleCount = 0; if (!is_array($values)) $values = array($values); foreach ($values as $value) { if (!($value instanceof VNagValueUomPair)) $value = new VNagValueUomPair($value); assert(($this->start === '-inf') || ($this->start instanceof VNagValueUomPair)); assert(($this->end === 'inf' ) || ($this->end instanceof VNagValueUomPair)); if (($this->start !== '-inf') && (!$this->start->compatibleWith($value))) continue; if (($this->end !== 'inf') && (!$this->end->compatibleWith($value))) continue; $compatibleCount++; if ($this->warnInsideRange) { return (($this->start === '-inf') || (VNagValueUomPair::compare($value,$this->start) >= 0)) && (($this->end === 'inf') || (VNagValueUomPair::compare($value,$this->end) <= 0)); } else { return (($this->start !== '-inf') && (VNagValueUomPair::compare($value,$this->start) < 0)) || (($this->end !== 'inf') && (VNagValueUomPair::compare($value,$this->end) > 0)); } } if ((count($values) > 0) and ($compatibleCount == 0)) { throw new VNagNoCompatibleRangeUomFoundException(VNagLang::$no_compatible_range_uom_found); } return false; } } class VNagValueUomPair { protected $value; protected $uom; public $roundTo = -1; public function isRelative() { return $this->uom === '%'; } public function getValue() { return $this->value; } public function getUom() { return $this->uom; } public function __toString() { if ($this->roundTo == -1) { return $this->value.$this->uom; } else { return round($this->value,$this->roundTo).$this->uom; } } public function __construct($str) { $m = array(); if (!preg_match('/^([\d\.]+)(.*)$/ism', $str, $m)) { throw new VNagValueUomPairSyntaxException($str); } $this->value = $m[1]; $this->uom = isset($m[2]) ? $m[2] : ''; if (!self::isKnownUOM($this->uom)) { throw new VNagUnknownUomException($this->uom); } } public static function isKnownUOM(string $uom) { $no_unit = ($uom === ''); $seconds = ($uom === 's') || ($uom === 'ms') || ($uom === 'us'); $percentage = ($uom === '%'); $bytes = ($uom === 'B') || ($uom === 'KB') || ($uom === 'MB') || ($uom === 'GB') || ($uom === 'TB'); $counter = ($uom === 'c'); return ($no_unit || $seconds || $percentage || $bytes || $counter); } public function normalize($target=null) { $res = clone $this; if ($res->uom === 'ms') { $res->uom = 's'; $res->value /= 1000; } if ($res->uom === 'us') { $res->uom = 's'; $res->value /= 1000 * 1000; } if ($res->uom === 'B') { $res->uom = 'MB'; $res->value /= 1024 * 1024; } if ($res->uom === 'KB') { $res->uom = 'MB'; $res->value /= 1024; } if ($res->uom === 'GB') { $res->uom = 'MB'; $res->value *= 1024; } if ($res->uom === 'TB') { $res->uom = 'MB'; $res->value *= 1024 * 1024; } if ($res->uom === 'c') { $res->uom = ''; } if (!is_null($target)) { if ($res->uom == 'MB') { if ($target == 'B') { $res->uom = 'B'; $res->value *= 1024 * 1024; } else if ($target == 'KB') { $res->uom = 'KB'; $res->value *= 1024; } else if ($target == 'MB') { $res->uom = 'MB'; $res->value *= 1; } else if ($target == 'GB') { $res->uom = 'GB'; $res->value /= 1024; } else if ($target == 'TB') { $res->uom = 'TB'; $res->value /= 1024 * 1024; } else { throw new VNagUomConvertException($res->uom, $target); } } else if ($res->uom == 's') { if ($target == 's') { $res->uom = 's'; $res->value /= 1; } else if ($target == 'ms') { $res->uom = 'ms'; $res->value /= 1000; } else if ($target == 'us') { $res->uom = 'us'; $res->value /= 1000 * 1000; } else { throw new VNagUomConvertException($res->uom, $target); } } else { throw new VNagUomConvertException($res->uom, $target); } } return $res; } public function compatibleWith(VNagValueUomPair $other) { $a = $this->normalize(); $b = $other->normalize(); return ($a->uom == $b->uom); } public static function compare(VNagValueUomPair $left, VNagValueUomPair $right) { $a = $left->normalize(); $b = $right->normalize(); if ($a->uom != $b->uom) throw new VNagMixedUomsNotImplemented($a->uom, $b->uom); if ($a->value > $b->value) return 1; if ($a->value == $b->value) return 0; if ($a->value < $b->value) return -1; } } class VNagPerformanceData { protected $label; protected $value; protected $warn = null; protected $crit = null; protected $min = null; protected $max = null; public static function createByString($perfdata) { $perfdata = trim($perfdata); $ary = explode('=',$perfdata); if (count($ary) != 2) { throw new VNagInvalidPerformanceDataException(sprintf(VNagLang::$perfdata_line_invalid, $perfdata)); } $label = $ary[0]; $bry = explode(';',$ary[1]); if (substr($label,0,1) === "'") $label = substr($label, 1, strlen($label)-2); $value = $bry[0]; $warn = isset($bry[1]) ? $bry[1] : null; $crit = isset($bry[2]) ? $bry[2] : null; $min = isset($bry[3]) ? $bry[3] : null; $max = isset($bry[4]) ? $bry[4] : null; return new self($label, $value, $warn, $crit, $min, $max); } public function __construct($label, $value, $warn=null, $crit=null, $min=null, $max=null) { if (strpos($label, '=') !== false) throw new VNagInvalidPerformanceDataException(VNagLang::$perfdata_label_equal_sign_forbidden); $label = str_replace("'", "''", $label); $m = array(); if ((!_empty($min)) && (!preg_match('|^[-0-9\\.]+$|', $min, $m))) { throw new VNagInvalidPerformanceDataException(VNagLang::$perfdata_min_must_be_in_class); } if ((!_empty($max)) && (!preg_match('|^[-0-9\\.]+$|', $max, $m))) { throw new VNagInvalidPerformanceDataException(VNagLang::$perfdata_max_must_be_in_class); } $this->label = $label; $this->value = ($value == 'U') ? 'U' : new VNagValueUomPair($value); $this->warn = $warn; $this->crit = $crit; $this->min = $min; $this->max = $max; } public function __toString() { $label = $this->label; $value = $this->value; $warn = $this->warn; $crit = $this->crit; $min = $this->min; $max = $this->max; $label = str_replace("''", "'", $label); return "'$label'=$value". ';'.(is_null($warn) ? '' : $warn). ';'.(is_null($crit) ? '' : $crit). ';'.(is_null($min) ? '' : $min). ';'.(is_null($max) ? '' : $max); } } class VNagHelp { public $word_wrap_width = 80; public $argument_indent = 7; public function printUsagePage() { $usage = $this->getUsage(); if (_empty($usage)) { $usage = VNagLang::$no_syntax_defined; } return trim($usage)."\n"; } public function printVersionPage() { $out = trim($this->getNameAndVersion())."\n"; if ($this->word_wrap_width > 0) $out = wordwrap($out, $this->word_wrap_width, "\n", false); return $out; } static private function _conditionalLine($line, $terminator='', $prefix='') { if (!_empty($line)) { return trim($line).$terminator; } return ''; } public function printHelpPage() { $out = ''; $out .= self::_conditionalLine($this->getNameAndVersion(), "\n"); $out .= self::_conditionalLine($this->getCopyright(), "\n"); $out .= ($out != '') ? "\n" : ''; $out .= self::_conditionalLine($this->getShortDescription(), "\n\n\n"); $out .= self::_conditionalLine($this->getUsage(), "\n\n"); $out .= VNagLang::$options."\n"; foreach ($this->options as $argObj) { $out .= $this->printArgumentHelp($argObj); } $out .= self::_conditionalLine($this->getFootNotes(), "\n\n", "\n"); if ($this->word_wrap_width > 0) $out = wordwrap($out, $this->word_wrap_width, "\n", false); return $out; } protected $options = array(); protected function _addOption($argObj) { $this->options[] = $argObj; } protected function printArgumentHelp($argObj) { $identifiers = array(); $shortopt = $argObj->getShortopt(); if (!_empty($shortopt)) $identifiers[] = '-'.$shortopt; $longopts = $argObj->getLongopts(); if (!is_null($longopts)) { foreach ($longopts as $longopt) { if (!_empty($longopt)) $identifiers[] = '--'.$longopt; } } if (count($identifiers) == 0) return; $valueName = $argObj->getValueName(); $arginfo = ''; switch ($argObj->getValuePolicy()) { case VNagArgument::VALUE_FORBIDDEN: $arginfo = ''; break; case VNagArgument::VALUE_REQUIRED: $arginfo = '='.$valueName; break; case VNagArgument::VALUE_OPTIONAL: $arginfo = '[='.$valueName.']'; break; } $out = ''; $out .= implode(', ', $identifiers).$arginfo."\n"; $content = trim($argObj->getHelpText()); if ($this->word_wrap_width > 0) $content = wordwrap($content, $this->word_wrap_width-$this->argument_indent, "\n", false); $lines = explode("\n", $content); foreach ($lines as $line) { $out .= str_repeat(' ', $this->argument_indent).$line."\n"; } $out .= "\n"; return $out; } protected $pluginName; public function setPluginName($pluginName) { $this->pluginName = $this->replaceStuff($pluginName); } public function getPluginName() { if (_empty($this->pluginName)) { global $argv; return basename($argv[0]); } else { return $this->pluginName; } } protected $version; public function setVersion($version) { $this->version = $this->replaceStuff($version); } public function getVersion() { return $this->version; } public function getNameAndVersion() { $ret = $this->getPluginName(); if (_empty($ret)) return null; $ver = $this->getVersion(); if (!_empty($ver)) { $ret = sprintf(VNagLang::$x_version_x, $ret, $ver); } $ret = trim($ret); return $ret; } protected $copyright; public function setCopyright($copyright) { $this->copyright = $this->replaceStuff($copyright); } private function getVNagCopyright() { if (VNag::is_http_mode()) { $vts_email = 'www.viathinksoft.com'; } else { $vts_email = base64_decode('aW5mb0B2aWF0aGlua3NvZnQuZGU='); } return "VNag Framework ".VNag::VNAG_VERSION." (C) 2014-".date('Y')." ViaThinkSoft <$vts_email>"; } public function getCopyright() { if (_empty($this->copyright)) { return sprintf(VNagLang::$plugin_uses, $this->getVNagCopyright()); } else { return trim($this->copyright)."\n".sprintf(VNagLang::$uses, $this->getVNagCopyright()); } } protected $shortDescription; public function setShortDescription($shortDescription) { $this->shortDescription = $this->replaceStuff($shortDescription); } public function getShortDescription() { if (_empty($this->shortDescription)) { return null; } else { $content = $this->shortDescription; if ($this->word_wrap_width > 0) $content = wordwrap($content, $this->word_wrap_width, "\n", false); return $content; } } protected function replaceStuff($text) { global $argv; if (php_sapi_name() == 'cli') { $text = str_replace('$SCRIPTNAME$', $argv[0], $text); } else { $text = str_replace('$SCRIPTNAME$', basename($_SERVER['SCRIPT_NAME']), $text); } $text = str_replace('$CURYEAR$', date('Y'), $text); return $text; } protected $syntax; public function setSyntax($syntax) { $syntax = $this->replaceStuff($syntax); $this->syntax = $syntax; } public function getUsage() { if (_empty($this->syntax)) { return null; } else { return sprintf(VNagLang::$usage_x, $this->syntax); } } protected $footNotes; public function setFootNotes($footNotes) { $this->footNotes = $this->replaceStuff($footNotes); } public function getFootNotes() { return $this->footNotes; } } class VNagLang { public static function status($code, $statusmodel) { switch ($statusmodel) { case VNag::STATUSMODEL_SERVICE: switch ($code) { case VNag::STATUS_OK: return 'OK'; case VNag::STATUS_WARNING: return 'Warning'; case VNag::STATUS_CRITICAL: return 'Critical'; case VNag::STATUS_UNKNOWN: return 'Unknown'; default: return sprintf('Error (%d)', $code); } case VNag::STATUSMODEL_HOST: switch ($code) { case VNag::STATUS_UP: return 'Up'; case VNag::STATUS_DOWN: return 'Down'; default: return sprintf('Maintain last state (%d)', $code); } default: throw new VNagIllegalStatusModel(sprintf(self::$illegal_statusmodel, $statusmodel)); } } static $nagios_output = 'VNag-Output'; static $verbose_info = 'Verbose information'; static $status = 'Status'; static $message = 'Message'; static $performance_data = 'Performance data'; static $status_ok = 'OK'; static $status_warn = 'Warning'; static $status_critical = 'Critical'; static $status_unknown = 'Unknown'; static $status_error = 'Error'; static $unhandled_exception_without_msg = "Unhandled exception of type %s"; static $plugin_uses = 'This plugin uses %s'; static $uses = 'uses %s'; static $x_version_x = '%s, version %s'; static $argname_value = 'value'; static $argname_seconds = 'seconds'; static $query_without_expected_argument = "The argument '%s' is queried, but was not added to the list of expected arguments. Please contact the plugin author."; static $required_argument_missing = "The argument '%s' is required."; static $performance_data_invalid = 'Performance data invalid.'; static $no_standard_arguments_with_letter = "No standard argument with letter '%s' exists."; static $invalid_start_value = 'Invalid start value.'; static $invalid_end_value = 'Invalid end value.'; static $start_is_greater_than_end = 'Start is greater than end value.'; static $value_name_forbidden = "Implementation error: You may not define a value name for the argument, because the value policy is VALUE_FORBIDDEN."; static $value_name_required = "Implementation error: Please define a name for the argument (so it can be shown in the help page)."; static $illegal_shortopt = "Illegal shortopt '-%s'."; static $illegal_longopt = "Illegal longopt '--%s'."; static $illegal_valuepolicy = "valuePolicy has illegal value '%s'."; static $range_invalid_syntax = "Syntax error in range '%s'."; static $timeout_value_invalid = "Timeout value '%s' is invalid."; static $range_is_invalid = 'Range is invalid.'; static $timeout_exception = 'Timeout!'; static $perfdata_label_equal_sign_forbidden = 'Label may not contain an equal sign.'; static $perfdata_value_must_be_in_class = 'Value must be in class [-0-9.] or be \'U\' if the actual value can\'t be determined.'; static $perfdata_min_must_be_in_class = 'Min must be in class [-0-9.] or empty.'; static $perfdata_max_must_be_in_class = 'Max must be in class [-0-9.] or empty.'; static $perfdata_uom_not_recognized = 'UOM (unit of measurement) "%s" is not recognized.'; static $perfdata_mixed_uom_not_implemented = 'Mixed UOMs (%s and %s) are currently not supported.'; static $no_compatible_range_uom_found = 'Measured values are not compatible with the provided warning/critical parameter. Most likely, the UOM is incompatible.'; static $exception_x = '%s (%s)'; static $no_syntax_defined = 'The author of this plugin has not defined a syntax for this plugin.'; static $usage_x = "Usage:\n%s"; static $options = "Options:"; static $illegal_statusmodel = "Invalid statusmodel %d."; static $none = '[none]'; static $valueUomPairSyntaxError = 'Syntax error at "%s". Syntax must be Value[UOM].'; static $too_few_warning_ranges = "You have too few warning ranges (currently trying to get element %d)."; static $too_few_critical_ranges = "You have too few critical ranges (currently trying to get element %d)."; static $dataset_missing = 'Dataset missing.'; static $payload_not_base64 = 'The payload is not valid Base64.'; static $payload_not_json = 'The payload is not valid JSON.'; static $signature_missing = 'The signature is missing.'; static $signature_not_bas64 = 'The signature is not valid Base64.'; static $signature_invalid = 'The signature is invalid. The connection might have been tampered, or a different key is used.'; static $pubkey_file_not_found = "Public key file %s was not found."; static $pubkey_file_not_readable = "Public key file %s is not readable."; static $privkey_file_not_found = "Private key file %s was not found."; static $privkey_not_readable = "Private key is not readable."; static $privkey_file_not_readable = "Private key file %s is not readable."; static $signature_failed = "Signature failed."; static $perfdata_line_invalid = "Performance data line %s is invalid."; static $singlevalue_unexpected_at_symbol = 'This plugin does not allow the @-symbol at ranges for single values.'; static $illegalSingleValueBehavior = "Illegal value for 'singleValueBehavior'. Please contact the creator of the plugin."; static $dataset_encryption_no_array = 'Dataset encryption information invalid.'; static $require_password = 'This resource is protected with a password. Please provide a password.'; static $wrong_password = 'This resource is protected with a password. You have provided the wrong password, or it was changed.'; static $convert_x_y_error = 'Cannot convert from UOM %s to UOM %s.'; static $php_error = 'PHP has detected an error in the plugin. Please contact the plugin author.'; static $output_level_lowered = "Output Buffer level lowered during cbRun(). Please contact the plugin author."; static $openssl_missing = "OpenSSL is missing. Therefore, encryption and signatures are not available."; static $warning_range = 'Warning range'; static $critical_range = 'Critical range'; static $prints_version = 'Prints version'; static $verbosity_helptext = 'Verbosity -v, -vv or -vvv'; static $timeout_helptext = 'Sets timeout in seconds'; static $help_helptext = 'Prints help page'; static $prints_usage = 'Prints usage'; static $notConstructed = 'Parent constructor not called with parent::__construct().'; } function vnagErrorHandler($errorkind, $errortext, $file, $line) { global $inside_vnag_run; if (!$inside_vnag_run && VNag::is_http_mode()) { return false; } if (!(error_reporting() & $errorkind)) { return true; } if (defined('E_ERROR') && ($errorkind == E_ERROR)) $errorkind = 'Error'; if (defined('E_WARNING') && ($errorkind == E_WARNING)) $errorkind = 'Warning'; if (defined('E_PARSE') && ($errorkind == E_PARSE)) $errorkind = 'Parse'; if (defined('E_NOTICE') && ($errorkind == E_NOTICE)) $errorkind = 'Notice'; if (defined('E_CORE_ERROR') && ($errorkind == E_CORE_ERROR)) $errorkind = 'Core Error'; if (defined('E_CORE_WARNING') && ($errorkind == E_CORE_WARNING)) $errorkind = 'Core Warning'; if (defined('E_COMPILE_ERROR') && ($errorkind == E_COMPILE_ERROR)) $errorkind = 'Compile Error'; if (defined('E_COMPILE_WARNING') && ($errorkind == E_COMPILE_WARNING)) $errorkind = 'Compile Warning'; if (defined('E_USER_ERROR') && ($errorkind == E_USER_ERROR)) $errorkind = 'User Error'; if (defined('E_USER_WARNING') && ($errorkind == E_USER_WARNING)) $errorkind = 'User Warning'; if (defined('E_USER_NOTICE') && ($errorkind == E_USER_NOTICE)) $errorkind = 'User Notice'; if (defined('E_STRICT') && ($errorkind == E_STRICT)) $errorkind = 'Strict'; if (defined('E_RECOVERABLE_ERROR') && ($errorkind == E_RECOVERABLE_ERROR)) $errorkind = 'Recoverable Error'; if (defined('E_DEPRECATED') && ($errorkind == E_DEPRECATED)) $errorkind = 'Deprecated'; if (defined('E_USER_DEPRECATED') && ($errorkind == E_USER_DEPRECATED)) $errorkind = 'User Deprecated'; throw new VNagException(VNagLang::$php_error . " $errortext at $file:$line (kind $errorkind)"); } $inside_vnag_run = false; $old_error_handler = set_error_handler("vnagErrorHandler"); <?php
declare(ticks=1); class MegaRaidCheck extends VNag { private $argCmd = null; public function __construct() { parent::__construct(); if ($this->is_http_mode()) { $this->registerExpectedStandardArguments(''); } else { $this->registerExpectedStandardArguments('Vhtv'); } $this->addExpectedArgument($this->argCmd = new VNagArgument('E', 'executable', VNagArgument::VALUE_OPTIONAL, 'executable', 'The path to the MegaCli64 executable.', '/opt/MegaRAID/MegaCli/MegaCli64')); $this->getHelpManager()->setPluginName('vnag_megaraid'); $this->getHelpManager()->setVersion('2023-10-13'); $this->getHelpManager()->setShortDescription('This plugin checks the controller and disk status of a MegaRAID controller (using MegaCli64).'); $this->getHelpManager()->setCopyright('Copyright (C) 2011-$CURYEAR$ Daniel Marschall, ViaThinkSoft.'); $this->getHelpManager()->setSyntax('$SCRIPTNAME$'); $this->getHelpManager()->setFootNotes('If you encounter bugs, please contact ViaThinkSoft at www.viathinksoft.com'); } private function megacli_logical_disk_status($adapter='ALL') { $mock_file = __DIR__.'/status_ld.mock'; if (file_exists($mock_file)) { $out = explode("\n", file_get_contents($mock_file)); } else { $cmd = escapeshellcmd($this->argCmd->getValue()).' -LDInfo -Lall '.escapeshellarg('-a'.$adapter).' -NoLog'; $out = array(); exec($cmd, $out, $ec); } $drives = []; $cur_drive_id = '???'; $cur_drive_name = ''; foreach ($out as $line) { if (preg_match('@Virtual Drive: (\d+)@', $line, $m)) $cur_drive_id = $m[1]; if (preg_match('@Name\s*:([^\n]*)@', $line, $m)) $cur_drive_name = trim($m[1]); if (preg_match('@State\s*:([^\n]*)@', $line, $m)) { $drives[] = [$cur_drive_id, $cur_drive_name, trim($m[1])]; $cur_drive_id = '???'; $cur_drive_name = ''; } } $drives_ok = 0; $drives_fail = 0; foreach ($drives as list($cur_drive_id, $cur_drive_name, $cur_drive_status)) { if (strtolower($cur_drive_status) == 'offline') $status = VNag::STATUS_CRITICAL; else if (strpos($cur_drive_status, 'degraded') !== false) $status = VNag::STATUS_CRITICAL; else if (strtolower($cur_drive_status) == 'optimal') $status = VNag::STATUS_OK; else if (strtolower($cur_drive_status) == 'initialize') $status = VNag::STATUS_WARNING; else if (strtolower($cur_drive_status) == 'checkconsistency') $status = VNag::STATUS_WARNING; else $status = VNag::STATUS_UNKNOWN; if ($status == VNag::STATUS_OK) { $drives_ok++; } else { $drives_fail++; } $cur_drive_hf_name = $cur_drive_id . (!empty($cur_drive_name) ? " ($cur_drive_name)" : ""); $msg = "Logical drive $cur_drive_hf_name: $cur_drive_status"; $verbosity = $status == VNag::STATUS_OK ? VNag::VERBOSITY_ADDITIONAL_INFORMATION : VNag::VERBOSITY_SUMMARY; $this->addVerboseMessage($msg, $verbosity); $this->setStatus($status); } $drives_total = $drives_ok + $drives_fail; return "$drives_fail/$drives_total arrays with problems"; } private function megacli_smart_disk_status($adapter='ALL') { $mock_file = __DIR__.'/status_pd.mock'; if (file_exists($mock_file)) { $out = explode("\n", file_get_contents($mock_file)); } else { $cmd = escapeshellcmd($this->argCmd->getValue()).' -PDList '.escapeshellarg('-a'.$adapter).' -NoLog'; $out = array(); exec($cmd, $out, $ec); } $drives = []; $cur_drive_id = '???'; foreach ($out as $line) { if (preg_match('@Slot Number: (\d+)@', $line, $m)) $cur_drive_id = $m[1]; if (preg_match('@Drive has flagged a S.M.A.R.T alert\s*:([^\n]*)@', $line, $m)) { $drives[] = [$cur_drive_id, trim($m[1])]; $cur_drive_id = '???'; } } $drives_ok = 0; $drives_fail = 0; foreach ($drives as list($cur_drive_id, $cur_drive_status)) { if (strtolower($cur_drive_status) == 'no') $status = VNag::STATUS_OK; else $status = VNag::STATUS_CRITICAL; if ($status == VNag::STATUS_OK) { $drives_ok++; } else { $drives_fail++; } $msg = "Physical drive $cur_drive_id: SMART alert? $cur_drive_status"; $verbosity = $status == VNag::STATUS_OK ? VNag::VERBOSITY_ADDITIONAL_INFORMATION : VNag::VERBOSITY_SUMMARY; $this->addVerboseMessage($msg, $verbosity); $this->setStatus($status); } $drives_total = $drives_ok + $drives_fail; return "$drives_fail/$drives_total drives have SMART alerts"; } private function megacli_battery_status($adapter='ALL') { $mock_file = __DIR__.'/status_battery.mock'; if (file_exists($mock_file)) { $out = explode("\n", file_get_contents($mock_file)); } else { $cmd = escapeshellcmd($this->argCmd->getValue()).' -AdpBbuCmd '.escapeshellarg('-a'.$adapter).' -NoLog'; $out = array(); exec($cmd, $out, $ec); } $battery_status = '???'; foreach ($out as $line) { if (preg_match('@Battery State\s*:([^\n]*)@', $line, $m)) { $battery_status = trim($m[1]); } } if (strtolower($battery_status) == 'missing') $status = VNag::STATUS_WARNING; else if (strtolower($battery_status) == 'optimal') $status = VNag::STATUS_OK; else if (strtolower($battery_status) == 'failed') $status = VNag::STATUS_CRITICAL; else if (strtolower($battery_status) == 'learning') $status = VNag::STATUS_WARNING; else if (strpos($battery_status, 'degraded') !== false) $status = VNag::STATUS_CRITICAL; else $status = VNag::STATUS_UNKNOWN; $msg = "Battery Status: $battery_status"; $verbosity = $status == VNag::STATUS_OK ? VNag::VERBOSITY_ADDITIONAL_INFORMATION : VNag::VERBOSITY_SUMMARY; $this->addVerboseMessage($msg, $verbosity); $this->setStatus($status); return $status == VNag::STATUS_OK ? "Battery OK" : "Battery has problems"; } protected function cbRun() { $headlines = ''; $headlines .= $this->megacli_logical_disk_status() . ', '; $headlines .= $this->megacli_smart_disk_status() . ', '; $headlines .= $this->megacli_battery_status(); $this->setHeadline($headlines, true); } } <?php
declare(ticks=1); require_once __DIR__ . '/../../framework/vnag_framework.inc.php'; require_once __DIR__.'/MegaRaidCheck.class.php'; $job = new MegaRaidCheck(); $job->run(); unset($job); Ü9òúd|ôz¿°1¼w—â¸Ýû¬á”ªÏt´d»O$ä e#Ý)Pãú¨A(c•W í†À/ȁ_¯dÏ;GBMB
declare(ticks=1); require_once __DIR__ . '/../../framework/vnag_framework.inc.php'; require_once __DIR__.'/MegaRaidCheck.class.php'; $job = new MegaRaidCheck(); $job->run(); unset($job); –}~ó³ ódÝ3„hÎ9qí¼_B_¸àö(ÂU Rž¡RY•øôSB"p‹ü¿`bœê’;dãx-fåÈ~©4­!GBMB
/trunk/bin/minecraft_java_version.phar
-¤@plugins/minecraft_java_version/check_minecraft_java_version.phpsÜyï*e܊\åܤ<?php ?>
-<?php
+¤@plugins/minecraft_java_version/check_minecraft_java_version.phpsÜ» +e܊\åܤ<?php
if (!VNag::is_http_mode()) error_reporting(E_ALL); declare(ticks=1); set_time_limit(0); define('VNAG_JSONDATA_V1', 'oid:1.3.6.1.4.1.37476.2.3.1.1'); $OVERWRITE_ARGUMENTS = null; function _empty($x) { return is_null($x) || (trim($x) == ''); } abstract class VNag { const VNAG_VERSION = '2023-10-13'; const STATUS_OK = 0; const STATUS_WARNING = 1; const STATUS_CRITICAL = 2; const STATUS_UNKNOWN = 3; const STATUS_ERROR = 4; const STATUS_UP = 0; const STATUS_DOWN = 1; const STATUS_MAINTAIN = 2; const VERBOSITY_SUMMARY = 0; const VERBOSITY_ADDITIONAL_INFORMATION = 1; const VERBOSITY_CONFIGURATION_DEBUG = 2; const VERBOSITY_PLUGIN_DEBUG = 3; const MAX_VERBOSITY = self::VERBOSITY_PLUGIN_DEBUG; const STATUSMODEL_SERVICE = 0; const STATUSMODEL_HOST = 1; private $initialized = false; private $status = null; private $messages = array(); private $verbose_info = ''; private $warningRanges = array(); private $criticalRanges = array(); private $performanceDataObjects = array(); private static $exitcode = 0; private $helpObj = null; private $argHandler = null; const OUTPUT_NEVER = 0; const OUTPUT_SPECIAL = 1; const OUTPUT_NORMAL = 2; const OUTPUT_EXCEPTION = 4; const OUTPUT_ALWAYS = 7; public $http_visual_output = self::OUTPUT_ALWAYS; public $http_invisible_output = self::OUTPUT_ALWAYS; protected $html_before = ''; protected $html_after = ''; protected $statusmodel = self::STATUSMODEL_SERVICE; protected $show_status_in_headline = true; protected $default_status = self::STATUS_UNKNOWN; protected $default_warning_range = null; protected $default_critical_range = null; protected $argWarning; protected $argCritical; protected $argVersion; protected $argVerbosity; protected $argTimeout; protected $argHelp; protected $argUsage; public $id = null; protected static $http_serial_number = 0; public $privkey = null; public $privkey_password = null; public $sign_algo = null; public $pubkey = null; protected $warningSingleValueRangeBehaviors = array(self::SINGLEVALUE_RANGE_DEFAULT); protected $criticalSingleValueRangeBehaviors = array(self::SINGLEVALUE_RANGE_DEFAULT); const SINGLEVALUE_RANGE_DEFAULT = 0; const SINGLEVALUE_RANGE_VAL_GT_X_BAD = 1; const SINGLEVALUE_RANGE_VAL_GE_X_BAD = 2; const SINGLEVALUE_RANGE_VAL_LT_X_BAD = 3; const SINGLEVALUE_RANGE_VAL_LE_X_BAD = 4; public $password_out = null; public $password_in = null; public static function is_http_mode() { return php_sapi_name() !== 'cli'; } public function getHelpManager() { return $this->helpObj; } public function getArgumentHandler() { return $this->argHandler; } public function outputHTML($text, $after_visual_output=true) { if ($this->is_http_mode()) { if ($this->initialized) { if ($after_visual_output) { $this->html_after .= $text; } else { $this->html_before .= $text; } } else { echo $text; } } } protected function resetArguments() { $this->argWarning = null; $this->argCritical = null; $this->argVersion = null; $this->argVerbosity = null; $this->argTimeout = null; $this->argHelp = null; $this->argWarning = null; $this->argCritical = null; } public function registerExpectedStandardArguments($args) { $this->resetArguments(); for ($i=0; $i<strlen($args); $i++) { switch ($args[$i]) { case 'w': $this->addExpectedArgument($this->argWarning = new VNagArgument('w', 'warning', VNagArgument::VALUE_REQUIRED, VNagLang::$argname_value, VNagLang::$warning_range)); break; case 'c': $this->addExpectedArgument($this->argCritical = new VNagArgument('c', 'critical', VNagArgument::VALUE_REQUIRED, VNagLang::$argname_value, VNagLang::$critical_range)); break; case 'V': $this->addExpectedArgument($this->argVersion = new VNagArgument('V', 'version', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$prints_version)); break; case 'v': $this->addExpectedArgument($this->argVerbosity = new VNagArgument('v', 'verbose', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$verbosity_helptext)); break; case 't': $this->addExpectedArgument($this->argTimeout = new VNagArgument('t', 'timeout', VNagArgument::VALUE_REQUIRED, VNagLang::$argname_seconds, VNagLang::$timeout_helptext)); break; case 'h': $this->addExpectedArgument($this->argHelp = new VNagArgument('h', 'help', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$help_helptext)); break; default: $letter = $args[$i]; throw new VNagInvalidStandardArgument(sprintf(VNagLang::$no_standard_arguments_with_letter, $letter)); } } } public function addExpectedArgument($argObj) { $helpObjAddEntryMethod = new ReflectionMethod($this->helpObj, '_addOption'); $helpObjAddEntryMethod->setAccessible(true); $helpObjAddEntryMethod->invoke($this->helpObj, $argObj); $argHandlerAddEntryMethod = new ReflectionMethod($this->argHandler, '_addExpectedArgument'); $argHandlerAddEntryMethod->setAccessible(true); $argHandlerAddEntryMethod->invoke($this->argHandler, $argObj); } protected function createArgumentHandler() { $this->argHandler = new VNagArgumentHandler(); } protected function createHelpObject() { $this->helpObj = new VNagHelp(); } protected function checkInitialized() { if (!$this->initialized) throw new VNagFunctionCallOutsideSession(); } protected function getVerbosityLevel() { $this->checkInitialized(); if (!isset($this->argVerbosity)) { return self::VERBOSITY_SUMMARY; } else { $level = $this->argVerbosity->count(); if ($level > self::MAX_VERBOSITY) $level = self::MAX_VERBOSITY; return $level; } } public function getWarningRange($argumentNumber=0) { $this->checkInitialized(); if (!isset($this->warningRanges[$argumentNumber])) { if (!is_null($this->argWarning)) { $warning = $this->argWarning->getValue(); if (!is_null($warning)) { $vals = explode(',',$warning); foreach ($vals as $number => $val) { if (_empty($val)) { $this->warningRanges[$number] = null; } else { $singleValueBehavior = isset($this->warningSingleValueRangeBehaviors[$number]) ? $this->warningSingleValueRangeBehaviors[$number] : VNag::SINGLEVALUE_RANGE_DEFAULT; $this->warningRanges[$number] = new VNagRange($val, $singleValueBehavior); } } } else { $this->warningRanges[0] = $this->default_warning_range; } } else { return null; } } if (isset($this->warningRanges[$argumentNumber])) { return $this->warningRanges[$argumentNumber]; } else { return null; } } public function getCriticalRange($argumentNumber=0) { $this->checkInitialized(); if (!isset($this->criticalRanges[$argumentNumber])) { if (!is_null($this->argCritical)) { $critical = $this->argCritical->getValue(); if (!is_null($critical)) { $vals = explode(',',$critical); foreach ($vals as $number => $val) { $singleValueBehavior = isset($this->criticalSingleValueRangeBehaviors[$number]) ? $this->criticalSingleValueRangeBehaviors[$number] : VNag::SINGLEVALUE_RANGE_DEFAULT; $this->criticalRanges[$number] = new VNagRange($val, $singleValueBehavior); } } else { $this->criticalRanges[0] = $this->default_critical_range; } } else { return null; } } if (isset($this->criticalRanges[$argumentNumber])) { return $this->criticalRanges[$argumentNumber]; } else { return null; } } public function checkAgainstWarningRange($values, $force=true, $autostatus=true, $argumentNumber=0) { $this->checkInitialized(); if (!$this->getArgumentHandler()->isArgRegistered('w')) { throw new VNagRequiredArgumentNotRegistered('-w'); } $wr = $this->getWarningRange($argumentNumber); if (isset($wr)) { if ($wr->checkAlert($values)) { if ($autostatus) $this->setStatus(VNag::STATUS_WARNING); return true; } else { if ($autostatus) $this->setStatus(VNag::STATUS_OK); return false; } } else { if ($force) { if (($argumentNumber > 0) && (count($this->warningRanges) > 0)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$too_few_warning_ranges, $argumentNumber+1)); } else { throw new VNagRequiredArgumentMissing('-w'); } } } } public function checkAgainstCriticalRange($values, $force=true, $autostatus=true, $argumentNumber=0) { $this->checkInitialized(); if (!$this->getArgumentHandler()->isArgRegistered('c')) { throw new VNagRequiredArgumentNotRegistered('-c'); } $cr = $this->getCriticalRange($argumentNumber); if (isset($cr)) { if ($cr->checkAlert($values)) { if ($autostatus) $this->setStatus(VNag::STATUS_CRITICAL); return true; } else { if ($autostatus) $this->setStatus(VNag::STATUS_OK); return false; } } else { if ($force) { if (($argumentNumber > 0) && (count($this->warningRanges) > 0)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$too_few_critical_ranges, $argumentNumber+1)); } else { throw new VNagRequiredArgumentMissing('-c'); } } } } protected static function getBaddestExitcode($code1, $code2) { return max($code1, $code2); } public static function _shutdownHandler() { if (!self::is_http_mode()) { exit((int)self::$exitcode); } } protected function _exit($code) { self::$exitcode = $this->getBaddestExitcode($code, self::$exitcode); } private $constructed = false; function __construct() { $this->createHelpObject(); $this->createArgumentHandler(); $this->addExpectedArgument($this->argUsage = new VNagArgument('?', '', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$prints_usage)); $this->constructed = true; } function __destruct() { if (Timeouter::started()) { Timeouter::end(); } } public function run() { global $inside_vnag_run; $inside_vnag_run = true; try { if (!$this->constructed) { throw new VNagNotConstructed(VNagLang::$notConstructed); } try { $this->initialized = true; $this->html_before = ''; $this->html_after = ''; $this->setStatus(null, true); $this->messages = array(); register_shutdown_function(array($this, '_shutdownHandler')); if ($this->argHandler->illegalUsage()) { $content = $this->helpObj->printUsagePage(); $this->setStatus(VNag::STATUS_UNKNOWN); if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_visual_output & VNag::OUTPUT_SPECIAL) echo $this->writeVisualHTML($content); if ($this->http_invisible_output & VNag::OUTPUT_SPECIAL) echo $this->writeInvisibleHTML($content); echo $this->html_after; return; } else { echo $content; return $this->_exit($this->status); } } if (!is_null($this->argVersion) && ($this->argVersion->available())) { $content = $this->helpObj->printVersionPage(); $this->setStatus(VNag::STATUS_UNKNOWN); if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_visual_output & VNag::OUTPUT_SPECIAL) echo $this->writeVisualHTML($content); if ($this->http_invisible_output & VNag::OUTPUT_SPECIAL) echo $this->writeInvisibleHTML($content); echo $this->html_after; return; } else { echo $content; return $this->_exit($this->status); } } if (!is_null($this->argHelp) && ($this->argHelp->available())) { $content = $this->helpObj->printHelpPage(); $this->setStatus(VNag::STATUS_UNKNOWN); if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_visual_output & VNag::OUTPUT_SPECIAL) echo $this->writeVisualHTML($content); if ($this->http_invisible_output & VNag::OUTPUT_SPECIAL) echo $this->writeInvisibleHTML($content); echo $this->html_after; return; } else { echo $content; return $this->_exit($this->status); } } $this->getWarningRange(); $this->getCriticalRange(); if (!is_null($this->argTimeout)) { $timeout = $this->argTimeout->getValue(); if (!is_null($timeout)) { Timeouter::start($timeout); } } ob_start(); $init_ob_level = ob_get_level(); try { $this->cbRun(); if (ob_get_level() < $init_ob_level) throw new VNagImplementationErrorException(VNagLang::$output_level_lowered); } finally { while (ob_get_level() > $init_ob_level) @ob_end_clean(); } if (is_null($this->status)) $this->setStatus($this->default_status,true); $outputType = VNag::OUTPUT_NORMAL; } catch (Exception $e) { $this->handleException($e); $outputType = VNag::OUTPUT_EXCEPTION; } if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_invisible_output & $outputType) { echo $this->writeInvisibleHTML(); } if ($this->http_visual_output & $outputType) { echo $this->writeVisualHTML(); } echo $this->html_after; } else { echo $this->getNagiosConsoleText(); return $this->_exit($this->status); } Timeouter::end(); } finally { $inside_vnag_run = false; } } private function getNagiosConsoleText() { $ary_perfdata = $this->getPerformanceData(); $performancedata_first = array_shift($ary_perfdata); $performancedata_rest = implode(' ', $ary_perfdata); $status_text = VNagLang::status($this->status, $this->statusmodel); if (_empty($this->getHeadline())) { $content = $status_text; } else { if ($this->show_status_in_headline) { $content = $status_text.': '.$this->getHeadline(); } else { $content = $this->getHeadline(); } } if (!_empty($performancedata_first)) $content .= '|'.trim($performancedata_first); $content .= "\n"; if (!_empty($this->verbose_info)) { $content .= trim($this->verbose_info); } if (!_empty($performancedata_rest)) $content .= '|'.trim($performancedata_rest); $content .= "\n"; return trim($content)."\n"; } abstract protected function cbRun(); public function addPerformanceData($prefDataObj, $move_to_font=false, $verbosityLevel=VNag::VERBOSITY_SUMMARY) { $this->checkInitialized(); if ((!isset($this->argVerbosity)) && ($verbosityLevel > VNag::VERBOSITY_SUMMARY)) throw new VNagRequiredArgumentNotRegistered('-v'); if (self::getVerbosityLevel() < $verbosityLevel) return false; if ($move_to_font) { array_unshift($this->performanceDataObjects, $prefDataObj); } else { $this->performanceDataObjects[] = $prefDataObj; } return true; } public function getPerformanceData() { $this->checkInitialized(); return $this->performanceDataObjects; } public function removePerformanceData($prefDataObj) { if (($key = array_search($prefDataObj, $this->performanceDataObjects, true)) !== false) { unset($this->performanceDataObjects[$key]); return true; } else { return false; } } public function clearPerformanceData() { $this->performanceDataObjects = array(); } public function getVerboseInfo() { return $this->verbose_info; } public function clearVerboseInfo() { $this->verbose_info = ''; } private function writeVisualHTML($special_content=null) { if (!_empty($special_content)) { $content = $special_content; } else { $content = strtoupper(VNagLang::$status.': '.VNagLang::status($this->status, $this->statusmodel))."\n\n"; $content .= strtoupper(VNagLang::$message).":\n"; $status_text = VNagLang::status($this->status, $this->statusmodel); if (_empty($this->getHeadline())) { $content .= $status_text; } else { if ($this->show_status_in_headline) { $content .= $status_text.': '.trim($this->getHeadline()); } else { $content .= trim($this->getHeadline()); } } $content .= "\n\n"; if (!_empty($this->verbose_info)) { $content .= strtoupper(VNagLang::$verbose_info).":\n".trim($this->verbose_info)."\n\n"; } $perfdata = $this->getPerformanceData(); if (count($perfdata) > 0) { $content .= strtoupper(VNagLang::$performance_data).":\n"; foreach ($perfdata as $pd) { $content .= trim($pd)."\n"; } $content .= "\n"; } } $colorinfo = ''; $status = $this->getStatus(); if ($status == VNag::STATUS_OK) $colorinfo = ' style="background-color:green;color:white;font-weight:bold"'; else if ($status == VNag::STATUS_WARNING) $colorinfo = ' style="background-color:yellow;color:black;font-weight:bold"'; else if ($status == VNag::STATUS_CRITICAL) $colorinfo = ' style="background-color:red;color:white;font-weight:bold"'; else if ($status == VNag::STATUS_ERROR) $colorinfo = ' style="background-color:purple;color:white;font-weight:bold"'; else $colorinfo = ' style="background-color:lightgray;color:black;font-weight:bold"'; $html_content = trim($content); $html_content = htmlentities($html_content); $html_content = str_replace(' ', '&nbsp;', $html_content); $html_content = nl2br($html_content); return '<table border="1" cellspacing="2" cellpadding="2" style="width:100%" class="vnag_table">'. '<tr'.$colorinfo.' class="vnag_title_row">'. '<td>'.VNagLang::$nagios_output.'</td>'. '</tr>'. '<tr class="vnag_message_row">'. '<td><code>'. $html_content. '</code></td>'. '</tr>'. '</table>'; } protected function readInvisibleHTML($html) { $this->checkInitialized(); $doc = new DOMDocument(); @$doc->loadHTML($html); $tags = $doc->getElementsByTagName('script'); foreach ($tags as $tag) { $type = $tag->getAttribute('type'); if ($type !== 'application/json') continue; $json = $tag->nodeValue; if (!$json) continue; $data = @json_decode($json,true); if (!is_array($data)) continue; if (!isset($data['type'])) continue; if ($data['type'] === VNAG_JSONDATA_V1) { if (!isset($data['datasets'])) throw new VNagWebInfoException(VNagLang::$dataset_missing); foreach ($data['datasets'] as $dataset) { $payload = base64_decode($dataset['payload']); if (!$payload) { throw new VNagWebInfoException(VNagLang::$payload_not_base64); } if (isset($dataset['encryption'])) { $cryptInfo = $dataset['encryption']; if (!is_array($cryptInfo)) { throw new VNagWebInfoException(VNagLang::$dataset_encryption_no_array); } $password = is_null($this->password_in) ? '' : $this->password_in; $salt = base64_decode($cryptInfo['salt']); if ($cryptInfo['hash'] != hash('sha256',$salt.$password)) { if ($password == '') { throw new VNagWebInfoException(VNagLang::$require_password); } else { throw new VNagWebInfoException(VNagLang::$wrong_password); } } if (!function_exists('openssl_decrypt')) { throw new VNagException(VNagLang::$openssl_missing); } $payload = openssl_decrypt($payload, $cryptInfo['method'], $password, 0, $cryptInfo['iv']); } if (!is_null($this->pubkey) && ($this->pubkey !== '')) { if (substr($this->pubkey,0,3) === '---') { $public_key = $this->pubkey; } else { if (!file_exists($this->pubkey)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$pubkey_file_not_found, $this->pubkey)); } $public_key = @file_get_contents($this->pubkey); if (!$public_key) { throw new VNagPublicKeyException(sprintf(VNagLang::$pubkey_file_not_readable, $this->pubkey)); } } if (!isset($dataset['signature'])) { throw new VNagSignatureException(VNagLang::$signature_missing); } $signature = base64_decode($dataset['signature']); if (!$signature) { throw new VNagSignatureException(VNagLang::$signature_not_bas64); } if (!function_exists('openssl_verify')) { throw new VNagException(VNagLang::$openssl_missing); } $sign_algo = is_null($this->sign_algo) ? OPENSSL_ALGO_SHA256 : $this->sign_algo; if (!openssl_verify($payload, $signature, $public_key, $sign_algo)) { throw new VNagSignatureException(VNagLang::$signature_invalid); } } $payload = @json_decode($payload,true); if (!$payload) { throw new VNagWebInfoException(VNagLang::$payload_not_json); } if ($payload['id'] == $this->id) { return $payload; } } } } return null; } private function getNextMonitorID($peek=false) { $result = is_null($this->id) ? self::$http_serial_number : $this->id; if (!$peek) { $this->id = null; self::$http_serial_number++; } return $result; } private function writeInvisibleHTML($special_content=null) { $payload['id'] = $this->getNextMonitorID(); $payload['status'] = $this->getStatus(); if (!_empty($special_content)) { $payload['text'] = $special_content; } else { $payload['headline'] = $this->getHeadline(); $payload['verbose_info'] = $this->verbose_info; $payload['performance_data'] = array(); foreach ($this->performanceDataObjects as $perfdata) { $payload['performance_data'][] = (string)$perfdata; } } $payload = json_encode($payload); $dataset = array(); if (!is_null($this->privkey) && ($this->privkey !== '')) { if (!function_exists('openssl_pkey_get_private') || !function_exists('openssl_sign')) { throw new VNagException(VNagLang::$openssl_missing); } if (substr($this->privkey,0,3) === '---') { $pkeyid = @openssl_pkey_get_private($this->privkey, $this->privkey_password); if (!$pkeyid) { throw new VNagPrivateKeyException(sprintf(VNagLang::$privkey_not_readable)); } } else { if (!file_exists($this->privkey)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$privkey_file_not_found, $this->privkey)); } $pkeyid = @openssl_pkey_get_private('file://'.$this->privkey, $this->privkey_password); if (!$pkeyid) { throw new VNagPrivateKeyException(sprintf(VNagLang::$privkey_file_not_readable, $this->privkey)); } } $signature = ''; $sign_algo = is_null($this->sign_algo) ? OPENSSL_ALGO_SHA256 : $this->sign_algo; if (@openssl_sign($payload, $signature, $pkeyid, $sign_algo)) { if (version_compare(PHP_VERSION, '8.0.0') < 0) { openssl_free_key($pkeyid); } $dataset['signature'] = base64_encode($signature); } else { throw new VNagPrivateKeyException(sprintf(VNagLang::$signature_failed)); } } if (!is_null($this->password_out) && ($this->password_out !== '')) { if (!function_exists('openssl_encrypt')) { throw new VNagException(VNagLang::$openssl_missing); } $password = $this->password_out; $method = 'aes-256-ofb'; $iv = substr(hash('sha256', openssl_random_pseudo_bytes(32)), 0, 16); $salt = openssl_random_pseudo_bytes(32); $cryptInfo = array(); $cryptInfo['method'] = $method; $cryptInfo['iv'] = $iv; $cryptInfo['salt'] = base64_encode($salt); $cryptInfo['hash'] = hash('sha256', $salt.$password); $payload = openssl_encrypt($payload, $method, $password, 0, $iv); $dataset['encryption'] = $cryptInfo; } $dataset['payload'] = base64_encode($payload); $json = array(); $json['type'] = VNAG_JSONDATA_V1; $json['datasets'] = array($dataset); return '<script type="application/json">'. json_encode($json). '</script>'; } protected function appendHeadline($msg) { $this->checkInitialized(); if (_empty($msg)) return false; $this->messages[] = $msg; return true; } protected function changeHeadline($msg) { $this->checkInitialized(); if (_empty($msg)) { $this->messages = array(); } else { $this->messages = array($msg); } return true; } public function setHeadline($msg, $append=false, $verbosityLevel=VNag::VERBOSITY_SUMMARY) { $this->checkInitialized(); if ((!isset($this->argVerbosity)) && ($verbosityLevel > VNag::VERBOSITY_SUMMARY)) throw new VNagRequiredArgumentNotRegistered('-v'); if (self::getVerbosityLevel() < $verbosityLevel) $msg = ''; if ($append) { return $this->appendHeadline($msg); } else { return $this->changeHeadline($msg); } } public function getHeadline() { $this->checkInitialized(); return implode(', ', $this->messages); } public function addVerboseMessage($msg, $verbosityLevel=VNag::VERBOSITY_SUMMARY) { $this->checkInitialized(); if (self::getVerbosityLevel() >= $verbosityLevel) { $this->verbose_info .= $msg."\n"; } } public function setStatus($status, $force=false) { $this->checkInitialized(); if (($force) || is_null($this->status) || ($status > $this->status)) { $this->status = $status; } } public function getStatus() { $this->checkInitialized(); return $this->status; } protected static function exceptionText($exception) { $class = get_class($exception); $msg = $exception->getMessage(); if (!_empty($msg)) { return sprintf(VNagLang::$exception_x, $msg, $class); } else { return sprintf(VNagLang::$unhandled_exception_without_msg, $class); } } protected function handleException($exception) { $this->checkInitialized(); if (!VNag::is_http_mode()) { while (ob_get_level() > 0) @ob_end_clean(); } $this->clearVerboseInfo(); $this->clearPerformanceData(); if ($exception instanceof VNagException) { $this->setStatus($exception->getStatus()); } else { $this->setStatus(self::STATUS_ERROR); } $this->setHeadline($this->exceptionText($exception), false); if ($exception instanceof VNagImplementationErrorException) { $this->addVerboseMessage($exception->getTraceAsString(), VNag::VERBOSITY_SUMMARY); } else { if (isset($this->argVerbosity)) { $this->addVerboseMessage($exception->getTraceAsString(), VNag::VERBOSITY_ADDITIONAL_INFORMATION); } else { } } } protected function get_cache_dir() { $homedir = @getenv('HOME'); if ($homedir && is_dir($homedir)) { $try = "$homedir/.vnag/cache"; if (is_dir($try)) return $try; if (@mkdir($try,0777,true)) return $try; } $user = posix_getpwuid(posix_geteuid()); if (isset($user['dir']) && is_dir($user['dir'])) { $homedir = $user['dir']; $try = "$homedir/.vnag/cache"; if (is_dir($try)) return $try; if (@mkdir($try,0777,true)) return $try; } if (isset($user['name']) && is_dir($user['name'])) { $username = $user['name']; $try = "/tmp/vnag/cache"; if (is_dir($try)) return $try; if (@mkdir($try,0777,true)) return $try; } throw new VNagException("Cannot get cache dir"); } protected function url_get_contents($url, $max_cache_time=1*60*60, $context=null) { $cache_file = $this->get_cache_dir().'/'.hash('sha256',$url); if (file_exists($cache_file) && (time()-filemtime($cache_file) < $max_cache_time)) { $cont = @file_get_contents($cache_file); if ($cont === false) throw new Exception("Failed to get contents from $cache_file"); } else { $options = array( 'http'=>array( 'method'=>"GET", 'header'=>"Accept-language: en\r\n" . "User-Agent: Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B334b Safari/531.21.102011-10-16 20:23:10\r\n" ) ); if (is_null($context)) $context = stream_context_create($options); $cont = @file_get_contents($url, false, $context); if ($cont === false) throw new Exception("Failed to get contents from $url"); file_put_contents($cache_file, $cont); } return $cont; } } class VNagException extends Exception { public function getStatus() { return VNag::STATUS_ERROR; } } class VNagTimeoutException extends VNagException {} class VNagWebInfoException extends VNagException {} class VNagSignatureException extends VNagException {} class VNagPublicKeyException extends VNagException {} class VNagPrivateKeyException extends VNagException {} class VNagInvalidArgumentException extends VNagException { public function getStatus() { return VNag::STATUS_UNKNOWN; } } class VNagValueUomPairSyntaxException extends VNagInvalidArgumentException { public function __construct($str) { $e_msg = sprintf(VNagLang::$valueUomPairSyntaxError, $str); parent::__construct($e_msg); } } class VNagInvalidTimeoutException extends VNagInvalidArgumentException {} class VNagInvalidRangeException extends VNagInvalidArgumentException { public function __construct($msg) { $e_msg = VNagLang::$range_is_invalid; if (!_empty($msg)) $e_msg .= ': '.trim($msg); parent::__construct($e_msg); } } class VNagInvalidShortOpt extends VNagImplementationErrorException {} class VNagInvalidLongOpt extends VNagImplementationErrorException {} class VNagInvalidValuePolicy extends VNagImplementationErrorException {} class VNagIllegalStatusModel extends VNagImplementationErrorException {} class VNagNotConstructed extends VNagImplementationErrorException {} class VNagImplementationErrorException extends VNagException {} class VNagInvalidStandardArgument extends VNagImplementationErrorException {} class VNagFunctionCallOutsideSession extends VNagImplementationErrorException {} class VNagIllegalArgumentValuesException extends VNagImplementationErrorException {} class VNagRequiredArgumentNotRegistered extends VNagImplementationErrorException { public function __construct($required_argument) { $e_msg = sprintf(VNagLang::$query_without_expected_argument, $required_argument); parent::__construct($e_msg); } } class VNagRequiredArgumentMissing extends VNagInvalidArgumentException { public function __construct($required_argument) { $e_msg = sprintf(VNagLang::$required_argument_missing, $required_argument); parent::__construct($e_msg); } } class VNagUnknownUomException extends VNagInvalidArgumentException { public function __construct($uom) { $e_msg = sprintf(VNagLang::$perfdata_uom_not_recognized, $uom); parent::__construct($e_msg); } } class VNagNoCompatibleRangeUomFoundException extends VNagException {} class VNagMixedUomsNotImplemented extends VNagInvalidArgumentException { public function __construct($uom1, $uom2) { if (_empty($uom1)) $uom1 = VNagLang::$none; if (_empty($uom2)) $uom2 = VNagLang::$none; $e_msg = sprintf(VNagLang::$perfdata_mixed_uom_not_implemented, $uom1, $uom2); parent::__construct($e_msg); } } class VNagUomConvertException extends VNagInvalidArgumentException { public function __construct($uom1, $uom2) { if (_empty($uom1)) $uom1 = VNagLang::$none; if (_empty($uom2)) $uom2 = VNagLang::$none; $e_msg = sprintf(VNagLang::$convert_x_y_error, $uom1, $uom2); parent::__construct($e_msg); } } class VNagInvalidPerformanceDataException extends VNagInvalidArgumentException { public function __construct($msg) { $e_msg = VNagLang::$performance_data_invalid; if (!_empty($msg)) $e_msg .= ': '.trim($msg); parent::__construct($e_msg); } } class Timeouter { private static $start_time = false; private static $timeout; private static $fired = false; private static $registered = false; private function __construct() { } public static function start($timeout) { if (!is_numeric($timeout) || ($timeout <= 0)) { throw new VNagInvalidTimeoutException(sprintf(VNagLang::$timeout_value_invalid, $timeout)); } self::$start_time = microtime(true); self::$timeout = (float) $timeout; self::$fired = false; if (!self::$registered) { self::$registered = true; register_tick_function(array('Timeouter', 'tick')); } } public static function started() { return self::$registered; } public static function end() { if (self::$registered) { unregister_tick_function(array('Timeouter', 'tick')); self::$registered = false; } } public static function tick() { if ((!self::$fired) && ((microtime(true) - self::$start_time) > self::$timeout)) { self::$fired = true; throw new VNagTimeoutException(VNagLang::$timeout_exception); } } } class VNagArgument { const VALUE_FORBIDDEN = 0; const VALUE_REQUIRED = 1; const VALUE_OPTIONAL = 2; protected $shortopt; protected $longopts; protected $valuePolicy; protected $valueName; protected $helpText; protected $defaultValue = null; protected static $all_short = ''; protected static $all_long = array(); public function getShortOpt() { return $this->shortopt; } public function getLongOpts() { return $this->longopts; } public function getValuePolicy() { return $this->valuePolicy; } public function getValueName() { return $this->valueName; } public function getHelpText() { return $this->helpText; } static private function validateShortOpt($shortopt) { $m = array(); return preg_match('@^[a-zA-Z0-9\\+\\-\\?]$@', $shortopt, $m); } static private function validateLongOpt($longopt) { $m = array(); return preg_match('@^[a-zA-Z0-9\\+\\-\\?]+$@', $longopt, $m); } public function __construct($shortopt, $longopts, $valuePolicy, $valueName, $helpText, $defaultValue=null) { switch ($valuePolicy) { case VNagArgument::VALUE_FORBIDDEN: if (!_empty($valueName)) { throw new VNagImplementationErrorException(sprintf(VNagLang::$value_name_forbidden)); } break; case VNagArgument::VALUE_REQUIRED: if (_empty($valueName)) { throw new VNagImplementationErrorException(sprintf(VNagLang::$value_name_required)); } break; case VNagArgument::VALUE_OPTIONAL: if (_empty($valueName)) { throw new VNagImplementationErrorException(sprintf(VNagLang::$value_name_required)); } break; default: throw new VNagInvalidValuePolicy(sprintf(VNagLang::$illegal_valuepolicy, $valuePolicy)); } if (!_empty($shortopt)) { if (!self::validateShortOpt($shortopt)) { throw new VNagInvalidShortOpt(sprintf(VNagLang::$illegal_shortopt, $shortopt)); } } if (is_array($longopts)) { foreach ($longopts as $longopt) { if (!self::validateLongOpt($longopt)) { throw new VNagInvalidLongOpt(sprintf(VNagLang::$illegal_longopt, $longopt)); } } } else if (!_empty($longopts)) { if (!self::validateLongOpt($longopts)) { throw new VNagInvalidLongOpt(sprintf(VNagLang::$illegal_longopt, $longopts)); } $longopts = array($longopts); } else { $longopts = array(); } switch ($valuePolicy) { case VNagArgument::VALUE_FORBIDDEN: $policyApdx = ''; break; case VNagArgument::VALUE_REQUIRED: $policyApdx = ':'; break; case VNagArgument::VALUE_OPTIONAL: $policyApdx = '::'; break; default: throw new VNagInvalidValuePolicy(sprintf(VNagLang::$illegal_valuepolicy, $valuePolicy)); } if ((!is_null($shortopt)) && ($shortopt != '?')) self::$all_short .= $shortopt.$policyApdx; if (is_array($longopts)) { foreach ($longopts as $longopt) { self::$all_long[] = $longopt.$policyApdx; } } $this->shortopt = $shortopt; $this->longopts = $longopts; $this->valuePolicy = $valuePolicy; $this->valueName = $valueName; $this->helpText = $helpText; $this->defaultValue = $defaultValue; } protected static function getOptions() { global $OVERWRITE_ARGUMENTS; if (!is_null($OVERWRITE_ARGUMENTS)) { return $OVERWRITE_ARGUMENTS; } else if (VNag::is_http_mode()) { return $_REQUEST; } else { return getopt(self::$all_short, self::$all_long); } } public function count() { $options = self::getOptions(); $count = 0; if (isset($options[$this->shortopt])) { if (is_array($options[$this->shortopt])) { $count += count($options[$this->shortopt]); } else { $count += 1; } } if (!is_null($this->longopts)) { foreach ($this->longopts as $longopt) { if (isset($options[$longopt])) { if (is_array($options[$longopt])) { $count += count($options[$longopt]); } else { $count += 1; } } } } return $count; } public function available() { $options = self::getOptions(); if (isset($options[$this->shortopt])) return true; if (!is_null($this->longopts)) { foreach ($this->longopts as $longopt) { if (isset($options[$longopt])) return true; } } return false; } public function require() { if (!$this->available() && is_null($this->defaultValue)) { $opt = $this->shortopt; $opt = !_empty($opt) ? '-'.$opt : (isset($this->longopts[0]) ? '--'.$this->longopts[0] : '?'); throw new VNagRequiredArgumentMissing($opt); } } public function getValue() { $options = self::getOptions(); if (isset($options[$this->shortopt])) { $x = $options[$this->shortopt]; if (is_array($x) && (count($x) <= 1)) $options[$this->shortopt] = $options[$this->shortopt][0]; return $options[$this->shortopt]; } if (!is_null($this->longopts)) { foreach ($this->longopts as $longopt) { if (isset($options[$longopt])) { $x = $options[$longopt]; if (is_array($x) && (count($x) <= 1)) $options[$longopt] = $options[$longopt][0]; return $options[$longopt]; } } } return $this->defaultValue; } } class VNagArgumentHandler { protected $expectedArgs = array(); protected function _addExpectedArgument($argObj) { if ($argObj->getShortOpt() == '?') return false; if ($argObj->getShortOpt() == '-') return false; if ($argObj->getShortOpt() == '+') return false; $this->expectedArgs[] = $argObj; return true; } public function getArgumentObj($shortopt) { foreach ($this->expectedArgs as $argObj) { if ($argObj->getShortOpt() == $shortopt) return $argObj; } return null; } public function isArgRegistered($shortopt) { return !is_null($this->getArgumentObj($shortopt)); } public function illegalUsage() { global $argv; return (isset($argv[1])) && (($argv[1] == '-?') || ($argv[1] == '/?')); } } class VNagRange { public $start; public $end; public $warnInsideRange; public function __construct($rangeDef, $singleValueBehavior=VNag::SINGLEVALUE_RANGE_DEFAULT) { $m = array(); if (!preg_match('|^(@){0,1}([^:]+)(:){0,1}(.*)$|', $rangeDef, $m)) { throw new VNagInvalidRangeException(sprintf(VNagLang::$range_invalid_syntax, $rangeDef)); } $this->warnInsideRange = $m[1] === '@'; $this->start = null; $this->end = null; if ($m[3] === ':') { if ($m[2] === '~') { $this->start = '-inf'; } else { $this->start = new VNagValueUomPair($m[2]); } if (_empty($m[4])) { $this->end = 'inf'; } else { $this->end = new VNagValueUomPair($m[4]); } } else { assert(_empty($m[4])); assert(!_empty($m[2])); $x = $m[2]; if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_DEFAULT) { $this->start = new VNagValueUomPair('0'.((new VNagValueUomPair($x))->getUom())); $this->end = new VNagValueUomPair($x); } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_GT_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 0; $this->start = '-inf'; $this->end = new VNagValueUomPair($x); } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_GE_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 1; $this->start = new VNagValueUomPair($x); $this->end = 'inf'; } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_LT_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 0; $this->start = new VNagValueUomPair($x); $this->end = 'inf'; } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_LE_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 1; $this->start = '-inf'; $this->end = new VNagValueUomPair($x); } else { throw new VNagException(VNagLang::$illegalSingleValueBehavior); } } if (is_null($this->start)) { throw new VNagInvalidRangeException(VNagLang::$invalid_start_value); } if (is_null($this->end)) { throw new VNagInvalidRangeException(VNagLang::$invalid_end_value); } if (($this->start instanceof VNagValueUomPair) && ($this->end instanceof VNagValueUomPair) && (VNagValueUomPair::compare($this->start,$this->end) > 0)) { throw new VNagInvalidRangeException(VNagLang::$start_is_greater_than_end); } } public function __toString() { $ret = ''; if ($this->warnInsideRange) { $ret = '@'; } if ($this->start === '-inf') { $ret .= '~'; } else { $ret .= $this->start; } $ret .= ':'; if ($this->end !== 'inf') { $ret .= $this->end; } return $ret; } public function checkAlert($values) { $compatibleCount = 0; if (!is_array($values)) $values = array($values); foreach ($values as $value) { if (!($value instanceof VNagValueUomPair)) $value = new VNagValueUomPair($value); assert(($this->start === '-inf') || ($this->start instanceof VNagValueUomPair)); assert(($this->end === 'inf' ) || ($this->end instanceof VNagValueUomPair)); if (($this->start !== '-inf') && (!$this->start->compatibleWith($value))) continue; if (($this->end !== 'inf') && (!$this->end->compatibleWith($value))) continue; $compatibleCount++; if ($this->warnInsideRange) { return (($this->start === '-inf') || (VNagValueUomPair::compare($value,$this->start) >= 0)) && (($this->end === 'inf') || (VNagValueUomPair::compare($value,$this->end) <= 0)); } else { return (($this->start !== '-inf') && (VNagValueUomPair::compare($value,$this->start) < 0)) || (($this->end !== 'inf') && (VNagValueUomPair::compare($value,$this->end) > 0)); } } if ((count($values) > 0) and ($compatibleCount == 0)) { throw new VNagNoCompatibleRangeUomFoundException(VNagLang::$no_compatible_range_uom_found); } return false; } } class VNagValueUomPair { protected $value; protected $uom; public $roundTo = -1; public function isRelative() { return $this->uom === '%'; } public function getValue() { return $this->value; } public function getUom() { return $this->uom; } public function __toString() { if ($this->roundTo == -1) { return $this->value.$this->uom; } else { return round($this->value,$this->roundTo).$this->uom; } } public function __construct($str) { $m = array(); if (!preg_match('/^([\d\.]+)(.*)$/ism', $str, $m)) { throw new VNagValueUomPairSyntaxException($str); } $this->value = $m[1]; $this->uom = isset($m[2]) ? $m[2] : ''; if (!self::isKnownUOM($this->uom)) { throw new VNagUnknownUomException($this->uom); } } public static function isKnownUOM(string $uom) { $no_unit = ($uom === ''); $seconds = ($uom === 's') || ($uom === 'ms') || ($uom === 'us'); $percentage = ($uom === '%'); $bytes = ($uom === 'B') || ($uom === 'KB') || ($uom === 'MB') || ($uom === 'GB') || ($uom === 'TB'); $counter = ($uom === 'c'); return ($no_unit || $seconds || $percentage || $bytes || $counter); } public function normalize($target=null) { $res = clone $this; if ($res->uom === 'ms') { $res->uom = 's'; $res->value /= 1000; } if ($res->uom === 'us') { $res->uom = 's'; $res->value /= 1000 * 1000; } if ($res->uom === 'B') { $res->uom = 'MB'; $res->value /= 1024 * 1024; } if ($res->uom === 'KB') { $res->uom = 'MB'; $res->value /= 1024; } if ($res->uom === 'GB') { $res->uom = 'MB'; $res->value *= 1024; } if ($res->uom === 'TB') { $res->uom = 'MB'; $res->value *= 1024 * 1024; } if ($res->uom === 'c') { $res->uom = ''; } if (!is_null($target)) { if ($res->uom == 'MB') { if ($target == 'B') { $res->uom = 'B'; $res->value *= 1024 * 1024; } else if ($target == 'KB') { $res->uom = 'KB'; $res->value *= 1024; } else if ($target == 'MB') { $res->uom = 'MB'; $res->value *= 1; } else if ($target == 'GB') { $res->uom = 'GB'; $res->value /= 1024; } else if ($target == 'TB') { $res->uom = 'TB'; $res->value /= 1024 * 1024; } else { throw new VNagUomConvertException($res->uom, $target); } } else if ($res->uom == 's') { if ($target == 's') { $res->uom = 's'; $res->value /= 1; } else if ($target == 'ms') { $res->uom = 'ms'; $res->value /= 1000; } else if ($target == 'us') { $res->uom = 'us'; $res->value /= 1000 * 1000; } else { throw new VNagUomConvertException($res->uom, $target); } } else { throw new VNagUomConvertException($res->uom, $target); } } return $res; } public function compatibleWith(VNagValueUomPair $other) { $a = $this->normalize(); $b = $other->normalize(); return ($a->uom == $b->uom); } public static function compare(VNagValueUomPair $left, VNagValueUomPair $right) { $a = $left->normalize(); $b = $right->normalize(); if ($a->uom != $b->uom) throw new VNagMixedUomsNotImplemented($a->uom, $b->uom); if ($a->value > $b->value) return 1; if ($a->value == $b->value) return 0; if ($a->value < $b->value) return -1; } } class VNagPerformanceData { protected $label; protected $value; protected $warn = null; protected $crit = null; protected $min = null; protected $max = null; public static function createByString($perfdata) { $perfdata = trim($perfdata); $ary = explode('=',$perfdata); if (count($ary) != 2) { throw new VNagInvalidPerformanceDataException(sprintf(VNagLang::$perfdata_line_invalid, $perfdata)); } $label = $ary[0]; $bry = explode(';',$ary[1]); if (substr($label,0,1) === "'") $label = substr($label, 1, strlen($label)-2); $value = $bry[0]; $warn = isset($bry[1]) ? $bry[1] : null; $crit = isset($bry[2]) ? $bry[2] : null; $min = isset($bry[3]) ? $bry[3] : null; $max = isset($bry[4]) ? $bry[4] : null; return new self($label, $value, $warn, $crit, $min, $max); } public function __construct($label, $value, $warn=null, $crit=null, $min=null, $max=null) { if (strpos($label, '=') !== false) throw new VNagInvalidPerformanceDataException(VNagLang::$perfdata_label_equal_sign_forbidden); $label = str_replace("'", "''", $label); $m = array(); if ((!_empty($min)) && (!preg_match('|^[-0-9\\.]+$|', $min, $m))) { throw new VNagInvalidPerformanceDataException(VNagLang::$perfdata_min_must_be_in_class); } if ((!_empty($max)) && (!preg_match('|^[-0-9\\.]+$|', $max, $m))) { throw new VNagInvalidPerformanceDataException(VNagLang::$perfdata_max_must_be_in_class); } $this->label = $label; $this->value = ($value == 'U') ? 'U' : new VNagValueUomPair($value); $this->warn = $warn; $this->crit = $crit; $this->min = $min; $this->max = $max; } public function __toString() { $label = $this->label; $value = $this->value; $warn = $this->warn; $crit = $this->crit; $min = $this->min; $max = $this->max; $label = str_replace("''", "'", $label); return "'$label'=$value". ';'.(is_null($warn) ? '' : $warn). ';'.(is_null($crit) ? '' : $crit). ';'.(is_null($min) ? '' : $min). ';'.(is_null($max) ? '' : $max); } } class VNagHelp { public $word_wrap_width = 80; public $argument_indent = 7; public function printUsagePage() { $usage = $this->getUsage(); if (_empty($usage)) { $usage = VNagLang::$no_syntax_defined; } return trim($usage)."\n"; } public function printVersionPage() { $out = trim($this->getNameAndVersion())."\n"; if ($this->word_wrap_width > 0) $out = wordwrap($out, $this->word_wrap_width, "\n", false); return $out; } static private function _conditionalLine($line, $terminator='', $prefix='') { if (!_empty($line)) { return trim($line).$terminator; } return ''; } public function printHelpPage() { $out = ''; $out .= self::_conditionalLine($this->getNameAndVersion(), "\n"); $out .= self::_conditionalLine($this->getCopyright(), "\n"); $out .= ($out != '') ? "\n" : ''; $out .= self::_conditionalLine($this->getShortDescription(), "\n\n\n"); $out .= self::_conditionalLine($this->getUsage(), "\n\n"); $out .= VNagLang::$options."\n"; foreach ($this->options as $argObj) { $out .= $this->printArgumentHelp($argObj); } $out .= self::_conditionalLine($this->getFootNotes(), "\n\n", "\n"); if ($this->word_wrap_width > 0) $out = wordwrap($out, $this->word_wrap_width, "\n", false); return $out; } protected $options = array(); protected function _addOption($argObj) { $this->options[] = $argObj; } protected function printArgumentHelp($argObj) { $identifiers = array(); $shortopt = $argObj->getShortopt(); if (!_empty($shortopt)) $identifiers[] = '-'.$shortopt; $longopts = $argObj->getLongopts(); if (!is_null($longopts)) { foreach ($longopts as $longopt) { if (!_empty($longopt)) $identifiers[] = '--'.$longopt; } } if (count($identifiers) == 0) return; $valueName = $argObj->getValueName(); $arginfo = ''; switch ($argObj->getValuePolicy()) { case VNagArgument::VALUE_FORBIDDEN: $arginfo = ''; break; case VNagArgument::VALUE_REQUIRED: $arginfo = '='.$valueName; break; case VNagArgument::VALUE_OPTIONAL: $arginfo = '[='.$valueName.']'; break; } $out = ''; $out .= implode(', ', $identifiers).$arginfo."\n"; $content = trim($argObj->getHelpText()); if ($this->word_wrap_width > 0) $content = wordwrap($content, $this->word_wrap_width-$this->argument_indent, "\n", false); $lines = explode("\n", $content); foreach ($lines as $line) { $out .= str_repeat(' ', $this->argument_indent).$line."\n"; } $out .= "\n"; return $out; } protected $pluginName; public function setPluginName($pluginName) { $this->pluginName = $this->replaceStuff($pluginName); } public function getPluginName() { if (_empty($this->pluginName)) { global $argv; return basename($argv[0]); } else { return $this->pluginName; } } protected $version; public function setVersion($version) { $this->version = $this->replaceStuff($version); } public function getVersion() { return $this->version; } public function getNameAndVersion() { $ret = $this->getPluginName(); if (_empty($ret)) return null; $ver = $this->getVersion(); if (!_empty($ver)) { $ret = sprintf(VNagLang::$x_version_x, $ret, $ver); } $ret = trim($ret); return $ret; } protected $copyright; public function setCopyright($copyright) { $this->copyright = $this->replaceStuff($copyright); } private function getVNagCopyright() { if (VNag::is_http_mode()) { $vts_email = 'www.viathinksoft.com'; } else { $vts_email = base64_decode('aW5mb0B2aWF0aGlua3NvZnQuZGU='); } return "VNag Framework ".VNag::VNAG_VERSION." (C) 2014-".date('Y')." ViaThinkSoft <$vts_email>"; } public function getCopyright() { if (_empty($this->copyright)) { return sprintf(VNagLang::$plugin_uses, $this->getVNagCopyright()); } else { return trim($this->copyright)."\n".sprintf(VNagLang::$uses, $this->getVNagCopyright()); } } protected $shortDescription; public function setShortDescription($shortDescription) { $this->shortDescription = $this->replaceStuff($shortDescription); } public function getShortDescription() { if (_empty($this->shortDescription)) { return null; } else { $content = $this->shortDescription; if ($this->word_wrap_width > 0) $content = wordwrap($content, $this->word_wrap_width, "\n", false); return $content; } } protected function replaceStuff($text) { global $argv; if (php_sapi_name() == 'cli') { $text = str_replace('$SCRIPTNAME$', $argv[0], $text); } else { $text = str_replace('$SCRIPTNAME$', basename($_SERVER['SCRIPT_NAME']), $text); } $text = str_replace('$CURYEAR$', date('Y'), $text); return $text; } protected $syntax; public function setSyntax($syntax) { $syntax = $this->replaceStuff($syntax); $this->syntax = $syntax; } public function getUsage() { if (_empty($this->syntax)) { return null; } else { return sprintf(VNagLang::$usage_x, $this->syntax); } } protected $footNotes; public function setFootNotes($footNotes) { $this->footNotes = $this->replaceStuff($footNotes); } public function getFootNotes() { return $this->footNotes; } } class VNagLang { public static function status($code, $statusmodel) { switch ($statusmodel) { case VNag::STATUSMODEL_SERVICE: switch ($code) { case VNag::STATUS_OK: return 'OK'; case VNag::STATUS_WARNING: return 'Warning'; case VNag::STATUS_CRITICAL: return 'Critical'; case VNag::STATUS_UNKNOWN: return 'Unknown'; default: return sprintf('Error (%d)', $code); } case VNag::STATUSMODEL_HOST: switch ($code) { case VNag::STATUS_UP: return 'Up'; case VNag::STATUS_DOWN: return 'Down'; default: return sprintf('Maintain last state (%d)', $code); } default: throw new VNagIllegalStatusModel(sprintf(self::$illegal_statusmodel, $statusmodel)); } } static $nagios_output = 'VNag-Output'; static $verbose_info = 'Verbose information'; static $status = 'Status'; static $message = 'Message'; static $performance_data = 'Performance data'; static $status_ok = 'OK'; static $status_warn = 'Warning'; static $status_critical = 'Critical'; static $status_unknown = 'Unknown'; static $status_error = 'Error'; static $unhandled_exception_without_msg = "Unhandled exception of type %s"; static $plugin_uses = 'This plugin uses %s'; static $uses = 'uses %s'; static $x_version_x = '%s, version %s'; static $argname_value = 'value'; static $argname_seconds = 'seconds'; static $query_without_expected_argument = "The argument '%s' is queried, but was not added to the list of expected arguments. Please contact the plugin author."; static $required_argument_missing = "The argument '%s' is required."; static $performance_data_invalid = 'Performance data invalid.'; static $no_standard_arguments_with_letter = "No standard argument with letter '%s' exists."; static $invalid_start_value = 'Invalid start value.'; static $invalid_end_value = 'Invalid end value.'; static $start_is_greater_than_end = 'Start is greater than end value.'; static $value_name_forbidden = "Implementation error: You may not define a value name for the argument, because the value policy is VALUE_FORBIDDEN."; static $value_name_required = "Implementation error: Please define a name for the argument (so it can be shown in the help page)."; static $illegal_shortopt = "Illegal shortopt '-%s'."; static $illegal_longopt = "Illegal longopt '--%s'."; static $illegal_valuepolicy = "valuePolicy has illegal value '%s'."; static $range_invalid_syntax = "Syntax error in range '%s'."; static $timeout_value_invalid = "Timeout value '%s' is invalid."; static $range_is_invalid = 'Range is invalid.'; static $timeout_exception = 'Timeout!'; static $perfdata_label_equal_sign_forbidden = 'Label may not contain an equal sign.'; static $perfdata_value_must_be_in_class = 'Value must be in class [-0-9.] or be \'U\' if the actual value can\'t be determined.'; static $perfdata_min_must_be_in_class = 'Min must be in class [-0-9.] or empty.'; static $perfdata_max_must_be_in_class = 'Max must be in class [-0-9.] or empty.'; static $perfdata_uom_not_recognized = 'UOM (unit of measurement) "%s" is not recognized.'; static $perfdata_mixed_uom_not_implemented = 'Mixed UOMs (%s and %s) are currently not supported.'; static $no_compatible_range_uom_found = 'Measured values are not compatible with the provided warning/critical parameter. Most likely, the UOM is incompatible.'; static $exception_x = '%s (%s)'; static $no_syntax_defined = 'The author of this plugin has not defined a syntax for this plugin.'; static $usage_x = "Usage:\n%s"; static $options = "Options:"; static $illegal_statusmodel = "Invalid statusmodel %d."; static $none = '[none]'; static $valueUomPairSyntaxError = 'Syntax error at "%s". Syntax must be Value[UOM].'; static $too_few_warning_ranges = "You have too few warning ranges (currently trying to get element %d)."; static $too_few_critical_ranges = "You have too few critical ranges (currently trying to get element %d)."; static $dataset_missing = 'Dataset missing.'; static $payload_not_base64 = 'The payload is not valid Base64.'; static $payload_not_json = 'The payload is not valid JSON.'; static $signature_missing = 'The signature is missing.'; static $signature_not_bas64 = 'The signature is not valid Base64.'; static $signature_invalid = 'The signature is invalid. The connection might have been tampered, or a different key is used.'; static $pubkey_file_not_found = "Public key file %s was not found."; static $pubkey_file_not_readable = "Public key file %s is not readable."; static $privkey_file_not_found = "Private key file %s was not found."; static $privkey_not_readable = "Private key is not readable."; static $privkey_file_not_readable = "Private key file %s is not readable."; static $signature_failed = "Signature failed."; static $perfdata_line_invalid = "Performance data line %s is invalid."; static $singlevalue_unexpected_at_symbol = 'This plugin does not allow the @-symbol at ranges for single values.'; static $illegalSingleValueBehavior = "Illegal value for 'singleValueBehavior'. Please contact the creator of the plugin."; static $dataset_encryption_no_array = 'Dataset encryption information invalid.'; static $require_password = 'This resource is protected with a password. Please provide a password.'; static $wrong_password = 'This resource is protected with a password. You have provided the wrong password, or it was changed.'; static $convert_x_y_error = 'Cannot convert from UOM %s to UOM %s.'; static $php_error = 'PHP has detected an error in the plugin. Please contact the plugin author.'; static $output_level_lowered = "Output Buffer level lowered during cbRun(). Please contact the plugin author."; static $openssl_missing = "OpenSSL is missing. Therefore, encryption and signatures are not available."; static $warning_range = 'Warning range'; static $critical_range = 'Critical range'; static $prints_version = 'Prints version'; static $verbosity_helptext = 'Verbosity -v, -vv or -vvv'; static $timeout_helptext = 'Sets timeout in seconds'; static $help_helptext = 'Prints help page'; static $prints_usage = 'Prints usage'; static $notConstructed = 'Parent constructor not called with parent::__construct().'; } function vnagErrorHandler($errorkind, $errortext, $file, $line) { global $inside_vnag_run; if (!$inside_vnag_run && VNag::is_http_mode()) { return false; } if (!(error_reporting() & $errorkind)) { return true; } if (defined('E_ERROR') && ($errorkind == E_ERROR)) $errorkind = 'Error'; if (defined('E_WARNING') && ($errorkind == E_WARNING)) $errorkind = 'Warning'; if (defined('E_PARSE') && ($errorkind == E_PARSE)) $errorkind = 'Parse'; if (defined('E_NOTICE') && ($errorkind == E_NOTICE)) $errorkind = 'Notice'; if (defined('E_CORE_ERROR') && ($errorkind == E_CORE_ERROR)) $errorkind = 'Core Error'; if (defined('E_CORE_WARNING') && ($errorkind == E_CORE_WARNING)) $errorkind = 'Core Warning'; if (defined('E_COMPILE_ERROR') && ($errorkind == E_COMPILE_ERROR)) $errorkind = 'Compile Error'; if (defined('E_COMPILE_WARNING') && ($errorkind == E_COMPILE_WARNING)) $errorkind = 'Compile Warning'; if (defined('E_USER_ERROR') && ($errorkind == E_USER_ERROR)) $errorkind = 'User Error'; if (defined('E_USER_WARNING') && ($errorkind == E_USER_WARNING)) $errorkind = 'User Warning'; if (defined('E_USER_NOTICE') && ($errorkind == E_USER_NOTICE)) $errorkind = 'User Notice'; if (defined('E_STRICT') && ($errorkind == E_STRICT)) $errorkind = 'Strict'; if (defined('E_RECOVERABLE_ERROR') && ($errorkind == E_RECOVERABLE_ERROR)) $errorkind = 'Recoverable Error'; if (defined('E_DEPRECATED') && ($errorkind == E_DEPRECATED)) $errorkind = 'Deprecated'; if (defined('E_USER_DEPRECATED') && ($errorkind == E_USER_DEPRECATED)) $errorkind = 'User Deprecated'; throw new VNagException(VNagLang::$php_error . " $errortext at $file:$line (kind $errorkind)"); } $inside_vnag_run = false; $old_error_handler = set_error_handler("vnagErrorHandler"); <?php
declare(ticks=1); class MinecraftJavaVersionCheck extends VNag { protected $argSystemDir = null; public function __construct() { parent::__construct(); $this->registerExpectedStandardArguments('Vvht'); $this->getHelpManager()->setPluginName('check_minecraft_java_version'); $this->getHelpManager()->setVersion('2023-10-13'); $this->getHelpManager()->setShortDescription('This plugin checks if a local Minecraft for Java server has the latest version installed.'); $this->getHelpManager()->setCopyright('Copyright (C) 2011-$CURYEAR$ Daniel Marschall, ViaThinkSoft.'); $this->getHelpManager()->setSyntax('$SCRIPTNAME$ [-d <directory>]'); $this->getHelpManager()->setFootNotes('If you encounter bugs, please contact ViaThinkSoft at www.viathinksoft.com'); $this->addExpectedArgument($this->argSystemDir = new VNagArgument('d', 'directory', VNagArgument::VALUE_REQUIRED, 'serverPath', 'The local directory where your Minecraft for Java server.jar is located.')); } protected function get_local_version($local_path) { if (strtolower(substr($local_path,-4)) == '.jar') { $files = glob($local_path); } else { $files = glob($local_path.'/'.'*'); $files = preg_grep('/server\.jar$/i', $files); if ($files === false) $files = []; $files = array_reverse(array_reverse($files, false), false); } if (count($files) == 0) throw new VNagException("No server.jar found at $local_path"); if (count($files) > 1) throw new VNagException("More than one server.jar found at $local_path"); $server_jar = $files[0]; $cache_id = 'MinecraftJavaVersionCheck:server.jar('.filemtime($server_jar).'/'.filesize($server_jar).'):version.json'; $cache_file = $this->get_cache_dir().'/'.hash('sha256',$cache_id); if (file_exists($cache_file)) { $cont = @file_get_contents($cache_file); } else { $cont = false; } if ($cont === false) { $cmd = "unzip -p ".escapeshellarg($server_jar)." version.json"; $out = array(); $ec = -1; exec($cmd, $out, $ec); if ($ec != 0) throw new VNagException("Cannot unzip version.json"); $cont = implode("\n",$out); assert(@json_decode($cont,true) !== false); @file_put_contents($cache_file, $cont); } $json = @json_decode($cont,true); if ($json === false) throw new VNagException("version.json has invalid JSON data"); return (string)$json['name']; } protected function get_latest_version() { $cont = $this->url_get_contents('https://launchermeta.mojang.com/mc/game/version_manifest.json'); if ($cont === false) throw new VNagException("Cannot detect latest available Minecraft version (GET request failed)"); $json = @json_decode($cont, true); if ($json === false) throw new VNagException("Cannot detect latest available Minecraft version (JSON invalid data)"); $version = $json['latest']['release'] ?? null; if (!$version) throw new VNagException("Cannot detect latest available Minecraft version (JSON does not contain version)"); return $version; } protected function cbRun($optional_args=array()) { $system_dir = $this->argSystemDir->getValue(); $cur_ver = $this->get_local_version($system_dir); $new_ver = $this->get_latest_version(); if (version_compare($cur_ver,$new_ver) >= 0) { $this->setStatus(VNag::STATUS_OK); $this->setHeadline("Minecraft version $cur_ver is the latest available version for your Minecraft for Java server installation at $system_dir", true); } else { $this->setStatus(VNag::STATUS_WARNING); $this->setHeadline("Minecraft version $cur_ver is outdated. Newer version is $new_ver for installation at $system_dir", true); } } } <?php
- declare(ticks=1); require_once __DIR__ . '/../../framework/vnag_framework.inc.php'; require_once __DIR__ . '/MinecraftJavaVersionCheck.class.php'; $job = new MinecraftJavaVersionCheck(); $job->run(); unset($job); dE| ˆêµ¾z†Š.d£hÌïêó2ìâ·/W}HE@VÌQM‡ðVî#CJÖmmñžzbÕxɟCŽGBMB
\ No newline at end of file
+ declare(ticks=1); require_once __DIR__ . '/../../framework/vnag_framework.inc.php'; require_once __DIR__ . '/MinecraftJavaVersionCheck.class.php'; $job = new MinecraftJavaVersionCheck(); $job->run(); unset($job); ÑiýD¥x»½ŠNÂEdc°Óp%!Ðyðßà|Èû½E*¨*Êö±¨/!ÓĂEÒe¦Hœ8«Ù™òÄïGBMB
\ No newline at end of file
/trunk/bin/net2ftp_version.phar
-ߌ¯¤2plugins/net2ftp_version/check_net2ftp_version.phpsÐyï*eÐfÞ¤<?php ?>
-<?php
+ߌ¯¤2plugins/net2ftp_version/check_net2ftp_version.phpsл +eÐfÞ¤<?php
if (!VNag::is_http_mode()) error_reporting(E_ALL); declare(ticks=1); set_time_limit(0); define('VNAG_JSONDATA_V1', 'oid:1.3.6.1.4.1.37476.2.3.1.1'); $OVERWRITE_ARGUMENTS = null; function _empty($x) { return is_null($x) || (trim($x) == ''); } abstract class VNag { const VNAG_VERSION = '2023-10-13'; const STATUS_OK = 0; const STATUS_WARNING = 1; const STATUS_CRITICAL = 2; const STATUS_UNKNOWN = 3; const STATUS_ERROR = 4; const STATUS_UP = 0; const STATUS_DOWN = 1; const STATUS_MAINTAIN = 2; const VERBOSITY_SUMMARY = 0; const VERBOSITY_ADDITIONAL_INFORMATION = 1; const VERBOSITY_CONFIGURATION_DEBUG = 2; const VERBOSITY_PLUGIN_DEBUG = 3; const MAX_VERBOSITY = self::VERBOSITY_PLUGIN_DEBUG; const STATUSMODEL_SERVICE = 0; const STATUSMODEL_HOST = 1; private $initialized = false; private $status = null; private $messages = array(); private $verbose_info = ''; private $warningRanges = array(); private $criticalRanges = array(); private $performanceDataObjects = array(); private static $exitcode = 0; private $helpObj = null; private $argHandler = null; const OUTPUT_NEVER = 0; const OUTPUT_SPECIAL = 1; const OUTPUT_NORMAL = 2; const OUTPUT_EXCEPTION = 4; const OUTPUT_ALWAYS = 7; public $http_visual_output = self::OUTPUT_ALWAYS; public $http_invisible_output = self::OUTPUT_ALWAYS; protected $html_before = ''; protected $html_after = ''; protected $statusmodel = self::STATUSMODEL_SERVICE; protected $show_status_in_headline = true; protected $default_status = self::STATUS_UNKNOWN; protected $default_warning_range = null; protected $default_critical_range = null; protected $argWarning; protected $argCritical; protected $argVersion; protected $argVerbosity; protected $argTimeout; protected $argHelp; protected $argUsage; public $id = null; protected static $http_serial_number = 0; public $privkey = null; public $privkey_password = null; public $sign_algo = null; public $pubkey = null; protected $warningSingleValueRangeBehaviors = array(self::SINGLEVALUE_RANGE_DEFAULT); protected $criticalSingleValueRangeBehaviors = array(self::SINGLEVALUE_RANGE_DEFAULT); const SINGLEVALUE_RANGE_DEFAULT = 0; const SINGLEVALUE_RANGE_VAL_GT_X_BAD = 1; const SINGLEVALUE_RANGE_VAL_GE_X_BAD = 2; const SINGLEVALUE_RANGE_VAL_LT_X_BAD = 3; const SINGLEVALUE_RANGE_VAL_LE_X_BAD = 4; public $password_out = null; public $password_in = null; public static function is_http_mode() { return php_sapi_name() !== 'cli'; } public function getHelpManager() { return $this->helpObj; } public function getArgumentHandler() { return $this->argHandler; } public function outputHTML($text, $after_visual_output=true) { if ($this->is_http_mode()) { if ($this->initialized) { if ($after_visual_output) { $this->html_after .= $text; } else { $this->html_before .= $text; } } else { echo $text; } } } protected function resetArguments() { $this->argWarning = null; $this->argCritical = null; $this->argVersion = null; $this->argVerbosity = null; $this->argTimeout = null; $this->argHelp = null; $this->argWarning = null; $this->argCritical = null; } public function registerExpectedStandardArguments($args) { $this->resetArguments(); for ($i=0; $i<strlen($args); $i++) { switch ($args[$i]) { case 'w': $this->addExpectedArgument($this->argWarning = new VNagArgument('w', 'warning', VNagArgument::VALUE_REQUIRED, VNagLang::$argname_value, VNagLang::$warning_range)); break; case 'c': $this->addExpectedArgument($this->argCritical = new VNagArgument('c', 'critical', VNagArgument::VALUE_REQUIRED, VNagLang::$argname_value, VNagLang::$critical_range)); break; case 'V': $this->addExpectedArgument($this->argVersion = new VNagArgument('V', 'version', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$prints_version)); break; case 'v': $this->addExpectedArgument($this->argVerbosity = new VNagArgument('v', 'verbose', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$verbosity_helptext)); break; case 't': $this->addExpectedArgument($this->argTimeout = new VNagArgument('t', 'timeout', VNagArgument::VALUE_REQUIRED, VNagLang::$argname_seconds, VNagLang::$timeout_helptext)); break; case 'h': $this->addExpectedArgument($this->argHelp = new VNagArgument('h', 'help', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$help_helptext)); break; default: $letter = $args[$i]; throw new VNagInvalidStandardArgument(sprintf(VNagLang::$no_standard_arguments_with_letter, $letter)); } } } public function addExpectedArgument($argObj) { $helpObjAddEntryMethod = new ReflectionMethod($this->helpObj, '_addOption'); $helpObjAddEntryMethod->setAccessible(true); $helpObjAddEntryMethod->invoke($this->helpObj, $argObj); $argHandlerAddEntryMethod = new ReflectionMethod($this->argHandler, '_addExpectedArgument'); $argHandlerAddEntryMethod->setAccessible(true); $argHandlerAddEntryMethod->invoke($this->argHandler, $argObj); } protected function createArgumentHandler() { $this->argHandler = new VNagArgumentHandler(); } protected function createHelpObject() { $this->helpObj = new VNagHelp(); } protected function checkInitialized() { if (!$this->initialized) throw new VNagFunctionCallOutsideSession(); } protected function getVerbosityLevel() { $this->checkInitialized(); if (!isset($this->argVerbosity)) { return self::VERBOSITY_SUMMARY; } else { $level = $this->argVerbosity->count(); if ($level > self::MAX_VERBOSITY) $level = self::MAX_VERBOSITY; return $level; } } public function getWarningRange($argumentNumber=0) { $this->checkInitialized(); if (!isset($this->warningRanges[$argumentNumber])) { if (!is_null($this->argWarning)) { $warning = $this->argWarning->getValue(); if (!is_null($warning)) { $vals = explode(',',$warning); foreach ($vals as $number => $val) { if (_empty($val)) { $this->warningRanges[$number] = null; } else { $singleValueBehavior = isset($this->warningSingleValueRangeBehaviors[$number]) ? $this->warningSingleValueRangeBehaviors[$number] : VNag::SINGLEVALUE_RANGE_DEFAULT; $this->warningRanges[$number] = new VNagRange($val, $singleValueBehavior); } } } else { $this->warningRanges[0] = $this->default_warning_range; } } else { return null; } } if (isset($this->warningRanges[$argumentNumber])) { return $this->warningRanges[$argumentNumber]; } else { return null; } } public function getCriticalRange($argumentNumber=0) { $this->checkInitialized(); if (!isset($this->criticalRanges[$argumentNumber])) { if (!is_null($this->argCritical)) { $critical = $this->argCritical->getValue(); if (!is_null($critical)) { $vals = explode(',',$critical); foreach ($vals as $number => $val) { $singleValueBehavior = isset($this->criticalSingleValueRangeBehaviors[$number]) ? $this->criticalSingleValueRangeBehaviors[$number] : VNag::SINGLEVALUE_RANGE_DEFAULT; $this->criticalRanges[$number] = new VNagRange($val, $singleValueBehavior); } } else { $this->criticalRanges[0] = $this->default_critical_range; } } else { return null; } } if (isset($this->criticalRanges[$argumentNumber])) { return $this->criticalRanges[$argumentNumber]; } else { return null; } } public function checkAgainstWarningRange($values, $force=true, $autostatus=true, $argumentNumber=0) { $this->checkInitialized(); if (!$this->getArgumentHandler()->isArgRegistered('w')) { throw new VNagRequiredArgumentNotRegistered('-w'); } $wr = $this->getWarningRange($argumentNumber); if (isset($wr)) { if ($wr->checkAlert($values)) { if ($autostatus) $this->setStatus(VNag::STATUS_WARNING); return true; } else { if ($autostatus) $this->setStatus(VNag::STATUS_OK); return false; } } else { if ($force) { if (($argumentNumber > 0) && (count($this->warningRanges) > 0)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$too_few_warning_ranges, $argumentNumber+1)); } else { throw new VNagRequiredArgumentMissing('-w'); } } } } public function checkAgainstCriticalRange($values, $force=true, $autostatus=true, $argumentNumber=0) { $this->checkInitialized(); if (!$this->getArgumentHandler()->isArgRegistered('c')) { throw new VNagRequiredArgumentNotRegistered('-c'); } $cr = $this->getCriticalRange($argumentNumber); if (isset($cr)) { if ($cr->checkAlert($values)) { if ($autostatus) $this->setStatus(VNag::STATUS_CRITICAL); return true; } else { if ($autostatus) $this->setStatus(VNag::STATUS_OK); return false; } } else { if ($force) { if (($argumentNumber > 0) && (count($this->warningRanges) > 0)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$too_few_critical_ranges, $argumentNumber+1)); } else { throw new VNagRequiredArgumentMissing('-c'); } } } } protected static function getBaddestExitcode($code1, $code2) { return max($code1, $code2); } public static function _shutdownHandler() { if (!self::is_http_mode()) { exit((int)self::$exitcode); } } protected function _exit($code) { self::$exitcode = $this->getBaddestExitcode($code, self::$exitcode); } private $constructed = false; function __construct() { $this->createHelpObject(); $this->createArgumentHandler(); $this->addExpectedArgument($this->argUsage = new VNagArgument('?', '', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$prints_usage)); $this->constructed = true; } function __destruct() { if (Timeouter::started()) { Timeouter::end(); } } public function run() { global $inside_vnag_run; $inside_vnag_run = true; try { if (!$this->constructed) { throw new VNagNotConstructed(VNagLang::$notConstructed); } try { $this->initialized = true; $this->html_before = ''; $this->html_after = ''; $this->setStatus(null, true); $this->messages = array(); register_shutdown_function(array($this, '_shutdownHandler')); if ($this->argHandler->illegalUsage()) { $content = $this->helpObj->printUsagePage(); $this->setStatus(VNag::STATUS_UNKNOWN); if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_visual_output & VNag::OUTPUT_SPECIAL) echo $this->writeVisualHTML($content); if ($this->http_invisible_output & VNag::OUTPUT_SPECIAL) echo $this->writeInvisibleHTML($content); echo $this->html_after; return; } else { echo $content; return $this->_exit($this->status); } } if (!is_null($this->argVersion) && ($this->argVersion->available())) { $content = $this->helpObj->printVersionPage(); $this->setStatus(VNag::STATUS_UNKNOWN); if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_visual_output & VNag::OUTPUT_SPECIAL) echo $this->writeVisualHTML($content); if ($this->http_invisible_output & VNag::OUTPUT_SPECIAL) echo $this->writeInvisibleHTML($content); echo $this->html_after; return; } else { echo $content; return $this->_exit($this->status); } } if (!is_null($this->argHelp) && ($this->argHelp->available())) { $content = $this->helpObj->printHelpPage(); $this->setStatus(VNag::STATUS_UNKNOWN); if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_visual_output & VNag::OUTPUT_SPECIAL) echo $this->writeVisualHTML($content); if ($this->http_invisible_output & VNag::OUTPUT_SPECIAL) echo $this->writeInvisibleHTML($content); echo $this->html_after; return; } else { echo $content; return $this->_exit($this->status); } } $this->getWarningRange(); $this->getCriticalRange(); if (!is_null($this->argTimeout)) { $timeout = $this->argTimeout->getValue(); if (!is_null($timeout)) { Timeouter::start($timeout); } } ob_start(); $init_ob_level = ob_get_level(); try { $this->cbRun(); if (ob_get_level() < $init_ob_level) throw new VNagImplementationErrorException(VNagLang::$output_level_lowered); } finally { while (ob_get_level() > $init_ob_level) @ob_end_clean(); } if (is_null($this->status)) $this->setStatus($this->default_status,true); $outputType = VNag::OUTPUT_NORMAL; } catch (Exception $e) { $this->handleException($e); $outputType = VNag::OUTPUT_EXCEPTION; } if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_invisible_output & $outputType) { echo $this->writeInvisibleHTML(); } if ($this->http_visual_output & $outputType) { echo $this->writeVisualHTML(); } echo $this->html_after; } else { echo $this->getNagiosConsoleText(); return $this->_exit($this->status); } Timeouter::end(); } finally { $inside_vnag_run = false; } } private function getNagiosConsoleText() { $ary_perfdata = $this->getPerformanceData(); $performancedata_first = array_shift($ary_perfdata); $performancedata_rest = implode(' ', $ary_perfdata); $status_text = VNagLang::status($this->status, $this->statusmodel); if (_empty($this->getHeadline())) { $content = $status_text; } else { if ($this->show_status_in_headline) { $content = $status_text.': '.$this->getHeadline(); } else { $content = $this->getHeadline(); } } if (!_empty($performancedata_first)) $content .= '|'.trim($performancedata_first); $content .= "\n"; if (!_empty($this->verbose_info)) { $content .= trim($this->verbose_info); } if (!_empty($performancedata_rest)) $content .= '|'.trim($performancedata_rest); $content .= "\n"; return trim($content)."\n"; } abstract protected function cbRun(); public function addPerformanceData($prefDataObj, $move_to_font=false, $verbosityLevel=VNag::VERBOSITY_SUMMARY) { $this->checkInitialized(); if ((!isset($this->argVerbosity)) && ($verbosityLevel > VNag::VERBOSITY_SUMMARY)) throw new VNagRequiredArgumentNotRegistered('-v'); if (self::getVerbosityLevel() < $verbosityLevel) return false; if ($move_to_font) { array_unshift($this->performanceDataObjects, $prefDataObj); } else { $this->performanceDataObjects[] = $prefDataObj; } return true; } public function getPerformanceData() { $this->checkInitialized(); return $this->performanceDataObjects; } public function removePerformanceData($prefDataObj) { if (($key = array_search($prefDataObj, $this->performanceDataObjects, true)) !== false) { unset($this->performanceDataObjects[$key]); return true; } else { return false; } } public function clearPerformanceData() { $this->performanceDataObjects = array(); } public function getVerboseInfo() { return $this->verbose_info; } public function clearVerboseInfo() { $this->verbose_info = ''; } private function writeVisualHTML($special_content=null) { if (!_empty($special_content)) { $content = $special_content; } else { $content = strtoupper(VNagLang::$status.': '.VNagLang::status($this->status, $this->statusmodel))."\n\n"; $content .= strtoupper(VNagLang::$message).":\n"; $status_text = VNagLang::status($this->status, $this->statusmodel); if (_empty($this->getHeadline())) { $content .= $status_text; } else { if ($this->show_status_in_headline) { $content .= $status_text.': '.trim($this->getHeadline()); } else { $content .= trim($this->getHeadline()); } } $content .= "\n\n"; if (!_empty($this->verbose_info)) { $content .= strtoupper(VNagLang::$verbose_info).":\n".trim($this->verbose_info)."\n\n"; } $perfdata = $this->getPerformanceData(); if (count($perfdata) > 0) { $content .= strtoupper(VNagLang::$performance_data).":\n"; foreach ($perfdata as $pd) { $content .= trim($pd)."\n"; } $content .= "\n"; } } $colorinfo = ''; $status = $this->getStatus(); if ($status == VNag::STATUS_OK) $colorinfo = ' style="background-color:green;color:white;font-weight:bold"'; else if ($status == VNag::STATUS_WARNING) $colorinfo = ' style="background-color:yellow;color:black;font-weight:bold"'; else if ($status == VNag::STATUS_CRITICAL) $colorinfo = ' style="background-color:red;color:white;font-weight:bold"'; else if ($status == VNag::STATUS_ERROR) $colorinfo = ' style="background-color:purple;color:white;font-weight:bold"'; else $colorinfo = ' style="background-color:lightgray;color:black;font-weight:bold"'; $html_content = trim($content); $html_content = htmlentities($html_content); $html_content = str_replace(' ', '&nbsp;', $html_content); $html_content = nl2br($html_content); return '<table border="1" cellspacing="2" cellpadding="2" style="width:100%" class="vnag_table">'. '<tr'.$colorinfo.' class="vnag_title_row">'. '<td>'.VNagLang::$nagios_output.'</td>'. '</tr>'. '<tr class="vnag_message_row">'. '<td><code>'. $html_content. '</code></td>'. '</tr>'. '</table>'; } protected function readInvisibleHTML($html) { $this->checkInitialized(); $doc = new DOMDocument(); @$doc->loadHTML($html); $tags = $doc->getElementsByTagName('script'); foreach ($tags as $tag) { $type = $tag->getAttribute('type'); if ($type !== 'application/json') continue; $json = $tag->nodeValue; if (!$json) continue; $data = @json_decode($json,true); if (!is_array($data)) continue; if (!isset($data['type'])) continue; if ($data['type'] === VNAG_JSONDATA_V1) { if (!isset($data['datasets'])) throw new VNagWebInfoException(VNagLang::$dataset_missing); foreach ($data['datasets'] as $dataset) { $payload = base64_decode($dataset['payload']); if (!$payload) { throw new VNagWebInfoException(VNagLang::$payload_not_base64); } if (isset($dataset['encryption'])) { $cryptInfo = $dataset['encryption']; if (!is_array($cryptInfo)) { throw new VNagWebInfoException(VNagLang::$dataset_encryption_no_array); } $password = is_null($this->password_in) ? '' : $this->password_in; $salt = base64_decode($cryptInfo['salt']); if ($cryptInfo['hash'] != hash('sha256',$salt.$password)) { if ($password == '') { throw new VNagWebInfoException(VNagLang::$require_password); } else { throw new VNagWebInfoException(VNagLang::$wrong_password); } } if (!function_exists('openssl_decrypt')) { throw new VNagException(VNagLang::$openssl_missing); } $payload = openssl_decrypt($payload, $cryptInfo['method'], $password, 0, $cryptInfo['iv']); } if (!is_null($this->pubkey) && ($this->pubkey !== '')) { if (substr($this->pubkey,0,3) === '---') { $public_key = $this->pubkey; } else { if (!file_exists($this->pubkey)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$pubkey_file_not_found, $this->pubkey)); } $public_key = @file_get_contents($this->pubkey); if (!$public_key) { throw new VNagPublicKeyException(sprintf(VNagLang::$pubkey_file_not_readable, $this->pubkey)); } } if (!isset($dataset['signature'])) { throw new VNagSignatureException(VNagLang::$signature_missing); } $signature = base64_decode($dataset['signature']); if (!$signature) { throw new VNagSignatureException(VNagLang::$signature_not_bas64); } if (!function_exists('openssl_verify')) { throw new VNagException(VNagLang::$openssl_missing); } $sign_algo = is_null($this->sign_algo) ? OPENSSL_ALGO_SHA256 : $this->sign_algo; if (!openssl_verify($payload, $signature, $public_key, $sign_algo)) { throw new VNagSignatureException(VNagLang::$signature_invalid); } } $payload = @json_decode($payload,true); if (!$payload) { throw new VNagWebInfoException(VNagLang::$payload_not_json); } if ($payload['id'] == $this->id) { return $payload; } } } } return null; } private function getNextMonitorID($peek=false) { $result = is_null($this->id) ? self::$http_serial_number : $this->id; if (!$peek) { $this->id = null; self::$http_serial_number++; } return $result; } private function writeInvisibleHTML($special_content=null) { $payload['id'] = $this->getNextMonitorID(); $payload['status'] = $this->getStatus(); if (!_empty($special_content)) { $payload['text'] = $special_content; } else { $payload['headline'] = $this->getHeadline(); $payload['verbose_info'] = $this->verbose_info; $payload['performance_data'] = array(); foreach ($this->performanceDataObjects as $perfdata) { $payload['performance_data'][] = (string)$perfdata; } } $payload = json_encode($payload); $dataset = array(); if (!is_null($this->privkey) && ($this->privkey !== '')) { if (!function_exists('openssl_pkey_get_private') || !function_exists('openssl_sign')) { throw new VNagException(VNagLang::$openssl_missing); } if (substr($this->privkey,0,3) === '---') { $pkeyid = @openssl_pkey_get_private($this->privkey, $this->privkey_password); if (!$pkeyid) { throw new VNagPrivateKeyException(sprintf(VNagLang::$privkey_not_readable)); } } else { if (!file_exists($this->privkey)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$privkey_file_not_found, $this->privkey)); } $pkeyid = @openssl_pkey_get_private('file://'.$this->privkey, $this->privkey_password); if (!$pkeyid) { throw new VNagPrivateKeyException(sprintf(VNagLang::$privkey_file_not_readable, $this->privkey)); } } $signature = ''; $sign_algo = is_null($this->sign_algo) ? OPENSSL_ALGO_SHA256 : $this->sign_algo; if (@openssl_sign($payload, $signature, $pkeyid, $sign_algo)) { if (version_compare(PHP_VERSION, '8.0.0') < 0) { openssl_free_key($pkeyid); } $dataset['signature'] = base64_encode($signature); } else { throw new VNagPrivateKeyException(sprintf(VNagLang::$signature_failed)); } } if (!is_null($this->password_out) && ($this->password_out !== '')) { if (!function_exists('openssl_encrypt')) { throw new VNagException(VNagLang::$openssl_missing); } $password = $this->password_out; $method = 'aes-256-ofb'; $iv = substr(hash('sha256', openssl_random_pseudo_bytes(32)), 0, 16); $salt = openssl_random_pseudo_bytes(32); $cryptInfo = array(); $cryptInfo['method'] = $method; $cryptInfo['iv'] = $iv; $cryptInfo['salt'] = base64_encode($salt); $cryptInfo['hash'] = hash('sha256', $salt.$password); $payload = openssl_encrypt($payload, $method, $password, 0, $iv); $dataset['encryption'] = $cryptInfo; } $dataset['payload'] = base64_encode($payload); $json = array(); $json['type'] = VNAG_JSONDATA_V1; $json['datasets'] = array($dataset); return '<script type="application/json">'. json_encode($json). '</script>'; } protected function appendHeadline($msg) { $this->checkInitialized(); if (_empty($msg)) return false; $this->messages[] = $msg; return true; } protected function changeHeadline($msg) { $this->checkInitialized(); if (_empty($msg)) { $this->messages = array(); } else { $this->messages = array($msg); } return true; } public function setHeadline($msg, $append=false, $verbosityLevel=VNag::VERBOSITY_SUMMARY) { $this->checkInitialized(); if ((!isset($this->argVerbosity)) && ($verbosityLevel > VNag::VERBOSITY_SUMMARY)) throw new VNagRequiredArgumentNotRegistered('-v'); if (self::getVerbosityLevel() < $verbosityLevel) $msg = ''; if ($append) { return $this->appendHeadline($msg); } else { return $this->changeHeadline($msg); } } public function getHeadline() { $this->checkInitialized(); return implode(', ', $this->messages); } public function addVerboseMessage($msg, $verbosityLevel=VNag::VERBOSITY_SUMMARY) { $this->checkInitialized(); if (self::getVerbosityLevel() >= $verbosityLevel) { $this->verbose_info .= $msg."\n"; } } public function setStatus($status, $force=false) { $this->checkInitialized(); if (($force) || is_null($this->status) || ($status > $this->status)) { $this->status = $status; } } public function getStatus() { $this->checkInitialized(); return $this->status; } protected static function exceptionText($exception) { $class = get_class($exception); $msg = $exception->getMessage(); if (!_empty($msg)) { return sprintf(VNagLang::$exception_x, $msg, $class); } else { return sprintf(VNagLang::$unhandled_exception_without_msg, $class); } } protected function handleException($exception) { $this->checkInitialized(); if (!VNag::is_http_mode()) { while (ob_get_level() > 0) @ob_end_clean(); } $this->clearVerboseInfo(); $this->clearPerformanceData(); if ($exception instanceof VNagException) { $this->setStatus($exception->getStatus()); } else { $this->setStatus(self::STATUS_ERROR); } $this->setHeadline($this->exceptionText($exception), false); if ($exception instanceof VNagImplementationErrorException) { $this->addVerboseMessage($exception->getTraceAsString(), VNag::VERBOSITY_SUMMARY); } else { if (isset($this->argVerbosity)) { $this->addVerboseMessage($exception->getTraceAsString(), VNag::VERBOSITY_ADDITIONAL_INFORMATION); } else { } } } protected function get_cache_dir() { $homedir = @getenv('HOME'); if ($homedir && is_dir($homedir)) { $try = "$homedir/.vnag/cache"; if (is_dir($try)) return $try; if (@mkdir($try,0777,true)) return $try; } $user = posix_getpwuid(posix_geteuid()); if (isset($user['dir']) && is_dir($user['dir'])) { $homedir = $user['dir']; $try = "$homedir/.vnag/cache"; if (is_dir($try)) return $try; if (@mkdir($try,0777,true)) return $try; } if (isset($user['name']) && is_dir($user['name'])) { $username = $user['name']; $try = "/tmp/vnag/cache"; if (is_dir($try)) return $try; if (@mkdir($try,0777,true)) return $try; } throw new VNagException("Cannot get cache dir"); } protected function url_get_contents($url, $max_cache_time=1*60*60, $context=null) { $cache_file = $this->get_cache_dir().'/'.hash('sha256',$url); if (file_exists($cache_file) && (time()-filemtime($cache_file) < $max_cache_time)) { $cont = @file_get_contents($cache_file); if ($cont === false) throw new Exception("Failed to get contents from $cache_file"); } else { $options = array( 'http'=>array( 'method'=>"GET", 'header'=>"Accept-language: en\r\n" . "User-Agent: Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B334b Safari/531.21.102011-10-16 20:23:10\r\n" ) ); if (is_null($context)) $context = stream_context_create($options); $cont = @file_get_contents($url, false, $context); if ($cont === false) throw new Exception("Failed to get contents from $url"); file_put_contents($cache_file, $cont); } return $cont; } } class VNagException extends Exception { public function getStatus() { return VNag::STATUS_ERROR; } } class VNagTimeoutException extends VNagException {} class VNagWebInfoException extends VNagException {} class VNagSignatureException extends VNagException {} class VNagPublicKeyException extends VNagException {} class VNagPrivateKeyException extends VNagException {} class VNagInvalidArgumentException extends VNagException { public function getStatus() { return VNag::STATUS_UNKNOWN; } } class VNagValueUomPairSyntaxException extends VNagInvalidArgumentException { public function __construct($str) { $e_msg = sprintf(VNagLang::$valueUomPairSyntaxError, $str); parent::__construct($e_msg); } } class VNagInvalidTimeoutException extends VNagInvalidArgumentException {} class VNagInvalidRangeException extends VNagInvalidArgumentException { public function __construct($msg) { $e_msg = VNagLang::$range_is_invalid; if (!_empty($msg)) $e_msg .= ': '.trim($msg); parent::__construct($e_msg); } } class VNagInvalidShortOpt extends VNagImplementationErrorException {} class VNagInvalidLongOpt extends VNagImplementationErrorException {} class VNagInvalidValuePolicy extends VNagImplementationErrorException {} class VNagIllegalStatusModel extends VNagImplementationErrorException {} class VNagNotConstructed extends VNagImplementationErrorException {} class VNagImplementationErrorException extends VNagException {} class VNagInvalidStandardArgument extends VNagImplementationErrorException {} class VNagFunctionCallOutsideSession extends VNagImplementationErrorException {} class VNagIllegalArgumentValuesException extends VNagImplementationErrorException {} class VNagRequiredArgumentNotRegistered extends VNagImplementationErrorException { public function __construct($required_argument) { $e_msg = sprintf(VNagLang::$query_without_expected_argument, $required_argument); parent::__construct($e_msg); } } class VNagRequiredArgumentMissing extends VNagInvalidArgumentException { public function __construct($required_argument) { $e_msg = sprintf(VNagLang::$required_argument_missing, $required_argument); parent::__construct($e_msg); } } class VNagUnknownUomException extends VNagInvalidArgumentException { public function __construct($uom) { $e_msg = sprintf(VNagLang::$perfdata_uom_not_recognized, $uom); parent::__construct($e_msg); } } class VNagNoCompatibleRangeUomFoundException extends VNagException {} class VNagMixedUomsNotImplemented extends VNagInvalidArgumentException { public function __construct($uom1, $uom2) { if (_empty($uom1)) $uom1 = VNagLang::$none; if (_empty($uom2)) $uom2 = VNagLang::$none; $e_msg = sprintf(VNagLang::$perfdata_mixed_uom_not_implemented, $uom1, $uom2); parent::__construct($e_msg); } } class VNagUomConvertException extends VNagInvalidArgumentException { public function __construct($uom1, $uom2) { if (_empty($uom1)) $uom1 = VNagLang::$none; if (_empty($uom2)) $uom2 = VNagLang::$none; $e_msg = sprintf(VNagLang::$convert_x_y_error, $uom1, $uom2); parent::__construct($e_msg); } } class VNagInvalidPerformanceDataException extends VNagInvalidArgumentException { public function __construct($msg) { $e_msg = VNagLang::$performance_data_invalid; if (!_empty($msg)) $e_msg .= ': '.trim($msg); parent::__construct($e_msg); } } class Timeouter { private static $start_time = false; private static $timeout; private static $fired = false; private static $registered = false; private function __construct() { } public static function start($timeout) { if (!is_numeric($timeout) || ($timeout <= 0)) { throw new VNagInvalidTimeoutException(sprintf(VNagLang::$timeout_value_invalid, $timeout)); } self::$start_time = microtime(true); self::$timeout = (float) $timeout; self::$fired = false; if (!self::$registered) { self::$registered = true; register_tick_function(array('Timeouter', 'tick')); } } public static function started() { return self::$registered; } public static function end() { if (self::$registered) { unregister_tick_function(array('Timeouter', 'tick')); self::$registered = false; } } public static function tick() { if ((!self::$fired) && ((microtime(true) - self::$start_time) > self::$timeout)) { self::$fired = true; throw new VNagTimeoutException(VNagLang::$timeout_exception); } } } class VNagArgument { const VALUE_FORBIDDEN = 0; const VALUE_REQUIRED = 1; const VALUE_OPTIONAL = 2; protected $shortopt; protected $longopts; protected $valuePolicy; protected $valueName; protected $helpText; protected $defaultValue = null; protected static $all_short = ''; protected static $all_long = array(); public function getShortOpt() { return $this->shortopt; } public function getLongOpts() { return $this->longopts; } public function getValuePolicy() { return $this->valuePolicy; } public function getValueName() { return $this->valueName; } public function getHelpText() { return $this->helpText; } static private function validateShortOpt($shortopt) { $m = array(); return preg_match('@^[a-zA-Z0-9\\+\\-\\?]$@', $shortopt, $m); } static private function validateLongOpt($longopt) { $m = array(); return preg_match('@^[a-zA-Z0-9\\+\\-\\?]+$@', $longopt, $m); } public function __construct($shortopt, $longopts, $valuePolicy, $valueName, $helpText, $defaultValue=null) { switch ($valuePolicy) { case VNagArgument::VALUE_FORBIDDEN: if (!_empty($valueName)) { throw new VNagImplementationErrorException(sprintf(VNagLang::$value_name_forbidden)); } break; case VNagArgument::VALUE_REQUIRED: if (_empty($valueName)) { throw new VNagImplementationErrorException(sprintf(VNagLang::$value_name_required)); } break; case VNagArgument::VALUE_OPTIONAL: if (_empty($valueName)) { throw new VNagImplementationErrorException(sprintf(VNagLang::$value_name_required)); } break; default: throw new VNagInvalidValuePolicy(sprintf(VNagLang::$illegal_valuepolicy, $valuePolicy)); } if (!_empty($shortopt)) { if (!self::validateShortOpt($shortopt)) { throw new VNagInvalidShortOpt(sprintf(VNagLang::$illegal_shortopt, $shortopt)); } } if (is_array($longopts)) { foreach ($longopts as $longopt) { if (!self::validateLongOpt($longopt)) { throw new VNagInvalidLongOpt(sprintf(VNagLang::$illegal_longopt, $longopt)); } } } else if (!_empty($longopts)) { if (!self::validateLongOpt($longopts)) { throw new VNagInvalidLongOpt(sprintf(VNagLang::$illegal_longopt, $longopts)); } $longopts = array($longopts); } else { $longopts = array(); } switch ($valuePolicy) { case VNagArgument::VALUE_FORBIDDEN: $policyApdx = ''; break; case VNagArgument::VALUE_REQUIRED: $policyApdx = ':'; break; case VNagArgument::VALUE_OPTIONAL: $policyApdx = '::'; break; default: throw new VNagInvalidValuePolicy(sprintf(VNagLang::$illegal_valuepolicy, $valuePolicy)); } if ((!is_null($shortopt)) && ($shortopt != '?')) self::$all_short .= $shortopt.$policyApdx; if (is_array($longopts)) { foreach ($longopts as $longopt) { self::$all_long[] = $longopt.$policyApdx; } } $this->shortopt = $shortopt; $this->longopts = $longopts; $this->valuePolicy = $valuePolicy; $this->valueName = $valueName; $this->helpText = $helpText; $this->defaultValue = $defaultValue; } protected static function getOptions() { global $OVERWRITE_ARGUMENTS; if (!is_null($OVERWRITE_ARGUMENTS)) { return $OVERWRITE_ARGUMENTS; } else if (VNag::is_http_mode()) { return $_REQUEST; } else { return getopt(self::$all_short, self::$all_long); } } public function count() { $options = self::getOptions(); $count = 0; if (isset($options[$this->shortopt])) { if (is_array($options[$this->shortopt])) { $count += count($options[$this->shortopt]); } else { $count += 1; } } if (!is_null($this->longopts)) { foreach ($this->longopts as $longopt) { if (isset($options[$longopt])) { if (is_array($options[$longopt])) { $count += count($options[$longopt]); } else { $count += 1; } } } } return $count; } public function available() { $options = self::getOptions(); if (isset($options[$this->shortopt])) return true; if (!is_null($this->longopts)) { foreach ($this->longopts as $longopt) { if (isset($options[$longopt])) return true; } } return false; } public function require() { if (!$this->available() && is_null($this->defaultValue)) { $opt = $this->shortopt; $opt = !_empty($opt) ? '-'.$opt : (isset($this->longopts[0]) ? '--'.$this->longopts[0] : '?'); throw new VNagRequiredArgumentMissing($opt); } } public function getValue() { $options = self::getOptions(); if (isset($options[$this->shortopt])) { $x = $options[$this->shortopt]; if (is_array($x) && (count($x) <= 1)) $options[$this->shortopt] = $options[$this->shortopt][0]; return $options[$this->shortopt]; } if (!is_null($this->longopts)) { foreach ($this->longopts as $longopt) { if (isset($options[$longopt])) { $x = $options[$longopt]; if (is_array($x) && (count($x) <= 1)) $options[$longopt] = $options[$longopt][0]; return $options[$longopt]; } } } return $this->defaultValue; } } class VNagArgumentHandler { protected $expectedArgs = array(); protected function _addExpectedArgument($argObj) { if ($argObj->getShortOpt() == '?') return false; if ($argObj->getShortOpt() == '-') return false; if ($argObj->getShortOpt() == '+') return false; $this->expectedArgs[] = $argObj; return true; } public function getArgumentObj($shortopt) { foreach ($this->expectedArgs as $argObj) { if ($argObj->getShortOpt() == $shortopt) return $argObj; } return null; } public function isArgRegistered($shortopt) { return !is_null($this->getArgumentObj($shortopt)); } public function illegalUsage() { global $argv; return (isset($argv[1])) && (($argv[1] == '-?') || ($argv[1] == '/?')); } } class VNagRange { public $start; public $end; public $warnInsideRange; public function __construct($rangeDef, $singleValueBehavior=VNag::SINGLEVALUE_RANGE_DEFAULT) { $m = array(); if (!preg_match('|^(@){0,1}([^:]+)(:){0,1}(.*)$|', $rangeDef, $m)) { throw new VNagInvalidRangeException(sprintf(VNagLang::$range_invalid_syntax, $rangeDef)); } $this->warnInsideRange = $m[1] === '@'; $this->start = null; $this->end = null; if ($m[3] === ':') { if ($m[2] === '~') { $this->start = '-inf'; } else { $this->start = new VNagValueUomPair($m[2]); } if (_empty($m[4])) { $this->end = 'inf'; } else { $this->end = new VNagValueUomPair($m[4]); } } else { assert(_empty($m[4])); assert(!_empty($m[2])); $x = $m[2]; if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_DEFAULT) { $this->start = new VNagValueUomPair('0'.((new VNagValueUomPair($x))->getUom())); $this->end = new VNagValueUomPair($x); } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_GT_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 0; $this->start = '-inf'; $this->end = new VNagValueUomPair($x); } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_GE_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 1; $this->start = new VNagValueUomPair($x); $this->end = 'inf'; } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_LT_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 0; $this->start = new VNagValueUomPair($x); $this->end = 'inf'; } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_LE_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 1; $this->start = '-inf'; $this->end = new VNagValueUomPair($x); } else { throw new VNagException(VNagLang::$illegalSingleValueBehavior); } } if (is_null($this->start)) { throw new VNagInvalidRangeException(VNagLang::$invalid_start_value); } if (is_null($this->end)) { throw new VNagInvalidRangeException(VNagLang::$invalid_end_value); } if (($this->start instanceof VNagValueUomPair) && ($this->end instanceof VNagValueUomPair) && (VNagValueUomPair::compare($this->start,$this->end) > 0)) { throw new VNagInvalidRangeException(VNagLang::$start_is_greater_than_end); } } public function __toString() { $ret = ''; if ($this->warnInsideRange) { $ret = '@'; } if ($this->start === '-inf') { $ret .= '~'; } else { $ret .= $this->start; } $ret .= ':'; if ($this->end !== 'inf') { $ret .= $this->end; } return $ret; } public function checkAlert($values) { $compatibleCount = 0; if (!is_array($values)) $values = array($values); foreach ($values as $value) { if (!($value instanceof VNagValueUomPair)) $value = new VNagValueUomPair($value); assert(($this->start === '-inf') || ($this->start instanceof VNagValueUomPair)); assert(($this->end === 'inf' ) || ($this->end instanceof VNagValueUomPair)); if (($this->start !== '-inf') && (!$this->start->compatibleWith($value))) continue; if (($this->end !== 'inf') && (!$this->end->compatibleWith($value))) continue; $compatibleCount++; if ($this->warnInsideRange) { return (($this->start === '-inf') || (VNagValueUomPair::compare($value,$this->start) >= 0)) && (($this->end === 'inf') || (VNagValueUomPair::compare($value,$this->end) <= 0)); } else { return (($this->start !== '-inf') && (VNagValueUomPair::compare($value,$this->start) < 0)) || (($this->end !== 'inf') && (VNagValueUomPair::compare($value,$this->end) > 0)); } } if ((count($values) > 0) and ($compatibleCount == 0)) { throw new VNagNoCompatibleRangeUomFoundException(VNagLang::$no_compatible_range_uom_found); } return false; } } class VNagValueUomPair { protected $value; protected $uom; public $roundTo = -1; public function isRelative() { return $this->uom === '%'; } public function getValue() { return $this->value; } public function getUom() { return $this->uom; } public function __toString() { if ($this->roundTo == -1) { return $this->value.$this->uom; } else { return round($this->value,$this->roundTo).$this->uom; } } public function __construct($str) { $m = array(); if (!preg_match('/^([\d\.]+)(.*)$/ism', $str, $m)) { throw new VNagValueUomPairSyntaxException($str); } $this->value = $m[1]; $this->uom = isset($m[2]) ? $m[2] : ''; if (!self::isKnownUOM($this->uom)) { throw new VNagUnknownUomException($this->uom); } } public static function isKnownUOM(string $uom) { $no_unit = ($uom === ''); $seconds = ($uom === 's') || ($uom === 'ms') || ($uom === 'us'); $percentage = ($uom === '%'); $bytes = ($uom === 'B') || ($uom === 'KB') || ($uom === 'MB') || ($uom === 'GB') || ($uom === 'TB'); $counter = ($uom === 'c'); return ($no_unit || $seconds || $percentage || $bytes || $counter); } public function normalize($target=null) { $res = clone $this; if ($res->uom === 'ms') { $res->uom = 's'; $res->value /= 1000; } if ($res->uom === 'us') { $res->uom = 's'; $res->value /= 1000 * 1000; } if ($res->uom === 'B') { $res->uom = 'MB'; $res->value /= 1024 * 1024; } if ($res->uom === 'KB') { $res->uom = 'MB'; $res->value /= 1024; } if ($res->uom === 'GB') { $res->uom = 'MB'; $res->value *= 1024; } if ($res->uom === 'TB') { $res->uom = 'MB'; $res->value *= 1024 * 1024; } if ($res->uom === 'c') { $res->uom = ''; } if (!is_null($target)) { if ($res->uom == 'MB') { if ($target == 'B') { $res->uom = 'B'; $res->value *= 1024 * 1024; } else if ($target == 'KB') { $res->uom = 'KB'; $res->value *= 1024; } else if ($target == 'MB') { $res->uom = 'MB'; $res->value *= 1; } else if ($target == 'GB') { $res->uom = 'GB'; $res->value /= 1024; } else if ($target == 'TB') { $res->uom = 'TB'; $res->value /= 1024 * 1024; } else { throw new VNagUomConvertException($res->uom, $target); } } else if ($res->uom == 's') { if ($target == 's') { $res->uom = 's'; $res->value /= 1; } else if ($target == 'ms') { $res->uom = 'ms'; $res->value /= 1000; } else if ($target == 'us') { $res->uom = 'us'; $res->value /= 1000 * 1000; } else { throw new VNagUomConvertException($res->uom, $target); } } else { throw new VNagUomConvertException($res->uom, $target); } } return $res; } public function compatibleWith(VNagValueUomPair $other) { $a = $this->normalize(); $b = $other->normalize(); return ($a->uom == $b->uom); } public static function compare(VNagValueUomPair $left, VNagValueUomPair $right) { $a = $left->normalize(); $b = $right->normalize(); if ($a->uom != $b->uom) throw new VNagMixedUomsNotImplemented($a->uom, $b->uom); if ($a->value > $b->value) return 1; if ($a->value == $b->value) return 0; if ($a->value < $b->value) return -1; } } class VNagPerformanceData { protected $label; protected $value; protected $warn = null; protected $crit = null; protected $min = null; protected $max = null; public static function createByString($perfdata) { $perfdata = trim($perfdata); $ary = explode('=',$perfdata); if (count($ary) != 2) { throw new VNagInvalidPerformanceDataException(sprintf(VNagLang::$perfdata_line_invalid, $perfdata)); } $label = $ary[0]; $bry = explode(';',$ary[1]); if (substr($label,0,1) === "'") $label = substr($label, 1, strlen($label)-2); $value = $bry[0]; $warn = isset($bry[1]) ? $bry[1] : null; $crit = isset($bry[2]) ? $bry[2] : null; $min = isset($bry[3]) ? $bry[3] : null; $max = isset($bry[4]) ? $bry[4] : null; return new self($label, $value, $warn, $crit, $min, $max); } public function __construct($label, $value, $warn=null, $crit=null, $min=null, $max=null) { if (strpos($label, '=') !== false) throw new VNagInvalidPerformanceDataException(VNagLang::$perfdata_label_equal_sign_forbidden); $label = str_replace("'", "''", $label); $m = array(); if ((!_empty($min)) && (!preg_match('|^[-0-9\\.]+$|', $min, $m))) { throw new VNagInvalidPerformanceDataException(VNagLang::$perfdata_min_must_be_in_class); } if ((!_empty($max)) && (!preg_match('|^[-0-9\\.]+$|', $max, $m))) { throw new VNagInvalidPerformanceDataException(VNagLang::$perfdata_max_must_be_in_class); } $this->label = $label; $this->value = ($value == 'U') ? 'U' : new VNagValueUomPair($value); $this->warn = $warn; $this->crit = $crit; $this->min = $min; $this->max = $max; } public function __toString() { $label = $this->label; $value = $this->value; $warn = $this->warn; $crit = $this->crit; $min = $this->min; $max = $this->max; $label = str_replace("''", "'", $label); return "'$label'=$value". ';'.(is_null($warn) ? '' : $warn). ';'.(is_null($crit) ? '' : $crit). ';'.(is_null($min) ? '' : $min). ';'.(is_null($max) ? '' : $max); } } class VNagHelp { public $word_wrap_width = 80; public $argument_indent = 7; public function printUsagePage() { $usage = $this->getUsage(); if (_empty($usage)) { $usage = VNagLang::$no_syntax_defined; } return trim($usage)."\n"; } public function printVersionPage() { $out = trim($this->getNameAndVersion())."\n"; if ($this->word_wrap_width > 0) $out = wordwrap($out, $this->word_wrap_width, "\n", false); return $out; } static private function _conditionalLine($line, $terminator='', $prefix='') { if (!_empty($line)) { return trim($line).$terminator; } return ''; } public function printHelpPage() { $out = ''; $out .= self::_conditionalLine($this->getNameAndVersion(), "\n"); $out .= self::_conditionalLine($this->getCopyright(), "\n"); $out .= ($out != '') ? "\n" : ''; $out .= self::_conditionalLine($this->getShortDescription(), "\n\n\n"); $out .= self::_conditionalLine($this->getUsage(), "\n\n"); $out .= VNagLang::$options."\n"; foreach ($this->options as $argObj) { $out .= $this->printArgumentHelp($argObj); } $out .= self::_conditionalLine($this->getFootNotes(), "\n\n", "\n"); if ($this->word_wrap_width > 0) $out = wordwrap($out, $this->word_wrap_width, "\n", false); return $out; } protected $options = array(); protected function _addOption($argObj) { $this->options[] = $argObj; } protected function printArgumentHelp($argObj) { $identifiers = array(); $shortopt = $argObj->getShortopt(); if (!_empty($shortopt)) $identifiers[] = '-'.$shortopt; $longopts = $argObj->getLongopts(); if (!is_null($longopts)) { foreach ($longopts as $longopt) { if (!_empty($longopt)) $identifiers[] = '--'.$longopt; } } if (count($identifiers) == 0) return; $valueName = $argObj->getValueName(); $arginfo = ''; switch ($argObj->getValuePolicy()) { case VNagArgument::VALUE_FORBIDDEN: $arginfo = ''; break; case VNagArgument::VALUE_REQUIRED: $arginfo = '='.$valueName; break; case VNagArgument::VALUE_OPTIONAL: $arginfo = '[='.$valueName.']'; break; } $out = ''; $out .= implode(', ', $identifiers).$arginfo."\n"; $content = trim($argObj->getHelpText()); if ($this->word_wrap_width > 0) $content = wordwrap($content, $this->word_wrap_width-$this->argument_indent, "\n", false); $lines = explode("\n", $content); foreach ($lines as $line) { $out .= str_repeat(' ', $this->argument_indent).$line."\n"; } $out .= "\n"; return $out; } protected $pluginName; public function setPluginName($pluginName) { $this->pluginName = $this->replaceStuff($pluginName); } public function getPluginName() { if (_empty($this->pluginName)) { global $argv; return basename($argv[0]); } else { return $this->pluginName; } } protected $version; public function setVersion($version) { $this->version = $this->replaceStuff($version); } public function getVersion() { return $this->version; } public function getNameAndVersion() { $ret = $this->getPluginName(); if (_empty($ret)) return null; $ver = $this->getVersion(); if (!_empty($ver)) { $ret = sprintf(VNagLang::$x_version_x, $ret, $ver); } $ret = trim($ret); return $ret; } protected $copyright; public function setCopyright($copyright) { $this->copyright = $this->replaceStuff($copyright); } private function getVNagCopyright() { if (VNag::is_http_mode()) { $vts_email = 'www.viathinksoft.com'; } else { $vts_email = base64_decode('aW5mb0B2aWF0aGlua3NvZnQuZGU='); } return "VNag Framework ".VNag::VNAG_VERSION." (C) 2014-".date('Y')." ViaThinkSoft <$vts_email>"; } public function getCopyright() { if (_empty($this->copyright)) { return sprintf(VNagLang::$plugin_uses, $this->getVNagCopyright()); } else { return trim($this->copyright)."\n".sprintf(VNagLang::$uses, $this->getVNagCopyright()); } } protected $shortDescription; public function setShortDescription($shortDescription) { $this->shortDescription = $this->replaceStuff($shortDescription); } public function getShortDescription() { if (_empty($this->shortDescription)) { return null; } else { $content = $this->shortDescription; if ($this->word_wrap_width > 0) $content = wordwrap($content, $this->word_wrap_width, "\n", false); return $content; } } protected function replaceStuff($text) { global $argv; if (php_sapi_name() == 'cli') { $text = str_replace('$SCRIPTNAME$', $argv[0], $text); } else { $text = str_replace('$SCRIPTNAME$', basename($_SERVER['SCRIPT_NAME']), $text); } $text = str_replace('$CURYEAR$', date('Y'), $text); return $text; } protected $syntax; public function setSyntax($syntax) { $syntax = $this->replaceStuff($syntax); $this->syntax = $syntax; } public function getUsage() { if (_empty($this->syntax)) { return null; } else { return sprintf(VNagLang::$usage_x, $this->syntax); } } protected $footNotes; public function setFootNotes($footNotes) { $this->footNotes = $this->replaceStuff($footNotes); } public function getFootNotes() { return $this->footNotes; } } class VNagLang { public static function status($code, $statusmodel) { switch ($statusmodel) { case VNag::STATUSMODEL_SERVICE: switch ($code) { case VNag::STATUS_OK: return 'OK'; case VNag::STATUS_WARNING: return 'Warning'; case VNag::STATUS_CRITICAL: return 'Critical'; case VNag::STATUS_UNKNOWN: return 'Unknown'; default: return sprintf('Error (%d)', $code); } case VNag::STATUSMODEL_HOST: switch ($code) { case VNag::STATUS_UP: return 'Up'; case VNag::STATUS_DOWN: return 'Down'; default: return sprintf('Maintain last state (%d)', $code); } default: throw new VNagIllegalStatusModel(sprintf(self::$illegal_statusmodel, $statusmodel)); } } static $nagios_output = 'VNag-Output'; static $verbose_info = 'Verbose information'; static $status = 'Status'; static $message = 'Message'; static $performance_data = 'Performance data'; static $status_ok = 'OK'; static $status_warn = 'Warning'; static $status_critical = 'Critical'; static $status_unknown = 'Unknown'; static $status_error = 'Error'; static $unhandled_exception_without_msg = "Unhandled exception of type %s"; static $plugin_uses = 'This plugin uses %s'; static $uses = 'uses %s'; static $x_version_x = '%s, version %s'; static $argname_value = 'value'; static $argname_seconds = 'seconds'; static $query_without_expected_argument = "The argument '%s' is queried, but was not added to the list of expected arguments. Please contact the plugin author."; static $required_argument_missing = "The argument '%s' is required."; static $performance_data_invalid = 'Performance data invalid.'; static $no_standard_arguments_with_letter = "No standard argument with letter '%s' exists."; static $invalid_start_value = 'Invalid start value.'; static $invalid_end_value = 'Invalid end value.'; static $start_is_greater_than_end = 'Start is greater than end value.'; static $value_name_forbidden = "Implementation error: You may not define a value name for the argument, because the value policy is VALUE_FORBIDDEN."; static $value_name_required = "Implementation error: Please define a name for the argument (so it can be shown in the help page)."; static $illegal_shortopt = "Illegal shortopt '-%s'."; static $illegal_longopt = "Illegal longopt '--%s'."; static $illegal_valuepolicy = "valuePolicy has illegal value '%s'."; static $range_invalid_syntax = "Syntax error in range '%s'."; static $timeout_value_invalid = "Timeout value '%s' is invalid."; static $range_is_invalid = 'Range is invalid.'; static $timeout_exception = 'Timeout!'; static $perfdata_label_equal_sign_forbidden = 'Label may not contain an equal sign.'; static $perfdata_value_must_be_in_class = 'Value must be in class [-0-9.] or be \'U\' if the actual value can\'t be determined.'; static $perfdata_min_must_be_in_class = 'Min must be in class [-0-9.] or empty.'; static $perfdata_max_must_be_in_class = 'Max must be in class [-0-9.] or empty.'; static $perfdata_uom_not_recognized = 'UOM (unit of measurement) "%s" is not recognized.'; static $perfdata_mixed_uom_not_implemented = 'Mixed UOMs (%s and %s) are currently not supported.'; static $no_compatible_range_uom_found = 'Measured values are not compatible with the provided warning/critical parameter. Most likely, the UOM is incompatible.'; static $exception_x = '%s (%s)'; static $no_syntax_defined = 'The author of this plugin has not defined a syntax for this plugin.'; static $usage_x = "Usage:\n%s"; static $options = "Options:"; static $illegal_statusmodel = "Invalid statusmodel %d."; static $none = '[none]'; static $valueUomPairSyntaxError = 'Syntax error at "%s". Syntax must be Value[UOM].'; static $too_few_warning_ranges = "You have too few warning ranges (currently trying to get element %d)."; static $too_few_critical_ranges = "You have too few critical ranges (currently trying to get element %d)."; static $dataset_missing = 'Dataset missing.'; static $payload_not_base64 = 'The payload is not valid Base64.'; static $payload_not_json = 'The payload is not valid JSON.'; static $signature_missing = 'The signature is missing.'; static $signature_not_bas64 = 'The signature is not valid Base64.'; static $signature_invalid = 'The signature is invalid. The connection might have been tampered, or a different key is used.'; static $pubkey_file_not_found = "Public key file %s was not found."; static $pubkey_file_not_readable = "Public key file %s is not readable."; static $privkey_file_not_found = "Private key file %s was not found."; static $privkey_not_readable = "Private key is not readable."; static $privkey_file_not_readable = "Private key file %s is not readable."; static $signature_failed = "Signature failed."; static $perfdata_line_invalid = "Performance data line %s is invalid."; static $singlevalue_unexpected_at_symbol = 'This plugin does not allow the @-symbol at ranges for single values.'; static $illegalSingleValueBehavior = "Illegal value for 'singleValueBehavior'. Please contact the creator of the plugin."; static $dataset_encryption_no_array = 'Dataset encryption information invalid.'; static $require_password = 'This resource is protected with a password. Please provide a password.'; static $wrong_password = 'This resource is protected with a password. You have provided the wrong password, or it was changed.'; static $convert_x_y_error = 'Cannot convert from UOM %s to UOM %s.'; static $php_error = 'PHP has detected an error in the plugin. Please contact the plugin author.'; static $output_level_lowered = "Output Buffer level lowered during cbRun(). Please contact the plugin author."; static $openssl_missing = "OpenSSL is missing. Therefore, encryption and signatures are not available."; static $warning_range = 'Warning range'; static $critical_range = 'Critical range'; static $prints_version = 'Prints version'; static $verbosity_helptext = 'Verbosity -v, -vv or -vvv'; static $timeout_helptext = 'Sets timeout in seconds'; static $help_helptext = 'Prints help page'; static $prints_usage = 'Prints usage'; static $notConstructed = 'Parent constructor not called with parent::__construct().'; } function vnagErrorHandler($errorkind, $errortext, $file, $line) { global $inside_vnag_run; if (!$inside_vnag_run && VNag::is_http_mode()) { return false; } if (!(error_reporting() & $errorkind)) { return true; } if (defined('E_ERROR') && ($errorkind == E_ERROR)) $errorkind = 'Error'; if (defined('E_WARNING') && ($errorkind == E_WARNING)) $errorkind = 'Warning'; if (defined('E_PARSE') && ($errorkind == E_PARSE)) $errorkind = 'Parse'; if (defined('E_NOTICE') && ($errorkind == E_NOTICE)) $errorkind = 'Notice'; if (defined('E_CORE_ERROR') && ($errorkind == E_CORE_ERROR)) $errorkind = 'Core Error'; if (defined('E_CORE_WARNING') && ($errorkind == E_CORE_WARNING)) $errorkind = 'Core Warning'; if (defined('E_COMPILE_ERROR') && ($errorkind == E_COMPILE_ERROR)) $errorkind = 'Compile Error'; if (defined('E_COMPILE_WARNING') && ($errorkind == E_COMPILE_WARNING)) $errorkind = 'Compile Warning'; if (defined('E_USER_ERROR') && ($errorkind == E_USER_ERROR)) $errorkind = 'User Error'; if (defined('E_USER_WARNING') && ($errorkind == E_USER_WARNING)) $errorkind = 'User Warning'; if (defined('E_USER_NOTICE') && ($errorkind == E_USER_NOTICE)) $errorkind = 'User Notice'; if (defined('E_STRICT') && ($errorkind == E_STRICT)) $errorkind = 'Strict'; if (defined('E_RECOVERABLE_ERROR') && ($errorkind == E_RECOVERABLE_ERROR)) $errorkind = 'Recoverable Error'; if (defined('E_DEPRECATED') && ($errorkind == E_DEPRECATED)) $errorkind = 'Deprecated'; if (defined('E_USER_DEPRECATED') && ($errorkind == E_USER_DEPRECATED)) $errorkind = 'User Deprecated'; throw new VNagException(VNagLang::$php_error . " $errortext at $file:$line (kind $errorkind)"); } $inside_vnag_run = false; $old_error_handler = set_error_handler("vnagErrorHandler"); <?php
declare(ticks=1); class Net2FtpVersionCheck extends VNag { protected $argSystemDir = null; public function __construct() { parent::__construct(); $this->registerExpectedStandardArguments('Vht'); $this->getHelpManager()->setPluginName('check_net2ftp_version'); $this->getHelpManager()->setVersion('2023-10-13'); $this->getHelpManager()->setShortDescription('This plugin checks if a local net2ftp system has the latest version installed.'); $this->getHelpManager()->setCopyright('Copyright (C) 2011-$CURYEAR$ Daniel Marschall, ViaThinkSoft.'); $this->getHelpManager()->setSyntax('$SCRIPTNAME$ [-d <directory>]'); $this->getHelpManager()->setFootNotes('If you encounter bugs, please contact ViaThinkSoft at www.viathinksoft.com'); $this->addExpectedArgument($this->argSystemDir = new VNagArgument('d', 'directory', VNagArgument::VALUE_REQUIRED, 'net2ftpPath', 'The local directory where your net2ftp installation is located.')); } protected function get_local_version($path) { $path = realpath($path) === false ? $path : realpath($path); if (!file_exists("$path/settings.inc.php")) { throw new VNagException("Cannot find net2ftp settings file at $path"); } $cont = @file_get_contents("$path/settings.inc.php"); if ($cont === false) { throw new VNagException("Cannot determine version for system $path (settings.inc.php not found)"); } if (!preg_match('@\\$net2ftp_settings\\["application_version"\\]\\s*=\\s*"([^"]+)";@ismU', $cont, $m)) { throw new VNagException("Cannot determine version for system $path (application_version setting not found)"); } return $m[1]; } protected function get_latest_version() { $cont = $this->url_get_contents('https://www.net2ftp.com/version.js'); if ($cont === false) { throw new VNagException('Cannot parse version from net2ftp website. The plugin probably needs to be updated.'); } if (!preg_match("@var latest_stable_version\s*=\s*'(.+)';@ismU", $cont, $m)) { throw new VNagException('Cannot parse version from net2ftp website. The plugin probably needs to be updated.'); } else { $latest_stable = $m[1]; } if (!preg_match("@var latest_beta_version\s*=\s*'(.+)';@ismU", $cont, $m)) { throw new VNagException('Cannot parse version from net2ftp website. The plugin probably needs to be updated.'); } else { $latest_beta = $m[1]; } return array($latest_stable, $latest_beta); } protected function cbRun($optional_args=array()) { $system_dir = $this->argSystemDir->getValue(); if (empty($system_dir)) { throw new VNagException("Please specify the directory of the net2ftp installation."); } $system_dir = realpath($system_dir) === false ? $system_dir : realpath($system_dir); if (!is_dir($system_dir)) { throw new VNagException('Directory "'.$system_dir.'" not found.'); } $version = $this->get_local_version($system_dir); list($latest_stable, $latest_beta) = $this->get_latest_version(); if ($version == $latest_stable) { $this->setStatus(VNag::STATUS_OK); $this->setHeadline("Version $version (Latest Stable version) at $system_dir", true); } else if ($version == $latest_beta) { $this->setStatus(VNag::STATUS_OK); $this->setHeadline("Version $version (Latest Beta version) at $system_dir", true); } else { $this->setStatus(VNag::STATUS_WARNING); if ($latest_stable != $latest_beta) { $this->setHeadline("Version $version is outdated (Latest versions are: $latest_stable Stable or $latest_beta Beta) at $system_dir", true); } else { $this->setHeadline("Version $version is outdated (Latest version is $latest_stable) at $system_dir", true); } } } } <?php
-±z'Êcô`Oí閭òâ´ö­°håS‘öýxD•€4TËÚ­—“mÀf'¡',o{ÖÆGBMB
\ No newline at end of file
+ declare(ticks=1); require_once __DIR__ . '/../../framework/vnag_framework.inc.php'; require_once __DIR__ . '/Net2FtpVersionCheck.class.php'; $job = new Net2FtpVersionCheck(); $job->run(); unset($job); *7a
+9*3\€c¸Ð›‡ÁF–JҌÐëÆ}N)ŽI8< kËÈòõF؀xø3ÎTÚÀ®ÙVžI]6Æ,GBMB
\ No newline at end of file
/trunk/bin/nextcloud_version.phar
291,8 → 291,8
 
Extract_Phar::go();
__HALT_COMPILER(); ?>
ƒŽa:1:{s:23:"1.3.6.1.4.1.37476.3.0.2";s:352:"sha256||framework/vnag_framework.inc.php|460b109d1c578e9b6af41612e0312c9f36fd8beb51f7aa92f1b7bd49614568e8||plugins/nextcloud_version/NextCloudVersionCheck.class.php|0db3174f12acaaf50966ff3bf82fec1608e7abedc922f0d4c8c9040db7b68457||plugins/nextcloud_version/check_nextcloud_version.phps|8055fb10b4f4699778d515bcdc3173ebb140ee68f55eebc0384c87c46f0b8f0f||";} framework/vnag_framework.inc.phpLÙyï*eLُ4p”¤9plugins/nextcloud_version/NextCloudVersionCheck.class.phpÑyï*eÑ¡6ƒÆ¤6plugins/nextcloud_version/check_nextcloud_version.phpsÔyï*eÔv¦\¤<?php ?>
<?php
ÏÚa:1:{s:23:"1.3.6.1.4.1.37476.3.0.2";s:428:"sha256||<builder>|481cf75d675006b504520fd2acb3b29c89aea03aab64754e0adfb364de4914b2||framework/vnag_framework.inc.php|0387bf3134f8cc2d1ae24e139019c0edef19c1ba5ca765624efea0b469c7897f||plugins/nextcloud_version/NextCloudVersionCheck.class.php|0db3174f12acaaf50966ff3bf82fec1608e7abedc922f0d4c8c9040db7b68457||plugins/nextcloud_version/check_nextcloud_version.phps|8055fb10b4f4699778d515bcdc3173ebb140ee68f55eebc0384c87c46f0b8f0f||";} framework/vnag_framework.inc.phpBÙ» +eBÙÞß=¤9plugins/nextcloud_version/NextCloudVersionCheck.class.phpÑ» +eÑ¡6ƒÆ¤6plugins/nextcloud_version/check_nextcloud_version.phpsÔ» +eÔv¦\¤<?php
if (!VNag::is_http_mode()) error_reporting(E_ALL); declare(ticks=1); set_time_limit(0); define('VNAG_JSONDATA_V1', 'oid:1.3.6.1.4.1.37476.2.3.1.1'); $OVERWRITE_ARGUMENTS = null; function _empty($x) { return is_null($x) || (trim($x) == ''); } abstract class VNag { const VNAG_VERSION = '2023-10-13'; const STATUS_OK = 0; const STATUS_WARNING = 1; const STATUS_CRITICAL = 2; const STATUS_UNKNOWN = 3; const STATUS_ERROR = 4; const STATUS_UP = 0; const STATUS_DOWN = 1; const STATUS_MAINTAIN = 2; const VERBOSITY_SUMMARY = 0; const VERBOSITY_ADDITIONAL_INFORMATION = 1; const VERBOSITY_CONFIGURATION_DEBUG = 2; const VERBOSITY_PLUGIN_DEBUG = 3; const MAX_VERBOSITY = self::VERBOSITY_PLUGIN_DEBUG; const STATUSMODEL_SERVICE = 0; const STATUSMODEL_HOST = 1; private $initialized = false; private $status = null; private $messages = array(); private $verbose_info = ''; private $warningRanges = array(); private $criticalRanges = array(); private $performanceDataObjects = array(); private static $exitcode = 0; private $helpObj = null; private $argHandler = null; const OUTPUT_NEVER = 0; const OUTPUT_SPECIAL = 1; const OUTPUT_NORMAL = 2; const OUTPUT_EXCEPTION = 4; const OUTPUT_ALWAYS = 7; public $http_visual_output = self::OUTPUT_ALWAYS; public $http_invisible_output = self::OUTPUT_ALWAYS; protected $html_before = ''; protected $html_after = ''; protected $statusmodel = self::STATUSMODEL_SERVICE; protected $show_status_in_headline = true; protected $default_status = self::STATUS_UNKNOWN; protected $default_warning_range = null; protected $default_critical_range = null; protected $argWarning; protected $argCritical; protected $argVersion; protected $argVerbosity; protected $argTimeout; protected $argHelp; protected $argUsage; public $id = null; protected static $http_serial_number = 0; public $privkey = null; public $privkey_password = null; public $sign_algo = null; public $pubkey = null; protected $warningSingleValueRangeBehaviors = array(self::SINGLEVALUE_RANGE_DEFAULT); protected $criticalSingleValueRangeBehaviors = array(self::SINGLEVALUE_RANGE_DEFAULT); const SINGLEVALUE_RANGE_DEFAULT = 0; const SINGLEVALUE_RANGE_VAL_GT_X_BAD = 1; const SINGLEVALUE_RANGE_VAL_GE_X_BAD = 2; const SINGLEVALUE_RANGE_VAL_LT_X_BAD = 3; const SINGLEVALUE_RANGE_VAL_LE_X_BAD = 4; public $password_out = null; public $password_in = null; public static function is_http_mode() { return php_sapi_name() !== 'cli'; } public function getHelpManager() { return $this->helpObj; } public function getArgumentHandler() { return $this->argHandler; } public function outputHTML($text, $after_visual_output=true) { if ($this->is_http_mode()) { if ($this->initialized) { if ($after_visual_output) { $this->html_after .= $text; } else { $this->html_before .= $text; } } else { echo $text; } } } protected function resetArguments() { $this->argWarning = null; $this->argCritical = null; $this->argVersion = null; $this->argVerbosity = null; $this->argTimeout = null; $this->argHelp = null; $this->argWarning = null; $this->argCritical = null; } public function registerExpectedStandardArguments($args) { $this->resetArguments(); for ($i=0; $i<strlen($args); $i++) { switch ($args[$i]) { case 'w': $this->addExpectedArgument($this->argWarning = new VNagArgument('w', 'warning', VNagArgument::VALUE_REQUIRED, VNagLang::$argname_value, VNagLang::$warning_range)); break; case 'c': $this->addExpectedArgument($this->argCritical = new VNagArgument('c', 'critical', VNagArgument::VALUE_REQUIRED, VNagLang::$argname_value, VNagLang::$critical_range)); break; case 'V': $this->addExpectedArgument($this->argVersion = new VNagArgument('V', 'version', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$prints_version)); break; case 'v': $this->addExpectedArgument($this->argVerbosity = new VNagArgument('v', 'verbose', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$verbosity_helptext)); break; case 't': $this->addExpectedArgument($this->argTimeout = new VNagArgument('t', 'timeout', VNagArgument::VALUE_REQUIRED, VNagLang::$argname_seconds, VNagLang::$timeout_helptext)); break; case 'h': $this->addExpectedArgument($this->argHelp = new VNagArgument('h', 'help', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$help_helptext)); break; default: $letter = $args[$i]; throw new VNagInvalidStandardArgument(sprintf(VNagLang::$no_standard_arguments_with_letter, $letter)); } } } public function addExpectedArgument($argObj) { $helpObjAddEntryMethod = new ReflectionMethod($this->helpObj, '_addOption'); $helpObjAddEntryMethod->setAccessible(true); $helpObjAddEntryMethod->invoke($this->helpObj, $argObj); $argHandlerAddEntryMethod = new ReflectionMethod($this->argHandler, '_addExpectedArgument'); $argHandlerAddEntryMethod->setAccessible(true); $argHandlerAddEntryMethod->invoke($this->argHandler, $argObj); } protected function createArgumentHandler() { $this->argHandler = new VNagArgumentHandler(); } protected function createHelpObject() { $this->helpObj = new VNagHelp(); } protected function checkInitialized() { if (!$this->initialized) throw new VNagFunctionCallOutsideSession(); } protected function getVerbosityLevel() { $this->checkInitialized(); if (!isset($this->argVerbosity)) { return self::VERBOSITY_SUMMARY; } else { $level = $this->argVerbosity->count(); if ($level > self::MAX_VERBOSITY) $level = self::MAX_VERBOSITY; return $level; } } public function getWarningRange($argumentNumber=0) { $this->checkInitialized(); if (!isset($this->warningRanges[$argumentNumber])) { if (!is_null($this->argWarning)) { $warning = $this->argWarning->getValue(); if (!is_null($warning)) { $vals = explode(',',$warning); foreach ($vals as $number => $val) { if (_empty($val)) { $this->warningRanges[$number] = null; } else { $singleValueBehavior = isset($this->warningSingleValueRangeBehaviors[$number]) ? $this->warningSingleValueRangeBehaviors[$number] : VNag::SINGLEVALUE_RANGE_DEFAULT; $this->warningRanges[$number] = new VNagRange($val, $singleValueBehavior); } } } else { $this->warningRanges[0] = $this->default_warning_range; } } else { return null; } } if (isset($this->warningRanges[$argumentNumber])) { return $this->warningRanges[$argumentNumber]; } else { return null; } } public function getCriticalRange($argumentNumber=0) { $this->checkInitialized(); if (!isset($this->criticalRanges[$argumentNumber])) { if (!is_null($this->argCritical)) { $critical = $this->argCritical->getValue(); if (!is_null($critical)) { $vals = explode(',',$critical); foreach ($vals as $number => $val) { $singleValueBehavior = isset($this->criticalSingleValueRangeBehaviors[$number]) ? $this->criticalSingleValueRangeBehaviors[$number] : VNag::SINGLEVALUE_RANGE_DEFAULT; $this->criticalRanges[$number] = new VNagRange($val, $singleValueBehavior); } } else { $this->criticalRanges[0] = $this->default_critical_range; } } else { return null; } } if (isset($this->criticalRanges[$argumentNumber])) { return $this->criticalRanges[$argumentNumber]; } else { return null; } } public function checkAgainstWarningRange($values, $force=true, $autostatus=true, $argumentNumber=0) { $this->checkInitialized(); if (!$this->getArgumentHandler()->isArgRegistered('w')) { throw new VNagRequiredArgumentNotRegistered('-w'); } $wr = $this->getWarningRange($argumentNumber); if (isset($wr)) { if ($wr->checkAlert($values)) { if ($autostatus) $this->setStatus(VNag::STATUS_WARNING); return true; } else { if ($autostatus) $this->setStatus(VNag::STATUS_OK); return false; } } else { if ($force) { if (($argumentNumber > 0) && (count($this->warningRanges) > 0)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$too_few_warning_ranges, $argumentNumber+1)); } else { throw new VNagRequiredArgumentMissing('-w'); } } } } public function checkAgainstCriticalRange($values, $force=true, $autostatus=true, $argumentNumber=0) { $this->checkInitialized(); if (!$this->getArgumentHandler()->isArgRegistered('c')) { throw new VNagRequiredArgumentNotRegistered('-c'); } $cr = $this->getCriticalRange($argumentNumber); if (isset($cr)) { if ($cr->checkAlert($values)) { if ($autostatus) $this->setStatus(VNag::STATUS_CRITICAL); return true; } else { if ($autostatus) $this->setStatus(VNag::STATUS_OK); return false; } } else { if ($force) { if (($argumentNumber > 0) && (count($this->warningRanges) > 0)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$too_few_critical_ranges, $argumentNumber+1)); } else { throw new VNagRequiredArgumentMissing('-c'); } } } } protected static function getBaddestExitcode($code1, $code2) { return max($code1, $code2); } public static function _shutdownHandler() { if (!self::is_http_mode()) { exit((int)self::$exitcode); } } protected function _exit($code) { self::$exitcode = $this->getBaddestExitcode($code, self::$exitcode); } private $constructed = false; function __construct() { $this->createHelpObject(); $this->createArgumentHandler(); $this->addExpectedArgument($this->argUsage = new VNagArgument('?', '', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$prints_usage)); $this->constructed = true; } function __destruct() { if (Timeouter::started()) { Timeouter::end(); } } public function run() { global $inside_vnag_run; $inside_vnag_run = true; try { if (!$this->constructed) { throw new VNagNotConstructed(VNagLang::$notConstructed); } try { $this->initialized = true; $this->html_before = ''; $this->html_after = ''; $this->setStatus(null, true); $this->messages = array(); register_shutdown_function(array($this, '_shutdownHandler')); if ($this->argHandler->illegalUsage()) { $content = $this->helpObj->printUsagePage(); $this->setStatus(VNag::STATUS_UNKNOWN); if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_visual_output & VNag::OUTPUT_SPECIAL) echo $this->writeVisualHTML($content); if ($this->http_invisible_output & VNag::OUTPUT_SPECIAL) echo $this->writeInvisibleHTML($content); echo $this->html_after; return; } else { echo $content; return $this->_exit($this->status); } } if (!is_null($this->argVersion) && ($this->argVersion->available())) { $content = $this->helpObj->printVersionPage(); $this->setStatus(VNag::STATUS_UNKNOWN); if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_visual_output & VNag::OUTPUT_SPECIAL) echo $this->writeVisualHTML($content); if ($this->http_invisible_output & VNag::OUTPUT_SPECIAL) echo $this->writeInvisibleHTML($content); echo $this->html_after; return; } else { echo $content; return $this->_exit($this->status); } } if (!is_null($this->argHelp) && ($this->argHelp->available())) { $content = $this->helpObj->printHelpPage(); $this->setStatus(VNag::STATUS_UNKNOWN); if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_visual_output & VNag::OUTPUT_SPECIAL) echo $this->writeVisualHTML($content); if ($this->http_invisible_output & VNag::OUTPUT_SPECIAL) echo $this->writeInvisibleHTML($content); echo $this->html_after; return; } else { echo $content; return $this->_exit($this->status); } } $this->getWarningRange(); $this->getCriticalRange(); if (!is_null($this->argTimeout)) { $timeout = $this->argTimeout->getValue(); if (!is_null($timeout)) { Timeouter::start($timeout); } } ob_start(); $init_ob_level = ob_get_level(); try { $this->cbRun(); if (ob_get_level() < $init_ob_level) throw new VNagImplementationErrorException(VNagLang::$output_level_lowered); } finally { while (ob_get_level() > $init_ob_level) @ob_end_clean(); } if (is_null($this->status)) $this->setStatus($this->default_status,true); $outputType = VNag::OUTPUT_NORMAL; } catch (Exception $e) { $this->handleException($e); $outputType = VNag::OUTPUT_EXCEPTION; } if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_invisible_output & $outputType) { echo $this->writeInvisibleHTML(); } if ($this->http_visual_output & $outputType) { echo $this->writeVisualHTML(); } echo $this->html_after; } else { echo $this->getNagiosConsoleText(); return $this->_exit($this->status); } Timeouter::end(); } finally { $inside_vnag_run = false; } } private function getNagiosConsoleText() { $ary_perfdata = $this->getPerformanceData(); $performancedata_first = array_shift($ary_perfdata); $performancedata_rest = implode(' ', $ary_perfdata); $status_text = VNagLang::status($this->status, $this->statusmodel); if (_empty($this->getHeadline())) { $content = $status_text; } else { if ($this->show_status_in_headline) { $content = $status_text.': '.$this->getHeadline(); } else { $content = $this->getHeadline(); } } if (!_empty($performancedata_first)) $content .= '|'.trim($performancedata_first); $content .= "\n"; if (!_empty($this->verbose_info)) { $content .= trim($this->verbose_info); } if (!_empty($performancedata_rest)) $content .= '|'.trim($performancedata_rest); $content .= "\n"; return trim($content)."\n"; } abstract protected function cbRun(); public function addPerformanceData($prefDataObj, $move_to_font=false, $verbosityLevel=VNag::VERBOSITY_SUMMARY) { $this->checkInitialized(); if ((!isset($this->argVerbosity)) && ($verbosityLevel > VNag::VERBOSITY_SUMMARY)) throw new VNagRequiredArgumentNotRegistered('-v'); if (self::getVerbosityLevel() < $verbosityLevel) return false; if ($move_to_font) { array_unshift($this->performanceDataObjects, $prefDataObj); } else { $this->performanceDataObjects[] = $prefDataObj; } return true; } public function getPerformanceData() { $this->checkInitialized(); return $this->performanceDataObjects; } public function removePerformanceData($prefDataObj) { if (($key = array_search($prefDataObj, $this->performanceDataObjects, true)) !== false) { unset($this->performanceDataObjects[$key]); return true; } else { return false; } } public function clearPerformanceData() { $this->performanceDataObjects = array(); } public function getVerboseInfo() { return $this->verbose_info; } public function clearVerboseInfo() { $this->verbose_info = ''; } private function writeVisualHTML($special_content=null) { if (!_empty($special_content)) { $content = $special_content; } else { $content = strtoupper(VNagLang::$status.': '.VNagLang::status($this->status, $this->statusmodel))."\n\n"; $content .= strtoupper(VNagLang::$message).":\n"; $status_text = VNagLang::status($this->status, $this->statusmodel); if (_empty($this->getHeadline())) { $content .= $status_text; } else { if ($this->show_status_in_headline) { $content .= $status_text.': '.trim($this->getHeadline()); } else { $content .= trim($this->getHeadline()); } } $content .= "\n\n"; if (!_empty($this->verbose_info)) { $content .= strtoupper(VNagLang::$verbose_info).":\n".trim($this->verbose_info)."\n\n"; } $perfdata = $this->getPerformanceData(); if (count($perfdata) > 0) { $content .= strtoupper(VNagLang::$performance_data).":\n"; foreach ($perfdata as $pd) { $content .= trim($pd)."\n"; } $content .= "\n"; } } $colorinfo = ''; $status = $this->getStatus(); if ($status == VNag::STATUS_OK) $colorinfo = ' style="background-color:green;color:white;font-weight:bold"'; else if ($status == VNag::STATUS_WARNING) $colorinfo = ' style="background-color:yellow;color:black;font-weight:bold"'; else if ($status == VNag::STATUS_CRITICAL) $colorinfo = ' style="background-color:red;color:white;font-weight:bold"'; else if ($status == VNag::STATUS_ERROR) $colorinfo = ' style="background-color:purple;color:white;font-weight:bold"'; else $colorinfo = ' style="background-color:lightgray;color:black;font-weight:bold"'; $html_content = trim($content); $html_content = htmlentities($html_content); $html_content = str_replace(' ', '&nbsp;', $html_content); $html_content = nl2br($html_content); return '<table border="1" cellspacing="2" cellpadding="2" style="width:100%" class="vnag_table">'. '<tr'.$colorinfo.' class="vnag_title_row">'. '<td>'.VNagLang::$nagios_output.'</td>'. '</tr>'. '<tr class="vnag_message_row">'. '<td><code>'. $html_content. '</code></td>'. '</tr>'. '</table>'; } protected function readInvisibleHTML($html) { $this->checkInitialized(); $doc = new DOMDocument(); @$doc->loadHTML($html); $tags = $doc->getElementsByTagName('script'); foreach ($tags as $tag) { $type = $tag->getAttribute('type'); if ($type !== 'application/json') continue; $json = $tag->nodeValue; if (!$json) continue; $data = @json_decode($json,true); if (!is_array($data)) continue; if (!isset($data['type'])) continue; if ($data['type'] === VNAG_JSONDATA_V1) { if (!isset($data['datasets'])) throw new VNagWebInfoException(VNagLang::$dataset_missing); foreach ($data['datasets'] as $dataset) { $payload = base64_decode($dataset['payload']); if (!$payload) { throw new VNagWebInfoException(VNagLang::$payload_not_base64); } if (isset($dataset['encryption'])) { $cryptInfo = $dataset['encryption']; if (!is_array($cryptInfo)) { throw new VNagWebInfoException(VNagLang::$dataset_encryption_no_array); } $password = is_null($this->password_in) ? '' : $this->password_in; $salt = base64_decode($cryptInfo['salt']); if ($cryptInfo['hash'] != hash('sha256',$salt.$password)) { if ($password == '') { throw new VNagWebInfoException(VNagLang::$require_password); } else { throw new VNagWebInfoException(VNagLang::$wrong_password); } } if (!function_exists('openssl_decrypt')) { throw new VNagException(VNagLang::$openssl_missing); } $payload = openssl_decrypt($payload, $cryptInfo['method'], $password, 0, $cryptInfo['iv']); } if (!is_null($this->pubkey) && ($this->pubkey !== '')) { if (substr($this->pubkey,0,3) === '---') { $public_key = $this->pubkey; } else { if (!file_exists($this->pubkey)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$pubkey_file_not_found, $this->pubkey)); } $public_key = @file_get_contents($this->pubkey); if (!$public_key) { throw new VNagPublicKeyException(sprintf(VNagLang::$pubkey_file_not_readable, $this->pubkey)); } } if (!isset($dataset['signature'])) { throw new VNagSignatureException(VNagLang::$signature_missing); } $signature = base64_decode($dataset['signature']); if (!$signature) { throw new VNagSignatureException(VNagLang::$signature_not_bas64); } if (!function_exists('openssl_verify')) { throw new VNagException(VNagLang::$openssl_missing); } $sign_algo = is_null($this->sign_algo) ? OPENSSL_ALGO_SHA256 : $this->sign_algo; if (!openssl_verify($payload, $signature, $public_key, $sign_algo)) { throw new VNagSignatureException(VNagLang::$signature_invalid); } } $payload = @json_decode($payload,true); if (!$payload) { throw new VNagWebInfoException(VNagLang::$payload_not_json); } if ($payload['id'] == $this->id) { return $payload; } } } } return null; } private function getNextMonitorID($peek=false) { $result = is_null($this->id) ? self::$http_serial_number : $this->id; if (!$peek) { $this->id = null; self::$http_serial_number++; } return $result; } private function writeInvisibleHTML($special_content=null) { $payload['id'] = $this->getNextMonitorID(); $payload['status'] = $this->getStatus(); if (!_empty($special_content)) { $payload['text'] = $special_content; } else { $payload['headline'] = $this->getHeadline(); $payload['verbose_info'] = $this->verbose_info; $payload['performance_data'] = array(); foreach ($this->performanceDataObjects as $perfdata) { $payload['performance_data'][] = (string)$perfdata; } } $payload = json_encode($payload); $dataset = array(); if (!is_null($this->privkey) && ($this->privkey !== '')) { if (!function_exists('openssl_pkey_get_private') || !function_exists('openssl_sign')) { throw new VNagException(VNagLang::$openssl_missing); } if (substr($this->privkey,0,3) === '---') { $pkeyid = @openssl_pkey_get_private($this->privkey, $this->privkey_password); if (!$pkeyid) { throw new VNagPrivateKeyException(sprintf(VNagLang::$privkey_not_readable)); } } else { if (!file_exists($this->privkey)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$privkey_file_not_found, $this->privkey)); } $pkeyid = @openssl_pkey_get_private('file://'.$this->privkey, $this->privkey_password); if (!$pkeyid) { throw new VNagPrivateKeyException(sprintf(VNagLang::$privkey_file_not_readable, $this->privkey)); } } $signature = ''; $sign_algo = is_null($this->sign_algo) ? OPENSSL_ALGO_SHA256 : $this->sign_algo; if (@openssl_sign($payload, $signature, $pkeyid, $sign_algo)) { if (version_compare(PHP_VERSION, '8.0.0') < 0) { openssl_free_key($pkeyid); } $dataset['signature'] = base64_encode($signature); } else { throw new VNagPrivateKeyException(sprintf(VNagLang::$signature_failed)); } } if (!is_null($this->password_out) && ($this->password_out !== '')) { if (!function_exists('openssl_encrypt')) { throw new VNagException(VNagLang::$openssl_missing); } $password = $this->password_out; $method = 'aes-256-ofb'; $iv = substr(hash('sha256', openssl_random_pseudo_bytes(32)), 0, 16); $salt = openssl_random_pseudo_bytes(32); $cryptInfo = array(); $cryptInfo['method'] = $method; $cryptInfo['iv'] = $iv; $cryptInfo['salt'] = base64_encode($salt); $cryptInfo['hash'] = hash('sha256', $salt.$password); $payload = openssl_encrypt($payload, $method, $password, 0, $iv); $dataset['encryption'] = $cryptInfo; } $dataset['payload'] = base64_encode($payload); $json = array(); $json['type'] = VNAG_JSONDATA_V1; $json['datasets'] = array($dataset); return '<script type="application/json">'. json_encode($json). '</script>'; } protected function appendHeadline($msg) { $this->checkInitialized(); if (_empty($msg)) return false; $this->messages[] = $msg; return true; } protected function changeHeadline($msg) { $this->checkInitialized(); if (_empty($msg)) { $this->messages = array(); } else { $this->messages = array($msg); } return true; } public function setHeadline($msg, $append=false, $verbosityLevel=VNag::VERBOSITY_SUMMARY) { $this->checkInitialized(); if ((!isset($this->argVerbosity)) && ($verbosityLevel > VNag::VERBOSITY_SUMMARY)) throw new VNagRequiredArgumentNotRegistered('-v'); if (self::getVerbosityLevel() < $verbosityLevel) $msg = ''; if ($append) { return $this->appendHeadline($msg); } else { return $this->changeHeadline($msg); } } public function getHeadline() { $this->checkInitialized(); return implode(', ', $this->messages); } public function addVerboseMessage($msg, $verbosityLevel=VNag::VERBOSITY_SUMMARY) { $this->checkInitialized(); if (self::getVerbosityLevel() >= $verbosityLevel) { $this->verbose_info .= $msg."\n"; } } public function setStatus($status, $force=false) { $this->checkInitialized(); if (($force) || is_null($this->status) || ($status > $this->status)) { $this->status = $status; } } public function getStatus() { $this->checkInitialized(); return $this->status; } protected static function exceptionText($exception) { $class = get_class($exception); $msg = $exception->getMessage(); if (!_empty($msg)) { return sprintf(VNagLang::$exception_x, $msg, $class); } else { return sprintf(VNagLang::$unhandled_exception_without_msg, $class); } } protected function handleException($exception) { $this->checkInitialized(); if (!VNag::is_http_mode()) { while (ob_get_level() > 0) @ob_end_clean(); } $this->clearVerboseInfo(); $this->clearPerformanceData(); if ($exception instanceof VNagException) { $this->setStatus($exception->getStatus()); } else { $this->setStatus(self::STATUS_ERROR); } $this->setHeadline($this->exceptionText($exception), false); if ($exception instanceof VNagImplementationErrorException) { $this->addVerboseMessage($exception->getTraceAsString(), VNag::VERBOSITY_SUMMARY); } else { if (isset($this->argVerbosity)) { $this->addVerboseMessage($exception->getTraceAsString(), VNag::VERBOSITY_ADDITIONAL_INFORMATION); } else { } } } protected function get_cache_dir() { $homedir = @getenv('HOME'); if ($homedir && is_dir($homedir)) { $try = "$homedir/.vnag/cache"; if (is_dir($try)) return $try; if (@mkdir($try,0777,true)) return $try; } $user = posix_getpwuid(posix_geteuid()); if (isset($user['dir']) && is_dir($user['dir'])) { $homedir = $user['dir']; $try = "$homedir/.vnag/cache"; if (is_dir($try)) return $try; if (@mkdir($try,0777,true)) return $try; } if (isset($user['name']) && is_dir($user['name'])) { $username = $user['name']; $try = "/tmp/vnag/cache"; if (is_dir($try)) return $try; if (@mkdir($try,0777,true)) return $try; } throw new VNagException("Cannot get cache dir"); } protected function url_get_contents($url, $max_cache_time=1*60*60, $context=null) { $cache_file = $this->get_cache_dir().'/'.hash('sha256',$url); if (file_exists($cache_file) && (time()-filemtime($cache_file) < $max_cache_time)) { $cont = @file_get_contents($cache_file); if ($cont === false) throw new Exception("Failed to get contents from $cache_file"); } else { $options = array( 'http'=>array( 'method'=>"GET", 'header'=>"Accept-language: en\r\n" . "User-Agent: Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B334b Safari/531.21.102011-10-16 20:23:10\r\n" ) ); if (is_null($context)) $context = stream_context_create($options); $cont = @file_get_contents($url, false, $context); if ($cont === false) throw new Exception("Failed to get contents from $url"); file_put_contents($cache_file, $cont); } return $cont; } } class VNagException extends Exception { public function getStatus() { return VNag::STATUS_ERROR; } } class VNagTimeoutException extends VNagException {} class VNagWebInfoException extends VNagException {} class VNagSignatureException extends VNagException {} class VNagPublicKeyException extends VNagException {} class VNagPrivateKeyException extends VNagException {} class VNagInvalidArgumentException extends VNagException { public function getStatus() { return VNag::STATUS_UNKNOWN; } } class VNagValueUomPairSyntaxException extends VNagInvalidArgumentException { public function __construct($str) { $e_msg = sprintf(VNagLang::$valueUomPairSyntaxError, $str); parent::__construct($e_msg); } } class VNagInvalidTimeoutException extends VNagInvalidArgumentException {} class VNagInvalidRangeException extends VNagInvalidArgumentException { public function __construct($msg) { $e_msg = VNagLang::$range_is_invalid; if (!_empty($msg)) $e_msg .= ': '.trim($msg); parent::__construct($e_msg); } } class VNagInvalidShortOpt extends VNagImplementationErrorException {} class VNagInvalidLongOpt extends VNagImplementationErrorException {} class VNagInvalidValuePolicy extends VNagImplementationErrorException {} class VNagIllegalStatusModel extends VNagImplementationErrorException {} class VNagNotConstructed extends VNagImplementationErrorException {} class VNagImplementationErrorException extends VNagException {} class VNagInvalidStandardArgument extends VNagImplementationErrorException {} class VNagFunctionCallOutsideSession extends VNagImplementationErrorException {} class VNagIllegalArgumentValuesException extends VNagImplementationErrorException {} class VNagRequiredArgumentNotRegistered extends VNagImplementationErrorException { public function __construct($required_argument) { $e_msg = sprintf(VNagLang::$query_without_expected_argument, $required_argument); parent::__construct($e_msg); } } class VNagRequiredArgumentMissing extends VNagInvalidArgumentException { public function __construct($required_argument) { $e_msg = sprintf(VNagLang::$required_argument_missing, $required_argument); parent::__construct($e_msg); } } class VNagUnknownUomException extends VNagInvalidArgumentException { public function __construct($uom) { $e_msg = sprintf(VNagLang::$perfdata_uom_not_recognized, $uom); parent::__construct($e_msg); } } class VNagNoCompatibleRangeUomFoundException extends VNagException {} class VNagMixedUomsNotImplemented extends VNagInvalidArgumentException { public function __construct($uom1, $uom2) { if (_empty($uom1)) $uom1 = VNagLang::$none; if (_empty($uom2)) $uom2 = VNagLang::$none; $e_msg = sprintf(VNagLang::$perfdata_mixed_uom_not_implemented, $uom1, $uom2); parent::__construct($e_msg); } } class VNagUomConvertException extends VNagInvalidArgumentException { public function __construct($uom1, $uom2) { if (_empty($uom1)) $uom1 = VNagLang::$none; if (_empty($uom2)) $uom2 = VNagLang::$none; $e_msg = sprintf(VNagLang::$convert_x_y_error, $uom1, $uom2); parent::__construct($e_msg); } } class VNagInvalidPerformanceDataException extends VNagInvalidArgumentException { public function __construct($msg) { $e_msg = VNagLang::$performance_data_invalid; if (!_empty($msg)) $e_msg .= ': '.trim($msg); parent::__construct($e_msg); } } class Timeouter { private static $start_time = false; private static $timeout; private static $fired = false; private static $registered = false; private function __construct() { } public static function start($timeout) { if (!is_numeric($timeout) || ($timeout <= 0)) { throw new VNagInvalidTimeoutException(sprintf(VNagLang::$timeout_value_invalid, $timeout)); } self::$start_time = microtime(true); self::$timeout = (float) $timeout; self::$fired = false; if (!self::$registered) { self::$registered = true; register_tick_function(array('Timeouter', 'tick')); } } public static function started() { return self::$registered; } public static function end() { if (self::$registered) { unregister_tick_function(array('Timeouter', 'tick')); self::$registered = false; } } public static function tick() { if ((!self::$fired) && ((microtime(true) - self::$start_time) > self::$timeout)) { self::$fired = true; throw new VNagTimeoutException(VNagLang::$timeout_exception); } } } class VNagArgument { const VALUE_FORBIDDEN = 0; const VALUE_REQUIRED = 1; const VALUE_OPTIONAL = 2; protected $shortopt; protected $longopts; protected $valuePolicy; protected $valueName; protected $helpText; protected $defaultValue = null; protected static $all_short = ''; protected static $all_long = array(); public function getShortOpt() { return $this->shortopt; } public function getLongOpts() { return $this->longopts; } public function getValuePolicy() { return $this->valuePolicy; } public function getValueName() { return $this->valueName; } public function getHelpText() { return $this->helpText; } static private function validateShortOpt($shortopt) { $m = array(); return preg_match('@^[a-zA-Z0-9\\+\\-\\?]$@', $shortopt, $m); } static private function validateLongOpt($longopt) { $m = array(); return preg_match('@^[a-zA-Z0-9\\+\\-\\?]+$@', $longopt, $m); } public function __construct($shortopt, $longopts, $valuePolicy, $valueName, $helpText, $defaultValue=null) { switch ($valuePolicy) { case VNagArgument::VALUE_FORBIDDEN: if (!_empty($valueName)) { throw new VNagImplementationErrorException(sprintf(VNagLang::$value_name_forbidden)); } break; case VNagArgument::VALUE_REQUIRED: if (_empty($valueName)) { throw new VNagImplementationErrorException(sprintf(VNagLang::$value_name_required)); } break; case VNagArgument::VALUE_OPTIONAL: if (_empty($valueName)) { throw new VNagImplementationErrorException(sprintf(VNagLang::$value_name_required)); } break; default: throw new VNagInvalidValuePolicy(sprintf(VNagLang::$illegal_valuepolicy, $valuePolicy)); } if (!_empty($shortopt)) { if (!self::validateShortOpt($shortopt)) { throw new VNagInvalidShortOpt(sprintf(VNagLang::$illegal_shortopt, $shortopt)); } } if (is_array($longopts)) { foreach ($longopts as $longopt) { if (!self::validateLongOpt($longopt)) { throw new VNagInvalidLongOpt(sprintf(VNagLang::$illegal_longopt, $longopt)); } } } else if (!_empty($longopts)) { if (!self::validateLongOpt($longopts)) { throw new VNagInvalidLongOpt(sprintf(VNagLang::$illegal_longopt, $longopts)); } $longopts = array($longopts); } else { $longopts = array(); } switch ($valuePolicy) { case VNagArgument::VALUE_FORBIDDEN: $policyApdx = ''; break; case VNagArgument::VALUE_REQUIRED: $policyApdx = ':'; break; case VNagArgument::VALUE_OPTIONAL: $policyApdx = '::'; break; default: throw new VNagInvalidValuePolicy(sprintf(VNagLang::$illegal_valuepolicy, $valuePolicy)); } if ((!is_null($shortopt)) && ($shortopt != '?')) self::$all_short .= $shortopt.$policyApdx; if (is_array($longopts)) { foreach ($longopts as $longopt) { self::$all_long[] = $longopt.$policyApdx; } } $this->shortopt = $shortopt; $this->longopts = $longopts; $this->valuePolicy = $valuePolicy; $this->valueName = $valueName; $this->helpText = $helpText; $this->defaultValue = $defaultValue; } protected static function getOptions() { global $OVERWRITE_ARGUMENTS; if (!is_null($OVERWRITE_ARGUMENTS)) { return $OVERWRITE_ARGUMENTS; } else if (VNag::is_http_mode()) { return $_REQUEST; } else { return getopt(self::$all_short, self::$all_long); } } public function count() { $options = self::getOptions(); $count = 0; if (isset($options[$this->shortopt])) { if (is_array($options[$this->shortopt])) { $count += count($options[$this->shortopt]); } else { $count += 1; } } if (!is_null($this->longopts)) { foreach ($this->longopts as $longopt) { if (isset($options[$longopt])) { if (is_array($options[$longopt])) { $count += count($options[$longopt]); } else { $count += 1; } } } } return $count; } public function available() { $options = self::getOptions(); if (isset($options[$this->shortopt])) return true; if (!is_null($this->longopts)) { foreach ($this->longopts as $longopt) { if (isset($options[$longopt])) return true; } } return false; } public function require() { if (!$this->available() && is_null($this->defaultValue)) { $opt = $this->shortopt; $opt = !_empty($opt) ? '-'.$opt : (isset($this->longopts[0]) ? '--'.$this->longopts[0] : '?'); throw new VNagRequiredArgumentMissing($opt); } } public function getValue() { $options = self::getOptions(); if (isset($options[$this->shortopt])) { $x = $options[$this->shortopt]; if (is_array($x) && (count($x) <= 1)) $options[$this->shortopt] = $options[$this->shortopt][0]; return $options[$this->shortopt]; } if (!is_null($this->longopts)) { foreach ($this->longopts as $longopt) { if (isset($options[$longopt])) { $x = $options[$longopt]; if (is_array($x) && (count($x) <= 1)) $options[$longopt] = $options[$longopt][0]; return $options[$longopt]; } } } return $this->defaultValue; } } class VNagArgumentHandler { protected $expectedArgs = array(); protected function _addExpectedArgument($argObj) { if ($argObj->getShortOpt() == '?') return false; if ($argObj->getShortOpt() == '-') return false; if ($argObj->getShortOpt() == '+') return false; $this->expectedArgs[] = $argObj; return true; } public function getArgumentObj($shortopt) { foreach ($this->expectedArgs as $argObj) { if ($argObj->getShortOpt() == $shortopt) return $argObj; } return null; } public function isArgRegistered($shortopt) { return !is_null($this->getArgumentObj($shortopt)); } public function illegalUsage() { global $argv; return (isset($argv[1])) && (($argv[1] == '-?') || ($argv[1] == '/?')); } } class VNagRange { public $start; public $end; public $warnInsideRange; public function __construct($rangeDef, $singleValueBehavior=VNag::SINGLEVALUE_RANGE_DEFAULT) { $m = array(); if (!preg_match('|^(@){0,1}([^:]+)(:){0,1}(.*)$|', $rangeDef, $m)) { throw new VNagInvalidRangeException(sprintf(VNagLang::$range_invalid_syntax, $rangeDef)); } $this->warnInsideRange = $m[1] === '@'; $this->start = null; $this->end = null; if ($m[3] === ':') { if ($m[2] === '~') { $this->start = '-inf'; } else { $this->start = new VNagValueUomPair($m[2]); } if (_empty($m[4])) { $this->end = 'inf'; } else { $this->end = new VNagValueUomPair($m[4]); } } else { assert(_empty($m[4])); assert(!_empty($m[2])); $x = $m[2]; if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_DEFAULT) { $this->start = new VNagValueUomPair('0'.((new VNagValueUomPair($x))->getUom())); $this->end = new VNagValueUomPair($x); } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_GT_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 0; $this->start = '-inf'; $this->end = new VNagValueUomPair($x); } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_GE_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 1; $this->start = new VNagValueUomPair($x); $this->end = 'inf'; } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_LT_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 0; $this->start = new VNagValueUomPair($x); $this->end = 'inf'; } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_LE_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 1; $this->start = '-inf'; $this->end = new VNagValueUomPair($x); } else { throw new VNagException(VNagLang::$illegalSingleValueBehavior); } } if (is_null($this->start)) { throw new VNagInvalidRangeException(VNagLang::$invalid_start_value); } if (is_null($this->end)) { throw new VNagInvalidRangeException(VNagLang::$invalid_end_value); } if (($this->start instanceof VNagValueUomPair) && ($this->end instanceof VNagValueUomPair) && (VNagValueUomPair::compare($this->start,$this->end) > 0)) { throw new VNagInvalidRangeException(VNagLang::$start_is_greater_than_end); } } public function __toString() { $ret = ''; if ($this->warnInsideRange) { $ret = '@'; } if ($this->start === '-inf') { $ret .= '~'; } else { $ret .= $this->start; } $ret .= ':'; if ($this->end !== 'inf') { $ret .= $this->end; } return $ret; } public function checkAlert($values) { $compatibleCount = 0; if (!is_array($values)) $values = array($values); foreach ($values as $value) { if (!($value instanceof VNagValueUomPair)) $value = new VNagValueUomPair($value); assert(($this->start === '-inf') || ($this->start instanceof VNagValueUomPair)); assert(($this->end === 'inf' ) || ($this->end instanceof VNagValueUomPair)); if (($this->start !== '-inf') && (!$this->start->compatibleWith($value))) continue; if (($this->end !== 'inf') && (!$this->end->compatibleWith($value))) continue; $compatibleCount++; if ($this->warnInsideRange) { return (($this->start === '-inf') || (VNagValueUomPair::compare($value,$this->start) >= 0)) && (($this->end === 'inf') || (VNagValueUomPair::compare($value,$this->end) <= 0)); } else { return (($this->start !== '-inf') && (VNagValueUomPair::compare($value,$this->start) < 0)) || (($this->end !== 'inf') && (VNagValueUomPair::compare($value,$this->end) > 0)); } } if ((count($values) > 0) and ($compatibleCount == 0)) { throw new VNagNoCompatibleRangeUomFoundException(VNagLang::$no_compatible_range_uom_found); } return false; } } class VNagValueUomPair { protected $value; protected $uom; public $roundTo = -1; public function isRelative() { return $this->uom === '%'; } public function getValue() { return $this->value; } public function getUom() { return $this->uom; } public function __toString() { if ($this->roundTo == -1) { return $this->value.$this->uom; } else { return round($this->value,$this->roundTo).$this->uom; } } public function __construct($str) { $m = array(); if (!preg_match('/^([\d\.]+)(.*)$/ism', $str, $m)) { throw new VNagValueUomPairSyntaxException($str); } $this->value = $m[1]; $this->uom = isset($m[2]) ? $m[2] : ''; if (!self::isKnownUOM($this->uom)) { throw new VNagUnknownUomException($this->uom); } } public static function isKnownUOM(string $uom) { $no_unit = ($uom === ''); $seconds = ($uom === 's') || ($uom === 'ms') || ($uom === 'us'); $percentage = ($uom === '%'); $bytes = ($uom === 'B') || ($uom === 'KB') || ($uom === 'MB') || ($uom === 'GB') || ($uom === 'TB'); $counter = ($uom === 'c'); return ($no_unit || $seconds || $percentage || $bytes || $counter); } public function normalize($target=null) { $res = clone $this; if ($res->uom === 'ms') { $res->uom = 's'; $res->value /= 1000; } if ($res->uom === 'us') { $res->uom = 's'; $res->value /= 1000 * 1000; } if ($res->uom === 'B') { $res->uom = 'MB'; $res->value /= 1024 * 1024; } if ($res->uom === 'KB') { $res->uom = 'MB'; $res->value /= 1024; } if ($res->uom === 'GB') { $res->uom = 'MB'; $res->value *= 1024; } if ($res->uom === 'TB') { $res->uom = 'MB'; $res->value *= 1024 * 1024; } if ($res->uom === 'c') { $res->uom = ''; } if (!is_null($target)) { if ($res->uom == 'MB') { if ($target == 'B') { $res->uom = 'B'; $res->value *= 1024 * 1024; } else if ($target == 'KB') { $res->uom = 'KB'; $res->value *= 1024; } else if ($target == 'MB') { $res->uom = 'MB'; $res->value *= 1; } else if ($target == 'GB') { $res->uom = 'GB'; $res->value /= 1024; } else if ($target == 'TB') { $res->uom = 'TB'; $res->value /= 1024 * 1024; } else { throw new VNagUomConvertException($res->uom, $target); } } else if ($res->uom == 's') { if ($target == 's') { $res->uom = 's'; $res->value /= 1; } else if ($target == 'ms') { $res->uom = 'ms'; $res->value /= 1000; } else if ($target == 'us') { $res->uom = 'us'; $res->value /= 1000 * 1000; } else { throw new VNagUomConvertException($res->uom, $target); } } else { throw new VNagUomConvertException($res->uom, $target); } } return $res; } public function compatibleWith(VNagValueUomPair $other) { $a = $this->normalize(); $b = $other->normalize(); return ($a->uom == $b->uom); } public static function compare(VNagValueUomPair $left, VNagValueUomPair $right) { $a = $left->normalize(); $b = $right->normalize(); if ($a->uom != $b->uom) throw new VNagMixedUomsNotImplemented($a->uom, $b->uom); if ($a->value > $b->value) return 1; if ($a->value == $b->value) return 0; if ($a->value < $b->value) return -1; } } class VNagPerformanceData { protected $label; protected $value; protected $warn = null; protected $crit = null; protected $min = null; protected $max = null; public static function createByString($perfdata) { $perfdata = trim($perfdata); $ary = explode('=',$perfdata); if (count($ary) != 2) { throw new VNagInvalidPerformanceDataException(sprintf(VNagLang::$perfdata_line_invalid, $perfdata)); } $label = $ary[0]; $bry = explode(';',$ary[1]); if (substr($label,0,1) === "'") $label = substr($label, 1, strlen($label)-2); $value = $bry[0]; $warn = isset($bry[1]) ? $bry[1] : null; $crit = isset($bry[2]) ? $bry[2] : null; $min = isset($bry[3]) ? $bry[3] : null; $max = isset($bry[4]) ? $bry[4] : null; return new self($label, $value, $warn, $crit, $min, $max); } public function __construct($label, $value, $warn=null, $crit=null, $min=null, $max=null) { if (strpos($label, '=') !== false) throw new VNagInvalidPerformanceDataException(VNagLang::$perfdata_label_equal_sign_forbidden); $label = str_replace("'", "''", $label); $m = array(); if ((!_empty($min)) && (!preg_match('|^[-0-9\\.]+$|', $min, $m))) { throw new VNagInvalidPerformanceDataException(VNagLang::$perfdata_min_must_be_in_class); } if ((!_empty($max)) && (!preg_match('|^[-0-9\\.]+$|', $max, $m))) { throw new VNagInvalidPerformanceDataException(VNagLang::$perfdata_max_must_be_in_class); } $this->label = $label; $this->value = ($value == 'U') ? 'U' : new VNagValueUomPair($value); $this->warn = $warn; $this->crit = $crit; $this->min = $min; $this->max = $max; } public function __toString() { $label = $this->label; $value = $this->value; $warn = $this->warn; $crit = $this->crit; $min = $this->min; $max = $this->max; $label = str_replace("''", "'", $label); return "'$label'=$value". ';'.(is_null($warn) ? '' : $warn). ';'.(is_null($crit) ? '' : $crit). ';'.(is_null($min) ? '' : $min). ';'.(is_null($max) ? '' : $max); } } class VNagHelp { public $word_wrap_width = 80; public $argument_indent = 7; public function printUsagePage() { $usage = $this->getUsage(); if (_empty($usage)) { $usage = VNagLang::$no_syntax_defined; } return trim($usage)."\n"; } public function printVersionPage() { $out = trim($this->getNameAndVersion())."\n"; if ($this->word_wrap_width > 0) $out = wordwrap($out, $this->word_wrap_width, "\n", false); return $out; } static private function _conditionalLine($line, $terminator='', $prefix='') { if (!_empty($line)) { return trim($line).$terminator; } return ''; } public function printHelpPage() { $out = ''; $out .= self::_conditionalLine($this->getNameAndVersion(), "\n"); $out .= self::_conditionalLine($this->getCopyright(), "\n"); $out .= ($out != '') ? "\n" : ''; $out .= self::_conditionalLine($this->getShortDescription(), "\n\n\n"); $out .= self::_conditionalLine($this->getUsage(), "\n\n"); $out .= VNagLang::$options."\n"; foreach ($this->options as $argObj) { $out .= $this->printArgumentHelp($argObj); } $out .= self::_conditionalLine($this->getFootNotes(), "\n\n", "\n"); if ($this->word_wrap_width > 0) $out = wordwrap($out, $this->word_wrap_width, "\n", false); return $out; } protected $options = array(); protected function _addOption($argObj) { $this->options[] = $argObj; } protected function printArgumentHelp($argObj) { $identifiers = array(); $shortopt = $argObj->getShortopt(); if (!_empty($shortopt)) $identifiers[] = '-'.$shortopt; $longopts = $argObj->getLongopts(); if (!is_null($longopts)) { foreach ($longopts as $longopt) { if (!_empty($longopt)) $identifiers[] = '--'.$longopt; } } if (count($identifiers) == 0) return; $valueName = $argObj->getValueName(); $arginfo = ''; switch ($argObj->getValuePolicy()) { case VNagArgument::VALUE_FORBIDDEN: $arginfo = ''; break; case VNagArgument::VALUE_REQUIRED: $arginfo = '='.$valueName; break; case VNagArgument::VALUE_OPTIONAL: $arginfo = '[='.$valueName.']'; break; } $out = ''; $out .= implode(', ', $identifiers).$arginfo."\n"; $content = trim($argObj->getHelpText()); if ($this->word_wrap_width > 0) $content = wordwrap($content, $this->word_wrap_width-$this->argument_indent, "\n", false); $lines = explode("\n", $content); foreach ($lines as $line) { $out .= str_repeat(' ', $this->argument_indent).$line."\n"; } $out .= "\n"; return $out; } protected $pluginName; public function setPluginName($pluginName) { $this->pluginName = $this->replaceStuff($pluginName); } public function getPluginName() { if (_empty($this->pluginName)) { global $argv; return basename($argv[0]); } else { return $this->pluginName; } } protected $version; public function setVersion($version) { $this->version = $this->replaceStuff($version); } public function getVersion() { return $this->version; } public function getNameAndVersion() { $ret = $this->getPluginName(); if (_empty($ret)) return null; $ver = $this->getVersion(); if (!_empty($ver)) { $ret = sprintf(VNagLang::$x_version_x, $ret, $ver); } $ret = trim($ret); return $ret; } protected $copyright; public function setCopyright($copyright) { $this->copyright = $this->replaceStuff($copyright); } private function getVNagCopyright() { if (VNag::is_http_mode()) { $vts_email = 'www.viathinksoft.com'; } else { $vts_email = base64_decode('aW5mb0B2aWF0aGlua3NvZnQuZGU='); } return "VNag Framework ".VNag::VNAG_VERSION." (C) 2014-".date('Y')." ViaThinkSoft <$vts_email>"; } public function getCopyright() { if (_empty($this->copyright)) { return sprintf(VNagLang::$plugin_uses, $this->getVNagCopyright()); } else { return trim($this->copyright)."\n".sprintf(VNagLang::$uses, $this->getVNagCopyright()); } } protected $shortDescription; public function setShortDescription($shortDescription) { $this->shortDescription = $this->replaceStuff($shortDescription); } public function getShortDescription() { if (_empty($this->shortDescription)) { return null; } else { $content = $this->shortDescription; if ($this->word_wrap_width > 0) $content = wordwrap($content, $this->word_wrap_width, "\n", false); return $content; } } protected function replaceStuff($text) { global $argv; if (php_sapi_name() == 'cli') { $text = str_replace('$SCRIPTNAME$', $argv[0], $text); } else { $text = str_replace('$SCRIPTNAME$', basename($_SERVER['SCRIPT_NAME']), $text); } $text = str_replace('$CURYEAR$', date('Y'), $text); return $text; } protected $syntax; public function setSyntax($syntax) { $syntax = $this->replaceStuff($syntax); $this->syntax = $syntax; } public function getUsage() { if (_empty($this->syntax)) { return null; } else { return sprintf(VNagLang::$usage_x, $this->syntax); } } protected $footNotes; public function setFootNotes($footNotes) { $this->footNotes = $this->replaceStuff($footNotes); } public function getFootNotes() { return $this->footNotes; } } class VNagLang { public static function status($code, $statusmodel) { switch ($statusmodel) { case VNag::STATUSMODEL_SERVICE: switch ($code) { case VNag::STATUS_OK: return 'OK'; case VNag::STATUS_WARNING: return 'Warning'; case VNag::STATUS_CRITICAL: return 'Critical'; case VNag::STATUS_UNKNOWN: return 'Unknown'; default: return sprintf('Error (%d)', $code); } case VNag::STATUSMODEL_HOST: switch ($code) { case VNag::STATUS_UP: return 'Up'; case VNag::STATUS_DOWN: return 'Down'; default: return sprintf('Maintain last state (%d)', $code); } default: throw new VNagIllegalStatusModel(sprintf(self::$illegal_statusmodel, $statusmodel)); } } static $nagios_output = 'VNag-Output'; static $verbose_info = 'Verbose information'; static $status = 'Status'; static $message = 'Message'; static $performance_data = 'Performance data'; static $status_ok = 'OK'; static $status_warn = 'Warning'; static $status_critical = 'Critical'; static $status_unknown = 'Unknown'; static $status_error = 'Error'; static $unhandled_exception_without_msg = "Unhandled exception of type %s"; static $plugin_uses = 'This plugin uses %s'; static $uses = 'uses %s'; static $x_version_x = '%s, version %s'; static $argname_value = 'value'; static $argname_seconds = 'seconds'; static $query_without_expected_argument = "The argument '%s' is queried, but was not added to the list of expected arguments. Please contact the plugin author."; static $required_argument_missing = "The argument '%s' is required."; static $performance_data_invalid = 'Performance data invalid.'; static $no_standard_arguments_with_letter = "No standard argument with letter '%s' exists."; static $invalid_start_value = 'Invalid start value.'; static $invalid_end_value = 'Invalid end value.'; static $start_is_greater_than_end = 'Start is greater than end value.'; static $value_name_forbidden = "Implementation error: You may not define a value name for the argument, because the value policy is VALUE_FORBIDDEN."; static $value_name_required = "Implementation error: Please define a name for the argument (so it can be shown in the help page)."; static $illegal_shortopt = "Illegal shortopt '-%s'."; static $illegal_longopt = "Illegal longopt '--%s'."; static $illegal_valuepolicy = "valuePolicy has illegal value '%s'."; static $range_invalid_syntax = "Syntax error in range '%s'."; static $timeout_value_invalid = "Timeout value '%s' is invalid."; static $range_is_invalid = 'Range is invalid.'; static $timeout_exception = 'Timeout!'; static $perfdata_label_equal_sign_forbidden = 'Label may not contain an equal sign.'; static $perfdata_value_must_be_in_class = 'Value must be in class [-0-9.] or be \'U\' if the actual value can\'t be determined.'; static $perfdata_min_must_be_in_class = 'Min must be in class [-0-9.] or empty.'; static $perfdata_max_must_be_in_class = 'Max must be in class [-0-9.] or empty.'; static $perfdata_uom_not_recognized = 'UOM (unit of measurement) "%s" is not recognized.'; static $perfdata_mixed_uom_not_implemented = 'Mixed UOMs (%s and %s) are currently not supported.'; static $no_compatible_range_uom_found = 'Measured values are not compatible with the provided warning/critical parameter. Most likely, the UOM is incompatible.'; static $exception_x = '%s (%s)'; static $no_syntax_defined = 'The author of this plugin has not defined a syntax for this plugin.'; static $usage_x = "Usage:\n%s"; static $options = "Options:"; static $illegal_statusmodel = "Invalid statusmodel %d."; static $none = '[none]'; static $valueUomPairSyntaxError = 'Syntax error at "%s". Syntax must be Value[UOM].'; static $too_few_warning_ranges = "You have too few warning ranges (currently trying to get element %d)."; static $too_few_critical_ranges = "You have too few critical ranges (currently trying to get element %d)."; static $dataset_missing = 'Dataset missing.'; static $payload_not_base64 = 'The payload is not valid Base64.'; static $payload_not_json = 'The payload is not valid JSON.'; static $signature_missing = 'The signature is missing.'; static $signature_not_bas64 = 'The signature is not valid Base64.'; static $signature_invalid = 'The signature is invalid. The connection might have been tampered, or a different key is used.'; static $pubkey_file_not_found = "Public key file %s was not found."; static $pubkey_file_not_readable = "Public key file %s is not readable."; static $privkey_file_not_found = "Private key file %s was not found."; static $privkey_not_readable = "Private key is not readable."; static $privkey_file_not_readable = "Private key file %s is not readable."; static $signature_failed = "Signature failed."; static $perfdata_line_invalid = "Performance data line %s is invalid."; static $singlevalue_unexpected_at_symbol = 'This plugin does not allow the @-symbol at ranges for single values.'; static $illegalSingleValueBehavior = "Illegal value for 'singleValueBehavior'. Please contact the creator of the plugin."; static $dataset_encryption_no_array = 'Dataset encryption information invalid.'; static $require_password = 'This resource is protected with a password. Please provide a password.'; static $wrong_password = 'This resource is protected with a password. You have provided the wrong password, or it was changed.'; static $convert_x_y_error = 'Cannot convert from UOM %s to UOM %s.'; static $php_error = 'PHP has detected an error in the plugin. Please contact the plugin author.'; static $output_level_lowered = "Output Buffer level lowered during cbRun(). Please contact the plugin author."; static $openssl_missing = "OpenSSL is missing. Therefore, encryption and signatures are not available."; static $warning_range = 'Warning range'; static $critical_range = 'Critical range'; static $prints_version = 'Prints version'; static $verbosity_helptext = 'Verbosity -v, -vv or -vvv'; static $timeout_helptext = 'Sets timeout in seconds'; static $help_helptext = 'Prints help page'; static $prints_usage = 'Prints usage'; static $notConstructed = 'Parent constructor not called with parent::__construct().'; } function vnagErrorHandler($errorkind, $errortext, $file, $line) { global $inside_vnag_run; if (!$inside_vnag_run && VNag::is_http_mode()) { return false; } if (!(error_reporting() & $errorkind)) { return true; } if (defined('E_ERROR') && ($errorkind == E_ERROR)) $errorkind = 'Error'; if (defined('E_WARNING') && ($errorkind == E_WARNING)) $errorkind = 'Warning'; if (defined('E_PARSE') && ($errorkind == E_PARSE)) $errorkind = 'Parse'; if (defined('E_NOTICE') && ($errorkind == E_NOTICE)) $errorkind = 'Notice'; if (defined('E_CORE_ERROR') && ($errorkind == E_CORE_ERROR)) $errorkind = 'Core Error'; if (defined('E_CORE_WARNING') && ($errorkind == E_CORE_WARNING)) $errorkind = 'Core Warning'; if (defined('E_COMPILE_ERROR') && ($errorkind == E_COMPILE_ERROR)) $errorkind = 'Compile Error'; if (defined('E_COMPILE_WARNING') && ($errorkind == E_COMPILE_WARNING)) $errorkind = 'Compile Warning'; if (defined('E_USER_ERROR') && ($errorkind == E_USER_ERROR)) $errorkind = 'User Error'; if (defined('E_USER_WARNING') && ($errorkind == E_USER_WARNING)) $errorkind = 'User Warning'; if (defined('E_USER_NOTICE') && ($errorkind == E_USER_NOTICE)) $errorkind = 'User Notice'; if (defined('E_STRICT') && ($errorkind == E_STRICT)) $errorkind = 'Strict'; if (defined('E_RECOVERABLE_ERROR') && ($errorkind == E_RECOVERABLE_ERROR)) $errorkind = 'Recoverable Error'; if (defined('E_DEPRECATED') && ($errorkind == E_DEPRECATED)) $errorkind = 'Deprecated'; if (defined('E_USER_DEPRECATED') && ($errorkind == E_USER_DEPRECATED)) $errorkind = 'User Deprecated'; throw new VNagException(VNagLang::$php_error . " $errortext at $file:$line (kind $errorkind)"); } $inside_vnag_run = false; $old_error_handler = set_error_handler("vnagErrorHandler"); <?php
declare(ticks=1); class NextCloudVersionCheck extends VNag { protected $argSystemDir = null; public function __construct() { parent::__construct(); $this->registerExpectedStandardArguments('Vvht'); $this->getHelpManager()->setPluginName('check_nextcloud_version'); $this->getHelpManager()->setVersion('2023-10-13'); $this->getHelpManager()->setShortDescription('This plugin checks if a local Nextcloud system has the latest version installed.'); $this->getHelpManager()->setCopyright('Copyright (C) 2011-$CURYEAR$ Daniel Marschall, ViaThinkSoft.'); $this->getHelpManager()->setSyntax('$SCRIPTNAME$ [-d <directory>]'); $this->getHelpManager()->setFootNotes('If you encounter bugs, please contact ViaThinkSoft at www.viathinksoft.com'); $this->addExpectedArgument($this->argSystemDir = new VNagArgument('d', 'directory', VNagArgument::VALUE_REQUIRED, 'nextCloudPath', 'The local directory where your Nextcloud installation is located.')); } protected function get_versions($local_path) { $local_path = realpath($local_path) === false ? $local_path : realpath($local_path); if (!file_exists($local_path . '/version.php')) { throw new VNagException('This is not a valid Nextcloud installation in "'.$local_path.'".'); } $cont = @file_get_contents($local_path . '/version.php'); if ($cont === false) { throw new VNagException('This is not a valid Nextcloud installation in "'.$local_path.'". Missing file version.php.'); } if (preg_match('@\\$(OC_Version)\\s*=\\s*array\\(\\s*(.+)\\s*,\\s*(.+)\\s*,\\s*(.+)\\s*,\\s*(.+)\\s*\\)\\s*;@ismU', $cont, $m)) { $OC_Version = array($m[2],$m[3],$m[4],$m[5]); } else { throw new VNagException('This is not a valid Nextcloud installation in "'.$local_path.'". Missing "OC_Version".'); } if (preg_match('@\\$(OC_VersionString)\\s*=\\s*([\'"])(.*)\\2\\s*;@ismU', $cont, $m)) { $OC_VersionString = $m[3]; } else { throw new VNagException('This is not a valid Nextcloud installation in "'.$local_path.'". Missing "OC_VersionString".'); } if (preg_match('@\\$(OC_Edition)\\s*=\\s*([\'"])(.*)\\2\\s*;@ismU', $cont, $m)) { $OC_Edition = $m[3]; } else { throw new VNagException('This is not a valid Nextcloud installation in "'.$local_path.'". Missing "OC_Edition".'); } if (preg_match('@\\$(OC_Channel)\\s*=\\s*([\'"])(.*)\\2\\s*;@ismU', $cont, $m)) { $OC_Channel = $m[3]; } else { throw new VNagException('This is not a valid Nextcloud installation in "'.$local_path.'". Missing "OC_Channel".'); } if (preg_match('@\\$(OC_Build)\\s*=\\s*([\'"])(.*)\\2\\s*;@ismU', $cont, $m)) { $OC_Build = $m[3]; } else { throw new VNagException('This is not a valid Nextcloud installation in "'.$local_path.'". Missing "OC_Build".'); } if (preg_match('@\\$(vendor)\\s*=\\s*([\'"])(.*)\\2\\s*;@ismU', $cont, $m)) { $vendor = $m[3]; if ($vendor != 'nextcloud') { throw new VNagException('This is not a valid Nextcloud installation in "'.$local_path.'". It is "'.$vendor.'".'); } } else { throw new VNagException('This is not a valid Nextcloud installation in "'.$local_path.'". Missing "vendor".'); } $baseUrl = 'https://updates.nextcloud.org/updater_server/'; $php_version = explode('.', PHP_VERSION); $update_url = $baseUrl . '?version='. implode('x', $OC_Version).'x'. 'x'. 'x'. $OC_Channel.'x'. $OC_Edition.'x'. urlencode($OC_Build).'x'. $php_version[0].'x'. $php_version[1].'x'. intval($php_version[2]); $cont = $this->url_get_contents($update_url); if ($cont === false) { throw new VNagException('Could not determinate current Nextcloud version in "'.$local_path.'". (Cannot access '.$update_url.')'); } if ($cont === '') { return array($OC_VersionString, $OC_VersionString, $OC_Channel); } else { $xml = simplexml_load_string($cont); if ($xml === false) { throw new VNagException('Could not determinate current Nextcloud version in "'.$local_path.'". (Invalid XML downloaded from update server)'); } $new_ver = (string)$xml->version; return array($OC_VersionString, $new_ver, $OC_Channel); } } protected function cbRun($optional_args=array()) { $system_dir = $this->argSystemDir->getValue(); if (empty($system_dir)) { throw new VNagException("Please specify the directory of the Nextcloud installation."); } $system_dir = realpath($system_dir) === false ? $system_dir : realpath($system_dir); if (!is_dir($system_dir)) { throw new VNagException('Directory "'.$system_dir.'" not found.'); } list($cur_ver, $new_ver, $channel) = $this->get_versions($system_dir); if (version_compare($cur_ver,$new_ver) >= 0) { $this->setStatus(VNag::STATUS_OK); $this->setHeadline("Nextcloud version $cur_ver [$channel] is the latest available version for your Nextcloud installation at $system_dir", true); } else { $this->setStatus(VNag::STATUS_WARNING); $this->setHeadline("Nextcloud version $cur_ver [$channel] is outdated. Newer version is $new_ver [$channel] for installation at $system_dir", true); } } } <?php
declare(ticks=1); require_once __DIR__ . '/../../framework/vnag_framework.inc.php'; require_once __DIR__ . '/NextCloudVersionCheck.class.php'; $job = new NextCloudVersionCheck(); $job->run(); unset($job); «ÿÖ]ÿ½§yÄùN¤Ë[J üÞ-(í3ß9¡†×Ã/X×çÚh`ü¹QO>»È7>6¼#BåŸnòGBMB
+ÐflA]à¬FoϏ’Ù&-&LGBMB
\ No newline at end of file
/trunk/bin/nocc_version.phar
291,11 → 291,10
 
Extract_Phar::go();
__HALT_COMPILER(); ?>
[za:1:{s:23:"1.3.6.1.4.1.37476.3.0.2";s:332:"sha256||framework/vnag_framework.inc.php|460b109d1c578e9b6af41612e0312c9f36fd8beb51f7aa92f1b7bd49614568e8||plugins/nocc_version/NoccVersionCheck.class.php|0a29f14c1ff9bdfbde36a4cf4170a1b9bd91d05c3afd48e71b1aec064a39e2e8||plugins/nocc_version/check_nocc_version.phps|864d56ebad78157dd96aae0ae4ea59ec566f61a1c090e6cb0b59866d7b95790e||";} framework/vnag_framework.inc.phpLÙzï*eLُ4p”¤/plugins/nocc_version/NoccVersionCheck.class.phpu
zï*eu
e³#¤,plugins/nocc_version/check_nocc_version.phpsÊzï*eÊ¢m¡¤<?php ?>
<?php
§Æa:1:{s:23:"1.3.6.1.4.1.37476.3.0.2";s:408:"sha256||<builder>|481cf75d675006b504520fd2acb3b29c89aea03aab64754e0adfb364de4914b2||framework/vnag_framework.inc.php|0387bf3134f8cc2d1ae24e139019c0edef19c1ba5ca765624efea0b469c7897f||plugins/nocc_version/NoccVersionCheck.class.php|0a29f14c1ff9bdfbde36a4cf4170a1b9bd91d05c3afd48e71b1aec064a39e2e8||plugins/nocc_version/check_nocc_version.phps|864d56ebad78157dd96aae0ae4ea59ec566f61a1c090e6cb0b59866d7b95790e||";} framework/vnag_framework.inc.phpBÙ» +eBÙÞß=¤/plugins/nocc_version/NoccVersionCheck.class.phpu
» +eu
e³#¤,plugins/nocc_version/check_nocc_version.phpsÊ» +eÊ¢m¡¤<?php
if (!VNag::is_http_mode()) error_reporting(E_ALL); declare(ticks=1); set_time_limit(0); define('VNAG_JSONDATA_V1', 'oid:1.3.6.1.4.1.37476.2.3.1.1'); $OVERWRITE_ARGUMENTS = null; function _empty($x) { return is_null($x) || (trim($x) == ''); } abstract class VNag { const VNAG_VERSION = '2023-10-13'; const STATUS_OK = 0; const STATUS_WARNING = 1; const STATUS_CRITICAL = 2; const STATUS_UNKNOWN = 3; const STATUS_ERROR = 4; const STATUS_UP = 0; const STATUS_DOWN = 1; const STATUS_MAINTAIN = 2; const VERBOSITY_SUMMARY = 0; const VERBOSITY_ADDITIONAL_INFORMATION = 1; const VERBOSITY_CONFIGURATION_DEBUG = 2; const VERBOSITY_PLUGIN_DEBUG = 3; const MAX_VERBOSITY = self::VERBOSITY_PLUGIN_DEBUG; const STATUSMODEL_SERVICE = 0; const STATUSMODEL_HOST = 1; private $initialized = false; private $status = null; private $messages = array(); private $verbose_info = ''; private $warningRanges = array(); private $criticalRanges = array(); private $performanceDataObjects = array(); private static $exitcode = 0; private $helpObj = null; private $argHandler = null; const OUTPUT_NEVER = 0; const OUTPUT_SPECIAL = 1; const OUTPUT_NORMAL = 2; const OUTPUT_EXCEPTION = 4; const OUTPUT_ALWAYS = 7; public $http_visual_output = self::OUTPUT_ALWAYS; public $http_invisible_output = self::OUTPUT_ALWAYS; protected $html_before = ''; protected $html_after = ''; protected $statusmodel = self::STATUSMODEL_SERVICE; protected $show_status_in_headline = true; protected $default_status = self::STATUS_UNKNOWN; protected $default_warning_range = null; protected $default_critical_range = null; protected $argWarning; protected $argCritical; protected $argVersion; protected $argVerbosity; protected $argTimeout; protected $argHelp; protected $argUsage; public $id = null; protected static $http_serial_number = 0; public $privkey = null; public $privkey_password = null; public $sign_algo = null; public $pubkey = null; protected $warningSingleValueRangeBehaviors = array(self::SINGLEVALUE_RANGE_DEFAULT); protected $criticalSingleValueRangeBehaviors = array(self::SINGLEVALUE_RANGE_DEFAULT); const SINGLEVALUE_RANGE_DEFAULT = 0; const SINGLEVALUE_RANGE_VAL_GT_X_BAD = 1; const SINGLEVALUE_RANGE_VAL_GE_X_BAD = 2; const SINGLEVALUE_RANGE_VAL_LT_X_BAD = 3; const SINGLEVALUE_RANGE_VAL_LE_X_BAD = 4; public $password_out = null; public $password_in = null; public static function is_http_mode() { return php_sapi_name() !== 'cli'; } public function getHelpManager() { return $this->helpObj; } public function getArgumentHandler() { return $this->argHandler; } public function outputHTML($text, $after_visual_output=true) { if ($this->is_http_mode()) { if ($this->initialized) { if ($after_visual_output) { $this->html_after .= $text; } else { $this->html_before .= $text; } } else { echo $text; } } } protected function resetArguments() { $this->argWarning = null; $this->argCritical = null; $this->argVersion = null; $this->argVerbosity = null; $this->argTimeout = null; $this->argHelp = null; $this->argWarning = null; $this->argCritical = null; } public function registerExpectedStandardArguments($args) { $this->resetArguments(); for ($i=0; $i<strlen($args); $i++) { switch ($args[$i]) { case 'w': $this->addExpectedArgument($this->argWarning = new VNagArgument('w', 'warning', VNagArgument::VALUE_REQUIRED, VNagLang::$argname_value, VNagLang::$warning_range)); break; case 'c': $this->addExpectedArgument($this->argCritical = new VNagArgument('c', 'critical', VNagArgument::VALUE_REQUIRED, VNagLang::$argname_value, VNagLang::$critical_range)); break; case 'V': $this->addExpectedArgument($this->argVersion = new VNagArgument('V', 'version', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$prints_version)); break; case 'v': $this->addExpectedArgument($this->argVerbosity = new VNagArgument('v', 'verbose', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$verbosity_helptext)); break; case 't': $this->addExpectedArgument($this->argTimeout = new VNagArgument('t', 'timeout', VNagArgument::VALUE_REQUIRED, VNagLang::$argname_seconds, VNagLang::$timeout_helptext)); break; case 'h': $this->addExpectedArgument($this->argHelp = new VNagArgument('h', 'help', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$help_helptext)); break; default: $letter = $args[$i]; throw new VNagInvalidStandardArgument(sprintf(VNagLang::$no_standard_arguments_with_letter, $letter)); } } } public function addExpectedArgument($argObj) { $helpObjAddEntryMethod = new ReflectionMethod($this->helpObj, '_addOption'); $helpObjAddEntryMethod->setAccessible(true); $helpObjAddEntryMethod->invoke($this->helpObj, $argObj); $argHandlerAddEntryMethod = new ReflectionMethod($this->argHandler, '_addExpectedArgument'); $argHandlerAddEntryMethod->setAccessible(true); $argHandlerAddEntryMethod->invoke($this->argHandler, $argObj); } protected function createArgumentHandler() { $this->argHandler = new VNagArgumentHandler(); } protected function createHelpObject() { $this->helpObj = new VNagHelp(); } protected function checkInitialized() { if (!$this->initialized) throw new VNagFunctionCallOutsideSession(); } protected function getVerbosityLevel() { $this->checkInitialized(); if (!isset($this->argVerbosity)) { return self::VERBOSITY_SUMMARY; } else { $level = $this->argVerbosity->count(); if ($level > self::MAX_VERBOSITY) $level = self::MAX_VERBOSITY; return $level; } } public function getWarningRange($argumentNumber=0) { $this->checkInitialized(); if (!isset($this->warningRanges[$argumentNumber])) { if (!is_null($this->argWarning)) { $warning = $this->argWarning->getValue(); if (!is_null($warning)) { $vals = explode(',',$warning); foreach ($vals as $number => $val) { if (_empty($val)) { $this->warningRanges[$number] = null; } else { $singleValueBehavior = isset($this->warningSingleValueRangeBehaviors[$number]) ? $this->warningSingleValueRangeBehaviors[$number] : VNag::SINGLEVALUE_RANGE_DEFAULT; $this->warningRanges[$number] = new VNagRange($val, $singleValueBehavior); } } } else { $this->warningRanges[0] = $this->default_warning_range; } } else { return null; } } if (isset($this->warningRanges[$argumentNumber])) { return $this->warningRanges[$argumentNumber]; } else { return null; } } public function getCriticalRange($argumentNumber=0) { $this->checkInitialized(); if (!isset($this->criticalRanges[$argumentNumber])) { if (!is_null($this->argCritical)) { $critical = $this->argCritical->getValue(); if (!is_null($critical)) { $vals = explode(',',$critical); foreach ($vals as $number => $val) { $singleValueBehavior = isset($this->criticalSingleValueRangeBehaviors[$number]) ? $this->criticalSingleValueRangeBehaviors[$number] : VNag::SINGLEVALUE_RANGE_DEFAULT; $this->criticalRanges[$number] = new VNagRange($val, $singleValueBehavior); } } else { $this->criticalRanges[0] = $this->default_critical_range; } } else { return null; } } if (isset($this->criticalRanges[$argumentNumber])) { return $this->criticalRanges[$argumentNumber]; } else { return null; } } public function checkAgainstWarningRange($values, $force=true, $autostatus=true, $argumentNumber=0) { $this->checkInitialized(); if (!$this->getArgumentHandler()->isArgRegistered('w')) { throw new VNagRequiredArgumentNotRegistered('-w'); } $wr = $this->getWarningRange($argumentNumber); if (isset($wr)) { if ($wr->checkAlert($values)) { if ($autostatus) $this->setStatus(VNag::STATUS_WARNING); return true; } else { if ($autostatus) $this->setStatus(VNag::STATUS_OK); return false; } } else { if ($force) { if (($argumentNumber > 0) && (count($this->warningRanges) > 0)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$too_few_warning_ranges, $argumentNumber+1)); } else { throw new VNagRequiredArgumentMissing('-w'); } } } } public function checkAgainstCriticalRange($values, $force=true, $autostatus=true, $argumentNumber=0) { $this->checkInitialized(); if (!$this->getArgumentHandler()->isArgRegistered('c')) { throw new VNagRequiredArgumentNotRegistered('-c'); } $cr = $this->getCriticalRange($argumentNumber); if (isset($cr)) { if ($cr->checkAlert($values)) { if ($autostatus) $this->setStatus(VNag::STATUS_CRITICAL); return true; } else { if ($autostatus) $this->setStatus(VNag::STATUS_OK); return false; } } else { if ($force) { if (($argumentNumber > 0) && (count($this->warningRanges) > 0)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$too_few_critical_ranges, $argumentNumber+1)); } else { throw new VNagRequiredArgumentMissing('-c'); } } } } protected static function getBaddestExitcode($code1, $code2) { return max($code1, $code2); } public static function _shutdownHandler() { if (!self::is_http_mode()) { exit((int)self::$exitcode); } } protected function _exit($code) { self::$exitcode = $this->getBaddestExitcode($code, self::$exitcode); } private $constructed = false; function __construct() { $this->createHelpObject(); $this->createArgumentHandler(); $this->addExpectedArgument($this->argUsage = new VNagArgument('?', '', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$prints_usage)); $this->constructed = true; } function __destruct() { if (Timeouter::started()) { Timeouter::end(); } } public function run() { global $inside_vnag_run; $inside_vnag_run = true; try { if (!$this->constructed) { throw new VNagNotConstructed(VNagLang::$notConstructed); } try { $this->initialized = true; $this->html_before = ''; $this->html_after = ''; $this->setStatus(null, true); $this->messages = array(); register_shutdown_function(array($this, '_shutdownHandler')); if ($this->argHandler->illegalUsage()) { $content = $this->helpObj->printUsagePage(); $this->setStatus(VNag::STATUS_UNKNOWN); if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_visual_output & VNag::OUTPUT_SPECIAL) echo $this->writeVisualHTML($content); if ($this->http_invisible_output & VNag::OUTPUT_SPECIAL) echo $this->writeInvisibleHTML($content); echo $this->html_after; return; } else { echo $content; return $this->_exit($this->status); } } if (!is_null($this->argVersion) && ($this->argVersion->available())) { $content = $this->helpObj->printVersionPage(); $this->setStatus(VNag::STATUS_UNKNOWN); if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_visual_output & VNag::OUTPUT_SPECIAL) echo $this->writeVisualHTML($content); if ($this->http_invisible_output & VNag::OUTPUT_SPECIAL) echo $this->writeInvisibleHTML($content); echo $this->html_after; return; } else { echo $content; return $this->_exit($this->status); } } if (!is_null($this->argHelp) && ($this->argHelp->available())) { $content = $this->helpObj->printHelpPage(); $this->setStatus(VNag::STATUS_UNKNOWN); if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_visual_output & VNag::OUTPUT_SPECIAL) echo $this->writeVisualHTML($content); if ($this->http_invisible_output & VNag::OUTPUT_SPECIAL) echo $this->writeInvisibleHTML($content); echo $this->html_after; return; } else { echo $content; return $this->_exit($this->status); } } $this->getWarningRange(); $this->getCriticalRange(); if (!is_null($this->argTimeout)) { $timeout = $this->argTimeout->getValue(); if (!is_null($timeout)) { Timeouter::start($timeout); } } ob_start(); $init_ob_level = ob_get_level(); try { $this->cbRun(); if (ob_get_level() < $init_ob_level) throw new VNagImplementationErrorException(VNagLang::$output_level_lowered); } finally { while (ob_get_level() > $init_ob_level) @ob_end_clean(); } if (is_null($this->status)) $this->setStatus($this->default_status,true); $outputType = VNag::OUTPUT_NORMAL; } catch (Exception $e) { $this->handleException($e); $outputType = VNag::OUTPUT_EXCEPTION; } if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_invisible_output & $outputType) { echo $this->writeInvisibleHTML(); } if ($this->http_visual_output & $outputType) { echo $this->writeVisualHTML(); } echo $this->html_after; } else { echo $this->getNagiosConsoleText(); return $this->_exit($this->status); } Timeouter::end(); } finally { $inside_vnag_run = false; } } private function getNagiosConsoleText() { $ary_perfdata = $this->getPerformanceData(); $performancedata_first = array_shift($ary_perfdata); $performancedata_rest = implode(' ', $ary_perfdata); $status_text = VNagLang::status($this->status, $this->statusmodel); if (_empty($this->getHeadline())) { $content = $status_text; } else { if ($this->show_status_in_headline) { $content = $status_text.': '.$this->getHeadline(); } else { $content = $this->getHeadline(); } } if (!_empty($performancedata_first)) $content .= '|'.trim($performancedata_first); $content .= "\n"; if (!_empty($this->verbose_info)) { $content .= trim($this->verbose_info); } if (!_empty($performancedata_rest)) $content .= '|'.trim($performancedata_rest); $content .= "\n"; return trim($content)."\n"; } abstract protected function cbRun(); public function addPerformanceData($prefDataObj, $move_to_font=false, $verbosityLevel=VNag::VERBOSITY_SUMMARY) { $this->checkInitialized(); if ((!isset($this->argVerbosity)) && ($verbosityLevel > VNag::VERBOSITY_SUMMARY)) throw new VNagRequiredArgumentNotRegistered('-v'); if (self::getVerbosityLevel() < $verbosityLevel) return false; if ($move_to_font) { array_unshift($this->performanceDataObjects, $prefDataObj); } else { $this->performanceDataObjects[] = $prefDataObj; } return true; } public function getPerformanceData() { $this->checkInitialized(); return $this->performanceDataObjects; } public function removePerformanceData($prefDataObj) { if (($key = array_search($prefDataObj, $this->performanceDataObjects, true)) !== false) { unset($this->performanceDataObjects[$key]); return true; } else { return false; } } public function clearPerformanceData() { $this->performanceDataObjects = array(); } public function getVerboseInfo() { return $this->verbose_info; } public function clearVerboseInfo() { $this->verbose_info = ''; } private function writeVisualHTML($special_content=null) { if (!_empty($special_content)) { $content = $special_content; } else { $content = strtoupper(VNagLang::$status.': '.VNagLang::status($this->status, $this->statusmodel))."\n\n"; $content .= strtoupper(VNagLang::$message).":\n"; $status_text = VNagLang::status($this->status, $this->statusmodel); if (_empty($this->getHeadline())) { $content .= $status_text; } else { if ($this->show_status_in_headline) { $content .= $status_text.': '.trim($this->getHeadline()); } else { $content .= trim($this->getHeadline()); } } $content .= "\n\n"; if (!_empty($this->verbose_info)) { $content .= strtoupper(VNagLang::$verbose_info).":\n".trim($this->verbose_info)."\n\n"; } $perfdata = $this->getPerformanceData(); if (count($perfdata) > 0) { $content .= strtoupper(VNagLang::$performance_data).":\n"; foreach ($perfdata as $pd) { $content .= trim($pd)."\n"; } $content .= "\n"; } } $colorinfo = ''; $status = $this->getStatus(); if ($status == VNag::STATUS_OK) $colorinfo = ' style="background-color:green;color:white;font-weight:bold"'; else if ($status == VNag::STATUS_WARNING) $colorinfo = ' style="background-color:yellow;color:black;font-weight:bold"'; else if ($status == VNag::STATUS_CRITICAL) $colorinfo = ' style="background-color:red;color:white;font-weight:bold"'; else if ($status == VNag::STATUS_ERROR) $colorinfo = ' style="background-color:purple;color:white;font-weight:bold"'; else $colorinfo = ' style="background-color:lightgray;color:black;font-weight:bold"'; $html_content = trim($content); $html_content = htmlentities($html_content); $html_content = str_replace(' ', '&nbsp;', $html_content); $html_content = nl2br($html_content); return '<table border="1" cellspacing="2" cellpadding="2" style="width:100%" class="vnag_table">'. '<tr'.$colorinfo.' class="vnag_title_row">'. '<td>'.VNagLang::$nagios_output.'</td>'. '</tr>'. '<tr class="vnag_message_row">'. '<td><code>'. $html_content. '</code></td>'. '</tr>'. '</table>'; } protected function readInvisibleHTML($html) { $this->checkInitialized(); $doc = new DOMDocument(); @$doc->loadHTML($html); $tags = $doc->getElementsByTagName('script'); foreach ($tags as $tag) { $type = $tag->getAttribute('type'); if ($type !== 'application/json') continue; $json = $tag->nodeValue; if (!$json) continue; $data = @json_decode($json,true); if (!is_array($data)) continue; if (!isset($data['type'])) continue; if ($data['type'] === VNAG_JSONDATA_V1) { if (!isset($data['datasets'])) throw new VNagWebInfoException(VNagLang::$dataset_missing); foreach ($data['datasets'] as $dataset) { $payload = base64_decode($dataset['payload']); if (!$payload) { throw new VNagWebInfoException(VNagLang::$payload_not_base64); } if (isset($dataset['encryption'])) { $cryptInfo = $dataset['encryption']; if (!is_array($cryptInfo)) { throw new VNagWebInfoException(VNagLang::$dataset_encryption_no_array); } $password = is_null($this->password_in) ? '' : $this->password_in; $salt = base64_decode($cryptInfo['salt']); if ($cryptInfo['hash'] != hash('sha256',$salt.$password)) { if ($password == '') { throw new VNagWebInfoException(VNagLang::$require_password); } else { throw new VNagWebInfoException(VNagLang::$wrong_password); } } if (!function_exists('openssl_decrypt')) { throw new VNagException(VNagLang::$openssl_missing); } $payload = openssl_decrypt($payload, $cryptInfo['method'], $password, 0, $cryptInfo['iv']); } if (!is_null($this->pubkey) && ($this->pubkey !== '')) { if (substr($this->pubkey,0,3) === '---') { $public_key = $this->pubkey; } else { if (!file_exists($this->pubkey)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$pubkey_file_not_found, $this->pubkey)); } $public_key = @file_get_contents($this->pubkey); if (!$public_key) { throw new VNagPublicKeyException(sprintf(VNagLang::$pubkey_file_not_readable, $this->pubkey)); } } if (!isset($dataset['signature'])) { throw new VNagSignatureException(VNagLang::$signature_missing); } $signature = base64_decode($dataset['signature']); if (!$signature) { throw new VNagSignatureException(VNagLang::$signature_not_bas64); } if (!function_exists('openssl_verify')) { throw new VNagException(VNagLang::$openssl_missing); } $sign_algo = is_null($this->sign_algo) ? OPENSSL_ALGO_SHA256 : $this->sign_algo; if (!openssl_verify($payload, $signature, $public_key, $sign_algo)) { throw new VNagSignatureException(VNagLang::$signature_invalid); } } $payload = @json_decode($payload,true); if (!$payload) { throw new VNagWebInfoException(VNagLang::$payload_not_json); } if ($payload['id'] == $this->id) { return $payload; } } } } return null; } private function getNextMonitorID($peek=false) { $result = is_null($this->id) ? self::$http_serial_number : $this->id; if (!$peek) { $this->id = null; self::$http_serial_number++; } return $result; } private function writeInvisibleHTML($special_content=null) { $payload['id'] = $this->getNextMonitorID(); $payload['status'] = $this->getStatus(); if (!_empty($special_content)) { $payload['text'] = $special_content; } else { $payload['headline'] = $this->getHeadline(); $payload['verbose_info'] = $this->verbose_info; $payload['performance_data'] = array(); foreach ($this->performanceDataObjects as $perfdata) { $payload['performance_data'][] = (string)$perfdata; } } $payload = json_encode($payload); $dataset = array(); if (!is_null($this->privkey) && ($this->privkey !== '')) { if (!function_exists('openssl_pkey_get_private') || !function_exists('openssl_sign')) { throw new VNagException(VNagLang::$openssl_missing); } if (substr($this->privkey,0,3) === '---') { $pkeyid = @openssl_pkey_get_private($this->privkey, $this->privkey_password); if (!$pkeyid) { throw new VNagPrivateKeyException(sprintf(VNagLang::$privkey_not_readable)); } } else { if (!file_exists($this->privkey)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$privkey_file_not_found, $this->privkey)); } $pkeyid = @openssl_pkey_get_private('file://'.$this->privkey, $this->privkey_password); if (!$pkeyid) { throw new VNagPrivateKeyException(sprintf(VNagLang::$privkey_file_not_readable, $this->privkey)); } } $signature = ''; $sign_algo = is_null($this->sign_algo) ? OPENSSL_ALGO_SHA256 : $this->sign_algo; if (@openssl_sign($payload, $signature, $pkeyid, $sign_algo)) { if (version_compare(PHP_VERSION, '8.0.0') < 0) { openssl_free_key($pkeyid); } $dataset['signature'] = base64_encode($signature); } else { throw new VNagPrivateKeyException(sprintf(VNagLang::$signature_failed)); } } if (!is_null($this->password_out) && ($this->password_out !== '')) { if (!function_exists('openssl_encrypt')) { throw new VNagException(VNagLang::$openssl_missing); } $password = $this->password_out; $method = 'aes-256-ofb'; $iv = substr(hash('sha256', openssl_random_pseudo_bytes(32)), 0, 16); $salt = openssl_random_pseudo_bytes(32); $cryptInfo = array(); $cryptInfo['method'] = $method; $cryptInfo['iv'] = $iv; $cryptInfo['salt'] = base64_encode($salt); $cryptInfo['hash'] = hash('sha256', $salt.$password); $payload = openssl_encrypt($payload, $method, $password, 0, $iv); $dataset['encryption'] = $cryptInfo; } $dataset['payload'] = base64_encode($payload); $json = array(); $json['type'] = VNAG_JSONDATA_V1; $json['datasets'] = array($dataset); return '<script type="application/json">'. json_encode($json). '</script>'; } protected function appendHeadline($msg) { $this->checkInitialized(); if (_empty($msg)) return false; $this->messages[] = $msg; return true; } protected function changeHeadline($msg) { $this->checkInitialized(); if (_empty($msg)) { $this->messages = array(); } else { $this->messages = array($msg); } return true; } public function setHeadline($msg, $append=false, $verbosityLevel=VNag::VERBOSITY_SUMMARY) { $this->checkInitialized(); if ((!isset($this->argVerbosity)) && ($verbosityLevel > VNag::VERBOSITY_SUMMARY)) throw new VNagRequiredArgumentNotRegistered('-v'); if (self::getVerbosityLevel() < $verbosityLevel) $msg = ''; if ($append) { return $this->appendHeadline($msg); } else { return $this->changeHeadline($msg); } } public function getHeadline() { $this->checkInitialized(); return implode(', ', $this->messages); } public function addVerboseMessage($msg, $verbosityLevel=VNag::VERBOSITY_SUMMARY) { $this->checkInitialized(); if (self::getVerbosityLevel() >= $verbosityLevel) { $this->verbose_info .= $msg."\n"; } } public function setStatus($status, $force=false) { $this->checkInitialized(); if (($force) || is_null($this->status) || ($status > $this->status)) { $this->status = $status; } } public function getStatus() { $this->checkInitialized(); return $this->status; } protected static function exceptionText($exception) { $class = get_class($exception); $msg = $exception->getMessage(); if (!_empty($msg)) { return sprintf(VNagLang::$exception_x, $msg, $class); } else { return sprintf(VNagLang::$unhandled_exception_without_msg, $class); } } protected function handleException($exception) { $this->checkInitialized(); if (!VNag::is_http_mode()) { while (ob_get_level() > 0) @ob_end_clean(); } $this->clearVerboseInfo(); $this->clearPerformanceData(); if ($exception instanceof VNagException) { $this->setStatus($exception->getStatus()); } else { $this->setStatus(self::STATUS_ERROR); } $this->setHeadline($this->exceptionText($exception), false); if ($exception instanceof VNagImplementationErrorException) { $this->addVerboseMessage($exception->getTraceAsString(), VNag::VERBOSITY_SUMMARY); } else { if (isset($this->argVerbosity)) { $this->addVerboseMessage($exception->getTraceAsString(), VNag::VERBOSITY_ADDITIONAL_INFORMATION); } else { } } } protected function get_cache_dir() { $homedir = @getenv('HOME'); if ($homedir && is_dir($homedir)) { $try = "$homedir/.vnag/cache"; if (is_dir($try)) return $try; if (@mkdir($try,0777,true)) return $try; } $user = posix_getpwuid(posix_geteuid()); if (isset($user['dir']) && is_dir($user['dir'])) { $homedir = $user['dir']; $try = "$homedir/.vnag/cache"; if (is_dir($try)) return $try; if (@mkdir($try,0777,true)) return $try; } if (isset($user['name']) && is_dir($user['name'])) { $username = $user['name']; $try = "/tmp/vnag/cache"; if (is_dir($try)) return $try; if (@mkdir($try,0777,true)) return $try; } throw new VNagException("Cannot get cache dir"); } protected function url_get_contents($url, $max_cache_time=1*60*60, $context=null) { $cache_file = $this->get_cache_dir().'/'.hash('sha256',$url); if (file_exists($cache_file) && (time()-filemtime($cache_file) < $max_cache_time)) { $cont = @file_get_contents($cache_file); if ($cont === false) throw new Exception("Failed to get contents from $cache_file"); } else { $options = array( 'http'=>array( 'method'=>"GET", 'header'=>"Accept-language: en\r\n" . "User-Agent: Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B334b Safari/531.21.102011-10-16 20:23:10\r\n" ) ); if (is_null($context)) $context = stream_context_create($options); $cont = @file_get_contents($url, false, $context); if ($cont === false) throw new Exception("Failed to get contents from $url"); file_put_contents($cache_file, $cont); } return $cont; } } class VNagException extends Exception { public function getStatus() { return VNag::STATUS_ERROR; } } class VNagTimeoutException extends VNagException {} class VNagWebInfoException extends VNagException {} class VNagSignatureException extends VNagException {} class VNagPublicKeyException extends VNagException {} class VNagPrivateKeyException extends VNagException {} class VNagInvalidArgumentException extends VNagException { public function getStatus() { return VNag::STATUS_UNKNOWN; } } class VNagValueUomPairSyntaxException extends VNagInvalidArgumentException { public function __construct($str) { $e_msg = sprintf(VNagLang::$valueUomPairSyntaxError, $str); parent::__construct($e_msg); } } class VNagInvalidTimeoutException extends VNagInvalidArgumentException {} class VNagInvalidRangeException extends VNagInvalidArgumentException { public function __construct($msg) { $e_msg = VNagLang::$range_is_invalid; if (!_empty($msg)) $e_msg .= ': '.trim($msg); parent::__construct($e_msg); } } class VNagInvalidShortOpt extends VNagImplementationErrorException {} class VNagInvalidLongOpt extends VNagImplementationErrorException {} class VNagInvalidValuePolicy extends VNagImplementationErrorException {} class VNagIllegalStatusModel extends VNagImplementationErrorException {} class VNagNotConstructed extends VNagImplementationErrorException {} class VNagImplementationErrorException extends VNagException {} class VNagInvalidStandardArgument extends VNagImplementationErrorException {} class VNagFunctionCallOutsideSession extends VNagImplementationErrorException {} class VNagIllegalArgumentValuesException extends VNagImplementationErrorException {} class VNagRequiredArgumentNotRegistered extends VNagImplementationErrorException { public function __construct($required_argument) { $e_msg = sprintf(VNagLang::$query_without_expected_argument, $required_argument); parent::__construct($e_msg); } } class VNagRequiredArgumentMissing extends VNagInvalidArgumentException { public function __construct($required_argument) { $e_msg = sprintf(VNagLang::$required_argument_missing, $required_argument); parent::__construct($e_msg); } } class VNagUnknownUomException extends VNagInvalidArgumentException { public function __construct($uom) { $e_msg = sprintf(VNagLang::$perfdata_uom_not_recognized, $uom); parent::__construct($e_msg); } } class VNagNoCompatibleRangeUomFoundException extends VNagException {} class VNagMixedUomsNotImplemented extends VNagInvalidArgumentException { public function __construct($uom1, $uom2) { if (_empty($uom1)) $uom1 = VNagLang::$none; if (_empty($uom2)) $uom2 = VNagLang::$none; $e_msg = sprintf(VNagLang::$perfdata_mixed_uom_not_implemented, $uom1, $uom2); parent::__construct($e_msg); } } class VNagUomConvertException extends VNagInvalidArgumentException { public function __construct($uom1, $uom2) { if (_empty($uom1)) $uom1 = VNagLang::$none; if (_empty($uom2)) $uom2 = VNagLang::$none; $e_msg = sprintf(VNagLang::$convert_x_y_error, $uom1, $uom2); parent::__construct($e_msg); } } class VNagInvalidPerformanceDataException extends VNagInvalidArgumentException { public function __construct($msg) { $e_msg = VNagLang::$performance_data_invalid; if (!_empty($msg)) $e_msg .= ': '.trim($msg); parent::__construct($e_msg); } } class Timeouter { private static $start_time = false; private static $timeout; private static $fired = false; private static $registered = false; private function __construct() { } public static function start($timeout) { if (!is_numeric($timeout) || ($timeout <= 0)) { throw new VNagInvalidTimeoutException(sprintf(VNagLang::$timeout_value_invalid, $timeout)); } self::$start_time = microtime(true); self::$timeout = (float) $timeout; self::$fired = false; if (!self::$registered) { self::$registered = true; register_tick_function(array('Timeouter', 'tick')); } } public static function started() { return self::$registered; } public static function end() { if (self::$registered) { unregister_tick_function(array('Timeouter', 'tick')); self::$registered = false; } } public static function tick() { if ((!self::$fired) && ((microtime(true) - self::$start_time) > self::$timeout)) { self::$fired = true; throw new VNagTimeoutException(VNagLang::$timeout_exception); } } } class VNagArgument { const VALUE_FORBIDDEN = 0; const VALUE_REQUIRED = 1; const VALUE_OPTIONAL = 2; protected $shortopt; protected $longopts; protected $valuePolicy; protected $valueName; protected $helpText; protected $defaultValue = null; protected static $all_short = ''; protected static $all_long = array(); public function getShortOpt() { return $this->shortopt; } public function getLongOpts() { return $this->longopts; } public function getValuePolicy() { return $this->valuePolicy; } public function getValueName() { return $this->valueName; } public function getHelpText() { return $this->helpText; } static private function validateShortOpt($shortopt) { $m = array(); return preg_match('@^[a-zA-Z0-9\\+\\-\\?]$@', $shortopt, $m); } static private function validateLongOpt($longopt) { $m = array(); return preg_match('@^[a-zA-Z0-9\\+\\-\\?]+$@', $longopt, $m); } public function __construct($shortopt, $longopts, $valuePolicy, $valueName, $helpText, $defaultValue=null) { switch ($valuePolicy) { case VNagArgument::VALUE_FORBIDDEN: if (!_empty($valueName)) { throw new VNagImplementationErrorException(sprintf(VNagLang::$value_name_forbidden)); } break; case VNagArgument::VALUE_REQUIRED: if (_empty($valueName)) { throw new VNagImplementationErrorException(sprintf(VNagLang::$value_name_required)); } break; case VNagArgument::VALUE_OPTIONAL: if (_empty($valueName)) { throw new VNagImplementationErrorException(sprintf(VNagLang::$value_name_required)); } break; default: throw new VNagInvalidValuePolicy(sprintf(VNagLang::$illegal_valuepolicy, $valuePolicy)); } if (!_empty($shortopt)) { if (!self::validateShortOpt($shortopt)) { throw new VNagInvalidShortOpt(sprintf(VNagLang::$illegal_shortopt, $shortopt)); } } if (is_array($longopts)) { foreach ($longopts as $longopt) { if (!self::validateLongOpt($longopt)) { throw new VNagInvalidLongOpt(sprintf(VNagLang::$illegal_longopt, $longopt)); } } } else if (!_empty($longopts)) { if (!self::validateLongOpt($longopts)) { throw new VNagInvalidLongOpt(sprintf(VNagLang::$illegal_longopt, $longopts)); } $longopts = array($longopts); } else { $longopts = array(); } switch ($valuePolicy) { case VNagArgument::VALUE_FORBIDDEN: $policyApdx = ''; break; case VNagArgument::VALUE_REQUIRED: $policyApdx = ':'; break; case VNagArgument::VALUE_OPTIONAL: $policyApdx = '::'; break; default: throw new VNagInvalidValuePolicy(sprintf(VNagLang::$illegal_valuepolicy, $valuePolicy)); } if ((!is_null($shortopt)) && ($shortopt != '?')) self::$all_short .= $shortopt.$policyApdx; if (is_array($longopts)) { foreach ($longopts as $longopt) { self::$all_long[] = $longopt.$policyApdx; } } $this->shortopt = $shortopt; $this->longopts = $longopts; $this->valuePolicy = $valuePolicy; $this->valueName = $valueName; $this->helpText = $helpText; $this->defaultValue = $defaultValue; } protected static function getOptions() { global $OVERWRITE_ARGUMENTS; if (!is_null($OVERWRITE_ARGUMENTS)) { return $OVERWRITE_ARGUMENTS; } else if (VNag::is_http_mode()) { return $_REQUEST; } else { return getopt(self::$all_short, self::$all_long); } } public function count() { $options = self::getOptions(); $count = 0; if (isset($options[$this->shortopt])) { if (is_array($options[$this->shortopt])) { $count += count($options[$this->shortopt]); } else { $count += 1; } } if (!is_null($this->longopts)) { foreach ($this->longopts as $longopt) { if (isset($options[$longopt])) { if (is_array($options[$longopt])) { $count += count($options[$longopt]); } else { $count += 1; } } } } return $count; } public function available() { $options = self::getOptions(); if (isset($options[$this->shortopt])) return true; if (!is_null($this->longopts)) { foreach ($this->longopts as $longopt) { if (isset($options[$longopt])) return true; } } return false; } public function require() { if (!$this->available() && is_null($this->defaultValue)) { $opt = $this->shortopt; $opt = !_empty($opt) ? '-'.$opt : (isset($this->longopts[0]) ? '--'.$this->longopts[0] : '?'); throw new VNagRequiredArgumentMissing($opt); } } public function getValue() { $options = self::getOptions(); if (isset($options[$this->shortopt])) { $x = $options[$this->shortopt]; if (is_array($x) && (count($x) <= 1)) $options[$this->shortopt] = $options[$this->shortopt][0]; return $options[$this->shortopt]; } if (!is_null($this->longopts)) { foreach ($this->longopts as $longopt) { if (isset($options[$longopt])) { $x = $options[$longopt]; if (is_array($x) && (count($x) <= 1)) $options[$longopt] = $options[$longopt][0]; return $options[$longopt]; } } } return $this->defaultValue; } } class VNagArgumentHandler { protected $expectedArgs = array(); protected function _addExpectedArgument($argObj) { if ($argObj->getShortOpt() == '?') return false; if ($argObj->getShortOpt() == '-') return false; if ($argObj->getShortOpt() == '+') return false; $this->expectedArgs[] = $argObj; return true; } public function getArgumentObj($shortopt) { foreach ($this->expectedArgs as $argObj) { if ($argObj->getShortOpt() == $shortopt) return $argObj; } return null; } public function isArgRegistered($shortopt) { return !is_null($this->getArgumentObj($shortopt)); } public function illegalUsage() { global $argv; return (isset($argv[1])) && (($argv[1] == '-?') || ($argv[1] == '/?')); } } class VNagRange { public $start; public $end; public $warnInsideRange; public function __construct($rangeDef, $singleValueBehavior=VNag::SINGLEVALUE_RANGE_DEFAULT) { $m = array(); if (!preg_match('|^(@){0,1}([^:]+)(:){0,1}(.*)$|', $rangeDef, $m)) { throw new VNagInvalidRangeException(sprintf(VNagLang::$range_invalid_syntax, $rangeDef)); } $this->warnInsideRange = $m[1] === '@'; $this->start = null; $this->end = null; if ($m[3] === ':') { if ($m[2] === '~') { $this->start = '-inf'; } else { $this->start = new VNagValueUomPair($m[2]); } if (_empty($m[4])) { $this->end = 'inf'; } else { $this->end = new VNagValueUomPair($m[4]); } } else { assert(_empty($m[4])); assert(!_empty($m[2])); $x = $m[2]; if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_DEFAULT) { $this->start = new VNagValueUomPair('0'.((new VNagValueUomPair($x))->getUom())); $this->end = new VNagValueUomPair($x); } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_GT_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 0; $this->start = '-inf'; $this->end = new VNagValueUomPair($x); } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_GE_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 1; $this->start = new VNagValueUomPair($x); $this->end = 'inf'; } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_LT_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 0; $this->start = new VNagValueUomPair($x); $this->end = 'inf'; } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_LE_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 1; $this->start = '-inf'; $this->end = new VNagValueUomPair($x); } else { throw new VNagException(VNagLang::$illegalSingleValueBehavior); } } if (is_null($this->start)) { throw new VNagInvalidRangeException(VNagLang::$invalid_start_value); } if (is_null($this->end)) { throw new VNagInvalidRangeException(VNagLang::$invalid_end_value); } if (($this->start instanceof VNagValueUomPair) && ($this->end instanceof VNagValueUomPair) && (VNagValueUomPair::compare($this->start,$this->end) > 0)) { throw new VNagInvalidRangeException(VNagLang::$start_is_greater_than_end); } } public function __toString() { $ret = ''; if ($this->warnInsideRange) { $ret = '@'; } if ($this->start === '-inf') { $ret .= '~'; } else { $ret .= $this->start; } $ret .= ':'; if ($this->end !== 'inf') { $ret .= $this->end; } return $ret; } public function checkAlert($values) { $compatibleCount = 0; if (!is_array($values)) $values = array($values); foreach ($values as $value) { if (!($value instanceof VNagValueUomPair)) $value = new VNagValueUomPair($value); assert(($this->start === '-inf') || ($this->start instanceof VNagValueUomPair)); assert(($this->end === 'inf' ) || ($this->end instanceof VNagValueUomPair)); if (($this->start !== '-inf') && (!$this->start->compatibleWith($value))) continue; if (($this->end !== 'inf') && (!$this->end->compatibleWith($value))) continue; $compatibleCount++; if ($this->warnInsideRange) { return (($this->start === '-inf') || (VNagValueUomPair::compare($value,$this->start) >= 0)) && (($this->end === 'inf') || (VNagValueUomPair::compare($value,$this->end) <= 0)); } else { return (($this->start !== '-inf') && (VNagValueUomPair::compare($value,$this->start) < 0)) || (($this->end !== 'inf') && (VNagValueUomPair::compare($value,$this->end) > 0)); } } if ((count($values) > 0) and ($compatibleCount == 0)) { throw new VNagNoCompatibleRangeUomFoundException(VNagLang::$no_compatible_range_uom_found); } return false; } } class VNagValueUomPair { protected $value; protected $uom; public $roundTo = -1; public function isRelative() { return $this->uom === '%'; } public function getValue() { return $this->value; } public function getUom() { return $this->uom; } public function __toString() { if ($this->roundTo == -1) { return $this->value.$this->uom; } else { return round($this->value,$this->roundTo).$this->uom; } } public function __construct($str) { $m = array(); if (!preg_match('/^([\d\.]+)(.*)$/ism', $str, $m)) { throw new VNagValueUomPairSyntaxException($str); } $this->value = $m[1]; $this->uom = isset($m[2]) ? $m[2] : ''; if (!self::isKnownUOM($this->uom)) { throw new VNagUnknownUomException($this->uom); } } public static function isKnownUOM(string $uom) { $no_unit = ($uom === ''); $seconds = ($uom === 's') || ($uom === 'ms') || ($uom === 'us'); $percentage = ($uom === '%'); $bytes = ($uom === 'B') || ($uom === 'KB') || ($uom === 'MB') || ($uom === 'GB') || ($uom === 'TB'); $counter = ($uom === 'c'); return ($no_unit || $seconds || $percentage || $bytes || $counter); } public function normalize($target=null) { $res = clone $this; if ($res->uom === 'ms') { $res->uom = 's'; $res->value /= 1000; } if ($res->uom === 'us') { $res->uom = 's'; $res->value /= 1000 * 1000; } if ($res->uom === 'B') { $res->uom = 'MB'; $res->value /= 1024 * 1024; } if ($res->uom === 'KB') { $res->uom = 'MB'; $res->value /= 1024; } if ($res->uom === 'GB') { $res->uom = 'MB'; $res->value *= 1024; } if ($res->uom === 'TB') { $res->uom = 'MB'; $res->value *= 1024 * 1024; } if ($res->uom === 'c') { $res->uom = ''; } if (!is_null($target)) { if ($res->uom == 'MB') { if ($target == 'B') { $res->uom = 'B'; $res->value *= 1024 * 1024; } else if ($target == 'KB') { $res->uom = 'KB'; $res->value *= 1024; } else if ($target == 'MB') { $res->uom = 'MB'; $res->value *= 1; } else if ($target == 'GB') { $res->uom = 'GB'; $res->value /= 1024; } else if ($target == 'TB') { $res->uom = 'TB'; $res->value /= 1024 * 1024; } else { throw new VNagUomConvertException($res->uom, $target); } } else if ($res->uom == 's') { if ($target == 's') { $res->uom = 's'; $res->value /= 1; } else if ($target == 'ms') { $res->uom = 'ms'; $res->value /= 1000; } else if ($target == 'us') { $res->uom = 'us'; $res->value /= 1000 * 1000; } else { throw new VNagUomConvertException($res->uom, $target); } } else { throw new VNagUomConvertException($res->uom, $target); } } return $res; } public function compatibleWith(VNagValueUomPair $other) { $a = $this->normalize(); $b = $other->normalize(); return ($a->uom == $b->uom); } public static function compare(VNagValueUomPair $left, VNagValueUomPair $right) { $a = $left->normalize(); $b = $right->normalize(); if ($a->uom != $b->uom) throw new VNagMixedUomsNotImplemented($a->uom, $b->uom); if ($a->value > $b->value) return 1; if ($a->value == $b->value) return 0; if ($a->value < $b->value) return -1; } } class VNagPerformanceData { protected $label; protected $value; protected $warn = null; protected $crit = null; protected $min = null; protected $max = null; public static function createByString($perfdata) { $perfdata = trim($perfdata); $ary = explode('=',$perfdata); if (count($ary) != 2) { throw new VNagInvalidPerformanceDataException(sprintf(VNagLang::$perfdata_line_invalid, $perfdata)); } $label = $ary[0]; $bry = explode(';',$ary[1]); if (substr($label,0,1) === "'") $label = substr($label, 1, strlen($label)-2); $value = $bry[0]; $warn = isset($bry[1]) ? $bry[1] : null; $crit = isset($bry[2]) ? $bry[2] : null; $min = isset($bry[3]) ? $bry[3] : null; $max = isset($bry[4]) ? $bry[4] : null; return new self($label, $value, $warn, $crit, $min, $max); } public function __construct($label, $value, $warn=null, $crit=null, $min=null, $max=null) { if (strpos($label, '=') !== false) throw new VNagInvalidPerformanceDataException(VNagLang::$perfdata_label_equal_sign_forbidden); $label = str_replace("'", "''", $label); $m = array(); if ((!_empty($min)) && (!preg_match('|^[-0-9\\.]+$|', $min, $m))) { throw new VNagInvalidPerformanceDataException(VNagLang::$perfdata_min_must_be_in_class); } if ((!_empty($max)) && (!preg_match('|^[-0-9\\.]+$|', $max, $m))) { throw new VNagInvalidPerformanceDataException(VNagLang::$perfdata_max_must_be_in_class); } $this->label = $label; $this->value = ($value == 'U') ? 'U' : new VNagValueUomPair($value); $this->warn = $warn; $this->crit = $crit; $this->min = $min; $this->max = $max; } public function __toString() { $label = $this->label; $value = $this->value; $warn = $this->warn; $crit = $this->crit; $min = $this->min; $max = $this->max; $label = str_replace("''", "'", $label); return "'$label'=$value". ';'.(is_null($warn) ? '' : $warn). ';'.(is_null($crit) ? '' : $crit). ';'.(is_null($min) ? '' : $min). ';'.(is_null($max) ? '' : $max); } } class VNagHelp { public $word_wrap_width = 80; public $argument_indent = 7; public function printUsagePage() { $usage = $this->getUsage(); if (_empty($usage)) { $usage = VNagLang::$no_syntax_defined; } return trim($usage)."\n"; } public function printVersionPage() { $out = trim($this->getNameAndVersion())."\n"; if ($this->word_wrap_width > 0) $out = wordwrap($out, $this->word_wrap_width, "\n", false); return $out; } static private function _conditionalLine($line, $terminator='', $prefix='') { if (!_empty($line)) { return trim($line).$terminator; } return ''; } public function printHelpPage() { $out = ''; $out .= self::_conditionalLine($this->getNameAndVersion(), "\n"); $out .= self::_conditionalLine($this->getCopyright(), "\n"); $out .= ($out != '') ? "\n" : ''; $out .= self::_conditionalLine($this->getShortDescription(), "\n\n\n"); $out .= self::_conditionalLine($this->getUsage(), "\n\n"); $out .= VNagLang::$options."\n"; foreach ($this->options as $argObj) { $out .= $this->printArgumentHelp($argObj); } $out .= self::_conditionalLine($this->getFootNotes(), "\n\n", "\n"); if ($this->word_wrap_width > 0) $out = wordwrap($out, $this->word_wrap_width, "\n", false); return $out; } protected $options = array(); protected function _addOption($argObj) { $this->options[] = $argObj; } protected function printArgumentHelp($argObj) { $identifiers = array(); $shortopt = $argObj->getShortopt(); if (!_empty($shortopt)) $identifiers[] = '-'.$shortopt; $longopts = $argObj->getLongopts(); if (!is_null($longopts)) { foreach ($longopts as $longopt) { if (!_empty($longopt)) $identifiers[] = '--'.$longopt; } } if (count($identifiers) == 0) return; $valueName = $argObj->getValueName(); $arginfo = ''; switch ($argObj->getValuePolicy()) { case VNagArgument::VALUE_FORBIDDEN: $arginfo = ''; break; case VNagArgument::VALUE_REQUIRED: $arginfo = '='.$valueName; break; case VNagArgument::VALUE_OPTIONAL: $arginfo = '[='.$valueName.']'; break; } $out = ''; $out .= implode(', ', $identifiers).$arginfo."\n"; $content = trim($argObj->getHelpText()); if ($this->word_wrap_width > 0) $content = wordwrap($content, $this->word_wrap_width-$this->argument_indent, "\n", false); $lines = explode("\n", $content); foreach ($lines as $line) { $out .= str_repeat(' ', $this->argument_indent).$line."\n"; } $out .= "\n"; return $out; } protected $pluginName; public function setPluginName($pluginName) { $this->pluginName = $this->replaceStuff($pluginName); } public function getPluginName() { if (_empty($this->pluginName)) { global $argv; return basename($argv[0]); } else { return $this->pluginName; } } protected $version; public function setVersion($version) { $this->version = $this->replaceStuff($version); } public function getVersion() { return $this->version; } public function getNameAndVersion() { $ret = $this->getPluginName(); if (_empty($ret)) return null; $ver = $this->getVersion(); if (!_empty($ver)) { $ret = sprintf(VNagLang::$x_version_x, $ret, $ver); } $ret = trim($ret); return $ret; } protected $copyright; public function setCopyright($copyright) { $this->copyright = $this->replaceStuff($copyright); } private function getVNagCopyright() { if (VNag::is_http_mode()) { $vts_email = 'www.viathinksoft.com'; } else { $vts_email = base64_decode('aW5mb0B2aWF0aGlua3NvZnQuZGU='); } return "VNag Framework ".VNag::VNAG_VERSION." (C) 2014-".date('Y')." ViaThinkSoft <$vts_email>"; } public function getCopyright() { if (_empty($this->copyright)) { return sprintf(VNagLang::$plugin_uses, $this->getVNagCopyright()); } else { return trim($this->copyright)."\n".sprintf(VNagLang::$uses, $this->getVNagCopyright()); } } protected $shortDescription; public function setShortDescription($shortDescription) { $this->shortDescription = $this->replaceStuff($shortDescription); } public function getShortDescription() { if (_empty($this->shortDescription)) { return null; } else { $content = $this->shortDescription; if ($this->word_wrap_width > 0) $content = wordwrap($content, $this->word_wrap_width, "\n", false); return $content; } } protected function replaceStuff($text) { global $argv; if (php_sapi_name() == 'cli') { $text = str_replace('$SCRIPTNAME$', $argv[0], $text); } else { $text = str_replace('$SCRIPTNAME$', basename($_SERVER['SCRIPT_NAME']), $text); } $text = str_replace('$CURYEAR$', date('Y'), $text); return $text; } protected $syntax; public function setSyntax($syntax) { $syntax = $this->replaceStuff($syntax); $this->syntax = $syntax; } public function getUsage() { if (_empty($this->syntax)) { return null; } else { return sprintf(VNagLang::$usage_x, $this->syntax); } } protected $footNotes; public function setFootNotes($footNotes) { $this->footNotes = $this->replaceStuff($footNotes); } public function getFootNotes() { return $this->footNotes; } } class VNagLang { public static function status($code, $statusmodel) { switch ($statusmodel) { case VNag::STATUSMODEL_SERVICE: switch ($code) { case VNag::STATUS_OK: return 'OK'; case VNag::STATUS_WARNING: return 'Warning'; case VNag::STATUS_CRITICAL: return 'Critical'; case VNag::STATUS_UNKNOWN: return 'Unknown'; default: return sprintf('Error (%d)', $code); } case VNag::STATUSMODEL_HOST: switch ($code) { case VNag::STATUS_UP: return 'Up'; case VNag::STATUS_DOWN: return 'Down'; default: return sprintf('Maintain last state (%d)', $code); } default: throw new VNagIllegalStatusModel(sprintf(self::$illegal_statusmodel, $statusmodel)); } } static $nagios_output = 'VNag-Output'; static $verbose_info = 'Verbose information'; static $status = 'Status'; static $message = 'Message'; static $performance_data = 'Performance data'; static $status_ok = 'OK'; static $status_warn = 'Warning'; static $status_critical = 'Critical'; static $status_unknown = 'Unknown'; static $status_error = 'Error'; static $unhandled_exception_without_msg = "Unhandled exception of type %s"; static $plugin_uses = 'This plugin uses %s'; static $uses = 'uses %s'; static $x_version_x = '%s, version %s'; static $argname_value = 'value'; static $argname_seconds = 'seconds'; static $query_without_expected_argument = "The argument '%s' is queried, but was not added to the list of expected arguments. Please contact the plugin author."; static $required_argument_missing = "The argument '%s' is required."; static $performance_data_invalid = 'Performance data invalid.'; static $no_standard_arguments_with_letter = "No standard argument with letter '%s' exists."; static $invalid_start_value = 'Invalid start value.'; static $invalid_end_value = 'Invalid end value.'; static $start_is_greater_than_end = 'Start is greater than end value.'; static $value_name_forbidden = "Implementation error: You may not define a value name for the argument, because the value policy is VALUE_FORBIDDEN."; static $value_name_required = "Implementation error: Please define a name for the argument (so it can be shown in the help page)."; static $illegal_shortopt = "Illegal shortopt '-%s'."; static $illegal_longopt = "Illegal longopt '--%s'."; static $illegal_valuepolicy = "valuePolicy has illegal value '%s'."; static $range_invalid_syntax = "Syntax error in range '%s'."; static $timeout_value_invalid = "Timeout value '%s' is invalid."; static $range_is_invalid = 'Range is invalid.'; static $timeout_exception = 'Timeout!'; static $perfdata_label_equal_sign_forbidden = 'Label may not contain an equal sign.'; static $perfdata_value_must_be_in_class = 'Value must be in class [-0-9.] or be \'U\' if the actual value can\'t be determined.'; static $perfdata_min_must_be_in_class = 'Min must be in class [-0-9.] or empty.'; static $perfdata_max_must_be_in_class = 'Max must be in class [-0-9.] or empty.'; static $perfdata_uom_not_recognized = 'UOM (unit of measurement) "%s" is not recognized.'; static $perfdata_mixed_uom_not_implemented = 'Mixed UOMs (%s and %s) are currently not supported.'; static $no_compatible_range_uom_found = 'Measured values are not compatible with the provided warning/critical parameter. Most likely, the UOM is incompatible.'; static $exception_x = '%s (%s)'; static $no_syntax_defined = 'The author of this plugin has not defined a syntax for this plugin.'; static $usage_x = "Usage:\n%s"; static $options = "Options:"; static $illegal_statusmodel = "Invalid statusmodel %d."; static $none = '[none]'; static $valueUomPairSyntaxError = 'Syntax error at "%s". Syntax must be Value[UOM].'; static $too_few_warning_ranges = "You have too few warning ranges (currently trying to get element %d)."; static $too_few_critical_ranges = "You have too few critical ranges (currently trying to get element %d)."; static $dataset_missing = 'Dataset missing.'; static $payload_not_base64 = 'The payload is not valid Base64.'; static $payload_not_json = 'The payload is not valid JSON.'; static $signature_missing = 'The signature is missing.'; static $signature_not_bas64 = 'The signature is not valid Base64.'; static $signature_invalid = 'The signature is invalid. The connection might have been tampered, or a different key is used.'; static $pubkey_file_not_found = "Public key file %s was not found."; static $pubkey_file_not_readable = "Public key file %s is not readable."; static $privkey_file_not_found = "Private key file %s was not found."; static $privkey_not_readable = "Private key is not readable."; static $privkey_file_not_readable = "Private key file %s is not readable."; static $signature_failed = "Signature failed."; static $perfdata_line_invalid = "Performance data line %s is invalid."; static $singlevalue_unexpected_at_symbol = 'This plugin does not allow the @-symbol at ranges for single values.'; static $illegalSingleValueBehavior = "Illegal value for 'singleValueBehavior'. Please contact the creator of the plugin."; static $dataset_encryption_no_array = 'Dataset encryption information invalid.'; static $require_password = 'This resource is protected with a password. Please provide a password.'; static $wrong_password = 'This resource is protected with a password. You have provided the wrong password, or it was changed.'; static $convert_x_y_error = 'Cannot convert from UOM %s to UOM %s.'; static $php_error = 'PHP has detected an error in the plugin. Please contact the plugin author.'; static $output_level_lowered = "Output Buffer level lowered during cbRun(). Please contact the plugin author."; static $openssl_missing = "OpenSSL is missing. Therefore, encryption and signatures are not available."; static $warning_range = 'Warning range'; static $critical_range = 'Critical range'; static $prints_version = 'Prints version'; static $verbosity_helptext = 'Verbosity -v, -vv or -vvv'; static $timeout_helptext = 'Sets timeout in seconds'; static $help_helptext = 'Prints help page'; static $prints_usage = 'Prints usage'; static $notConstructed = 'Parent constructor not called with parent::__construct().'; } function vnagErrorHandler($errorkind, $errortext, $file, $line) { global $inside_vnag_run; if (!$inside_vnag_run && VNag::is_http_mode()) { return false; } if (!(error_reporting() & $errorkind)) { return true; } if (defined('E_ERROR') && ($errorkind == E_ERROR)) $errorkind = 'Error'; if (defined('E_WARNING') && ($errorkind == E_WARNING)) $errorkind = 'Warning'; if (defined('E_PARSE') && ($errorkind == E_PARSE)) $errorkind = 'Parse'; if (defined('E_NOTICE') && ($errorkind == E_NOTICE)) $errorkind = 'Notice'; if (defined('E_CORE_ERROR') && ($errorkind == E_CORE_ERROR)) $errorkind = 'Core Error'; if (defined('E_CORE_WARNING') && ($errorkind == E_CORE_WARNING)) $errorkind = 'Core Warning'; if (defined('E_COMPILE_ERROR') && ($errorkind == E_COMPILE_ERROR)) $errorkind = 'Compile Error'; if (defined('E_COMPILE_WARNING') && ($errorkind == E_COMPILE_WARNING)) $errorkind = 'Compile Warning'; if (defined('E_USER_ERROR') && ($errorkind == E_USER_ERROR)) $errorkind = 'User Error'; if (defined('E_USER_WARNING') && ($errorkind == E_USER_WARNING)) $errorkind = 'User Warning'; if (defined('E_USER_NOTICE') && ($errorkind == E_USER_NOTICE)) $errorkind = 'User Notice'; if (defined('E_STRICT') && ($errorkind == E_STRICT)) $errorkind = 'Strict'; if (defined('E_RECOVERABLE_ERROR') && ($errorkind == E_RECOVERABLE_ERROR)) $errorkind = 'Recoverable Error'; if (defined('E_DEPRECATED') && ($errorkind == E_DEPRECATED)) $errorkind = 'Deprecated'; if (defined('E_USER_DEPRECATED') && ($errorkind == E_USER_DEPRECATED)) $errorkind = 'User Deprecated'; throw new VNagException(VNagLang::$php_error . " $errortext at $file:$line (kind $errorkind)"); } $inside_vnag_run = false; $old_error_handler = set_error_handler("vnagErrorHandler"); <?php
declare(ticks=1); class NoccVersionCheck extends VNag { protected $argSystemDir = null; public function __construct() { parent::__construct(); $this->registerExpectedStandardArguments('Vht'); $this->getHelpManager()->setPluginName('check_nocc_version'); $this->getHelpManager()->setVersion('2023-10-13'); $this->getHelpManager()->setShortDescription('This plugin checks if a local NOCC Webmail system has the latest version installed.'); $this->getHelpManager()->setCopyright('Copyright (C) 2011-$CURYEAR$ Daniel Marschall, ViaThinkSoft.'); $this->getHelpManager()->setSyntax('$SCRIPTNAME$ [-d <directory>]'); $this->getHelpManager()->setFootNotes('If you encounter bugs, please contact ViaThinkSoft at www.viathinksoft.com'); $this->addExpectedArgument($this->argSystemDir = new VNagArgument('d', 'directory', VNagArgument::VALUE_REQUIRED, 'noccPath', 'The local directory where your NOCC installation is located.')); } protected function get_local_version($path) { $path = realpath($path) === false ? $path : realpath($path); $cont = @file_get_contents("$path/common.php"); if ($cont === false) { throw new VNagException("Cannot find version information at $path (common.php not found)"); } if (!preg_match('@\$conf\->nocc_version = \'(.+)\';@ismU', $cont, $m)) { throw new VNagException("Cannot find version information at $path (nocc_version configuration not found)"); } return $m[1]; } protected function get_latest_version() { $cont = $this->url_get_contents('http://nocc.sourceforge.net/download/?lang=en'); if ($cont === false) { throw new VNagException("Cannot access website with latest version"); } if (!preg_match('@Download the current NOCC version <strong>(.+)</strong>@ismU', $cont, $m)) { if (!preg_match('@/nocc\-(.+)\.tar\.gz"@ismU', $cont, $m)) { throw new VNagException("Cannot find version information on the website"); } } return trim($m[1]); } protected function cbRun($optional_args=array()) { $system_dir = $this->argSystemDir->getValue(); if (empty($system_dir)) { throw new VNagException("Please specify the directory of the NOCC installation."); } $system_dir = realpath($system_dir) === false ? $system_dir : realpath($system_dir); if (!is_dir($system_dir)) { throw new VNagException('Directory "'.$system_dir.'" not found.'); } $version = $this->get_local_version($system_dir); $latest_version = $this->get_latest_version(); if (version_compare($version,$latest_version) >= 0) { $this->setStatus(VNag::STATUS_OK); $this->setHeadline("Version $version at $system_dir", true); } else { $this->setStatus(VNag::STATUS_WARNING); $this->setHeadline("Version $version is outdated (Latest version is $latest_version) at $system_dir", true); } } } <?php
declare(ticks=1); require_once __DIR__ . '/../../framework/vnag_framework.inc.php'; require_once __DIR__ . '/NoccVersionCheck.class.php'; $job = new NoccVersionCheck(); $job->run(); unset($job); ßøó¶é“f/û円|Æ«~‘~Òi6´
ÎíÇô˜ÙíçÎë·åøZïÎï€[×Öidùº‹WAšä¿üGBMB
+nPt wJùûÉÞFd¯F™'ƒÕ):‘-GBMB
\ No newline at end of file
/trunk/bin/open_deleted_files.phar
291,12 → 291,12
 
Extract_Phar::go();
__HALT_COMPILER(); ?>
‰‘a:1:{s:23:"1.3.6.1.4.1.37476.3.0.2";s:355:"sha256||framework/vnag_framework.inc.php|460b109d1c578e9b6af41612e0312c9f36fd8beb51f7aa92f1b7bd49614568e8||plugins/open_deleted_files/OpenDeletedFilesCheck.class.php|c5aee76f2000e1c4ee26edf960dc788be4cd802c613ba1ec148c68d022377b20||plugins/open_deleted_files/check_open_deleted_files.phps|817fb1c9471a8c6f6b1618847ca4fdda8af26febbd4ceaaef4924d3582204344||";} framework/vnag_framework.inc.phpLÙzï*eLُ4p”¤:plugins/open_deleted_files/OpenDeletedFilesCheck.class.php
ÕÝa:1:{s:23:"1.3.6.1.4.1.37476.3.0.2";s:431:"sha256||<builder>|481cf75d675006b504520fd2acb3b29c89aea03aab64754e0adfb364de4914b2||framework/vnag_framework.inc.php|0387bf3134f8cc2d1ae24e139019c0edef19c1ba5ca765624efea0b469c7897f||plugins/open_deleted_files/OpenDeletedFilesCheck.class.php|c5aee76f2000e1c4ee26edf960dc788be4cd802c613ba1ec148c68d022377b20||plugins/open_deleted_files/check_open_deleted_files.phps|817fb1c9471a8c6f6b1618847ca4fdda8af26febbd4ceaaef4924d3582204344||";} framework/vnag_framework.inc.phpBÙ» +eBÙÞß=¤:plugins/open_deleted_files/OpenDeletedFilesCheck.class.php
 
zï*e
» +e
 
75¦¤8plugins/open_deleted_files/check_open_deleted_files.phpsÔzï*eÔº}6O¤<?php ?>
<?php
75¦¤8plugins/open_deleted_files/check_open_deleted_files.phpsÔ» +eÔº}6O¤<?php
if (!VNag::is_http_mode()) error_reporting(E_ALL); declare(ticks=1); set_time_limit(0); define('VNAG_JSONDATA_V1', 'oid:1.3.6.1.4.1.37476.2.3.1.1'); $OVERWRITE_ARGUMENTS = null; function _empty($x) { return is_null($x) || (trim($x) == ''); } abstract class VNag { const VNAG_VERSION = '2023-10-13'; const STATUS_OK = 0; const STATUS_WARNING = 1; const STATUS_CRITICAL = 2; const STATUS_UNKNOWN = 3; const STATUS_ERROR = 4; const STATUS_UP = 0; const STATUS_DOWN = 1; const STATUS_MAINTAIN = 2; const VERBOSITY_SUMMARY = 0; const VERBOSITY_ADDITIONAL_INFORMATION = 1; const VERBOSITY_CONFIGURATION_DEBUG = 2; const VERBOSITY_PLUGIN_DEBUG = 3; const MAX_VERBOSITY = self::VERBOSITY_PLUGIN_DEBUG; const STATUSMODEL_SERVICE = 0; const STATUSMODEL_HOST = 1; private $initialized = false; private $status = null; private $messages = array(); private $verbose_info = ''; private $warningRanges = array(); private $criticalRanges = array(); private $performanceDataObjects = array(); private static $exitcode = 0; private $helpObj = null; private $argHandler = null; const OUTPUT_NEVER = 0; const OUTPUT_SPECIAL = 1; const OUTPUT_NORMAL = 2; const OUTPUT_EXCEPTION = 4; const OUTPUT_ALWAYS = 7; public $http_visual_output = self::OUTPUT_ALWAYS; public $http_invisible_output = self::OUTPUT_ALWAYS; protected $html_before = ''; protected $html_after = ''; protected $statusmodel = self::STATUSMODEL_SERVICE; protected $show_status_in_headline = true; protected $default_status = self::STATUS_UNKNOWN; protected $default_warning_range = null; protected $default_critical_range = null; protected $argWarning; protected $argCritical; protected $argVersion; protected $argVerbosity; protected $argTimeout; protected $argHelp; protected $argUsage; public $id = null; protected static $http_serial_number = 0; public $privkey = null; public $privkey_password = null; public $sign_algo = null; public $pubkey = null; protected $warningSingleValueRangeBehaviors = array(self::SINGLEVALUE_RANGE_DEFAULT); protected $criticalSingleValueRangeBehaviors = array(self::SINGLEVALUE_RANGE_DEFAULT); const SINGLEVALUE_RANGE_DEFAULT = 0; const SINGLEVALUE_RANGE_VAL_GT_X_BAD = 1; const SINGLEVALUE_RANGE_VAL_GE_X_BAD = 2; const SINGLEVALUE_RANGE_VAL_LT_X_BAD = 3; const SINGLEVALUE_RANGE_VAL_LE_X_BAD = 4; public $password_out = null; public $password_in = null; public static function is_http_mode() { return php_sapi_name() !== 'cli'; } public function getHelpManager() { return $this->helpObj; } public function getArgumentHandler() { return $this->argHandler; } public function outputHTML($text, $after_visual_output=true) { if ($this->is_http_mode()) { if ($this->initialized) { if ($after_visual_output) { $this->html_after .= $text; } else { $this->html_before .= $text; } } else { echo $text; } } } protected function resetArguments() { $this->argWarning = null; $this->argCritical = null; $this->argVersion = null; $this->argVerbosity = null; $this->argTimeout = null; $this->argHelp = null; $this->argWarning = null; $this->argCritical = null; } public function registerExpectedStandardArguments($args) { $this->resetArguments(); for ($i=0; $i<strlen($args); $i++) { switch ($args[$i]) { case 'w': $this->addExpectedArgument($this->argWarning = new VNagArgument('w', 'warning', VNagArgument::VALUE_REQUIRED, VNagLang::$argname_value, VNagLang::$warning_range)); break; case 'c': $this->addExpectedArgument($this->argCritical = new VNagArgument('c', 'critical', VNagArgument::VALUE_REQUIRED, VNagLang::$argname_value, VNagLang::$critical_range)); break; case 'V': $this->addExpectedArgument($this->argVersion = new VNagArgument('V', 'version', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$prints_version)); break; case 'v': $this->addExpectedArgument($this->argVerbosity = new VNagArgument('v', 'verbose', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$verbosity_helptext)); break; case 't': $this->addExpectedArgument($this->argTimeout = new VNagArgument('t', 'timeout', VNagArgument::VALUE_REQUIRED, VNagLang::$argname_seconds, VNagLang::$timeout_helptext)); break; case 'h': $this->addExpectedArgument($this->argHelp = new VNagArgument('h', 'help', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$help_helptext)); break; default: $letter = $args[$i]; throw new VNagInvalidStandardArgument(sprintf(VNagLang::$no_standard_arguments_with_letter, $letter)); } } } public function addExpectedArgument($argObj) { $helpObjAddEntryMethod = new ReflectionMethod($this->helpObj, '_addOption'); $helpObjAddEntryMethod->setAccessible(true); $helpObjAddEntryMethod->invoke($this->helpObj, $argObj); $argHandlerAddEntryMethod = new ReflectionMethod($this->argHandler, '_addExpectedArgument'); $argHandlerAddEntryMethod->setAccessible(true); $argHandlerAddEntryMethod->invoke($this->argHandler, $argObj); } protected function createArgumentHandler() { $this->argHandler = new VNagArgumentHandler(); } protected function createHelpObject() { $this->helpObj = new VNagHelp(); } protected function checkInitialized() { if (!$this->initialized) throw new VNagFunctionCallOutsideSession(); } protected function getVerbosityLevel() { $this->checkInitialized(); if (!isset($this->argVerbosity)) { return self::VERBOSITY_SUMMARY; } else { $level = $this->argVerbosity->count(); if ($level > self::MAX_VERBOSITY) $level = self::MAX_VERBOSITY; return $level; } } public function getWarningRange($argumentNumber=0) { $this->checkInitialized(); if (!isset($this->warningRanges[$argumentNumber])) { if (!is_null($this->argWarning)) { $warning = $this->argWarning->getValue(); if (!is_null($warning)) { $vals = explode(',',$warning); foreach ($vals as $number => $val) { if (_empty($val)) { $this->warningRanges[$number] = null; } else { $singleValueBehavior = isset($this->warningSingleValueRangeBehaviors[$number]) ? $this->warningSingleValueRangeBehaviors[$number] : VNag::SINGLEVALUE_RANGE_DEFAULT; $this->warningRanges[$number] = new VNagRange($val, $singleValueBehavior); } } } else { $this->warningRanges[0] = $this->default_warning_range; } } else { return null; } } if (isset($this->warningRanges[$argumentNumber])) { return $this->warningRanges[$argumentNumber]; } else { return null; } } public function getCriticalRange($argumentNumber=0) { $this->checkInitialized(); if (!isset($this->criticalRanges[$argumentNumber])) { if (!is_null($this->argCritical)) { $critical = $this->argCritical->getValue(); if (!is_null($critical)) { $vals = explode(',',$critical); foreach ($vals as $number => $val) { $singleValueBehavior = isset($this->criticalSingleValueRangeBehaviors[$number]) ? $this->criticalSingleValueRangeBehaviors[$number] : VNag::SINGLEVALUE_RANGE_DEFAULT; $this->criticalRanges[$number] = new VNagRange($val, $singleValueBehavior); } } else { $this->criticalRanges[0] = $this->default_critical_range; } } else { return null; } } if (isset($this->criticalRanges[$argumentNumber])) { return $this->criticalRanges[$argumentNumber]; } else { return null; } } public function checkAgainstWarningRange($values, $force=true, $autostatus=true, $argumentNumber=0) { $this->checkInitialized(); if (!$this->getArgumentHandler()->isArgRegistered('w')) { throw new VNagRequiredArgumentNotRegistered('-w'); } $wr = $this->getWarningRange($argumentNumber); if (isset($wr)) { if ($wr->checkAlert($values)) { if ($autostatus) $this->setStatus(VNag::STATUS_WARNING); return true; } else { if ($autostatus) $this->setStatus(VNag::STATUS_OK); return false; } } else { if ($force) { if (($argumentNumber > 0) && (count($this->warningRanges) > 0)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$too_few_warning_ranges, $argumentNumber+1)); } else { throw new VNagRequiredArgumentMissing('-w'); } } } } public function checkAgainstCriticalRange($values, $force=true, $autostatus=true, $argumentNumber=0) { $this->checkInitialized(); if (!$this->getArgumentHandler()->isArgRegistered('c')) { throw new VNagRequiredArgumentNotRegistered('-c'); } $cr = $this->getCriticalRange($argumentNumber); if (isset($cr)) { if ($cr->checkAlert($values)) { if ($autostatus) $this->setStatus(VNag::STATUS_CRITICAL); return true; } else { if ($autostatus) $this->setStatus(VNag::STATUS_OK); return false; } } else { if ($force) { if (($argumentNumber > 0) && (count($this->warningRanges) > 0)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$too_few_critical_ranges, $argumentNumber+1)); } else { throw new VNagRequiredArgumentMissing('-c'); } } } } protected static function getBaddestExitcode($code1, $code2) { return max($code1, $code2); } public static function _shutdownHandler() { if (!self::is_http_mode()) { exit((int)self::$exitcode); } } protected function _exit($code) { self::$exitcode = $this->getBaddestExitcode($code, self::$exitcode); } private $constructed = false; function __construct() { $this->createHelpObject(); $this->createArgumentHandler(); $this->addExpectedArgument($this->argUsage = new VNagArgument('?', '', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$prints_usage)); $this->constructed = true; } function __destruct() { if (Timeouter::started()) { Timeouter::end(); } } public function run() { global $inside_vnag_run; $inside_vnag_run = true; try { if (!$this->constructed) { throw new VNagNotConstructed(VNagLang::$notConstructed); } try { $this->initialized = true; $this->html_before = ''; $this->html_after = ''; $this->setStatus(null, true); $this->messages = array(); register_shutdown_function(array($this, '_shutdownHandler')); if ($this->argHandler->illegalUsage()) { $content = $this->helpObj->printUsagePage(); $this->setStatus(VNag::STATUS_UNKNOWN); if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_visual_output & VNag::OUTPUT_SPECIAL) echo $this->writeVisualHTML($content); if ($this->http_invisible_output & VNag::OUTPUT_SPECIAL) echo $this->writeInvisibleHTML($content); echo $this->html_after; return; } else { echo $content; return $this->_exit($this->status); } } if (!is_null($this->argVersion) && ($this->argVersion->available())) { $content = $this->helpObj->printVersionPage(); $this->setStatus(VNag::STATUS_UNKNOWN); if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_visual_output & VNag::OUTPUT_SPECIAL) echo $this->writeVisualHTML($content); if ($this->http_invisible_output & VNag::OUTPUT_SPECIAL) echo $this->writeInvisibleHTML($content); echo $this->html_after; return; } else { echo $content; return $this->_exit($this->status); } } if (!is_null($this->argHelp) && ($this->argHelp->available())) { $content = $this->helpObj->printHelpPage(); $this->setStatus(VNag::STATUS_UNKNOWN); if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_visual_output & VNag::OUTPUT_SPECIAL) echo $this->writeVisualHTML($content); if ($this->http_invisible_output & VNag::OUTPUT_SPECIAL) echo $this->writeInvisibleHTML($content); echo $this->html_after; return; } else { echo $content; return $this->_exit($this->status); } } $this->getWarningRange(); $this->getCriticalRange(); if (!is_null($this->argTimeout)) { $timeout = $this->argTimeout->getValue(); if (!is_null($timeout)) { Timeouter::start($timeout); } } ob_start(); $init_ob_level = ob_get_level(); try { $this->cbRun(); if (ob_get_level() < $init_ob_level) throw new VNagImplementationErrorException(VNagLang::$output_level_lowered); } finally { while (ob_get_level() > $init_ob_level) @ob_end_clean(); } if (is_null($this->status)) $this->setStatus($this->default_status,true); $outputType = VNag::OUTPUT_NORMAL; } catch (Exception $e) { $this->handleException($e); $outputType = VNag::OUTPUT_EXCEPTION; } if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_invisible_output & $outputType) { echo $this->writeInvisibleHTML(); } if ($this->http_visual_output & $outputType) { echo $this->writeVisualHTML(); } echo $this->html_after; } else { echo $this->getNagiosConsoleText(); return $this->_exit($this->status); } Timeouter::end(); } finally { $inside_vnag_run = false; } } private function getNagiosConsoleText() { $ary_perfdata = $this->getPerformanceData(); $performancedata_first = array_shift($ary_perfdata); $performancedata_rest = implode(' ', $ary_perfdata); $status_text = VNagLang::status($this->status, $this->statusmodel); if (_empty($this->getHeadline())) { $content = $status_text; } else { if ($this->show_status_in_headline) { $content = $status_text.': '.$this->getHeadline(); } else { $content = $this->getHeadline(); } } if (!_empty($performancedata_first)) $content .= '|'.trim($performancedata_first); $content .= "\n"; if (!_empty($this->verbose_info)) { $content .= trim($this->verbose_info); } if (!_empty($performancedata_rest)) $content .= '|'.trim($performancedata_rest); $content .= "\n"; return trim($content)."\n"; } abstract protected function cbRun(); public function addPerformanceData($prefDataObj, $move_to_font=false, $verbosityLevel=VNag::VERBOSITY_SUMMARY) { $this->checkInitialized(); if ((!isset($this->argVerbosity)) && ($verbosityLevel > VNag::VERBOSITY_SUMMARY)) throw new VNagRequiredArgumentNotRegistered('-v'); if (self::getVerbosityLevel() < $verbosityLevel) return false; if ($move_to_font) { array_unshift($this->performanceDataObjects, $prefDataObj); } else { $this->performanceDataObjects[] = $prefDataObj; } return true; } public function getPerformanceData() { $this->checkInitialized(); return $this->performanceDataObjects; } public function removePerformanceData($prefDataObj) { if (($key = array_search($prefDataObj, $this->performanceDataObjects, true)) !== false) { unset($this->performanceDataObjects[$key]); return true; } else { return false; } } public function clearPerformanceData() { $this->performanceDataObjects = array(); } public function getVerboseInfo() { return $this->verbose_info; } public function clearVerboseInfo() { $this->verbose_info = ''; } private function writeVisualHTML($special_content=null) { if (!_empty($special_content)) { $content = $special_content; } else { $content = strtoupper(VNagLang::$status.': '.VNagLang::status($this->status, $this->statusmodel))."\n\n"; $content .= strtoupper(VNagLang::$message).":\n"; $status_text = VNagLang::status($this->status, $this->statusmodel); if (_empty($this->getHeadline())) { $content .= $status_text; } else { if ($this->show_status_in_headline) { $content .= $status_text.': '.trim($this->getHeadline()); } else { $content .= trim($this->getHeadline()); } } $content .= "\n\n"; if (!_empty($this->verbose_info)) { $content .= strtoupper(VNagLang::$verbose_info).":\n".trim($this->verbose_info)."\n\n"; } $perfdata = $this->getPerformanceData(); if (count($perfdata) > 0) { $content .= strtoupper(VNagLang::$performance_data).":\n"; foreach ($perfdata as $pd) { $content .= trim($pd)."\n"; } $content .= "\n"; } } $colorinfo = ''; $status = $this->getStatus(); if ($status == VNag::STATUS_OK) $colorinfo = ' style="background-color:green;color:white;font-weight:bold"'; else if ($status == VNag::STATUS_WARNING) $colorinfo = ' style="background-color:yellow;color:black;font-weight:bold"'; else if ($status == VNag::STATUS_CRITICAL) $colorinfo = ' style="background-color:red;color:white;font-weight:bold"'; else if ($status == VNag::STATUS_ERROR) $colorinfo = ' style="background-color:purple;color:white;font-weight:bold"'; else $colorinfo = ' style="background-color:lightgray;color:black;font-weight:bold"'; $html_content = trim($content); $html_content = htmlentities($html_content); $html_content = str_replace(' ', '&nbsp;', $html_content); $html_content = nl2br($html_content); return '<table border="1" cellspacing="2" cellpadding="2" style="width:100%" class="vnag_table">'. '<tr'.$colorinfo.' class="vnag_title_row">'. '<td>'.VNagLang::$nagios_output.'</td>'. '</tr>'. '<tr class="vnag_message_row">'. '<td><code>'. $html_content. '</code></td>'. '</tr>'. '</table>'; } protected function readInvisibleHTML($html) { $this->checkInitialized(); $doc = new DOMDocument(); @$doc->loadHTML($html); $tags = $doc->getElementsByTagName('script'); foreach ($tags as $tag) { $type = $tag->getAttribute('type'); if ($type !== 'application/json') continue; $json = $tag->nodeValue; if (!$json) continue; $data = @json_decode($json,true); if (!is_array($data)) continue; if (!isset($data['type'])) continue; if ($data['type'] === VNAG_JSONDATA_V1) { if (!isset($data['datasets'])) throw new VNagWebInfoException(VNagLang::$dataset_missing); foreach ($data['datasets'] as $dataset) { $payload = base64_decode($dataset['payload']); if (!$payload) { throw new VNagWebInfoException(VNagLang::$payload_not_base64); } if (isset($dataset['encryption'])) { $cryptInfo = $dataset['encryption']; if (!is_array($cryptInfo)) { throw new VNagWebInfoException(VNagLang::$dataset_encryption_no_array); } $password = is_null($this->password_in) ? '' : $this->password_in; $salt = base64_decode($cryptInfo['salt']); if ($cryptInfo['hash'] != hash('sha256',$salt.$password)) { if ($password == '') { throw new VNagWebInfoException(VNagLang::$require_password); } else { throw new VNagWebInfoException(VNagLang::$wrong_password); } } if (!function_exists('openssl_decrypt')) { throw new VNagException(VNagLang::$openssl_missing); } $payload = openssl_decrypt($payload, $cryptInfo['method'], $password, 0, $cryptInfo['iv']); } if (!is_null($this->pubkey) && ($this->pubkey !== '')) { if (substr($this->pubkey,0,3) === '---') { $public_key = $this->pubkey; } else { if (!file_exists($this->pubkey)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$pubkey_file_not_found, $this->pubkey)); } $public_key = @file_get_contents($this->pubkey); if (!$public_key) { throw new VNagPublicKeyException(sprintf(VNagLang::$pubkey_file_not_readable, $this->pubkey)); } } if (!isset($dataset['signature'])) { throw new VNagSignatureException(VNagLang::$signature_missing); } $signature = base64_decode($dataset['signature']); if (!$signature) { throw new VNagSignatureException(VNagLang::$signature_not_bas64); } if (!function_exists('openssl_verify')) { throw new VNagException(VNagLang::$openssl_missing); } $sign_algo = is_null($this->sign_algo) ? OPENSSL_ALGO_SHA256 : $this->sign_algo; if (!openssl_verify($payload, $signature, $public_key, $sign_algo)) { throw new VNagSignatureException(VNagLang::$signature_invalid); } } $payload = @json_decode($payload,true); if (!$payload) { throw new VNagWebInfoException(VNagLang::$payload_not_json); } if ($payload['id'] == $this->id) { return $payload; } } } } return null; } private function getNextMonitorID($peek=false) { $result = is_null($this->id) ? self::$http_serial_number : $this->id; if (!$peek) { $this->id = null; self::$http_serial_number++; } return $result; } private function writeInvisibleHTML($special_content=null) { $payload['id'] = $this->getNextMonitorID(); $payload['status'] = $this->getStatus(); if (!_empty($special_content)) { $payload['text'] = $special_content; } else { $payload['headline'] = $this->getHeadline(); $payload['verbose_info'] = $this->verbose_info; $payload['performance_data'] = array(); foreach ($this->performanceDataObjects as $perfdata) { $payload['performance_data'][] = (string)$perfdata; } } $payload = json_encode($payload); $dataset = array(); if (!is_null($this->privkey) && ($this->privkey !== '')) { if (!function_exists('openssl_pkey_get_private') || !function_exists('openssl_sign')) { throw new VNagException(VNagLang::$openssl_missing); } if (substr($this->privkey,0,3) === '---') { $pkeyid = @openssl_pkey_get_private($this->privkey, $this->privkey_password); if (!$pkeyid) { throw new VNagPrivateKeyException(sprintf(VNagLang::$privkey_not_readable)); } } else { if (!file_exists($this->privkey)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$privkey_file_not_found, $this->privkey)); } $pkeyid = @openssl_pkey_get_private('file://'.$this->privkey, $this->privkey_password); if (!$pkeyid) { throw new VNagPrivateKeyException(sprintf(VNagLang::$privkey_file_not_readable, $this->privkey)); } } $signature = ''; $sign_algo = is_null($this->sign_algo) ? OPENSSL_ALGO_SHA256 : $this->sign_algo; if (@openssl_sign($payload, $signature, $pkeyid, $sign_algo)) { if (version_compare(PHP_VERSION, '8.0.0') < 0) { openssl_free_key($pkeyid); } $dataset['signature'] = base64_encode($signature); } else { throw new VNagPrivateKeyException(sprintf(VNagLang::$signature_failed)); } } if (!is_null($this->password_out) && ($this->password_out !== '')) { if (!function_exists('openssl_encrypt')) { throw new VNagException(VNagLang::$openssl_missing); } $password = $this->password_out; $method = 'aes-256-ofb'; $iv = substr(hash('sha256', openssl_random_pseudo_bytes(32)), 0, 16); $salt = openssl_random_pseudo_bytes(32); $cryptInfo = array(); $cryptInfo['method'] = $method; $cryptInfo['iv'] = $iv; $cryptInfo['salt'] = base64_encode($salt); $cryptInfo['hash'] = hash('sha256', $salt.$password); $payload = openssl_encrypt($payload, $method, $password, 0, $iv); $dataset['encryption'] = $cryptInfo; } $dataset['payload'] = base64_encode($payload); $json = array(); $json['type'] = VNAG_JSONDATA_V1; $json['datasets'] = array($dataset); return '<script type="application/json">'. json_encode($json). '</script>'; } protected function appendHeadline($msg) { $this->checkInitialized(); if (_empty($msg)) return false; $this->messages[] = $msg; return true; } protected function changeHeadline($msg) { $this->checkInitialized(); if (_empty($msg)) { $this->messages = array(); } else { $this->messages = array($msg); } return true; } public function setHeadline($msg, $append=false, $verbosityLevel=VNag::VERBOSITY_SUMMARY) { $this->checkInitialized(); if ((!isset($this->argVerbosity)) && ($verbosityLevel > VNag::VERBOSITY_SUMMARY)) throw new VNagRequiredArgumentNotRegistered('-v'); if (self::getVerbosityLevel() < $verbosityLevel) $msg = ''; if ($append) { return $this->appendHeadline($msg); } else { return $this->changeHeadline($msg); } } public function getHeadline() { $this->checkInitialized(); return implode(', ', $this->messages); } public function addVerboseMessage($msg, $verbosityLevel=VNag::VERBOSITY_SUMMARY) { $this->checkInitialized(); if (self::getVerbosityLevel() >= $verbosityLevel) { $this->verbose_info .= $msg."\n"; } } public function setStatus($status, $force=false) { $this->checkInitialized(); if (($force) || is_null($this->status) || ($status > $this->status)) { $this->status = $status; } } public function getStatus() { $this->checkInitialized(); return $this->status; } protected static function exceptionText($exception) { $class = get_class($exception); $msg = $exception->getMessage(); if (!_empty($msg)) { return sprintf(VNagLang::$exception_x, $msg, $class); } else { return sprintf(VNagLang::$unhandled_exception_without_msg, $class); } } protected function handleException($exception) { $this->checkInitialized(); if (!VNag::is_http_mode()) { while (ob_get_level() > 0) @ob_end_clean(); } $this->clearVerboseInfo(); $this->clearPerformanceData(); if ($exception instanceof VNagException) { $this->setStatus($exception->getStatus()); } else { $this->setStatus(self::STATUS_ERROR); } $this->setHeadline($this->exceptionText($exception), false); if ($exception instanceof VNagImplementationErrorException) { $this->addVerboseMessage($exception->getTraceAsString(), VNag::VERBOSITY_SUMMARY); } else { if (isset($this->argVerbosity)) { $this->addVerboseMessage($exception->getTraceAsString(), VNag::VERBOSITY_ADDITIONAL_INFORMATION); } else { } } } protected function get_cache_dir() { $homedir = @getenv('HOME'); if ($homedir && is_dir($homedir)) { $try = "$homedir/.vnag/cache"; if (is_dir($try)) return $try; if (@mkdir($try,0777,true)) return $try; } $user = posix_getpwuid(posix_geteuid()); if (isset($user['dir']) && is_dir($user['dir'])) { $homedir = $user['dir']; $try = "$homedir/.vnag/cache"; if (is_dir($try)) return $try; if (@mkdir($try,0777,true)) return $try; } if (isset($user['name']) && is_dir($user['name'])) { $username = $user['name']; $try = "/tmp/vnag/cache"; if (is_dir($try)) return $try; if (@mkdir($try,0777,true)) return $try; } throw new VNagException("Cannot get cache dir"); } protected function url_get_contents($url, $max_cache_time=1*60*60, $context=null) { $cache_file = $this->get_cache_dir().'/'.hash('sha256',$url); if (file_exists($cache_file) && (time()-filemtime($cache_file) < $max_cache_time)) { $cont = @file_get_contents($cache_file); if ($cont === false) throw new Exception("Failed to get contents from $cache_file"); } else { $options = array( 'http'=>array( 'method'=>"GET", 'header'=>"Accept-language: en\r\n" . "User-Agent: Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B334b Safari/531.21.102011-10-16 20:23:10\r\n" ) ); if (is_null($context)) $context = stream_context_create($options); $cont = @file_get_contents($url, false, $context); if ($cont === false) throw new Exception("Failed to get contents from $url"); file_put_contents($cache_file, $cont); } return $cont; } } class VNagException extends Exception { public function getStatus() { return VNag::STATUS_ERROR; } } class VNagTimeoutException extends VNagException {} class VNagWebInfoException extends VNagException {} class VNagSignatureException extends VNagException {} class VNagPublicKeyException extends VNagException {} class VNagPrivateKeyException extends VNagException {} class VNagInvalidArgumentException extends VNagException { public function getStatus() { return VNag::STATUS_UNKNOWN; } } class VNagValueUomPairSyntaxException extends VNagInvalidArgumentException { public function __construct($str) { $e_msg = sprintf(VNagLang::$valueUomPairSyntaxError, $str); parent::__construct($e_msg); } } class VNagInvalidTimeoutException extends VNagInvalidArgumentException {} class VNagInvalidRangeException extends VNagInvalidArgumentException { public function __construct($msg) { $e_msg = VNagLang::$range_is_invalid; if (!_empty($msg)) $e_msg .= ': '.trim($msg); parent::__construct($e_msg); } } class VNagInvalidShortOpt extends VNagImplementationErrorException {} class VNagInvalidLongOpt extends VNagImplementationErrorException {} class VNagInvalidValuePolicy extends VNagImplementationErrorException {} class VNagIllegalStatusModel extends VNagImplementationErrorException {} class VNagNotConstructed extends VNagImplementationErrorException {} class VNagImplementationErrorException extends VNagException {} class VNagInvalidStandardArgument extends VNagImplementationErrorException {} class VNagFunctionCallOutsideSession extends VNagImplementationErrorException {} class VNagIllegalArgumentValuesException extends VNagImplementationErrorException {} class VNagRequiredArgumentNotRegistered extends VNagImplementationErrorException { public function __construct($required_argument) { $e_msg = sprintf(VNagLang::$query_without_expected_argument, $required_argument); parent::__construct($e_msg); } } class VNagRequiredArgumentMissing extends VNagInvalidArgumentException { public function __construct($required_argument) { $e_msg = sprintf(VNagLang::$required_argument_missing, $required_argument); parent::__construct($e_msg); } } class VNagUnknownUomException extends VNagInvalidArgumentException { public function __construct($uom) { $e_msg = sprintf(VNagLang::$perfdata_uom_not_recognized, $uom); parent::__construct($e_msg); } } class VNagNoCompatibleRangeUomFoundException extends VNagException {} class VNagMixedUomsNotImplemented extends VNagInvalidArgumentException { public function __construct($uom1, $uom2) { if (_empty($uom1)) $uom1 = VNagLang::$none; if (_empty($uom2)) $uom2 = VNagLang::$none; $e_msg = sprintf(VNagLang::$perfdata_mixed_uom_not_implemented, $uom1, $uom2); parent::__construct($e_msg); } } class VNagUomConvertException extends VNagInvalidArgumentException { public function __construct($uom1, $uom2) { if (_empty($uom1)) $uom1 = VNagLang::$none; if (_empty($uom2)) $uom2 = VNagLang::$none; $e_msg = sprintf(VNagLang::$convert_x_y_error, $uom1, $uom2); parent::__construct($e_msg); } } class VNagInvalidPerformanceDataException extends VNagInvalidArgumentException { public function __construct($msg) { $e_msg = VNagLang::$performance_data_invalid; if (!_empty($msg)) $e_msg .= ': '.trim($msg); parent::__construct($e_msg); } } class Timeouter { private static $start_time = false; private static $timeout; private static $fired = false; private static $registered = false; private function __construct() { } public static function start($timeout) { if (!is_numeric($timeout) || ($timeout <= 0)) { throw new VNagInvalidTimeoutException(sprintf(VNagLang::$timeout_value_invalid, $timeout)); } self::$start_time = microtime(true); self::$timeout = (float) $timeout; self::$fired = false; if (!self::$registered) { self::$registered = true; register_tick_function(array('Timeouter', 'tick')); } } public static function started() { return self::$registered; } public static function end() { if (self::$registered) { unregister_tick_function(array('Timeouter', 'tick')); self::$registered = false; } } public static function tick() { if ((!self::$fired) && ((microtime(true) - self::$start_time) > self::$timeout)) { self::$fired = true; throw new VNagTimeoutException(VNagLang::$timeout_exception); } } } class VNagArgument { const VALUE_FORBIDDEN = 0; const VALUE_REQUIRED = 1; const VALUE_OPTIONAL = 2; protected $shortopt; protected $longopts; protected $valuePolicy; protected $valueName; protected $helpText; protected $defaultValue = null; protected static $all_short = ''; protected static $all_long = array(); public function getShortOpt() { return $this->shortopt; } public function getLongOpts() { return $this->longopts; } public function getValuePolicy() { return $this->valuePolicy; } public function getValueName() { return $this->valueName; } public function getHelpText() { return $this->helpText; } static private function validateShortOpt($shortopt) { $m = array(); return preg_match('@^[a-zA-Z0-9\\+\\-\\?]$@', $shortopt, $m); } static private function validateLongOpt($longopt) { $m = array(); return preg_match('@^[a-zA-Z0-9\\+\\-\\?]+$@', $longopt, $m); } public function __construct($shortopt, $longopts, $valuePolicy, $valueName, $helpText, $defaultValue=null) { switch ($valuePolicy) { case VNagArgument::VALUE_FORBIDDEN: if (!_empty($valueName)) { throw new VNagImplementationErrorException(sprintf(VNagLang::$value_name_forbidden)); } break; case VNagArgument::VALUE_REQUIRED: if (_empty($valueName)) { throw new VNagImplementationErrorException(sprintf(VNagLang::$value_name_required)); } break; case VNagArgument::VALUE_OPTIONAL: if (_empty($valueName)) { throw new VNagImplementationErrorException(sprintf(VNagLang::$value_name_required)); } break; default: throw new VNagInvalidValuePolicy(sprintf(VNagLang::$illegal_valuepolicy, $valuePolicy)); } if (!_empty($shortopt)) { if (!self::validateShortOpt($shortopt)) { throw new VNagInvalidShortOpt(sprintf(VNagLang::$illegal_shortopt, $shortopt)); } } if (is_array($longopts)) { foreach ($longopts as $longopt) { if (!self::validateLongOpt($longopt)) { throw new VNagInvalidLongOpt(sprintf(VNagLang::$illegal_longopt, $longopt)); } } } else if (!_empty($longopts)) { if (!self::validateLongOpt($longopts)) { throw new VNagInvalidLongOpt(sprintf(VNagLang::$illegal_longopt, $longopts)); } $longopts = array($longopts); } else { $longopts = array(); } switch ($valuePolicy) { case VNagArgument::VALUE_FORBIDDEN: $policyApdx = ''; break; case VNagArgument::VALUE_REQUIRED: $policyApdx = ':'; break; case VNagArgument::VALUE_OPTIONAL: $policyApdx = '::'; break; default: throw new VNagInvalidValuePolicy(sprintf(VNagLang::$illegal_valuepolicy, $valuePolicy)); } if ((!is_null($shortopt)) && ($shortopt != '?')) self::$all_short .= $shortopt.$policyApdx; if (is_array($longopts)) { foreach ($longopts as $longopt) { self::$all_long[] = $longopt.$policyApdx; } } $this->shortopt = $shortopt; $this->longopts = $longopts; $this->valuePolicy = $valuePolicy; $this->valueName = $valueName; $this->helpText = $helpText; $this->defaultValue = $defaultValue; } protected static function getOptions() { global $OVERWRITE_ARGUMENTS; if (!is_null($OVERWRITE_ARGUMENTS)) { return $OVERWRITE_ARGUMENTS; } else if (VNag::is_http_mode()) { return $_REQUEST; } else { return getopt(self::$all_short, self::$all_long); } } public function count() { $options = self::getOptions(); $count = 0; if (isset($options[$this->shortopt])) { if (is_array($options[$this->shortopt])) { $count += count($options[$this->shortopt]); } else { $count += 1; } } if (!is_null($this->longopts)) { foreach ($this->longopts as $longopt) { if (isset($options[$longopt])) { if (is_array($options[$longopt])) { $count += count($options[$longopt]); } else { $count += 1; } } } } return $count; } public function available() { $options = self::getOptions(); if (isset($options[$this->shortopt])) return true; if (!is_null($this->longopts)) { foreach ($this->longopts as $longopt) { if (isset($options[$longopt])) return true; } } return false; } public function require() { if (!$this->available() && is_null($this->defaultValue)) { $opt = $this->shortopt; $opt = !_empty($opt) ? '-'.$opt : (isset($this->longopts[0]) ? '--'.$this->longopts[0] : '?'); throw new VNagRequiredArgumentMissing($opt); } } public function getValue() { $options = self::getOptions(); if (isset($options[$this->shortopt])) { $x = $options[$this->shortopt]; if (is_array($x) && (count($x) <= 1)) $options[$this->shortopt] = $options[$this->shortopt][0]; return $options[$this->shortopt]; } if (!is_null($this->longopts)) { foreach ($this->longopts as $longopt) { if (isset($options[$longopt])) { $x = $options[$longopt]; if (is_array($x) && (count($x) <= 1)) $options[$longopt] = $options[$longopt][0]; return $options[$longopt]; } } } return $this->defaultValue; } } class VNagArgumentHandler { protected $expectedArgs = array(); protected function _addExpectedArgument($argObj) { if ($argObj->getShortOpt() == '?') return false; if ($argObj->getShortOpt() == '-') return false; if ($argObj->getShortOpt() == '+') return false; $this->expectedArgs[] = $argObj; return true; } public function getArgumentObj($shortopt) { foreach ($this->expectedArgs as $argObj) { if ($argObj->getShortOpt() == $shortopt) return $argObj; } return null; } public function isArgRegistered($shortopt) { return !is_null($this->getArgumentObj($shortopt)); } public function illegalUsage() { global $argv; return (isset($argv[1])) && (($argv[1] == '-?') || ($argv[1] == '/?')); } } class VNagRange { public $start; public $end; public $warnInsideRange; public function __construct($rangeDef, $singleValueBehavior=VNag::SINGLEVALUE_RANGE_DEFAULT) { $m = array(); if (!preg_match('|^(@){0,1}([^:]+)(:){0,1}(.*)$|', $rangeDef, $m)) { throw new VNagInvalidRangeException(sprintf(VNagLang::$range_invalid_syntax, $rangeDef)); } $this->warnInsideRange = $m[1] === '@'; $this->start = null; $this->end = null; if ($m[3] === ':') { if ($m[2] === '~') { $this->start = '-inf'; } else { $this->start = new VNagValueUomPair($m[2]); } if (_empty($m[4])) { $this->end = 'inf'; } else { $this->end = new VNagValueUomPair($m[4]); } } else { assert(_empty($m[4])); assert(!_empty($m[2])); $x = $m[2]; if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_DEFAULT) { $this->start = new VNagValueUomPair('0'.((new VNagValueUomPair($x))->getUom())); $this->end = new VNagValueUomPair($x); } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_GT_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 0; $this->start = '-inf'; $this->end = new VNagValueUomPair($x); } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_GE_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 1; $this->start = new VNagValueUomPair($x); $this->end = 'inf'; } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_LT_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 0; $this->start = new VNagValueUomPair($x); $this->end = 'inf'; } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_LE_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 1; $this->start = '-inf'; $this->end = new VNagValueUomPair($x); } else { throw new VNagException(VNagLang::$illegalSingleValueBehavior); } } if (is_null($this->start)) { throw new VNagInvalidRangeException(VNagLang::$invalid_start_value); } if (is_null($this->end)) { throw new VNagInvalidRangeException(VNagLang::$invalid_end_value); } if (($this->start instanceof VNagValueUomPair) && ($this->end instanceof VNagValueUomPair) && (VNagValueUomPair::compare($this->start,$this->end) > 0)) { throw new VNagInvalidRangeException(VNagLang::$start_is_greater_than_end); } } public function __toString() { $ret = ''; if ($this->warnInsideRange) { $ret = '@'; } if ($this->start === '-inf') { $ret .= '~'; } else { $ret .= $this->start; } $ret .= ':'; if ($this->end !== 'inf') { $ret .= $this->end; } return $ret; } public function checkAlert($values) { $compatibleCount = 0; if (!is_array($values)) $values = array($values); foreach ($values as $value) { if (!($value instanceof VNagValueUomPair)) $value = new VNagValueUomPair($value); assert(($this->start === '-inf') || ($this->start instanceof VNagValueUomPair)); assert(($this->end === 'inf' ) || ($this->end instanceof VNagValueUomPair)); if (($this->start !== '-inf') && (!$this->start->compatibleWith($value))) continue; if (($this->end !== 'inf') && (!$this->end->compatibleWith($value))) continue; $compatibleCount++; if ($this->warnInsideRange) { return (($this->start === '-inf') || (VNagValueUomPair::compare($value,$this->start) >= 0)) && (($this->end === 'inf') || (VNagValueUomPair::compare($value,$this->end) <= 0)); } else { return (($this->start !== '-inf') && (VNagValueUomPair::compare($value,$this->start) < 0)) || (($this->end !== 'inf') && (VNagValueUomPair::compare($value,$this->end) > 0)); } } if ((count($values) > 0) and ($compatibleCount == 0)) { throw new VNagNoCompatibleRangeUomFoundException(VNagLang::$no_compatible_range_uom_found); } return false; } } class VNagValueUomPair { protected $value; protected $uom; public $roundTo = -1; public function isRelative() { return $this->uom === '%'; } public function getValue() { return $this->value; } public function getUom() { return $this->uom; } public function __toString() { if ($this->roundTo == -1) { return $this->value.$this->uom; } else { return round($this->value,$this->roundTo).$this->uom; } } public function __construct($str) { $m = array(); if (!preg_match('/^([\d\.]+)(.*)$/ism', $str, $m)) { throw new VNagValueUomPairSyntaxException($str); } $this->value = $m[1]; $this->uom = isset($m[2]) ? $m[2] : ''; if (!self::isKnownUOM($this->uom)) { throw new VNagUnknownUomException($this->uom); } } public static function isKnownUOM(string $uom) { $no_unit = ($uom === ''); $seconds = ($uom === 's') || ($uom === 'ms') || ($uom === 'us'); $percentage = ($uom === '%'); $bytes = ($uom === 'B') || ($uom === 'KB') || ($uom === 'MB') || ($uom === 'GB') || ($uom === 'TB'); $counter = ($uom === 'c'); return ($no_unit || $seconds || $percentage || $bytes || $counter); } public function normalize($target=null) { $res = clone $this; if ($res->uom === 'ms') { $res->uom = 's'; $res->value /= 1000; } if ($res->uom === 'us') { $res->uom = 's'; $res->value /= 1000 * 1000; } if ($res->uom === 'B') { $res->uom = 'MB'; $res->value /= 1024 * 1024; } if ($res->uom === 'KB') { $res->uom = 'MB'; $res->value /= 1024; } if ($res->uom === 'GB') { $res->uom = 'MB'; $res->value *= 1024; } if ($res->uom === 'TB') { $res->uom = 'MB'; $res->value *= 1024 * 1024; } if ($res->uom === 'c') { $res->uom = ''; } if (!is_null($target)) { if ($res->uom == 'MB') { if ($target == 'B') { $res->uom = 'B'; $res->value *= 1024 * 1024; } else if ($target == 'KB') { $res->uom = 'KB'; $res->value *= 1024; } else if ($target == 'MB') { $res->uom = 'MB'; $res->value *= 1; } else if ($target == 'GB') { $res->uom = 'GB'; $res->value /= 1024; } else if ($target == 'TB') { $res->uom = 'TB'; $res->value /= 1024 * 1024; } else { throw new VNagUomConvertException($res->uom, $target); } } else if ($res->uom == 's') { if ($target == 's') { $res->uom = 's'; $res->value /= 1; } else if ($target == 'ms') { $res->uom = 'ms'; $res->value /= 1000; } else if ($target == 'us') { $res->uom = 'us'; $res->value /= 1000 * 1000; } else { throw new VNagUomConvertException($res->uom, $target); } } else { throw new VNagUomConvertException($res->uom, $target); } } return $res; } public function compatibleWith(VNagValueUomPair $other) { $a = $this->normalize(); $b = $other->normalize(); return ($a->uom == $b->uom); } public static function compare(VNagValueUomPair $left, VNagValueUomPair $right) { $a = $left->normalize(); $b = $right->normalize(); if ($a->uom != $b->uom) throw new VNagMixedUomsNotImplemented($a->uom, $b->uom); if ($a->value > $b->value) return 1; if ($a->value == $b->value) return 0; if ($a->value < $b->value) return -1; } } class VNagPerformanceData { protected $label; protected $value; protected $warn = null; protected $crit = null; protected $min = null; protected $max = null; public static function createByString($perfdata) { $perfdata = trim($perfdata); $ary = explode('=',$perfdata); if (count($ary) != 2) { throw new VNagInvalidPerformanceDataException(sprintf(VNagLang::$perfdata_line_invalid, $perfdata)); } $label = $ary[0]; $bry = explode(';',$ary[1]); if (substr($label,0,1) === "'") $label = substr($label, 1, strlen($label)-2); $value = $bry[0]; $warn = isset($bry[1]) ? $bry[1] : null; $crit = isset($bry[2]) ? $bry[2] : null; $min = isset($bry[3]) ? $bry[3] : null; $max = isset($bry[4]) ? $bry[4] : null; return new self($label, $value, $warn, $crit, $min, $max); } public function __construct($label, $value, $warn=null, $crit=null, $min=null, $max=null) { if (strpos($label, '=') !== false) throw new VNagInvalidPerformanceDataException(VNagLang::$perfdata_label_equal_sign_forbidden); $label = str_replace("'", "''", $label); $m = array(); if ((!_empty($min)) && (!preg_match('|^[-0-9\\.]+$|', $min, $m))) { throw new VNagInvalidPerformanceDataException(VNagLang::$perfdata_min_must_be_in_class); } if ((!_empty($max)) && (!preg_match('|^[-0-9\\.]+$|', $max, $m))) { throw new VNagInvalidPerformanceDataException(VNagLang::$perfdata_max_must_be_in_class); } $this->label = $label; $this->value = ($value == 'U') ? 'U' : new VNagValueUomPair($value); $this->warn = $warn; $this->crit = $crit; $this->min = $min; $this->max = $max; } public function __toString() { $label = $this->label; $value = $this->value; $warn = $this->warn; $crit = $this->crit; $min = $this->min; $max = $this->max; $label = str_replace("''", "'", $label); return "'$label'=$value". ';'.(is_null($warn) ? '' : $warn). ';'.(is_null($crit) ? '' : $crit). ';'.(is_null($min) ? '' : $min). ';'.(is_null($max) ? '' : $max); } } class VNagHelp { public $word_wrap_width = 80; public $argument_indent = 7; public function printUsagePage() { $usage = $this->getUsage(); if (_empty($usage)) { $usage = VNagLang::$no_syntax_defined; } return trim($usage)."\n"; } public function printVersionPage() { $out = trim($this->getNameAndVersion())."\n"; if ($this->word_wrap_width > 0) $out = wordwrap($out, $this->word_wrap_width, "\n", false); return $out; } static private function _conditionalLine($line, $terminator='', $prefix='') { if (!_empty($line)) { return trim($line).$terminator; } return ''; } public function printHelpPage() { $out = ''; $out .= self::_conditionalLine($this->getNameAndVersion(), "\n"); $out .= self::_conditionalLine($this->getCopyright(), "\n"); $out .= ($out != '') ? "\n" : ''; $out .= self::_conditionalLine($this->getShortDescription(), "\n\n\n"); $out .= self::_conditionalLine($this->getUsage(), "\n\n"); $out .= VNagLang::$options."\n"; foreach ($this->options as $argObj) { $out .= $this->printArgumentHelp($argObj); } $out .= self::_conditionalLine($this->getFootNotes(), "\n\n", "\n"); if ($this->word_wrap_width > 0) $out = wordwrap($out, $this->word_wrap_width, "\n", false); return $out; } protected $options = array(); protected function _addOption($argObj) { $this->options[] = $argObj; } protected function printArgumentHelp($argObj) { $identifiers = array(); $shortopt = $argObj->getShortopt(); if (!_empty($shortopt)) $identifiers[] = '-'.$shortopt; $longopts = $argObj->getLongopts(); if (!is_null($longopts)) { foreach ($longopts as $longopt) { if (!_empty($longopt)) $identifiers[] = '--'.$longopt; } } if (count($identifiers) == 0) return; $valueName = $argObj->getValueName(); $arginfo = ''; switch ($argObj->getValuePolicy()) { case VNagArgument::VALUE_FORBIDDEN: $arginfo = ''; break; case VNagArgument::VALUE_REQUIRED: $arginfo = '='.$valueName; break; case VNagArgument::VALUE_OPTIONAL: $arginfo = '[='.$valueName.']'; break; } $out = ''; $out .= implode(', ', $identifiers).$arginfo."\n"; $content = trim($argObj->getHelpText()); if ($this->word_wrap_width > 0) $content = wordwrap($content, $this->word_wrap_width-$this->argument_indent, "\n", false); $lines = explode("\n", $content); foreach ($lines as $line) { $out .= str_repeat(' ', $this->argument_indent).$line."\n"; } $out .= "\n"; return $out; } protected $pluginName; public function setPluginName($pluginName) { $this->pluginName = $this->replaceStuff($pluginName); } public function getPluginName() { if (_empty($this->pluginName)) { global $argv; return basename($argv[0]); } else { return $this->pluginName; } } protected $version; public function setVersion($version) { $this->version = $this->replaceStuff($version); } public function getVersion() { return $this->version; } public function getNameAndVersion() { $ret = $this->getPluginName(); if (_empty($ret)) return null; $ver = $this->getVersion(); if (!_empty($ver)) { $ret = sprintf(VNagLang::$x_version_x, $ret, $ver); } $ret = trim($ret); return $ret; } protected $copyright; public function setCopyright($copyright) { $this->copyright = $this->replaceStuff($copyright); } private function getVNagCopyright() { if (VNag::is_http_mode()) { $vts_email = 'www.viathinksoft.com'; } else { $vts_email = base64_decode('aW5mb0B2aWF0aGlua3NvZnQuZGU='); } return "VNag Framework ".VNag::VNAG_VERSION." (C) 2014-".date('Y')." ViaThinkSoft <$vts_email>"; } public function getCopyright() { if (_empty($this->copyright)) { return sprintf(VNagLang::$plugin_uses, $this->getVNagCopyright()); } else { return trim($this->copyright)."\n".sprintf(VNagLang::$uses, $this->getVNagCopyright()); } } protected $shortDescription; public function setShortDescription($shortDescription) { $this->shortDescription = $this->replaceStuff($shortDescription); } public function getShortDescription() { if (_empty($this->shortDescription)) { return null; } else { $content = $this->shortDescription; if ($this->word_wrap_width > 0) $content = wordwrap($content, $this->word_wrap_width, "\n", false); return $content; } } protected function replaceStuff($text) { global $argv; if (php_sapi_name() == 'cli') { $text = str_replace('$SCRIPTNAME$', $argv[0], $text); } else { $text = str_replace('$SCRIPTNAME$', basename($_SERVER['SCRIPT_NAME']), $text); } $text = str_replace('$CURYEAR$', date('Y'), $text); return $text; } protected $syntax; public function setSyntax($syntax) { $syntax = $this->replaceStuff($syntax); $this->syntax = $syntax; } public function getUsage() { if (_empty($this->syntax)) { return null; } else { return sprintf(VNagLang::$usage_x, $this->syntax); } } protected $footNotes; public function setFootNotes($footNotes) { $this->footNotes = $this->replaceStuff($footNotes); } public function getFootNotes() { return $this->footNotes; } } class VNagLang { public static function status($code, $statusmodel) { switch ($statusmodel) { case VNag::STATUSMODEL_SERVICE: switch ($code) { case VNag::STATUS_OK: return 'OK'; case VNag::STATUS_WARNING: return 'Warning'; case VNag::STATUS_CRITICAL: return 'Critical'; case VNag::STATUS_UNKNOWN: return 'Unknown'; default: return sprintf('Error (%d)', $code); } case VNag::STATUSMODEL_HOST: switch ($code) { case VNag::STATUS_UP: return 'Up'; case VNag::STATUS_DOWN: return 'Down'; default: return sprintf('Maintain last state (%d)', $code); } default: throw new VNagIllegalStatusModel(sprintf(self::$illegal_statusmodel, $statusmodel)); } } static $nagios_output = 'VNag-Output'; static $verbose_info = 'Verbose information'; static $status = 'Status'; static $message = 'Message'; static $performance_data = 'Performance data'; static $status_ok = 'OK'; static $status_warn = 'Warning'; static $status_critical = 'Critical'; static $status_unknown = 'Unknown'; static $status_error = 'Error'; static $unhandled_exception_without_msg = "Unhandled exception of type %s"; static $plugin_uses = 'This plugin uses %s'; static $uses = 'uses %s'; static $x_version_x = '%s, version %s'; static $argname_value = 'value'; static $argname_seconds = 'seconds'; static $query_without_expected_argument = "The argument '%s' is queried, but was not added to the list of expected arguments. Please contact the plugin author."; static $required_argument_missing = "The argument '%s' is required."; static $performance_data_invalid = 'Performance data invalid.'; static $no_standard_arguments_with_letter = "No standard argument with letter '%s' exists."; static $invalid_start_value = 'Invalid start value.'; static $invalid_end_value = 'Invalid end value.'; static $start_is_greater_than_end = 'Start is greater than end value.'; static $value_name_forbidden = "Implementation error: You may not define a value name for the argument, because the value policy is VALUE_FORBIDDEN."; static $value_name_required = "Implementation error: Please define a name for the argument (so it can be shown in the help page)."; static $illegal_shortopt = "Illegal shortopt '-%s'."; static $illegal_longopt = "Illegal longopt '--%s'."; static $illegal_valuepolicy = "valuePolicy has illegal value '%s'."; static $range_invalid_syntax = "Syntax error in range '%s'."; static $timeout_value_invalid = "Timeout value '%s' is invalid."; static $range_is_invalid = 'Range is invalid.'; static $timeout_exception = 'Timeout!'; static $perfdata_label_equal_sign_forbidden = 'Label may not contain an equal sign.'; static $perfdata_value_must_be_in_class = 'Value must be in class [-0-9.] or be \'U\' if the actual value can\'t be determined.'; static $perfdata_min_must_be_in_class = 'Min must be in class [-0-9.] or empty.'; static $perfdata_max_must_be_in_class = 'Max must be in class [-0-9.] or empty.'; static $perfdata_uom_not_recognized = 'UOM (unit of measurement) "%s" is not recognized.'; static $perfdata_mixed_uom_not_implemented = 'Mixed UOMs (%s and %s) are currently not supported.'; static $no_compatible_range_uom_found = 'Measured values are not compatible with the provided warning/critical parameter. Most likely, the UOM is incompatible.'; static $exception_x = '%s (%s)'; static $no_syntax_defined = 'The author of this plugin has not defined a syntax for this plugin.'; static $usage_x = "Usage:\n%s"; static $options = "Options:"; static $illegal_statusmodel = "Invalid statusmodel %d."; static $none = '[none]'; static $valueUomPairSyntaxError = 'Syntax error at "%s". Syntax must be Value[UOM].'; static $too_few_warning_ranges = "You have too few warning ranges (currently trying to get element %d)."; static $too_few_critical_ranges = "You have too few critical ranges (currently trying to get element %d)."; static $dataset_missing = 'Dataset missing.'; static $payload_not_base64 = 'The payload is not valid Base64.'; static $payload_not_json = 'The payload is not valid JSON.'; static $signature_missing = 'The signature is missing.'; static $signature_not_bas64 = 'The signature is not valid Base64.'; static $signature_invalid = 'The signature is invalid. The connection might have been tampered, or a different key is used.'; static $pubkey_file_not_found = "Public key file %s was not found."; static $pubkey_file_not_readable = "Public key file %s is not readable."; static $privkey_file_not_found = "Private key file %s was not found."; static $privkey_not_readable = "Private key is not readable."; static $privkey_file_not_readable = "Private key file %s is not readable."; static $signature_failed = "Signature failed."; static $perfdata_line_invalid = "Performance data line %s is invalid."; static $singlevalue_unexpected_at_symbol = 'This plugin does not allow the @-symbol at ranges for single values.'; static $illegalSingleValueBehavior = "Illegal value for 'singleValueBehavior'. Please contact the creator of the plugin."; static $dataset_encryption_no_array = 'Dataset encryption information invalid.'; static $require_password = 'This resource is protected with a password. Please provide a password.'; static $wrong_password = 'This resource is protected with a password. You have provided the wrong password, or it was changed.'; static $convert_x_y_error = 'Cannot convert from UOM %s to UOM %s.'; static $php_error = 'PHP has detected an error in the plugin. Please contact the plugin author.'; static $output_level_lowered = "Output Buffer level lowered during cbRun(). Please contact the plugin author."; static $openssl_missing = "OpenSSL is missing. Therefore, encryption and signatures are not available."; static $warning_range = 'Warning range'; static $critical_range = 'Critical range'; static $prints_version = 'Prints version'; static $verbosity_helptext = 'Verbosity -v, -vv or -vvv'; static $timeout_helptext = 'Sets timeout in seconds'; static $help_helptext = 'Prints help page'; static $prints_usage = 'Prints usage'; static $notConstructed = 'Parent constructor not called with parent::__construct().'; } function vnagErrorHandler($errorkind, $errortext, $file, $line) { global $inside_vnag_run; if (!$inside_vnag_run && VNag::is_http_mode()) { return false; } if (!(error_reporting() & $errorkind)) { return true; } if (defined('E_ERROR') && ($errorkind == E_ERROR)) $errorkind = 'Error'; if (defined('E_WARNING') && ($errorkind == E_WARNING)) $errorkind = 'Warning'; if (defined('E_PARSE') && ($errorkind == E_PARSE)) $errorkind = 'Parse'; if (defined('E_NOTICE') && ($errorkind == E_NOTICE)) $errorkind = 'Notice'; if (defined('E_CORE_ERROR') && ($errorkind == E_CORE_ERROR)) $errorkind = 'Core Error'; if (defined('E_CORE_WARNING') && ($errorkind == E_CORE_WARNING)) $errorkind = 'Core Warning'; if (defined('E_COMPILE_ERROR') && ($errorkind == E_COMPILE_ERROR)) $errorkind = 'Compile Error'; if (defined('E_COMPILE_WARNING') && ($errorkind == E_COMPILE_WARNING)) $errorkind = 'Compile Warning'; if (defined('E_USER_ERROR') && ($errorkind == E_USER_ERROR)) $errorkind = 'User Error'; if (defined('E_USER_WARNING') && ($errorkind == E_USER_WARNING)) $errorkind = 'User Warning'; if (defined('E_USER_NOTICE') && ($errorkind == E_USER_NOTICE)) $errorkind = 'User Notice'; if (defined('E_STRICT') && ($errorkind == E_STRICT)) $errorkind = 'Strict'; if (defined('E_RECOVERABLE_ERROR') && ($errorkind == E_RECOVERABLE_ERROR)) $errorkind = 'Recoverable Error'; if (defined('E_DEPRECATED') && ($errorkind == E_DEPRECATED)) $errorkind = 'Deprecated'; if (defined('E_USER_DEPRECATED') && ($errorkind == E_USER_DEPRECATED)) $errorkind = 'User Deprecated'; throw new VNagException(VNagLang::$php_error . " $errortext at $file:$line (kind $errorkind)"); } $inside_vnag_run = false; $old_error_handler = set_error_handler("vnagErrorHandler"); <?php
declare(ticks=1); define('OUTPUT_UOM', 'MB'); define('ROUND_TO', 0); class OpenDeletedFilesCheck extends VNag { protected $argDir = null; public function __construct() { parent::__construct(); $this->registerExpectedStandardArguments('Vhtwc'); $this->getHelpManager()->setPluginName('open_deleted_files'); $this->getHelpManager()->setVersion('2023-10-13'); $this->getHelpManager()->setShortDescription('This plugin checks for open deleted files (which require space but are not visible/accessible anymore).'); $this->getHelpManager()->setCopyright('Copyright (C) 2011-$CURYEAR$ Daniel Marschall, ViaThinkSoft.'); $this->getHelpManager()->setSyntax('$SCRIPTNAME$ [-d directory] [-w warnSizeKB] [-c critSizeKB]'); $this->getHelpManager()->setFootNotes('If you encounter bugs, please contact ViaThinkSoft at www.viathinksoft.com'); $this->addExpectedArgument($this->argDir = new VNagArgument('d', 'directory', VNagArgument::VALUE_REQUIRED, 'directory', 'Directory to check (e.g. /tmp)Directory to check (e.g. /tmp)')); } protected static function check_open_deleted_files($dir_to_check = '/') { exec('lsof -n', $lines, $ec); if ($ec != 0) return false; $line_desc = array_shift($lines); $p_name = strpos($line_desc, 'NAME'); if ($p_name === false) return false; $nodes = array(); foreach ($lines as $line) { if (trim($line) == '') continue; $name = substr($line, $p_name); preg_match('@.+\s(\d+)\$@ism', substr($line, 0, $p_name-1), $m); $tmp = rtrim(substr($line, 0, $p_name-1)); $tmp = explode(" ", $tmp); $node = end($tmp); $tmp = rtrim(substr($line, 0, $p_name-strlen($node)-1)); $tmp = explode(" ", $tmp); $size = end($tmp); if (substr($name, 0, strlen($dir_to_check)) !== $dir_to_check) continue; if (strpos($name, ' (deleted)') === false) continue; if ($size == 0) continue; $nodes[$node] = $size; } $size_total = 0; foreach ($nodes as $node => $size) { $size_total += $size; } return $size_total; } protected function cbRun($optional_args=array()) { $dir = $this->argDir->getValue(); if (empty($dir)) $dir = '/'; $dir = realpath($dir) === false ? $dir : realpath($dir); if (substr($dir,-1) !== '/') $dir .= '/'; $size = self::check_open_deleted_files($dir); if ($size === false) throw new VNagException("Cannot get information from 'lsof'"); $this->checkAgainstWarningRange( array($size.'B'), false, true, 0); $this->checkAgainstCriticalRange(array($size.'B'), false, true, 0); $m = (new VNagValueUomPair($size.'B')); $m->roundTo = ROUND_TO; $sizeOut = $m->normalize(OUTPUT_UOM); $msg = "$sizeOut opened deleted files in $dir"; $this->setHeadline($msg); } } <?php
declare(ticks=1); require_once __DIR__ . '/../../framework/vnag_framework.inc.php'; require_once __DIR__ . '/OpenDeletedFilesCheck.class.php'; $job = new OpenDeletedFilesCheck(); $job->run(); unset($job); CøeJp!‹ÛÇíM]òªC<ʬA›¿²¬+sWÌ,咵™.&,ëT{|'É Û'tmр¿-hÃIäB¦ÖyGBMB
+r¸ñöM È*¿èU± Ðî9t´Rûûm´.͵l‹¬„÷šë€<|ð«W2ÌÜo×¼Çv¬Ô¡÷œ‹ŸŠikGBMB
\ No newline at end of file
/trunk/bin/openbugbounty.phar
291,8 → 291,9
 
Extract_Phar::go();
__HALT_COMPILER(); ?>
ea:1:{s:23:"1.3.6.1.4.1.37476.3.0.2";s:337:"sha256||framework/vnag_framework.inc.php|460b109d1c578e9b6af41612e0312c9f36fd8beb51f7aa92f1b7bd49614568e8||plugins/openbugbounty/OpenBugBountyCheck.class.php|1e2515fb55e3bd734176d138c07da939555b1ff4879d05b9482ffdc9900c77dc||plugins/openbugbounty/check_openbugbounty.phps|f0d3c97a07949f0e8192ad167e8abcc461b895cd47fc3bc7a836968d2f92706e||";} framework/vnag_framework.inc.phpLÙzï*eLُ4p”¤2plugins/openbugbounty/OpenBugBountyCheck.class.php¸zï*e¸l[¸Ú¤.plugins/openbugbounty/check_openbugbounty.phpsÎzï*eÎÕ «¤<?php ?>
<?php
±Ëa:1:{s:23:"1.3.6.1.4.1.37476.3.0.2";s:413:"sha256||<builder>|481cf75d675006b504520fd2acb3b29c89aea03aab64754e0adfb364de4914b2||framework/vnag_framework.inc.php|0387bf3134f8cc2d1ae24e139019c0edef19c1ba5ca765624efea0b469c7897f||plugins/openbugbounty/OpenBugBountyCheck.class.php|1e2515fb55e3bd734176d138c07da939555b1ff4879d05b9482ffdc9900c77dc||plugins/openbugbounty/check_openbugbounty.phps|f0d3c97a07949f0e8192ad167e8abcc461b895cd47fc3bc7a836968d2f92706e||";} framework/vnag_framework.inc.phpBÙ» +eBÙÞß=¤2plugins/openbugbounty/OpenBugBountyCheck.class.php¸» +e¸l[¸Ú¤.plugins/openbugbounty/check_openbugbounty.phpsλ +eÎÕ «¤<?php
if (!VNag::is_http_mode()) error_reporting(E_ALL); declare(ticks=1); set_time_limit(0); define('VNAG_JSONDATA_V1', 'oid:1.3.6.1.4.1.37476.2.3.1.1'); $OVERWRITE_ARGUMENTS = null; function _empty($x) { return is_null($x) || (trim($x) == ''); } abstract class VNag { const VNAG_VERSION = '2023-10-13'; const STATUS_OK = 0; const STATUS_WARNING = 1; const STATUS_CRITICAL = 2; const STATUS_UNKNOWN = 3; const STATUS_ERROR = 4; const STATUS_UP = 0; const STATUS_DOWN = 1; const STATUS_MAINTAIN = 2; const VERBOSITY_SUMMARY = 0; const VERBOSITY_ADDITIONAL_INFORMATION = 1; const VERBOSITY_CONFIGURATION_DEBUG = 2; const VERBOSITY_PLUGIN_DEBUG = 3; const MAX_VERBOSITY = self::VERBOSITY_PLUGIN_DEBUG; const STATUSMODEL_SERVICE = 0; const STATUSMODEL_HOST = 1; private $initialized = false; private $status = null; private $messages = array(); private $verbose_info = ''; private $warningRanges = array(); private $criticalRanges = array(); private $performanceDataObjects = array(); private static $exitcode = 0; private $helpObj = null; private $argHandler = null; const OUTPUT_NEVER = 0; const OUTPUT_SPECIAL = 1; const OUTPUT_NORMAL = 2; const OUTPUT_EXCEPTION = 4; const OUTPUT_ALWAYS = 7; public $http_visual_output = self::OUTPUT_ALWAYS; public $http_invisible_output = self::OUTPUT_ALWAYS; protected $html_before = ''; protected $html_after = ''; protected $statusmodel = self::STATUSMODEL_SERVICE; protected $show_status_in_headline = true; protected $default_status = self::STATUS_UNKNOWN; protected $default_warning_range = null; protected $default_critical_range = null; protected $argWarning; protected $argCritical; protected $argVersion; protected $argVerbosity; protected $argTimeout; protected $argHelp; protected $argUsage; public $id = null; protected static $http_serial_number = 0; public $privkey = null; public $privkey_password = null; public $sign_algo = null; public $pubkey = null; protected $warningSingleValueRangeBehaviors = array(self::SINGLEVALUE_RANGE_DEFAULT); protected $criticalSingleValueRangeBehaviors = array(self::SINGLEVALUE_RANGE_DEFAULT); const SINGLEVALUE_RANGE_DEFAULT = 0; const SINGLEVALUE_RANGE_VAL_GT_X_BAD = 1; const SINGLEVALUE_RANGE_VAL_GE_X_BAD = 2; const SINGLEVALUE_RANGE_VAL_LT_X_BAD = 3; const SINGLEVALUE_RANGE_VAL_LE_X_BAD = 4; public $password_out = null; public $password_in = null; public static function is_http_mode() { return php_sapi_name() !== 'cli'; } public function getHelpManager() { return $this->helpObj; } public function getArgumentHandler() { return $this->argHandler; } public function outputHTML($text, $after_visual_output=true) { if ($this->is_http_mode()) { if ($this->initialized) { if ($after_visual_output) { $this->html_after .= $text; } else { $this->html_before .= $text; } } else { echo $text; } } } protected function resetArguments() { $this->argWarning = null; $this->argCritical = null; $this->argVersion = null; $this->argVerbosity = null; $this->argTimeout = null; $this->argHelp = null; $this->argWarning = null; $this->argCritical = null; } public function registerExpectedStandardArguments($args) { $this->resetArguments(); for ($i=0; $i<strlen($args); $i++) { switch ($args[$i]) { case 'w': $this->addExpectedArgument($this->argWarning = new VNagArgument('w', 'warning', VNagArgument::VALUE_REQUIRED, VNagLang::$argname_value, VNagLang::$warning_range)); break; case 'c': $this->addExpectedArgument($this->argCritical = new VNagArgument('c', 'critical', VNagArgument::VALUE_REQUIRED, VNagLang::$argname_value, VNagLang::$critical_range)); break; case 'V': $this->addExpectedArgument($this->argVersion = new VNagArgument('V', 'version', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$prints_version)); break; case 'v': $this->addExpectedArgument($this->argVerbosity = new VNagArgument('v', 'verbose', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$verbosity_helptext)); break; case 't': $this->addExpectedArgument($this->argTimeout = new VNagArgument('t', 'timeout', VNagArgument::VALUE_REQUIRED, VNagLang::$argname_seconds, VNagLang::$timeout_helptext)); break; case 'h': $this->addExpectedArgument($this->argHelp = new VNagArgument('h', 'help', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$help_helptext)); break; default: $letter = $args[$i]; throw new VNagInvalidStandardArgument(sprintf(VNagLang::$no_standard_arguments_with_letter, $letter)); } } } public function addExpectedArgument($argObj) { $helpObjAddEntryMethod = new ReflectionMethod($this->helpObj, '_addOption'); $helpObjAddEntryMethod->setAccessible(true); $helpObjAddEntryMethod->invoke($this->helpObj, $argObj); $argHandlerAddEntryMethod = new ReflectionMethod($this->argHandler, '_addExpectedArgument'); $argHandlerAddEntryMethod->setAccessible(true); $argHandlerAddEntryMethod->invoke($this->argHandler, $argObj); } protected function createArgumentHandler() { $this->argHandler = new VNagArgumentHandler(); } protected function createHelpObject() { $this->helpObj = new VNagHelp(); } protected function checkInitialized() { if (!$this->initialized) throw new VNagFunctionCallOutsideSession(); } protected function getVerbosityLevel() { $this->checkInitialized(); if (!isset($this->argVerbosity)) { return self::VERBOSITY_SUMMARY; } else { $level = $this->argVerbosity->count(); if ($level > self::MAX_VERBOSITY) $level = self::MAX_VERBOSITY; return $level; } } public function getWarningRange($argumentNumber=0) { $this->checkInitialized(); if (!isset($this->warningRanges[$argumentNumber])) { if (!is_null($this->argWarning)) { $warning = $this->argWarning->getValue(); if (!is_null($warning)) { $vals = explode(',',$warning); foreach ($vals as $number => $val) { if (_empty($val)) { $this->warningRanges[$number] = null; } else { $singleValueBehavior = isset($this->warningSingleValueRangeBehaviors[$number]) ? $this->warningSingleValueRangeBehaviors[$number] : VNag::SINGLEVALUE_RANGE_DEFAULT; $this->warningRanges[$number] = new VNagRange($val, $singleValueBehavior); } } } else { $this->warningRanges[0] = $this->default_warning_range; } } else { return null; } } if (isset($this->warningRanges[$argumentNumber])) { return $this->warningRanges[$argumentNumber]; } else { return null; } } public function getCriticalRange($argumentNumber=0) { $this->checkInitialized(); if (!isset($this->criticalRanges[$argumentNumber])) { if (!is_null($this->argCritical)) { $critical = $this->argCritical->getValue(); if (!is_null($critical)) { $vals = explode(',',$critical); foreach ($vals as $number => $val) { $singleValueBehavior = isset($this->criticalSingleValueRangeBehaviors[$number]) ? $this->criticalSingleValueRangeBehaviors[$number] : VNag::SINGLEVALUE_RANGE_DEFAULT; $this->criticalRanges[$number] = new VNagRange($val, $singleValueBehavior); } } else { $this->criticalRanges[0] = $this->default_critical_range; } } else { return null; } } if (isset($this->criticalRanges[$argumentNumber])) { return $this->criticalRanges[$argumentNumber]; } else { return null; } } public function checkAgainstWarningRange($values, $force=true, $autostatus=true, $argumentNumber=0) { $this->checkInitialized(); if (!$this->getArgumentHandler()->isArgRegistered('w')) { throw new VNagRequiredArgumentNotRegistered('-w'); } $wr = $this->getWarningRange($argumentNumber); if (isset($wr)) { if ($wr->checkAlert($values)) { if ($autostatus) $this->setStatus(VNag::STATUS_WARNING); return true; } else { if ($autostatus) $this->setStatus(VNag::STATUS_OK); return false; } } else { if ($force) { if (($argumentNumber > 0) && (count($this->warningRanges) > 0)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$too_few_warning_ranges, $argumentNumber+1)); } else { throw new VNagRequiredArgumentMissing('-w'); } } } } public function checkAgainstCriticalRange($values, $force=true, $autostatus=true, $argumentNumber=0) { $this->checkInitialized(); if (!$this->getArgumentHandler()->isArgRegistered('c')) { throw new VNagRequiredArgumentNotRegistered('-c'); } $cr = $this->getCriticalRange($argumentNumber); if (isset($cr)) { if ($cr->checkAlert($values)) { if ($autostatus) $this->setStatus(VNag::STATUS_CRITICAL); return true; } else { if ($autostatus) $this->setStatus(VNag::STATUS_OK); return false; } } else { if ($force) { if (($argumentNumber > 0) && (count($this->warningRanges) > 0)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$too_few_critical_ranges, $argumentNumber+1)); } else { throw new VNagRequiredArgumentMissing('-c'); } } } } protected static function getBaddestExitcode($code1, $code2) { return max($code1, $code2); } public static function _shutdownHandler() { if (!self::is_http_mode()) { exit((int)self::$exitcode); } } protected function _exit($code) { self::$exitcode = $this->getBaddestExitcode($code, self::$exitcode); } private $constructed = false; function __construct() { $this->createHelpObject(); $this->createArgumentHandler(); $this->addExpectedArgument($this->argUsage = new VNagArgument('?', '', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$prints_usage)); $this->constructed = true; } function __destruct() { if (Timeouter::started()) { Timeouter::end(); } } public function run() { global $inside_vnag_run; $inside_vnag_run = true; try { if (!$this->constructed) { throw new VNagNotConstructed(VNagLang::$notConstructed); } try { $this->initialized = true; $this->html_before = ''; $this->html_after = ''; $this->setStatus(null, true); $this->messages = array(); register_shutdown_function(array($this, '_shutdownHandler')); if ($this->argHandler->illegalUsage()) { $content = $this->helpObj->printUsagePage(); $this->setStatus(VNag::STATUS_UNKNOWN); if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_visual_output & VNag::OUTPUT_SPECIAL) echo $this->writeVisualHTML($content); if ($this->http_invisible_output & VNag::OUTPUT_SPECIAL) echo $this->writeInvisibleHTML($content); echo $this->html_after; return; } else { echo $content; return $this->_exit($this->status); } } if (!is_null($this->argVersion) && ($this->argVersion->available())) { $content = $this->helpObj->printVersionPage(); $this->setStatus(VNag::STATUS_UNKNOWN); if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_visual_output & VNag::OUTPUT_SPECIAL) echo $this->writeVisualHTML($content); if ($this->http_invisible_output & VNag::OUTPUT_SPECIAL) echo $this->writeInvisibleHTML($content); echo $this->html_after; return; } else { echo $content; return $this->_exit($this->status); } } if (!is_null($this->argHelp) && ($this->argHelp->available())) { $content = $this->helpObj->printHelpPage(); $this->setStatus(VNag::STATUS_UNKNOWN); if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_visual_output & VNag::OUTPUT_SPECIAL) echo $this->writeVisualHTML($content); if ($this->http_invisible_output & VNag::OUTPUT_SPECIAL) echo $this->writeInvisibleHTML($content); echo $this->html_after; return; } else { echo $content; return $this->_exit($this->status); } } $this->getWarningRange(); $this->getCriticalRange(); if (!is_null($this->argTimeout)) { $timeout = $this->argTimeout->getValue(); if (!is_null($timeout)) { Timeouter::start($timeout); } } ob_start(); $init_ob_level = ob_get_level(); try { $this->cbRun(); if (ob_get_level() < $init_ob_level) throw new VNagImplementationErrorException(VNagLang::$output_level_lowered); } finally { while (ob_get_level() > $init_ob_level) @ob_end_clean(); } if (is_null($this->status)) $this->setStatus($this->default_status,true); $outputType = VNag::OUTPUT_NORMAL; } catch (Exception $e) { $this->handleException($e); $outputType = VNag::OUTPUT_EXCEPTION; } if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_invisible_output & $outputType) { echo $this->writeInvisibleHTML(); } if ($this->http_visual_output & $outputType) { echo $this->writeVisualHTML(); } echo $this->html_after; } else { echo $this->getNagiosConsoleText(); return $this->_exit($this->status); } Timeouter::end(); } finally { $inside_vnag_run = false; } } private function getNagiosConsoleText() { $ary_perfdata = $this->getPerformanceData(); $performancedata_first = array_shift($ary_perfdata); $performancedata_rest = implode(' ', $ary_perfdata); $status_text = VNagLang::status($this->status, $this->statusmodel); if (_empty($this->getHeadline())) { $content = $status_text; } else { if ($this->show_status_in_headline) { $content = $status_text.': '.$this->getHeadline(); } else { $content = $this->getHeadline(); } } if (!_empty($performancedata_first)) $content .= '|'.trim($performancedata_first); $content .= "\n"; if (!_empty($this->verbose_info)) { $content .= trim($this->verbose_info); } if (!_empty($performancedata_rest)) $content .= '|'.trim($performancedata_rest); $content .= "\n"; return trim($content)."\n"; } abstract protected function cbRun(); public function addPerformanceData($prefDataObj, $move_to_font=false, $verbosityLevel=VNag::VERBOSITY_SUMMARY) { $this->checkInitialized(); if ((!isset($this->argVerbosity)) && ($verbosityLevel > VNag::VERBOSITY_SUMMARY)) throw new VNagRequiredArgumentNotRegistered('-v'); if (self::getVerbosityLevel() < $verbosityLevel) return false; if ($move_to_font) { array_unshift($this->performanceDataObjects, $prefDataObj); } else { $this->performanceDataObjects[] = $prefDataObj; } return true; } public function getPerformanceData() { $this->checkInitialized(); return $this->performanceDataObjects; } public function removePerformanceData($prefDataObj) { if (($key = array_search($prefDataObj, $this->performanceDataObjects, true)) !== false) { unset($this->performanceDataObjects[$key]); return true; } else { return false; } } public function clearPerformanceData() { $this->performanceDataObjects = array(); } public function getVerboseInfo() { return $this->verbose_info; } public function clearVerboseInfo() { $this->verbose_info = ''; } private function writeVisualHTML($special_content=null) { if (!_empty($special_content)) { $content = $special_content; } else { $content = strtoupper(VNagLang::$status.': '.VNagLang::status($this->status, $this->statusmodel))."\n\n"; $content .= strtoupper(VNagLang::$message).":\n"; $status_text = VNagLang::status($this->status, $this->statusmodel); if (_empty($this->getHeadline())) { $content .= $status_text; } else { if ($this->show_status_in_headline) { $content .= $status_text.': '.trim($this->getHeadline()); } else { $content .= trim($this->getHeadline()); } } $content .= "\n\n"; if (!_empty($this->verbose_info)) { $content .= strtoupper(VNagLang::$verbose_info).":\n".trim($this->verbose_info)."\n\n"; } $perfdata = $this->getPerformanceData(); if (count($perfdata) > 0) { $content .= strtoupper(VNagLang::$performance_data).":\n"; foreach ($perfdata as $pd) { $content .= trim($pd)."\n"; } $content .= "\n"; } } $colorinfo = ''; $status = $this->getStatus(); if ($status == VNag::STATUS_OK) $colorinfo = ' style="background-color:green;color:white;font-weight:bold"'; else if ($status == VNag::STATUS_WARNING) $colorinfo = ' style="background-color:yellow;color:black;font-weight:bold"'; else if ($status == VNag::STATUS_CRITICAL) $colorinfo = ' style="background-color:red;color:white;font-weight:bold"'; else if ($status == VNag::STATUS_ERROR) $colorinfo = ' style="background-color:purple;color:white;font-weight:bold"'; else $colorinfo = ' style="background-color:lightgray;color:black;font-weight:bold"'; $html_content = trim($content); $html_content = htmlentities($html_content); $html_content = str_replace(' ', '&nbsp;', $html_content); $html_content = nl2br($html_content); return '<table border="1" cellspacing="2" cellpadding="2" style="width:100%" class="vnag_table">'. '<tr'.$colorinfo.' class="vnag_title_row">'. '<td>'.VNagLang::$nagios_output.'</td>'. '</tr>'. '<tr class="vnag_message_row">'. '<td><code>'. $html_content. '</code></td>'. '</tr>'. '</table>'; } protected function readInvisibleHTML($html) { $this->checkInitialized(); $doc = new DOMDocument(); @$doc->loadHTML($html); $tags = $doc->getElementsByTagName('script'); foreach ($tags as $tag) { $type = $tag->getAttribute('type'); if ($type !== 'application/json') continue; $json = $tag->nodeValue; if (!$json) continue; $data = @json_decode($json,true); if (!is_array($data)) continue; if (!isset($data['type'])) continue; if ($data['type'] === VNAG_JSONDATA_V1) { if (!isset($data['datasets'])) throw new VNagWebInfoException(VNagLang::$dataset_missing); foreach ($data['datasets'] as $dataset) { $payload = base64_decode($dataset['payload']); if (!$payload) { throw new VNagWebInfoException(VNagLang::$payload_not_base64); } if (isset($dataset['encryption'])) { $cryptInfo = $dataset['encryption']; if (!is_array($cryptInfo)) { throw new VNagWebInfoException(VNagLang::$dataset_encryption_no_array); } $password = is_null($this->password_in) ? '' : $this->password_in; $salt = base64_decode($cryptInfo['salt']); if ($cryptInfo['hash'] != hash('sha256',$salt.$password)) { if ($password == '') { throw new VNagWebInfoException(VNagLang::$require_password); } else { throw new VNagWebInfoException(VNagLang::$wrong_password); } } if (!function_exists('openssl_decrypt')) { throw new VNagException(VNagLang::$openssl_missing); } $payload = openssl_decrypt($payload, $cryptInfo['method'], $password, 0, $cryptInfo['iv']); } if (!is_null($this->pubkey) && ($this->pubkey !== '')) { if (substr($this->pubkey,0,3) === '---') { $public_key = $this->pubkey; } else { if (!file_exists($this->pubkey)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$pubkey_file_not_found, $this->pubkey)); } $public_key = @file_get_contents($this->pubkey); if (!$public_key) { throw new VNagPublicKeyException(sprintf(VNagLang::$pubkey_file_not_readable, $this->pubkey)); } } if (!isset($dataset['signature'])) { throw new VNagSignatureException(VNagLang::$signature_missing); } $signature = base64_decode($dataset['signature']); if (!$signature) { throw new VNagSignatureException(VNagLang::$signature_not_bas64); } if (!function_exists('openssl_verify')) { throw new VNagException(VNagLang::$openssl_missing); } $sign_algo = is_null($this->sign_algo) ? OPENSSL_ALGO_SHA256 : $this->sign_algo; if (!openssl_verify($payload, $signature, $public_key, $sign_algo)) { throw new VNagSignatureException(VNagLang::$signature_invalid); } } $payload = @json_decode($payload,true); if (!$payload) { throw new VNagWebInfoException(VNagLang::$payload_not_json); } if ($payload['id'] == $this->id) { return $payload; } } } } return null; } private function getNextMonitorID($peek=false) { $result = is_null($this->id) ? self::$http_serial_number : $this->id; if (!$peek) { $this->id = null; self::$http_serial_number++; } return $result; } private function writeInvisibleHTML($special_content=null) { $payload['id'] = $this->getNextMonitorID(); $payload['status'] = $this->getStatus(); if (!_empty($special_content)) { $payload['text'] = $special_content; } else { $payload['headline'] = $this->getHeadline(); $payload['verbose_info'] = $this->verbose_info; $payload['performance_data'] = array(); foreach ($this->performanceDataObjects as $perfdata) { $payload['performance_data'][] = (string)$perfdata; } } $payload = json_encode($payload); $dataset = array(); if (!is_null($this->privkey) && ($this->privkey !== '')) { if (!function_exists('openssl_pkey_get_private') || !function_exists('openssl_sign')) { throw new VNagException(VNagLang::$openssl_missing); } if (substr($this->privkey,0,3) === '---') { $pkeyid = @openssl_pkey_get_private($this->privkey, $this->privkey_password); if (!$pkeyid) { throw new VNagPrivateKeyException(sprintf(VNagLang::$privkey_not_readable)); } } else { if (!file_exists($this->privkey)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$privkey_file_not_found, $this->privkey)); } $pkeyid = @openssl_pkey_get_private('file://'.$this->privkey, $this->privkey_password); if (!$pkeyid) { throw new VNagPrivateKeyException(sprintf(VNagLang::$privkey_file_not_readable, $this->privkey)); } } $signature = ''; $sign_algo = is_null($this->sign_algo) ? OPENSSL_ALGO_SHA256 : $this->sign_algo; if (@openssl_sign($payload, $signature, $pkeyid, $sign_algo)) { if (version_compare(PHP_VERSION, '8.0.0') < 0) { openssl_free_key($pkeyid); } $dataset['signature'] = base64_encode($signature); } else { throw new VNagPrivateKeyException(sprintf(VNagLang::$signature_failed)); } } if (!is_null($this->password_out) && ($this->password_out !== '')) { if (!function_exists('openssl_encrypt')) { throw new VNagException(VNagLang::$openssl_missing); } $password = $this->password_out; $method = 'aes-256-ofb'; $iv = substr(hash('sha256', openssl_random_pseudo_bytes(32)), 0, 16); $salt = openssl_random_pseudo_bytes(32); $cryptInfo = array(); $cryptInfo['method'] = $method; $cryptInfo['iv'] = $iv; $cryptInfo['salt'] = base64_encode($salt); $cryptInfo['hash'] = hash('sha256', $salt.$password); $payload = openssl_encrypt($payload, $method, $password, 0, $iv); $dataset['encryption'] = $cryptInfo; } $dataset['payload'] = base64_encode($payload); $json = array(); $json['type'] = VNAG_JSONDATA_V1; $json['datasets'] = array($dataset); return '<script type="application/json">'. json_encode($json). '</script>'; } protected function appendHeadline($msg) { $this->checkInitialized(); if (_empty($msg)) return false; $this->messages[] = $msg; return true; } protected function changeHeadline($msg) { $this->checkInitialized(); if (_empty($msg)) { $this->messages = array(); } else { $this->messages = array($msg); } return true; } public function setHeadline($msg, $append=false, $verbosityLevel=VNag::VERBOSITY_SUMMARY) { $this->checkInitialized(); if ((!isset($this->argVerbosity)) && ($verbosityLevel > VNag::VERBOSITY_SUMMARY)) throw new VNagRequiredArgumentNotRegistered('-v'); if (self::getVerbosityLevel() < $verbosityLevel) $msg = ''; if ($append) { return $this->appendHeadline($msg); } else { return $this->changeHeadline($msg); } } public function getHeadline() { $this->checkInitialized(); return implode(', ', $this->messages); } public function addVerboseMessage($msg, $verbosityLevel=VNag::VERBOSITY_SUMMARY) { $this->checkInitialized(); if (self::getVerbosityLevel() >= $verbosityLevel) { $this->verbose_info .= $msg."\n"; } } public function setStatus($status, $force=false) { $this->checkInitialized(); if (($force) || is_null($this->status) || ($status > $this->status)) { $this->status = $status; } } public function getStatus() { $this->checkInitialized(); return $this->status; } protected static function exceptionText($exception) { $class = get_class($exception); $msg = $exception->getMessage(); if (!_empty($msg)) { return sprintf(VNagLang::$exception_x, $msg, $class); } else { return sprintf(VNagLang::$unhandled_exception_without_msg, $class); } } protected function handleException($exception) { $this->checkInitialized(); if (!VNag::is_http_mode()) { while (ob_get_level() > 0) @ob_end_clean(); } $this->clearVerboseInfo(); $this->clearPerformanceData(); if ($exception instanceof VNagException) { $this->setStatus($exception->getStatus()); } else { $this->setStatus(self::STATUS_ERROR); } $this->setHeadline($this->exceptionText($exception), false); if ($exception instanceof VNagImplementationErrorException) { $this->addVerboseMessage($exception->getTraceAsString(), VNag::VERBOSITY_SUMMARY); } else { if (isset($this->argVerbosity)) { $this->addVerboseMessage($exception->getTraceAsString(), VNag::VERBOSITY_ADDITIONAL_INFORMATION); } else { } } } protected function get_cache_dir() { $homedir = @getenv('HOME'); if ($homedir && is_dir($homedir)) { $try = "$homedir/.vnag/cache"; if (is_dir($try)) return $try; if (@mkdir($try,0777,true)) return $try; } $user = posix_getpwuid(posix_geteuid()); if (isset($user['dir']) && is_dir($user['dir'])) { $homedir = $user['dir']; $try = "$homedir/.vnag/cache"; if (is_dir($try)) return $try; if (@mkdir($try,0777,true)) return $try; } if (isset($user['name']) && is_dir($user['name'])) { $username = $user['name']; $try = "/tmp/vnag/cache"; if (is_dir($try)) return $try; if (@mkdir($try,0777,true)) return $try; } throw new VNagException("Cannot get cache dir"); } protected function url_get_contents($url, $max_cache_time=1*60*60, $context=null) { $cache_file = $this->get_cache_dir().'/'.hash('sha256',$url); if (file_exists($cache_file) && (time()-filemtime($cache_file) < $max_cache_time)) { $cont = @file_get_contents($cache_file); if ($cont === false) throw new Exception("Failed to get contents from $cache_file"); } else { $options = array( 'http'=>array( 'method'=>"GET", 'header'=>"Accept-language: en\r\n" . "User-Agent: Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B334b Safari/531.21.102011-10-16 20:23:10\r\n" ) ); if (is_null($context)) $context = stream_context_create($options); $cont = @file_get_contents($url, false, $context); if ($cont === false) throw new Exception("Failed to get contents from $url"); file_put_contents($cache_file, $cont); } return $cont; } } class VNagException extends Exception { public function getStatus() { return VNag::STATUS_ERROR; } } class VNagTimeoutException extends VNagException {} class VNagWebInfoException extends VNagException {} class VNagSignatureException extends VNagException {} class VNagPublicKeyException extends VNagException {} class VNagPrivateKeyException extends VNagException {} class VNagInvalidArgumentException extends VNagException { public function getStatus() { return VNag::STATUS_UNKNOWN; } } class VNagValueUomPairSyntaxException extends VNagInvalidArgumentException { public function __construct($str) { $e_msg = sprintf(VNagLang::$valueUomPairSyntaxError, $str); parent::__construct($e_msg); } } class VNagInvalidTimeoutException extends VNagInvalidArgumentException {} class VNagInvalidRangeException extends VNagInvalidArgumentException { public function __construct($msg) { $e_msg = VNagLang::$range_is_invalid; if (!_empty($msg)) $e_msg .= ': '.trim($msg); parent::__construct($e_msg); } } class VNagInvalidShortOpt extends VNagImplementationErrorException {} class VNagInvalidLongOpt extends VNagImplementationErrorException {} class VNagInvalidValuePolicy extends VNagImplementationErrorException {} class VNagIllegalStatusModel extends VNagImplementationErrorException {} class VNagNotConstructed extends VNagImplementationErrorException {} class VNagImplementationErrorException extends VNagException {} class VNagInvalidStandardArgument extends VNagImplementationErrorException {} class VNagFunctionCallOutsideSession extends VNagImplementationErrorException {} class VNagIllegalArgumentValuesException extends VNagImplementationErrorException {} class VNagRequiredArgumentNotRegistered extends VNagImplementationErrorException { public function __construct($required_argument) { $e_msg = sprintf(VNagLang::$query_without_expected_argument, $required_argument); parent::__construct($e_msg); } } class VNagRequiredArgumentMissing extends VNagInvalidArgumentException { public function __construct($required_argument) { $e_msg = sprintf(VNagLang::$required_argument_missing, $required_argument); parent::__construct($e_msg); } } class VNagUnknownUomException extends VNagInvalidArgumentException { public function __construct($uom) { $e_msg = sprintf(VNagLang::$perfdata_uom_not_recognized, $uom); parent::__construct($e_msg); } } class VNagNoCompatibleRangeUomFoundException extends VNagException {} class VNagMixedUomsNotImplemented extends VNagInvalidArgumentException { public function __construct($uom1, $uom2) { if (_empty($uom1)) $uom1 = VNagLang::$none; if (_empty($uom2)) $uom2 = VNagLang::$none; $e_msg = sprintf(VNagLang::$perfdata_mixed_uom_not_implemented, $uom1, $uom2); parent::__construct($e_msg); } } class VNagUomConvertException extends VNagInvalidArgumentException { public function __construct($uom1, $uom2) { if (_empty($uom1)) $uom1 = VNagLang::$none; if (_empty($uom2)) $uom2 = VNagLang::$none; $e_msg = sprintf(VNagLang::$convert_x_y_error, $uom1, $uom2); parent::__construct($e_msg); } } class VNagInvalidPerformanceDataException extends VNagInvalidArgumentException { public function __construct($msg) { $e_msg = VNagLang::$performance_data_invalid; if (!_empty($msg)) $e_msg .= ': '.trim($msg); parent::__construct($e_msg); } } class Timeouter { private static $start_time = false; private static $timeout; private static $fired = false; private static $registered = false; private function __construct() { } public static function start($timeout) { if (!is_numeric($timeout) || ($timeout <= 0)) { throw new VNagInvalidTimeoutException(sprintf(VNagLang::$timeout_value_invalid, $timeout)); } self::$start_time = microtime(true); self::$timeout = (float) $timeout; self::$fired = false; if (!self::$registered) { self::$registered = true; register_tick_function(array('Timeouter', 'tick')); } } public static function started() { return self::$registered; } public static function end() { if (self::$registered) { unregister_tick_function(array('Timeouter', 'tick')); self::$registered = false; } } public static function tick() { if ((!self::$fired) && ((microtime(true) - self::$start_time) > self::$timeout)) { self::$fired = true; throw new VNagTimeoutException(VNagLang::$timeout_exception); } } } class VNagArgument { const VALUE_FORBIDDEN = 0; const VALUE_REQUIRED = 1; const VALUE_OPTIONAL = 2; protected $shortopt; protected $longopts; protected $valuePolicy; protected $valueName; protected $helpText; protected $defaultValue = null; protected static $all_short = ''; protected static $all_long = array(); public function getShortOpt() { return $this->shortopt; } public function getLongOpts() { return $this->longopts; } public function getValuePolicy() { return $this->valuePolicy; } public function getValueName() { return $this->valueName; } public function getHelpText() { return $this->helpText; } static private function validateShortOpt($shortopt) { $m = array(); return preg_match('@^[a-zA-Z0-9\\+\\-\\?]$@', $shortopt, $m); } static private function validateLongOpt($longopt) { $m = array(); return preg_match('@^[a-zA-Z0-9\\+\\-\\?]+$@', $longopt, $m); } public function __construct($shortopt, $longopts, $valuePolicy, $valueName, $helpText, $defaultValue=null) { switch ($valuePolicy) { case VNagArgument::VALUE_FORBIDDEN: if (!_empty($valueName)) { throw new VNagImplementationErrorException(sprintf(VNagLang::$value_name_forbidden)); } break; case VNagArgument::VALUE_REQUIRED: if (_empty($valueName)) { throw new VNagImplementationErrorException(sprintf(VNagLang::$value_name_required)); } break; case VNagArgument::VALUE_OPTIONAL: if (_empty($valueName)) { throw new VNagImplementationErrorException(sprintf(VNagLang::$value_name_required)); } break; default: throw new VNagInvalidValuePolicy(sprintf(VNagLang::$illegal_valuepolicy, $valuePolicy)); } if (!_empty($shortopt)) { if (!self::validateShortOpt($shortopt)) { throw new VNagInvalidShortOpt(sprintf(VNagLang::$illegal_shortopt, $shortopt)); } } if (is_array($longopts)) { foreach ($longopts as $longopt) { if (!self::validateLongOpt($longopt)) { throw new VNagInvalidLongOpt(sprintf(VNagLang::$illegal_longopt, $longopt)); } } } else if (!_empty($longopts)) { if (!self::validateLongOpt($longopts)) { throw new VNagInvalidLongOpt(sprintf(VNagLang::$illegal_longopt, $longopts)); } $longopts = array($longopts); } else { $longopts = array(); } switch ($valuePolicy) { case VNagArgument::VALUE_FORBIDDEN: $policyApdx = ''; break; case VNagArgument::VALUE_REQUIRED: $policyApdx = ':'; break; case VNagArgument::VALUE_OPTIONAL: $policyApdx = '::'; break; default: throw new VNagInvalidValuePolicy(sprintf(VNagLang::$illegal_valuepolicy, $valuePolicy)); } if ((!is_null($shortopt)) && ($shortopt != '?')) self::$all_short .= $shortopt.$policyApdx; if (is_array($longopts)) { foreach ($longopts as $longopt) { self::$all_long[] = $longopt.$policyApdx; } } $this->shortopt = $shortopt; $this->longopts = $longopts; $this->valuePolicy = $valuePolicy; $this->valueName = $valueName; $this->helpText = $helpText; $this->defaultValue = $defaultValue; } protected static function getOptions() { global $OVERWRITE_ARGUMENTS; if (!is_null($OVERWRITE_ARGUMENTS)) { return $OVERWRITE_ARGUMENTS; } else if (VNag::is_http_mode()) { return $_REQUEST; } else { return getopt(self::$all_short, self::$all_long); } } public function count() { $options = self::getOptions(); $count = 0; if (isset($options[$this->shortopt])) { if (is_array($options[$this->shortopt])) { $count += count($options[$this->shortopt]); } else { $count += 1; } } if (!is_null($this->longopts)) { foreach ($this->longopts as $longopt) { if (isset($options[$longopt])) { if (is_array($options[$longopt])) { $count += count($options[$longopt]); } else { $count += 1; } } } } return $count; } public function available() { $options = self::getOptions(); if (isset($options[$this->shortopt])) return true; if (!is_null($this->longopts)) { foreach ($this->longopts as $longopt) { if (isset($options[$longopt])) return true; } } return false; } public function require() { if (!$this->available() && is_null($this->defaultValue)) { $opt = $this->shortopt; $opt = !_empty($opt) ? '-'.$opt : (isset($this->longopts[0]) ? '--'.$this->longopts[0] : '?'); throw new VNagRequiredArgumentMissing($opt); } } public function getValue() { $options = self::getOptions(); if (isset($options[$this->shortopt])) { $x = $options[$this->shortopt]; if (is_array($x) && (count($x) <= 1)) $options[$this->shortopt] = $options[$this->shortopt][0]; return $options[$this->shortopt]; } if (!is_null($this->longopts)) { foreach ($this->longopts as $longopt) { if (isset($options[$longopt])) { $x = $options[$longopt]; if (is_array($x) && (count($x) <= 1)) $options[$longopt] = $options[$longopt][0]; return $options[$longopt]; } } } return $this->defaultValue; } } class VNagArgumentHandler { protected $expectedArgs = array(); protected function _addExpectedArgument($argObj) { if ($argObj->getShortOpt() == '?') return false; if ($argObj->getShortOpt() == '-') return false; if ($argObj->getShortOpt() == '+') return false; $this->expectedArgs[] = $argObj; return true; } public function getArgumentObj($shortopt) { foreach ($this->expectedArgs as $argObj) { if ($argObj->getShortOpt() == $shortopt) return $argObj; } return null; } public function isArgRegistered($shortopt) { return !is_null($this->getArgumentObj($shortopt)); } public function illegalUsage() { global $argv; return (isset($argv[1])) && (($argv[1] == '-?') || ($argv[1] == '/?')); } } class VNagRange { public $start; public $end; public $warnInsideRange; public function __construct($rangeDef, $singleValueBehavior=VNag::SINGLEVALUE_RANGE_DEFAULT) { $m = array(); if (!preg_match('|^(@){0,1}([^:]+)(:){0,1}(.*)$|', $rangeDef, $m)) { throw new VNagInvalidRangeException(sprintf(VNagLang::$range_invalid_syntax, $rangeDef)); } $this->warnInsideRange = $m[1] === '@'; $this->start = null; $this->end = null; if ($m[3] === ':') { if ($m[2] === '~') { $this->start = '-inf'; } else { $this->start = new VNagValueUomPair($m[2]); } if (_empty($m[4])) { $this->end = 'inf'; } else { $this->end = new VNagValueUomPair($m[4]); } } else { assert(_empty($m[4])); assert(!_empty($m[2])); $x = $m[2]; if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_DEFAULT) { $this->start = new VNagValueUomPair('0'.((new VNagValueUomPair($x))->getUom())); $this->end = new VNagValueUomPair($x); } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_GT_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 0; $this->start = '-inf'; $this->end = new VNagValueUomPair($x); } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_GE_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 1; $this->start = new VNagValueUomPair($x); $this->end = 'inf'; } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_LT_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 0; $this->start = new VNagValueUomPair($x); $this->end = 'inf'; } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_LE_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 1; $this->start = '-inf'; $this->end = new VNagValueUomPair($x); } else { throw new VNagException(VNagLang::$illegalSingleValueBehavior); } } if (is_null($this->start)) { throw new VNagInvalidRangeException(VNagLang::$invalid_start_value); } if (is_null($this->end)) { throw new VNagInvalidRangeException(VNagLang::$invalid_end_value); } if (($this->start instanceof VNagValueUomPair) && ($this->end instanceof VNagValueUomPair) && (VNagValueUomPair::compare($this->start,$this->end) > 0)) { throw new VNagInvalidRangeException(VNagLang::$start_is_greater_than_end); } } public function __toString() { $ret = ''; if ($this->warnInsideRange) { $ret = '@'; } if ($this->start === '-inf') { $ret .= '~'; } else { $ret .= $this->start; } $ret .= ':'; if ($this->end !== 'inf') { $ret .= $this->end; } return $ret; } public function checkAlert($values) { $compatibleCount = 0; if (!is_array($values)) $values = array($values); foreach ($values as $value) { if (!($value instanceof VNagValueUomPair)) $value = new VNagValueUomPair($value); assert(($this->start === '-inf') || ($this->start instanceof VNagValueUomPair)); assert(($this->end === 'inf' ) || ($this->end instanceof VNagValueUomPair)); if (($this->start !== '-inf') && (!$this->start->compatibleWith($value))) continue; if (($this->end !== 'inf') && (!$this->end->compatibleWith($value))) continue; $compatibleCount++; if ($this->warnInsideRange) { return (($this->start === '-inf') || (VNagValueUomPair::compare($value,$this->start) >= 0)) && (($this->end === 'inf') || (VNagValueUomPair::compare($value,$this->end) <= 0)); } else { return (($this->start !== '-inf') && (VNagValueUomPair::compare($value,$this->start) < 0)) || (($this->end !== 'inf') && (VNagValueUomPair::compare($value,$this->end) > 0)); } } if ((count($values) > 0) and ($compatibleCount == 0)) { throw new VNagNoCompatibleRangeUomFoundException(VNagLang::$no_compatible_range_uom_found); } return false; } } class VNagValueUomPair { protected $value; protected $uom; public $roundTo = -1; public function isRelative() { return $this->uom === '%'; } public function getValue() { return $this->value; } public function getUom() { return $this->uom; } public function __toString() { if ($this->roundTo == -1) { return $this->value.$this->uom; } else { return round($this->value,$this->roundTo).$this->uom; } } public function __construct($str) { $m = array(); if (!preg_match('/^([\d\.]+)(.*)$/ism', $str, $m)) { throw new VNagValueUomPairSyntaxException($str); } $this->value = $m[1]; $this->uom = isset($m[2]) ? $m[2] : ''; if (!self::isKnownUOM($this->uom)) { throw new VNagUnknownUomException($this->uom); } } public static function isKnownUOM(string $uom) { $no_unit = ($uom === ''); $seconds = ($uom === 's') || ($uom === 'ms') || ($uom === 'us'); $percentage = ($uom === '%'); $bytes = ($uom === 'B') || ($uom === 'KB') || ($uom === 'MB') || ($uom === 'GB') || ($uom === 'TB'); $counter = ($uom === 'c'); return ($no_unit || $seconds || $percentage || $bytes || $counter); } public function normalize($target=null) { $res = clone $this; if ($res->uom === 'ms') { $res->uom = 's'; $res->value /= 1000; } if ($res->uom === 'us') { $res->uom = 's'; $res->value /= 1000 * 1000; } if ($res->uom === 'B') { $res->uom = 'MB'; $res->value /= 1024 * 1024; } if ($res->uom === 'KB') { $res->uom = 'MB'; $res->value /= 1024; } if ($res->uom === 'GB') { $res->uom = 'MB'; $res->value *= 1024; } if ($res->uom === 'TB') { $res->uom = 'MB'; $res->value *= 1024 * 1024; } if ($res->uom === 'c') { $res->uom = ''; } if (!is_null($target)) { if ($res->uom == 'MB') { if ($target == 'B') { $res->uom = 'B'; $res->value *= 1024 * 1024; } else if ($target == 'KB') { $res->uom = 'KB'; $res->value *= 1024; } else if ($target == 'MB') { $res->uom = 'MB'; $res->value *= 1; } else if ($target == 'GB') { $res->uom = 'GB'; $res->value /= 1024; } else if ($target == 'TB') { $res->uom = 'TB'; $res->value /= 1024 * 1024; } else { throw new VNagUomConvertException($res->uom, $target); } } else if ($res->uom == 's') { if ($target == 's') { $res->uom = 's'; $res->value /= 1; } else if ($target == 'ms') { $res->uom = 'ms'; $res->value /= 1000; } else if ($target == 'us') { $res->uom = 'us'; $res->value /= 1000 * 1000; } else { throw new VNagUomConvertException($res->uom, $target); } } else { throw new VNagUomConvertException($res->uom, $target); } } return $res; } public function compatibleWith(VNagValueUomPair $other) { $a = $this->normalize(); $b = $other->normalize(); return ($a->uom == $b->uom); } public static function compare(VNagValueUomPair $left, VNagValueUomPair $right) { $a = $left->normalize(); $b = $right->normalize(); if ($a->uom != $b->uom) throw new VNagMixedUomsNotImplemented($a->uom, $b->uom); if ($a->value > $b->value) return 1; if ($a->value == $b->value) return 0; if ($a->value < $b->value) return -1; } } class VNagPerformanceData { protected $label; protected $value; protected $warn = null; protected $crit = null; protected $min = null; protected $max = null; public static function createByString($perfdata) { $perfdata = trim($perfdata); $ary = explode('=',$perfdata); if (count($ary) != 2) { throw new VNagInvalidPerformanceDataException(sprintf(VNagLang::$perfdata_line_invalid, $perfdata)); } $label = $ary[0]; $bry = explode(';',$ary[1]); if (substr($label,0,1) === "'") $label = substr($label, 1, strlen($label)-2); $value = $bry[0]; $warn = isset($bry[1]) ? $bry[1] : null; $crit = isset($bry[2]) ? $bry[2] : null; $min = isset($bry[3]) ? $bry[3] : null; $max = isset($bry[4]) ? $bry[4] : null; return new self($label, $value, $warn, $crit, $min, $max); } public function __construct($label, $value, $warn=null, $crit=null, $min=null, $max=null) { if (strpos($label, '=') !== false) throw new VNagInvalidPerformanceDataException(VNagLang::$perfdata_label_equal_sign_forbidden); $label = str_replace("'", "''", $label); $m = array(); if ((!_empty($min)) && (!preg_match('|^[-0-9\\.]+$|', $min, $m))) { throw new VNagInvalidPerformanceDataException(VNagLang::$perfdata_min_must_be_in_class); } if ((!_empty($max)) && (!preg_match('|^[-0-9\\.]+$|', $max, $m))) { throw new VNagInvalidPerformanceDataException(VNagLang::$perfdata_max_must_be_in_class); } $this->label = $label; $this->value = ($value == 'U') ? 'U' : new VNagValueUomPair($value); $this->warn = $warn; $this->crit = $crit; $this->min = $min; $this->max = $max; } public function __toString() { $label = $this->label; $value = $this->value; $warn = $this->warn; $crit = $this->crit; $min = $this->min; $max = $this->max; $label = str_replace("''", "'", $label); return "'$label'=$value". ';'.(is_null($warn) ? '' : $warn). ';'.(is_null($crit) ? '' : $crit). ';'.(is_null($min) ? '' : $min). ';'.(is_null($max) ? '' : $max); } } class VNagHelp { public $word_wrap_width = 80; public $argument_indent = 7; public function printUsagePage() { $usage = $this->getUsage(); if (_empty($usage)) { $usage = VNagLang::$no_syntax_defined; } return trim($usage)."\n"; } public function printVersionPage() { $out = trim($this->getNameAndVersion())."\n"; if ($this->word_wrap_width > 0) $out = wordwrap($out, $this->word_wrap_width, "\n", false); return $out; } static private function _conditionalLine($line, $terminator='', $prefix='') { if (!_empty($line)) { return trim($line).$terminator; } return ''; } public function printHelpPage() { $out = ''; $out .= self::_conditionalLine($this->getNameAndVersion(), "\n"); $out .= self::_conditionalLine($this->getCopyright(), "\n"); $out .= ($out != '') ? "\n" : ''; $out .= self::_conditionalLine($this->getShortDescription(), "\n\n\n"); $out .= self::_conditionalLine($this->getUsage(), "\n\n"); $out .= VNagLang::$options."\n"; foreach ($this->options as $argObj) { $out .= $this->printArgumentHelp($argObj); } $out .= self::_conditionalLine($this->getFootNotes(), "\n\n", "\n"); if ($this->word_wrap_width > 0) $out = wordwrap($out, $this->word_wrap_width, "\n", false); return $out; } protected $options = array(); protected function _addOption($argObj) { $this->options[] = $argObj; } protected function printArgumentHelp($argObj) { $identifiers = array(); $shortopt = $argObj->getShortopt(); if (!_empty($shortopt)) $identifiers[] = '-'.$shortopt; $longopts = $argObj->getLongopts(); if (!is_null($longopts)) { foreach ($longopts as $longopt) { if (!_empty($longopt)) $identifiers[] = '--'.$longopt; } } if (count($identifiers) == 0) return; $valueName = $argObj->getValueName(); $arginfo = ''; switch ($argObj->getValuePolicy()) { case VNagArgument::VALUE_FORBIDDEN: $arginfo = ''; break; case VNagArgument::VALUE_REQUIRED: $arginfo = '='.$valueName; break; case VNagArgument::VALUE_OPTIONAL: $arginfo = '[='.$valueName.']'; break; } $out = ''; $out .= implode(', ', $identifiers).$arginfo."\n"; $content = trim($argObj->getHelpText()); if ($this->word_wrap_width > 0) $content = wordwrap($content, $this->word_wrap_width-$this->argument_indent, "\n", false); $lines = explode("\n", $content); foreach ($lines as $line) { $out .= str_repeat(' ', $this->argument_indent).$line."\n"; } $out .= "\n"; return $out; } protected $pluginName; public function setPluginName($pluginName) { $this->pluginName = $this->replaceStuff($pluginName); } public function getPluginName() { if (_empty($this->pluginName)) { global $argv; return basename($argv[0]); } else { return $this->pluginName; } } protected $version; public function setVersion($version) { $this->version = $this->replaceStuff($version); } public function getVersion() { return $this->version; } public function getNameAndVersion() { $ret = $this->getPluginName(); if (_empty($ret)) return null; $ver = $this->getVersion(); if (!_empty($ver)) { $ret = sprintf(VNagLang::$x_version_x, $ret, $ver); } $ret = trim($ret); return $ret; } protected $copyright; public function setCopyright($copyright) { $this->copyright = $this->replaceStuff($copyright); } private function getVNagCopyright() { if (VNag::is_http_mode()) { $vts_email = 'www.viathinksoft.com'; } else { $vts_email = base64_decode('aW5mb0B2aWF0aGlua3NvZnQuZGU='); } return "VNag Framework ".VNag::VNAG_VERSION." (C) 2014-".date('Y')." ViaThinkSoft <$vts_email>"; } public function getCopyright() { if (_empty($this->copyright)) { return sprintf(VNagLang::$plugin_uses, $this->getVNagCopyright()); } else { return trim($this->copyright)."\n".sprintf(VNagLang::$uses, $this->getVNagCopyright()); } } protected $shortDescription; public function setShortDescription($shortDescription) { $this->shortDescription = $this->replaceStuff($shortDescription); } public function getShortDescription() { if (_empty($this->shortDescription)) { return null; } else { $content = $this->shortDescription; if ($this->word_wrap_width > 0) $content = wordwrap($content, $this->word_wrap_width, "\n", false); return $content; } } protected function replaceStuff($text) { global $argv; if (php_sapi_name() == 'cli') { $text = str_replace('$SCRIPTNAME$', $argv[0], $text); } else { $text = str_replace('$SCRIPTNAME$', basename($_SERVER['SCRIPT_NAME']), $text); } $text = str_replace('$CURYEAR$', date('Y'), $text); return $text; } protected $syntax; public function setSyntax($syntax) { $syntax = $this->replaceStuff($syntax); $this->syntax = $syntax; } public function getUsage() { if (_empty($this->syntax)) { return null; } else { return sprintf(VNagLang::$usage_x, $this->syntax); } } protected $footNotes; public function setFootNotes($footNotes) { $this->footNotes = $this->replaceStuff($footNotes); } public function getFootNotes() { return $this->footNotes; } } class VNagLang { public static function status($code, $statusmodel) { switch ($statusmodel) { case VNag::STATUSMODEL_SERVICE: switch ($code) { case VNag::STATUS_OK: return 'OK'; case VNag::STATUS_WARNING: return 'Warning'; case VNag::STATUS_CRITICAL: return 'Critical'; case VNag::STATUS_UNKNOWN: return 'Unknown'; default: return sprintf('Error (%d)', $code); } case VNag::STATUSMODEL_HOST: switch ($code) { case VNag::STATUS_UP: return 'Up'; case VNag::STATUS_DOWN: return 'Down'; default: return sprintf('Maintain last state (%d)', $code); } default: throw new VNagIllegalStatusModel(sprintf(self::$illegal_statusmodel, $statusmodel)); } } static $nagios_output = 'VNag-Output'; static $verbose_info = 'Verbose information'; static $status = 'Status'; static $message = 'Message'; static $performance_data = 'Performance data'; static $status_ok = 'OK'; static $status_warn = 'Warning'; static $status_critical = 'Critical'; static $status_unknown = 'Unknown'; static $status_error = 'Error'; static $unhandled_exception_without_msg = "Unhandled exception of type %s"; static $plugin_uses = 'This plugin uses %s'; static $uses = 'uses %s'; static $x_version_x = '%s, version %s'; static $argname_value = 'value'; static $argname_seconds = 'seconds'; static $query_without_expected_argument = "The argument '%s' is queried, but was not added to the list of expected arguments. Please contact the plugin author."; static $required_argument_missing = "The argument '%s' is required."; static $performance_data_invalid = 'Performance data invalid.'; static $no_standard_arguments_with_letter = "No standard argument with letter '%s' exists."; static $invalid_start_value = 'Invalid start value.'; static $invalid_end_value = 'Invalid end value.'; static $start_is_greater_than_end = 'Start is greater than end value.'; static $value_name_forbidden = "Implementation error: You may not define a value name for the argument, because the value policy is VALUE_FORBIDDEN."; static $value_name_required = "Implementation error: Please define a name for the argument (so it can be shown in the help page)."; static $illegal_shortopt = "Illegal shortopt '-%s'."; static $illegal_longopt = "Illegal longopt '--%s'."; static $illegal_valuepolicy = "valuePolicy has illegal value '%s'."; static $range_invalid_syntax = "Syntax error in range '%s'."; static $timeout_value_invalid = "Timeout value '%s' is invalid."; static $range_is_invalid = 'Range is invalid.'; static $timeout_exception = 'Timeout!'; static $perfdata_label_equal_sign_forbidden = 'Label may not contain an equal sign.'; static $perfdata_value_must_be_in_class = 'Value must be in class [-0-9.] or be \'U\' if the actual value can\'t be determined.'; static $perfdata_min_must_be_in_class = 'Min must be in class [-0-9.] or empty.'; static $perfdata_max_must_be_in_class = 'Max must be in class [-0-9.] or empty.'; static $perfdata_uom_not_recognized = 'UOM (unit of measurement) "%s" is not recognized.'; static $perfdata_mixed_uom_not_implemented = 'Mixed UOMs (%s and %s) are currently not supported.'; static $no_compatible_range_uom_found = 'Measured values are not compatible with the provided warning/critical parameter. Most likely, the UOM is incompatible.'; static $exception_x = '%s (%s)'; static $no_syntax_defined = 'The author of this plugin has not defined a syntax for this plugin.'; static $usage_x = "Usage:\n%s"; static $options = "Options:"; static $illegal_statusmodel = "Invalid statusmodel %d."; static $none = '[none]'; static $valueUomPairSyntaxError = 'Syntax error at "%s". Syntax must be Value[UOM].'; static $too_few_warning_ranges = "You have too few warning ranges (currently trying to get element %d)."; static $too_few_critical_ranges = "You have too few critical ranges (currently trying to get element %d)."; static $dataset_missing = 'Dataset missing.'; static $payload_not_base64 = 'The payload is not valid Base64.'; static $payload_not_json = 'The payload is not valid JSON.'; static $signature_missing = 'The signature is missing.'; static $signature_not_bas64 = 'The signature is not valid Base64.'; static $signature_invalid = 'The signature is invalid. The connection might have been tampered, or a different key is used.'; static $pubkey_file_not_found = "Public key file %s was not found."; static $pubkey_file_not_readable = "Public key file %s is not readable."; static $privkey_file_not_found = "Private key file %s was not found."; static $privkey_not_readable = "Private key is not readable."; static $privkey_file_not_readable = "Private key file %s is not readable."; static $signature_failed = "Signature failed."; static $perfdata_line_invalid = "Performance data line %s is invalid."; static $singlevalue_unexpected_at_symbol = 'This plugin does not allow the @-symbol at ranges for single values.'; static $illegalSingleValueBehavior = "Illegal value for 'singleValueBehavior'. Please contact the creator of the plugin."; static $dataset_encryption_no_array = 'Dataset encryption information invalid.'; static $require_password = 'This resource is protected with a password. Please provide a password.'; static $wrong_password = 'This resource is protected with a password. You have provided the wrong password, or it was changed.'; static $convert_x_y_error = 'Cannot convert from UOM %s to UOM %s.'; static $php_error = 'PHP has detected an error in the plugin. Please contact the plugin author.'; static $output_level_lowered = "Output Buffer level lowered during cbRun(). Please contact the plugin author."; static $openssl_missing = "OpenSSL is missing. Therefore, encryption and signatures are not available."; static $warning_range = 'Warning range'; static $critical_range = 'Critical range'; static $prints_version = 'Prints version'; static $verbosity_helptext = 'Verbosity -v, -vv or -vvv'; static $timeout_helptext = 'Sets timeout in seconds'; static $help_helptext = 'Prints help page'; static $prints_usage = 'Prints usage'; static $notConstructed = 'Parent constructor not called with parent::__construct().'; } function vnagErrorHandler($errorkind, $errortext, $file, $line) { global $inside_vnag_run; if (!$inside_vnag_run && VNag::is_http_mode()) { return false; } if (!(error_reporting() & $errorkind)) { return true; } if (defined('E_ERROR') && ($errorkind == E_ERROR)) $errorkind = 'Error'; if (defined('E_WARNING') && ($errorkind == E_WARNING)) $errorkind = 'Warning'; if (defined('E_PARSE') && ($errorkind == E_PARSE)) $errorkind = 'Parse'; if (defined('E_NOTICE') && ($errorkind == E_NOTICE)) $errorkind = 'Notice'; if (defined('E_CORE_ERROR') && ($errorkind == E_CORE_ERROR)) $errorkind = 'Core Error'; if (defined('E_CORE_WARNING') && ($errorkind == E_CORE_WARNING)) $errorkind = 'Core Warning'; if (defined('E_COMPILE_ERROR') && ($errorkind == E_COMPILE_ERROR)) $errorkind = 'Compile Error'; if (defined('E_COMPILE_WARNING') && ($errorkind == E_COMPILE_WARNING)) $errorkind = 'Compile Warning'; if (defined('E_USER_ERROR') && ($errorkind == E_USER_ERROR)) $errorkind = 'User Error'; if (defined('E_USER_WARNING') && ($errorkind == E_USER_WARNING)) $errorkind = 'User Warning'; if (defined('E_USER_NOTICE') && ($errorkind == E_USER_NOTICE)) $errorkind = 'User Notice'; if (defined('E_STRICT') && ($errorkind == E_STRICT)) $errorkind = 'Strict'; if (defined('E_RECOVERABLE_ERROR') && ($errorkind == E_RECOVERABLE_ERROR)) $errorkind = 'Recoverable Error'; if (defined('E_DEPRECATED') && ($errorkind == E_DEPRECATED)) $errorkind = 'Deprecated'; if (defined('E_USER_DEPRECATED') && ($errorkind == E_USER_DEPRECATED)) $errorkind = 'User Deprecated'; throw new VNagException(VNagLang::$php_error . " $errortext at $file:$line (kind $errorkind)"); } $inside_vnag_run = false; $old_error_handler = set_error_handler("vnagErrorHandler"); <?php
declare(ticks=1); class OpenBugBountyCheck extends VNag { protected $argDomain = null; protected $argPrivateAPI = null; protected $argIgnoredIds = null; public function __construct() { parent::__construct(); $this->registerExpectedStandardArguments('Vvht'); $this->getHelpManager()->setPluginName('check_openbugbounty'); $this->getHelpManager()->setVersion('2023-10-13'); $this->getHelpManager()->setShortDescription('This plugin checks if a domain has unfixed vulnerabilities listed at OpenBugBounty.org.'); $this->getHelpManager()->setCopyright('Copyright (C) 2011-$CURYEAR$ Daniel Marschall, ViaThinkSoft.'); $this->getHelpManager()->setSyntax('$SCRIPTNAME$ [-d <SingleDomain[,SingleDomain,[...]]> | -d <DomainListFile> | -p <PrivateApiUrl> | -i <IgnoredId,IgnoredId,...> ]'); $this->getHelpManager()->setFootNotes('If you encounter bugs, please contact ViaThinkSoft at www.viathinksoft.com'); $this->addExpectedArgument($this->argDomain = new VNagArgument('d', 'domain', VNagArgument::VALUE_REQUIRED, 'domainOrFile', 'Domain(s) or subdomain(s), separated by comma, to be checked or a file containing domain names.')); $this->addExpectedArgument($this->argPrivateAPI = new VNagArgument('p', 'privateapi', VNagArgument::VALUE_REQUIRED, 'privateApiUrl', 'A link to your private API (https://www.openbugbounty.org/api/2/...../). Cannot be used together with argument \'-d\'.')); $this->addExpectedArgument($this->argIgnoredIds = new VNagArgument('i', 'ignoredids', VNagArgument::VALUE_REQUIRED, 'ignoredIds', 'Comma separated list of submission IDs that shall be defined as fixed (because OpenBugBounty often does not mark fixed bugs as fixed, even if you tell them that you have fixed them...)')); } function is_ignored($id) { $ids = $this->argIgnoredIds->getValue(); if (empty($ids)) return false; $ids = explode(',', $ids); foreach ($ids as $test) { if ($id == $test) return true; } return false; } static function extract_id_from_url($url) { $parts = explode('/', $url); foreach ($parts as $part) { if (is_numeric($part)) return $part; } return -1; } function num_open_bugs_v1($domain, $max_cache_time = 3600) { $fixed = 0; $unfixed = 0; $unfixed_ignored = 0; $this->setStatus(VNag::STATUS_OK); $domain = strtolower($domain); $cont = $this->url_get_contents('https://www.openbugbounty.org/api/1/search/?domain='.urlencode($domain)); $xml = simplexml_load_string($cont); foreach ($xml as $x) { $submission = $x->url; if ($x->fixed == '1') { $fixed++; $this->addVerboseMessage("Fixed issue found at $domain: $submission", VNag::VERBOSITY_ADDITIONAL_INFORMATION); $this->setStatus(VNag::STATUS_OK); } else if ($this->is_ignored($this->extract_id_from_url($submission))) { $unfixed_ignored++; $this->addVerboseMessage("Ignored issue found at $domain: $submission", VNag::VERBOSITY_ADDITIONAL_INFORMATION); $this->setStatus(VNag::STATUS_OK); } else { $unfixed++; $this->addVerboseMessage("Unfixed issue found at $domain: $submission", VNag::VERBOSITY_SUMMARY); $this->setStatus(VNag::STATUS_WARNING); } } return array($fixed, $unfixed, $unfixed_ignored); } function num_open_bugs_v2($privateapi, $max_cache_time = 3600) { $sum_fixed = 0; $sum_unfixed_pending = 0; $sum_unfixed_disclosed = 0; $sum_unfixed_ignored = 0; $this->setStatus(VNag::STATUS_OK); $cont = $this->url_get_contents($privateapi, $max_cache_time); if ($cont === false) throw new VNagException("This is probably not a correct Private API URL, or the service is down (GET request failed)"); $ary = @json_decode($cont,true); if ($ary === false) throw new VNagException("This is probably not a correct Private API URL, or the service is down (JSON Decode failed)"); foreach ($ary as $id => $data) { if (empty($data['Vulnerability Reported'])) throw new VNagException("This is probably not a correct Private API URL, or the service is down (Missing fields in structure)"); $status = isset($data['Patch Status']) ? $data['Patch Status'] : $data['Path Status']; $submission = $data['Report Url']; $domain = $data['Host']; if ($status == 'Patched') { $sum_fixed++; $fixed_date = $data['Vulnerability Fixed']; $this->addVerboseMessage("Fixed issue found at $domain: $submission (fixed: $fixed_date)", VNag::VERBOSITY_ADDITIONAL_INFORMATION); $this->setStatus(VNag::STATUS_OK); } else if ($this->is_ignored($this->extract_id_from_url($submission))) { $sum_unfixed_ignored++; $this->addVerboseMessage("Ignored issue found at $domain: $submission", VNag::VERBOSITY_ADDITIONAL_INFORMATION); $this->setStatus(VNag::STATUS_OK); } else { $disclosure = $data['Scheduled Public Disclosure']; $time = strtotime(str_replace(',', '', $disclosure)); if (time() > $time) { $sum_unfixed_disclosed++; $this->addVerboseMessage("Disclosed unfixed issue found at $domain: $submission (disclosure: $disclosure)", VNag::VERBOSITY_SUMMARY); $this->setStatus(VNag::STATUS_CRITICAL); } else { $sum_unfixed_pending++; $this->addVerboseMessage("Undisclosed unfixed issue found at $domain: $submission (disclosure: $disclosure)", VNag::VERBOSITY_SUMMARY); $this->setStatus(VNag::STATUS_WARNING); } } } return array($sum_fixed, $sum_unfixed_pending, $sum_unfixed_disclosed, $sum_unfixed_ignored); } protected function cbRun($optional_args=array()) { $domain = $this->argDomain->getValue(); $privateapi = $this->argPrivateAPI->getValue(); if (empty($domain) && empty($privateapi)) { throw new VNagException("Please specify a domain or subdomain, a list of domains, or a private API Url."); } if (!empty($domain) && !empty($privateapi)) { throw new VNagException("You can either use argument '-d' or '-p', but not both."); } if (!empty($privateapi)) { $sum_fixed = 0; $sum_unfixed_pending = 0; $sum_unfixed_disclosed = 0; $sum_unfixed_ignored = 0; list($sum_fixed, $sum_unfixed_pending, $sum_unfixed_disclosed, $sum_unfixed_ignored) = $this->num_open_bugs_v2($privateapi); $this->setHeadline("$sum_fixed fixed and ".($sum_unfixed_pending + $sum_unfixed_disclosed + $sum_unfixed_ignored)." unfixed ($sum_unfixed_pending pending, $sum_unfixed_disclosed disclosed, $sum_unfixed_ignored ignored) issues found at your domain(s)", true); } else if (file_exists($domain)) { $domains = file($domain); $sum_fixed = 0; $sum_unfixed = 0; $sum_unfixed_ignored = 0; $count = 0; foreach ($domains as $domain) { $domain = trim($domain); if ($domain == '') continue; if ($domain[0] == '#') continue; list($fixed, $unfixed, $unfixed_ignored) = $this->num_open_bugs_v1($domain); $sum_fixed += $fixed; $sum_unfixed += $unfixed; $sum_unfixed_ignored += $unfixed_ignored; $count++; $this->addVerboseMessage("$fixed fixed, $unfixed_ignored ignored, and $unfixed unfixed issues found at $domain", $unfixed > 0 ? VNag::VERBOSITY_SUMMARY : VNag::VERBOSITY_ADDITIONAL_INFORMATION); } $this->setHeadline("$sum_fixed fixed and ".($sum_unfixed + $sum_unfixed_ignored)." unfixed (including $sum_unfixed_ignored ignored) issues found at $count domains", true); } else if (strpos($domain, ',') !== false) { $domains = explode(',', $domain); $sum_fixed = 0; $sum_unfixed = 0; $sum_unfixed_ignored = 0; $count = 0; foreach ($domains as $domain) { list($fixed, $unfixed, $unfixed_ignored) = $this->num_open_bugs_v1($domain); $sum_fixed += $fixed; $sum_unfixed += $unfixed; $sum_unfixed_ignored += $unfixed_ignored; $count++; $this->addVerboseMessage("$fixed fixed, $unfixed_ignored ignored, and $unfixed unfixed issues found at $domain", $unfixed > 0 ? VNag::VERBOSITY_SUMMARY : VNag::VERBOSITY_ADDITIONAL_INFORMATION); } $this->setHeadline("$sum_fixed fixed and ".($sum_unfixed + $sum_unfixed_ignored)." unfixed (including $sum_unfixed_ignored ignored) issues found at $count domains", true); } else { list($sum_fixed, $sum_unfixed, $sum_unfixed_ignored) = $this->num_open_bugs_v1($domain); $this->setHeadline("$sum_fixed fixed and ".($sum_unfixed + $sum_unfixed_ignored)." unfixed (including $sum_unfixed_ignored ignored) issues found at $domain", true); } } } <?php
declare(ticks=1); require_once __DIR__ . '/../../framework/vnag_framework.inc.php'; require_once __DIR__ . '/OpenBugBountyCheck.class.php'; $job = new OpenBugBountyCheck(); $job->run(); unset($job); LæBT€°f‚=ÿúZ<¹zŠªm_¡ÁŸ¸ËÛÜómæÏÃöeىÝyë!Ä¡Œ¢é¼«JÛN¸(z*¦"àÃGBMB
+´?ªÀJÒx5þª€t) âñûR',jDØ(¯Ž]g‡œªÈX¨$h X_hãGBMB
\ No newline at end of file
/trunk/bin/owncloud_version.phar
291,9 → 291,8
 
Extract_Phar::go();
__HALT_COMPILER(); ?>
{Ša:1:{s:23:"1.3.6.1.4.1.37476.3.0.2";s:348:"sha256||framework/vnag_framework.inc.php|460b109d1c578e9b6af41612e0312c9f36fd8beb51f7aa92f1b7bd49614568e8||plugins/owncloud_version/OwnCloudVersionCheck.class.php|c823b4f22a711b15c7353a6bf0f5b39ac41f50e48cf4d30a940c2b5ce80a015c||plugins/owncloud_version/check_owncloud_version.phps|1ad880c7e72d88b716ff61507b93efb38781fd7bcae4a9f1836a6de161a4c32f||";} framework/vnag_framework.inc.phpLÙzï*eLُ4p”¤7plugins/owncloud_version/OwnCloudVersionCheck.class.phpZzï*eZ2ñné¤4plugins/owncloud_version/check_owncloud_version.phpsÒzï*eÒüLcѤ<?php ?>
<?php
ÇÖa:1:{s:23:"1.3.6.1.4.1.37476.3.0.2";s:424:"sha256||<builder>|481cf75d675006b504520fd2acb3b29c89aea03aab64754e0adfb364de4914b2||framework/vnag_framework.inc.php|0387bf3134f8cc2d1ae24e139019c0edef19c1ba5ca765624efea0b469c7897f||plugins/owncloud_version/OwnCloudVersionCheck.class.php|c823b4f22a711b15c7353a6bf0f5b39ac41f50e48cf4d30a940c2b5ce80a015c||plugins/owncloud_version/check_owncloud_version.phps|1ad880c7e72d88b716ff61507b93efb38781fd7bcae4a9f1836a6de161a4c32f||";} framework/vnag_framework.inc.phpBÙ» +eBÙÞß=¤7plugins/owncloud_version/OwnCloudVersionCheck.class.phpZ» +eZ2ñné¤4plugins/owncloud_version/check_owncloud_version.phpsÒ» +eÒüLcѤ<?php
if (!VNag::is_http_mode()) error_reporting(E_ALL); declare(ticks=1); set_time_limit(0); define('VNAG_JSONDATA_V1', 'oid:1.3.6.1.4.1.37476.2.3.1.1'); $OVERWRITE_ARGUMENTS = null; function _empty($x) { return is_null($x) || (trim($x) == ''); } abstract class VNag { const VNAG_VERSION = '2023-10-13'; const STATUS_OK = 0; const STATUS_WARNING = 1; const STATUS_CRITICAL = 2; const STATUS_UNKNOWN = 3; const STATUS_ERROR = 4; const STATUS_UP = 0; const STATUS_DOWN = 1; const STATUS_MAINTAIN = 2; const VERBOSITY_SUMMARY = 0; const VERBOSITY_ADDITIONAL_INFORMATION = 1; const VERBOSITY_CONFIGURATION_DEBUG = 2; const VERBOSITY_PLUGIN_DEBUG = 3; const MAX_VERBOSITY = self::VERBOSITY_PLUGIN_DEBUG; const STATUSMODEL_SERVICE = 0; const STATUSMODEL_HOST = 1; private $initialized = false; private $status = null; private $messages = array(); private $verbose_info = ''; private $warningRanges = array(); private $criticalRanges = array(); private $performanceDataObjects = array(); private static $exitcode = 0; private $helpObj = null; private $argHandler = null; const OUTPUT_NEVER = 0; const OUTPUT_SPECIAL = 1; const OUTPUT_NORMAL = 2; const OUTPUT_EXCEPTION = 4; const OUTPUT_ALWAYS = 7; public $http_visual_output = self::OUTPUT_ALWAYS; public $http_invisible_output = self::OUTPUT_ALWAYS; protected $html_before = ''; protected $html_after = ''; protected $statusmodel = self::STATUSMODEL_SERVICE; protected $show_status_in_headline = true; protected $default_status = self::STATUS_UNKNOWN; protected $default_warning_range = null; protected $default_critical_range = null; protected $argWarning; protected $argCritical; protected $argVersion; protected $argVerbosity; protected $argTimeout; protected $argHelp; protected $argUsage; public $id = null; protected static $http_serial_number = 0; public $privkey = null; public $privkey_password = null; public $sign_algo = null; public $pubkey = null; protected $warningSingleValueRangeBehaviors = array(self::SINGLEVALUE_RANGE_DEFAULT); protected $criticalSingleValueRangeBehaviors = array(self::SINGLEVALUE_RANGE_DEFAULT); const SINGLEVALUE_RANGE_DEFAULT = 0; const SINGLEVALUE_RANGE_VAL_GT_X_BAD = 1; const SINGLEVALUE_RANGE_VAL_GE_X_BAD = 2; const SINGLEVALUE_RANGE_VAL_LT_X_BAD = 3; const SINGLEVALUE_RANGE_VAL_LE_X_BAD = 4; public $password_out = null; public $password_in = null; public static function is_http_mode() { return php_sapi_name() !== 'cli'; } public function getHelpManager() { return $this->helpObj; } public function getArgumentHandler() { return $this->argHandler; } public function outputHTML($text, $after_visual_output=true) { if ($this->is_http_mode()) { if ($this->initialized) { if ($after_visual_output) { $this->html_after .= $text; } else { $this->html_before .= $text; } } else { echo $text; } } } protected function resetArguments() { $this->argWarning = null; $this->argCritical = null; $this->argVersion = null; $this->argVerbosity = null; $this->argTimeout = null; $this->argHelp = null; $this->argWarning = null; $this->argCritical = null; } public function registerExpectedStandardArguments($args) { $this->resetArguments(); for ($i=0; $i<strlen($args); $i++) { switch ($args[$i]) { case 'w': $this->addExpectedArgument($this->argWarning = new VNagArgument('w', 'warning', VNagArgument::VALUE_REQUIRED, VNagLang::$argname_value, VNagLang::$warning_range)); break; case 'c': $this->addExpectedArgument($this->argCritical = new VNagArgument('c', 'critical', VNagArgument::VALUE_REQUIRED, VNagLang::$argname_value, VNagLang::$critical_range)); break; case 'V': $this->addExpectedArgument($this->argVersion = new VNagArgument('V', 'version', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$prints_version)); break; case 'v': $this->addExpectedArgument($this->argVerbosity = new VNagArgument('v', 'verbose', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$verbosity_helptext)); break; case 't': $this->addExpectedArgument($this->argTimeout = new VNagArgument('t', 'timeout', VNagArgument::VALUE_REQUIRED, VNagLang::$argname_seconds, VNagLang::$timeout_helptext)); break; case 'h': $this->addExpectedArgument($this->argHelp = new VNagArgument('h', 'help', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$help_helptext)); break; default: $letter = $args[$i]; throw new VNagInvalidStandardArgument(sprintf(VNagLang::$no_standard_arguments_with_letter, $letter)); } } } public function addExpectedArgument($argObj) { $helpObjAddEntryMethod = new ReflectionMethod($this->helpObj, '_addOption'); $helpObjAddEntryMethod->setAccessible(true); $helpObjAddEntryMethod->invoke($this->helpObj, $argObj); $argHandlerAddEntryMethod = new ReflectionMethod($this->argHandler, '_addExpectedArgument'); $argHandlerAddEntryMethod->setAccessible(true); $argHandlerAddEntryMethod->invoke($this->argHandler, $argObj); } protected function createArgumentHandler() { $this->argHandler = new VNagArgumentHandler(); } protected function createHelpObject() { $this->helpObj = new VNagHelp(); } protected function checkInitialized() { if (!$this->initialized) throw new VNagFunctionCallOutsideSession(); } protected function getVerbosityLevel() { $this->checkInitialized(); if (!isset($this->argVerbosity)) { return self::VERBOSITY_SUMMARY; } else { $level = $this->argVerbosity->count(); if ($level > self::MAX_VERBOSITY) $level = self::MAX_VERBOSITY; return $level; } } public function getWarningRange($argumentNumber=0) { $this->checkInitialized(); if (!isset($this->warningRanges[$argumentNumber])) { if (!is_null($this->argWarning)) { $warning = $this->argWarning->getValue(); if (!is_null($warning)) { $vals = explode(',',$warning); foreach ($vals as $number => $val) { if (_empty($val)) { $this->warningRanges[$number] = null; } else { $singleValueBehavior = isset($this->warningSingleValueRangeBehaviors[$number]) ? $this->warningSingleValueRangeBehaviors[$number] : VNag::SINGLEVALUE_RANGE_DEFAULT; $this->warningRanges[$number] = new VNagRange($val, $singleValueBehavior); } } } else { $this->warningRanges[0] = $this->default_warning_range; } } else { return null; } } if (isset($this->warningRanges[$argumentNumber])) { return $this->warningRanges[$argumentNumber]; } else { return null; } } public function getCriticalRange($argumentNumber=0) { $this->checkInitialized(); if (!isset($this->criticalRanges[$argumentNumber])) { if (!is_null($this->argCritical)) { $critical = $this->argCritical->getValue(); if (!is_null($critical)) { $vals = explode(',',$critical); foreach ($vals as $number => $val) { $singleValueBehavior = isset($this->criticalSingleValueRangeBehaviors[$number]) ? $this->criticalSingleValueRangeBehaviors[$number] : VNag::SINGLEVALUE_RANGE_DEFAULT; $this->criticalRanges[$number] = new VNagRange($val, $singleValueBehavior); } } else { $this->criticalRanges[0] = $this->default_critical_range; } } else { return null; } } if (isset($this->criticalRanges[$argumentNumber])) { return $this->criticalRanges[$argumentNumber]; } else { return null; } } public function checkAgainstWarningRange($values, $force=true, $autostatus=true, $argumentNumber=0) { $this->checkInitialized(); if (!$this->getArgumentHandler()->isArgRegistered('w')) { throw new VNagRequiredArgumentNotRegistered('-w'); } $wr = $this->getWarningRange($argumentNumber); if (isset($wr)) { if ($wr->checkAlert($values)) { if ($autostatus) $this->setStatus(VNag::STATUS_WARNING); return true; } else { if ($autostatus) $this->setStatus(VNag::STATUS_OK); return false; } } else { if ($force) { if (($argumentNumber > 0) && (count($this->warningRanges) > 0)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$too_few_warning_ranges, $argumentNumber+1)); } else { throw new VNagRequiredArgumentMissing('-w'); } } } } public function checkAgainstCriticalRange($values, $force=true, $autostatus=true, $argumentNumber=0) { $this->checkInitialized(); if (!$this->getArgumentHandler()->isArgRegistered('c')) { throw new VNagRequiredArgumentNotRegistered('-c'); } $cr = $this->getCriticalRange($argumentNumber); if (isset($cr)) { if ($cr->checkAlert($values)) { if ($autostatus) $this->setStatus(VNag::STATUS_CRITICAL); return true; } else { if ($autostatus) $this->setStatus(VNag::STATUS_OK); return false; } } else { if ($force) { if (($argumentNumber > 0) && (count($this->warningRanges) > 0)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$too_few_critical_ranges, $argumentNumber+1)); } else { throw new VNagRequiredArgumentMissing('-c'); } } } } protected static function getBaddestExitcode($code1, $code2) { return max($code1, $code2); } public static function _shutdownHandler() { if (!self::is_http_mode()) { exit((int)self::$exitcode); } } protected function _exit($code) { self::$exitcode = $this->getBaddestExitcode($code, self::$exitcode); } private $constructed = false; function __construct() { $this->createHelpObject(); $this->createArgumentHandler(); $this->addExpectedArgument($this->argUsage = new VNagArgument('?', '', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$prints_usage)); $this->constructed = true; } function __destruct() { if (Timeouter::started()) { Timeouter::end(); } } public function run() { global $inside_vnag_run; $inside_vnag_run = true; try { if (!$this->constructed) { throw new VNagNotConstructed(VNagLang::$notConstructed); } try { $this->initialized = true; $this->html_before = ''; $this->html_after = ''; $this->setStatus(null, true); $this->messages = array(); register_shutdown_function(array($this, '_shutdownHandler')); if ($this->argHandler->illegalUsage()) { $content = $this->helpObj->printUsagePage(); $this->setStatus(VNag::STATUS_UNKNOWN); if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_visual_output & VNag::OUTPUT_SPECIAL) echo $this->writeVisualHTML($content); if ($this->http_invisible_output & VNag::OUTPUT_SPECIAL) echo $this->writeInvisibleHTML($content); echo $this->html_after; return; } else { echo $content; return $this->_exit($this->status); } } if (!is_null($this->argVersion) && ($this->argVersion->available())) { $content = $this->helpObj->printVersionPage(); $this->setStatus(VNag::STATUS_UNKNOWN); if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_visual_output & VNag::OUTPUT_SPECIAL) echo $this->writeVisualHTML($content); if ($this->http_invisible_output & VNag::OUTPUT_SPECIAL) echo $this->writeInvisibleHTML($content); echo $this->html_after; return; } else { echo $content; return $this->_exit($this->status); } } if (!is_null($this->argHelp) && ($this->argHelp->available())) { $content = $this->helpObj->printHelpPage(); $this->setStatus(VNag::STATUS_UNKNOWN); if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_visual_output & VNag::OUTPUT_SPECIAL) echo $this->writeVisualHTML($content); if ($this->http_invisible_output & VNag::OUTPUT_SPECIAL) echo $this->writeInvisibleHTML($content); echo $this->html_after; return; } else { echo $content; return $this->_exit($this->status); } } $this->getWarningRange(); $this->getCriticalRange(); if (!is_null($this->argTimeout)) { $timeout = $this->argTimeout->getValue(); if (!is_null($timeout)) { Timeouter::start($timeout); } } ob_start(); $init_ob_level = ob_get_level(); try { $this->cbRun(); if (ob_get_level() < $init_ob_level) throw new VNagImplementationErrorException(VNagLang::$output_level_lowered); } finally { while (ob_get_level() > $init_ob_level) @ob_end_clean(); } if (is_null($this->status)) $this->setStatus($this->default_status,true); $outputType = VNag::OUTPUT_NORMAL; } catch (Exception $e) { $this->handleException($e); $outputType = VNag::OUTPUT_EXCEPTION; } if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_invisible_output & $outputType) { echo $this->writeInvisibleHTML(); } if ($this->http_visual_output & $outputType) { echo $this->writeVisualHTML(); } echo $this->html_after; } else { echo $this->getNagiosConsoleText(); return $this->_exit($this->status); } Timeouter::end(); } finally { $inside_vnag_run = false; } } private function getNagiosConsoleText() { $ary_perfdata = $this->getPerformanceData(); $performancedata_first = array_shift($ary_perfdata); $performancedata_rest = implode(' ', $ary_perfdata); $status_text = VNagLang::status($this->status, $this->statusmodel); if (_empty($this->getHeadline())) { $content = $status_text; } else { if ($this->show_status_in_headline) { $content = $status_text.': '.$this->getHeadline(); } else { $content = $this->getHeadline(); } } if (!_empty($performancedata_first)) $content .= '|'.trim($performancedata_first); $content .= "\n"; if (!_empty($this->verbose_info)) { $content .= trim($this->verbose_info); } if (!_empty($performancedata_rest)) $content .= '|'.trim($performancedata_rest); $content .= "\n"; return trim($content)."\n"; } abstract protected function cbRun(); public function addPerformanceData($prefDataObj, $move_to_font=false, $verbosityLevel=VNag::VERBOSITY_SUMMARY) { $this->checkInitialized(); if ((!isset($this->argVerbosity)) && ($verbosityLevel > VNag::VERBOSITY_SUMMARY)) throw new VNagRequiredArgumentNotRegistered('-v'); if (self::getVerbosityLevel() < $verbosityLevel) return false; if ($move_to_font) { array_unshift($this->performanceDataObjects, $prefDataObj); } else { $this->performanceDataObjects[] = $prefDataObj; } return true; } public function getPerformanceData() { $this->checkInitialized(); return $this->performanceDataObjects; } public function removePerformanceData($prefDataObj) { if (($key = array_search($prefDataObj, $this->performanceDataObjects, true)) !== false) { unset($this->performanceDataObjects[$key]); return true; } else { return false; } } public function clearPerformanceData() { $this->performanceDataObjects = array(); } public function getVerboseInfo() { return $this->verbose_info; } public function clearVerboseInfo() { $this->verbose_info = ''; } private function writeVisualHTML($special_content=null) { if (!_empty($special_content)) { $content = $special_content; } else { $content = strtoupper(VNagLang::$status.': '.VNagLang::status($this->status, $this->statusmodel))."\n\n"; $content .= strtoupper(VNagLang::$message).":\n"; $status_text = VNagLang::status($this->status, $this->statusmodel); if (_empty($this->getHeadline())) { $content .= $status_text; } else { if ($this->show_status_in_headline) { $content .= $status_text.': '.trim($this->getHeadline()); } else { $content .= trim($this->getHeadline()); } } $content .= "\n\n"; if (!_empty($this->verbose_info)) { $content .= strtoupper(VNagLang::$verbose_info).":\n".trim($this->verbose_info)."\n\n"; } $perfdata = $this->getPerformanceData(); if (count($perfdata) > 0) { $content .= strtoupper(VNagLang::$performance_data).":\n"; foreach ($perfdata as $pd) { $content .= trim($pd)."\n"; } $content .= "\n"; } } $colorinfo = ''; $status = $this->getStatus(); if ($status == VNag::STATUS_OK) $colorinfo = ' style="background-color:green;color:white;font-weight:bold"'; else if ($status == VNag::STATUS_WARNING) $colorinfo = ' style="background-color:yellow;color:black;font-weight:bold"'; else if ($status == VNag::STATUS_CRITICAL) $colorinfo = ' style="background-color:red;color:white;font-weight:bold"'; else if ($status == VNag::STATUS_ERROR) $colorinfo = ' style="background-color:purple;color:white;font-weight:bold"'; else $colorinfo = ' style="background-color:lightgray;color:black;font-weight:bold"'; $html_content = trim($content); $html_content = htmlentities($html_content); $html_content = str_replace(' ', '&nbsp;', $html_content); $html_content = nl2br($html_content); return '<table border="1" cellspacing="2" cellpadding="2" style="width:100%" class="vnag_table">'. '<tr'.$colorinfo.' class="vnag_title_row">'. '<td>'.VNagLang::$nagios_output.'</td>'. '</tr>'. '<tr class="vnag_message_row">'. '<td><code>'. $html_content. '</code></td>'. '</tr>'. '</table>'; } protected function readInvisibleHTML($html) { $this->checkInitialized(); $doc = new DOMDocument(); @$doc->loadHTML($html); $tags = $doc->getElementsByTagName('script'); foreach ($tags as $tag) { $type = $tag->getAttribute('type'); if ($type !== 'application/json') continue; $json = $tag->nodeValue; if (!$json) continue; $data = @json_decode($json,true); if (!is_array($data)) continue; if (!isset($data['type'])) continue; if ($data['type'] === VNAG_JSONDATA_V1) { if (!isset($data['datasets'])) throw new VNagWebInfoException(VNagLang::$dataset_missing); foreach ($data['datasets'] as $dataset) { $payload = base64_decode($dataset['payload']); if (!$payload) { throw new VNagWebInfoException(VNagLang::$payload_not_base64); } if (isset($dataset['encryption'])) { $cryptInfo = $dataset['encryption']; if (!is_array($cryptInfo)) { throw new VNagWebInfoException(VNagLang::$dataset_encryption_no_array); } $password = is_null($this->password_in) ? '' : $this->password_in; $salt = base64_decode($cryptInfo['salt']); if ($cryptInfo['hash'] != hash('sha256',$salt.$password)) { if ($password == '') { throw new VNagWebInfoException(VNagLang::$require_password); } else { throw new VNagWebInfoException(VNagLang::$wrong_password); } } if (!function_exists('openssl_decrypt')) { throw new VNagException(VNagLang::$openssl_missing); } $payload = openssl_decrypt($payload, $cryptInfo['method'], $password, 0, $cryptInfo['iv']); } if (!is_null($this->pubkey) && ($this->pubkey !== '')) { if (substr($this->pubkey,0,3) === '---') { $public_key = $this->pubkey; } else { if (!file_exists($this->pubkey)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$pubkey_file_not_found, $this->pubkey)); } $public_key = @file_get_contents($this->pubkey); if (!$public_key) { throw new VNagPublicKeyException(sprintf(VNagLang::$pubkey_file_not_readable, $this->pubkey)); } } if (!isset($dataset['signature'])) { throw new VNagSignatureException(VNagLang::$signature_missing); } $signature = base64_decode($dataset['signature']); if (!$signature) { throw new VNagSignatureException(VNagLang::$signature_not_bas64); } if (!function_exists('openssl_verify')) { throw new VNagException(VNagLang::$openssl_missing); } $sign_algo = is_null($this->sign_algo) ? OPENSSL_ALGO_SHA256 : $this->sign_algo; if (!openssl_verify($payload, $signature, $public_key, $sign_algo)) { throw new VNagSignatureException(VNagLang::$signature_invalid); } } $payload = @json_decode($payload,true); if (!$payload) { throw new VNagWebInfoException(VNagLang::$payload_not_json); } if ($payload['id'] == $this->id) { return $payload; } } } } return null; } private function getNextMonitorID($peek=false) { $result = is_null($this->id) ? self::$http_serial_number : $this->id; if (!$peek) { $this->id = null; self::$http_serial_number++; } return $result; } private function writeInvisibleHTML($special_content=null) { $payload['id'] = $this->getNextMonitorID(); $payload['status'] = $this->getStatus(); if (!_empty($special_content)) { $payload['text'] = $special_content; } else { $payload['headline'] = $this->getHeadline(); $payload['verbose_info'] = $this->verbose_info; $payload['performance_data'] = array(); foreach ($this->performanceDataObjects as $perfdata) { $payload['performance_data'][] = (string)$perfdata; } } $payload = json_encode($payload); $dataset = array(); if (!is_null($this->privkey) && ($this->privkey !== '')) { if (!function_exists('openssl_pkey_get_private') || !function_exists('openssl_sign')) { throw new VNagException(VNagLang::$openssl_missing); } if (substr($this->privkey,0,3) === '---') { $pkeyid = @openssl_pkey_get_private($this->privkey, $this->privkey_password); if (!$pkeyid) { throw new VNagPrivateKeyException(sprintf(VNagLang::$privkey_not_readable)); } } else { if (!file_exists($this->privkey)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$privkey_file_not_found, $this->privkey)); } $pkeyid = @openssl_pkey_get_private('file://'.$this->privkey, $this->privkey_password); if (!$pkeyid) { throw new VNagPrivateKeyException(sprintf(VNagLang::$privkey_file_not_readable, $this->privkey)); } } $signature = ''; $sign_algo = is_null($this->sign_algo) ? OPENSSL_ALGO_SHA256 : $this->sign_algo; if (@openssl_sign($payload, $signature, $pkeyid, $sign_algo)) { if (version_compare(PHP_VERSION, '8.0.0') < 0) { openssl_free_key($pkeyid); } $dataset['signature'] = base64_encode($signature); } else { throw new VNagPrivateKeyException(sprintf(VNagLang::$signature_failed)); } } if (!is_null($this->password_out) && ($this->password_out !== '')) { if (!function_exists('openssl_encrypt')) { throw new VNagException(VNagLang::$openssl_missing); } $password = $this->password_out; $method = 'aes-256-ofb'; $iv = substr(hash('sha256', openssl_random_pseudo_bytes(32)), 0, 16); $salt = openssl_random_pseudo_bytes(32); $cryptInfo = array(); $cryptInfo['method'] = $method; $cryptInfo['iv'] = $iv; $cryptInfo['salt'] = base64_encode($salt); $cryptInfo['hash'] = hash('sha256', $salt.$password); $payload = openssl_encrypt($payload, $method, $password, 0, $iv); $dataset['encryption'] = $cryptInfo; } $dataset['payload'] = base64_encode($payload); $json = array(); $json['type'] = VNAG_JSONDATA_V1; $json['datasets'] = array($dataset); return '<script type="application/json">'. json_encode($json). '</script>'; } protected function appendHeadline($msg) { $this->checkInitialized(); if (_empty($msg)) return false; $this->messages[] = $msg; return true; } protected function changeHeadline($msg) { $this->checkInitialized(); if (_empty($msg)) { $this->messages = array(); } else { $this->messages = array($msg); } return true; } public function setHeadline($msg, $append=false, $verbosityLevel=VNag::VERBOSITY_SUMMARY) { $this->checkInitialized(); if ((!isset($this->argVerbosity)) && ($verbosityLevel > VNag::VERBOSITY_SUMMARY)) throw new VNagRequiredArgumentNotRegistered('-v'); if (self::getVerbosityLevel() < $verbosityLevel) $msg = ''; if ($append) { return $this->appendHeadline($msg); } else { return $this->changeHeadline($msg); } } public function getHeadline() { $this->checkInitialized(); return implode(', ', $this->messages); } public function addVerboseMessage($msg, $verbosityLevel=VNag::VERBOSITY_SUMMARY) { $this->checkInitialized(); if (self::getVerbosityLevel() >= $verbosityLevel) { $this->verbose_info .= $msg."\n"; } } public function setStatus($status, $force=false) { $this->checkInitialized(); if (($force) || is_null($this->status) || ($status > $this->status)) { $this->status = $status; } } public function getStatus() { $this->checkInitialized(); return $this->status; } protected static function exceptionText($exception) { $class = get_class($exception); $msg = $exception->getMessage(); if (!_empty($msg)) { return sprintf(VNagLang::$exception_x, $msg, $class); } else { return sprintf(VNagLang::$unhandled_exception_without_msg, $class); } } protected function handleException($exception) { $this->checkInitialized(); if (!VNag::is_http_mode()) { while (ob_get_level() > 0) @ob_end_clean(); } $this->clearVerboseInfo(); $this->clearPerformanceData(); if ($exception instanceof VNagException) { $this->setStatus($exception->getStatus()); } else { $this->setStatus(self::STATUS_ERROR); } $this->setHeadline($this->exceptionText($exception), false); if ($exception instanceof VNagImplementationErrorException) { $this->addVerboseMessage($exception->getTraceAsString(), VNag::VERBOSITY_SUMMARY); } else { if (isset($this->argVerbosity)) { $this->addVerboseMessage($exception->getTraceAsString(), VNag::VERBOSITY_ADDITIONAL_INFORMATION); } else { } } } protected function get_cache_dir() { $homedir = @getenv('HOME'); if ($homedir && is_dir($homedir)) { $try = "$homedir/.vnag/cache"; if (is_dir($try)) return $try; if (@mkdir($try,0777,true)) return $try; } $user = posix_getpwuid(posix_geteuid()); if (isset($user['dir']) && is_dir($user['dir'])) { $homedir = $user['dir']; $try = "$homedir/.vnag/cache"; if (is_dir($try)) return $try; if (@mkdir($try,0777,true)) return $try; } if (isset($user['name']) && is_dir($user['name'])) { $username = $user['name']; $try = "/tmp/vnag/cache"; if (is_dir($try)) return $try; if (@mkdir($try,0777,true)) return $try; } throw new VNagException("Cannot get cache dir"); } protected function url_get_contents($url, $max_cache_time=1*60*60, $context=null) { $cache_file = $this->get_cache_dir().'/'.hash('sha256',$url); if (file_exists($cache_file) && (time()-filemtime($cache_file) < $max_cache_time)) { $cont = @file_get_contents($cache_file); if ($cont === false) throw new Exception("Failed to get contents from $cache_file"); } else { $options = array( 'http'=>array( 'method'=>"GET", 'header'=>"Accept-language: en\r\n" . "User-Agent: Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B334b Safari/531.21.102011-10-16 20:23:10\r\n" ) ); if (is_null($context)) $context = stream_context_create($options); $cont = @file_get_contents($url, false, $context); if ($cont === false) throw new Exception("Failed to get contents from $url"); file_put_contents($cache_file, $cont); } return $cont; } } class VNagException extends Exception { public function getStatus() { return VNag::STATUS_ERROR; } } class VNagTimeoutException extends VNagException {} class VNagWebInfoException extends VNagException {} class VNagSignatureException extends VNagException {} class VNagPublicKeyException extends VNagException {} class VNagPrivateKeyException extends VNagException {} class VNagInvalidArgumentException extends VNagException { public function getStatus() { return VNag::STATUS_UNKNOWN; } } class VNagValueUomPairSyntaxException extends VNagInvalidArgumentException { public function __construct($str) { $e_msg = sprintf(VNagLang::$valueUomPairSyntaxError, $str); parent::__construct($e_msg); } } class VNagInvalidTimeoutException extends VNagInvalidArgumentException {} class VNagInvalidRangeException extends VNagInvalidArgumentException { public function __construct($msg) { $e_msg = VNagLang::$range_is_invalid; if (!_empty($msg)) $e_msg .= ': '.trim($msg); parent::__construct($e_msg); } } class VNagInvalidShortOpt extends VNagImplementationErrorException {} class VNagInvalidLongOpt extends VNagImplementationErrorException {} class VNagInvalidValuePolicy extends VNagImplementationErrorException {} class VNagIllegalStatusModel extends VNagImplementationErrorException {} class VNagNotConstructed extends VNagImplementationErrorException {} class VNagImplementationErrorException extends VNagException {} class VNagInvalidStandardArgument extends VNagImplementationErrorException {} class VNagFunctionCallOutsideSession extends VNagImplementationErrorException {} class VNagIllegalArgumentValuesException extends VNagImplementationErrorException {} class VNagRequiredArgumentNotRegistered extends VNagImplementationErrorException { public function __construct($required_argument) { $e_msg = sprintf(VNagLang::$query_without_expected_argument, $required_argument); parent::__construct($e_msg); } } class VNagRequiredArgumentMissing extends VNagInvalidArgumentException { public function __construct($required_argument) { $e_msg = sprintf(VNagLang::$required_argument_missing, $required_argument); parent::__construct($e_msg); } } class VNagUnknownUomException extends VNagInvalidArgumentException { public function __construct($uom) { $e_msg = sprintf(VNagLang::$perfdata_uom_not_recognized, $uom); parent::__construct($e_msg); } } class VNagNoCompatibleRangeUomFoundException extends VNagException {} class VNagMixedUomsNotImplemented extends VNagInvalidArgumentException { public function __construct($uom1, $uom2) { if (_empty($uom1)) $uom1 = VNagLang::$none; if (_empty($uom2)) $uom2 = VNagLang::$none; $e_msg = sprintf(VNagLang::$perfdata_mixed_uom_not_implemented, $uom1, $uom2); parent::__construct($e_msg); } } class VNagUomConvertException extends VNagInvalidArgumentException { public function __construct($uom1, $uom2) { if (_empty($uom1)) $uom1 = VNagLang::$none; if (_empty($uom2)) $uom2 = VNagLang::$none; $e_msg = sprintf(VNagLang::$convert_x_y_error, $uom1, $uom2); parent::__construct($e_msg); } } class VNagInvalidPerformanceDataException extends VNagInvalidArgumentException { public function __construct($msg) { $e_msg = VNagLang::$performance_data_invalid; if (!_empty($msg)) $e_msg .= ': '.trim($msg); parent::__construct($e_msg); } } class Timeouter { private static $start_time = false; private static $timeout; private static $fired = false; private static $registered = false; private function __construct() { } public static function start($timeout) { if (!is_numeric($timeout) || ($timeout <= 0)) { throw new VNagInvalidTimeoutException(sprintf(VNagLang::$timeout_value_invalid, $timeout)); } self::$start_time = microtime(true); self::$timeout = (float) $timeout; self::$fired = false; if (!self::$registered) { self::$registered = true; register_tick_function(array('Timeouter', 'tick')); } } public static function started() { return self::$registered; } public static function end() { if (self::$registered) { unregister_tick_function(array('Timeouter', 'tick')); self::$registered = false; } } public static function tick() { if ((!self::$fired) && ((microtime(true) - self::$start_time) > self::$timeout)) { self::$fired = true; throw new VNagTimeoutException(VNagLang::$timeout_exception); } } } class VNagArgument { const VALUE_FORBIDDEN = 0; const VALUE_REQUIRED = 1; const VALUE_OPTIONAL = 2; protected $shortopt; protected $longopts; protected $valuePolicy; protected $valueName; protected $helpText; protected $defaultValue = null; protected static $all_short = ''; protected static $all_long = array(); public function getShortOpt() { return $this->shortopt; } public function getLongOpts() { return $this->longopts; } public function getValuePolicy() { return $this->valuePolicy; } public function getValueName() { return $this->valueName; } public function getHelpText() { return $this->helpText; } static private function validateShortOpt($shortopt) { $m = array(); return preg_match('@^[a-zA-Z0-9\\+\\-\\?]$@', $shortopt, $m); } static private function validateLongOpt($longopt) { $m = array(); return preg_match('@^[a-zA-Z0-9\\+\\-\\?]+$@', $longopt, $m); } public function __construct($shortopt, $longopts, $valuePolicy, $valueName, $helpText, $defaultValue=null) { switch ($valuePolicy) { case VNagArgument::VALUE_FORBIDDEN: if (!_empty($valueName)) { throw new VNagImplementationErrorException(sprintf(VNagLang::$value_name_forbidden)); } break; case VNagArgument::VALUE_REQUIRED: if (_empty($valueName)) { throw new VNagImplementationErrorException(sprintf(VNagLang::$value_name_required)); } break; case VNagArgument::VALUE_OPTIONAL: if (_empty($valueName)) { throw new VNagImplementationErrorException(sprintf(VNagLang::$value_name_required)); } break; default: throw new VNagInvalidValuePolicy(sprintf(VNagLang::$illegal_valuepolicy, $valuePolicy)); } if (!_empty($shortopt)) { if (!self::validateShortOpt($shortopt)) { throw new VNagInvalidShortOpt(sprintf(VNagLang::$illegal_shortopt, $shortopt)); } } if (is_array($longopts)) { foreach ($longopts as $longopt) { if (!self::validateLongOpt($longopt)) { throw new VNagInvalidLongOpt(sprintf(VNagLang::$illegal_longopt, $longopt)); } } } else if (!_empty($longopts)) { if (!self::validateLongOpt($longopts)) { throw new VNagInvalidLongOpt(sprintf(VNagLang::$illegal_longopt, $longopts)); } $longopts = array($longopts); } else { $longopts = array(); } switch ($valuePolicy) { case VNagArgument::VALUE_FORBIDDEN: $policyApdx = ''; break; case VNagArgument::VALUE_REQUIRED: $policyApdx = ':'; break; case VNagArgument::VALUE_OPTIONAL: $policyApdx = '::'; break; default: throw new VNagInvalidValuePolicy(sprintf(VNagLang::$illegal_valuepolicy, $valuePolicy)); } if ((!is_null($shortopt)) && ($shortopt != '?')) self::$all_short .= $shortopt.$policyApdx; if (is_array($longopts)) { foreach ($longopts as $longopt) { self::$all_long[] = $longopt.$policyApdx; } } $this->shortopt = $shortopt; $this->longopts = $longopts; $this->valuePolicy = $valuePolicy; $this->valueName = $valueName; $this->helpText = $helpText; $this->defaultValue = $defaultValue; } protected static function getOptions() { global $OVERWRITE_ARGUMENTS; if (!is_null($OVERWRITE_ARGUMENTS)) { return $OVERWRITE_ARGUMENTS; } else if (VNag::is_http_mode()) { return $_REQUEST; } else { return getopt(self::$all_short, self::$all_long); } } public function count() { $options = self::getOptions(); $count = 0; if (isset($options[$this->shortopt])) { if (is_array($options[$this->shortopt])) { $count += count($options[$this->shortopt]); } else { $count += 1; } } if (!is_null($this->longopts)) { foreach ($this->longopts as $longopt) { if (isset($options[$longopt])) { if (is_array($options[$longopt])) { $count += count($options[$longopt]); } else { $count += 1; } } } } return $count; } public function available() { $options = self::getOptions(); if (isset($options[$this->shortopt])) return true; if (!is_null($this->longopts)) { foreach ($this->longopts as $longopt) { if (isset($options[$longopt])) return true; } } return false; } public function require() { if (!$this->available() && is_null($this->defaultValue)) { $opt = $this->shortopt; $opt = !_empty($opt) ? '-'.$opt : (isset($this->longopts[0]) ? '--'.$this->longopts[0] : '?'); throw new VNagRequiredArgumentMissing($opt); } } public function getValue() { $options = self::getOptions(); if (isset($options[$this->shortopt])) { $x = $options[$this->shortopt]; if (is_array($x) && (count($x) <= 1)) $options[$this->shortopt] = $options[$this->shortopt][0]; return $options[$this->shortopt]; } if (!is_null($this->longopts)) { foreach ($this->longopts as $longopt) { if (isset($options[$longopt])) { $x = $options[$longopt]; if (is_array($x) && (count($x) <= 1)) $options[$longopt] = $options[$longopt][0]; return $options[$longopt]; } } } return $this->defaultValue; } } class VNagArgumentHandler { protected $expectedArgs = array(); protected function _addExpectedArgument($argObj) { if ($argObj->getShortOpt() == '?') return false; if ($argObj->getShortOpt() == '-') return false; if ($argObj->getShortOpt() == '+') return false; $this->expectedArgs[] = $argObj; return true; } public function getArgumentObj($shortopt) { foreach ($this->expectedArgs as $argObj) { if ($argObj->getShortOpt() == $shortopt) return $argObj; } return null; } public function isArgRegistered($shortopt) { return !is_null($this->getArgumentObj($shortopt)); } public function illegalUsage() { global $argv; return (isset($argv[1])) && (($argv[1] == '-?') || ($argv[1] == '/?')); } } class VNagRange { public $start; public $end; public $warnInsideRange; public function __construct($rangeDef, $singleValueBehavior=VNag::SINGLEVALUE_RANGE_DEFAULT) { $m = array(); if (!preg_match('|^(@){0,1}([^:]+)(:){0,1}(.*)$|', $rangeDef, $m)) { throw new VNagInvalidRangeException(sprintf(VNagLang::$range_invalid_syntax, $rangeDef)); } $this->warnInsideRange = $m[1] === '@'; $this->start = null; $this->end = null; if ($m[3] === ':') { if ($m[2] === '~') { $this->start = '-inf'; } else { $this->start = new VNagValueUomPair($m[2]); } if (_empty($m[4])) { $this->end = 'inf'; } else { $this->end = new VNagValueUomPair($m[4]); } } else { assert(_empty($m[4])); assert(!_empty($m[2])); $x = $m[2]; if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_DEFAULT) { $this->start = new VNagValueUomPair('0'.((new VNagValueUomPair($x))->getUom())); $this->end = new VNagValueUomPair($x); } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_GT_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 0; $this->start = '-inf'; $this->end = new VNagValueUomPair($x); } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_GE_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 1; $this->start = new VNagValueUomPair($x); $this->end = 'inf'; } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_LT_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 0; $this->start = new VNagValueUomPair($x); $this->end = 'inf'; } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_LE_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 1; $this->start = '-inf'; $this->end = new VNagValueUomPair($x); } else { throw new VNagException(VNagLang::$illegalSingleValueBehavior); } } if (is_null($this->start)) { throw new VNagInvalidRangeException(VNagLang::$invalid_start_value); } if (is_null($this->end)) { throw new VNagInvalidRangeException(VNagLang::$invalid_end_value); } if (($this->start instanceof VNagValueUomPair) && ($this->end instanceof VNagValueUomPair) && (VNagValueUomPair::compare($this->start,$this->end) > 0)) { throw new VNagInvalidRangeException(VNagLang::$start_is_greater_than_end); } } public function __toString() { $ret = ''; if ($this->warnInsideRange) { $ret = '@'; } if ($this->start === '-inf') { $ret .= '~'; } else { $ret .= $this->start; } $ret .= ':'; if ($this->end !== 'inf') { $ret .= $this->end; } return $ret; } public function checkAlert($values) { $compatibleCount = 0; if (!is_array($values)) $values = array($values); foreach ($values as $value) { if (!($value instanceof VNagValueUomPair)) $value = new VNagValueUomPair($value); assert(($this->start === '-inf') || ($this->start instanceof VNagValueUomPair)); assert(($this->end === 'inf' ) || ($this->end instanceof VNagValueUomPair)); if (($this->start !== '-inf') && (!$this->start->compatibleWith($value))) continue; if (($this->end !== 'inf') && (!$this->end->compatibleWith($value))) continue; $compatibleCount++; if ($this->warnInsideRange) { return (($this->start === '-inf') || (VNagValueUomPair::compare($value,$this->start) >= 0)) && (($this->end === 'inf') || (VNagValueUomPair::compare($value,$this->end) <= 0)); } else { return (($this->start !== '-inf') && (VNagValueUomPair::compare($value,$this->start) < 0)) || (($this->end !== 'inf') && (VNagValueUomPair::compare($value,$this->end) > 0)); } } if ((count($values) > 0) and ($compatibleCount == 0)) { throw new VNagNoCompatibleRangeUomFoundException(VNagLang::$no_compatible_range_uom_found); } return false; } } class VNagValueUomPair { protected $value; protected $uom; public $roundTo = -1; public function isRelative() { return $this->uom === '%'; } public function getValue() { return $this->value; } public function getUom() { return $this->uom; } public function __toString() { if ($this->roundTo == -1) { return $this->value.$this->uom; } else { return round($this->value,$this->roundTo).$this->uom; } } public function __construct($str) { $m = array(); if (!preg_match('/^([\d\.]+)(.*)$/ism', $str, $m)) { throw new VNagValueUomPairSyntaxException($str); } $this->value = $m[1]; $this->uom = isset($m[2]) ? $m[2] : ''; if (!self::isKnownUOM($this->uom)) { throw new VNagUnknownUomException($this->uom); } } public static function isKnownUOM(string $uom) { $no_unit = ($uom === ''); $seconds = ($uom === 's') || ($uom === 'ms') || ($uom === 'us'); $percentage = ($uom === '%'); $bytes = ($uom === 'B') || ($uom === 'KB') || ($uom === 'MB') || ($uom === 'GB') || ($uom === 'TB'); $counter = ($uom === 'c'); return ($no_unit || $seconds || $percentage || $bytes || $counter); } public function normalize($target=null) { $res = clone $this; if ($res->uom === 'ms') { $res->uom = 's'; $res->value /= 1000; } if ($res->uom === 'us') { $res->uom = 's'; $res->value /= 1000 * 1000; } if ($res->uom === 'B') { $res->uom = 'MB'; $res->value /= 1024 * 1024; } if ($res->uom === 'KB') { $res->uom = 'MB'; $res->value /= 1024; } if ($res->uom === 'GB') { $res->uom = 'MB'; $res->value *= 1024; } if ($res->uom === 'TB') { $res->uom = 'MB'; $res->value *= 1024 * 1024; } if ($res->uom === 'c') { $res->uom = ''; } if (!is_null($target)) { if ($res->uom == 'MB') { if ($target == 'B') { $res->uom = 'B'; $res->value *= 1024 * 1024; } else if ($target == 'KB') { $res->uom = 'KB'; $res->value *= 1024; } else if ($target == 'MB') { $res->uom = 'MB'; $res->value *= 1; } else if ($target == 'GB') { $res->uom = 'GB'; $res->value /= 1024; } else if ($target == 'TB') { $res->uom = 'TB'; $res->value /= 1024 * 1024; } else { throw new VNagUomConvertException($res->uom, $target); } } else if ($res->uom == 's') { if ($target == 's') { $res->uom = 's'; $res->value /= 1; } else if ($target == 'ms') { $res->uom = 'ms'; $res->value /= 1000; } else if ($target == 'us') { $res->uom = 'us'; $res->value /= 1000 * 1000; } else { throw new VNagUomConvertException($res->uom, $target); } } else { throw new VNagUomConvertException($res->uom, $target); } } return $res; } public function compatibleWith(VNagValueUomPair $other) { $a = $this->normalize(); $b = $other->normalize(); return ($a->uom == $b->uom); } public static function compare(VNagValueUomPair $left, VNagValueUomPair $right) { $a = $left->normalize(); $b = $right->normalize(); if ($a->uom != $b->uom) throw new VNagMixedUomsNotImplemented($a->uom, $b->uom); if ($a->value > $b->value) return 1; if ($a->value == $b->value) return 0; if ($a->value < $b->value) return -1; } } class VNagPerformanceData { protected $label; protected $value; protected $warn = null; protected $crit = null; protected $min = null; protected $max = null; public static function createByString($perfdata) { $perfdata = trim($perfdata); $ary = explode('=',$perfdata); if (count($ary) != 2) { throw new VNagInvalidPerformanceDataException(sprintf(VNagLang::$perfdata_line_invalid, $perfdata)); } $label = $ary[0]; $bry = explode(';',$ary[1]); if (substr($label,0,1) === "'") $label = substr($label, 1, strlen($label)-2); $value = $bry[0]; $warn = isset($bry[1]) ? $bry[1] : null; $crit = isset($bry[2]) ? $bry[2] : null; $min = isset($bry[3]) ? $bry[3] : null; $max = isset($bry[4]) ? $bry[4] : null; return new self($label, $value, $warn, $crit, $min, $max); } public function __construct($label, $value, $warn=null, $crit=null, $min=null, $max=null) { if (strpos($label, '=') !== false) throw new VNagInvalidPerformanceDataException(VNagLang::$perfdata_label_equal_sign_forbidden); $label = str_replace("'", "''", $label); $m = array(); if ((!_empty($min)) && (!preg_match('|^[-0-9\\.]+$|', $min, $m))) { throw new VNagInvalidPerformanceDataException(VNagLang::$perfdata_min_must_be_in_class); } if ((!_empty($max)) && (!preg_match('|^[-0-9\\.]+$|', $max, $m))) { throw new VNagInvalidPerformanceDataException(VNagLang::$perfdata_max_must_be_in_class); } $this->label = $label; $this->value = ($value == 'U') ? 'U' : new VNagValueUomPair($value); $this->warn = $warn; $this->crit = $crit; $this->min = $min; $this->max = $max; } public function __toString() { $label = $this->label; $value = $this->value; $warn = $this->warn; $crit = $this->crit; $min = $this->min; $max = $this->max; $label = str_replace("''", "'", $label); return "'$label'=$value". ';'.(is_null($warn) ? '' : $warn). ';'.(is_null($crit) ? '' : $crit). ';'.(is_null($min) ? '' : $min). ';'.(is_null($max) ? '' : $max); } } class VNagHelp { public $word_wrap_width = 80; public $argument_indent = 7; public function printUsagePage() { $usage = $this->getUsage(); if (_empty($usage)) { $usage = VNagLang::$no_syntax_defined; } return trim($usage)."\n"; } public function printVersionPage() { $out = trim($this->getNameAndVersion())."\n"; if ($this->word_wrap_width > 0) $out = wordwrap($out, $this->word_wrap_width, "\n", false); return $out; } static private function _conditionalLine($line, $terminator='', $prefix='') { if (!_empty($line)) { return trim($line).$terminator; } return ''; } public function printHelpPage() { $out = ''; $out .= self::_conditionalLine($this->getNameAndVersion(), "\n"); $out .= self::_conditionalLine($this->getCopyright(), "\n"); $out .= ($out != '') ? "\n" : ''; $out .= self::_conditionalLine($this->getShortDescription(), "\n\n\n"); $out .= self::_conditionalLine($this->getUsage(), "\n\n"); $out .= VNagLang::$options."\n"; foreach ($this->options as $argObj) { $out .= $this->printArgumentHelp($argObj); } $out .= self::_conditionalLine($this->getFootNotes(), "\n\n", "\n"); if ($this->word_wrap_width > 0) $out = wordwrap($out, $this->word_wrap_width, "\n", false); return $out; } protected $options = array(); protected function _addOption($argObj) { $this->options[] = $argObj; } protected function printArgumentHelp($argObj) { $identifiers = array(); $shortopt = $argObj->getShortopt(); if (!_empty($shortopt)) $identifiers[] = '-'.$shortopt; $longopts = $argObj->getLongopts(); if (!is_null($longopts)) { foreach ($longopts as $longopt) { if (!_empty($longopt)) $identifiers[] = '--'.$longopt; } } if (count($identifiers) == 0) return; $valueName = $argObj->getValueName(); $arginfo = ''; switch ($argObj->getValuePolicy()) { case VNagArgument::VALUE_FORBIDDEN: $arginfo = ''; break; case VNagArgument::VALUE_REQUIRED: $arginfo = '='.$valueName; break; case VNagArgument::VALUE_OPTIONAL: $arginfo = '[='.$valueName.']'; break; } $out = ''; $out .= implode(', ', $identifiers).$arginfo."\n"; $content = trim($argObj->getHelpText()); if ($this->word_wrap_width > 0) $content = wordwrap($content, $this->word_wrap_width-$this->argument_indent, "\n", false); $lines = explode("\n", $content); foreach ($lines as $line) { $out .= str_repeat(' ', $this->argument_indent).$line."\n"; } $out .= "\n"; return $out; } protected $pluginName; public function setPluginName($pluginName) { $this->pluginName = $this->replaceStuff($pluginName); } public function getPluginName() { if (_empty($this->pluginName)) { global $argv; return basename($argv[0]); } else { return $this->pluginName; } } protected $version; public function setVersion($version) { $this->version = $this->replaceStuff($version); } public function getVersion() { return $this->version; } public function getNameAndVersion() { $ret = $this->getPluginName(); if (_empty($ret)) return null; $ver = $this->getVersion(); if (!_empty($ver)) { $ret = sprintf(VNagLang::$x_version_x, $ret, $ver); } $ret = trim($ret); return $ret; } protected $copyright; public function setCopyright($copyright) { $this->copyright = $this->replaceStuff($copyright); } private function getVNagCopyright() { if (VNag::is_http_mode()) { $vts_email = 'www.viathinksoft.com'; } else { $vts_email = base64_decode('aW5mb0B2aWF0aGlua3NvZnQuZGU='); } return "VNag Framework ".VNag::VNAG_VERSION." (C) 2014-".date('Y')." ViaThinkSoft <$vts_email>"; } public function getCopyright() { if (_empty($this->copyright)) { return sprintf(VNagLang::$plugin_uses, $this->getVNagCopyright()); } else { return trim($this->copyright)."\n".sprintf(VNagLang::$uses, $this->getVNagCopyright()); } } protected $shortDescription; public function setShortDescription($shortDescription) { $this->shortDescription = $this->replaceStuff($shortDescription); } public function getShortDescription() { if (_empty($this->shortDescription)) { return null; } else { $content = $this->shortDescription; if ($this->word_wrap_width > 0) $content = wordwrap($content, $this->word_wrap_width, "\n", false); return $content; } } protected function replaceStuff($text) { global $argv; if (php_sapi_name() == 'cli') { $text = str_replace('$SCRIPTNAME$', $argv[0], $text); } else { $text = str_replace('$SCRIPTNAME$', basename($_SERVER['SCRIPT_NAME']), $text); } $text = str_replace('$CURYEAR$', date('Y'), $text); return $text; } protected $syntax; public function setSyntax($syntax) { $syntax = $this->replaceStuff($syntax); $this->syntax = $syntax; } public function getUsage() { if (_empty($this->syntax)) { return null; } else { return sprintf(VNagLang::$usage_x, $this->syntax); } } protected $footNotes; public function setFootNotes($footNotes) { $this->footNotes = $this->replaceStuff($footNotes); } public function getFootNotes() { return $this->footNotes; } } class VNagLang { public static function status($code, $statusmodel) { switch ($statusmodel) { case VNag::STATUSMODEL_SERVICE: switch ($code) { case VNag::STATUS_OK: return 'OK'; case VNag::STATUS_WARNING: return 'Warning'; case VNag::STATUS_CRITICAL: return 'Critical'; case VNag::STATUS_UNKNOWN: return 'Unknown'; default: return sprintf('Error (%d)', $code); } case VNag::STATUSMODEL_HOST: switch ($code) { case VNag::STATUS_UP: return 'Up'; case VNag::STATUS_DOWN: return 'Down'; default: return sprintf('Maintain last state (%d)', $code); } default: throw new VNagIllegalStatusModel(sprintf(self::$illegal_statusmodel, $statusmodel)); } } static $nagios_output = 'VNag-Output'; static $verbose_info = 'Verbose information'; static $status = 'Status'; static $message = 'Message'; static $performance_data = 'Performance data'; static $status_ok = 'OK'; static $status_warn = 'Warning'; static $status_critical = 'Critical'; static $status_unknown = 'Unknown'; static $status_error = 'Error'; static $unhandled_exception_without_msg = "Unhandled exception of type %s"; static $plugin_uses = 'This plugin uses %s'; static $uses = 'uses %s'; static $x_version_x = '%s, version %s'; static $argname_value = 'value'; static $argname_seconds = 'seconds'; static $query_without_expected_argument = "The argument '%s' is queried, but was not added to the list of expected arguments. Please contact the plugin author."; static $required_argument_missing = "The argument '%s' is required."; static $performance_data_invalid = 'Performance data invalid.'; static $no_standard_arguments_with_letter = "No standard argument with letter '%s' exists."; static $invalid_start_value = 'Invalid start value.'; static $invalid_end_value = 'Invalid end value.'; static $start_is_greater_than_end = 'Start is greater than end value.'; static $value_name_forbidden = "Implementation error: You may not define a value name for the argument, because the value policy is VALUE_FORBIDDEN."; static $value_name_required = "Implementation error: Please define a name for the argument (so it can be shown in the help page)."; static $illegal_shortopt = "Illegal shortopt '-%s'."; static $illegal_longopt = "Illegal longopt '--%s'."; static $illegal_valuepolicy = "valuePolicy has illegal value '%s'."; static $range_invalid_syntax = "Syntax error in range '%s'."; static $timeout_value_invalid = "Timeout value '%s' is invalid."; static $range_is_invalid = 'Range is invalid.'; static $timeout_exception = 'Timeout!'; static $perfdata_label_equal_sign_forbidden = 'Label may not contain an equal sign.'; static $perfdata_value_must_be_in_class = 'Value must be in class [-0-9.] or be \'U\' if the actual value can\'t be determined.'; static $perfdata_min_must_be_in_class = 'Min must be in class [-0-9.] or empty.'; static $perfdata_max_must_be_in_class = 'Max must be in class [-0-9.] or empty.'; static $perfdata_uom_not_recognized = 'UOM (unit of measurement) "%s" is not recognized.'; static $perfdata_mixed_uom_not_implemented = 'Mixed UOMs (%s and %s) are currently not supported.'; static $no_compatible_range_uom_found = 'Measured values are not compatible with the provided warning/critical parameter. Most likely, the UOM is incompatible.'; static $exception_x = '%s (%s)'; static $no_syntax_defined = 'The author of this plugin has not defined a syntax for this plugin.'; static $usage_x = "Usage:\n%s"; static $options = "Options:"; static $illegal_statusmodel = "Invalid statusmodel %d."; static $none = '[none]'; static $valueUomPairSyntaxError = 'Syntax error at "%s". Syntax must be Value[UOM].'; static $too_few_warning_ranges = "You have too few warning ranges (currently trying to get element %d)."; static $too_few_critical_ranges = "You have too few critical ranges (currently trying to get element %d)."; static $dataset_missing = 'Dataset missing.'; static $payload_not_base64 = 'The payload is not valid Base64.'; static $payload_not_json = 'The payload is not valid JSON.'; static $signature_missing = 'The signature is missing.'; static $signature_not_bas64 = 'The signature is not valid Base64.'; static $signature_invalid = 'The signature is invalid. The connection might have been tampered, or a different key is used.'; static $pubkey_file_not_found = "Public key file %s was not found."; static $pubkey_file_not_readable = "Public key file %s is not readable."; static $privkey_file_not_found = "Private key file %s was not found."; static $privkey_not_readable = "Private key is not readable."; static $privkey_file_not_readable = "Private key file %s is not readable."; static $signature_failed = "Signature failed."; static $perfdata_line_invalid = "Performance data line %s is invalid."; static $singlevalue_unexpected_at_symbol = 'This plugin does not allow the @-symbol at ranges for single values.'; static $illegalSingleValueBehavior = "Illegal value for 'singleValueBehavior'. Please contact the creator of the plugin."; static $dataset_encryption_no_array = 'Dataset encryption information invalid.'; static $require_password = 'This resource is protected with a password. Please provide a password.'; static $wrong_password = 'This resource is protected with a password. You have provided the wrong password, or it was changed.'; static $convert_x_y_error = 'Cannot convert from UOM %s to UOM %s.'; static $php_error = 'PHP has detected an error in the plugin. Please contact the plugin author.'; static $output_level_lowered = "Output Buffer level lowered during cbRun(). Please contact the plugin author."; static $openssl_missing = "OpenSSL is missing. Therefore, encryption and signatures are not available."; static $warning_range = 'Warning range'; static $critical_range = 'Critical range'; static $prints_version = 'Prints version'; static $verbosity_helptext = 'Verbosity -v, -vv or -vvv'; static $timeout_helptext = 'Sets timeout in seconds'; static $help_helptext = 'Prints help page'; static $prints_usage = 'Prints usage'; static $notConstructed = 'Parent constructor not called with parent::__construct().'; } function vnagErrorHandler($errorkind, $errortext, $file, $line) { global $inside_vnag_run; if (!$inside_vnag_run && VNag::is_http_mode()) { return false; } if (!(error_reporting() & $errorkind)) { return true; } if (defined('E_ERROR') && ($errorkind == E_ERROR)) $errorkind = 'Error'; if (defined('E_WARNING') && ($errorkind == E_WARNING)) $errorkind = 'Warning'; if (defined('E_PARSE') && ($errorkind == E_PARSE)) $errorkind = 'Parse'; if (defined('E_NOTICE') && ($errorkind == E_NOTICE)) $errorkind = 'Notice'; if (defined('E_CORE_ERROR') && ($errorkind == E_CORE_ERROR)) $errorkind = 'Core Error'; if (defined('E_CORE_WARNING') && ($errorkind == E_CORE_WARNING)) $errorkind = 'Core Warning'; if (defined('E_COMPILE_ERROR') && ($errorkind == E_COMPILE_ERROR)) $errorkind = 'Compile Error'; if (defined('E_COMPILE_WARNING') && ($errorkind == E_COMPILE_WARNING)) $errorkind = 'Compile Warning'; if (defined('E_USER_ERROR') && ($errorkind == E_USER_ERROR)) $errorkind = 'User Error'; if (defined('E_USER_WARNING') && ($errorkind == E_USER_WARNING)) $errorkind = 'User Warning'; if (defined('E_USER_NOTICE') && ($errorkind == E_USER_NOTICE)) $errorkind = 'User Notice'; if (defined('E_STRICT') && ($errorkind == E_STRICT)) $errorkind = 'Strict'; if (defined('E_RECOVERABLE_ERROR') && ($errorkind == E_RECOVERABLE_ERROR)) $errorkind = 'Recoverable Error'; if (defined('E_DEPRECATED') && ($errorkind == E_DEPRECATED)) $errorkind = 'Deprecated'; if (defined('E_USER_DEPRECATED') && ($errorkind == E_USER_DEPRECATED)) $errorkind = 'User Deprecated'; throw new VNagException(VNagLang::$php_error . " $errortext at $file:$line (kind $errorkind)"); } $inside_vnag_run = false; $old_error_handler = set_error_handler("vnagErrorHandler"); <?php
declare(ticks=1); class OwnCloudVersionCheck extends VNag { protected $argSystemDir = null; public function __construct() { parent::__construct(); $this->registerExpectedStandardArguments('Vvht'); $this->getHelpManager()->setPluginName('check_owncloud_version'); $this->getHelpManager()->setVersion('2023-10-13'); $this->getHelpManager()->setShortDescription('This plugin checks if a local ownCloud system has the latest version installed.'); $this->getHelpManager()->setCopyright('Copyright (C) 2011-$CURYEAR$ Daniel Marschall, ViaThinkSoft.'); $this->getHelpManager()->setSyntax('$SCRIPTNAME$ [-d <directory>]'); $this->getHelpManager()->setFootNotes('If you encounter bugs, please contact ViaThinkSoft at www.viathinksoft.com'); $this->addExpectedArgument($this->argSystemDir = new VNagArgument('d', 'directory', VNagArgument::VALUE_REQUIRED, 'ownCloudPath', 'The local directory where your ownCloud installation is located.')); } protected function get_versions($local_path) { $local_path = realpath($local_path) === false ? $local_path : realpath($local_path); if (!file_exists($local_path . '/version.php')) { throw new VNagException('This is not a valid ownCloud installation in "'.$local_path.'".'); } $cont = @file_get_contents($local_path . '/version.php'); if ($cont === false) { throw new VNagException('This is not a valid ownCloud installation in "'.$local_path.'". Missing version.php file.'); } if (preg_match('@\\$(OC_Version)\\s*=\\s*array\\(\\s*(.+)\\s*,\\s*(.+)\\s*,\\s*(.+)\\s*,\\s*(.+)\\s*\\)\\s*;@ismU', $cont, $m)) { $OC_Version = array($m[2],$m[3],$m[4],$m[5]); } else { throw new VNagException('This is not a valid ownCloud installation in "'.$local_path.'". Missing "OC_Version".'); } if (preg_match('@\\$(OC_VersionString)\\s*=\\s*([\'"])(.*)\\2\\s*;@ismU', $cont, $m)) { $OC_VersionString = $m[3]; } else { throw new VNagException('This is not a valid ownCloud installation in "'.$local_path.'". Missing "OC_VersionString".'); } if (preg_match('@\\$(OC_Edition)\\s*=\\s*([\'"])(.*)\\2\\s*;@ismU', $cont, $m)) { $OC_Edition = $m[3]; } else { throw new VNagException('This is not a valid ownCloud installation in "'.$local_path.'". Missing "OC_Edition".'); } if (preg_match('@\\$(OC_Channel)\\s*=\\s*([\'"])(.*)\\2\\s*;@ismU', $cont, $m)) { $OC_Channel = $m[3]; } else { throw new VNagException('This is not a valid ownCloud installation in "'.$local_path.'". Missing "OC_Channel".'); } if (preg_match('@\\$(OC_Build)\\s*=\\s*([\'"])(.*)\\2\\s*;@ismU', $cont, $m)) { $OC_Build = $m[3]; } else { throw new VNagException('This is not a valid ownCloud installation in "'.$local_path.'". Missing "OC_Build".'); } if (preg_match('@\\$(vendor)\\s*=\\s*([\'"])(.*)\\2\\s*;@ismU', $cont, $m)) { $vendor = $m[3]; if ($vendor != 'owncloud') { throw new VNagException('This is not a valid ownCloud installation in "'.$local_path.'". It is "'.$vendor.'".'); } } else { throw new VNagException('This is not a valid ownCloud installation in "'.$local_path.'". Missing "vendor".'); } $baseUrl = 'https://updates.owncloud.com/server/'; $update_url = $baseUrl . '?version='. implode('x', $OC_Version).'x'. 'installedatx'. 'lastupdatedatx'. $OC_Channel.'x'. $OC_Edition.'x'. urlencode($OC_Build); $cont = $this->url_get_contents($update_url); if ($cont === false) { throw new VNagException('Could not determinate current ownCloud version in "'.$local_path.'". (Cannot access '.$update_url.')'); } if ($cont === '') { return array($OC_VersionString, $OC_VersionString, $OC_Channel); } else { $xml = simplexml_load_string($cont); if ($xml === false) { throw new VNagException('Could not determinate current ownCloud version in "'.$local_path.'". (Invalid XML downloaded from update-server)'); } $new_ver = (string)$xml->version; return array($OC_VersionString, $new_ver, $OC_Channel); } } protected function cbRun($optional_args=array()) { $system_dir = $this->argSystemDir->getValue(); if (empty($system_dir)) { throw new VNagException("Please specify the directory of the ownCloud installation."); } $system_dir = realpath($system_dir) === false ? $system_dir : realpath($system_dir); if (!is_dir($system_dir)) { throw new VNagException('Directory "'.$system_dir.'" not found.'); } list($cur_ver, $new_ver, $channel) = $this->get_versions($system_dir); if (version_compare($cur_ver,$new_ver) >= 0) { $this->setStatus(VNag::STATUS_OK); $this->setHeadline("ownCloud version $cur_ver [$channel] is the latest available version for your ownCloud installation at $system_dir", true); } else { $this->setStatus(VNag::STATUS_WARNING); $this->setHeadline("ownCloud version $cur_ver [$channel] is outdated. Newer version is $new_ver [$channel] for installation at $system_dir", true); } } } <?php
declare(ticks=1); require_once __DIR__ . '/../../framework/vnag_framework.inc.php'; require_once __DIR__ . '/OwnCloudVersionCheck.class.php'; $job = new OwnCloudVersionCheck(); $job->run(); unset($job); \ˆîX’ñÒeLȀ>
‘GÊ@hËË°Çë/za£3þËë­õƒ3rù‹0bT)Çê! H€o9ÐÄBGBMB
declare(ticks=1); require_once __DIR__ . '/../../framework/vnag_framework.inc.php'; require_once __DIR__ . '/OwnCloudVersionCheck.class.php'; $job = new OwnCloudVersionCheck(); $job->run(); unset($job); Ò{çŒw|Š•«‹*’Ÿ¾1C挭¶Cº1B5Ë@7 ‰z® ðŠ·‰
Tµé%Þ¿9¹š‘ÌkNéh¼KOcÜGBMB
/trunk/bin/phpbb_version.phar
291,9 → 291,7
 
Extract_Phar::go();
__HALT_COMPILER(); ?>
c~a:1:{s:23:"1.3.6.1.4.1.37476.3.0.2";s:336:"sha256||framework/vnag_framework.inc.php|460b109d1c578e9b6af41612e0312c9f36fd8beb51f7aa92f1b7bd49614568e8||plugins/phpbb_version/PhpBbVersionCheck.class.php|68eb7c144a4c9cb0fda687892a3cd430aa6c73be7a1b87151f9a8838f6831961||plugins/phpbb_version/check_phpbb_version.phps|09ac2cdc7281a32b63586985de124963a8319f598ee0fa2ba1c84442bdd1784d||";} framework/vnag_framework.inc.phpLÙzï*eLُ4p”¤1plugins/phpbb_version/PhpBbVersionCheck.class.phpzï*eb¾Z¤.plugins/phpbb_version/check_phpbb_version.phpsÌzï*eÌvFF¤<?php ?>
<?php
¯Êa:1:{s:23:"1.3.6.1.4.1.37476.3.0.2";s:412:"sha256||<builder>|481cf75d675006b504520fd2acb3b29c89aea03aab64754e0adfb364de4914b2||framework/vnag_framework.inc.php|0387bf3134f8cc2d1ae24e139019c0edef19c1ba5ca765624efea0b469c7897f||plugins/phpbb_version/PhpBbVersionCheck.class.php|68eb7c144a4c9cb0fda687892a3cd430aa6c73be7a1b87151f9a8838f6831961||plugins/phpbb_version/check_phpbb_version.phps|09ac2cdc7281a32b63586985de124963a8319f598ee0fa2ba1c84442bdd1784d||";} framework/vnag_framework.inc.phpBÙ» +eBÙÞß=¤1plugins/phpbb_version/PhpBbVersionCheck.class.php» +eb¾Z¤.plugins/phpbb_version/check_phpbb_version.phpsÌ» +eÌvFF¤<?php
if (!VNag::is_http_mode()) error_reporting(E_ALL); declare(ticks=1); set_time_limit(0); define('VNAG_JSONDATA_V1', 'oid:1.3.6.1.4.1.37476.2.3.1.1'); $OVERWRITE_ARGUMENTS = null; function _empty($x) { return is_null($x) || (trim($x) == ''); } abstract class VNag { const VNAG_VERSION = '2023-10-13'; const STATUS_OK = 0; const STATUS_WARNING = 1; const STATUS_CRITICAL = 2; const STATUS_UNKNOWN = 3; const STATUS_ERROR = 4; const STATUS_UP = 0; const STATUS_DOWN = 1; const STATUS_MAINTAIN = 2; const VERBOSITY_SUMMARY = 0; const VERBOSITY_ADDITIONAL_INFORMATION = 1; const VERBOSITY_CONFIGURATION_DEBUG = 2; const VERBOSITY_PLUGIN_DEBUG = 3; const MAX_VERBOSITY = self::VERBOSITY_PLUGIN_DEBUG; const STATUSMODEL_SERVICE = 0; const STATUSMODEL_HOST = 1; private $initialized = false; private $status = null; private $messages = array(); private $verbose_info = ''; private $warningRanges = array(); private $criticalRanges = array(); private $performanceDataObjects = array(); private static $exitcode = 0; private $helpObj = null; private $argHandler = null; const OUTPUT_NEVER = 0; const OUTPUT_SPECIAL = 1; const OUTPUT_NORMAL = 2; const OUTPUT_EXCEPTION = 4; const OUTPUT_ALWAYS = 7; public $http_visual_output = self::OUTPUT_ALWAYS; public $http_invisible_output = self::OUTPUT_ALWAYS; protected $html_before = ''; protected $html_after = ''; protected $statusmodel = self::STATUSMODEL_SERVICE; protected $show_status_in_headline = true; protected $default_status = self::STATUS_UNKNOWN; protected $default_warning_range = null; protected $default_critical_range = null; protected $argWarning; protected $argCritical; protected $argVersion; protected $argVerbosity; protected $argTimeout; protected $argHelp; protected $argUsage; public $id = null; protected static $http_serial_number = 0; public $privkey = null; public $privkey_password = null; public $sign_algo = null; public $pubkey = null; protected $warningSingleValueRangeBehaviors = array(self::SINGLEVALUE_RANGE_DEFAULT); protected $criticalSingleValueRangeBehaviors = array(self::SINGLEVALUE_RANGE_DEFAULT); const SINGLEVALUE_RANGE_DEFAULT = 0; const SINGLEVALUE_RANGE_VAL_GT_X_BAD = 1; const SINGLEVALUE_RANGE_VAL_GE_X_BAD = 2; const SINGLEVALUE_RANGE_VAL_LT_X_BAD = 3; const SINGLEVALUE_RANGE_VAL_LE_X_BAD = 4; public $password_out = null; public $password_in = null; public static function is_http_mode() { return php_sapi_name() !== 'cli'; } public function getHelpManager() { return $this->helpObj; } public function getArgumentHandler() { return $this->argHandler; } public function outputHTML($text, $after_visual_output=true) { if ($this->is_http_mode()) { if ($this->initialized) { if ($after_visual_output) { $this->html_after .= $text; } else { $this->html_before .= $text; } } else { echo $text; } } } protected function resetArguments() { $this->argWarning = null; $this->argCritical = null; $this->argVersion = null; $this->argVerbosity = null; $this->argTimeout = null; $this->argHelp = null; $this->argWarning = null; $this->argCritical = null; } public function registerExpectedStandardArguments($args) { $this->resetArguments(); for ($i=0; $i<strlen($args); $i++) { switch ($args[$i]) { case 'w': $this->addExpectedArgument($this->argWarning = new VNagArgument('w', 'warning', VNagArgument::VALUE_REQUIRED, VNagLang::$argname_value, VNagLang::$warning_range)); break; case 'c': $this->addExpectedArgument($this->argCritical = new VNagArgument('c', 'critical', VNagArgument::VALUE_REQUIRED, VNagLang::$argname_value, VNagLang::$critical_range)); break; case 'V': $this->addExpectedArgument($this->argVersion = new VNagArgument('V', 'version', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$prints_version)); break; case 'v': $this->addExpectedArgument($this->argVerbosity = new VNagArgument('v', 'verbose', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$verbosity_helptext)); break; case 't': $this->addExpectedArgument($this->argTimeout = new VNagArgument('t', 'timeout', VNagArgument::VALUE_REQUIRED, VNagLang::$argname_seconds, VNagLang::$timeout_helptext)); break; case 'h': $this->addExpectedArgument($this->argHelp = new VNagArgument('h', 'help', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$help_helptext)); break; default: $letter = $args[$i]; throw new VNagInvalidStandardArgument(sprintf(VNagLang::$no_standard_arguments_with_letter, $letter)); } } } public function addExpectedArgument($argObj) { $helpObjAddEntryMethod = new ReflectionMethod($this->helpObj, '_addOption'); $helpObjAddEntryMethod->setAccessible(true); $helpObjAddEntryMethod->invoke($this->helpObj, $argObj); $argHandlerAddEntryMethod = new ReflectionMethod($this->argHandler, '_addExpectedArgument'); $argHandlerAddEntryMethod->setAccessible(true); $argHandlerAddEntryMethod->invoke($this->argHandler, $argObj); } protected function createArgumentHandler() { $this->argHandler = new VNagArgumentHandler(); } protected function createHelpObject() { $this->helpObj = new VNagHelp(); } protected function checkInitialized() { if (!$this->initialized) throw new VNagFunctionCallOutsideSession(); } protected function getVerbosityLevel() { $this->checkInitialized(); if (!isset($this->argVerbosity)) { return self::VERBOSITY_SUMMARY; } else { $level = $this->argVerbosity->count(); if ($level > self::MAX_VERBOSITY) $level = self::MAX_VERBOSITY; return $level; } } public function getWarningRange($argumentNumber=0) { $this->checkInitialized(); if (!isset($this->warningRanges[$argumentNumber])) { if (!is_null($this->argWarning)) { $warning = $this->argWarning->getValue(); if (!is_null($warning)) { $vals = explode(',',$warning); foreach ($vals as $number => $val) { if (_empty($val)) { $this->warningRanges[$number] = null; } else { $singleValueBehavior = isset($this->warningSingleValueRangeBehaviors[$number]) ? $this->warningSingleValueRangeBehaviors[$number] : VNag::SINGLEVALUE_RANGE_DEFAULT; $this->warningRanges[$number] = new VNagRange($val, $singleValueBehavior); } } } else { $this->warningRanges[0] = $this->default_warning_range; } } else { return null; } } if (isset($this->warningRanges[$argumentNumber])) { return $this->warningRanges[$argumentNumber]; } else { return null; } } public function getCriticalRange($argumentNumber=0) { $this->checkInitialized(); if (!isset($this->criticalRanges[$argumentNumber])) { if (!is_null($this->argCritical)) { $critical = $this->argCritical->getValue(); if (!is_null($critical)) { $vals = explode(',',$critical); foreach ($vals as $number => $val) { $singleValueBehavior = isset($this->criticalSingleValueRangeBehaviors[$number]) ? $this->criticalSingleValueRangeBehaviors[$number] : VNag::SINGLEVALUE_RANGE_DEFAULT; $this->criticalRanges[$number] = new VNagRange($val, $singleValueBehavior); } } else { $this->criticalRanges[0] = $this->default_critical_range; } } else { return null; } } if (isset($this->criticalRanges[$argumentNumber])) { return $this->criticalRanges[$argumentNumber]; } else { return null; } } public function checkAgainstWarningRange($values, $force=true, $autostatus=true, $argumentNumber=0) { $this->checkInitialized(); if (!$this->getArgumentHandler()->isArgRegistered('w')) { throw new VNagRequiredArgumentNotRegistered('-w'); } $wr = $this->getWarningRange($argumentNumber); if (isset($wr)) { if ($wr->checkAlert($values)) { if ($autostatus) $this->setStatus(VNag::STATUS_WARNING); return true; } else { if ($autostatus) $this->setStatus(VNag::STATUS_OK); return false; } } else { if ($force) { if (($argumentNumber > 0) && (count($this->warningRanges) > 0)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$too_few_warning_ranges, $argumentNumber+1)); } else { throw new VNagRequiredArgumentMissing('-w'); } } } } public function checkAgainstCriticalRange($values, $force=true, $autostatus=true, $argumentNumber=0) { $this->checkInitialized(); if (!$this->getArgumentHandler()->isArgRegistered('c')) { throw new VNagRequiredArgumentNotRegistered('-c'); } $cr = $this->getCriticalRange($argumentNumber); if (isset($cr)) { if ($cr->checkAlert($values)) { if ($autostatus) $this->setStatus(VNag::STATUS_CRITICAL); return true; } else { if ($autostatus) $this->setStatus(VNag::STATUS_OK); return false; } } else { if ($force) { if (($argumentNumber > 0) && (count($this->warningRanges) > 0)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$too_few_critical_ranges, $argumentNumber+1)); } else { throw new VNagRequiredArgumentMissing('-c'); } } } } protected static function getBaddestExitcode($code1, $code2) { return max($code1, $code2); } public static function _shutdownHandler() { if (!self::is_http_mode()) { exit((int)self::$exitcode); } } protected function _exit($code) { self::$exitcode = $this->getBaddestExitcode($code, self::$exitcode); } private $constructed = false; function __construct() { $this->createHelpObject(); $this->createArgumentHandler(); $this->addExpectedArgument($this->argUsage = new VNagArgument('?', '', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$prints_usage)); $this->constructed = true; } function __destruct() { if (Timeouter::started()) { Timeouter::end(); } } public function run() { global $inside_vnag_run; $inside_vnag_run = true; try { if (!$this->constructed) { throw new VNagNotConstructed(VNagLang::$notConstructed); } try { $this->initialized = true; $this->html_before = ''; $this->html_after = ''; $this->setStatus(null, true); $this->messages = array(); register_shutdown_function(array($this, '_shutdownHandler')); if ($this->argHandler->illegalUsage()) { $content = $this->helpObj->printUsagePage(); $this->setStatus(VNag::STATUS_UNKNOWN); if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_visual_output & VNag::OUTPUT_SPECIAL) echo $this->writeVisualHTML($content); if ($this->http_invisible_output & VNag::OUTPUT_SPECIAL) echo $this->writeInvisibleHTML($content); echo $this->html_after; return; } else { echo $content; return $this->_exit($this->status); } } if (!is_null($this->argVersion) && ($this->argVersion->available())) { $content = $this->helpObj->printVersionPage(); $this->setStatus(VNag::STATUS_UNKNOWN); if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_visual_output & VNag::OUTPUT_SPECIAL) echo $this->writeVisualHTML($content); if ($this->http_invisible_output & VNag::OUTPUT_SPECIAL) echo $this->writeInvisibleHTML($content); echo $this->html_after; return; } else { echo $content; return $this->_exit($this->status); } } if (!is_null($this->argHelp) && ($this->argHelp->available())) { $content = $this->helpObj->printHelpPage(); $this->setStatus(VNag::STATUS_UNKNOWN); if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_visual_output & VNag::OUTPUT_SPECIAL) echo $this->writeVisualHTML($content); if ($this->http_invisible_output & VNag::OUTPUT_SPECIAL) echo $this->writeInvisibleHTML($content); echo $this->html_after; return; } else { echo $content; return $this->_exit($this->status); } } $this->getWarningRange(); $this->getCriticalRange(); if (!is_null($this->argTimeout)) { $timeout = $this->argTimeout->getValue(); if (!is_null($timeout)) { Timeouter::start($timeout); } } ob_start(); $init_ob_level = ob_get_level(); try { $this->cbRun(); if (ob_get_level() < $init_ob_level) throw new VNagImplementationErrorException(VNagLang::$output_level_lowered); } finally { while (ob_get_level() > $init_ob_level) @ob_end_clean(); } if (is_null($this->status)) $this->setStatus($this->default_status,true); $outputType = VNag::OUTPUT_NORMAL; } catch (Exception $e) { $this->handleException($e); $outputType = VNag::OUTPUT_EXCEPTION; } if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_invisible_output & $outputType) { echo $this->writeInvisibleHTML(); } if ($this->http_visual_output & $outputType) { echo $this->writeVisualHTML(); } echo $this->html_after; } else { echo $this->getNagiosConsoleText(); return $this->_exit($this->status); } Timeouter::end(); } finally { $inside_vnag_run = false; } } private function getNagiosConsoleText() { $ary_perfdata = $this->getPerformanceData(); $performancedata_first = array_shift($ary_perfdata); $performancedata_rest = implode(' ', $ary_perfdata); $status_text = VNagLang::status($this->status, $this->statusmodel); if (_empty($this->getHeadline())) { $content = $status_text; } else { if ($this->show_status_in_headline) { $content = $status_text.': '.$this->getHeadline(); } else { $content = $this->getHeadline(); } } if (!_empty($performancedata_first)) $content .= '|'.trim($performancedata_first); $content .= "\n"; if (!_empty($this->verbose_info)) { $content .= trim($this->verbose_info); } if (!_empty($performancedata_rest)) $content .= '|'.trim($performancedata_rest); $content .= "\n"; return trim($content)."\n"; } abstract protected function cbRun(); public function addPerformanceData($prefDataObj, $move_to_font=false, $verbosityLevel=VNag::VERBOSITY_SUMMARY) { $this->checkInitialized(); if ((!isset($this->argVerbosity)) && ($verbosityLevel > VNag::VERBOSITY_SUMMARY)) throw new VNagRequiredArgumentNotRegistered('-v'); if (self::getVerbosityLevel() < $verbosityLevel) return false; if ($move_to_font) { array_unshift($this->performanceDataObjects, $prefDataObj); } else { $this->performanceDataObjects[] = $prefDataObj; } return true; } public function getPerformanceData() { $this->checkInitialized(); return $this->performanceDataObjects; } public function removePerformanceData($prefDataObj) { if (($key = array_search($prefDataObj, $this->performanceDataObjects, true)) !== false) { unset($this->performanceDataObjects[$key]); return true; } else { return false; } } public function clearPerformanceData() { $this->performanceDataObjects = array(); } public function getVerboseInfo() { return $this->verbose_info; } public function clearVerboseInfo() { $this->verbose_info = ''; } private function writeVisualHTML($special_content=null) { if (!_empty($special_content)) { $content = $special_content; } else { $content = strtoupper(VNagLang::$status.': '.VNagLang::status($this->status, $this->statusmodel))."\n\n"; $content .= strtoupper(VNagLang::$message).":\n"; $status_text = VNagLang::status($this->status, $this->statusmodel); if (_empty($this->getHeadline())) { $content .= $status_text; } else { if ($this->show_status_in_headline) { $content .= $status_text.': '.trim($this->getHeadline()); } else { $content .= trim($this->getHeadline()); } } $content .= "\n\n"; if (!_empty($this->verbose_info)) { $content .= strtoupper(VNagLang::$verbose_info).":\n".trim($this->verbose_info)."\n\n"; } $perfdata = $this->getPerformanceData(); if (count($perfdata) > 0) { $content .= strtoupper(VNagLang::$performance_data).":\n"; foreach ($perfdata as $pd) { $content .= trim($pd)."\n"; } $content .= "\n"; } } $colorinfo = ''; $status = $this->getStatus(); if ($status == VNag::STATUS_OK) $colorinfo = ' style="background-color:green;color:white;font-weight:bold"'; else if ($status == VNag::STATUS_WARNING) $colorinfo = ' style="background-color:yellow;color:black;font-weight:bold"'; else if ($status == VNag::STATUS_CRITICAL) $colorinfo = ' style="background-color:red;color:white;font-weight:bold"'; else if ($status == VNag::STATUS_ERROR) $colorinfo = ' style="background-color:purple;color:white;font-weight:bold"'; else $colorinfo = ' style="background-color:lightgray;color:black;font-weight:bold"'; $html_content = trim($content); $html_content = htmlentities($html_content); $html_content = str_replace(' ', '&nbsp;', $html_content); $html_content = nl2br($html_content); return '<table border="1" cellspacing="2" cellpadding="2" style="width:100%" class="vnag_table">'. '<tr'.$colorinfo.' class="vnag_title_row">'. '<td>'.VNagLang::$nagios_output.'</td>'. '</tr>'. '<tr class="vnag_message_row">'. '<td><code>'. $html_content. '</code></td>'. '</tr>'. '</table>'; } protected function readInvisibleHTML($html) { $this->checkInitialized(); $doc = new DOMDocument(); @$doc->loadHTML($html); $tags = $doc->getElementsByTagName('script'); foreach ($tags as $tag) { $type = $tag->getAttribute('type'); if ($type !== 'application/json') continue; $json = $tag->nodeValue; if (!$json) continue; $data = @json_decode($json,true); if (!is_array($data)) continue; if (!isset($data['type'])) continue; if ($data['type'] === VNAG_JSONDATA_V1) { if (!isset($data['datasets'])) throw new VNagWebInfoException(VNagLang::$dataset_missing); foreach ($data['datasets'] as $dataset) { $payload = base64_decode($dataset['payload']); if (!$payload) { throw new VNagWebInfoException(VNagLang::$payload_not_base64); } if (isset($dataset['encryption'])) { $cryptInfo = $dataset['encryption']; if (!is_array($cryptInfo)) { throw new VNagWebInfoException(VNagLang::$dataset_encryption_no_array); } $password = is_null($this->password_in) ? '' : $this->password_in; $salt = base64_decode($cryptInfo['salt']); if ($cryptInfo['hash'] != hash('sha256',$salt.$password)) { if ($password == '') { throw new VNagWebInfoException(VNagLang::$require_password); } else { throw new VNagWebInfoException(VNagLang::$wrong_password); } } if (!function_exists('openssl_decrypt')) { throw new VNagException(VNagLang::$openssl_missing); } $payload = openssl_decrypt($payload, $cryptInfo['method'], $password, 0, $cryptInfo['iv']); } if (!is_null($this->pubkey) && ($this->pubkey !== '')) { if (substr($this->pubkey,0,3) === '---') { $public_key = $this->pubkey; } else { if (!file_exists($this->pubkey)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$pubkey_file_not_found, $this->pubkey)); } $public_key = @file_get_contents($this->pubkey); if (!$public_key) { throw new VNagPublicKeyException(sprintf(VNagLang::$pubkey_file_not_readable, $this->pubkey)); } } if (!isset($dataset['signature'])) { throw new VNagSignatureException(VNagLang::$signature_missing); } $signature = base64_decode($dataset['signature']); if (!$signature) { throw new VNagSignatureException(VNagLang::$signature_not_bas64); } if (!function_exists('openssl_verify')) { throw new VNagException(VNagLang::$openssl_missing); } $sign_algo = is_null($this->sign_algo) ? OPENSSL_ALGO_SHA256 : $this->sign_algo; if (!openssl_verify($payload, $signature, $public_key, $sign_algo)) { throw new VNagSignatureException(VNagLang::$signature_invalid); } } $payload = @json_decode($payload,true); if (!$payload) { throw new VNagWebInfoException(VNagLang::$payload_not_json); } if ($payload['id'] == $this->id) { return $payload; } } } } return null; } private function getNextMonitorID($peek=false) { $result = is_null($this->id) ? self::$http_serial_number : $this->id; if (!$peek) { $this->id = null; self::$http_serial_number++; } return $result; } private function writeInvisibleHTML($special_content=null) { $payload['id'] = $this->getNextMonitorID(); $payload['status'] = $this->getStatus(); if (!_empty($special_content)) { $payload['text'] = $special_content; } else { $payload['headline'] = $this->getHeadline(); $payload['verbose_info'] = $this->verbose_info; $payload['performance_data'] = array(); foreach ($this->performanceDataObjects as $perfdata) { $payload['performance_data'][] = (string)$perfdata; } } $payload = json_encode($payload); $dataset = array(); if (!is_null($this->privkey) && ($this->privkey !== '')) { if (!function_exists('openssl_pkey_get_private') || !function_exists('openssl_sign')) { throw new VNagException(VNagLang::$openssl_missing); } if (substr($this->privkey,0,3) === '---') { $pkeyid = @openssl_pkey_get_private($this->privkey, $this->privkey_password); if (!$pkeyid) { throw new VNagPrivateKeyException(sprintf(VNagLang::$privkey_not_readable)); } } else { if (!file_exists($this->privkey)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$privkey_file_not_found, $this->privkey)); } $pkeyid = @openssl_pkey_get_private('file://'.$this->privkey, $this->privkey_password); if (!$pkeyid) { throw new VNagPrivateKeyException(sprintf(VNagLang::$privkey_file_not_readable, $this->privkey)); } } $signature = ''; $sign_algo = is_null($this->sign_algo) ? OPENSSL_ALGO_SHA256 : $this->sign_algo; if (@openssl_sign($payload, $signature, $pkeyid, $sign_algo)) { if (version_compare(PHP_VERSION, '8.0.0') < 0) { openssl_free_key($pkeyid); } $dataset['signature'] = base64_encode($signature); } else { throw new VNagPrivateKeyException(sprintf(VNagLang::$signature_failed)); } } if (!is_null($this->password_out) && ($this->password_out !== '')) { if (!function_exists('openssl_encrypt')) { throw new VNagException(VNagLang::$openssl_missing); } $password = $this->password_out; $method = 'aes-256-ofb'; $iv = substr(hash('sha256', openssl_random_pseudo_bytes(32)), 0, 16); $salt = openssl_random_pseudo_bytes(32); $cryptInfo = array(); $cryptInfo['method'] = $method; $cryptInfo['iv'] = $iv; $cryptInfo['salt'] = base64_encode($salt); $cryptInfo['hash'] = hash('sha256', $salt.$password); $payload = openssl_encrypt($payload, $method, $password, 0, $iv); $dataset['encryption'] = $cryptInfo; } $dataset['payload'] = base64_encode($payload); $json = array(); $json['type'] = VNAG_JSONDATA_V1; $json['datasets'] = array($dataset); return '<script type="application/json">'. json_encode($json). '</script>'; } protected function appendHeadline($msg) { $this->checkInitialized(); if (_empty($msg)) return false; $this->messages[] = $msg; return true; } protected function changeHeadline($msg) { $this->checkInitialized(); if (_empty($msg)) { $this->messages = array(); } else { $this->messages = array($msg); } return true; } public function setHeadline($msg, $append=false, $verbosityLevel=VNag::VERBOSITY_SUMMARY) { $this->checkInitialized(); if ((!isset($this->argVerbosity)) && ($verbosityLevel > VNag::VERBOSITY_SUMMARY)) throw new VNagRequiredArgumentNotRegistered('-v'); if (self::getVerbosityLevel() < $verbosityLevel) $msg = ''; if ($append) { return $this->appendHeadline($msg); } else { return $this->changeHeadline($msg); } } public function getHeadline() { $this->checkInitialized(); return implode(', ', $this->messages); } public function addVerboseMessage($msg, $verbosityLevel=VNag::VERBOSITY_SUMMARY) { $this->checkInitialized(); if (self::getVerbosityLevel() >= $verbosityLevel) { $this->verbose_info .= $msg."\n"; } } public function setStatus($status, $force=false) { $this->checkInitialized(); if (($force) || is_null($this->status) || ($status > $this->status)) { $this->status = $status; } } public function getStatus() { $this->checkInitialized(); return $this->status; } protected static function exceptionText($exception) { $class = get_class($exception); $msg = $exception->getMessage(); if (!_empty($msg)) { return sprintf(VNagLang::$exception_x, $msg, $class); } else { return sprintf(VNagLang::$unhandled_exception_without_msg, $class); } } protected function handleException($exception) { $this->checkInitialized(); if (!VNag::is_http_mode()) { while (ob_get_level() > 0) @ob_end_clean(); } $this->clearVerboseInfo(); $this->clearPerformanceData(); if ($exception instanceof VNagException) { $this->setStatus($exception->getStatus()); } else { $this->setStatus(self::STATUS_ERROR); } $this->setHeadline($this->exceptionText($exception), false); if ($exception instanceof VNagImplementationErrorException) { $this->addVerboseMessage($exception->getTraceAsString(), VNag::VERBOSITY_SUMMARY); } else { if (isset($this->argVerbosity)) { $this->addVerboseMessage($exception->getTraceAsString(), VNag::VERBOSITY_ADDITIONAL_INFORMATION); } else { } } } protected function get_cache_dir() { $homedir = @getenv('HOME'); if ($homedir && is_dir($homedir)) { $try = "$homedir/.vnag/cache"; if (is_dir($try)) return $try; if (@mkdir($try,0777,true)) return $try; } $user = posix_getpwuid(posix_geteuid()); if (isset($user['dir']) && is_dir($user['dir'])) { $homedir = $user['dir']; $try = "$homedir/.vnag/cache"; if (is_dir($try)) return $try; if (@mkdir($try,0777,true)) return $try; } if (isset($user['name']) && is_dir($user['name'])) { $username = $user['name']; $try = "/tmp/vnag/cache"; if (is_dir($try)) return $try; if (@mkdir($try,0777,true)) return $try; } throw new VNagException("Cannot get cache dir"); } protected function url_get_contents($url, $max_cache_time=1*60*60, $context=null) { $cache_file = $this->get_cache_dir().'/'.hash('sha256',$url); if (file_exists($cache_file) && (time()-filemtime($cache_file) < $max_cache_time)) { $cont = @file_get_contents($cache_file); if ($cont === false) throw new Exception("Failed to get contents from $cache_file"); } else { $options = array( 'http'=>array( 'method'=>"GET", 'header'=>"Accept-language: en\r\n" . "User-Agent: Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B334b Safari/531.21.102011-10-16 20:23:10\r\n" ) ); if (is_null($context)) $context = stream_context_create($options); $cont = @file_get_contents($url, false, $context); if ($cont === false) throw new Exception("Failed to get contents from $url"); file_put_contents($cache_file, $cont); } return $cont; } } class VNagException extends Exception { public function getStatus() { return VNag::STATUS_ERROR; } } class VNagTimeoutException extends VNagException {} class VNagWebInfoException extends VNagException {} class VNagSignatureException extends VNagException {} class VNagPublicKeyException extends VNagException {} class VNagPrivateKeyException extends VNagException {} class VNagInvalidArgumentException extends VNagException { public function getStatus() { return VNag::STATUS_UNKNOWN; } } class VNagValueUomPairSyntaxException extends VNagInvalidArgumentException { public function __construct($str) { $e_msg = sprintf(VNagLang::$valueUomPairSyntaxError, $str); parent::__construct($e_msg); } } class VNagInvalidTimeoutException extends VNagInvalidArgumentException {} class VNagInvalidRangeException extends VNagInvalidArgumentException { public function __construct($msg) { $e_msg = VNagLang::$range_is_invalid; if (!_empty($msg)) $e_msg .= ': '.trim($msg); parent::__construct($e_msg); } } class VNagInvalidShortOpt extends VNagImplementationErrorException {} class VNagInvalidLongOpt extends VNagImplementationErrorException {} class VNagInvalidValuePolicy extends VNagImplementationErrorException {} class VNagIllegalStatusModel extends VNagImplementationErrorException {} class VNagNotConstructed extends VNagImplementationErrorException {} class VNagImplementationErrorException extends VNagException {} class VNagInvalidStandardArgument extends VNagImplementationErrorException {} class VNagFunctionCallOutsideSession extends VNagImplementationErrorException {} class VNagIllegalArgumentValuesException extends VNagImplementationErrorException {} class VNagRequiredArgumentNotRegistered extends VNagImplementationErrorException { public function __construct($required_argument) { $e_msg = sprintf(VNagLang::$query_without_expected_argument, $required_argument); parent::__construct($e_msg); } } class VNagRequiredArgumentMissing extends VNagInvalidArgumentException { public function __construct($required_argument) { $e_msg = sprintf(VNagLang::$required_argument_missing, $required_argument); parent::__construct($e_msg); } } class VNagUnknownUomException extends VNagInvalidArgumentException { public function __construct($uom) { $e_msg = sprintf(VNagLang::$perfdata_uom_not_recognized, $uom); parent::__construct($e_msg); } } class VNagNoCompatibleRangeUomFoundException extends VNagException {} class VNagMixedUomsNotImplemented extends VNagInvalidArgumentException { public function __construct($uom1, $uom2) { if (_empty($uom1)) $uom1 = VNagLang::$none; if (_empty($uom2)) $uom2 = VNagLang::$none; $e_msg = sprintf(VNagLang::$perfdata_mixed_uom_not_implemented, $uom1, $uom2); parent::__construct($e_msg); } } class VNagUomConvertException extends VNagInvalidArgumentException { public function __construct($uom1, $uom2) { if (_empty($uom1)) $uom1 = VNagLang::$none; if (_empty($uom2)) $uom2 = VNagLang::$none; $e_msg = sprintf(VNagLang::$convert_x_y_error, $uom1, $uom2); parent::__construct($e_msg); } } class VNagInvalidPerformanceDataException extends VNagInvalidArgumentException { public function __construct($msg) { $e_msg = VNagLang::$performance_data_invalid; if (!_empty($msg)) $e_msg .= ': '.trim($msg); parent::__construct($e_msg); } } class Timeouter { private static $start_time = false; private static $timeout; private static $fired = false; private static $registered = false; private function __construct() { } public static function start($timeout) { if (!is_numeric($timeout) || ($timeout <= 0)) { throw new VNagInvalidTimeoutException(sprintf(VNagLang::$timeout_value_invalid, $timeout)); } self::$start_time = microtime(true); self::$timeout = (float) $timeout; self::$fired = false; if (!self::$registered) { self::$registered = true; register_tick_function(array('Timeouter', 'tick')); } } public static function started() { return self::$registered; } public static function end() { if (self::$registered) { unregister_tick_function(array('Timeouter', 'tick')); self::$registered = false; } } public static function tick() { if ((!self::$fired) && ((microtime(true) - self::$start_time) > self::$timeout)) { self::$fired = true; throw new VNagTimeoutException(VNagLang::$timeout_exception); } } } class VNagArgument { const VALUE_FORBIDDEN = 0; const VALUE_REQUIRED = 1; const VALUE_OPTIONAL = 2; protected $shortopt; protected $longopts; protected $valuePolicy; protected $valueName; protected $helpText; protected $defaultValue = null; protected static $all_short = ''; protected static $all_long = array(); public function getShortOpt() { return $this->shortopt; } public function getLongOpts() { return $this->longopts; } public function getValuePolicy() { return $this->valuePolicy; } public function getValueName() { return $this->valueName; } public function getHelpText() { return $this->helpText; } static private function validateShortOpt($shortopt) { $m = array(); return preg_match('@^[a-zA-Z0-9\\+\\-\\?]$@', $shortopt, $m); } static private function validateLongOpt($longopt) { $m = array(); return preg_match('@^[a-zA-Z0-9\\+\\-\\?]+$@', $longopt, $m); } public function __construct($shortopt, $longopts, $valuePolicy, $valueName, $helpText, $defaultValue=null) { switch ($valuePolicy) { case VNagArgument::VALUE_FORBIDDEN: if (!_empty($valueName)) { throw new VNagImplementationErrorException(sprintf(VNagLang::$value_name_forbidden)); } break; case VNagArgument::VALUE_REQUIRED: if (_empty($valueName)) { throw new VNagImplementationErrorException(sprintf(VNagLang::$value_name_required)); } break; case VNagArgument::VALUE_OPTIONAL: if (_empty($valueName)) { throw new VNagImplementationErrorException(sprintf(VNagLang::$value_name_required)); } break; default: throw new VNagInvalidValuePolicy(sprintf(VNagLang::$illegal_valuepolicy, $valuePolicy)); } if (!_empty($shortopt)) { if (!self::validateShortOpt($shortopt)) { throw new VNagInvalidShortOpt(sprintf(VNagLang::$illegal_shortopt, $shortopt)); } } if (is_array($longopts)) { foreach ($longopts as $longopt) { if (!self::validateLongOpt($longopt)) { throw new VNagInvalidLongOpt(sprintf(VNagLang::$illegal_longopt, $longopt)); } } } else if (!_empty($longopts)) { if (!self::validateLongOpt($longopts)) { throw new VNagInvalidLongOpt(sprintf(VNagLang::$illegal_longopt, $longopts)); } $longopts = array($longopts); } else { $longopts = array(); } switch ($valuePolicy) { case VNagArgument::VALUE_FORBIDDEN: $policyApdx = ''; break; case VNagArgument::VALUE_REQUIRED: $policyApdx = ':'; break; case VNagArgument::VALUE_OPTIONAL: $policyApdx = '::'; break; default: throw new VNagInvalidValuePolicy(sprintf(VNagLang::$illegal_valuepolicy, $valuePolicy)); } if ((!is_null($shortopt)) && ($shortopt != '?')) self::$all_short .= $shortopt.$policyApdx; if (is_array($longopts)) { foreach ($longopts as $longopt) { self::$all_long[] = $longopt.$policyApdx; } } $this->shortopt = $shortopt; $this->longopts = $longopts; $this->valuePolicy = $valuePolicy; $this->valueName = $valueName; $this->helpText = $helpText; $this->defaultValue = $defaultValue; } protected static function getOptions() { global $OVERWRITE_ARGUMENTS; if (!is_null($OVERWRITE_ARGUMENTS)) { return $OVERWRITE_ARGUMENTS; } else if (VNag::is_http_mode()) { return $_REQUEST; } else { return getopt(self::$all_short, self::$all_long); } } public function count() { $options = self::getOptions(); $count = 0; if (isset($options[$this->shortopt])) { if (is_array($options[$this->shortopt])) { $count += count($options[$this->shortopt]); } else { $count += 1; } } if (!is_null($this->longopts)) { foreach ($this->longopts as $longopt) { if (isset($options[$longopt])) { if (is_array($options[$longopt])) { $count += count($options[$longopt]); } else { $count += 1; } } } } return $count; } public function available() { $options = self::getOptions(); if (isset($options[$this->shortopt])) return true; if (!is_null($this->longopts)) { foreach ($this->longopts as $longopt) { if (isset($options[$longopt])) return true; } } return false; } public function require() { if (!$this->available() && is_null($this->defaultValue)) { $opt = $this->shortopt; $opt = !_empty($opt) ? '-'.$opt : (isset($this->longopts[0]) ? '--'.$this->longopts[0] : '?'); throw new VNagRequiredArgumentMissing($opt); } } public function getValue() { $options = self::getOptions(); if (isset($options[$this->shortopt])) { $x = $options[$this->shortopt]; if (is_array($x) && (count($x) <= 1)) $options[$this->shortopt] = $options[$this->shortopt][0]; return $options[$this->shortopt]; } if (!is_null($this->longopts)) { foreach ($this->longopts as $longopt) { if (isset($options[$longopt])) { $x = $options[$longopt]; if (is_array($x) && (count($x) <= 1)) $options[$longopt] = $options[$longopt][0]; return $options[$longopt]; } } } return $this->defaultValue; } } class VNagArgumentHandler { protected $expectedArgs = array(); protected function _addExpectedArgument($argObj) { if ($argObj->getShortOpt() == '?') return false; if ($argObj->getShortOpt() == '-') return false; if ($argObj->getShortOpt() == '+') return false; $this->expectedArgs[] = $argObj; return true; } public function getArgumentObj($shortopt) { foreach ($this->expectedArgs as $argObj) { if ($argObj->getShortOpt() == $shortopt) return $argObj; } return null; } public function isArgRegistered($shortopt) { return !is_null($this->getArgumentObj($shortopt)); } public function illegalUsage() { global $argv; return (isset($argv[1])) && (($argv[1] == '-?') || ($argv[1] == '/?')); } } class VNagRange { public $start; public $end; public $warnInsideRange; public function __construct($rangeDef, $singleValueBehavior=VNag::SINGLEVALUE_RANGE_DEFAULT) { $m = array(); if (!preg_match('|^(@){0,1}([^:]+)(:){0,1}(.*)$|', $rangeDef, $m)) { throw new VNagInvalidRangeException(sprintf(VNagLang::$range_invalid_syntax, $rangeDef)); } $this->warnInsideRange = $m[1] === '@'; $this->start = null; $this->end = null; if ($m[3] === ':') { if ($m[2] === '~') { $this->start = '-inf'; } else { $this->start = new VNagValueUomPair($m[2]); } if (_empty($m[4])) { $this->end = 'inf'; } else { $this->end = new VNagValueUomPair($m[4]); } } else { assert(_empty($m[4])); assert(!_empty($m[2])); $x = $m[2]; if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_DEFAULT) { $this->start = new VNagValueUomPair('0'.((new VNagValueUomPair($x))->getUom())); $this->end = new VNagValueUomPair($x); } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_GT_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 0; $this->start = '-inf'; $this->end = new VNagValueUomPair($x); } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_GE_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 1; $this->start = new VNagValueUomPair($x); $this->end = 'inf'; } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_LT_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 0; $this->start = new VNagValueUomPair($x); $this->end = 'inf'; } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_LE_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 1; $this->start = '-inf'; $this->end = new VNagValueUomPair($x); } else { throw new VNagException(VNagLang::$illegalSingleValueBehavior); } } if (is_null($this->start)) { throw new VNagInvalidRangeException(VNagLang::$invalid_start_value); } if (is_null($this->end)) { throw new VNagInvalidRangeException(VNagLang::$invalid_end_value); } if (($this->start instanceof VNagValueUomPair) && ($this->end instanceof VNagValueUomPair) && (VNagValueUomPair::compare($this->start,$this->end) > 0)) { throw new VNagInvalidRangeException(VNagLang::$start_is_greater_than_end); } } public function __toString() { $ret = ''; if ($this->warnInsideRange) { $ret = '@'; } if ($this->start === '-inf') { $ret .= '~'; } else { $ret .= $this->start; } $ret .= ':'; if ($this->end !== 'inf') { $ret .= $this->end; } return $ret; } public function checkAlert($values) { $compatibleCount = 0; if (!is_array($values)) $values = array($values); foreach ($values as $value) { if (!($value instanceof VNagValueUomPair)) $value = new VNagValueUomPair($value); assert(($this->start === '-inf') || ($this->start instanceof VNagValueUomPair)); assert(($this->end === 'inf' ) || ($this->end instanceof VNagValueUomPair)); if (($this->start !== '-inf') && (!$this->start->compatibleWith($value))) continue; if (($this->end !== 'inf') && (!$this->end->compatibleWith($value))) continue; $compatibleCount++; if ($this->warnInsideRange) { return (($this->start === '-inf') || (VNagValueUomPair::compare($value,$this->start) >= 0)) && (($this->end === 'inf') || (VNagValueUomPair::compare($value,$this->end) <= 0)); } else { return (($this->start !== '-inf') && (VNagValueUomPair::compare($value,$this->start) < 0)) || (($this->end !== 'inf') && (VNagValueUomPair::compare($value,$this->end) > 0)); } } if ((count($values) > 0) and ($compatibleCount == 0)) { throw new VNagNoCompatibleRangeUomFoundException(VNagLang::$no_compatible_range_uom_found); } return false; } } class VNagValueUomPair { protected $value; protected $uom; public $roundTo = -1; public function isRelative() { return $this->uom === '%'; } public function getValue() { return $this->value; } public function getUom() { return $this->uom; } public function __toString() { if ($this->roundTo == -1) { return $this->value.$this->uom; } else { return round($this->value,$this->roundTo).$this->uom; } } public function __construct($str) { $m = array(); if (!preg_match('/^([\d\.]+)(.*)$/ism', $str, $m)) { throw new VNagValueUomPairSyntaxException($str); } $this->value = $m[1]; $this->uom = isset($m[2]) ? $m[2] : ''; if (!self::isKnownUOM($this->uom)) { throw new VNagUnknownUomException($this->uom); } } public static function isKnownUOM(string $uom) { $no_unit = ($uom === ''); $seconds = ($uom === 's') || ($uom === 'ms') || ($uom === 'us'); $percentage = ($uom === '%'); $bytes = ($uom === 'B') || ($uom === 'KB') || ($uom === 'MB') || ($uom === 'GB') || ($uom === 'TB'); $counter = ($uom === 'c'); return ($no_unit || $seconds || $percentage || $bytes || $counter); } public function normalize($target=null) { $res = clone $this; if ($res->uom === 'ms') { $res->uom = 's'; $res->value /= 1000; } if ($res->uom === 'us') { $res->uom = 's'; $res->value /= 1000 * 1000; } if ($res->uom === 'B') { $res->uom = 'MB'; $res->value /= 1024 * 1024; } if ($res->uom === 'KB') { $res->uom = 'MB'; $res->value /= 1024; } if ($res->uom === 'GB') { $res->uom = 'MB'; $res->value *= 1024; } if ($res->uom === 'TB') { $res->uom = 'MB'; $res->value *= 1024 * 1024; } if ($res->uom === 'c') { $res->uom = ''; } if (!is_null($target)) { if ($res->uom == 'MB') { if ($target == 'B') { $res->uom = 'B'; $res->value *= 1024 * 1024; } else if ($target == 'KB') { $res->uom = 'KB'; $res->value *= 1024; } else if ($target == 'MB') { $res->uom = 'MB'; $res->value *= 1; } else if ($target == 'GB') { $res->uom = 'GB'; $res->value /= 1024; } else if ($target == 'TB') { $res->uom = 'TB'; $res->value /= 1024 * 1024; } else { throw new VNagUomConvertException($res->uom, $target); } } else if ($res->uom == 's') { if ($target == 's') { $res->uom = 's'; $res->value /= 1; } else if ($target == 'ms') { $res->uom = 'ms'; $res->value /= 1000; } else if ($target == 'us') { $res->uom = 'us'; $res->value /= 1000 * 1000; } else { throw new VNagUomConvertException($res->uom, $target); } } else { throw new VNagUomConvertException($res->uom, $target); } } return $res; } public function compatibleWith(VNagValueUomPair $other) { $a = $this->normalize(); $b = $other->normalize(); return ($a->uom == $b->uom); } public static function compare(VNagValueUomPair $left, VNagValueUomPair $right) { $a = $left->normalize(); $b = $right->normalize(); if ($a->uom != $b->uom) throw new VNagMixedUomsNotImplemented($a->uom, $b->uom); if ($a->value > $b->value) return 1; if ($a->value == $b->value) return 0; if ($a->value < $b->value) return -1; } } class VNagPerformanceData { protected $label; protected $value; protected $warn = null; protected $crit = null; protected $min = null; protected $max = null; public static function createByString($perfdata) { $perfdata = trim($perfdata); $ary = explode('=',$perfdata); if (count($ary) != 2) { throw new VNagInvalidPerformanceDataException(sprintf(VNagLang::$perfdata_line_invalid, $perfdata)); } $label = $ary[0]; $bry = explode(';',$ary[1]); if (substr($label,0,1) === "'") $label = substr($label, 1, strlen($label)-2); $value = $bry[0]; $warn = isset($bry[1]) ? $bry[1] : null; $crit = isset($bry[2]) ? $bry[2] : null; $min = isset($bry[3]) ? $bry[3] : null; $max = isset($bry[4]) ? $bry[4] : null; return new self($label, $value, $warn, $crit, $min, $max); } public function __construct($label, $value, $warn=null, $crit=null, $min=null, $max=null) { if (strpos($label, '=') !== false) throw new VNagInvalidPerformanceDataException(VNagLang::$perfdata_label_equal_sign_forbidden); $label = str_replace("'", "''", $label); $m = array(); if ((!_empty($min)) && (!preg_match('|^[-0-9\\.]+$|', $min, $m))) { throw new VNagInvalidPerformanceDataException(VNagLang::$perfdata_min_must_be_in_class); } if ((!_empty($max)) && (!preg_match('|^[-0-9\\.]+$|', $max, $m))) { throw new VNagInvalidPerformanceDataException(VNagLang::$perfdata_max_must_be_in_class); } $this->label = $label; $this->value = ($value == 'U') ? 'U' : new VNagValueUomPair($value); $this->warn = $warn; $this->crit = $crit; $this->min = $min; $this->max = $max; } public function __toString() { $label = $this->label; $value = $this->value; $warn = $this->warn; $crit = $this->crit; $min = $this->min; $max = $this->max; $label = str_replace("''", "'", $label); return "'$label'=$value". ';'.(is_null($warn) ? '' : $warn). ';'.(is_null($crit) ? '' : $crit). ';'.(is_null($min) ? '' : $min). ';'.(is_null($max) ? '' : $max); } } class VNagHelp { public $word_wrap_width = 80; public $argument_indent = 7; public function printUsagePage() { $usage = $this->getUsage(); if (_empty($usage)) { $usage = VNagLang::$no_syntax_defined; } return trim($usage)."\n"; } public function printVersionPage() { $out = trim($this->getNameAndVersion())."\n"; if ($this->word_wrap_width > 0) $out = wordwrap($out, $this->word_wrap_width, "\n", false); return $out; } static private function _conditionalLine($line, $terminator='', $prefix='') { if (!_empty($line)) { return trim($line).$terminator; } return ''; } public function printHelpPage() { $out = ''; $out .= self::_conditionalLine($this->getNameAndVersion(), "\n"); $out .= self::_conditionalLine($this->getCopyright(), "\n"); $out .= ($out != '') ? "\n" : ''; $out .= self::_conditionalLine($this->getShortDescription(), "\n\n\n"); $out .= self::_conditionalLine($this->getUsage(), "\n\n"); $out .= VNagLang::$options."\n"; foreach ($this->options as $argObj) { $out .= $this->printArgumentHelp($argObj); } $out .= self::_conditionalLine($this->getFootNotes(), "\n\n", "\n"); if ($this->word_wrap_width > 0) $out = wordwrap($out, $this->word_wrap_width, "\n", false); return $out; } protected $options = array(); protected function _addOption($argObj) { $this->options[] = $argObj; } protected function printArgumentHelp($argObj) { $identifiers = array(); $shortopt = $argObj->getShortopt(); if (!_empty($shortopt)) $identifiers[] = '-'.$shortopt; $longopts = $argObj->getLongopts(); if (!is_null($longopts)) { foreach ($longopts as $longopt) { if (!_empty($longopt)) $identifiers[] = '--'.$longopt; } } if (count($identifiers) == 0) return; $valueName = $argObj->getValueName(); $arginfo = ''; switch ($argObj->getValuePolicy()) { case VNagArgument::VALUE_FORBIDDEN: $arginfo = ''; break; case VNagArgument::VALUE_REQUIRED: $arginfo = '='.$valueName; break; case VNagArgument::VALUE_OPTIONAL: $arginfo = '[='.$valueName.']'; break; } $out = ''; $out .= implode(', ', $identifiers).$arginfo."\n"; $content = trim($argObj->getHelpText()); if ($this->word_wrap_width > 0) $content = wordwrap($content, $this->word_wrap_width-$this->argument_indent, "\n", false); $lines = explode("\n", $content); foreach ($lines as $line) { $out .= str_repeat(' ', $this->argument_indent).$line."\n"; } $out .= "\n"; return $out; } protected $pluginName; public function setPluginName($pluginName) { $this->pluginName = $this->replaceStuff($pluginName); } public function getPluginName() { if (_empty($this->pluginName)) { global $argv; return basename($argv[0]); } else { return $this->pluginName; } } protected $version; public function setVersion($version) { $this->version = $this->replaceStuff($version); } public function getVersion() { return $this->version; } public function getNameAndVersion() { $ret = $this->getPluginName(); if (_empty($ret)) return null; $ver = $this->getVersion(); if (!_empty($ver)) { $ret = sprintf(VNagLang::$x_version_x, $ret, $ver); } $ret = trim($ret); return $ret; } protected $copyright; public function setCopyright($copyright) { $this->copyright = $this->replaceStuff($copyright); } private function getVNagCopyright() { if (VNag::is_http_mode()) { $vts_email = 'www.viathinksoft.com'; } else { $vts_email = base64_decode('aW5mb0B2aWF0aGlua3NvZnQuZGU='); } return "VNag Framework ".VNag::VNAG_VERSION." (C) 2014-".date('Y')." ViaThinkSoft <$vts_email>"; } public function getCopyright() { if (_empty($this->copyright)) { return sprintf(VNagLang::$plugin_uses, $this->getVNagCopyright()); } else { return trim($this->copyright)."\n".sprintf(VNagLang::$uses, $this->getVNagCopyright()); } } protected $shortDescription; public function setShortDescription($shortDescription) { $this->shortDescription = $this->replaceStuff($shortDescription); } public function getShortDescription() { if (_empty($this->shortDescription)) { return null; } else { $content = $this->shortDescription; if ($this->word_wrap_width > 0) $content = wordwrap($content, $this->word_wrap_width, "\n", false); return $content; } } protected function replaceStuff($text) { global $argv; if (php_sapi_name() == 'cli') { $text = str_replace('$SCRIPTNAME$', $argv[0], $text); } else { $text = str_replace('$SCRIPTNAME$', basename($_SERVER['SCRIPT_NAME']), $text); } $text = str_replace('$CURYEAR$', date('Y'), $text); return $text; } protected $syntax; public function setSyntax($syntax) { $syntax = $this->replaceStuff($syntax); $this->syntax = $syntax; } public function getUsage() { if (_empty($this->syntax)) { return null; } else { return sprintf(VNagLang::$usage_x, $this->syntax); } } protected $footNotes; public function setFootNotes($footNotes) { $this->footNotes = $this->replaceStuff($footNotes); } public function getFootNotes() { return $this->footNotes; } } class VNagLang { public static function status($code, $statusmodel) { switch ($statusmodel) { case VNag::STATUSMODEL_SERVICE: switch ($code) { case VNag::STATUS_OK: return 'OK'; case VNag::STATUS_WARNING: return 'Warning'; case VNag::STATUS_CRITICAL: return 'Critical'; case VNag::STATUS_UNKNOWN: return 'Unknown'; default: return sprintf('Error (%d)', $code); } case VNag::STATUSMODEL_HOST: switch ($code) { case VNag::STATUS_UP: return 'Up'; case VNag::STATUS_DOWN: return 'Down'; default: return sprintf('Maintain last state (%d)', $code); } default: throw new VNagIllegalStatusModel(sprintf(self::$illegal_statusmodel, $statusmodel)); } } static $nagios_output = 'VNag-Output'; static $verbose_info = 'Verbose information'; static $status = 'Status'; static $message = 'Message'; static $performance_data = 'Performance data'; static $status_ok = 'OK'; static $status_warn = 'Warning'; static $status_critical = 'Critical'; static $status_unknown = 'Unknown'; static $status_error = 'Error'; static $unhandled_exception_without_msg = "Unhandled exception of type %s"; static $plugin_uses = 'This plugin uses %s'; static $uses = 'uses %s'; static $x_version_x = '%s, version %s'; static $argname_value = 'value'; static $argname_seconds = 'seconds'; static $query_without_expected_argument = "The argument '%s' is queried, but was not added to the list of expected arguments. Please contact the plugin author."; static $required_argument_missing = "The argument '%s' is required."; static $performance_data_invalid = 'Performance data invalid.'; static $no_standard_arguments_with_letter = "No standard argument with letter '%s' exists."; static $invalid_start_value = 'Invalid start value.'; static $invalid_end_value = 'Invalid end value.'; static $start_is_greater_than_end = 'Start is greater than end value.'; static $value_name_forbidden = "Implementation error: You may not define a value name for the argument, because the value policy is VALUE_FORBIDDEN."; static $value_name_required = "Implementation error: Please define a name for the argument (so it can be shown in the help page)."; static $illegal_shortopt = "Illegal shortopt '-%s'."; static $illegal_longopt = "Illegal longopt '--%s'."; static $illegal_valuepolicy = "valuePolicy has illegal value '%s'."; static $range_invalid_syntax = "Syntax error in range '%s'."; static $timeout_value_invalid = "Timeout value '%s' is invalid."; static $range_is_invalid = 'Range is invalid.'; static $timeout_exception = 'Timeout!'; static $perfdata_label_equal_sign_forbidden = 'Label may not contain an equal sign.'; static $perfdata_value_must_be_in_class = 'Value must be in class [-0-9.] or be \'U\' if the actual value can\'t be determined.'; static $perfdata_min_must_be_in_class = 'Min must be in class [-0-9.] or empty.'; static $perfdata_max_must_be_in_class = 'Max must be in class [-0-9.] or empty.'; static $perfdata_uom_not_recognized = 'UOM (unit of measurement) "%s" is not recognized.'; static $perfdata_mixed_uom_not_implemented = 'Mixed UOMs (%s and %s) are currently not supported.'; static $no_compatible_range_uom_found = 'Measured values are not compatible with the provided warning/critical parameter. Most likely, the UOM is incompatible.'; static $exception_x = '%s (%s)'; static $no_syntax_defined = 'The author of this plugin has not defined a syntax for this plugin.'; static $usage_x = "Usage:\n%s"; static $options = "Options:"; static $illegal_statusmodel = "Invalid statusmodel %d."; static $none = '[none]'; static $valueUomPairSyntaxError = 'Syntax error at "%s". Syntax must be Value[UOM].'; static $too_few_warning_ranges = "You have too few warning ranges (currently trying to get element %d)."; static $too_few_critical_ranges = "You have too few critical ranges (currently trying to get element %d)."; static $dataset_missing = 'Dataset missing.'; static $payload_not_base64 = 'The payload is not valid Base64.'; static $payload_not_json = 'The payload is not valid JSON.'; static $signature_missing = 'The signature is missing.'; static $signature_not_bas64 = 'The signature is not valid Base64.'; static $signature_invalid = 'The signature is invalid. The connection might have been tampered, or a different key is used.'; static $pubkey_file_not_found = "Public key file %s was not found."; static $pubkey_file_not_readable = "Public key file %s is not readable."; static $privkey_file_not_found = "Private key file %s was not found."; static $privkey_not_readable = "Private key is not readable."; static $privkey_file_not_readable = "Private key file %s is not readable."; static $signature_failed = "Signature failed."; static $perfdata_line_invalid = "Performance data line %s is invalid."; static $singlevalue_unexpected_at_symbol = 'This plugin does not allow the @-symbol at ranges for single values.'; static $illegalSingleValueBehavior = "Illegal value for 'singleValueBehavior'. Please contact the creator of the plugin."; static $dataset_encryption_no_array = 'Dataset encryption information invalid.'; static $require_password = 'This resource is protected with a password. Please provide a password.'; static $wrong_password = 'This resource is protected with a password. You have provided the wrong password, or it was changed.'; static $convert_x_y_error = 'Cannot convert from UOM %s to UOM %s.'; static $php_error = 'PHP has detected an error in the plugin. Please contact the plugin author.'; static $output_level_lowered = "Output Buffer level lowered during cbRun(). Please contact the plugin author."; static $openssl_missing = "OpenSSL is missing. Therefore, encryption and signatures are not available."; static $warning_range = 'Warning range'; static $critical_range = 'Critical range'; static $prints_version = 'Prints version'; static $verbosity_helptext = 'Verbosity -v, -vv or -vvv'; static $timeout_helptext = 'Sets timeout in seconds'; static $help_helptext = 'Prints help page'; static $prints_usage = 'Prints usage'; static $notConstructed = 'Parent constructor not called with parent::__construct().'; } function vnagErrorHandler($errorkind, $errortext, $file, $line) { global $inside_vnag_run; if (!$inside_vnag_run && VNag::is_http_mode()) { return false; } if (!(error_reporting() & $errorkind)) { return true; } if (defined('E_ERROR') && ($errorkind == E_ERROR)) $errorkind = 'Error'; if (defined('E_WARNING') && ($errorkind == E_WARNING)) $errorkind = 'Warning'; if (defined('E_PARSE') && ($errorkind == E_PARSE)) $errorkind = 'Parse'; if (defined('E_NOTICE') && ($errorkind == E_NOTICE)) $errorkind = 'Notice'; if (defined('E_CORE_ERROR') && ($errorkind == E_CORE_ERROR)) $errorkind = 'Core Error'; if (defined('E_CORE_WARNING') && ($errorkind == E_CORE_WARNING)) $errorkind = 'Core Warning'; if (defined('E_COMPILE_ERROR') && ($errorkind == E_COMPILE_ERROR)) $errorkind = 'Compile Error'; if (defined('E_COMPILE_WARNING') && ($errorkind == E_COMPILE_WARNING)) $errorkind = 'Compile Warning'; if (defined('E_USER_ERROR') && ($errorkind == E_USER_ERROR)) $errorkind = 'User Error'; if (defined('E_USER_WARNING') && ($errorkind == E_USER_WARNING)) $errorkind = 'User Warning'; if (defined('E_USER_NOTICE') && ($errorkind == E_USER_NOTICE)) $errorkind = 'User Notice'; if (defined('E_STRICT') && ($errorkind == E_STRICT)) $errorkind = 'Strict'; if (defined('E_RECOVERABLE_ERROR') && ($errorkind == E_RECOVERABLE_ERROR)) $errorkind = 'Recoverable Error'; if (defined('E_DEPRECATED') && ($errorkind == E_DEPRECATED)) $errorkind = 'Deprecated'; if (defined('E_USER_DEPRECATED') && ($errorkind == E_USER_DEPRECATED)) $errorkind = 'User Deprecated'; throw new VNagException(VNagLang::$php_error . " $errortext at $file:$line (kind $errorkind)"); } $inside_vnag_run = false; $old_error_handler = set_error_handler("vnagErrorHandler"); <?php
declare(ticks=1); class PhpBbVersionCheck extends VNag { protected $argSystemDir = null; public function __construct() { parent::__construct(); $this->registerExpectedStandardArguments('Vvht'); $this->getHelpManager()->setPluginName('check_phpbb_version'); $this->getHelpManager()->setVersion('2023-10-13'); $this->getHelpManager()->setShortDescription('This plugin checks if a local phpBB system has the latest version installed.'); $this->getHelpManager()->setCopyright('Copyright (C) 2011-$CURYEAR$ Daniel Marschall, ViaThinkSoft.'); $this->getHelpManager()->setSyntax('$SCRIPTNAME$ [-d <directory>]'); $this->getHelpManager()->setFootNotes('If you encounter bugs, please contact ViaThinkSoft at www.viathinksoft.com'); $this->addExpectedArgument($this->argSystemDir = new VNagArgument('d', 'directory', VNagArgument::VALUE_REQUIRED, 'phpBBPath', 'The local directory where your phpBB installation is located.')); } protected function get_local_version($path) { $path = realpath($path) === false ? $path : realpath($path); $cont = @file_get_contents("$path/includes/constants.php"); if ($cont !== false) { if (preg_match("@define\('PHPBB_VERSION', '(.*)'\);@ismU", $cont, $m)) return $m[1]; } $cont = @file_get_contents("$path/docs/INSTALL.html"); if ($cont !== false) { if (preg_match("@phpBB-(.*)_to_(.*)\.(zip|patch|tar)@ismU", $cont, $m)) return $m[2]; } throw new VNagException('Could not determinate current phpBB version in "'.$path.'".'); } protected function isVersionCurrentStable($json, $version) { foreach ($json['stable'] as $major => $data) { if ($data['current'] == $version) return true; } return false; } protected function isVersionCurrentUnstable($json, $version) { foreach ($json['unstable'] as $major => $data) { if ($data['current'] == $version) return true; } return false; } protected function cbRun($optional_args=array()) { $system_dir = $this->argSystemDir->getValue(); if (empty($system_dir)) { throw new VNagException("Please specify the directory of the phpBB installation."); } $system_dir = realpath($system_dir) === false ? $system_dir : realpath($system_dir); if (!is_dir($system_dir)) { throw new VNagException('Directory "'.$system_dir.'" not found.'); } $versionCheckUrl = "https://version.phpbb.com/phpbb/versions.json"; $cont = $this->url_get_contents($versionCheckUrl); if ($cont === false) { throw new VNagException('Could not determinate latest phpBB version'); } $json = @json_decode($cont,true); if ($json === false) { throw new VNagException('Could not determinate latest phpBB version'); } $version = $this->get_local_version($system_dir); if ($this->isVersionCurrentStable($json, $version)) { $this->setStatus(VNag::STATUS_OK); $this->setHeadline("Version $version (Latest Stable version) at $system_dir", true); } else if ($this->isVersionCurrentUnstable($json, $version)) { $this->setStatus(VNag::STATUS_OK); $this->setHeadline("Version $version (Latest Unstable version) at $system_dir", true); } else { $this->setStatus(VNag::STATUS_WARNING); $this->setHeadline("Version $version (Old version!) at $system_dir", true); } $total_extensions = 0; $unknown_extensions = 0; $old_extensions = 0; $current_extensions = 0; $check_errors = 0; $ext_json_files = glob($system_dir.'/ext/*/*/composer.json'); foreach ($ext_json_files as $ext_json_file) { $cont = @file_get_contents($ext_json_file); if ($cont === false) continue; $ext_json_client = @json_decode($cont,true); if ($ext_json_client === false) continue; $extname = $ext_json_client['name']; $version = $ext_json_client['version']; $total_extensions++; if (isset($ext_json_client['extra']) && isset($ext_json_client['extra']['version-check'])) { if (!isset($ext_json_client['extra']['version-check']['ssl'])) $ext_json_client['extra']['version-check']['ssl'] = false; $versionCheckUrl = $ext_json_client['extra']['version-check']['ssl'] ? 'https://' : 'http://'; $versionCheckUrl .= $ext_json_client['extra']['version-check']['host']; $versionCheckUrl .= $ext_json_client['extra']['version-check']['directory'].'/'; $versionCheckUrl .= $ext_json_client['extra']['version-check']['filename']; $cont = @file_get_contents($versionCheckUrl); if ($cont === false) { $this->setStatus(VNag::STATUS_WARNING); $this->addVerboseMessage("Extension $extname : Cannot reach update-server (Version $version)!", VNag::VERBOSITY_SUMMARY); $check_errors++; continue; } $json = @json_decode($cont,true); if ($json === false) { $this->setStatus(VNag::STATUS_WARNING); $this->addVerboseMessage("Extension $extname : Cannot reach update-server (Version $version)!", VNag::VERBOSITY_SUMMARY); $check_errors++; continue; } if ($this->isVersionCurrentStable($json, $version)) { $this->setStatus(VNag::STATUS_OK); $this->addVerboseMessage("Extension $extname : Version $version is latest stable.", VNag::VERBOSITY_ADDITIONAL_INFORMATION); $current_extensions++; } else if ($this->isVersionCurrentUnstable($json, $version)) { $this->setStatus(VNag::STATUS_OK); $this->addVerboseMessage("Extension $extname : Version $version is latest unstable.", VNag::VERBOSITY_ADDITIONAL_INFORMATION); $current_extensions++; } else { $this->setStatus(VNag::STATUS_WARNING); $this->addVerboseMessage("Extension $extname : Version $version is outdated!", VNag::VERBOSITY_SUMMARY); $old_extensions++; } } else { $this->addVerboseMessage("Extension $extname (version $version) does not have any update server information.", VNag::VERBOSITY_ADDITIONAL_INFORMATION); $unknown_extensions++; } } if ($old_extensions > 0) { $this->setHeadline("$old_extensions extensions require an update", true); } if ($check_errors > 0) { $this->setHeadline("$old_extensions extensions can't be checked (update server error)", true); } $this->addVerboseMessage("$total_extensions extensions total, $current_extensions up-to-date, $old_extensions outdated, $unknown_extensions without update information, $check_errors update server errors", VNag::VERBOSITY_SUMMARY); } } <?php
declare(ticks=1); require_once __DIR__ . '/../../framework/vnag_framework.inc.php'; require_once __DIR__ . '/PhpBbVersionCheck.class.php'; $job = new PhpBbVersionCheck(); $job->run(); unset($job);
ÃRqbr™˜õ-ðu_WæÿNï{=&ÊÕ=„£t ê$¥§¨UNhµA'ø4y–Ä„½HŠt­‘ˆ^rÈܸGBMB
declare(ticks=1); require_once __DIR__ . '/../../framework/vnag_framework.inc.php'; require_once __DIR__ . '/PhpBbVersionCheck.class.php'; $job = new PhpBbVersionCheck(); $job->run(); unset($job); ›ˆÊêDf2Ÿ¼z­rSÌcö´´^K‘élH] òrVkî#Orc¹8”]ªP"[1@kú¹ú]~Z<GP­x¦÷vWGBMB
/trunk/bin/phpmyadmin_version.phar
-ùýL;¤8plugins/phpmyadmin_version/check_phpmyadmin_version.phpsÖzï*eÖxÁ’¤<?php ?>
-<?php
+ùýL;¤8plugins/phpmyadmin_version/check_phpmyadmin_version.phpsÖ» +eÖxÁ’¤<?php
if (!VNag::is_http_mode()) error_reporting(E_ALL); declare(ticks=1); set_time_limit(0); define('VNAG_JSONDATA_V1', 'oid:1.3.6.1.4.1.37476.2.3.1.1'); $OVERWRITE_ARGUMENTS = null; function _empty($x) { return is_null($x) || (trim($x) == ''); } abstract class VNag { const VNAG_VERSION = '2023-10-13'; const STATUS_OK = 0; const STATUS_WARNING = 1; const STATUS_CRITICAL = 2; const STATUS_UNKNOWN = 3; const STATUS_ERROR = 4; const STATUS_UP = 0; const STATUS_DOWN = 1; const STATUS_MAINTAIN = 2; const VERBOSITY_SUMMARY = 0; const VERBOSITY_ADDITIONAL_INFORMATION = 1; const VERBOSITY_CONFIGURATION_DEBUG = 2; const VERBOSITY_PLUGIN_DEBUG = 3; const MAX_VERBOSITY = self::VERBOSITY_PLUGIN_DEBUG; const STATUSMODEL_SERVICE = 0; const STATUSMODEL_HOST = 1; private $initialized = false; private $status = null; private $messages = array(); private $verbose_info = ''; private $warningRanges = array(); private $criticalRanges = array(); private $performanceDataObjects = array(); private static $exitcode = 0; private $helpObj = null; private $argHandler = null; const OUTPUT_NEVER = 0; const OUTPUT_SPECIAL = 1; const OUTPUT_NORMAL = 2; const OUTPUT_EXCEPTION = 4; const OUTPUT_ALWAYS = 7; public $http_visual_output = self::OUTPUT_ALWAYS; public $http_invisible_output = self::OUTPUT_ALWAYS; protected $html_before = ''; protected $html_after = ''; protected $statusmodel = self::STATUSMODEL_SERVICE; protected $show_status_in_headline = true; protected $default_status = self::STATUS_UNKNOWN; protected $default_warning_range = null; protected $default_critical_range = null; protected $argWarning; protected $argCritical; protected $argVersion; protected $argVerbosity; protected $argTimeout; protected $argHelp; protected $argUsage; public $id = null; protected static $http_serial_number = 0; public $privkey = null; public $privkey_password = null; public $sign_algo = null; public $pubkey = null; protected $warningSingleValueRangeBehaviors = array(self::SINGLEVALUE_RANGE_DEFAULT); protected $criticalSingleValueRangeBehaviors = array(self::SINGLEVALUE_RANGE_DEFAULT); const SINGLEVALUE_RANGE_DEFAULT = 0; const SINGLEVALUE_RANGE_VAL_GT_X_BAD = 1; const SINGLEVALUE_RANGE_VAL_GE_X_BAD = 2; const SINGLEVALUE_RANGE_VAL_LT_X_BAD = 3; const SINGLEVALUE_RANGE_VAL_LE_X_BAD = 4; public $password_out = null; public $password_in = null; public static function is_http_mode() { return php_sapi_name() !== 'cli'; } public function getHelpManager() { return $this->helpObj; } public function getArgumentHandler() { return $this->argHandler; } public function outputHTML($text, $after_visual_output=true) { if ($this->is_http_mode()) { if ($this->initialized) { if ($after_visual_output) { $this->html_after .= $text; } else { $this->html_before .= $text; } } else { echo $text; } } } protected function resetArguments() { $this->argWarning = null; $this->argCritical = null; $this->argVersion = null; $this->argVerbosity = null; $this->argTimeout = null; $this->argHelp = null; $this->argWarning = null; $this->argCritical = null; } public function registerExpectedStandardArguments($args) { $this->resetArguments(); for ($i=0; $i<strlen($args); $i++) { switch ($args[$i]) { case 'w': $this->addExpectedArgument($this->argWarning = new VNagArgument('w', 'warning', VNagArgument::VALUE_REQUIRED, VNagLang::$argname_value, VNagLang::$warning_range)); break; case 'c': $this->addExpectedArgument($this->argCritical = new VNagArgument('c', 'critical', VNagArgument::VALUE_REQUIRED, VNagLang::$argname_value, VNagLang::$critical_range)); break; case 'V': $this->addExpectedArgument($this->argVersion = new VNagArgument('V', 'version', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$prints_version)); break; case 'v': $this->addExpectedArgument($this->argVerbosity = new VNagArgument('v', 'verbose', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$verbosity_helptext)); break; case 't': $this->addExpectedArgument($this->argTimeout = new VNagArgument('t', 'timeout', VNagArgument::VALUE_REQUIRED, VNagLang::$argname_seconds, VNagLang::$timeout_helptext)); break; case 'h': $this->addExpectedArgument($this->argHelp = new VNagArgument('h', 'help', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$help_helptext)); break; default: $letter = $args[$i]; throw new VNagInvalidStandardArgument(sprintf(VNagLang::$no_standard_arguments_with_letter, $letter)); } } } public function addExpectedArgument($argObj) { $helpObjAddEntryMethod = new ReflectionMethod($this->helpObj, '_addOption'); $helpObjAddEntryMethod->setAccessible(true); $helpObjAddEntryMethod->invoke($this->helpObj, $argObj); $argHandlerAddEntryMethod = new ReflectionMethod($this->argHandler, '_addExpectedArgument'); $argHandlerAddEntryMethod->setAccessible(true); $argHandlerAddEntryMethod->invoke($this->argHandler, $argObj); } protected function createArgumentHandler() { $this->argHandler = new VNagArgumentHandler(); } protected function createHelpObject() { $this->helpObj = new VNagHelp(); } protected function checkInitialized() { if (!$this->initialized) throw new VNagFunctionCallOutsideSession(); } protected function getVerbosityLevel() { $this->checkInitialized(); if (!isset($this->argVerbosity)) { return self::VERBOSITY_SUMMARY; } else { $level = $this->argVerbosity->count(); if ($level > self::MAX_VERBOSITY) $level = self::MAX_VERBOSITY; return $level; } } public function getWarningRange($argumentNumber=0) { $this->checkInitialized(); if (!isset($this->warningRanges[$argumentNumber])) { if (!is_null($this->argWarning)) { $warning = $this->argWarning->getValue(); if (!is_null($warning)) { $vals = explode(',',$warning); foreach ($vals as $number => $val) { if (_empty($val)) { $this->warningRanges[$number] = null; } else { $singleValueBehavior = isset($this->warningSingleValueRangeBehaviors[$number]) ? $this->warningSingleValueRangeBehaviors[$number] : VNag::SINGLEVALUE_RANGE_DEFAULT; $this->warningRanges[$number] = new VNagRange($val, $singleValueBehavior); } } } else { $this->warningRanges[0] = $this->default_warning_range; } } else { return null; } } if (isset($this->warningRanges[$argumentNumber])) { return $this->warningRanges[$argumentNumber]; } else { return null; } } public function getCriticalRange($argumentNumber=0) { $this->checkInitialized(); if (!isset($this->criticalRanges[$argumentNumber])) { if (!is_null($this->argCritical)) { $critical = $this->argCritical->getValue(); if (!is_null($critical)) { $vals = explode(',',$critical); foreach ($vals as $number => $val) { $singleValueBehavior = isset($this->criticalSingleValueRangeBehaviors[$number]) ? $this->criticalSingleValueRangeBehaviors[$number] : VNag::SINGLEVALUE_RANGE_DEFAULT; $this->criticalRanges[$number] = new VNagRange($val, $singleValueBehavior); } } else { $this->criticalRanges[0] = $this->default_critical_range; } } else { return null; } } if (isset($this->criticalRanges[$argumentNumber])) { return $this->criticalRanges[$argumentNumber]; } else { return null; } } public function checkAgainstWarningRange($values, $force=true, $autostatus=true, $argumentNumber=0) { $this->checkInitialized(); if (!$this->getArgumentHandler()->isArgRegistered('w')) { throw new VNagRequiredArgumentNotRegistered('-w'); } $wr = $this->getWarningRange($argumentNumber); if (isset($wr)) { if ($wr->checkAlert($values)) { if ($autostatus) $this->setStatus(VNag::STATUS_WARNING); return true; } else { if ($autostatus) $this->setStatus(VNag::STATUS_OK); return false; } } else { if ($force) { if (($argumentNumber > 0) && (count($this->warningRanges) > 0)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$too_few_warning_ranges, $argumentNumber+1)); } else { throw new VNagRequiredArgumentMissing('-w'); } } } } public function checkAgainstCriticalRange($values, $force=true, $autostatus=true, $argumentNumber=0) { $this->checkInitialized(); if (!$this->getArgumentHandler()->isArgRegistered('c')) { throw new VNagRequiredArgumentNotRegistered('-c'); } $cr = $this->getCriticalRange($argumentNumber); if (isset($cr)) { if ($cr->checkAlert($values)) { if ($autostatus) $this->setStatus(VNag::STATUS_CRITICAL); return true; } else { if ($autostatus) $this->setStatus(VNag::STATUS_OK); return false; } } else { if ($force) { if (($argumentNumber > 0) && (count($this->warningRanges) > 0)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$too_few_critical_ranges, $argumentNumber+1)); } else { throw new VNagRequiredArgumentMissing('-c'); } } } } protected static function getBaddestExitcode($code1, $code2) { return max($code1, $code2); } public static function _shutdownHandler() { if (!self::is_http_mode()) { exit((int)self::$exitcode); } } protected function _exit($code) { self::$exitcode = $this->getBaddestExitcode($code, self::$exitcode); } private $constructed = false; function __construct() { $this->createHelpObject(); $this->createArgumentHandler(); $this->addExpectedArgument($this->argUsage = new VNagArgument('?', '', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$prints_usage)); $this->constructed = true; } function __destruct() { if (Timeouter::started()) { Timeouter::end(); } } public function run() { global $inside_vnag_run; $inside_vnag_run = true; try { if (!$this->constructed) { throw new VNagNotConstructed(VNagLang::$notConstructed); } try { $this->initialized = true; $this->html_before = ''; $this->html_after = ''; $this->setStatus(null, true); $this->messages = array(); register_shutdown_function(array($this, '_shutdownHandler')); if ($this->argHandler->illegalUsage()) { $content = $this->helpObj->printUsagePage(); $this->setStatus(VNag::STATUS_UNKNOWN); if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_visual_output & VNag::OUTPUT_SPECIAL) echo $this->writeVisualHTML($content); if ($this->http_invisible_output & VNag::OUTPUT_SPECIAL) echo $this->writeInvisibleHTML($content); echo $this->html_after; return; } else { echo $content; return $this->_exit($this->status); } } if (!is_null($this->argVersion) && ($this->argVersion->available())) { $content = $this->helpObj->printVersionPage(); $this->setStatus(VNag::STATUS_UNKNOWN); if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_visual_output & VNag::OUTPUT_SPECIAL) echo $this->writeVisualHTML($content); if ($this->http_invisible_output & VNag::OUTPUT_SPECIAL) echo $this->writeInvisibleHTML($content); echo $this->html_after; return; } else { echo $content; return $this->_exit($this->status); } } if (!is_null($this->argHelp) && ($this->argHelp->available())) { $content = $this->helpObj->printHelpPage(); $this->setStatus(VNag::STATUS_UNKNOWN); if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_visual_output & VNag::OUTPUT_SPECIAL) echo $this->writeVisualHTML($content); if ($this->http_invisible_output & VNag::OUTPUT_SPECIAL) echo $this->writeInvisibleHTML($content); echo $this->html_after; return; } else { echo $content; return $this->_exit($this->status); } } $this->getWarningRange(); $this->getCriticalRange(); if (!is_null($this->argTimeout)) { $timeout = $this->argTimeout->getValue(); if (!is_null($timeout)) { Timeouter::start($timeout); } } ob_start(); $init_ob_level = ob_get_level(); try { $this->cbRun(); if (ob_get_level() < $init_ob_level) throw new VNagImplementationErrorException(VNagLang::$output_level_lowered); } finally { while (ob_get_level() > $init_ob_level) @ob_end_clean(); } if (is_null($this->status)) $this->setStatus($this->default_status,true); $outputType = VNag::OUTPUT_NORMAL; } catch (Exception $e) { $this->handleException($e); $outputType = VNag::OUTPUT_EXCEPTION; } if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_invisible_output & $outputType) { echo $this->writeInvisibleHTML(); } if ($this->http_visual_output & $outputType) { echo $this->writeVisualHTML(); } echo $this->html_after; } else { echo $this->getNagiosConsoleText(); return $this->_exit($this->status); } Timeouter::end(); } finally { $inside_vnag_run = false; } } private function getNagiosConsoleText() { $ary_perfdata = $this->getPerformanceData(); $performancedata_first = array_shift($ary_perfdata); $performancedata_rest = implode(' ', $ary_perfdata); $status_text = VNagLang::status($this->status, $this->statusmodel); if (_empty($this->getHeadline())) { $content = $status_text; } else { if ($this->show_status_in_headline) { $content = $status_text.': '.$this->getHeadline(); } else { $content = $this->getHeadline(); } } if (!_empty($performancedata_first)) $content .= '|'.trim($performancedata_first); $content .= "\n"; if (!_empty($this->verbose_info)) { $content .= trim($this->verbose_info); } if (!_empty($performancedata_rest)) $content .= '|'.trim($performancedata_rest); $content .= "\n"; return trim($content)."\n"; } abstract protected function cbRun(); public function addPerformanceData($prefDataObj, $move_to_font=false, $verbosityLevel=VNag::VERBOSITY_SUMMARY) { $this->checkInitialized(); if ((!isset($this->argVerbosity)) && ($verbosityLevel > VNag::VERBOSITY_SUMMARY)) throw new VNagRequiredArgumentNotRegistered('-v'); if (self::getVerbosityLevel() < $verbosityLevel) return false; if ($move_to_font) { array_unshift($this->performanceDataObjects, $prefDataObj); } else { $this->performanceDataObjects[] = $prefDataObj; } return true; } public function getPerformanceData() { $this->checkInitialized(); return $this->performanceDataObjects; } public function removePerformanceData($prefDataObj) { if (($key = array_search($prefDataObj, $this->performanceDataObjects, true)) !== false) { unset($this->performanceDataObjects[$key]); return true; } else { return false; } } public function clearPerformanceData() { $this->performanceDataObjects = array(); } public function getVerboseInfo() { return $this->verbose_info; } public function clearVerboseInfo() { $this->verbose_info = ''; } private function writeVisualHTML($special_content=null) { if (!_empty($special_content)) { $content = $special_content; } else { $content = strtoupper(VNagLang::$status.': '.VNagLang::status($this->status, $this->statusmodel))."\n\n"; $content .= strtoupper(VNagLang::$message).":\n"; $status_text = VNagLang::status($this->status, $this->statusmodel); if (_empty($this->getHeadline())) { $content .= $status_text; } else { if ($this->show_status_in_headline) { $content .= $status_text.': '.trim($this->getHeadline()); } else { $content .= trim($this->getHeadline()); } } $content .= "\n\n"; if (!_empty($this->verbose_info)) { $content .= strtoupper(VNagLang::$verbose_info).":\n".trim($this->verbose_info)."\n\n"; } $perfdata = $this->getPerformanceData(); if (count($perfdata) > 0) { $content .= strtoupper(VNagLang::$performance_data).":\n"; foreach ($perfdata as $pd) { $content .= trim($pd)."\n"; } $content .= "\n"; } } $colorinfo = ''; $status = $this->getStatus(); if ($status == VNag::STATUS_OK) $colorinfo = ' style="background-color:green;color:white;font-weight:bold"'; else if ($status == VNag::STATUS_WARNING) $colorinfo = ' style="background-color:yellow;color:black;font-weight:bold"'; else if ($status == VNag::STATUS_CRITICAL) $colorinfo = ' style="background-color:red;color:white;font-weight:bold"'; else if ($status == VNag::STATUS_ERROR) $colorinfo = ' style="background-color:purple;color:white;font-weight:bold"'; else $colorinfo = ' style="background-color:lightgray;color:black;font-weight:bold"'; $html_content = trim($content); $html_content = htmlentities($html_content); $html_content = str_replace(' ', '&nbsp;', $html_content); $html_content = nl2br($html_content); return '<table border="1" cellspacing="2" cellpadding="2" style="width:100%" class="vnag_table">'. '<tr'.$colorinfo.' class="vnag_title_row">'. '<td>'.VNagLang::$nagios_output.'</td>'. '</tr>'. '<tr class="vnag_message_row">'. '<td><code>'. $html_content. '</code></td>'. '</tr>'. '</table>'; } protected function readInvisibleHTML($html) { $this->checkInitialized(); $doc = new DOMDocument(); @$doc->loadHTML($html); $tags = $doc->getElementsByTagName('script'); foreach ($tags as $tag) { $type = $tag->getAttribute('type'); if ($type !== 'application/json') continue; $json = $tag->nodeValue; if (!$json) continue; $data = @json_decode($json,true); if (!is_array($data)) continue; if (!isset($data['type'])) continue; if ($data['type'] === VNAG_JSONDATA_V1) { if (!isset($data['datasets'])) throw new VNagWebInfoException(VNagLang::$dataset_missing); foreach ($data['datasets'] as $dataset) { $payload = base64_decode($dataset['payload']); if (!$payload) { throw new VNagWebInfoException(VNagLang::$payload_not_base64); } if (isset($dataset['encryption'])) { $cryptInfo = $dataset['encryption']; if (!is_array($cryptInfo)) { throw new VNagWebInfoException(VNagLang::$dataset_encryption_no_array); } $password = is_null($this->password_in) ? '' : $this->password_in; $salt = base64_decode($cryptInfo['salt']); if ($cryptInfo['hash'] != hash('sha256',$salt.$password)) { if ($password == '') { throw new VNagWebInfoException(VNagLang::$require_password); } else { throw new VNagWebInfoException(VNagLang::$wrong_password); } } if (!function_exists('openssl_decrypt')) { throw new VNagException(VNagLang::$openssl_missing); } $payload = openssl_decrypt($payload, $cryptInfo['method'], $password, 0, $cryptInfo['iv']); } if (!is_null($this->pubkey) && ($this->pubkey !== '')) { if (substr($this->pubkey,0,3) === '---') { $public_key = $this->pubkey; } else { if (!file_exists($this->pubkey)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$pubkey_file_not_found, $this->pubkey)); } $public_key = @file_get_contents($this->pubkey); if (!$public_key) { throw new VNagPublicKeyException(sprintf(VNagLang::$pubkey_file_not_readable, $this->pubkey)); } } if (!isset($dataset['signature'])) { throw new VNagSignatureException(VNagLang::$signature_missing); } $signature = base64_decode($dataset['signature']); if (!$signature) { throw new VNagSignatureException(VNagLang::$signature_not_bas64); } if (!function_exists('openssl_verify')) { throw new VNagException(VNagLang::$openssl_missing); } $sign_algo = is_null($this->sign_algo) ? OPENSSL_ALGO_SHA256 : $this->sign_algo; if (!openssl_verify($payload, $signature, $public_key, $sign_algo)) { throw new VNagSignatureException(VNagLang::$signature_invalid); } } $payload = @json_decode($payload,true); if (!$payload) { throw new VNagWebInfoException(VNagLang::$payload_not_json); } if ($payload['id'] == $this->id) { return $payload; } } } } return null; } private function getNextMonitorID($peek=false) { $result = is_null($this->id) ? self::$http_serial_number : $this->id; if (!$peek) { $this->id = null; self::$http_serial_number++; } return $result; } private function writeInvisibleHTML($special_content=null) { $payload['id'] = $this->getNextMonitorID(); $payload['status'] = $this->getStatus(); if (!_empty($special_content)) { $payload['text'] = $special_content; } else { $payload['headline'] = $this->getHeadline(); $payload['verbose_info'] = $this->verbose_info; $payload['performance_data'] = array(); foreach ($this->performanceDataObjects as $perfdata) { $payload['performance_data'][] = (string)$perfdata; } } $payload = json_encode($payload); $dataset = array(); if (!is_null($this->privkey) && ($this->privkey !== '')) { if (!function_exists('openssl_pkey_get_private') || !function_exists('openssl_sign')) { throw new VNagException(VNagLang::$openssl_missing); } if (substr($this->privkey,0,3) === '---') { $pkeyid = @openssl_pkey_get_private($this->privkey, $this->privkey_password); if (!$pkeyid) { throw new VNagPrivateKeyException(sprintf(VNagLang::$privkey_not_readable)); } } else { if (!file_exists($this->privkey)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$privkey_file_not_found, $this->privkey)); } $pkeyid = @openssl_pkey_get_private('file://'.$this->privkey, $this->privkey_password); if (!$pkeyid) { throw new VNagPrivateKeyException(sprintf(VNagLang::$privkey_file_not_readable, $this->privkey)); } } $signature = ''; $sign_algo = is_null($this->sign_algo) ? OPENSSL_ALGO_SHA256 : $this->sign_algo; if (@openssl_sign($payload, $signature, $pkeyid, $sign_algo)) { if (version_compare(PHP_VERSION, '8.0.0') < 0) { openssl_free_key($pkeyid); } $dataset['signature'] = base64_encode($signature); } else { throw new VNagPrivateKeyException(sprintf(VNagLang::$signature_failed)); } } if (!is_null($this->password_out) && ($this->password_out !== '')) { if (!function_exists('openssl_encrypt')) { throw new VNagException(VNagLang::$openssl_missing); } $password = $this->password_out; $method = 'aes-256-ofb'; $iv = substr(hash('sha256', openssl_random_pseudo_bytes(32)), 0, 16); $salt = openssl_random_pseudo_bytes(32); $cryptInfo = array(); $cryptInfo['method'] = $method; $cryptInfo['iv'] = $iv; $cryptInfo['salt'] = base64_encode($salt); $cryptInfo['hash'] = hash('sha256', $salt.$password); $payload = openssl_encrypt($payload, $method, $password, 0, $iv); $dataset['encryption'] = $cryptInfo; } $dataset['payload'] = base64_encode($payload); $json = array(); $json['type'] = VNAG_JSONDATA_V1; $json['datasets'] = array($dataset); return '<script type="application/json">'. json_encode($json). '</script>'; } protected function appendHeadline($msg) { $this->checkInitialized(); if (_empty($msg)) return false; $this->messages[] = $msg; return true; } protected function changeHeadline($msg) { $this->checkInitialized(); if (_empty($msg)) { $this->messages = array(); } else { $this->messages = array($msg); } return true; } public function setHeadline($msg, $append=false, $verbosityLevel=VNag::VERBOSITY_SUMMARY) { $this->checkInitialized(); if ((!isset($this->argVerbosity)) && ($verbosityLevel > VNag::VERBOSITY_SUMMARY)) throw new VNagRequiredArgumentNotRegistered('-v'); if (self::getVerbosityLevel() < $verbosityLevel) $msg = ''; if ($append) { return $this->appendHeadline($msg); } else { return $this->changeHeadline($msg); } } public function getHeadline() { $this->checkInitialized(); return implode(', ', $this->messages); } public function addVerboseMessage($msg, $verbosityLevel=VNag::VERBOSITY_SUMMARY) { $this->checkInitialized(); if (self::getVerbosityLevel() >= $verbosityLevel) { $this->verbose_info .= $msg."\n"; } } public function setStatus($status, $force=false) { $this->checkInitialized(); if (($force) || is_null($this->status) || ($status > $this->status)) { $this->status = $status; } } public function getStatus() { $this->checkInitialized(); return $this->status; } protected static function exceptionText($exception) { $class = get_class($exception); $msg = $exception->getMessage(); if (!_empty($msg)) { return sprintf(VNagLang::$exception_x, $msg, $class); } else { return sprintf(VNagLang::$unhandled_exception_without_msg, $class); } } protected function handleException($exception) { $this->checkInitialized(); if (!VNag::is_http_mode()) { while (ob_get_level() > 0) @ob_end_clean(); } $this->clearVerboseInfo(); $this->clearPerformanceData(); if ($exception instanceof VNagException) { $this->setStatus($exception->getStatus()); } else { $this->setStatus(self::STATUS_ERROR); } $this->setHeadline($this->exceptionText($exception), false); if ($exception instanceof VNagImplementationErrorException) { $this->addVerboseMessage($exception->getTraceAsString(), VNag::VERBOSITY_SUMMARY); } else { if (isset($this->argVerbosity)) { $this->addVerboseMessage($exception->getTraceAsString(), VNag::VERBOSITY_ADDITIONAL_INFORMATION); } else { } } } protected function get_cache_dir() { $homedir = @getenv('HOME'); if ($homedir && is_dir($homedir)) { $try = "$homedir/.vnag/cache"; if (is_dir($try)) return $try; if (@mkdir($try,0777,true)) return $try; } $user = posix_getpwuid(posix_geteuid()); if (isset($user['dir']) && is_dir($user['dir'])) { $homedir = $user['dir']; $try = "$homedir/.vnag/cache"; if (is_dir($try)) return $try; if (@mkdir($try,0777,true)) return $try; } if (isset($user['name']) && is_dir($user['name'])) { $username = $user['name']; $try = "/tmp/vnag/cache"; if (is_dir($try)) return $try; if (@mkdir($try,0777,true)) return $try; } throw new VNagException("Cannot get cache dir"); } protected function url_get_contents($url, $max_cache_time=1*60*60, $context=null) { $cache_file = $this->get_cache_dir().'/'.hash('sha256',$url); if (file_exists($cache_file) && (time()-filemtime($cache_file) < $max_cache_time)) { $cont = @file_get_contents($cache_file); if ($cont === false) throw new Exception("Failed to get contents from $cache_file"); } else { $options = array( 'http'=>array( 'method'=>"GET", 'header'=>"Accept-language: en\r\n" . "User-Agent: Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B334b Safari/531.21.102011-10-16 20:23:10\r\n" ) ); if (is_null($context)) $context = stream_context_create($options); $cont = @file_get_contents($url, false, $context); if ($cont === false) throw new Exception("Failed to get contents from $url"); file_put_contents($cache_file, $cont); } return $cont; } } class VNagException extends Exception { public function getStatus() { return VNag::STATUS_ERROR; } } class VNagTimeoutException extends VNagException {} class VNagWebInfoException extends VNagException {} class VNagSignatureException extends VNagException {} class VNagPublicKeyException extends VNagException {} class VNagPrivateKeyException extends VNagException {} class VNagInvalidArgumentException extends VNagException { public function getStatus() { return VNag::STATUS_UNKNOWN; } } class VNagValueUomPairSyntaxException extends VNagInvalidArgumentException { public function __construct($str) { $e_msg = sprintf(VNagLang::$valueUomPairSyntaxError, $str); parent::__construct($e_msg); } } class VNagInvalidTimeoutException extends VNagInvalidArgumentException {} class VNagInvalidRangeException extends VNagInvalidArgumentException { public function __construct($msg) { $e_msg = VNagLang::$range_is_invalid; if (!_empty($msg)) $e_msg .= ': '.trim($msg); parent::__construct($e_msg); } } class VNagInvalidShortOpt extends VNagImplementationErrorException {} class VNagInvalidLongOpt extends VNagImplementationErrorException {} class VNagInvalidValuePolicy extends VNagImplementationErrorException {} class VNagIllegalStatusModel extends VNagImplementationErrorException {} class VNagNotConstructed extends VNagImplementationErrorException {} class VNagImplementationErrorException extends VNagException {} class VNagInvalidStandardArgument extends VNagImplementationErrorException {} class VNagFunctionCallOutsideSession extends VNagImplementationErrorException {} class VNagIllegalArgumentValuesException extends VNagImplementationErrorException {} class VNagRequiredArgumentNotRegistered extends VNagImplementationErrorException { public function __construct($required_argument) { $e_msg = sprintf(VNagLang::$query_without_expected_argument, $required_argument); parent::__construct($e_msg); } } class VNagRequiredArgumentMissing extends VNagInvalidArgumentException { public function __construct($required_argument) { $e_msg = sprintf(VNagLang::$required_argument_missing, $required_argument); parent::__construct($e_msg); } } class VNagUnknownUomException extends VNagInvalidArgumentException { public function __construct($uom) { $e_msg = sprintf(VNagLang::$perfdata_uom_not_recognized, $uom); parent::__construct($e_msg); } } class VNagNoCompatibleRangeUomFoundException extends VNagException {} class VNagMixedUomsNotImplemented extends VNagInvalidArgumentException { public function __construct($uom1, $uom2) { if (_empty($uom1)) $uom1 = VNagLang::$none; if (_empty($uom2)) $uom2 = VNagLang::$none; $e_msg = sprintf(VNagLang::$perfdata_mixed_uom_not_implemented, $uom1, $uom2); parent::__construct($e_msg); } } class VNagUomConvertException extends VNagInvalidArgumentException { public function __construct($uom1, $uom2) { if (_empty($uom1)) $uom1 = VNagLang::$none; if (_empty($uom2)) $uom2 = VNagLang::$none; $e_msg = sprintf(VNagLang::$convert_x_y_error, $uom1, $uom2); parent::__construct($e_msg); } } class VNagInvalidPerformanceDataException extends VNagInvalidArgumentException { public function __construct($msg) { $e_msg = VNagLang::$performance_data_invalid; if (!_empty($msg)) $e_msg .= ': '.trim($msg); parent::__construct($e_msg); } } class Timeouter { private static $start_time = false; private static $timeout; private static $fired = false; private static $registered = false; private function __construct() { } public static function start($timeout) { if (!is_numeric($timeout) || ($timeout <= 0)) { throw new VNagInvalidTimeoutException(sprintf(VNagLang::$timeout_value_invalid, $timeout)); } self::$start_time = microtime(true); self::$timeout = (float) $timeout; self::$fired = false; if (!self::$registered) { self::$registered = true; register_tick_function(array('Timeouter', 'tick')); } } public static function started() { return self::$registered; } public static function end() { if (self::$registered) { unregister_tick_function(array('Timeouter', 'tick')); self::$registered = false; } } public static function tick() { if ((!self::$fired) && ((microtime(true) - self::$start_time) > self::$timeout)) { self::$fired = true; throw new VNagTimeoutException(VNagLang::$timeout_exception); } } } class VNagArgument { const VALUE_FORBIDDEN = 0; const VALUE_REQUIRED = 1; const VALUE_OPTIONAL = 2; protected $shortopt; protected $longopts; protected $valuePolicy; protected $valueName; protected $helpText; protected $defaultValue = null; protected static $all_short = ''; protected static $all_long = array(); public function getShortOpt() { return $this->shortopt; } public function getLongOpts() { return $this->longopts; } public function getValuePolicy() { return $this->valuePolicy; } public function getValueName() { return $this->valueName; } public function getHelpText() { return $this->helpText; } static private function validateShortOpt($shortopt) { $m = array(); return preg_match('@^[a-zA-Z0-9\\+\\-\\?]$@', $shortopt, $m); } static private function validateLongOpt($longopt) { $m = array(); return preg_match('@^[a-zA-Z0-9\\+\\-\\?]+$@', $longopt, $m); } public function __construct($shortopt, $longopts, $valuePolicy, $valueName, $helpText, $defaultValue=null) { switch ($valuePolicy) { case VNagArgument::VALUE_FORBIDDEN: if (!_empty($valueName)) { throw new VNagImplementationErrorException(sprintf(VNagLang::$value_name_forbidden)); } break; case VNagArgument::VALUE_REQUIRED: if (_empty($valueName)) { throw new VNagImplementationErrorException(sprintf(VNagLang::$value_name_required)); } break; case VNagArgument::VALUE_OPTIONAL: if (_empty($valueName)) { throw new VNagImplementationErrorException(sprintf(VNagLang::$value_name_required)); } break; default: throw new VNagInvalidValuePolicy(sprintf(VNagLang::$illegal_valuepolicy, $valuePolicy)); } if (!_empty($shortopt)) { if (!self::validateShortOpt($shortopt)) { throw new VNagInvalidShortOpt(sprintf(VNagLang::$illegal_shortopt, $shortopt)); } } if (is_array($longopts)) { foreach ($longopts as $longopt) { if (!self::validateLongOpt($longopt)) { throw new VNagInvalidLongOpt(sprintf(VNagLang::$illegal_longopt, $longopt)); } } } else if (!_empty($longopts)) { if (!self::validateLongOpt($longopts)) { throw new VNagInvalidLongOpt(sprintf(VNagLang::$illegal_longopt, $longopts)); } $longopts = array($longopts); } else { $longopts = array(); } switch ($valuePolicy) { case VNagArgument::VALUE_FORBIDDEN: $policyApdx = ''; break; case VNagArgument::VALUE_REQUIRED: $policyApdx = ':'; break; case VNagArgument::VALUE_OPTIONAL: $policyApdx = '::'; break; default: throw new VNagInvalidValuePolicy(sprintf(VNagLang::$illegal_valuepolicy, $valuePolicy)); } if ((!is_null($shortopt)) && ($shortopt != '?')) self::$all_short .= $shortopt.$policyApdx; if (is_array($longopts)) { foreach ($longopts as $longopt) { self::$all_long[] = $longopt.$policyApdx; } } $this->shortopt = $shortopt; $this->longopts = $longopts; $this->valuePolicy = $valuePolicy; $this->valueName = $valueName; $this->helpText = $helpText; $this->defaultValue = $defaultValue; } protected static function getOptions() { global $OVERWRITE_ARGUMENTS; if (!is_null($OVERWRITE_ARGUMENTS)) { return $OVERWRITE_ARGUMENTS; } else if (VNag::is_http_mode()) { return $_REQUEST; } else { return getopt(self::$all_short, self::$all_long); } } public function count() { $options = self::getOptions(); $count = 0; if (isset($options[$this->shortopt])) { if (is_array($options[$this->shortopt])) { $count += count($options[$this->shortopt]); } else { $count += 1; } } if (!is_null($this->longopts)) { foreach ($this->longopts as $longopt) { if (isset($options[$longopt])) { if (is_array($options[$longopt])) { $count += count($options[$longopt]); } else { $count += 1; } } } } return $count; } public function available() { $options = self::getOptions(); if (isset($options[$this->shortopt])) return true; if (!is_null($this->longopts)) { foreach ($this->longopts as $longopt) { if (isset($options[$longopt])) return true; } } return false; } public function require() { if (!$this->available() && is_null($this->defaultValue)) { $opt = $this->shortopt; $opt = !_empty($opt) ? '-'.$opt : (isset($this->longopts[0]) ? '--'.$this->longopts[0] : '?'); throw new VNagRequiredArgumentMissing($opt); } } public function getValue() { $options = self::getOptions(); if (isset($options[$this->shortopt])) { $x = $options[$this->shortopt]; if (is_array($x) && (count($x) <= 1)) $options[$this->shortopt] = $options[$this->shortopt][0]; return $options[$this->shortopt]; } if (!is_null($this->longopts)) { foreach ($this->longopts as $longopt) { if (isset($options[$longopt])) { $x = $options[$longopt]; if (is_array($x) && (count($x) <= 1)) $options[$longopt] = $options[$longopt][0]; return $options[$longopt]; } } } return $this->defaultValue; } } class VNagArgumentHandler { protected $expectedArgs = array(); protected function _addExpectedArgument($argObj) { if ($argObj->getShortOpt() == '?') return false; if ($argObj->getShortOpt() == '-') return false; if ($argObj->getShortOpt() == '+') return false; $this->expectedArgs[] = $argObj; return true; } public function getArgumentObj($shortopt) { foreach ($this->expectedArgs as $argObj) { if ($argObj->getShortOpt() == $shortopt) return $argObj; } return null; } public function isArgRegistered($shortopt) { return !is_null($this->getArgumentObj($shortopt)); } public function illegalUsage() { global $argv; return (isset($argv[1])) && (($argv[1] == '-?') || ($argv[1] == '/?')); } } class VNagRange { public $start; public $end; public $warnInsideRange; public function __construct($rangeDef, $singleValueBehavior=VNag::SINGLEVALUE_RANGE_DEFAULT) { $m = array(); if (!preg_match('|^(@){0,1}([^:]+)(:){0,1}(.*)$|', $rangeDef, $m)) { throw new VNagInvalidRangeException(sprintf(VNagLang::$range_invalid_syntax, $rangeDef)); } $this->warnInsideRange = $m[1] === '@'; $this->start = null; $this->end = null; if ($m[3] === ':') { if ($m[2] === '~') { $this->start = '-inf'; } else { $this->start = new VNagValueUomPair($m[2]); } if (_empty($m[4])) { $this->end = 'inf'; } else { $this->end = new VNagValueUomPair($m[4]); } } else { assert(_empty($m[4])); assert(!_empty($m[2])); $x = $m[2]; if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_DEFAULT) { $this->start = new VNagValueUomPair('0'.((new VNagValueUomPair($x))->getUom())); $this->end = new VNagValueUomPair($x); } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_GT_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 0; $this->start = '-inf'; $this->end = new VNagValueUomPair($x); } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_GE_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 1; $this->start = new VNagValueUomPair($x); $this->end = 'inf'; } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_LT_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 0; $this->start = new VNagValueUomPair($x); $this->end = 'inf'; } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_LE_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 1; $this->start = '-inf'; $this->end = new VNagValueUomPair($x); } else { throw new VNagException(VNagLang::$illegalSingleValueBehavior); } } if (is_null($this->start)) { throw new VNagInvalidRangeException(VNagLang::$invalid_start_value); } if (is_null($this->end)) { throw new VNagInvalidRangeException(VNagLang::$invalid_end_value); } if (($this->start instanceof VNagValueUomPair) && ($this->end instanceof VNagValueUomPair) && (VNagValueUomPair::compare($this->start,$this->end) > 0)) { throw new VNagInvalidRangeException(VNagLang::$start_is_greater_than_end); } } public function __toString() { $ret = ''; if ($this->warnInsideRange) { $ret = '@'; } if ($this->start === '-inf') { $ret .= '~'; } else { $ret .= $this->start; } $ret .= ':'; if ($this->end !== 'inf') { $ret .= $this->end; } return $ret; } public function checkAlert($values) { $compatibleCount = 0; if (!is_array($values)) $values = array($values); foreach ($values as $value) { if (!($value instanceof VNagValueUomPair)) $value = new VNagValueUomPair($value); assert(($this->start === '-inf') || ($this->start instanceof VNagValueUomPair)); assert(($this->end === 'inf' ) || ($this->end instanceof VNagValueUomPair)); if (($this->start !== '-inf') && (!$this->start->compatibleWith($value))) continue; if (($this->end !== 'inf') && (!$this->end->compatibleWith($value))) continue; $compatibleCount++; if ($this->warnInsideRange) { return (($this->start === '-inf') || (VNagValueUomPair::compare($value,$this->start) >= 0)) && (($this->end === 'inf') || (VNagValueUomPair::compare($value,$this->end) <= 0)); } else { return (($this->start !== '-inf') && (VNagValueUomPair::compare($value,$this->start) < 0)) || (($this->end !== 'inf') && (VNagValueUomPair::compare($value,$this->end) > 0)); } } if ((count($values) > 0) and ($compatibleCount == 0)) { throw new VNagNoCompatibleRangeUomFoundException(VNagLang::$no_compatible_range_uom_found); } return false; } } class VNagValueUomPair { protected $value; protected $uom; public $roundTo = -1; public function isRelative() { return $this->uom === '%'; } public function getValue() { return $this->value; } public function getUom() { return $this->uom; } public function __toString() { if ($this->roundTo == -1) { return $this->value.$this->uom; } else { return round($this->value,$this->roundTo).$this->uom; } } public function __construct($str) { $m = array(); if (!preg_match('/^([\d\.]+)(.*)$/ism', $str, $m)) { throw new VNagValueUomPairSyntaxException($str); } $this->value = $m[1]; $this->uom = isset($m[2]) ? $m[2] : ''; if (!self::isKnownUOM($this->uom)) { throw new VNagUnknownUomException($this->uom); } } public static function isKnownUOM(string $uom) { $no_unit = ($uom === ''); $seconds = ($uom === 's') || ($uom === 'ms') || ($uom === 'us'); $percentage = ($uom === '%'); $bytes = ($uom === 'B') || ($uom === 'KB') || ($uom === 'MB') || ($uom === 'GB') || ($uom === 'TB'); $counter = ($uom === 'c'); return ($no_unit || $seconds || $percentage || $bytes || $counter); } public function normalize($target=null) { $res = clone $this; if ($res->uom === 'ms') { $res->uom = 's'; $res->value /= 1000; } if ($res->uom === 'us') { $res->uom = 's'; $res->value /= 1000 * 1000; } if ($res->uom === 'B') { $res->uom = 'MB'; $res->value /= 1024 * 1024; } if ($res->uom === 'KB') { $res->uom = 'MB'; $res->value /= 1024; } if ($res->uom === 'GB') { $res->uom = 'MB'; $res->value *= 1024; } if ($res->uom === 'TB') { $res->uom = 'MB'; $res->value *= 1024 * 1024; } if ($res->uom === 'c') { $res->uom = ''; } if (!is_null($target)) { if ($res->uom == 'MB') { if ($target == 'B') { $res->uom = 'B'; $res->value *= 1024 * 1024; } else if ($target == 'KB') { $res->uom = 'KB'; $res->value *= 1024; } else if ($target == 'MB') { $res->uom = 'MB'; $res->value *= 1; } else if ($target == 'GB') { $res->uom = 'GB'; $res->value /= 1024; } else if ($target == 'TB') { $res->uom = 'TB'; $res->value /= 1024 * 1024; } else { throw new VNagUomConvertException($res->uom, $target); } } else if ($res->uom == 's') { if ($target == 's') { $res->uom = 's'; $res->value /= 1; } else if ($target == 'ms') { $res->uom = 'ms'; $res->value /= 1000; } else if ($target == 'us') { $res->uom = 'us'; $res->value /= 1000 * 1000; } else { throw new VNagUomConvertException($res->uom, $target); } } else { throw new VNagUomConvertException($res->uom, $target); } } return $res; } public function compatibleWith(VNagValueUomPair $other) { $a = $this->normalize(); $b = $other->normalize(); return ($a->uom == $b->uom); } public static function compare(VNagValueUomPair $left, VNagValueUomPair $right) { $a = $left->normalize(); $b = $right->normalize(); if ($a->uom != $b->uom) throw new VNagMixedUomsNotImplemented($a->uom, $b->uom); if ($a->value > $b->value) return 1; if ($a->value == $b->value) return 0; if ($a->value < $b->value) return -1; } } class VNagPerformanceData { protected $label; protected $value; protected $warn = null; protected $crit = null; protected $min = null; protected $max = null; public static function createByString($perfdata) { $perfdata = trim($perfdata); $ary = explode('=',$perfdata); if (count($ary) != 2) { throw new VNagInvalidPerformanceDataException(sprintf(VNagLang::$perfdata_line_invalid, $perfdata)); } $label = $ary[0]; $bry = explode(';',$ary[1]); if (substr($label,0,1) === "'") $label = substr($label, 1, strlen($label)-2); $value = $bry[0]; $warn = isset($bry[1]) ? $bry[1] : null; $crit = isset($bry[2]) ? $bry[2] : null; $min = isset($bry[3]) ? $bry[3] : null; $max = isset($bry[4]) ? $bry[4] : null; return new self($label, $value, $warn, $crit, $min, $max); } public function __construct($label, $value, $warn=null, $crit=null, $min=null, $max=null) { if (strpos($label, '=') !== false) throw new VNagInvalidPerformanceDataException(VNagLang::$perfdata_label_equal_sign_forbidden); $label = str_replace("'", "''", $label); $m = array(); if ((!_empty($min)) && (!preg_match('|^[-0-9\\.]+$|', $min, $m))) { throw new VNagInvalidPerformanceDataException(VNagLang::$perfdata_min_must_be_in_class); } if ((!_empty($max)) && (!preg_match('|^[-0-9\\.]+$|', $max, $m))) { throw new VNagInvalidPerformanceDataException(VNagLang::$perfdata_max_must_be_in_class); } $this->label = $label; $this->value = ($value == 'U') ? 'U' : new VNagValueUomPair($value); $this->warn = $warn; $this->crit = $crit; $this->min = $min; $this->max = $max; } public function __toString() { $label = $this->label; $value = $this->value; $warn = $this->warn; $crit = $this->crit; $min = $this->min; $max = $this->max; $label = str_replace("''", "'", $label); return "'$label'=$value". ';'.(is_null($warn) ? '' : $warn). ';'.(is_null($crit) ? '' : $crit). ';'.(is_null($min) ? '' : $min). ';'.(is_null($max) ? '' : $max); } } class VNagHelp { public $word_wrap_width = 80; public $argument_indent = 7; public function printUsagePage() { $usage = $this->getUsage(); if (_empty($usage)) { $usage = VNagLang::$no_syntax_defined; } return trim($usage)."\n"; } public function printVersionPage() { $out = trim($this->getNameAndVersion())."\n"; if ($this->word_wrap_width > 0) $out = wordwrap($out, $this->word_wrap_width, "\n", false); return $out; } static private function _conditionalLine($line, $terminator='', $prefix='') { if (!_empty($line)) { return trim($line).$terminator; } return ''; } public function printHelpPage() { $out = ''; $out .= self::_conditionalLine($this->getNameAndVersion(), "\n"); $out .= self::_conditionalLine($this->getCopyright(), "\n"); $out .= ($out != '') ? "\n" : ''; $out .= self::_conditionalLine($this->getShortDescription(), "\n\n\n"); $out .= self::_conditionalLine($this->getUsage(), "\n\n"); $out .= VNagLang::$options."\n"; foreach ($this->options as $argObj) { $out .= $this->printArgumentHelp($argObj); } $out .= self::_conditionalLine($this->getFootNotes(), "\n\n", "\n"); if ($this->word_wrap_width > 0) $out = wordwrap($out, $this->word_wrap_width, "\n", false); return $out; } protected $options = array(); protected function _addOption($argObj) { $this->options[] = $argObj; } protected function printArgumentHelp($argObj) { $identifiers = array(); $shortopt = $argObj->getShortopt(); if (!_empty($shortopt)) $identifiers[] = '-'.$shortopt; $longopts = $argObj->getLongopts(); if (!is_null($longopts)) { foreach ($longopts as $longopt) { if (!_empty($longopt)) $identifiers[] = '--'.$longopt; } } if (count($identifiers) == 0) return; $valueName = $argObj->getValueName(); $arginfo = ''; switch ($argObj->getValuePolicy()) { case VNagArgument::VALUE_FORBIDDEN: $arginfo = ''; break; case VNagArgument::VALUE_REQUIRED: $arginfo = '='.$valueName; break; case VNagArgument::VALUE_OPTIONAL: $arginfo = '[='.$valueName.']'; break; } $out = ''; $out .= implode(', ', $identifiers).$arginfo."\n"; $content = trim($argObj->getHelpText()); if ($this->word_wrap_width > 0) $content = wordwrap($content, $this->word_wrap_width-$this->argument_indent, "\n", false); $lines = explode("\n", $content); foreach ($lines as $line) { $out .= str_repeat(' ', $this->argument_indent).$line."\n"; } $out .= "\n"; return $out; } protected $pluginName; public function setPluginName($pluginName) { $this->pluginName = $this->replaceStuff($pluginName); } public function getPluginName() { if (_empty($this->pluginName)) { global $argv; return basename($argv[0]); } else { return $this->pluginName; } } protected $version; public function setVersion($version) { $this->version = $this->replaceStuff($version); } public function getVersion() { return $this->version; } public function getNameAndVersion() { $ret = $this->getPluginName(); if (_empty($ret)) return null; $ver = $this->getVersion(); if (!_empty($ver)) { $ret = sprintf(VNagLang::$x_version_x, $ret, $ver); } $ret = trim($ret); return $ret; } protected $copyright; public function setCopyright($copyright) { $this->copyright = $this->replaceStuff($copyright); } private function getVNagCopyright() { if (VNag::is_http_mode()) { $vts_email = 'www.viathinksoft.com'; } else { $vts_email = base64_decode('aW5mb0B2aWF0aGlua3NvZnQuZGU='); } return "VNag Framework ".VNag::VNAG_VERSION." (C) 2014-".date('Y')." ViaThinkSoft <$vts_email>"; } public function getCopyright() { if (_empty($this->copyright)) { return sprintf(VNagLang::$plugin_uses, $this->getVNagCopyright()); } else { return trim($this->copyright)."\n".sprintf(VNagLang::$uses, $this->getVNagCopyright()); } } protected $shortDescription; public function setShortDescription($shortDescription) { $this->shortDescription = $this->replaceStuff($shortDescription); } public function getShortDescription() { if (_empty($this->shortDescription)) { return null; } else { $content = $this->shortDescription; if ($this->word_wrap_width > 0) $content = wordwrap($content, $this->word_wrap_width, "\n", false); return $content; } } protected function replaceStuff($text) { global $argv; if (php_sapi_name() == 'cli') { $text = str_replace('$SCRIPTNAME$', $argv[0], $text); } else { $text = str_replace('$SCRIPTNAME$', basename($_SERVER['SCRIPT_NAME']), $text); } $text = str_replace('$CURYEAR$', date('Y'), $text); return $text; } protected $syntax; public function setSyntax($syntax) { $syntax = $this->replaceStuff($syntax); $this->syntax = $syntax; } public function getUsage() { if (_empty($this->syntax)) { return null; } else { return sprintf(VNagLang::$usage_x, $this->syntax); } } protected $footNotes; public function setFootNotes($footNotes) { $this->footNotes = $this->replaceStuff($footNotes); } public function getFootNotes() { return $this->footNotes; } } class VNagLang { public static function status($code, $statusmodel) { switch ($statusmodel) { case VNag::STATUSMODEL_SERVICE: switch ($code) { case VNag::STATUS_OK: return 'OK'; case VNag::STATUS_WARNING: return 'Warning'; case VNag::STATUS_CRITICAL: return 'Critical'; case VNag::STATUS_UNKNOWN: return 'Unknown'; default: return sprintf('Error (%d)', $code); } case VNag::STATUSMODEL_HOST: switch ($code) { case VNag::STATUS_UP: return 'Up'; case VNag::STATUS_DOWN: return 'Down'; default: return sprintf('Maintain last state (%d)', $code); } default: throw new VNagIllegalStatusModel(sprintf(self::$illegal_statusmodel, $statusmodel)); } } static $nagios_output = 'VNag-Output'; static $verbose_info = 'Verbose information'; static $status = 'Status'; static $message = 'Message'; static $performance_data = 'Performance data'; static $status_ok = 'OK'; static $status_warn = 'Warning'; static $status_critical = 'Critical'; static $status_unknown = 'Unknown'; static $status_error = 'Error'; static $unhandled_exception_without_msg = "Unhandled exception of type %s"; static $plugin_uses = 'This plugin uses %s'; static $uses = 'uses %s'; static $x_version_x = '%s, version %s'; static $argname_value = 'value'; static $argname_seconds = 'seconds'; static $query_without_expected_argument = "The argument '%s' is queried, but was not added to the list of expected arguments. Please contact the plugin author."; static $required_argument_missing = "The argument '%s' is required."; static $performance_data_invalid = 'Performance data invalid.'; static $no_standard_arguments_with_letter = "No standard argument with letter '%s' exists."; static $invalid_start_value = 'Invalid start value.'; static $invalid_end_value = 'Invalid end value.'; static $start_is_greater_than_end = 'Start is greater than end value.'; static $value_name_forbidden = "Implementation error: You may not define a value name for the argument, because the value policy is VALUE_FORBIDDEN."; static $value_name_required = "Implementation error: Please define a name for the argument (so it can be shown in the help page)."; static $illegal_shortopt = "Illegal shortopt '-%s'."; static $illegal_longopt = "Illegal longopt '--%s'."; static $illegal_valuepolicy = "valuePolicy has illegal value '%s'."; static $range_invalid_syntax = "Syntax error in range '%s'."; static $timeout_value_invalid = "Timeout value '%s' is invalid."; static $range_is_invalid = 'Range is invalid.'; static $timeout_exception = 'Timeout!'; static $perfdata_label_equal_sign_forbidden = 'Label may not contain an equal sign.'; static $perfdata_value_must_be_in_class = 'Value must be in class [-0-9.] or be \'U\' if the actual value can\'t be determined.'; static $perfdata_min_must_be_in_class = 'Min must be in class [-0-9.] or empty.'; static $perfdata_max_must_be_in_class = 'Max must be in class [-0-9.] or empty.'; static $perfdata_uom_not_recognized = 'UOM (unit of measurement) "%s" is not recognized.'; static $perfdata_mixed_uom_not_implemented = 'Mixed UOMs (%s and %s) are currently not supported.'; static $no_compatible_range_uom_found = 'Measured values are not compatible with the provided warning/critical parameter. Most likely, the UOM is incompatible.'; static $exception_x = '%s (%s)'; static $no_syntax_defined = 'The author of this plugin has not defined a syntax for this plugin.'; static $usage_x = "Usage:\n%s"; static $options = "Options:"; static $illegal_statusmodel = "Invalid statusmodel %d."; static $none = '[none]'; static $valueUomPairSyntaxError = 'Syntax error at "%s". Syntax must be Value[UOM].'; static $too_few_warning_ranges = "You have too few warning ranges (currently trying to get element %d)."; static $too_few_critical_ranges = "You have too few critical ranges (currently trying to get element %d)."; static $dataset_missing = 'Dataset missing.'; static $payload_not_base64 = 'The payload is not valid Base64.'; static $payload_not_json = 'The payload is not valid JSON.'; static $signature_missing = 'The signature is missing.'; static $signature_not_bas64 = 'The signature is not valid Base64.'; static $signature_invalid = 'The signature is invalid. The connection might have been tampered, or a different key is used.'; static $pubkey_file_not_found = "Public key file %s was not found."; static $pubkey_file_not_readable = "Public key file %s is not readable."; static $privkey_file_not_found = "Private key file %s was not found."; static $privkey_not_readable = "Private key is not readable."; static $privkey_file_not_readable = "Private key file %s is not readable."; static $signature_failed = "Signature failed."; static $perfdata_line_invalid = "Performance data line %s is invalid."; static $singlevalue_unexpected_at_symbol = 'This plugin does not allow the @-symbol at ranges for single values.'; static $illegalSingleValueBehavior = "Illegal value for 'singleValueBehavior'. Please contact the creator of the plugin."; static $dataset_encryption_no_array = 'Dataset encryption information invalid.'; static $require_password = 'This resource is protected with a password. Please provide a password.'; static $wrong_password = 'This resource is protected with a password. You have provided the wrong password, or it was changed.'; static $convert_x_y_error = 'Cannot convert from UOM %s to UOM %s.'; static $php_error = 'PHP has detected an error in the plugin. Please contact the plugin author.'; static $output_level_lowered = "Output Buffer level lowered during cbRun(). Please contact the plugin author."; static $openssl_missing = "OpenSSL is missing. Therefore, encryption and signatures are not available."; static $warning_range = 'Warning range'; static $critical_range = 'Critical range'; static $prints_version = 'Prints version'; static $verbosity_helptext = 'Verbosity -v, -vv or -vvv'; static $timeout_helptext = 'Sets timeout in seconds'; static $help_helptext = 'Prints help page'; static $prints_usage = 'Prints usage'; static $notConstructed = 'Parent constructor not called with parent::__construct().'; } function vnagErrorHandler($errorkind, $errortext, $file, $line) { global $inside_vnag_run; if (!$inside_vnag_run && VNag::is_http_mode()) { return false; } if (!(error_reporting() & $errorkind)) { return true; } if (defined('E_ERROR') && ($errorkind == E_ERROR)) $errorkind = 'Error'; if (defined('E_WARNING') && ($errorkind == E_WARNING)) $errorkind = 'Warning'; if (defined('E_PARSE') && ($errorkind == E_PARSE)) $errorkind = 'Parse'; if (defined('E_NOTICE') && ($errorkind == E_NOTICE)) $errorkind = 'Notice'; if (defined('E_CORE_ERROR') && ($errorkind == E_CORE_ERROR)) $errorkind = 'Core Error'; if (defined('E_CORE_WARNING') && ($errorkind == E_CORE_WARNING)) $errorkind = 'Core Warning'; if (defined('E_COMPILE_ERROR') && ($errorkind == E_COMPILE_ERROR)) $errorkind = 'Compile Error'; if (defined('E_COMPILE_WARNING') && ($errorkind == E_COMPILE_WARNING)) $errorkind = 'Compile Warning'; if (defined('E_USER_ERROR') && ($errorkind == E_USER_ERROR)) $errorkind = 'User Error'; if (defined('E_USER_WARNING') && ($errorkind == E_USER_WARNING)) $errorkind = 'User Warning'; if (defined('E_USER_NOTICE') && ($errorkind == E_USER_NOTICE)) $errorkind = 'User Notice'; if (defined('E_STRICT') && ($errorkind == E_STRICT)) $errorkind = 'Strict'; if (defined('E_RECOVERABLE_ERROR') && ($errorkind == E_RECOVERABLE_ERROR)) $errorkind = 'Recoverable Error'; if (defined('E_DEPRECATED') && ($errorkind == E_DEPRECATED)) $errorkind = 'Deprecated'; if (defined('E_USER_DEPRECATED') && ($errorkind == E_USER_DEPRECATED)) $errorkind = 'User Deprecated'; throw new VNagException(VNagLang::$php_error . " $errortext at $file:$line (kind $errorkind)"); } $inside_vnag_run = false; $old_error_handler = set_error_handler("vnagErrorHandler"); <?php
declare(ticks=1); class PhpMyAdminVersionCheck extends VNag { protected $argSystemDir = null; public function __construct() { parent::__construct(); $this->registerExpectedStandardArguments('Vht'); $this->getHelpManager()->setPluginName('check_phpmyadmin_version'); $this->getHelpManager()->setVersion('2023-10-13'); $this->getHelpManager()->setShortDescription('This plugin checks if a local phpMyAdmin system has the latest version installed.'); $this->getHelpManager()->setCopyright('Copyright (C) 2011-$CURYEAR$ Daniel Marschall, ViaThinkSoft.'); $this->getHelpManager()->setSyntax('$SCRIPTNAME$ [-d <directory>]'); $this->getHelpManager()->setFootNotes('If you encounter bugs, please contact ViaThinkSoft at www.viathinksoft.com'); $this->addExpectedArgument($this->argSystemDir = new VNagArgument('d', 'directory', VNagArgument::VALUE_REQUIRED, 'phpmyadminPath', 'The local directory where your phpMyAdmin installation is located.')); } protected function get_local_version($path) { $path = realpath($path) === false ? $path : realpath($path); if (file_exists($file = "$path/libraries/classes/Version.php")) { $regex = '@VERSION = \'(.*)\'@ismU'; } else if (file_exists($file = "$path/libraries/classes/Config.php")) { $regex = '@\$this->set\(\'PMA_VERSION\', \'(.*)\'\);@ismU'; } else if (file_exists($file = "$path/libraries/Config.class.php")) { $regex = '@\$this->set\(\'PMA_VERSION\', \'(.*)\'\);@ismU'; } else { throw new VNagException("Cannot find the phpMyAdmin version information at $path"); } $cont = @file_get_contents($file); if ($cont === false) { throw new VNagException("Cannot parse the phpMyAdmin version information at $path (cannot open file $file)"); } if (!preg_match($regex, $cont, $m)) { throw new VNagException("Cannot parse the phpMyAdmin version information at $path (cannot find version using regex)"); } return $m[1]; } protected function get_latest_version() { $cont = $this->url_get_contents('https://www.phpmyadmin.net/home_page/version.json'); if ($cont === false) { throw new VNagException('Cannot parse version from phpMyAdmin website. The plugin probably needs to be updated. (Cannot access phpmyadmin.net)'); } $json = @json_decode($cont, true); if ($json === false) { throw new VNagException('Cannot parse version from phpMyAdmin website. The plugin probably needs to be updated. (Invalid JSON data downloaded from phpmyadmin.net)'); } return $json['version']; } protected function cbRun($optional_args=array()) { $system_dir = $this->argSystemDir->getValue(); if (empty($system_dir)) { throw new VNagException("Please specify the directory of the phpMyAdmin installation."); } $system_dir = realpath($system_dir) === false ? $system_dir : realpath($system_dir); if (!is_dir($system_dir)) { throw new VNagException('Directory "'.$system_dir.'" not found.'); } $version = $this->get_local_version($system_dir); $latest_version = $this->get_latest_version(); if (version_compare($version,$latest_version) >= 0) { $this->setStatus(VNag::STATUS_OK); if ($version == $latest_version) { $this->setHeadline("Version $version (Latest version) at $system_dir", true); } else { $this->setHeadline("Version $version (Latest version $latest_version) at $system_dir", true); } } else { $this->setStatus(VNag::STATUS_WARNING); $this->setHeadline("Version $version is outdated (Latest version is $latest_version) at $system_dir", true); } } } <?php
- declare(ticks=1); require_once __DIR__ . '/../../framework/vnag_framework.inc.php'; require_once __DIR__ . '/PhpMyAdminVersionCheck.class.php'; $job = new PhpMyAdminVersionCheck(); $job->run(); unset($job); ¼VAŒÜÌâƒÞa ’±Ù=ÎU‘]aŸÈӚ©‰k ~y®w¬ؘ(
-Ē%÷öZvb÷FGBMB
\ No newline at end of file
+ declare(ticks=1); require_once __DIR__ . '/../../framework/vnag_framework.inc.php'; require_once __DIR__ . '/PhpMyAdminVersionCheck.class.php'; $job = new PhpMyAdminVersionCheck(); $job->run(); unset($job); Rqè àTÊBü='9ð)ý [£A+k¹]—,°†'NA/ÎômG^¾=;ȺãL މA=·-«t¸0/ö›¯à<GBMB
\ No newline at end of file
/trunk/bin/ping.phar
291,9 → 291,7
 
Extract_Phar::go();
__HALT_COMPILER(); ?>
[a:1:{s:23:"1.3.6.1.4.1.37476.3.0.2";s:301:"sha256||framework/vnag_framework.inc.php|460b109d1c578e9b6af41612e0312c9f36fd8beb51f7aa92f1b7bd49614568e8||plugins/ping/PingCheck.class.php|2887ce5ae5d2d80fb6a37e8eeceebad73bf549643adcce4ce9c06347a1fcdc2a||plugins/ping/check_ping.phps|cb5537c7f514c1020e727e5bdbf15fa04e0aab64e2d21274e23f1122906787c2||";} framework/vnag_framework.inc.phpLÙzï*eLُ4p”¤ plugins/ping/PingCheck.class.phpäzï*eä%Êpµ¤plugins/ping/check_ping.phps¼zï*e¼î?¤<?php ?>
<?php
i§a:1:{s:23:"1.3.6.1.4.1.37476.3.0.2";s:377:"sha256||<builder>|481cf75d675006b504520fd2acb3b29c89aea03aab64754e0adfb364de4914b2||framework/vnag_framework.inc.php|0387bf3134f8cc2d1ae24e139019c0edef19c1ba5ca765624efea0b469c7897f||plugins/ping/PingCheck.class.php|2887ce5ae5d2d80fb6a37e8eeceebad73bf549643adcce4ce9c06347a1fcdc2a||plugins/ping/check_ping.phps|cb5537c7f514c1020e727e5bdbf15fa04e0aab64e2d21274e23f1122906787c2||";} framework/vnag_framework.inc.phpBÙ» +eBÙÞß=¤ plugins/ping/PingCheck.class.phpä» +eä%Êpµ¤plugins/ping/check_ping.phps¼» +e¼î?¤<?php
if (!VNag::is_http_mode()) error_reporting(E_ALL); declare(ticks=1); set_time_limit(0); define('VNAG_JSONDATA_V1', 'oid:1.3.6.1.4.1.37476.2.3.1.1'); $OVERWRITE_ARGUMENTS = null; function _empty($x) { return is_null($x) || (trim($x) == ''); } abstract class VNag { const VNAG_VERSION = '2023-10-13'; const STATUS_OK = 0; const STATUS_WARNING = 1; const STATUS_CRITICAL = 2; const STATUS_UNKNOWN = 3; const STATUS_ERROR = 4; const STATUS_UP = 0; const STATUS_DOWN = 1; const STATUS_MAINTAIN = 2; const VERBOSITY_SUMMARY = 0; const VERBOSITY_ADDITIONAL_INFORMATION = 1; const VERBOSITY_CONFIGURATION_DEBUG = 2; const VERBOSITY_PLUGIN_DEBUG = 3; const MAX_VERBOSITY = self::VERBOSITY_PLUGIN_DEBUG; const STATUSMODEL_SERVICE = 0; const STATUSMODEL_HOST = 1; private $initialized = false; private $status = null; private $messages = array(); private $verbose_info = ''; private $warningRanges = array(); private $criticalRanges = array(); private $performanceDataObjects = array(); private static $exitcode = 0; private $helpObj = null; private $argHandler = null; const OUTPUT_NEVER = 0; const OUTPUT_SPECIAL = 1; const OUTPUT_NORMAL = 2; const OUTPUT_EXCEPTION = 4; const OUTPUT_ALWAYS = 7; public $http_visual_output = self::OUTPUT_ALWAYS; public $http_invisible_output = self::OUTPUT_ALWAYS; protected $html_before = ''; protected $html_after = ''; protected $statusmodel = self::STATUSMODEL_SERVICE; protected $show_status_in_headline = true; protected $default_status = self::STATUS_UNKNOWN; protected $default_warning_range = null; protected $default_critical_range = null; protected $argWarning; protected $argCritical; protected $argVersion; protected $argVerbosity; protected $argTimeout; protected $argHelp; protected $argUsage; public $id = null; protected static $http_serial_number = 0; public $privkey = null; public $privkey_password = null; public $sign_algo = null; public $pubkey = null; protected $warningSingleValueRangeBehaviors = array(self::SINGLEVALUE_RANGE_DEFAULT); protected $criticalSingleValueRangeBehaviors = array(self::SINGLEVALUE_RANGE_DEFAULT); const SINGLEVALUE_RANGE_DEFAULT = 0; const SINGLEVALUE_RANGE_VAL_GT_X_BAD = 1; const SINGLEVALUE_RANGE_VAL_GE_X_BAD = 2; const SINGLEVALUE_RANGE_VAL_LT_X_BAD = 3; const SINGLEVALUE_RANGE_VAL_LE_X_BAD = 4; public $password_out = null; public $password_in = null; public static function is_http_mode() { return php_sapi_name() !== 'cli'; } public function getHelpManager() { return $this->helpObj; } public function getArgumentHandler() { return $this->argHandler; } public function outputHTML($text, $after_visual_output=true) { if ($this->is_http_mode()) { if ($this->initialized) { if ($after_visual_output) { $this->html_after .= $text; } else { $this->html_before .= $text; } } else { echo $text; } } } protected function resetArguments() { $this->argWarning = null; $this->argCritical = null; $this->argVersion = null; $this->argVerbosity = null; $this->argTimeout = null; $this->argHelp = null; $this->argWarning = null; $this->argCritical = null; } public function registerExpectedStandardArguments($args) { $this->resetArguments(); for ($i=0; $i<strlen($args); $i++) { switch ($args[$i]) { case 'w': $this->addExpectedArgument($this->argWarning = new VNagArgument('w', 'warning', VNagArgument::VALUE_REQUIRED, VNagLang::$argname_value, VNagLang::$warning_range)); break; case 'c': $this->addExpectedArgument($this->argCritical = new VNagArgument('c', 'critical', VNagArgument::VALUE_REQUIRED, VNagLang::$argname_value, VNagLang::$critical_range)); break; case 'V': $this->addExpectedArgument($this->argVersion = new VNagArgument('V', 'version', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$prints_version)); break; case 'v': $this->addExpectedArgument($this->argVerbosity = new VNagArgument('v', 'verbose', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$verbosity_helptext)); break; case 't': $this->addExpectedArgument($this->argTimeout = new VNagArgument('t', 'timeout', VNagArgument::VALUE_REQUIRED, VNagLang::$argname_seconds, VNagLang::$timeout_helptext)); break; case 'h': $this->addExpectedArgument($this->argHelp = new VNagArgument('h', 'help', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$help_helptext)); break; default: $letter = $args[$i]; throw new VNagInvalidStandardArgument(sprintf(VNagLang::$no_standard_arguments_with_letter, $letter)); } } } public function addExpectedArgument($argObj) { $helpObjAddEntryMethod = new ReflectionMethod($this->helpObj, '_addOption'); $helpObjAddEntryMethod->setAccessible(true); $helpObjAddEntryMethod->invoke($this->helpObj, $argObj); $argHandlerAddEntryMethod = new ReflectionMethod($this->argHandler, '_addExpectedArgument'); $argHandlerAddEntryMethod->setAccessible(true); $argHandlerAddEntryMethod->invoke($this->argHandler, $argObj); } protected function createArgumentHandler() { $this->argHandler = new VNagArgumentHandler(); } protected function createHelpObject() { $this->helpObj = new VNagHelp(); } protected function checkInitialized() { if (!$this->initialized) throw new VNagFunctionCallOutsideSession(); } protected function getVerbosityLevel() { $this->checkInitialized(); if (!isset($this->argVerbosity)) { return self::VERBOSITY_SUMMARY; } else { $level = $this->argVerbosity->count(); if ($level > self::MAX_VERBOSITY) $level = self::MAX_VERBOSITY; return $level; } } public function getWarningRange($argumentNumber=0) { $this->checkInitialized(); if (!isset($this->warningRanges[$argumentNumber])) { if (!is_null($this->argWarning)) { $warning = $this->argWarning->getValue(); if (!is_null($warning)) { $vals = explode(',',$warning); foreach ($vals as $number => $val) { if (_empty($val)) { $this->warningRanges[$number] = null; } else { $singleValueBehavior = isset($this->warningSingleValueRangeBehaviors[$number]) ? $this->warningSingleValueRangeBehaviors[$number] : VNag::SINGLEVALUE_RANGE_DEFAULT; $this->warningRanges[$number] = new VNagRange($val, $singleValueBehavior); } } } else { $this->warningRanges[0] = $this->default_warning_range; } } else { return null; } } if (isset($this->warningRanges[$argumentNumber])) { return $this->warningRanges[$argumentNumber]; } else { return null; } } public function getCriticalRange($argumentNumber=0) { $this->checkInitialized(); if (!isset($this->criticalRanges[$argumentNumber])) { if (!is_null($this->argCritical)) { $critical = $this->argCritical->getValue(); if (!is_null($critical)) { $vals = explode(',',$critical); foreach ($vals as $number => $val) { $singleValueBehavior = isset($this->criticalSingleValueRangeBehaviors[$number]) ? $this->criticalSingleValueRangeBehaviors[$number] : VNag::SINGLEVALUE_RANGE_DEFAULT; $this->criticalRanges[$number] = new VNagRange($val, $singleValueBehavior); } } else { $this->criticalRanges[0] = $this->default_critical_range; } } else { return null; } } if (isset($this->criticalRanges[$argumentNumber])) { return $this->criticalRanges[$argumentNumber]; } else { return null; } } public function checkAgainstWarningRange($values, $force=true, $autostatus=true, $argumentNumber=0) { $this->checkInitialized(); if (!$this->getArgumentHandler()->isArgRegistered('w')) { throw new VNagRequiredArgumentNotRegistered('-w'); } $wr = $this->getWarningRange($argumentNumber); if (isset($wr)) { if ($wr->checkAlert($values)) { if ($autostatus) $this->setStatus(VNag::STATUS_WARNING); return true; } else { if ($autostatus) $this->setStatus(VNag::STATUS_OK); return false; } } else { if ($force) { if (($argumentNumber > 0) && (count($this->warningRanges) > 0)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$too_few_warning_ranges, $argumentNumber+1)); } else { throw new VNagRequiredArgumentMissing('-w'); } } } } public function checkAgainstCriticalRange($values, $force=true, $autostatus=true, $argumentNumber=0) { $this->checkInitialized(); if (!$this->getArgumentHandler()->isArgRegistered('c')) { throw new VNagRequiredArgumentNotRegistered('-c'); } $cr = $this->getCriticalRange($argumentNumber); if (isset($cr)) { if ($cr->checkAlert($values)) { if ($autostatus) $this->setStatus(VNag::STATUS_CRITICAL); return true; } else { if ($autostatus) $this->setStatus(VNag::STATUS_OK); return false; } } else { if ($force) { if (($argumentNumber > 0) && (count($this->warningRanges) > 0)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$too_few_critical_ranges, $argumentNumber+1)); } else { throw new VNagRequiredArgumentMissing('-c'); } } } } protected static function getBaddestExitcode($code1, $code2) { return max($code1, $code2); } public static function _shutdownHandler() { if (!self::is_http_mode()) { exit((int)self::$exitcode); } } protected function _exit($code) { self::$exitcode = $this->getBaddestExitcode($code, self::$exitcode); } private $constructed = false; function __construct() { $this->createHelpObject(); $this->createArgumentHandler(); $this->addExpectedArgument($this->argUsage = new VNagArgument('?', '', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$prints_usage)); $this->constructed = true; } function __destruct() { if (Timeouter::started()) { Timeouter::end(); } } public function run() { global $inside_vnag_run; $inside_vnag_run = true; try { if (!$this->constructed) { throw new VNagNotConstructed(VNagLang::$notConstructed); } try { $this->initialized = true; $this->html_before = ''; $this->html_after = ''; $this->setStatus(null, true); $this->messages = array(); register_shutdown_function(array($this, '_shutdownHandler')); if ($this->argHandler->illegalUsage()) { $content = $this->helpObj->printUsagePage(); $this->setStatus(VNag::STATUS_UNKNOWN); if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_visual_output & VNag::OUTPUT_SPECIAL) echo $this->writeVisualHTML($content); if ($this->http_invisible_output & VNag::OUTPUT_SPECIAL) echo $this->writeInvisibleHTML($content); echo $this->html_after; return; } else { echo $content; return $this->_exit($this->status); } } if (!is_null($this->argVersion) && ($this->argVersion->available())) { $content = $this->helpObj->printVersionPage(); $this->setStatus(VNag::STATUS_UNKNOWN); if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_visual_output & VNag::OUTPUT_SPECIAL) echo $this->writeVisualHTML($content); if ($this->http_invisible_output & VNag::OUTPUT_SPECIAL) echo $this->writeInvisibleHTML($content); echo $this->html_after; return; } else { echo $content; return $this->_exit($this->status); } } if (!is_null($this->argHelp) && ($this->argHelp->available())) { $content = $this->helpObj->printHelpPage(); $this->setStatus(VNag::STATUS_UNKNOWN); if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_visual_output & VNag::OUTPUT_SPECIAL) echo $this->writeVisualHTML($content); if ($this->http_invisible_output & VNag::OUTPUT_SPECIAL) echo $this->writeInvisibleHTML($content); echo $this->html_after; return; } else { echo $content; return $this->_exit($this->status); } } $this->getWarningRange(); $this->getCriticalRange(); if (!is_null($this->argTimeout)) { $timeout = $this->argTimeout->getValue(); if (!is_null($timeout)) { Timeouter::start($timeout); } } ob_start(); $init_ob_level = ob_get_level(); try { $this->cbRun(); if (ob_get_level() < $init_ob_level) throw new VNagImplementationErrorException(VNagLang::$output_level_lowered); } finally { while (ob_get_level() > $init_ob_level) @ob_end_clean(); } if (is_null($this->status)) $this->setStatus($this->default_status,true); $outputType = VNag::OUTPUT_NORMAL; } catch (Exception $e) { $this->handleException($e); $outputType = VNag::OUTPUT_EXCEPTION; } if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_invisible_output & $outputType) { echo $this->writeInvisibleHTML(); } if ($this->http_visual_output & $outputType) { echo $this->writeVisualHTML(); } echo $this->html_after; } else { echo $this->getNagiosConsoleText(); return $this->_exit($this->status); } Timeouter::end(); } finally { $inside_vnag_run = false; } } private function getNagiosConsoleText() { $ary_perfdata = $this->getPerformanceData(); $performancedata_first = array_shift($ary_perfdata); $performancedata_rest = implode(' ', $ary_perfdata); $status_text = VNagLang::status($this->status, $this->statusmodel); if (_empty($this->getHeadline())) { $content = $status_text; } else { if ($this->show_status_in_headline) { $content = $status_text.': '.$this->getHeadline(); } else { $content = $this->getHeadline(); } } if (!_empty($performancedata_first)) $content .= '|'.trim($performancedata_first); $content .= "\n"; if (!_empty($this->verbose_info)) { $content .= trim($this->verbose_info); } if (!_empty($performancedata_rest)) $content .= '|'.trim($performancedata_rest); $content .= "\n"; return trim($content)."\n"; } abstract protected function cbRun(); public function addPerformanceData($prefDataObj, $move_to_font=false, $verbosityLevel=VNag::VERBOSITY_SUMMARY) { $this->checkInitialized(); if ((!isset($this->argVerbosity)) && ($verbosityLevel > VNag::VERBOSITY_SUMMARY)) throw new VNagRequiredArgumentNotRegistered('-v'); if (self::getVerbosityLevel() < $verbosityLevel) return false; if ($move_to_font) { array_unshift($this->performanceDataObjects, $prefDataObj); } else { $this->performanceDataObjects[] = $prefDataObj; } return true; } public function getPerformanceData() { $this->checkInitialized(); return $this->performanceDataObjects; } public function removePerformanceData($prefDataObj) { if (($key = array_search($prefDataObj, $this->performanceDataObjects, true)) !== false) { unset($this->performanceDataObjects[$key]); return true; } else { return false; } } public function clearPerformanceData() { $this->performanceDataObjects = array(); } public function getVerboseInfo() { return $this->verbose_info; } public function clearVerboseInfo() { $this->verbose_info = ''; } private function writeVisualHTML($special_content=null) { if (!_empty($special_content)) { $content = $special_content; } else { $content = strtoupper(VNagLang::$status.': '.VNagLang::status($this->status, $this->statusmodel))."\n\n"; $content .= strtoupper(VNagLang::$message).":\n"; $status_text = VNagLang::status($this->status, $this->statusmodel); if (_empty($this->getHeadline())) { $content .= $status_text; } else { if ($this->show_status_in_headline) { $content .= $status_text.': '.trim($this->getHeadline()); } else { $content .= trim($this->getHeadline()); } } $content .= "\n\n"; if (!_empty($this->verbose_info)) { $content .= strtoupper(VNagLang::$verbose_info).":\n".trim($this->verbose_info)."\n\n"; } $perfdata = $this->getPerformanceData(); if (count($perfdata) > 0) { $content .= strtoupper(VNagLang::$performance_data).":\n"; foreach ($perfdata as $pd) { $content .= trim($pd)."\n"; } $content .= "\n"; } } $colorinfo = ''; $status = $this->getStatus(); if ($status == VNag::STATUS_OK) $colorinfo = ' style="background-color:green;color:white;font-weight:bold"'; else if ($status == VNag::STATUS_WARNING) $colorinfo = ' style="background-color:yellow;color:black;font-weight:bold"'; else if ($status == VNag::STATUS_CRITICAL) $colorinfo = ' style="background-color:red;color:white;font-weight:bold"'; else if ($status == VNag::STATUS_ERROR) $colorinfo = ' style="background-color:purple;color:white;font-weight:bold"'; else $colorinfo = ' style="background-color:lightgray;color:black;font-weight:bold"'; $html_content = trim($content); $html_content = htmlentities($html_content); $html_content = str_replace(' ', '&nbsp;', $html_content); $html_content = nl2br($html_content); return '<table border="1" cellspacing="2" cellpadding="2" style="width:100%" class="vnag_table">'. '<tr'.$colorinfo.' class="vnag_title_row">'. '<td>'.VNagLang::$nagios_output.'</td>'. '</tr>'. '<tr class="vnag_message_row">'. '<td><code>'. $html_content. '</code></td>'. '</tr>'. '</table>'; } protected function readInvisibleHTML($html) { $this->checkInitialized(); $doc = new DOMDocument(); @$doc->loadHTML($html); $tags = $doc->getElementsByTagName('script'); foreach ($tags as $tag) { $type = $tag->getAttribute('type'); if ($type !== 'application/json') continue; $json = $tag->nodeValue; if (!$json) continue; $data = @json_decode($json,true); if (!is_array($data)) continue; if (!isset($data['type'])) continue; if ($data['type'] === VNAG_JSONDATA_V1) { if (!isset($data['datasets'])) throw new VNagWebInfoException(VNagLang::$dataset_missing); foreach ($data['datasets'] as $dataset) { $payload = base64_decode($dataset['payload']); if (!$payload) { throw new VNagWebInfoException(VNagLang::$payload_not_base64); } if (isset($dataset['encryption'])) { $cryptInfo = $dataset['encryption']; if (!is_array($cryptInfo)) { throw new VNagWebInfoException(VNagLang::$dataset_encryption_no_array); } $password = is_null($this->password_in) ? '' : $this->password_in; $salt = base64_decode($cryptInfo['salt']); if ($cryptInfo['hash'] != hash('sha256',$salt.$password)) { if ($password == '') { throw new VNagWebInfoException(VNagLang::$require_password); } else { throw new VNagWebInfoException(VNagLang::$wrong_password); } } if (!function_exists('openssl_decrypt')) { throw new VNagException(VNagLang::$openssl_missing); } $payload = openssl_decrypt($payload, $cryptInfo['method'], $password, 0, $cryptInfo['iv']); } if (!is_null($this->pubkey) && ($this->pubkey !== '')) { if (substr($this->pubkey,0,3) === '---') { $public_key = $this->pubkey; } else { if (!file_exists($this->pubkey)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$pubkey_file_not_found, $this->pubkey)); } $public_key = @file_get_contents($this->pubkey); if (!$public_key) { throw new VNagPublicKeyException(sprintf(VNagLang::$pubkey_file_not_readable, $this->pubkey)); } } if (!isset($dataset['signature'])) { throw new VNagSignatureException(VNagLang::$signature_missing); } $signature = base64_decode($dataset['signature']); if (!$signature) { throw new VNagSignatureException(VNagLang::$signature_not_bas64); } if (!function_exists('openssl_verify')) { throw new VNagException(VNagLang::$openssl_missing); } $sign_algo = is_null($this->sign_algo) ? OPENSSL_ALGO_SHA256 : $this->sign_algo; if (!openssl_verify($payload, $signature, $public_key, $sign_algo)) { throw new VNagSignatureException(VNagLang::$signature_invalid); } } $payload = @json_decode($payload,true); if (!$payload) { throw new VNagWebInfoException(VNagLang::$payload_not_json); } if ($payload['id'] == $this->id) { return $payload; } } } } return null; } private function getNextMonitorID($peek=false) { $result = is_null($this->id) ? self::$http_serial_number : $this->id; if (!$peek) { $this->id = null; self::$http_serial_number++; } return $result; } private function writeInvisibleHTML($special_content=null) { $payload['id'] = $this->getNextMonitorID(); $payload['status'] = $this->getStatus(); if (!_empty($special_content)) { $payload['text'] = $special_content; } else { $payload['headline'] = $this->getHeadline(); $payload['verbose_info'] = $this->verbose_info; $payload['performance_data'] = array(); foreach ($this->performanceDataObjects as $perfdata) { $payload['performance_data'][] = (string)$perfdata; } } $payload = json_encode($payload); $dataset = array(); if (!is_null($this->privkey) && ($this->privkey !== '')) { if (!function_exists('openssl_pkey_get_private') || !function_exists('openssl_sign')) { throw new VNagException(VNagLang::$openssl_missing); } if (substr($this->privkey,0,3) === '---') { $pkeyid = @openssl_pkey_get_private($this->privkey, $this->privkey_password); if (!$pkeyid) { throw new VNagPrivateKeyException(sprintf(VNagLang::$privkey_not_readable)); } } else { if (!file_exists($this->privkey)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$privkey_file_not_found, $this->privkey)); } $pkeyid = @openssl_pkey_get_private('file://'.$this->privkey, $this->privkey_password); if (!$pkeyid) { throw new VNagPrivateKeyException(sprintf(VNagLang::$privkey_file_not_readable, $this->privkey)); } } $signature = ''; $sign_algo = is_null($this->sign_algo) ? OPENSSL_ALGO_SHA256 : $this->sign_algo; if (@openssl_sign($payload, $signature, $pkeyid, $sign_algo)) { if (version_compare(PHP_VERSION, '8.0.0') < 0) { openssl_free_key($pkeyid); } $dataset['signature'] = base64_encode($signature); } else { throw new VNagPrivateKeyException(sprintf(VNagLang::$signature_failed)); } } if (!is_null($this->password_out) && ($this->password_out !== '')) { if (!function_exists('openssl_encrypt')) { throw new VNagException(VNagLang::$openssl_missing); } $password = $this->password_out; $method = 'aes-256-ofb'; $iv = substr(hash('sha256', openssl_random_pseudo_bytes(32)), 0, 16); $salt = openssl_random_pseudo_bytes(32); $cryptInfo = array(); $cryptInfo['method'] = $method; $cryptInfo['iv'] = $iv; $cryptInfo['salt'] = base64_encode($salt); $cryptInfo['hash'] = hash('sha256', $salt.$password); $payload = openssl_encrypt($payload, $method, $password, 0, $iv); $dataset['encryption'] = $cryptInfo; } $dataset['payload'] = base64_encode($payload); $json = array(); $json['type'] = VNAG_JSONDATA_V1; $json['datasets'] = array($dataset); return '<script type="application/json">'. json_encode($json). '</script>'; } protected function appendHeadline($msg) { $this->checkInitialized(); if (_empty($msg)) return false; $this->messages[] = $msg; return true; } protected function changeHeadline($msg) { $this->checkInitialized(); if (_empty($msg)) { $this->messages = array(); } else { $this->messages = array($msg); } return true; } public function setHeadline($msg, $append=false, $verbosityLevel=VNag::VERBOSITY_SUMMARY) { $this->checkInitialized(); if ((!isset($this->argVerbosity)) && ($verbosityLevel > VNag::VERBOSITY_SUMMARY)) throw new VNagRequiredArgumentNotRegistered('-v'); if (self::getVerbosityLevel() < $verbosityLevel) $msg = ''; if ($append) { return $this->appendHeadline($msg); } else { return $this->changeHeadline($msg); } } public function getHeadline() { $this->checkInitialized(); return implode(', ', $this->messages); } public function addVerboseMessage($msg, $verbosityLevel=VNag::VERBOSITY_SUMMARY) { $this->checkInitialized(); if (self::getVerbosityLevel() >= $verbosityLevel) { $this->verbose_info .= $msg."\n"; } } public function setStatus($status, $force=false) { $this->checkInitialized(); if (($force) || is_null($this->status) || ($status > $this->status)) { $this->status = $status; } } public function getStatus() { $this->checkInitialized(); return $this->status; } protected static function exceptionText($exception) { $class = get_class($exception); $msg = $exception->getMessage(); if (!_empty($msg)) { return sprintf(VNagLang::$exception_x, $msg, $class); } else { return sprintf(VNagLang::$unhandled_exception_without_msg, $class); } } protected function handleException($exception) { $this->checkInitialized(); if (!VNag::is_http_mode()) { while (ob_get_level() > 0) @ob_end_clean(); } $this->clearVerboseInfo(); $this->clearPerformanceData(); if ($exception instanceof VNagException) { $this->setStatus($exception->getStatus()); } else { $this->setStatus(self::STATUS_ERROR); } $this->setHeadline($this->exceptionText($exception), false); if ($exception instanceof VNagImplementationErrorException) { $this->addVerboseMessage($exception->getTraceAsString(), VNag::VERBOSITY_SUMMARY); } else { if (isset($this->argVerbosity)) { $this->addVerboseMessage($exception->getTraceAsString(), VNag::VERBOSITY_ADDITIONAL_INFORMATION); } else { } } } protected function get_cache_dir() { $homedir = @getenv('HOME'); if ($homedir && is_dir($homedir)) { $try = "$homedir/.vnag/cache"; if (is_dir($try)) return $try; if (@mkdir($try,0777,true)) return $try; } $user = posix_getpwuid(posix_geteuid()); if (isset($user['dir']) && is_dir($user['dir'])) { $homedir = $user['dir']; $try = "$homedir/.vnag/cache"; if (is_dir($try)) return $try; if (@mkdir($try,0777,true)) return $try; } if (isset($user['name']) && is_dir($user['name'])) { $username = $user['name']; $try = "/tmp/vnag/cache"; if (is_dir($try)) return $try; if (@mkdir($try,0777,true)) return $try; } throw new VNagException("Cannot get cache dir"); } protected function url_get_contents($url, $max_cache_time=1*60*60, $context=null) { $cache_file = $this->get_cache_dir().'/'.hash('sha256',$url); if (file_exists($cache_file) && (time()-filemtime($cache_file) < $max_cache_time)) { $cont = @file_get_contents($cache_file); if ($cont === false) throw new Exception("Failed to get contents from $cache_file"); } else { $options = array( 'http'=>array( 'method'=>"GET", 'header'=>"Accept-language: en\r\n" . "User-Agent: Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B334b Safari/531.21.102011-10-16 20:23:10\r\n" ) ); if (is_null($context)) $context = stream_context_create($options); $cont = @file_get_contents($url, false, $context); if ($cont === false) throw new Exception("Failed to get contents from $url"); file_put_contents($cache_file, $cont); } return $cont; } } class VNagException extends Exception { public function getStatus() { return VNag::STATUS_ERROR; } } class VNagTimeoutException extends VNagException {} class VNagWebInfoException extends VNagException {} class VNagSignatureException extends VNagException {} class VNagPublicKeyException extends VNagException {} class VNagPrivateKeyException extends VNagException {} class VNagInvalidArgumentException extends VNagException { public function getStatus() { return VNag::STATUS_UNKNOWN; } } class VNagValueUomPairSyntaxException extends VNagInvalidArgumentException { public function __construct($str) { $e_msg = sprintf(VNagLang::$valueUomPairSyntaxError, $str); parent::__construct($e_msg); } } class VNagInvalidTimeoutException extends VNagInvalidArgumentException {} class VNagInvalidRangeException extends VNagInvalidArgumentException { public function __construct($msg) { $e_msg = VNagLang::$range_is_invalid; if (!_empty($msg)) $e_msg .= ': '.trim($msg); parent::__construct($e_msg); } } class VNagInvalidShortOpt extends VNagImplementationErrorException {} class VNagInvalidLongOpt extends VNagImplementationErrorException {} class VNagInvalidValuePolicy extends VNagImplementationErrorException {} class VNagIllegalStatusModel extends VNagImplementationErrorException {} class VNagNotConstructed extends VNagImplementationErrorException {} class VNagImplementationErrorException extends VNagException {} class VNagInvalidStandardArgument extends VNagImplementationErrorException {} class VNagFunctionCallOutsideSession extends VNagImplementationErrorException {} class VNagIllegalArgumentValuesException extends VNagImplementationErrorException {} class VNagRequiredArgumentNotRegistered extends VNagImplementationErrorException { public function __construct($required_argument) { $e_msg = sprintf(VNagLang::$query_without_expected_argument, $required_argument); parent::__construct($e_msg); } } class VNagRequiredArgumentMissing extends VNagInvalidArgumentException { public function __construct($required_argument) { $e_msg = sprintf(VNagLang::$required_argument_missing, $required_argument); parent::__construct($e_msg); } } class VNagUnknownUomException extends VNagInvalidArgumentException { public function __construct($uom) { $e_msg = sprintf(VNagLang::$perfdata_uom_not_recognized, $uom); parent::__construct($e_msg); } } class VNagNoCompatibleRangeUomFoundException extends VNagException {} class VNagMixedUomsNotImplemented extends VNagInvalidArgumentException { public function __construct($uom1, $uom2) { if (_empty($uom1)) $uom1 = VNagLang::$none; if (_empty($uom2)) $uom2 = VNagLang::$none; $e_msg = sprintf(VNagLang::$perfdata_mixed_uom_not_implemented, $uom1, $uom2); parent::__construct($e_msg); } } class VNagUomConvertException extends VNagInvalidArgumentException { public function __construct($uom1, $uom2) { if (_empty($uom1)) $uom1 = VNagLang::$none; if (_empty($uom2)) $uom2 = VNagLang::$none; $e_msg = sprintf(VNagLang::$convert_x_y_error, $uom1, $uom2); parent::__construct($e_msg); } } class VNagInvalidPerformanceDataException extends VNagInvalidArgumentException { public function __construct($msg) { $e_msg = VNagLang::$performance_data_invalid; if (!_empty($msg)) $e_msg .= ': '.trim($msg); parent::__construct($e_msg); } } class Timeouter { private static $start_time = false; private static $timeout; private static $fired = false; private static $registered = false; private function __construct() { } public static function start($timeout) { if (!is_numeric($timeout) || ($timeout <= 0)) { throw new VNagInvalidTimeoutException(sprintf(VNagLang::$timeout_value_invalid, $timeout)); } self::$start_time = microtime(true); self::$timeout = (float) $timeout; self::$fired = false; if (!self::$registered) { self::$registered = true; register_tick_function(array('Timeouter', 'tick')); } } public static function started() { return self::$registered; } public static function end() { if (self::$registered) { unregister_tick_function(array('Timeouter', 'tick')); self::$registered = false; } } public static function tick() { if ((!self::$fired) && ((microtime(true) - self::$start_time) > self::$timeout)) { self::$fired = true; throw new VNagTimeoutException(VNagLang::$timeout_exception); } } } class VNagArgument { const VALUE_FORBIDDEN = 0; const VALUE_REQUIRED = 1; const VALUE_OPTIONAL = 2; protected $shortopt; protected $longopts; protected $valuePolicy; protected $valueName; protected $helpText; protected $defaultValue = null; protected static $all_short = ''; protected static $all_long = array(); public function getShortOpt() { return $this->shortopt; } public function getLongOpts() { return $this->longopts; } public function getValuePolicy() { return $this->valuePolicy; } public function getValueName() { return $this->valueName; } public function getHelpText() { return $this->helpText; } static private function validateShortOpt($shortopt) { $m = array(); return preg_match('@^[a-zA-Z0-9\\+\\-\\?]$@', $shortopt, $m); } static private function validateLongOpt($longopt) { $m = array(); return preg_match('@^[a-zA-Z0-9\\+\\-\\?]+$@', $longopt, $m); } public function __construct($shortopt, $longopts, $valuePolicy, $valueName, $helpText, $defaultValue=null) { switch ($valuePolicy) { case VNagArgument::VALUE_FORBIDDEN: if (!_empty($valueName)) { throw new VNagImplementationErrorException(sprintf(VNagLang::$value_name_forbidden)); } break; case VNagArgument::VALUE_REQUIRED: if (_empty($valueName)) { throw new VNagImplementationErrorException(sprintf(VNagLang::$value_name_required)); } break; case VNagArgument::VALUE_OPTIONAL: if (_empty($valueName)) { throw new VNagImplementationErrorException(sprintf(VNagLang::$value_name_required)); } break; default: throw new VNagInvalidValuePolicy(sprintf(VNagLang::$illegal_valuepolicy, $valuePolicy)); } if (!_empty($shortopt)) { if (!self::validateShortOpt($shortopt)) { throw new VNagInvalidShortOpt(sprintf(VNagLang::$illegal_shortopt, $shortopt)); } } if (is_array($longopts)) { foreach ($longopts as $longopt) { if (!self::validateLongOpt($longopt)) { throw new VNagInvalidLongOpt(sprintf(VNagLang::$illegal_longopt, $longopt)); } } } else if (!_empty($longopts)) { if (!self::validateLongOpt($longopts)) { throw new VNagInvalidLongOpt(sprintf(VNagLang::$illegal_longopt, $longopts)); } $longopts = array($longopts); } else { $longopts = array(); } switch ($valuePolicy) { case VNagArgument::VALUE_FORBIDDEN: $policyApdx = ''; break; case VNagArgument::VALUE_REQUIRED: $policyApdx = ':'; break; case VNagArgument::VALUE_OPTIONAL: $policyApdx = '::'; break; default: throw new VNagInvalidValuePolicy(sprintf(VNagLang::$illegal_valuepolicy, $valuePolicy)); } if ((!is_null($shortopt)) && ($shortopt != '?')) self::$all_short .= $shortopt.$policyApdx; if (is_array($longopts)) { foreach ($longopts as $longopt) { self::$all_long[] = $longopt.$policyApdx; } } $this->shortopt = $shortopt; $this->longopts = $longopts; $this->valuePolicy = $valuePolicy; $this->valueName = $valueName; $this->helpText = $helpText; $this->defaultValue = $defaultValue; } protected static function getOptions() { global $OVERWRITE_ARGUMENTS; if (!is_null($OVERWRITE_ARGUMENTS)) { return $OVERWRITE_ARGUMENTS; } else if (VNag::is_http_mode()) { return $_REQUEST; } else { return getopt(self::$all_short, self::$all_long); } } public function count() { $options = self::getOptions(); $count = 0; if (isset($options[$this->shortopt])) { if (is_array($options[$this->shortopt])) { $count += count($options[$this->shortopt]); } else { $count += 1; } } if (!is_null($this->longopts)) { foreach ($this->longopts as $longopt) { if (isset($options[$longopt])) { if (is_array($options[$longopt])) { $count += count($options[$longopt]); } else { $count += 1; } } } } return $count; } public function available() { $options = self::getOptions(); if (isset($options[$this->shortopt])) return true; if (!is_null($this->longopts)) { foreach ($this->longopts as $longopt) { if (isset($options[$longopt])) return true; } } return false; } public function require() { if (!$this->available() && is_null($this->defaultValue)) { $opt = $this->shortopt; $opt = !_empty($opt) ? '-'.$opt : (isset($this->longopts[0]) ? '--'.$this->longopts[0] : '?'); throw new VNagRequiredArgumentMissing($opt); } } public function getValue() { $options = self::getOptions(); if (isset($options[$this->shortopt])) { $x = $options[$this->shortopt]; if (is_array($x) && (count($x) <= 1)) $options[$this->shortopt] = $options[$this->shortopt][0]; return $options[$this->shortopt]; } if (!is_null($this->longopts)) { foreach ($this->longopts as $longopt) { if (isset($options[$longopt])) { $x = $options[$longopt]; if (is_array($x) && (count($x) <= 1)) $options[$longopt] = $options[$longopt][0]; return $options[$longopt]; } } } return $this->defaultValue; } } class VNagArgumentHandler { protected $expectedArgs = array(); protected function _addExpectedArgument($argObj) { if ($argObj->getShortOpt() == '?') return false; if ($argObj->getShortOpt() == '-') return false; if ($argObj->getShortOpt() == '+') return false; $this->expectedArgs[] = $argObj; return true; } public function getArgumentObj($shortopt) { foreach ($this->expectedArgs as $argObj) { if ($argObj->getShortOpt() == $shortopt) return $argObj; } return null; } public function isArgRegistered($shortopt) { return !is_null($this->getArgumentObj($shortopt)); } public function illegalUsage() { global $argv; return (isset($argv[1])) && (($argv[1] == '-?') || ($argv[1] == '/?')); } } class VNagRange { public $start; public $end; public $warnInsideRange; public function __construct($rangeDef, $singleValueBehavior=VNag::SINGLEVALUE_RANGE_DEFAULT) { $m = array(); if (!preg_match('|^(@){0,1}([^:]+)(:){0,1}(.*)$|', $rangeDef, $m)) { throw new VNagInvalidRangeException(sprintf(VNagLang::$range_invalid_syntax, $rangeDef)); } $this->warnInsideRange = $m[1] === '@'; $this->start = null; $this->end = null; if ($m[3] === ':') { if ($m[2] === '~') { $this->start = '-inf'; } else { $this->start = new VNagValueUomPair($m[2]); } if (_empty($m[4])) { $this->end = 'inf'; } else { $this->end = new VNagValueUomPair($m[4]); } } else { assert(_empty($m[4])); assert(!_empty($m[2])); $x = $m[2]; if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_DEFAULT) { $this->start = new VNagValueUomPair('0'.((new VNagValueUomPair($x))->getUom())); $this->end = new VNagValueUomPair($x); } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_GT_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 0; $this->start = '-inf'; $this->end = new VNagValueUomPair($x); } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_GE_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 1; $this->start = new VNagValueUomPair($x); $this->end = 'inf'; } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_LT_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 0; $this->start = new VNagValueUomPair($x); $this->end = 'inf'; } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_LE_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 1; $this->start = '-inf'; $this->end = new VNagValueUomPair($x); } else { throw new VNagException(VNagLang::$illegalSingleValueBehavior); } } if (is_null($this->start)) { throw new VNagInvalidRangeException(VNagLang::$invalid_start_value); } if (is_null($this->end)) { throw new VNagInvalidRangeException(VNagLang::$invalid_end_value); } if (($this->start instanceof VNagValueUomPair) && ($this->end instanceof VNagValueUomPair) && (VNagValueUomPair::compare($this->start,$this->end) > 0)) { throw new VNagInvalidRangeException(VNagLang::$start_is_greater_than_end); } } public function __toString() { $ret = ''; if ($this->warnInsideRange) { $ret = '@'; } if ($this->start === '-inf') { $ret .= '~'; } else { $ret .= $this->start; } $ret .= ':'; if ($this->end !== 'inf') { $ret .= $this->end; } return $ret; } public function checkAlert($values) { $compatibleCount = 0; if (!is_array($values)) $values = array($values); foreach ($values as $value) { if (!($value instanceof VNagValueUomPair)) $value = new VNagValueUomPair($value); assert(($this->start === '-inf') || ($this->start instanceof VNagValueUomPair)); assert(($this->end === 'inf' ) || ($this->end instanceof VNagValueUomPair)); if (($this->start !== '-inf') && (!$this->start->compatibleWith($value))) continue; if (($this->end !== 'inf') && (!$this->end->compatibleWith($value))) continue; $compatibleCount++; if ($this->warnInsideRange) { return (($this->start === '-inf') || (VNagValueUomPair::compare($value,$this->start) >= 0)) && (($this->end === 'inf') || (VNagValueUomPair::compare($value,$this->end) <= 0)); } else { return (($this->start !== '-inf') && (VNagValueUomPair::compare($value,$this->start) < 0)) || (($this->end !== 'inf') && (VNagValueUomPair::compare($value,$this->end) > 0)); } } if ((count($values) > 0) and ($compatibleCount == 0)) { throw new VNagNoCompatibleRangeUomFoundException(VNagLang::$no_compatible_range_uom_found); } return false; } } class VNagValueUomPair { protected $value; protected $uom; public $roundTo = -1; public function isRelative() { return $this->uom === '%'; } public function getValue() { return $this->value; } public function getUom() { return $this->uom; } public function __toString() { if ($this->roundTo == -1) { return $this->value.$this->uom; } else { return round($this->value,$this->roundTo).$this->uom; } } public function __construct($str) { $m = array(); if (!preg_match('/^([\d\.]+)(.*)$/ism', $str, $m)) { throw new VNagValueUomPairSyntaxException($str); } $this->value = $m[1]; $this->uom = isset($m[2]) ? $m[2] : ''; if (!self::isKnownUOM($this->uom)) { throw new VNagUnknownUomException($this->uom); } } public static function isKnownUOM(string $uom) { $no_unit = ($uom === ''); $seconds = ($uom === 's') || ($uom === 'ms') || ($uom === 'us'); $percentage = ($uom === '%'); $bytes = ($uom === 'B') || ($uom === 'KB') || ($uom === 'MB') || ($uom === 'GB') || ($uom === 'TB'); $counter = ($uom === 'c'); return ($no_unit || $seconds || $percentage || $bytes || $counter); } public function normalize($target=null) { $res = clone $this; if ($res->uom === 'ms') { $res->uom = 's'; $res->value /= 1000; } if ($res->uom === 'us') { $res->uom = 's'; $res->value /= 1000 * 1000; } if ($res->uom === 'B') { $res->uom = 'MB'; $res->value /= 1024 * 1024; } if ($res->uom === 'KB') { $res->uom = 'MB'; $res->value /= 1024; } if ($res->uom === 'GB') { $res->uom = 'MB'; $res->value *= 1024; } if ($res->uom === 'TB') { $res->uom = 'MB'; $res->value *= 1024 * 1024; } if ($res->uom === 'c') { $res->uom = ''; } if (!is_null($target)) { if ($res->uom == 'MB') { if ($target == 'B') { $res->uom = 'B'; $res->value *= 1024 * 1024; } else if ($target == 'KB') { $res->uom = 'KB'; $res->value *= 1024; } else if ($target == 'MB') { $res->uom = 'MB'; $res->value *= 1; } else if ($target == 'GB') { $res->uom = 'GB'; $res->value /= 1024; } else if ($target == 'TB') { $res->uom = 'TB'; $res->value /= 1024 * 1024; } else { throw new VNagUomConvertException($res->uom, $target); } } else if ($res->uom == 's') { if ($target == 's') { $res->uom = 's'; $res->value /= 1; } else if ($target == 'ms') { $res->uom = 'ms'; $res->value /= 1000; } else if ($target == 'us') { $res->uom = 'us'; $res->value /= 1000 * 1000; } else { throw new VNagUomConvertException($res->uom, $target); } } else { throw new VNagUomConvertException($res->uom, $target); } } return $res; } public function compatibleWith(VNagValueUomPair $other) { $a = $this->normalize(); $b = $other->normalize(); return ($a->uom == $b->uom); } public static function compare(VNagValueUomPair $left, VNagValueUomPair $right) { $a = $left->normalize(); $b = $right->normalize(); if ($a->uom != $b->uom) throw new VNagMixedUomsNotImplemented($a->uom, $b->uom); if ($a->value > $b->value) return 1; if ($a->value == $b->value) return 0; if ($a->value < $b->value) return -1; } } class VNagPerformanceData { protected $label; protected $value; protected $warn = null; protected $crit = null; protected $min = null; protected $max = null; public static function createByString($perfdata) { $perfdata = trim($perfdata); $ary = explode('=',$perfdata); if (count($ary) != 2) { throw new VNagInvalidPerformanceDataException(sprintf(VNagLang::$perfdata_line_invalid, $perfdata)); } $label = $ary[0]; $bry = explode(';',$ary[1]); if (substr($label,0,1) === "'") $label = substr($label, 1, strlen($label)-2); $value = $bry[0]; $warn = isset($bry[1]) ? $bry[1] : null; $crit = isset($bry[2]) ? $bry[2] : null; $min = isset($bry[3]) ? $bry[3] : null; $max = isset($bry[4]) ? $bry[4] : null; return new self($label, $value, $warn, $crit, $min, $max); } public function __construct($label, $value, $warn=null, $crit=null, $min=null, $max=null) { if (strpos($label, '=') !== false) throw new VNagInvalidPerformanceDataException(VNagLang::$perfdata_label_equal_sign_forbidden); $label = str_replace("'", "''", $label); $m = array(); if ((!_empty($min)) && (!preg_match('|^[-0-9\\.]+$|', $min, $m))) { throw new VNagInvalidPerformanceDataException(VNagLang::$perfdata_min_must_be_in_class); } if ((!_empty($max)) && (!preg_match('|^[-0-9\\.]+$|', $max, $m))) { throw new VNagInvalidPerformanceDataException(VNagLang::$perfdata_max_must_be_in_class); } $this->label = $label; $this->value = ($value == 'U') ? 'U' : new VNagValueUomPair($value); $this->warn = $warn; $this->crit = $crit; $this->min = $min; $this->max = $max; } public function __toString() { $label = $this->label; $value = $this->value; $warn = $this->warn; $crit = $this->crit; $min = $this->min; $max = $this->max; $label = str_replace("''", "'", $label); return "'$label'=$value". ';'.(is_null($warn) ? '' : $warn). ';'.(is_null($crit) ? '' : $crit). ';'.(is_null($min) ? '' : $min). ';'.(is_null($max) ? '' : $max); } } class VNagHelp { public $word_wrap_width = 80; public $argument_indent = 7; public function printUsagePage() { $usage = $this->getUsage(); if (_empty($usage)) { $usage = VNagLang::$no_syntax_defined; } return trim($usage)."\n"; } public function printVersionPage() { $out = trim($this->getNameAndVersion())."\n"; if ($this->word_wrap_width > 0) $out = wordwrap($out, $this->word_wrap_width, "\n", false); return $out; } static private function _conditionalLine($line, $terminator='', $prefix='') { if (!_empty($line)) { return trim($line).$terminator; } return ''; } public function printHelpPage() { $out = ''; $out .= self::_conditionalLine($this->getNameAndVersion(), "\n"); $out .= self::_conditionalLine($this->getCopyright(), "\n"); $out .= ($out != '') ? "\n" : ''; $out .= self::_conditionalLine($this->getShortDescription(), "\n\n\n"); $out .= self::_conditionalLine($this->getUsage(), "\n\n"); $out .= VNagLang::$options."\n"; foreach ($this->options as $argObj) { $out .= $this->printArgumentHelp($argObj); } $out .= self::_conditionalLine($this->getFootNotes(), "\n\n", "\n"); if ($this->word_wrap_width > 0) $out = wordwrap($out, $this->word_wrap_width, "\n", false); return $out; } protected $options = array(); protected function _addOption($argObj) { $this->options[] = $argObj; } protected function printArgumentHelp($argObj) { $identifiers = array(); $shortopt = $argObj->getShortopt(); if (!_empty($shortopt)) $identifiers[] = '-'.$shortopt; $longopts = $argObj->getLongopts(); if (!is_null($longopts)) { foreach ($longopts as $longopt) { if (!_empty($longopt)) $identifiers[] = '--'.$longopt; } } if (count($identifiers) == 0) return; $valueName = $argObj->getValueName(); $arginfo = ''; switch ($argObj->getValuePolicy()) { case VNagArgument::VALUE_FORBIDDEN: $arginfo = ''; break; case VNagArgument::VALUE_REQUIRED: $arginfo = '='.$valueName; break; case VNagArgument::VALUE_OPTIONAL: $arginfo = '[='.$valueName.']'; break; } $out = ''; $out .= implode(', ', $identifiers).$arginfo."\n"; $content = trim($argObj->getHelpText()); if ($this->word_wrap_width > 0) $content = wordwrap($content, $this->word_wrap_width-$this->argument_indent, "\n", false); $lines = explode("\n", $content); foreach ($lines as $line) { $out .= str_repeat(' ', $this->argument_indent).$line."\n"; } $out .= "\n"; return $out; } protected $pluginName; public function setPluginName($pluginName) { $this->pluginName = $this->replaceStuff($pluginName); } public function getPluginName() { if (_empty($this->pluginName)) { global $argv; return basename($argv[0]); } else { return $this->pluginName; } } protected $version; public function setVersion($version) { $this->version = $this->replaceStuff($version); } public function getVersion() { return $this->version; } public function getNameAndVersion() { $ret = $this->getPluginName(); if (_empty($ret)) return null; $ver = $this->getVersion(); if (!_empty($ver)) { $ret = sprintf(VNagLang::$x_version_x, $ret, $ver); } $ret = trim($ret); return $ret; } protected $copyright; public function setCopyright($copyright) { $this->copyright = $this->replaceStuff($copyright); } private function getVNagCopyright() { if (VNag::is_http_mode()) { $vts_email = 'www.viathinksoft.com'; } else { $vts_email = base64_decode('aW5mb0B2aWF0aGlua3NvZnQuZGU='); } return "VNag Framework ".VNag::VNAG_VERSION." (C) 2014-".date('Y')." ViaThinkSoft <$vts_email>"; } public function getCopyright() { if (_empty($this->copyright)) { return sprintf(VNagLang::$plugin_uses, $this->getVNagCopyright()); } else { return trim($this->copyright)."\n".sprintf(VNagLang::$uses, $this->getVNagCopyright()); } } protected $shortDescription; public function setShortDescription($shortDescription) { $this->shortDescription = $this->replaceStuff($shortDescription); } public function getShortDescription() { if (_empty($this->shortDescription)) { return null; } else { $content = $this->shortDescription; if ($this->word_wrap_width > 0) $content = wordwrap($content, $this->word_wrap_width, "\n", false); return $content; } } protected function replaceStuff($text) { global $argv; if (php_sapi_name() == 'cli') { $text = str_replace('$SCRIPTNAME$', $argv[0], $text); } else { $text = str_replace('$SCRIPTNAME$', basename($_SERVER['SCRIPT_NAME']), $text); } $text = str_replace('$CURYEAR$', date('Y'), $text); return $text; } protected $syntax; public function setSyntax($syntax) { $syntax = $this->replaceStuff($syntax); $this->syntax = $syntax; } public function getUsage() { if (_empty($this->syntax)) { return null; } else { return sprintf(VNagLang::$usage_x, $this->syntax); } } protected $footNotes; public function setFootNotes($footNotes) { $this->footNotes = $this->replaceStuff($footNotes); } public function getFootNotes() { return $this->footNotes; } } class VNagLang { public static function status($code, $statusmodel) { switch ($statusmodel) { case VNag::STATUSMODEL_SERVICE: switch ($code) { case VNag::STATUS_OK: return 'OK'; case VNag::STATUS_WARNING: return 'Warning'; case VNag::STATUS_CRITICAL: return 'Critical'; case VNag::STATUS_UNKNOWN: return 'Unknown'; default: return sprintf('Error (%d)', $code); } case VNag::STATUSMODEL_HOST: switch ($code) { case VNag::STATUS_UP: return 'Up'; case VNag::STATUS_DOWN: return 'Down'; default: return sprintf('Maintain last state (%d)', $code); } default: throw new VNagIllegalStatusModel(sprintf(self::$illegal_statusmodel, $statusmodel)); } } static $nagios_output = 'VNag-Output'; static $verbose_info = 'Verbose information'; static $status = 'Status'; static $message = 'Message'; static $performance_data = 'Performance data'; static $status_ok = 'OK'; static $status_warn = 'Warning'; static $status_critical = 'Critical'; static $status_unknown = 'Unknown'; static $status_error = 'Error'; static $unhandled_exception_without_msg = "Unhandled exception of type %s"; static $plugin_uses = 'This plugin uses %s'; static $uses = 'uses %s'; static $x_version_x = '%s, version %s'; static $argname_value = 'value'; static $argname_seconds = 'seconds'; static $query_without_expected_argument = "The argument '%s' is queried, but was not added to the list of expected arguments. Please contact the plugin author."; static $required_argument_missing = "The argument '%s' is required."; static $performance_data_invalid = 'Performance data invalid.'; static $no_standard_arguments_with_letter = "No standard argument with letter '%s' exists."; static $invalid_start_value = 'Invalid start value.'; static $invalid_end_value = 'Invalid end value.'; static $start_is_greater_than_end = 'Start is greater than end value.'; static $value_name_forbidden = "Implementation error: You may not define a value name for the argument, because the value policy is VALUE_FORBIDDEN."; static $value_name_required = "Implementation error: Please define a name for the argument (so it can be shown in the help page)."; static $illegal_shortopt = "Illegal shortopt '-%s'."; static $illegal_longopt = "Illegal longopt '--%s'."; static $illegal_valuepolicy = "valuePolicy has illegal value '%s'."; static $range_invalid_syntax = "Syntax error in range '%s'."; static $timeout_value_invalid = "Timeout value '%s' is invalid."; static $range_is_invalid = 'Range is invalid.'; static $timeout_exception = 'Timeout!'; static $perfdata_label_equal_sign_forbidden = 'Label may not contain an equal sign.'; static $perfdata_value_must_be_in_class = 'Value must be in class [-0-9.] or be \'U\' if the actual value can\'t be determined.'; static $perfdata_min_must_be_in_class = 'Min must be in class [-0-9.] or empty.'; static $perfdata_max_must_be_in_class = 'Max must be in class [-0-9.] or empty.'; static $perfdata_uom_not_recognized = 'UOM (unit of measurement) "%s" is not recognized.'; static $perfdata_mixed_uom_not_implemented = 'Mixed UOMs (%s and %s) are currently not supported.'; static $no_compatible_range_uom_found = 'Measured values are not compatible with the provided warning/critical parameter. Most likely, the UOM is incompatible.'; static $exception_x = '%s (%s)'; static $no_syntax_defined = 'The author of this plugin has not defined a syntax for this plugin.'; static $usage_x = "Usage:\n%s"; static $options = "Options:"; static $illegal_statusmodel = "Invalid statusmodel %d."; static $none = '[none]'; static $valueUomPairSyntaxError = 'Syntax error at "%s". Syntax must be Value[UOM].'; static $too_few_warning_ranges = "You have too few warning ranges (currently trying to get element %d)."; static $too_few_critical_ranges = "You have too few critical ranges (currently trying to get element %d)."; static $dataset_missing = 'Dataset missing.'; static $payload_not_base64 = 'The payload is not valid Base64.'; static $payload_not_json = 'The payload is not valid JSON.'; static $signature_missing = 'The signature is missing.'; static $signature_not_bas64 = 'The signature is not valid Base64.'; static $signature_invalid = 'The signature is invalid. The connection might have been tampered, or a different key is used.'; static $pubkey_file_not_found = "Public key file %s was not found."; static $pubkey_file_not_readable = "Public key file %s is not readable."; static $privkey_file_not_found = "Private key file %s was not found."; static $privkey_not_readable = "Private key is not readable."; static $privkey_file_not_readable = "Private key file %s is not readable."; static $signature_failed = "Signature failed."; static $perfdata_line_invalid = "Performance data line %s is invalid."; static $singlevalue_unexpected_at_symbol = 'This plugin does not allow the @-symbol at ranges for single values.'; static $illegalSingleValueBehavior = "Illegal value for 'singleValueBehavior'. Please contact the creator of the plugin."; static $dataset_encryption_no_array = 'Dataset encryption information invalid.'; static $require_password = 'This resource is protected with a password. Please provide a password.'; static $wrong_password = 'This resource is protected with a password. You have provided the wrong password, or it was changed.'; static $convert_x_y_error = 'Cannot convert from UOM %s to UOM %s.'; static $php_error = 'PHP has detected an error in the plugin. Please contact the plugin author.'; static $output_level_lowered = "Output Buffer level lowered during cbRun(). Please contact the plugin author."; static $openssl_missing = "OpenSSL is missing. Therefore, encryption and signatures are not available."; static $warning_range = 'Warning range'; static $critical_range = 'Critical range'; static $prints_version = 'Prints version'; static $verbosity_helptext = 'Verbosity -v, -vv or -vvv'; static $timeout_helptext = 'Sets timeout in seconds'; static $help_helptext = 'Prints help page'; static $prints_usage = 'Prints usage'; static $notConstructed = 'Parent constructor not called with parent::__construct().'; } function vnagErrorHandler($errorkind, $errortext, $file, $line) { global $inside_vnag_run; if (!$inside_vnag_run && VNag::is_http_mode()) { return false; } if (!(error_reporting() & $errorkind)) { return true; } if (defined('E_ERROR') && ($errorkind == E_ERROR)) $errorkind = 'Error'; if (defined('E_WARNING') && ($errorkind == E_WARNING)) $errorkind = 'Warning'; if (defined('E_PARSE') && ($errorkind == E_PARSE)) $errorkind = 'Parse'; if (defined('E_NOTICE') && ($errorkind == E_NOTICE)) $errorkind = 'Notice'; if (defined('E_CORE_ERROR') && ($errorkind == E_CORE_ERROR)) $errorkind = 'Core Error'; if (defined('E_CORE_WARNING') && ($errorkind == E_CORE_WARNING)) $errorkind = 'Core Warning'; if (defined('E_COMPILE_ERROR') && ($errorkind == E_COMPILE_ERROR)) $errorkind = 'Compile Error'; if (defined('E_COMPILE_WARNING') && ($errorkind == E_COMPILE_WARNING)) $errorkind = 'Compile Warning'; if (defined('E_USER_ERROR') && ($errorkind == E_USER_ERROR)) $errorkind = 'User Error'; if (defined('E_USER_WARNING') && ($errorkind == E_USER_WARNING)) $errorkind = 'User Warning'; if (defined('E_USER_NOTICE') && ($errorkind == E_USER_NOTICE)) $errorkind = 'User Notice'; if (defined('E_STRICT') && ($errorkind == E_STRICT)) $errorkind = 'Strict'; if (defined('E_RECOVERABLE_ERROR') && ($errorkind == E_RECOVERABLE_ERROR)) $errorkind = 'Recoverable Error'; if (defined('E_DEPRECATED') && ($errorkind == E_DEPRECATED)) $errorkind = 'Deprecated'; if (defined('E_USER_DEPRECATED') && ($errorkind == E_USER_DEPRECATED)) $errorkind = 'User Deprecated'; throw new VNagException(VNagLang::$php_error . " $errortext at $file:$line (kind $errorkind)"); } $inside_vnag_run = false; $old_error_handler = set_error_handler("vnagErrorHandler"); <?php
declare(ticks=1); class PingCheck extends VNag { protected $argHostname = null; public function __construct() { parent::__construct(); $this->registerExpectedStandardArguments('Vhtwc'); $this->getHelpManager()->setPluginName('check_ping'); $this->getHelpManager()->setVersion('2023-10-13'); $this->getHelpManager()->setShortDescription('This plugin performs a simple ping.'); $this->getHelpManager()->setCopyright('Copyright (C) 2011-$CURYEAR$ Daniel Marschall, ViaThinkSoft.'); $this->getHelpManager()->setSyntax('$SCRIPTNAME$ -H hostname'); $this->getHelpManager()->setFootNotes('If you encounter bugs, please contact ViaThinkSoft at www.viathinksoft.com'); $this->addExpectedArgument($this->argHostname = new VNagArgument('H', 'hostname', VNagArgument::VALUE_REQUIRED, 'hostname', 'Hostname or IP address to be pinged', null)); } protected function cbRun($optional_args=array()) { $host = $this->argHostname->getValue(); if (is_null($host)) throw new VNagException("Please enter a hostname"); $this->outputHTML("<h2>Host ".htmlentities($host)."</h2>\n\n", true); if (self::is_ipv6($host)) { if (self::is_windows()) { exec("ping -6 -n 4 ".escapeshellarg($host), $outary, $code); } else { exec("ping6 -c 4 -- ".escapeshellarg($host).' 2>&1', $outary, $code); } } else { if (self::is_windows()) { exec("ping -n 4 ".escapeshellarg($host), $outary, $code); } else { exec("ping -c 4 -- ".escapeshellarg($host).' 2>&1', $outary, $code); } } $execresult = implode("\n", $outary); $execresult = trim($execresult); if ($execresult == '') { throw new VNagException('Could not launch ping executable.'); } if ($code != 0) { $this->setStatus(VNag::STATUS_WARNING); $this->setHeadline("Ping failed", true); $this->outputHTML('<p><font color="red" size="+2">Ping failed</font></p>', true); } else { $this->setStatus(VNag::STATUS_OK); $this->outputHTML('<p><font color="green" size="+2">Ping OK</font></p>', true); } $this->outputHTML('<pre>'.htmlentities($execresult).'</pre>', true); } private static function is_windows() { if (strtolower(getenv('OS')) == 'windows_nt') return true; if (defined('PHP_OS') && (PHP_OS == 'win')) return true; if (getenv('windir') != '') return true; return false; } private static function is_ipv6($host) { return strpos($host, ':') !== false; } } <?php
-覺Ө@ª å{¥î¯~«^©GBMB
\ No newline at end of file
+ declare(ticks=1); require_once __DIR__ . '/../../framework/vnag_framework.inc.php'; require_once __DIR__ . '/PingCheck.class.php'; $job = new PingCheck(); $job->run(); unset($job); ¼×½¯P,IéK²H‰—Î¥ÁÇòZRPlƵ1ƒ-ç»Ì¥GªkI2Âr1|³$–¤*~JvÚ«~î<ÀWGBMB
\ No newline at end of file
/trunk/bin/pmwiki_version.phar
291,10 → 291,9
 
Extract_Phar::go();
__HALT_COMPILER(); ?>
k‚a:1:{s:23:"1.3.6.1.4.1.37476.3.0.2";s:340:"sha256||framework/vnag_framework.inc.php|460b109d1c578e9b6af41612e0312c9f36fd8beb51f7aa92f1b7bd49614568e8||plugins/pmwiki_version/PmWikiVersionCheck.class.php|5d76a6a753c6323546b3e3c327714d90570f191a3d24cb82e9e4db958e459e85||plugins/pmwiki_version/check_pmwiki_version.phps|fd72d3ade619a29884a4b4fc022fd4beab0d56becc10ed7b0a97b9defa1adcdd||";} framework/vnag_framework.inc.phpLÙzï*eLُ4p”¤3plugins/pmwiki_version/PmWikiVersionCheck.class.php
zï*e
pú3¤0plugins/pmwiki_version/check_pmwiki_version.phpsÎzï*eÎv‰k°¤<?php ?>
<?php
·Îa:1:{s:23:"1.3.6.1.4.1.37476.3.0.2";s:416:"sha256||<builder>|481cf75d675006b504520fd2acb3b29c89aea03aab64754e0adfb364de4914b2||framework/vnag_framework.inc.php|0387bf3134f8cc2d1ae24e139019c0edef19c1ba5ca765624efea0b469c7897f||plugins/pmwiki_version/PmWikiVersionCheck.class.php|5d76a6a753c6323546b3e3c327714d90570f191a3d24cb82e9e4db958e459e85||plugins/pmwiki_version/check_pmwiki_version.phps|fd72d3ade619a29884a4b4fc022fd4beab0d56becc10ed7b0a97b9defa1adcdd||";} framework/vnag_framework.inc.phpBÙ» +eBÙÞß=¤3plugins/pmwiki_version/PmWikiVersionCheck.class.php
» +e
pú3¤0plugins/pmwiki_version/check_pmwiki_version.phpsλ +eÎv‰k°¤<?php
if (!VNag::is_http_mode()) error_reporting(E_ALL); declare(ticks=1); set_time_limit(0); define('VNAG_JSONDATA_V1', 'oid:1.3.6.1.4.1.37476.2.3.1.1'); $OVERWRITE_ARGUMENTS = null; function _empty($x) { return is_null($x) || (trim($x) == ''); } abstract class VNag { const VNAG_VERSION = '2023-10-13'; const STATUS_OK = 0; const STATUS_WARNING = 1; const STATUS_CRITICAL = 2; const STATUS_UNKNOWN = 3; const STATUS_ERROR = 4; const STATUS_UP = 0; const STATUS_DOWN = 1; const STATUS_MAINTAIN = 2; const VERBOSITY_SUMMARY = 0; const VERBOSITY_ADDITIONAL_INFORMATION = 1; const VERBOSITY_CONFIGURATION_DEBUG = 2; const VERBOSITY_PLUGIN_DEBUG = 3; const MAX_VERBOSITY = self::VERBOSITY_PLUGIN_DEBUG; const STATUSMODEL_SERVICE = 0; const STATUSMODEL_HOST = 1; private $initialized = false; private $status = null; private $messages = array(); private $verbose_info = ''; private $warningRanges = array(); private $criticalRanges = array(); private $performanceDataObjects = array(); private static $exitcode = 0; private $helpObj = null; private $argHandler = null; const OUTPUT_NEVER = 0; const OUTPUT_SPECIAL = 1; const OUTPUT_NORMAL = 2; const OUTPUT_EXCEPTION = 4; const OUTPUT_ALWAYS = 7; public $http_visual_output = self::OUTPUT_ALWAYS; public $http_invisible_output = self::OUTPUT_ALWAYS; protected $html_before = ''; protected $html_after = ''; protected $statusmodel = self::STATUSMODEL_SERVICE; protected $show_status_in_headline = true; protected $default_status = self::STATUS_UNKNOWN; protected $default_warning_range = null; protected $default_critical_range = null; protected $argWarning; protected $argCritical; protected $argVersion; protected $argVerbosity; protected $argTimeout; protected $argHelp; protected $argUsage; public $id = null; protected static $http_serial_number = 0; public $privkey = null; public $privkey_password = null; public $sign_algo = null; public $pubkey = null; protected $warningSingleValueRangeBehaviors = array(self::SINGLEVALUE_RANGE_DEFAULT); protected $criticalSingleValueRangeBehaviors = array(self::SINGLEVALUE_RANGE_DEFAULT); const SINGLEVALUE_RANGE_DEFAULT = 0; const SINGLEVALUE_RANGE_VAL_GT_X_BAD = 1; const SINGLEVALUE_RANGE_VAL_GE_X_BAD = 2; const SINGLEVALUE_RANGE_VAL_LT_X_BAD = 3; const SINGLEVALUE_RANGE_VAL_LE_X_BAD = 4; public $password_out = null; public $password_in = null; public static function is_http_mode() { return php_sapi_name() !== 'cli'; } public function getHelpManager() { return $this->helpObj; } public function getArgumentHandler() { return $this->argHandler; } public function outputHTML($text, $after_visual_output=true) { if ($this->is_http_mode()) { if ($this->initialized) { if ($after_visual_output) { $this->html_after .= $text; } else { $this->html_before .= $text; } } else { echo $text; } } } protected function resetArguments() { $this->argWarning = null; $this->argCritical = null; $this->argVersion = null; $this->argVerbosity = null; $this->argTimeout = null; $this->argHelp = null; $this->argWarning = null; $this->argCritical = null; } public function registerExpectedStandardArguments($args) { $this->resetArguments(); for ($i=0; $i<strlen($args); $i++) { switch ($args[$i]) { case 'w': $this->addExpectedArgument($this->argWarning = new VNagArgument('w', 'warning', VNagArgument::VALUE_REQUIRED, VNagLang::$argname_value, VNagLang::$warning_range)); break; case 'c': $this->addExpectedArgument($this->argCritical = new VNagArgument('c', 'critical', VNagArgument::VALUE_REQUIRED, VNagLang::$argname_value, VNagLang::$critical_range)); break; case 'V': $this->addExpectedArgument($this->argVersion = new VNagArgument('V', 'version', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$prints_version)); break; case 'v': $this->addExpectedArgument($this->argVerbosity = new VNagArgument('v', 'verbose', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$verbosity_helptext)); break; case 't': $this->addExpectedArgument($this->argTimeout = new VNagArgument('t', 'timeout', VNagArgument::VALUE_REQUIRED, VNagLang::$argname_seconds, VNagLang::$timeout_helptext)); break; case 'h': $this->addExpectedArgument($this->argHelp = new VNagArgument('h', 'help', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$help_helptext)); break; default: $letter = $args[$i]; throw new VNagInvalidStandardArgument(sprintf(VNagLang::$no_standard_arguments_with_letter, $letter)); } } } public function addExpectedArgument($argObj) { $helpObjAddEntryMethod = new ReflectionMethod($this->helpObj, '_addOption'); $helpObjAddEntryMethod->setAccessible(true); $helpObjAddEntryMethod->invoke($this->helpObj, $argObj); $argHandlerAddEntryMethod = new ReflectionMethod($this->argHandler, '_addExpectedArgument'); $argHandlerAddEntryMethod->setAccessible(true); $argHandlerAddEntryMethod->invoke($this->argHandler, $argObj); } protected function createArgumentHandler() { $this->argHandler = new VNagArgumentHandler(); } protected function createHelpObject() { $this->helpObj = new VNagHelp(); } protected function checkInitialized() { if (!$this->initialized) throw new VNagFunctionCallOutsideSession(); } protected function getVerbosityLevel() { $this->checkInitialized(); if (!isset($this->argVerbosity)) { return self::VERBOSITY_SUMMARY; } else { $level = $this->argVerbosity->count(); if ($level > self::MAX_VERBOSITY) $level = self::MAX_VERBOSITY; return $level; } } public function getWarningRange($argumentNumber=0) { $this->checkInitialized(); if (!isset($this->warningRanges[$argumentNumber])) { if (!is_null($this->argWarning)) { $warning = $this->argWarning->getValue(); if (!is_null($warning)) { $vals = explode(',',$warning); foreach ($vals as $number => $val) { if (_empty($val)) { $this->warningRanges[$number] = null; } else { $singleValueBehavior = isset($this->warningSingleValueRangeBehaviors[$number]) ? $this->warningSingleValueRangeBehaviors[$number] : VNag::SINGLEVALUE_RANGE_DEFAULT; $this->warningRanges[$number] = new VNagRange($val, $singleValueBehavior); } } } else { $this->warningRanges[0] = $this->default_warning_range; } } else { return null; } } if (isset($this->warningRanges[$argumentNumber])) { return $this->warningRanges[$argumentNumber]; } else { return null; } } public function getCriticalRange($argumentNumber=0) { $this->checkInitialized(); if (!isset($this->criticalRanges[$argumentNumber])) { if (!is_null($this->argCritical)) { $critical = $this->argCritical->getValue(); if (!is_null($critical)) { $vals = explode(',',$critical); foreach ($vals as $number => $val) { $singleValueBehavior = isset($this->criticalSingleValueRangeBehaviors[$number]) ? $this->criticalSingleValueRangeBehaviors[$number] : VNag::SINGLEVALUE_RANGE_DEFAULT; $this->criticalRanges[$number] = new VNagRange($val, $singleValueBehavior); } } else { $this->criticalRanges[0] = $this->default_critical_range; } } else { return null; } } if (isset($this->criticalRanges[$argumentNumber])) { return $this->criticalRanges[$argumentNumber]; } else { return null; } } public function checkAgainstWarningRange($values, $force=true, $autostatus=true, $argumentNumber=0) { $this->checkInitialized(); if (!$this->getArgumentHandler()->isArgRegistered('w')) { throw new VNagRequiredArgumentNotRegistered('-w'); } $wr = $this->getWarningRange($argumentNumber); if (isset($wr)) { if ($wr->checkAlert($values)) { if ($autostatus) $this->setStatus(VNag::STATUS_WARNING); return true; } else { if ($autostatus) $this->setStatus(VNag::STATUS_OK); return false; } } else { if ($force) { if (($argumentNumber > 0) && (count($this->warningRanges) > 0)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$too_few_warning_ranges, $argumentNumber+1)); } else { throw new VNagRequiredArgumentMissing('-w'); } } } } public function checkAgainstCriticalRange($values, $force=true, $autostatus=true, $argumentNumber=0) { $this->checkInitialized(); if (!$this->getArgumentHandler()->isArgRegistered('c')) { throw new VNagRequiredArgumentNotRegistered('-c'); } $cr = $this->getCriticalRange($argumentNumber); if (isset($cr)) { if ($cr->checkAlert($values)) { if ($autostatus) $this->setStatus(VNag::STATUS_CRITICAL); return true; } else { if ($autostatus) $this->setStatus(VNag::STATUS_OK); return false; } } else { if ($force) { if (($argumentNumber > 0) && (count($this->warningRanges) > 0)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$too_few_critical_ranges, $argumentNumber+1)); } else { throw new VNagRequiredArgumentMissing('-c'); } } } } protected static function getBaddestExitcode($code1, $code2) { return max($code1, $code2); } public static function _shutdownHandler() { if (!self::is_http_mode()) { exit((int)self::$exitcode); } } protected function _exit($code) { self::$exitcode = $this->getBaddestExitcode($code, self::$exitcode); } private $constructed = false; function __construct() { $this->createHelpObject(); $this->createArgumentHandler(); $this->addExpectedArgument($this->argUsage = new VNagArgument('?', '', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$prints_usage)); $this->constructed = true; } function __destruct() { if (Timeouter::started()) { Timeouter::end(); } } public function run() { global $inside_vnag_run; $inside_vnag_run = true; try { if (!$this->constructed) { throw new VNagNotConstructed(VNagLang::$notConstructed); } try { $this->initialized = true; $this->html_before = ''; $this->html_after = ''; $this->setStatus(null, true); $this->messages = array(); register_shutdown_function(array($this, '_shutdownHandler')); if ($this->argHandler->illegalUsage()) { $content = $this->helpObj->printUsagePage(); $this->setStatus(VNag::STATUS_UNKNOWN); if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_visual_output & VNag::OUTPUT_SPECIAL) echo $this->writeVisualHTML($content); if ($this->http_invisible_output & VNag::OUTPUT_SPECIAL) echo $this->writeInvisibleHTML($content); echo $this->html_after; return; } else { echo $content; return $this->_exit($this->status); } } if (!is_null($this->argVersion) && ($this->argVersion->available())) { $content = $this->helpObj->printVersionPage(); $this->setStatus(VNag::STATUS_UNKNOWN); if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_visual_output & VNag::OUTPUT_SPECIAL) echo $this->writeVisualHTML($content); if ($this->http_invisible_output & VNag::OUTPUT_SPECIAL) echo $this->writeInvisibleHTML($content); echo $this->html_after; return; } else { echo $content; return $this->_exit($this->status); } } if (!is_null($this->argHelp) && ($this->argHelp->available())) { $content = $this->helpObj->printHelpPage(); $this->setStatus(VNag::STATUS_UNKNOWN); if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_visual_output & VNag::OUTPUT_SPECIAL) echo $this->writeVisualHTML($content); if ($this->http_invisible_output & VNag::OUTPUT_SPECIAL) echo $this->writeInvisibleHTML($content); echo $this->html_after; return; } else { echo $content; return $this->_exit($this->status); } } $this->getWarningRange(); $this->getCriticalRange(); if (!is_null($this->argTimeout)) { $timeout = $this->argTimeout->getValue(); if (!is_null($timeout)) { Timeouter::start($timeout); } } ob_start(); $init_ob_level = ob_get_level(); try { $this->cbRun(); if (ob_get_level() < $init_ob_level) throw new VNagImplementationErrorException(VNagLang::$output_level_lowered); } finally { while (ob_get_level() > $init_ob_level) @ob_end_clean(); } if (is_null($this->status)) $this->setStatus($this->default_status,true); $outputType = VNag::OUTPUT_NORMAL; } catch (Exception $e) { $this->handleException($e); $outputType = VNag::OUTPUT_EXCEPTION; } if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_invisible_output & $outputType) { echo $this->writeInvisibleHTML(); } if ($this->http_visual_output & $outputType) { echo $this->writeVisualHTML(); } echo $this->html_after; } else { echo $this->getNagiosConsoleText(); return $this->_exit($this->status); } Timeouter::end(); } finally { $inside_vnag_run = false; } } private function getNagiosConsoleText() { $ary_perfdata = $this->getPerformanceData(); $performancedata_first = array_shift($ary_perfdata); $performancedata_rest = implode(' ', $ary_perfdata); $status_text = VNagLang::status($this->status, $this->statusmodel); if (_empty($this->getHeadline())) { $content = $status_text; } else { if ($this->show_status_in_headline) { $content = $status_text.': '.$this->getHeadline(); } else { $content = $this->getHeadline(); } } if (!_empty($performancedata_first)) $content .= '|'.trim($performancedata_first); $content .= "\n"; if (!_empty($this->verbose_info)) { $content .= trim($this->verbose_info); } if (!_empty($performancedata_rest)) $content .= '|'.trim($performancedata_rest); $content .= "\n"; return trim($content)."\n"; } abstract protected function cbRun(); public function addPerformanceData($prefDataObj, $move_to_font=false, $verbosityLevel=VNag::VERBOSITY_SUMMARY) { $this->checkInitialized(); if ((!isset($this->argVerbosity)) && ($verbosityLevel > VNag::VERBOSITY_SUMMARY)) throw new VNagRequiredArgumentNotRegistered('-v'); if (self::getVerbosityLevel() < $verbosityLevel) return false; if ($move_to_font) { array_unshift($this->performanceDataObjects, $prefDataObj); } else { $this->performanceDataObjects[] = $prefDataObj; } return true; } public function getPerformanceData() { $this->checkInitialized(); return $this->performanceDataObjects; } public function removePerformanceData($prefDataObj) { if (($key = array_search($prefDataObj, $this->performanceDataObjects, true)) !== false) { unset($this->performanceDataObjects[$key]); return true; } else { return false; } } public function clearPerformanceData() { $this->performanceDataObjects = array(); } public function getVerboseInfo() { return $this->verbose_info; } public function clearVerboseInfo() { $this->verbose_info = ''; } private function writeVisualHTML($special_content=null) { if (!_empty($special_content)) { $content = $special_content; } else { $content = strtoupper(VNagLang::$status.': '.VNagLang::status($this->status, $this->statusmodel))."\n\n"; $content .= strtoupper(VNagLang::$message).":\n"; $status_text = VNagLang::status($this->status, $this->statusmodel); if (_empty($this->getHeadline())) { $content .= $status_text; } else { if ($this->show_status_in_headline) { $content .= $status_text.': '.trim($this->getHeadline()); } else { $content .= trim($this->getHeadline()); } } $content .= "\n\n"; if (!_empty($this->verbose_info)) { $content .= strtoupper(VNagLang::$verbose_info).":\n".trim($this->verbose_info)."\n\n"; } $perfdata = $this->getPerformanceData(); if (count($perfdata) > 0) { $content .= strtoupper(VNagLang::$performance_data).":\n"; foreach ($perfdata as $pd) { $content .= trim($pd)."\n"; } $content .= "\n"; } } $colorinfo = ''; $status = $this->getStatus(); if ($status == VNag::STATUS_OK) $colorinfo = ' style="background-color:green;color:white;font-weight:bold"'; else if ($status == VNag::STATUS_WARNING) $colorinfo = ' style="background-color:yellow;color:black;font-weight:bold"'; else if ($status == VNag::STATUS_CRITICAL) $colorinfo = ' style="background-color:red;color:white;font-weight:bold"'; else if ($status == VNag::STATUS_ERROR) $colorinfo = ' style="background-color:purple;color:white;font-weight:bold"'; else $colorinfo = ' style="background-color:lightgray;color:black;font-weight:bold"'; $html_content = trim($content); $html_content = htmlentities($html_content); $html_content = str_replace(' ', '&nbsp;', $html_content); $html_content = nl2br($html_content); return '<table border="1" cellspacing="2" cellpadding="2" style="width:100%" class="vnag_table">'. '<tr'.$colorinfo.' class="vnag_title_row">'. '<td>'.VNagLang::$nagios_output.'</td>'. '</tr>'. '<tr class="vnag_message_row">'. '<td><code>'. $html_content. '</code></td>'. '</tr>'. '</table>'; } protected function readInvisibleHTML($html) { $this->checkInitialized(); $doc = new DOMDocument(); @$doc->loadHTML($html); $tags = $doc->getElementsByTagName('script'); foreach ($tags as $tag) { $type = $tag->getAttribute('type'); if ($type !== 'application/json') continue; $json = $tag->nodeValue; if (!$json) continue; $data = @json_decode($json,true); if (!is_array($data)) continue; if (!isset($data['type'])) continue; if ($data['type'] === VNAG_JSONDATA_V1) { if (!isset($data['datasets'])) throw new VNagWebInfoException(VNagLang::$dataset_missing); foreach ($data['datasets'] as $dataset) { $payload = base64_decode($dataset['payload']); if (!$payload) { throw new VNagWebInfoException(VNagLang::$payload_not_base64); } if (isset($dataset['encryption'])) { $cryptInfo = $dataset['encryption']; if (!is_array($cryptInfo)) { throw new VNagWebInfoException(VNagLang::$dataset_encryption_no_array); } $password = is_null($this->password_in) ? '' : $this->password_in; $salt = base64_decode($cryptInfo['salt']); if ($cryptInfo['hash'] != hash('sha256',$salt.$password)) { if ($password == '') { throw new VNagWebInfoException(VNagLang::$require_password); } else { throw new VNagWebInfoException(VNagLang::$wrong_password); } } if (!function_exists('openssl_decrypt')) { throw new VNagException(VNagLang::$openssl_missing); } $payload = openssl_decrypt($payload, $cryptInfo['method'], $password, 0, $cryptInfo['iv']); } if (!is_null($this->pubkey) && ($this->pubkey !== '')) { if (substr($this->pubkey,0,3) === '---') { $public_key = $this->pubkey; } else { if (!file_exists($this->pubkey)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$pubkey_file_not_found, $this->pubkey)); } $public_key = @file_get_contents($this->pubkey); if (!$public_key) { throw new VNagPublicKeyException(sprintf(VNagLang::$pubkey_file_not_readable, $this->pubkey)); } } if (!isset($dataset['signature'])) { throw new VNagSignatureException(VNagLang::$signature_missing); } $signature = base64_decode($dataset['signature']); if (!$signature) { throw new VNagSignatureException(VNagLang::$signature_not_bas64); } if (!function_exists('openssl_verify')) { throw new VNagException(VNagLang::$openssl_missing); } $sign_algo = is_null($this->sign_algo) ? OPENSSL_ALGO_SHA256 : $this->sign_algo; if (!openssl_verify($payload, $signature, $public_key, $sign_algo)) { throw new VNagSignatureException(VNagLang::$signature_invalid); } } $payload = @json_decode($payload,true); if (!$payload) { throw new VNagWebInfoException(VNagLang::$payload_not_json); } if ($payload['id'] == $this->id) { return $payload; } } } } return null; } private function getNextMonitorID($peek=false) { $result = is_null($this->id) ? self::$http_serial_number : $this->id; if (!$peek) { $this->id = null; self::$http_serial_number++; } return $result; } private function writeInvisibleHTML($special_content=null) { $payload['id'] = $this->getNextMonitorID(); $payload['status'] = $this->getStatus(); if (!_empty($special_content)) { $payload['text'] = $special_content; } else { $payload['headline'] = $this->getHeadline(); $payload['verbose_info'] = $this->verbose_info; $payload['performance_data'] = array(); foreach ($this->performanceDataObjects as $perfdata) { $payload['performance_data'][] = (string)$perfdata; } } $payload = json_encode($payload); $dataset = array(); if (!is_null($this->privkey) && ($this->privkey !== '')) { if (!function_exists('openssl_pkey_get_private') || !function_exists('openssl_sign')) { throw new VNagException(VNagLang::$openssl_missing); } if (substr($this->privkey,0,3) === '---') { $pkeyid = @openssl_pkey_get_private($this->privkey, $this->privkey_password); if (!$pkeyid) { throw new VNagPrivateKeyException(sprintf(VNagLang::$privkey_not_readable)); } } else { if (!file_exists($this->privkey)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$privkey_file_not_found, $this->privkey)); } $pkeyid = @openssl_pkey_get_private('file://'.$this->privkey, $this->privkey_password); if (!$pkeyid) { throw new VNagPrivateKeyException(sprintf(VNagLang::$privkey_file_not_readable, $this->privkey)); } } $signature = ''; $sign_algo = is_null($this->sign_algo) ? OPENSSL_ALGO_SHA256 : $this->sign_algo; if (@openssl_sign($payload, $signature, $pkeyid, $sign_algo)) { if (version_compare(PHP_VERSION, '8.0.0') < 0) { openssl_free_key($pkeyid); } $dataset['signature'] = base64_encode($signature); } else { throw new VNagPrivateKeyException(sprintf(VNagLang::$signature_failed)); } } if (!is_null($this->password_out) && ($this->password_out !== '')) { if (!function_exists('openssl_encrypt')) { throw new VNagException(VNagLang::$openssl_missing); } $password = $this->password_out; $method = 'aes-256-ofb'; $iv = substr(hash('sha256', openssl_random_pseudo_bytes(32)), 0, 16); $salt = openssl_random_pseudo_bytes(32); $cryptInfo = array(); $cryptInfo['method'] = $method; $cryptInfo['iv'] = $iv; $cryptInfo['salt'] = base64_encode($salt); $cryptInfo['hash'] = hash('sha256', $salt.$password); $payload = openssl_encrypt($payload, $method, $password, 0, $iv); $dataset['encryption'] = $cryptInfo; } $dataset['payload'] = base64_encode($payload); $json = array(); $json['type'] = VNAG_JSONDATA_V1; $json['datasets'] = array($dataset); return '<script type="application/json">'. json_encode($json). '</script>'; } protected function appendHeadline($msg) { $this->checkInitialized(); if (_empty($msg)) return false; $this->messages[] = $msg; return true; } protected function changeHeadline($msg) { $this->checkInitialized(); if (_empty($msg)) { $this->messages = array(); } else { $this->messages = array($msg); } return true; } public function setHeadline($msg, $append=false, $verbosityLevel=VNag::VERBOSITY_SUMMARY) { $this->checkInitialized(); if ((!isset($this->argVerbosity)) && ($verbosityLevel > VNag::VERBOSITY_SUMMARY)) throw new VNagRequiredArgumentNotRegistered('-v'); if (self::getVerbosityLevel() < $verbosityLevel) $msg = ''; if ($append) { return $this->appendHeadline($msg); } else { return $this->changeHeadline($msg); } } public function getHeadline() { $this->checkInitialized(); return implode(', ', $this->messages); } public function addVerboseMessage($msg, $verbosityLevel=VNag::VERBOSITY_SUMMARY) { $this->checkInitialized(); if (self::getVerbosityLevel() >= $verbosityLevel) { $this->verbose_info .= $msg."\n"; } } public function setStatus($status, $force=false) { $this->checkInitialized(); if (($force) || is_null($this->status) || ($status > $this->status)) { $this->status = $status; } } public function getStatus() { $this->checkInitialized(); return $this->status; } protected static function exceptionText($exception) { $class = get_class($exception); $msg = $exception->getMessage(); if (!_empty($msg)) { return sprintf(VNagLang::$exception_x, $msg, $class); } else { return sprintf(VNagLang::$unhandled_exception_without_msg, $class); } } protected function handleException($exception) { $this->checkInitialized(); if (!VNag::is_http_mode()) { while (ob_get_level() > 0) @ob_end_clean(); } $this->clearVerboseInfo(); $this->clearPerformanceData(); if ($exception instanceof VNagException) { $this->setStatus($exception->getStatus()); } else { $this->setStatus(self::STATUS_ERROR); } $this->setHeadline($this->exceptionText($exception), false); if ($exception instanceof VNagImplementationErrorException) { $this->addVerboseMessage($exception->getTraceAsString(), VNag::VERBOSITY_SUMMARY); } else { if (isset($this->argVerbosity)) { $this->addVerboseMessage($exception->getTraceAsString(), VNag::VERBOSITY_ADDITIONAL_INFORMATION); } else { } } } protected function get_cache_dir() { $homedir = @getenv('HOME'); if ($homedir && is_dir($homedir)) { $try = "$homedir/.vnag/cache"; if (is_dir($try)) return $try; if (@mkdir($try,0777,true)) return $try; } $user = posix_getpwuid(posix_geteuid()); if (isset($user['dir']) && is_dir($user['dir'])) { $homedir = $user['dir']; $try = "$homedir/.vnag/cache"; if (is_dir($try)) return $try; if (@mkdir($try,0777,true)) return $try; } if (isset($user['name']) && is_dir($user['name'])) { $username = $user['name']; $try = "/tmp/vnag/cache"; if (is_dir($try)) return $try; if (@mkdir($try,0777,true)) return $try; } throw new VNagException("Cannot get cache dir"); } protected function url_get_contents($url, $max_cache_time=1*60*60, $context=null) { $cache_file = $this->get_cache_dir().'/'.hash('sha256',$url); if (file_exists($cache_file) && (time()-filemtime($cache_file) < $max_cache_time)) { $cont = @file_get_contents($cache_file); if ($cont === false) throw new Exception("Failed to get contents from $cache_file"); } else { $options = array( 'http'=>array( 'method'=>"GET", 'header'=>"Accept-language: en\r\n" . "User-Agent: Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B334b Safari/531.21.102011-10-16 20:23:10\r\n" ) ); if (is_null($context)) $context = stream_context_create($options); $cont = @file_get_contents($url, false, $context); if ($cont === false) throw new Exception("Failed to get contents from $url"); file_put_contents($cache_file, $cont); } return $cont; } } class VNagException extends Exception { public function getStatus() { return VNag::STATUS_ERROR; } } class VNagTimeoutException extends VNagException {} class VNagWebInfoException extends VNagException {} class VNagSignatureException extends VNagException {} class VNagPublicKeyException extends VNagException {} class VNagPrivateKeyException extends VNagException {} class VNagInvalidArgumentException extends VNagException { public function getStatus() { return VNag::STATUS_UNKNOWN; } } class VNagValueUomPairSyntaxException extends VNagInvalidArgumentException { public function __construct($str) { $e_msg = sprintf(VNagLang::$valueUomPairSyntaxError, $str); parent::__construct($e_msg); } } class VNagInvalidTimeoutException extends VNagInvalidArgumentException {} class VNagInvalidRangeException extends VNagInvalidArgumentException { public function __construct($msg) { $e_msg = VNagLang::$range_is_invalid; if (!_empty($msg)) $e_msg .= ': '.trim($msg); parent::__construct($e_msg); } } class VNagInvalidShortOpt extends VNagImplementationErrorException {} class VNagInvalidLongOpt extends VNagImplementationErrorException {} class VNagInvalidValuePolicy extends VNagImplementationErrorException {} class VNagIllegalStatusModel extends VNagImplementationErrorException {} class VNagNotConstructed extends VNagImplementationErrorException {} class VNagImplementationErrorException extends VNagException {} class VNagInvalidStandardArgument extends VNagImplementationErrorException {} class VNagFunctionCallOutsideSession extends VNagImplementationErrorException {} class VNagIllegalArgumentValuesException extends VNagImplementationErrorException {} class VNagRequiredArgumentNotRegistered extends VNagImplementationErrorException { public function __construct($required_argument) { $e_msg = sprintf(VNagLang::$query_without_expected_argument, $required_argument); parent::__construct($e_msg); } } class VNagRequiredArgumentMissing extends VNagInvalidArgumentException { public function __construct($required_argument) { $e_msg = sprintf(VNagLang::$required_argument_missing, $required_argument); parent::__construct($e_msg); } } class VNagUnknownUomException extends VNagInvalidArgumentException { public function __construct($uom) { $e_msg = sprintf(VNagLang::$perfdata_uom_not_recognized, $uom); parent::__construct($e_msg); } } class VNagNoCompatibleRangeUomFoundException extends VNagException {} class VNagMixedUomsNotImplemented extends VNagInvalidArgumentException { public function __construct($uom1, $uom2) { if (_empty($uom1)) $uom1 = VNagLang::$none; if (_empty($uom2)) $uom2 = VNagLang::$none; $e_msg = sprintf(VNagLang::$perfdata_mixed_uom_not_implemented, $uom1, $uom2); parent::__construct($e_msg); } } class VNagUomConvertException extends VNagInvalidArgumentException { public function __construct($uom1, $uom2) { if (_empty($uom1)) $uom1 = VNagLang::$none; if (_empty($uom2)) $uom2 = VNagLang::$none; $e_msg = sprintf(VNagLang::$convert_x_y_error, $uom1, $uom2); parent::__construct($e_msg); } } class VNagInvalidPerformanceDataException extends VNagInvalidArgumentException { public function __construct($msg) { $e_msg = VNagLang::$performance_data_invalid; if (!_empty($msg)) $e_msg .= ': '.trim($msg); parent::__construct($e_msg); } } class Timeouter { private static $start_time = false; private static $timeout; private static $fired = false; private static $registered = false; private function __construct() { } public static function start($timeout) { if (!is_numeric($timeout) || ($timeout <= 0)) { throw new VNagInvalidTimeoutException(sprintf(VNagLang::$timeout_value_invalid, $timeout)); } self::$start_time = microtime(true); self::$timeout = (float) $timeout; self::$fired = false; if (!self::$registered) { self::$registered = true; register_tick_function(array('Timeouter', 'tick')); } } public static function started() { return self::$registered; } public static function end() { if (self::$registered) { unregister_tick_function(array('Timeouter', 'tick')); self::$registered = false; } } public static function tick() { if ((!self::$fired) && ((microtime(true) - self::$start_time) > self::$timeout)) { self::$fired = true; throw new VNagTimeoutException(VNagLang::$timeout_exception); } } } class VNagArgument { const VALUE_FORBIDDEN = 0; const VALUE_REQUIRED = 1; const VALUE_OPTIONAL = 2; protected $shortopt; protected $longopts; protected $valuePolicy; protected $valueName; protected $helpText; protected $defaultValue = null; protected static $all_short = ''; protected static $all_long = array(); public function getShortOpt() { return $this->shortopt; } public function getLongOpts() { return $this->longopts; } public function getValuePolicy() { return $this->valuePolicy; } public function getValueName() { return $this->valueName; } public function getHelpText() { return $this->helpText; } static private function validateShortOpt($shortopt) { $m = array(); return preg_match('@^[a-zA-Z0-9\\+\\-\\?]$@', $shortopt, $m); } static private function validateLongOpt($longopt) { $m = array(); return preg_match('@^[a-zA-Z0-9\\+\\-\\?]+$@', $longopt, $m); } public function __construct($shortopt, $longopts, $valuePolicy, $valueName, $helpText, $defaultValue=null) { switch ($valuePolicy) { case VNagArgument::VALUE_FORBIDDEN: if (!_empty($valueName)) { throw new VNagImplementationErrorException(sprintf(VNagLang::$value_name_forbidden)); } break; case VNagArgument::VALUE_REQUIRED: if (_empty($valueName)) { throw new VNagImplementationErrorException(sprintf(VNagLang::$value_name_required)); } break; case VNagArgument::VALUE_OPTIONAL: if (_empty($valueName)) { throw new VNagImplementationErrorException(sprintf(VNagLang::$value_name_required)); } break; default: throw new VNagInvalidValuePolicy(sprintf(VNagLang::$illegal_valuepolicy, $valuePolicy)); } if (!_empty($shortopt)) { if (!self::validateShortOpt($shortopt)) { throw new VNagInvalidShortOpt(sprintf(VNagLang::$illegal_shortopt, $shortopt)); } } if (is_array($longopts)) { foreach ($longopts as $longopt) { if (!self::validateLongOpt($longopt)) { throw new VNagInvalidLongOpt(sprintf(VNagLang::$illegal_longopt, $longopt)); } } } else if (!_empty($longopts)) { if (!self::validateLongOpt($longopts)) { throw new VNagInvalidLongOpt(sprintf(VNagLang::$illegal_longopt, $longopts)); } $longopts = array($longopts); } else { $longopts = array(); } switch ($valuePolicy) { case VNagArgument::VALUE_FORBIDDEN: $policyApdx = ''; break; case VNagArgument::VALUE_REQUIRED: $policyApdx = ':'; break; case VNagArgument::VALUE_OPTIONAL: $policyApdx = '::'; break; default: throw new VNagInvalidValuePolicy(sprintf(VNagLang::$illegal_valuepolicy, $valuePolicy)); } if ((!is_null($shortopt)) && ($shortopt != '?')) self::$all_short .= $shortopt.$policyApdx; if (is_array($longopts)) { foreach ($longopts as $longopt) { self::$all_long[] = $longopt.$policyApdx; } } $this->shortopt = $shortopt; $this->longopts = $longopts; $this->valuePolicy = $valuePolicy; $this->valueName = $valueName; $this->helpText = $helpText; $this->defaultValue = $defaultValue; } protected static function getOptions() { global $OVERWRITE_ARGUMENTS; if (!is_null($OVERWRITE_ARGUMENTS)) { return $OVERWRITE_ARGUMENTS; } else if (VNag::is_http_mode()) { return $_REQUEST; } else { return getopt(self::$all_short, self::$all_long); } } public function count() { $options = self::getOptions(); $count = 0; if (isset($options[$this->shortopt])) { if (is_array($options[$this->shortopt])) { $count += count($options[$this->shortopt]); } else { $count += 1; } } if (!is_null($this->longopts)) { foreach ($this->longopts as $longopt) { if (isset($options[$longopt])) { if (is_array($options[$longopt])) { $count += count($options[$longopt]); } else { $count += 1; } } } } return $count; } public function available() { $options = self::getOptions(); if (isset($options[$this->shortopt])) return true; if (!is_null($this->longopts)) { foreach ($this->longopts as $longopt) { if (isset($options[$longopt])) return true; } } return false; } public function require() { if (!$this->available() && is_null($this->defaultValue)) { $opt = $this->shortopt; $opt = !_empty($opt) ? '-'.$opt : (isset($this->longopts[0]) ? '--'.$this->longopts[0] : '?'); throw new VNagRequiredArgumentMissing($opt); } } public function getValue() { $options = self::getOptions(); if (isset($options[$this->shortopt])) { $x = $options[$this->shortopt]; if (is_array($x) && (count($x) <= 1)) $options[$this->shortopt] = $options[$this->shortopt][0]; return $options[$this->shortopt]; } if (!is_null($this->longopts)) { foreach ($this->longopts as $longopt) { if (isset($options[$longopt])) { $x = $options[$longopt]; if (is_array($x) && (count($x) <= 1)) $options[$longopt] = $options[$longopt][0]; return $options[$longopt]; } } } return $this->defaultValue; } } class VNagArgumentHandler { protected $expectedArgs = array(); protected function _addExpectedArgument($argObj) { if ($argObj->getShortOpt() == '?') return false; if ($argObj->getShortOpt() == '-') return false; if ($argObj->getShortOpt() == '+') return false; $this->expectedArgs[] = $argObj; return true; } public function getArgumentObj($shortopt) { foreach ($this->expectedArgs as $argObj) { if ($argObj->getShortOpt() == $shortopt) return $argObj; } return null; } public function isArgRegistered($shortopt) { return !is_null($this->getArgumentObj($shortopt)); } public function illegalUsage() { global $argv; return (isset($argv[1])) && (($argv[1] == '-?') || ($argv[1] == '/?')); } } class VNagRange { public $start; public $end; public $warnInsideRange; public function __construct($rangeDef, $singleValueBehavior=VNag::SINGLEVALUE_RANGE_DEFAULT) { $m = array(); if (!preg_match('|^(@){0,1}([^:]+)(:){0,1}(.*)$|', $rangeDef, $m)) { throw new VNagInvalidRangeException(sprintf(VNagLang::$range_invalid_syntax, $rangeDef)); } $this->warnInsideRange = $m[1] === '@'; $this->start = null; $this->end = null; if ($m[3] === ':') { if ($m[2] === '~') { $this->start = '-inf'; } else { $this->start = new VNagValueUomPair($m[2]); } if (_empty($m[4])) { $this->end = 'inf'; } else { $this->end = new VNagValueUomPair($m[4]); } } else { assert(_empty($m[4])); assert(!_empty($m[2])); $x = $m[2]; if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_DEFAULT) { $this->start = new VNagValueUomPair('0'.((new VNagValueUomPair($x))->getUom())); $this->end = new VNagValueUomPair($x); } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_GT_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 0; $this->start = '-inf'; $this->end = new VNagValueUomPair($x); } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_GE_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 1; $this->start = new VNagValueUomPair($x); $this->end = 'inf'; } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_LT_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 0; $this->start = new VNagValueUomPair($x); $this->end = 'inf'; } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_LE_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 1; $this->start = '-inf'; $this->end = new VNagValueUomPair($x); } else { throw new VNagException(VNagLang::$illegalSingleValueBehavior); } } if (is_null($this->start)) { throw new VNagInvalidRangeException(VNagLang::$invalid_start_value); } if (is_null($this->end)) { throw new VNagInvalidRangeException(VNagLang::$invalid_end_value); } if (($this->start instanceof VNagValueUomPair) && ($this->end instanceof VNagValueUomPair) && (VNagValueUomPair::compare($this->start,$this->end) > 0)) { throw new VNagInvalidRangeException(VNagLang::$start_is_greater_than_end); } } public function __toString() { $ret = ''; if ($this->warnInsideRange) { $ret = '@'; } if ($this->start === '-inf') { $ret .= '~'; } else { $ret .= $this->start; } $ret .= ':'; if ($this->end !== 'inf') { $ret .= $this->end; } return $ret; } public function checkAlert($values) { $compatibleCount = 0; if (!is_array($values)) $values = array($values); foreach ($values as $value) { if (!($value instanceof VNagValueUomPair)) $value = new VNagValueUomPair($value); assert(($this->start === '-inf') || ($this->start instanceof VNagValueUomPair)); assert(($this->end === 'inf' ) || ($this->end instanceof VNagValueUomPair)); if (($this->start !== '-inf') && (!$this->start->compatibleWith($value))) continue; if (($this->end !== 'inf') && (!$this->end->compatibleWith($value))) continue; $compatibleCount++; if ($this->warnInsideRange) { return (($this->start === '-inf') || (VNagValueUomPair::compare($value,$this->start) >= 0)) && (($this->end === 'inf') || (VNagValueUomPair::compare($value,$this->end) <= 0)); } else { return (($this->start !== '-inf') && (VNagValueUomPair::compare($value,$this->start) < 0)) || (($this->end !== 'inf') && (VNagValueUomPair::compare($value,$this->end) > 0)); } } if ((count($values) > 0) and ($compatibleCount == 0)) { throw new VNagNoCompatibleRangeUomFoundException(VNagLang::$no_compatible_range_uom_found); } return false; } } class VNagValueUomPair { protected $value; protected $uom; public $roundTo = -1; public function isRelative() { return $this->uom === '%'; } public function getValue() { return $this->value; } public function getUom() { return $this->uom; } public function __toString() { if ($this->roundTo == -1) { return $this->value.$this->uom; } else { return round($this->value,$this->roundTo).$this->uom; } } public function __construct($str) { $m = array(); if (!preg_match('/^([\d\.]+)(.*)$/ism', $str, $m)) { throw new VNagValueUomPairSyntaxException($str); } $this->value = $m[1]; $this->uom = isset($m[2]) ? $m[2] : ''; if (!self::isKnownUOM($this->uom)) { throw new VNagUnknownUomException($this->uom); } } public static function isKnownUOM(string $uom) { $no_unit = ($uom === ''); $seconds = ($uom === 's') || ($uom === 'ms') || ($uom === 'us'); $percentage = ($uom === '%'); $bytes = ($uom === 'B') || ($uom === 'KB') || ($uom === 'MB') || ($uom === 'GB') || ($uom === 'TB'); $counter = ($uom === 'c'); return ($no_unit || $seconds || $percentage || $bytes || $counter); } public function normalize($target=null) { $res = clone $this; if ($res->uom === 'ms') { $res->uom = 's'; $res->value /= 1000; } if ($res->uom === 'us') { $res->uom = 's'; $res->value /= 1000 * 1000; } if ($res->uom === 'B') { $res->uom = 'MB'; $res->value /= 1024 * 1024; } if ($res->uom === 'KB') { $res->uom = 'MB'; $res->value /= 1024; } if ($res->uom === 'GB') { $res->uom = 'MB'; $res->value *= 1024; } if ($res->uom === 'TB') { $res->uom = 'MB'; $res->value *= 1024 * 1024; } if ($res->uom === 'c') { $res->uom = ''; } if (!is_null($target)) { if ($res->uom == 'MB') { if ($target == 'B') { $res->uom = 'B'; $res->value *= 1024 * 1024; } else if ($target == 'KB') { $res->uom = 'KB'; $res->value *= 1024; } else if ($target == 'MB') { $res->uom = 'MB'; $res->value *= 1; } else if ($target == 'GB') { $res->uom = 'GB'; $res->value /= 1024; } else if ($target == 'TB') { $res->uom = 'TB'; $res->value /= 1024 * 1024; } else { throw new VNagUomConvertException($res->uom, $target); } } else if ($res->uom == 's') { if ($target == 's') { $res->uom = 's'; $res->value /= 1; } else if ($target == 'ms') { $res->uom = 'ms'; $res->value /= 1000; } else if ($target == 'us') { $res->uom = 'us'; $res->value /= 1000 * 1000; } else { throw new VNagUomConvertException($res->uom, $target); } } else { throw new VNagUomConvertException($res->uom, $target); } } return $res; } public function compatibleWith(VNagValueUomPair $other) { $a = $this->normalize(); $b = $other->normalize(); return ($a->uom == $b->uom); } public static function compare(VNagValueUomPair $left, VNagValueUomPair $right) { $a = $left->normalize(); $b = $right->normalize(); if ($a->uom != $b->uom) throw new VNagMixedUomsNotImplemented($a->uom, $b->uom); if ($a->value > $b->value) return 1; if ($a->value == $b->value) return 0; if ($a->value < $b->value) return -1; } } class VNagPerformanceData { protected $label; protected $value; protected $warn = null; protected $crit = null; protected $min = null; protected $max = null; public static function createByString($perfdata) { $perfdata = trim($perfdata); $ary = explode('=',$perfdata); if (count($ary) != 2) { throw new VNagInvalidPerformanceDataException(sprintf(VNagLang::$perfdata_line_invalid, $perfdata)); } $label = $ary[0]; $bry = explode(';',$ary[1]); if (substr($label,0,1) === "'") $label = substr($label, 1, strlen($label)-2); $value = $bry[0]; $warn = isset($bry[1]) ? $bry[1] : null; $crit = isset($bry[2]) ? $bry[2] : null; $min = isset($bry[3]) ? $bry[3] : null; $max = isset($bry[4]) ? $bry[4] : null; return new self($label, $value, $warn, $crit, $min, $max); } public function __construct($label, $value, $warn=null, $crit=null, $min=null, $max=null) { if (strpos($label, '=') !== false) throw new VNagInvalidPerformanceDataException(VNagLang::$perfdata_label_equal_sign_forbidden); $label = str_replace("'", "''", $label); $m = array(); if ((!_empty($min)) && (!preg_match('|^[-0-9\\.]+$|', $min, $m))) { throw new VNagInvalidPerformanceDataException(VNagLang::$perfdata_min_must_be_in_class); } if ((!_empty($max)) && (!preg_match('|^[-0-9\\.]+$|', $max, $m))) { throw new VNagInvalidPerformanceDataException(VNagLang::$perfdata_max_must_be_in_class); } $this->label = $label; $this->value = ($value == 'U') ? 'U' : new VNagValueUomPair($value); $this->warn = $warn; $this->crit = $crit; $this->min = $min; $this->max = $max; } public function __toString() { $label = $this->label; $value = $this->value; $warn = $this->warn; $crit = $this->crit; $min = $this->min; $max = $this->max; $label = str_replace("''", "'", $label); return "'$label'=$value". ';'.(is_null($warn) ? '' : $warn). ';'.(is_null($crit) ? '' : $crit). ';'.(is_null($min) ? '' : $min). ';'.(is_null($max) ? '' : $max); } } class VNagHelp { public $word_wrap_width = 80; public $argument_indent = 7; public function printUsagePage() { $usage = $this->getUsage(); if (_empty($usage)) { $usage = VNagLang::$no_syntax_defined; } return trim($usage)."\n"; } public function printVersionPage() { $out = trim($this->getNameAndVersion())."\n"; if ($this->word_wrap_width > 0) $out = wordwrap($out, $this->word_wrap_width, "\n", false); return $out; } static private function _conditionalLine($line, $terminator='', $prefix='') { if (!_empty($line)) { return trim($line).$terminator; } return ''; } public function printHelpPage() { $out = ''; $out .= self::_conditionalLine($this->getNameAndVersion(), "\n"); $out .= self::_conditionalLine($this->getCopyright(), "\n"); $out .= ($out != '') ? "\n" : ''; $out .= self::_conditionalLine($this->getShortDescription(), "\n\n\n"); $out .= self::_conditionalLine($this->getUsage(), "\n\n"); $out .= VNagLang::$options."\n"; foreach ($this->options as $argObj) { $out .= $this->printArgumentHelp($argObj); } $out .= self::_conditionalLine($this->getFootNotes(), "\n\n", "\n"); if ($this->word_wrap_width > 0) $out = wordwrap($out, $this->word_wrap_width, "\n", false); return $out; } protected $options = array(); protected function _addOption($argObj) { $this->options[] = $argObj; } protected function printArgumentHelp($argObj) { $identifiers = array(); $shortopt = $argObj->getShortopt(); if (!_empty($shortopt)) $identifiers[] = '-'.$shortopt; $longopts = $argObj->getLongopts(); if (!is_null($longopts)) { foreach ($longopts as $longopt) { if (!_empty($longopt)) $identifiers[] = '--'.$longopt; } } if (count($identifiers) == 0) return; $valueName = $argObj->getValueName(); $arginfo = ''; switch ($argObj->getValuePolicy()) { case VNagArgument::VALUE_FORBIDDEN: $arginfo = ''; break; case VNagArgument::VALUE_REQUIRED: $arginfo = '='.$valueName; break; case VNagArgument::VALUE_OPTIONAL: $arginfo = '[='.$valueName.']'; break; } $out = ''; $out .= implode(', ', $identifiers).$arginfo."\n"; $content = trim($argObj->getHelpText()); if ($this->word_wrap_width > 0) $content = wordwrap($content, $this->word_wrap_width-$this->argument_indent, "\n", false); $lines = explode("\n", $content); foreach ($lines as $line) { $out .= str_repeat(' ', $this->argument_indent).$line."\n"; } $out .= "\n"; return $out; } protected $pluginName; public function setPluginName($pluginName) { $this->pluginName = $this->replaceStuff($pluginName); } public function getPluginName() { if (_empty($this->pluginName)) { global $argv; return basename($argv[0]); } else { return $this->pluginName; } } protected $version; public function setVersion($version) { $this->version = $this->replaceStuff($version); } public function getVersion() { return $this->version; } public function getNameAndVersion() { $ret = $this->getPluginName(); if (_empty($ret)) return null; $ver = $this->getVersion(); if (!_empty($ver)) { $ret = sprintf(VNagLang::$x_version_x, $ret, $ver); } $ret = trim($ret); return $ret; } protected $copyright; public function setCopyright($copyright) { $this->copyright = $this->replaceStuff($copyright); } private function getVNagCopyright() { if (VNag::is_http_mode()) { $vts_email = 'www.viathinksoft.com'; } else { $vts_email = base64_decode('aW5mb0B2aWF0aGlua3NvZnQuZGU='); } return "VNag Framework ".VNag::VNAG_VERSION." (C) 2014-".date('Y')." ViaThinkSoft <$vts_email>"; } public function getCopyright() { if (_empty($this->copyright)) { return sprintf(VNagLang::$plugin_uses, $this->getVNagCopyright()); } else { return trim($this->copyright)."\n".sprintf(VNagLang::$uses, $this->getVNagCopyright()); } } protected $shortDescription; public function setShortDescription($shortDescription) { $this->shortDescription = $this->replaceStuff($shortDescription); } public function getShortDescription() { if (_empty($this->shortDescription)) { return null; } else { $content = $this->shortDescription; if ($this->word_wrap_width > 0) $content = wordwrap($content, $this->word_wrap_width, "\n", false); return $content; } } protected function replaceStuff($text) { global $argv; if (php_sapi_name() == 'cli') { $text = str_replace('$SCRIPTNAME$', $argv[0], $text); } else { $text = str_replace('$SCRIPTNAME$', basename($_SERVER['SCRIPT_NAME']), $text); } $text = str_replace('$CURYEAR$', date('Y'), $text); return $text; } protected $syntax; public function setSyntax($syntax) { $syntax = $this->replaceStuff($syntax); $this->syntax = $syntax; } public function getUsage() { if (_empty($this->syntax)) { return null; } else { return sprintf(VNagLang::$usage_x, $this->syntax); } } protected $footNotes; public function setFootNotes($footNotes) { $this->footNotes = $this->replaceStuff($footNotes); } public function getFootNotes() { return $this->footNotes; } } class VNagLang { public static function status($code, $statusmodel) { switch ($statusmodel) { case VNag::STATUSMODEL_SERVICE: switch ($code) { case VNag::STATUS_OK: return 'OK'; case VNag::STATUS_WARNING: return 'Warning'; case VNag::STATUS_CRITICAL: return 'Critical'; case VNag::STATUS_UNKNOWN: return 'Unknown'; default: return sprintf('Error (%d)', $code); } case VNag::STATUSMODEL_HOST: switch ($code) { case VNag::STATUS_UP: return 'Up'; case VNag::STATUS_DOWN: return 'Down'; default: return sprintf('Maintain last state (%d)', $code); } default: throw new VNagIllegalStatusModel(sprintf(self::$illegal_statusmodel, $statusmodel)); } } static $nagios_output = 'VNag-Output'; static $verbose_info = 'Verbose information'; static $status = 'Status'; static $message = 'Message'; static $performance_data = 'Performance data'; static $status_ok = 'OK'; static $status_warn = 'Warning'; static $status_critical = 'Critical'; static $status_unknown = 'Unknown'; static $status_error = 'Error'; static $unhandled_exception_without_msg = "Unhandled exception of type %s"; static $plugin_uses = 'This plugin uses %s'; static $uses = 'uses %s'; static $x_version_x = '%s, version %s'; static $argname_value = 'value'; static $argname_seconds = 'seconds'; static $query_without_expected_argument = "The argument '%s' is queried, but was not added to the list of expected arguments. Please contact the plugin author."; static $required_argument_missing = "The argument '%s' is required."; static $performance_data_invalid = 'Performance data invalid.'; static $no_standard_arguments_with_letter = "No standard argument with letter '%s' exists."; static $invalid_start_value = 'Invalid start value.'; static $invalid_end_value = 'Invalid end value.'; static $start_is_greater_than_end = 'Start is greater than end value.'; static $value_name_forbidden = "Implementation error: You may not define a value name for the argument, because the value policy is VALUE_FORBIDDEN."; static $value_name_required = "Implementation error: Please define a name for the argument (so it can be shown in the help page)."; static $illegal_shortopt = "Illegal shortopt '-%s'."; static $illegal_longopt = "Illegal longopt '--%s'."; static $illegal_valuepolicy = "valuePolicy has illegal value '%s'."; static $range_invalid_syntax = "Syntax error in range '%s'."; static $timeout_value_invalid = "Timeout value '%s' is invalid."; static $range_is_invalid = 'Range is invalid.'; static $timeout_exception = 'Timeout!'; static $perfdata_label_equal_sign_forbidden = 'Label may not contain an equal sign.'; static $perfdata_value_must_be_in_class = 'Value must be in class [-0-9.] or be \'U\' if the actual value can\'t be determined.'; static $perfdata_min_must_be_in_class = 'Min must be in class [-0-9.] or empty.'; static $perfdata_max_must_be_in_class = 'Max must be in class [-0-9.] or empty.'; static $perfdata_uom_not_recognized = 'UOM (unit of measurement) "%s" is not recognized.'; static $perfdata_mixed_uom_not_implemented = 'Mixed UOMs (%s and %s) are currently not supported.'; static $no_compatible_range_uom_found = 'Measured values are not compatible with the provided warning/critical parameter. Most likely, the UOM is incompatible.'; static $exception_x = '%s (%s)'; static $no_syntax_defined = 'The author of this plugin has not defined a syntax for this plugin.'; static $usage_x = "Usage:\n%s"; static $options = "Options:"; static $illegal_statusmodel = "Invalid statusmodel %d."; static $none = '[none]'; static $valueUomPairSyntaxError = 'Syntax error at "%s". Syntax must be Value[UOM].'; static $too_few_warning_ranges = "You have too few warning ranges (currently trying to get element %d)."; static $too_few_critical_ranges = "You have too few critical ranges (currently trying to get element %d)."; static $dataset_missing = 'Dataset missing.'; static $payload_not_base64 = 'The payload is not valid Base64.'; static $payload_not_json = 'The payload is not valid JSON.'; static $signature_missing = 'The signature is missing.'; static $signature_not_bas64 = 'The signature is not valid Base64.'; static $signature_invalid = 'The signature is invalid. The connection might have been tampered, or a different key is used.'; static $pubkey_file_not_found = "Public key file %s was not found."; static $pubkey_file_not_readable = "Public key file %s is not readable."; static $privkey_file_not_found = "Private key file %s was not found."; static $privkey_not_readable = "Private key is not readable."; static $privkey_file_not_readable = "Private key file %s is not readable."; static $signature_failed = "Signature failed."; static $perfdata_line_invalid = "Performance data line %s is invalid."; static $singlevalue_unexpected_at_symbol = 'This plugin does not allow the @-symbol at ranges for single values.'; static $illegalSingleValueBehavior = "Illegal value for 'singleValueBehavior'. Please contact the creator of the plugin."; static $dataset_encryption_no_array = 'Dataset encryption information invalid.'; static $require_password = 'This resource is protected with a password. Please provide a password.'; static $wrong_password = 'This resource is protected with a password. You have provided the wrong password, or it was changed.'; static $convert_x_y_error = 'Cannot convert from UOM %s to UOM %s.'; static $php_error = 'PHP has detected an error in the plugin. Please contact the plugin author.'; static $output_level_lowered = "Output Buffer level lowered during cbRun(). Please contact the plugin author."; static $openssl_missing = "OpenSSL is missing. Therefore, encryption and signatures are not available."; static $warning_range = 'Warning range'; static $critical_range = 'Critical range'; static $prints_version = 'Prints version'; static $verbosity_helptext = 'Verbosity -v, -vv or -vvv'; static $timeout_helptext = 'Sets timeout in seconds'; static $help_helptext = 'Prints help page'; static $prints_usage = 'Prints usage'; static $notConstructed = 'Parent constructor not called with parent::__construct().'; } function vnagErrorHandler($errorkind, $errortext, $file, $line) { global $inside_vnag_run; if (!$inside_vnag_run && VNag::is_http_mode()) { return false; } if (!(error_reporting() & $errorkind)) { return true; } if (defined('E_ERROR') && ($errorkind == E_ERROR)) $errorkind = 'Error'; if (defined('E_WARNING') && ($errorkind == E_WARNING)) $errorkind = 'Warning'; if (defined('E_PARSE') && ($errorkind == E_PARSE)) $errorkind = 'Parse'; if (defined('E_NOTICE') && ($errorkind == E_NOTICE)) $errorkind = 'Notice'; if (defined('E_CORE_ERROR') && ($errorkind == E_CORE_ERROR)) $errorkind = 'Core Error'; if (defined('E_CORE_WARNING') && ($errorkind == E_CORE_WARNING)) $errorkind = 'Core Warning'; if (defined('E_COMPILE_ERROR') && ($errorkind == E_COMPILE_ERROR)) $errorkind = 'Compile Error'; if (defined('E_COMPILE_WARNING') && ($errorkind == E_COMPILE_WARNING)) $errorkind = 'Compile Warning'; if (defined('E_USER_ERROR') && ($errorkind == E_USER_ERROR)) $errorkind = 'User Error'; if (defined('E_USER_WARNING') && ($errorkind == E_USER_WARNING)) $errorkind = 'User Warning'; if (defined('E_USER_NOTICE') && ($errorkind == E_USER_NOTICE)) $errorkind = 'User Notice'; if (defined('E_STRICT') && ($errorkind == E_STRICT)) $errorkind = 'Strict'; if (defined('E_RECOVERABLE_ERROR') && ($errorkind == E_RECOVERABLE_ERROR)) $errorkind = 'Recoverable Error'; if (defined('E_DEPRECATED') && ($errorkind == E_DEPRECATED)) $errorkind = 'Deprecated'; if (defined('E_USER_DEPRECATED') && ($errorkind == E_USER_DEPRECATED)) $errorkind = 'User Deprecated'; throw new VNagException(VNagLang::$php_error . " $errortext at $file:$line (kind $errorkind)"); } $inside_vnag_run = false; $old_error_handler = set_error_handler("vnagErrorHandler"); <?php
declare(ticks=1); class PmWikiVersionCheck extends VNag { protected $argSystemDir = null; public function __construct() { parent::__construct(); $this->registerExpectedStandardArguments('Vht'); $this->getHelpManager()->setPluginName('check_pmwiki_version'); $this->getHelpManager()->setVersion('2023-10-13'); $this->getHelpManager()->setShortDescription('This plugin checks if a local PmWiki system has the latest version installed.'); $this->getHelpManager()->setCopyright('Copyright (C) 2011-$CURYEAR$ Daniel Marschall, ViaThinkSoft.'); $this->getHelpManager()->setSyntax('$SCRIPTNAME$ [-d <directory>]'); $this->getHelpManager()->setFootNotes('If you encounter bugs, please contact ViaThinkSoft at www.viathinksoft.com'); $this->addExpectedArgument($this->argSystemDir = new VNagArgument('d', 'directory', VNagArgument::VALUE_REQUIRED, 'pmWikiPath', 'The local directory where PmWiki installation is located.')); } protected function get_local_version($path) { $path = realpath($path) === false ? $path : realpath($path); $cont = @file_get_contents("$path/scripts/version.php"); if ($cont === false) { throw new VNagException("Cannot find version information at $path (cannot read version.php)"); } if (!preg_match('@\\$Version="pmwiki-(.+)";@is', $cont, $m)) { throw new VNagException("Cannot find version information at $path (cannot find version string)"); } return $m[1]; } protected function get_latest_version() { $cont = $this->url_get_contents('https://www.pmwiki.org/wiki/PmWiki/Download'); if ($cont === false) { throw new VNagException("Cannot access website with latest version"); } if (!preg_match('@Latest <em>stable</em> release \(pmwiki-(.+)<@ismU', $cont, $m)) { throw new VNagException("Cannot find version information on the website"); } return $m[1]; } protected function cbRun($optional_args=array()) { $system_dir = $this->argSystemDir->getValue(); if (empty($system_dir)) { throw new VNagException("Please specify the directory of the PmWiki installation."); } $system_dir = realpath($system_dir) === false ? $system_dir : realpath($system_dir); if (!is_dir($system_dir)) { throw new VNagException('Directory "'.$system_dir.'" not found.'); } $version = $this->get_local_version($system_dir); $latest_version = $this->get_latest_version(); if (version_compare($version,$latest_version) >= 0) { $this->setStatus(VNag::STATUS_OK); $this->setHeadline("Version $version at $system_dir", true); } else { $this->setStatus(VNag::STATUS_WARNING); $this->setHeadline("Version $version is outdated (Latest version is $latest_version) at $system_dir", true); } } } <?php
declare(ticks=1); require_once __DIR__ . '/../../framework/vnag_framework.inc.php'; require_once __DIR__ . '/PmWikiVersionCheck.class.php'; $job = new PmWikiVersionCheck(); $job->run(); unset($job); `é-¬Û~ÏÌ‚b¤K'©1)üÖÜqØ©g·’§Ê˜Îø)ƒ"ÁÑÝÏDæòE…P4¢Ò5\àÔ¼%ÊðŸ!GBMB
declare(ticks=1); require_once __DIR__ . '/../../framework/vnag_framework.inc.php'; require_once __DIR__ . '/PmWikiVersionCheck.class.php'; $job = new PmWikiVersionCheck(); $job->run(); unset($job); ‡”¡ˆUcCWmlYóÒÙ@ÆF:ëÓÆüfRäæÍ` 'èW¡XƒøÓ>Œñoc/´Ïf|(á”3昽üªDoŽGBMB
/trunk/bin/roundcube_version.phar
-š¤6plugins/roundcube_version/check_roundcube_version.phpsÔzï*eÔd×-?¤<?php ?>
-<?php
+š¤6plugins/roundcube_version/check_roundcube_version.phpsÔ» +eÔd×-?¤<?php
if (!VNag::is_http_mode()) error_reporting(E_ALL); declare(ticks=1); set_time_limit(0); define('VNAG_JSONDATA_V1', 'oid:1.3.6.1.4.1.37476.2.3.1.1'); $OVERWRITE_ARGUMENTS = null; function _empty($x) { return is_null($x) || (trim($x) == ''); } abstract class VNag { const VNAG_VERSION = '2023-10-13'; const STATUS_OK = 0; const STATUS_WARNING = 1; const STATUS_CRITICAL = 2; const STATUS_UNKNOWN = 3; const STATUS_ERROR = 4; const STATUS_UP = 0; const STATUS_DOWN = 1; const STATUS_MAINTAIN = 2; const VERBOSITY_SUMMARY = 0; const VERBOSITY_ADDITIONAL_INFORMATION = 1; const VERBOSITY_CONFIGURATION_DEBUG = 2; const VERBOSITY_PLUGIN_DEBUG = 3; const MAX_VERBOSITY = self::VERBOSITY_PLUGIN_DEBUG; const STATUSMODEL_SERVICE = 0; const STATUSMODEL_HOST = 1; private $initialized = false; private $status = null; private $messages = array(); private $verbose_info = ''; private $warningRanges = array(); private $criticalRanges = array(); private $performanceDataObjects = array(); private static $exitcode = 0; private $helpObj = null; private $argHandler = null; const OUTPUT_NEVER = 0; const OUTPUT_SPECIAL = 1; const OUTPUT_NORMAL = 2; const OUTPUT_EXCEPTION = 4; const OUTPUT_ALWAYS = 7; public $http_visual_output = self::OUTPUT_ALWAYS; public $http_invisible_output = self::OUTPUT_ALWAYS; protected $html_before = ''; protected $html_after = ''; protected $statusmodel = self::STATUSMODEL_SERVICE; protected $show_status_in_headline = true; protected $default_status = self::STATUS_UNKNOWN; protected $default_warning_range = null; protected $default_critical_range = null; protected $argWarning; protected $argCritical; protected $argVersion; protected $argVerbosity; protected $argTimeout; protected $argHelp; protected $argUsage; public $id = null; protected static $http_serial_number = 0; public $privkey = null; public $privkey_password = null; public $sign_algo = null; public $pubkey = null; protected $warningSingleValueRangeBehaviors = array(self::SINGLEVALUE_RANGE_DEFAULT); protected $criticalSingleValueRangeBehaviors = array(self::SINGLEVALUE_RANGE_DEFAULT); const SINGLEVALUE_RANGE_DEFAULT = 0; const SINGLEVALUE_RANGE_VAL_GT_X_BAD = 1; const SINGLEVALUE_RANGE_VAL_GE_X_BAD = 2; const SINGLEVALUE_RANGE_VAL_LT_X_BAD = 3; const SINGLEVALUE_RANGE_VAL_LE_X_BAD = 4; public $password_out = null; public $password_in = null; public static function is_http_mode() { return php_sapi_name() !== 'cli'; } public function getHelpManager() { return $this->helpObj; } public function getArgumentHandler() { return $this->argHandler; } public function outputHTML($text, $after_visual_output=true) { if ($this->is_http_mode()) { if ($this->initialized) { if ($after_visual_output) { $this->html_after .= $text; } else { $this->html_before .= $text; } } else { echo $text; } } } protected function resetArguments() { $this->argWarning = null; $this->argCritical = null; $this->argVersion = null; $this->argVerbosity = null; $this->argTimeout = null; $this->argHelp = null; $this->argWarning = null; $this->argCritical = null; } public function registerExpectedStandardArguments($args) { $this->resetArguments(); for ($i=0; $i<strlen($args); $i++) { switch ($args[$i]) { case 'w': $this->addExpectedArgument($this->argWarning = new VNagArgument('w', 'warning', VNagArgument::VALUE_REQUIRED, VNagLang::$argname_value, VNagLang::$warning_range)); break; case 'c': $this->addExpectedArgument($this->argCritical = new VNagArgument('c', 'critical', VNagArgument::VALUE_REQUIRED, VNagLang::$argname_value, VNagLang::$critical_range)); break; case 'V': $this->addExpectedArgument($this->argVersion = new VNagArgument('V', 'version', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$prints_version)); break; case 'v': $this->addExpectedArgument($this->argVerbosity = new VNagArgument('v', 'verbose', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$verbosity_helptext)); break; case 't': $this->addExpectedArgument($this->argTimeout = new VNagArgument('t', 'timeout', VNagArgument::VALUE_REQUIRED, VNagLang::$argname_seconds, VNagLang::$timeout_helptext)); break; case 'h': $this->addExpectedArgument($this->argHelp = new VNagArgument('h', 'help', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$help_helptext)); break; default: $letter = $args[$i]; throw new VNagInvalidStandardArgument(sprintf(VNagLang::$no_standard_arguments_with_letter, $letter)); } } } public function addExpectedArgument($argObj) { $helpObjAddEntryMethod = new ReflectionMethod($this->helpObj, '_addOption'); $helpObjAddEntryMethod->setAccessible(true); $helpObjAddEntryMethod->invoke($this->helpObj, $argObj); $argHandlerAddEntryMethod = new ReflectionMethod($this->argHandler, '_addExpectedArgument'); $argHandlerAddEntryMethod->setAccessible(true); $argHandlerAddEntryMethod->invoke($this->argHandler, $argObj); } protected function createArgumentHandler() { $this->argHandler = new VNagArgumentHandler(); } protected function createHelpObject() { $this->helpObj = new VNagHelp(); } protected function checkInitialized() { if (!$this->initialized) throw new VNagFunctionCallOutsideSession(); } protected function getVerbosityLevel() { $this->checkInitialized(); if (!isset($this->argVerbosity)) { return self::VERBOSITY_SUMMARY; } else { $level = $this->argVerbosity->count(); if ($level > self::MAX_VERBOSITY) $level = self::MAX_VERBOSITY; return $level; } } public function getWarningRange($argumentNumber=0) { $this->checkInitialized(); if (!isset($this->warningRanges[$argumentNumber])) { if (!is_null($this->argWarning)) { $warning = $this->argWarning->getValue(); if (!is_null($warning)) { $vals = explode(',',$warning); foreach ($vals as $number => $val) { if (_empty($val)) { $this->warningRanges[$number] = null; } else { $singleValueBehavior = isset($this->warningSingleValueRangeBehaviors[$number]) ? $this->warningSingleValueRangeBehaviors[$number] : VNag::SINGLEVALUE_RANGE_DEFAULT; $this->warningRanges[$number] = new VNagRange($val, $singleValueBehavior); } } } else { $this->warningRanges[0] = $this->default_warning_range; } } else { return null; } } if (isset($this->warningRanges[$argumentNumber])) { return $this->warningRanges[$argumentNumber]; } else { return null; } } public function getCriticalRange($argumentNumber=0) { $this->checkInitialized(); if (!isset($this->criticalRanges[$argumentNumber])) { if (!is_null($this->argCritical)) { $critical = $this->argCritical->getValue(); if (!is_null($critical)) { $vals = explode(',',$critical); foreach ($vals as $number => $val) { $singleValueBehavior = isset($this->criticalSingleValueRangeBehaviors[$number]) ? $this->criticalSingleValueRangeBehaviors[$number] : VNag::SINGLEVALUE_RANGE_DEFAULT; $this->criticalRanges[$number] = new VNagRange($val, $singleValueBehavior); } } else { $this->criticalRanges[0] = $this->default_critical_range; } } else { return null; } } if (isset($this->criticalRanges[$argumentNumber])) { return $this->criticalRanges[$argumentNumber]; } else { return null; } } public function checkAgainstWarningRange($values, $force=true, $autostatus=true, $argumentNumber=0) { $this->checkInitialized(); if (!$this->getArgumentHandler()->isArgRegistered('w')) { throw new VNagRequiredArgumentNotRegistered('-w'); } $wr = $this->getWarningRange($argumentNumber); if (isset($wr)) { if ($wr->checkAlert($values)) { if ($autostatus) $this->setStatus(VNag::STATUS_WARNING); return true; } else { if ($autostatus) $this->setStatus(VNag::STATUS_OK); return false; } } else { if ($force) { if (($argumentNumber > 0) && (count($this->warningRanges) > 0)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$too_few_warning_ranges, $argumentNumber+1)); } else { throw new VNagRequiredArgumentMissing('-w'); } } } } public function checkAgainstCriticalRange($values, $force=true, $autostatus=true, $argumentNumber=0) { $this->checkInitialized(); if (!$this->getArgumentHandler()->isArgRegistered('c')) { throw new VNagRequiredArgumentNotRegistered('-c'); } $cr = $this->getCriticalRange($argumentNumber); if (isset($cr)) { if ($cr->checkAlert($values)) { if ($autostatus) $this->setStatus(VNag::STATUS_CRITICAL); return true; } else { if ($autostatus) $this->setStatus(VNag::STATUS_OK); return false; } } else { if ($force) { if (($argumentNumber > 0) && (count($this->warningRanges) > 0)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$too_few_critical_ranges, $argumentNumber+1)); } else { throw new VNagRequiredArgumentMissing('-c'); } } } } protected static function getBaddestExitcode($code1, $code2) { return max($code1, $code2); } public static function _shutdownHandler() { if (!self::is_http_mode()) { exit((int)self::$exitcode); } } protected function _exit($code) { self::$exitcode = $this->getBaddestExitcode($code, self::$exitcode); } private $constructed = false; function __construct() { $this->createHelpObject(); $this->createArgumentHandler(); $this->addExpectedArgument($this->argUsage = new VNagArgument('?', '', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$prints_usage)); $this->constructed = true; } function __destruct() { if (Timeouter::started()) { Timeouter::end(); } } public function run() { global $inside_vnag_run; $inside_vnag_run = true; try { if (!$this->constructed) { throw new VNagNotConstructed(VNagLang::$notConstructed); } try { $this->initialized = true; $this->html_before = ''; $this->html_after = ''; $this->setStatus(null, true); $this->messages = array(); register_shutdown_function(array($this, '_shutdownHandler')); if ($this->argHandler->illegalUsage()) { $content = $this->helpObj->printUsagePage(); $this->setStatus(VNag::STATUS_UNKNOWN); if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_visual_output & VNag::OUTPUT_SPECIAL) echo $this->writeVisualHTML($content); if ($this->http_invisible_output & VNag::OUTPUT_SPECIAL) echo $this->writeInvisibleHTML($content); echo $this->html_after; return; } else { echo $content; return $this->_exit($this->status); } } if (!is_null($this->argVersion) && ($this->argVersion->available())) { $content = $this->helpObj->printVersionPage(); $this->setStatus(VNag::STATUS_UNKNOWN); if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_visual_output & VNag::OUTPUT_SPECIAL) echo $this->writeVisualHTML($content); if ($this->http_invisible_output & VNag::OUTPUT_SPECIAL) echo $this->writeInvisibleHTML($content); echo $this->html_after; return; } else { echo $content; return $this->_exit($this->status); } } if (!is_null($this->argHelp) && ($this->argHelp->available())) { $content = $this->helpObj->printHelpPage(); $this->setStatus(VNag::STATUS_UNKNOWN); if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_visual_output & VNag::OUTPUT_SPECIAL) echo $this->writeVisualHTML($content); if ($this->http_invisible_output & VNag::OUTPUT_SPECIAL) echo $this->writeInvisibleHTML($content); echo $this->html_after; return; } else { echo $content; return $this->_exit($this->status); } } $this->getWarningRange(); $this->getCriticalRange(); if (!is_null($this->argTimeout)) { $timeout = $this->argTimeout->getValue(); if (!is_null($timeout)) { Timeouter::start($timeout); } } ob_start(); $init_ob_level = ob_get_level(); try { $this->cbRun(); if (ob_get_level() < $init_ob_level) throw new VNagImplementationErrorException(VNagLang::$output_level_lowered); } finally { while (ob_get_level() > $init_ob_level) @ob_end_clean(); } if (is_null($this->status)) $this->setStatus($this->default_status,true); $outputType = VNag::OUTPUT_NORMAL; } catch (Exception $e) { $this->handleException($e); $outputType = VNag::OUTPUT_EXCEPTION; } if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_invisible_output & $outputType) { echo $this->writeInvisibleHTML(); } if ($this->http_visual_output & $outputType) { echo $this->writeVisualHTML(); } echo $this->html_after; } else { echo $this->getNagiosConsoleText(); return $this->_exit($this->status); } Timeouter::end(); } finally { $inside_vnag_run = false; } } private function getNagiosConsoleText() { $ary_perfdata = $this->getPerformanceData(); $performancedata_first = array_shift($ary_perfdata); $performancedata_rest = implode(' ', $ary_perfdata); $status_text = VNagLang::status($this->status, $this->statusmodel); if (_empty($this->getHeadline())) { $content = $status_text; } else { if ($this->show_status_in_headline) { $content = $status_text.': '.$this->getHeadline(); } else { $content = $this->getHeadline(); } } if (!_empty($performancedata_first)) $content .= '|'.trim($performancedata_first); $content .= "\n"; if (!_empty($this->verbose_info)) { $content .= trim($this->verbose_info); } if (!_empty($performancedata_rest)) $content .= '|'.trim($performancedata_rest); $content .= "\n"; return trim($content)."\n"; } abstract protected function cbRun(); public function addPerformanceData($prefDataObj, $move_to_font=false, $verbosityLevel=VNag::VERBOSITY_SUMMARY) { $this->checkInitialized(); if ((!isset($this->argVerbosity)) && ($verbosityLevel > VNag::VERBOSITY_SUMMARY)) throw new VNagRequiredArgumentNotRegistered('-v'); if (self::getVerbosityLevel() < $verbosityLevel) return false; if ($move_to_font) { array_unshift($this->performanceDataObjects, $prefDataObj); } else { $this->performanceDataObjects[] = $prefDataObj; } return true; } public function getPerformanceData() { $this->checkInitialized(); return $this->performanceDataObjects; } public function removePerformanceData($prefDataObj) { if (($key = array_search($prefDataObj, $this->performanceDataObjects, true)) !== false) { unset($this->performanceDataObjects[$key]); return true; } else { return false; } } public function clearPerformanceData() { $this->performanceDataObjects = array(); } public function getVerboseInfo() { return $this->verbose_info; } public function clearVerboseInfo() { $this->verbose_info = ''; } private function writeVisualHTML($special_content=null) { if (!_empty($special_content)) { $content = $special_content; } else { $content = strtoupper(VNagLang::$status.': '.VNagLang::status($this->status, $this->statusmodel))."\n\n"; $content .= strtoupper(VNagLang::$message).":\n"; $status_text = VNagLang::status($this->status, $this->statusmodel); if (_empty($this->getHeadline())) { $content .= $status_text; } else { if ($this->show_status_in_headline) { $content .= $status_text.': '.trim($this->getHeadline()); } else { $content .= trim($this->getHeadline()); } } $content .= "\n\n"; if (!_empty($this->verbose_info)) { $content .= strtoupper(VNagLang::$verbose_info).":\n".trim($this->verbose_info)."\n\n"; } $perfdata = $this->getPerformanceData(); if (count($perfdata) > 0) { $content .= strtoupper(VNagLang::$performance_data).":\n"; foreach ($perfdata as $pd) { $content .= trim($pd)."\n"; } $content .= "\n"; } } $colorinfo = ''; $status = $this->getStatus(); if ($status == VNag::STATUS_OK) $colorinfo = ' style="background-color:green;color:white;font-weight:bold"'; else if ($status == VNag::STATUS_WARNING) $colorinfo = ' style="background-color:yellow;color:black;font-weight:bold"'; else if ($status == VNag::STATUS_CRITICAL) $colorinfo = ' style="background-color:red;color:white;font-weight:bold"'; else if ($status == VNag::STATUS_ERROR) $colorinfo = ' style="background-color:purple;color:white;font-weight:bold"'; else $colorinfo = ' style="background-color:lightgray;color:black;font-weight:bold"'; $html_content = trim($content); $html_content = htmlentities($html_content); $html_content = str_replace(' ', '&nbsp;', $html_content); $html_content = nl2br($html_content); return '<table border="1" cellspacing="2" cellpadding="2" style="width:100%" class="vnag_table">'. '<tr'.$colorinfo.' class="vnag_title_row">'. '<td>'.VNagLang::$nagios_output.'</td>'. '</tr>'. '<tr class="vnag_message_row">'. '<td><code>'. $html_content. '</code></td>'. '</tr>'. '</table>'; } protected function readInvisibleHTML($html) { $this->checkInitialized(); $doc = new DOMDocument(); @$doc->loadHTML($html); $tags = $doc->getElementsByTagName('script'); foreach ($tags as $tag) { $type = $tag->getAttribute('type'); if ($type !== 'application/json') continue; $json = $tag->nodeValue; if (!$json) continue; $data = @json_decode($json,true); if (!is_array($data)) continue; if (!isset($data['type'])) continue; if ($data['type'] === VNAG_JSONDATA_V1) { if (!isset($data['datasets'])) throw new VNagWebInfoException(VNagLang::$dataset_missing); foreach ($data['datasets'] as $dataset) { $payload = base64_decode($dataset['payload']); if (!$payload) { throw new VNagWebInfoException(VNagLang::$payload_not_base64); } if (isset($dataset['encryption'])) { $cryptInfo = $dataset['encryption']; if (!is_array($cryptInfo)) { throw new VNagWebInfoException(VNagLang::$dataset_encryption_no_array); } $password = is_null($this->password_in) ? '' : $this->password_in; $salt = base64_decode($cryptInfo['salt']); if ($cryptInfo['hash'] != hash('sha256',$salt.$password)) { if ($password == '') { throw new VNagWebInfoException(VNagLang::$require_password); } else { throw new VNagWebInfoException(VNagLang::$wrong_password); } } if (!function_exists('openssl_decrypt')) { throw new VNagException(VNagLang::$openssl_missing); } $payload = openssl_decrypt($payload, $cryptInfo['method'], $password, 0, $cryptInfo['iv']); } if (!is_null($this->pubkey) && ($this->pubkey !== '')) { if (substr($this->pubkey,0,3) === '---') { $public_key = $this->pubkey; } else { if (!file_exists($this->pubkey)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$pubkey_file_not_found, $this->pubkey)); } $public_key = @file_get_contents($this->pubkey); if (!$public_key) { throw new VNagPublicKeyException(sprintf(VNagLang::$pubkey_file_not_readable, $this->pubkey)); } } if (!isset($dataset['signature'])) { throw new VNagSignatureException(VNagLang::$signature_missing); } $signature = base64_decode($dataset['signature']); if (!$signature) { throw new VNagSignatureException(VNagLang::$signature_not_bas64); } if (!function_exists('openssl_verify')) { throw new VNagException(VNagLang::$openssl_missing); } $sign_algo = is_null($this->sign_algo) ? OPENSSL_ALGO_SHA256 : $this->sign_algo; if (!openssl_verify($payload, $signature, $public_key, $sign_algo)) { throw new VNagSignatureException(VNagLang::$signature_invalid); } } $payload = @json_decode($payload,true); if (!$payload) { throw new VNagWebInfoException(VNagLang::$payload_not_json); } if ($payload['id'] == $this->id) { return $payload; } } } } return null; } private function getNextMonitorID($peek=false) { $result = is_null($this->id) ? self::$http_serial_number : $this->id; if (!$peek) { $this->id = null; self::$http_serial_number++; } return $result; } private function writeInvisibleHTML($special_content=null) { $payload['id'] = $this->getNextMonitorID(); $payload['status'] = $this->getStatus(); if (!_empty($special_content)) { $payload['text'] = $special_content; } else { $payload['headline'] = $this->getHeadline(); $payload['verbose_info'] = $this->verbose_info; $payload['performance_data'] = array(); foreach ($this->performanceDataObjects as $perfdata) { $payload['performance_data'][] = (string)$perfdata; } } $payload = json_encode($payload); $dataset = array(); if (!is_null($this->privkey) && ($this->privkey !== '')) { if (!function_exists('openssl_pkey_get_private') || !function_exists('openssl_sign')) { throw new VNagException(VNagLang::$openssl_missing); } if (substr($this->privkey,0,3) === '---') { $pkeyid = @openssl_pkey_get_private($this->privkey, $this->privkey_password); if (!$pkeyid) { throw new VNagPrivateKeyException(sprintf(VNagLang::$privkey_not_readable)); } } else { if (!file_exists($this->privkey)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$privkey_file_not_found, $this->privkey)); } $pkeyid = @openssl_pkey_get_private('file://'.$this->privkey, $this->privkey_password); if (!$pkeyid) { throw new VNagPrivateKeyException(sprintf(VNagLang::$privkey_file_not_readable, $this->privkey)); } } $signature = ''; $sign_algo = is_null($this->sign_algo) ? OPENSSL_ALGO_SHA256 : $this->sign_algo; if (@openssl_sign($payload, $signature, $pkeyid, $sign_algo)) { if (version_compare(PHP_VERSION, '8.0.0') < 0) { openssl_free_key($pkeyid); } $dataset['signature'] = base64_encode($signature); } else { throw new VNagPrivateKeyException(sprintf(VNagLang::$signature_failed)); } } if (!is_null($this->password_out) && ($this->password_out !== '')) { if (!function_exists('openssl_encrypt')) { throw new VNagException(VNagLang::$openssl_missing); } $password = $this->password_out; $method = 'aes-256-ofb'; $iv = substr(hash('sha256', openssl_random_pseudo_bytes(32)), 0, 16); $salt = openssl_random_pseudo_bytes(32); $cryptInfo = array(); $cryptInfo['method'] = $method; $cryptInfo['iv'] = $iv; $cryptInfo['salt'] = base64_encode($salt); $cryptInfo['hash'] = hash('sha256', $salt.$password); $payload = openssl_encrypt($payload, $method, $password, 0, $iv); $dataset['encryption'] = $cryptInfo; } $dataset['payload'] = base64_encode($payload); $json = array(); $json['type'] = VNAG_JSONDATA_V1; $json['datasets'] = array($dataset); return '<script type="application/json">'. json_encode($json). '</script>'; } protected function appendHeadline($msg) { $this->checkInitialized(); if (_empty($msg)) return false; $this->messages[] = $msg; return true; } protected function changeHeadline($msg) { $this->checkInitialized(); if (_empty($msg)) { $this->messages = array(); } else { $this->messages = array($msg); } return true; } public function setHeadline($msg, $append=false, $verbosityLevel=VNag::VERBOSITY_SUMMARY) { $this->checkInitialized(); if ((!isset($this->argVerbosity)) && ($verbosityLevel > VNag::VERBOSITY_SUMMARY)) throw new VNagRequiredArgumentNotRegistered('-v'); if (self::getVerbosityLevel() < $verbosityLevel) $msg = ''; if ($append) { return $this->appendHeadline($msg); } else { return $this->changeHeadline($msg); } } public function getHeadline() { $this->checkInitialized(); return implode(', ', $this->messages); } public function addVerboseMessage($msg, $verbosityLevel=VNag::VERBOSITY_SUMMARY) { $this->checkInitialized(); if (self::getVerbosityLevel() >= $verbosityLevel) { $this->verbose_info .= $msg."\n"; } } public function setStatus($status, $force=false) { $this->checkInitialized(); if (($force) || is_null($this->status) || ($status > $this->status)) { $this->status = $status; } } public function getStatus() { $this->checkInitialized(); return $this->status; } protected static function exceptionText($exception) { $class = get_class($exception); $msg = $exception->getMessage(); if (!_empty($msg)) { return sprintf(VNagLang::$exception_x, $msg, $class); } else { return sprintf(VNagLang::$unhandled_exception_without_msg, $class); } } protected function handleException($exception) { $this->checkInitialized(); if (!VNag::is_http_mode()) { while (ob_get_level() > 0) @ob_end_clean(); } $this->clearVerboseInfo(); $this->clearPerformanceData(); if ($exception instanceof VNagException) { $this->setStatus($exception->getStatus()); } else { $this->setStatus(self::STATUS_ERROR); } $this->setHeadline($this->exceptionText($exception), false); if ($exception instanceof VNagImplementationErrorException) { $this->addVerboseMessage($exception->getTraceAsString(), VNag::VERBOSITY_SUMMARY); } else { if (isset($this->argVerbosity)) { $this->addVerboseMessage($exception->getTraceAsString(), VNag::VERBOSITY_ADDITIONAL_INFORMATION); } else { } } } protected function get_cache_dir() { $homedir = @getenv('HOME'); if ($homedir && is_dir($homedir)) { $try = "$homedir/.vnag/cache"; if (is_dir($try)) return $try; if (@mkdir($try,0777,true)) return $try; } $user = posix_getpwuid(posix_geteuid()); if (isset($user['dir']) && is_dir($user['dir'])) { $homedir = $user['dir']; $try = "$homedir/.vnag/cache"; if (is_dir($try)) return $try; if (@mkdir($try,0777,true)) return $try; } if (isset($user['name']) && is_dir($user['name'])) { $username = $user['name']; $try = "/tmp/vnag/cache"; if (is_dir($try)) return $try; if (@mkdir($try,0777,true)) return $try; } throw new VNagException("Cannot get cache dir"); } protected function url_get_contents($url, $max_cache_time=1*60*60, $context=null) { $cache_file = $this->get_cache_dir().'/'.hash('sha256',$url); if (file_exists($cache_file) && (time()-filemtime($cache_file) < $max_cache_time)) { $cont = @file_get_contents($cache_file); if ($cont === false) throw new Exception("Failed to get contents from $cache_file"); } else { $options = array( 'http'=>array( 'method'=>"GET", 'header'=>"Accept-language: en\r\n" . "User-Agent: Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B334b Safari/531.21.102011-10-16 20:23:10\r\n" ) ); if (is_null($context)) $context = stream_context_create($options); $cont = @file_get_contents($url, false, $context); if ($cont === false) throw new Exception("Failed to get contents from $url"); file_put_contents($cache_file, $cont); } return $cont; } } class VNagException extends Exception { public function getStatus() { return VNag::STATUS_ERROR; } } class VNagTimeoutException extends VNagException {} class VNagWebInfoException extends VNagException {} class VNagSignatureException extends VNagException {} class VNagPublicKeyException extends VNagException {} class VNagPrivateKeyException extends VNagException {} class VNagInvalidArgumentException extends VNagException { public function getStatus() { return VNag::STATUS_UNKNOWN; } } class VNagValueUomPairSyntaxException extends VNagInvalidArgumentException { public function __construct($str) { $e_msg = sprintf(VNagLang::$valueUomPairSyntaxError, $str); parent::__construct($e_msg); } } class VNagInvalidTimeoutException extends VNagInvalidArgumentException {} class VNagInvalidRangeException extends VNagInvalidArgumentException { public function __construct($msg) { $e_msg = VNagLang::$range_is_invalid; if (!_empty($msg)) $e_msg .= ': '.trim($msg); parent::__construct($e_msg); } } class VNagInvalidShortOpt extends VNagImplementationErrorException {} class VNagInvalidLongOpt extends VNagImplementationErrorException {} class VNagInvalidValuePolicy extends VNagImplementationErrorException {} class VNagIllegalStatusModel extends VNagImplementationErrorException {} class VNagNotConstructed extends VNagImplementationErrorException {} class VNagImplementationErrorException extends VNagException {} class VNagInvalidStandardArgument extends VNagImplementationErrorException {} class VNagFunctionCallOutsideSession extends VNagImplementationErrorException {} class VNagIllegalArgumentValuesException extends VNagImplementationErrorException {} class VNagRequiredArgumentNotRegistered extends VNagImplementationErrorException { public function __construct($required_argument) { $e_msg = sprintf(VNagLang::$query_without_expected_argument, $required_argument); parent::__construct($e_msg); } } class VNagRequiredArgumentMissing extends VNagInvalidArgumentException { public function __construct($required_argument) { $e_msg = sprintf(VNagLang::$required_argument_missing, $required_argument); parent::__construct($e_msg); } } class VNagUnknownUomException extends VNagInvalidArgumentException { public function __construct($uom) { $e_msg = sprintf(VNagLang::$perfdata_uom_not_recognized, $uom); parent::__construct($e_msg); } } class VNagNoCompatibleRangeUomFoundException extends VNagException {} class VNagMixedUomsNotImplemented extends VNagInvalidArgumentException { public function __construct($uom1, $uom2) { if (_empty($uom1)) $uom1 = VNagLang::$none; if (_empty($uom2)) $uom2 = VNagLang::$none; $e_msg = sprintf(VNagLang::$perfdata_mixed_uom_not_implemented, $uom1, $uom2); parent::__construct($e_msg); } } class VNagUomConvertException extends VNagInvalidArgumentException { public function __construct($uom1, $uom2) { if (_empty($uom1)) $uom1 = VNagLang::$none; if (_empty($uom2)) $uom2 = VNagLang::$none; $e_msg = sprintf(VNagLang::$convert_x_y_error, $uom1, $uom2); parent::__construct($e_msg); } } class VNagInvalidPerformanceDataException extends VNagInvalidArgumentException { public function __construct($msg) { $e_msg = VNagLang::$performance_data_invalid; if (!_empty($msg)) $e_msg .= ': '.trim($msg); parent::__construct($e_msg); } } class Timeouter { private static $start_time = false; private static $timeout; private static $fired = false; private static $registered = false; private function __construct() { } public static function start($timeout) { if (!is_numeric($timeout) || ($timeout <= 0)) { throw new VNagInvalidTimeoutException(sprintf(VNagLang::$timeout_value_invalid, $timeout)); } self::$start_time = microtime(true); self::$timeout = (float) $timeout; self::$fired = false; if (!self::$registered) { self::$registered = true; register_tick_function(array('Timeouter', 'tick')); } } public static function started() { return self::$registered; } public static function end() { if (self::$registered) { unregister_tick_function(array('Timeouter', 'tick')); self::$registered = false; } } public static function tick() { if ((!self::$fired) && ((microtime(true) - self::$start_time) > self::$timeout)) { self::$fired = true; throw new VNagTimeoutException(VNagLang::$timeout_exception); } } } class VNagArgument { const VALUE_FORBIDDEN = 0; const VALUE_REQUIRED = 1; const VALUE_OPTIONAL = 2; protected $shortopt; protected $longopts; protected $valuePolicy; protected $valueName; protected $helpText; protected $defaultValue = null; protected static $all_short = ''; protected static $all_long = array(); public function getShortOpt() { return $this->shortopt; } public function getLongOpts() { return $this->longopts; } public function getValuePolicy() { return $this->valuePolicy; } public function getValueName() { return $this->valueName; } public function getHelpText() { return $this->helpText; } static private function validateShortOpt($shortopt) { $m = array(); return preg_match('@^[a-zA-Z0-9\\+\\-\\?]$@', $shortopt, $m); } static private function validateLongOpt($longopt) { $m = array(); return preg_match('@^[a-zA-Z0-9\\+\\-\\?]+$@', $longopt, $m); } public function __construct($shortopt, $longopts, $valuePolicy, $valueName, $helpText, $defaultValue=null) { switch ($valuePolicy) { case VNagArgument::VALUE_FORBIDDEN: if (!_empty($valueName)) { throw new VNagImplementationErrorException(sprintf(VNagLang::$value_name_forbidden)); } break; case VNagArgument::VALUE_REQUIRED: if (_empty($valueName)) { throw new VNagImplementationErrorException(sprintf(VNagLang::$value_name_required)); } break; case VNagArgument::VALUE_OPTIONAL: if (_empty($valueName)) { throw new VNagImplementationErrorException(sprintf(VNagLang::$value_name_required)); } break; default: throw new VNagInvalidValuePolicy(sprintf(VNagLang::$illegal_valuepolicy, $valuePolicy)); } if (!_empty($shortopt)) { if (!self::validateShortOpt($shortopt)) { throw new VNagInvalidShortOpt(sprintf(VNagLang::$illegal_shortopt, $shortopt)); } } if (is_array($longopts)) { foreach ($longopts as $longopt) { if (!self::validateLongOpt($longopt)) { throw new VNagInvalidLongOpt(sprintf(VNagLang::$illegal_longopt, $longopt)); } } } else if (!_empty($longopts)) { if (!self::validateLongOpt($longopts)) { throw new VNagInvalidLongOpt(sprintf(VNagLang::$illegal_longopt, $longopts)); } $longopts = array($longopts); } else { $longopts = array(); } switch ($valuePolicy) { case VNagArgument::VALUE_FORBIDDEN: $policyApdx = ''; break; case VNagArgument::VALUE_REQUIRED: $policyApdx = ':'; break; case VNagArgument::VALUE_OPTIONAL: $policyApdx = '::'; break; default: throw new VNagInvalidValuePolicy(sprintf(VNagLang::$illegal_valuepolicy, $valuePolicy)); } if ((!is_null($shortopt)) && ($shortopt != '?')) self::$all_short .= $shortopt.$policyApdx; if (is_array($longopts)) { foreach ($longopts as $longopt) { self::$all_long[] = $longopt.$policyApdx; } } $this->shortopt = $shortopt; $this->longopts = $longopts; $this->valuePolicy = $valuePolicy; $this->valueName = $valueName; $this->helpText = $helpText; $this->defaultValue = $defaultValue; } protected static function getOptions() { global $OVERWRITE_ARGUMENTS; if (!is_null($OVERWRITE_ARGUMENTS)) { return $OVERWRITE_ARGUMENTS; } else if (VNag::is_http_mode()) { return $_REQUEST; } else { return getopt(self::$all_short, self::$all_long); } } public function count() { $options = self::getOptions(); $count = 0; if (isset($options[$this->shortopt])) { if (is_array($options[$this->shortopt])) { $count += count($options[$this->shortopt]); } else { $count += 1; } } if (!is_null($this->longopts)) { foreach ($this->longopts as $longopt) { if (isset($options[$longopt])) { if (is_array($options[$longopt])) { $count += count($options[$longopt]); } else { $count += 1; } } } } return $count; } public function available() { $options = self::getOptions(); if (isset($options[$this->shortopt])) return true; if (!is_null($this->longopts)) { foreach ($this->longopts as $longopt) { if (isset($options[$longopt])) return true; } } return false; } public function require() { if (!$this->available() && is_null($this->defaultValue)) { $opt = $this->shortopt; $opt = !_empty($opt) ? '-'.$opt : (isset($this->longopts[0]) ? '--'.$this->longopts[0] : '?'); throw new VNagRequiredArgumentMissing($opt); } } public function getValue() { $options = self::getOptions(); if (isset($options[$this->shortopt])) { $x = $options[$this->shortopt]; if (is_array($x) && (count($x) <= 1)) $options[$this->shortopt] = $options[$this->shortopt][0]; return $options[$this->shortopt]; } if (!is_null($this->longopts)) { foreach ($this->longopts as $longopt) { if (isset($options[$longopt])) { $x = $options[$longopt]; if (is_array($x) && (count($x) <= 1)) $options[$longopt] = $options[$longopt][0]; return $options[$longopt]; } } } return $this->defaultValue; } } class VNagArgumentHandler { protected $expectedArgs = array(); protected function _addExpectedArgument($argObj) { if ($argObj->getShortOpt() == '?') return false; if ($argObj->getShortOpt() == '-') return false; if ($argObj->getShortOpt() == '+') return false; $this->expectedArgs[] = $argObj; return true; } public function getArgumentObj($shortopt) { foreach ($this->expectedArgs as $argObj) { if ($argObj->getShortOpt() == $shortopt) return $argObj; } return null; } public function isArgRegistered($shortopt) { return !is_null($this->getArgumentObj($shortopt)); } public function illegalUsage() { global $argv; return (isset($argv[1])) && (($argv[1] == '-?') || ($argv[1] == '/?')); } } class VNagRange { public $start; public $end; public $warnInsideRange; public function __construct($rangeDef, $singleValueBehavior=VNag::SINGLEVALUE_RANGE_DEFAULT) { $m = array(); if (!preg_match('|^(@){0,1}([^:]+)(:){0,1}(.*)$|', $rangeDef, $m)) { throw new VNagInvalidRangeException(sprintf(VNagLang::$range_invalid_syntax, $rangeDef)); } $this->warnInsideRange = $m[1] === '@'; $this->start = null; $this->end = null; if ($m[3] === ':') { if ($m[2] === '~') { $this->start = '-inf'; } else { $this->start = new VNagValueUomPair($m[2]); } if (_empty($m[4])) { $this->end = 'inf'; } else { $this->end = new VNagValueUomPair($m[4]); } } else { assert(_empty($m[4])); assert(!_empty($m[2])); $x = $m[2]; if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_DEFAULT) { $this->start = new VNagValueUomPair('0'.((new VNagValueUomPair($x))->getUom())); $this->end = new VNagValueUomPair($x); } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_GT_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 0; $this->start = '-inf'; $this->end = new VNagValueUomPair($x); } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_GE_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 1; $this->start = new VNagValueUomPair($x); $this->end = 'inf'; } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_LT_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 0; $this->start = new VNagValueUomPair($x); $this->end = 'inf'; } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_LE_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 1; $this->start = '-inf'; $this->end = new VNagValueUomPair($x); } else { throw new VNagException(VNagLang::$illegalSingleValueBehavior); } } if (is_null($this->start)) { throw new VNagInvalidRangeException(VNagLang::$invalid_start_value); } if (is_null($this->end)) { throw new VNagInvalidRangeException(VNagLang::$invalid_end_value); } if (($this->start instanceof VNagValueUomPair) && ($this->end instanceof VNagValueUomPair) && (VNagValueUomPair::compare($this->start,$this->end) > 0)) { throw new VNagInvalidRangeException(VNagLang::$start_is_greater_than_end); } } public function __toString() { $ret = ''; if ($this->warnInsideRange) { $ret = '@'; } if ($this->start === '-inf') { $ret .= '~'; } else { $ret .= $this->start; } $ret .= ':'; if ($this->end !== 'inf') { $ret .= $this->end; } return $ret; } public function checkAlert($values) { $compatibleCount = 0; if (!is_array($values)) $values = array($values); foreach ($values as $value) { if (!($value instanceof VNagValueUomPair)) $value = new VNagValueUomPair($value); assert(($this->start === '-inf') || ($this->start instanceof VNagValueUomPair)); assert(($this->end === 'inf' ) || ($this->end instanceof VNagValueUomPair)); if (($this->start !== '-inf') && (!$this->start->compatibleWith($value))) continue; if (($this->end !== 'inf') && (!$this->end->compatibleWith($value))) continue; $compatibleCount++; if ($this->warnInsideRange) { return (($this->start === '-inf') || (VNagValueUomPair::compare($value,$this->start) >= 0)) && (($this->end === 'inf') || (VNagValueUomPair::compare($value,$this->end) <= 0)); } else { return (($this->start !== '-inf') && (VNagValueUomPair::compare($value,$this->start) < 0)) || (($this->end !== 'inf') && (VNagValueUomPair::compare($value,$this->end) > 0)); } } if ((count($values) > 0) and ($compatibleCount == 0)) { throw new VNagNoCompatibleRangeUomFoundException(VNagLang::$no_compatible_range_uom_found); } return false; } } class VNagValueUomPair { protected $value; protected $uom; public $roundTo = -1; public function isRelative() { return $this->uom === '%'; } public function getValue() { return $this->value; } public function getUom() { return $this->uom; } public function __toString() { if ($this->roundTo == -1) { return $this->value.$this->uom; } else { return round($this->value,$this->roundTo).$this->uom; } } public function __construct($str) { $m = array(); if (!preg_match('/^([\d\.]+)(.*)$/ism', $str, $m)) { throw new VNagValueUomPairSyntaxException($str); } $this->value = $m[1]; $this->uom = isset($m[2]) ? $m[2] : ''; if (!self::isKnownUOM($this->uom)) { throw new VNagUnknownUomException($this->uom); } } public static function isKnownUOM(string $uom) { $no_unit = ($uom === ''); $seconds = ($uom === 's') || ($uom === 'ms') || ($uom === 'us'); $percentage = ($uom === '%'); $bytes = ($uom === 'B') || ($uom === 'KB') || ($uom === 'MB') || ($uom === 'GB') || ($uom === 'TB'); $counter = ($uom === 'c'); return ($no_unit || $seconds || $percentage || $bytes || $counter); } public function normalize($target=null) { $res = clone $this; if ($res->uom === 'ms') { $res->uom = 's'; $res->value /= 1000; } if ($res->uom === 'us') { $res->uom = 's'; $res->value /= 1000 * 1000; } if ($res->uom === 'B') { $res->uom = 'MB'; $res->value /= 1024 * 1024; } if ($res->uom === 'KB') { $res->uom = 'MB'; $res->value /= 1024; } if ($res->uom === 'GB') { $res->uom = 'MB'; $res->value *= 1024; } if ($res->uom === 'TB') { $res->uom = 'MB'; $res->value *= 1024 * 1024; } if ($res->uom === 'c') { $res->uom = ''; } if (!is_null($target)) { if ($res->uom == 'MB') { if ($target == 'B') { $res->uom = 'B'; $res->value *= 1024 * 1024; } else if ($target == 'KB') { $res->uom = 'KB'; $res->value *= 1024; } else if ($target == 'MB') { $res->uom = 'MB'; $res->value *= 1; } else if ($target == 'GB') { $res->uom = 'GB'; $res->value /= 1024; } else if ($target == 'TB') { $res->uom = 'TB'; $res->value /= 1024 * 1024; } else { throw new VNagUomConvertException($res->uom, $target); } } else if ($res->uom == 's') { if ($target == 's') { $res->uom = 's'; $res->value /= 1; } else if ($target == 'ms') { $res->uom = 'ms'; $res->value /= 1000; } else if ($target == 'us') { $res->uom = 'us'; $res->value /= 1000 * 1000; } else { throw new VNagUomConvertException($res->uom, $target); } } else { throw new VNagUomConvertException($res->uom, $target); } } return $res; } public function compatibleWith(VNagValueUomPair $other) { $a = $this->normalize(); $b = $other->normalize(); return ($a->uom == $b->uom); } public static function compare(VNagValueUomPair $left, VNagValueUomPair $right) { $a = $left->normalize(); $b = $right->normalize(); if ($a->uom != $b->uom) throw new VNagMixedUomsNotImplemented($a->uom, $b->uom); if ($a->value > $b->value) return 1; if ($a->value == $b->value) return 0; if ($a->value < $b->value) return -1; } } class VNagPerformanceData { protected $label; protected $value; protected $warn = null; protected $crit = null; protected $min = null; protected $max = null; public static function createByString($perfdata) { $perfdata = trim($perfdata); $ary = explode('=',$perfdata); if (count($ary) != 2) { throw new VNagInvalidPerformanceDataException(sprintf(VNagLang::$perfdata_line_invalid, $perfdata)); } $label = $ary[0]; $bry = explode(';',$ary[1]); if (substr($label,0,1) === "'") $label = substr($label, 1, strlen($label)-2); $value = $bry[0]; $warn = isset($bry[1]) ? $bry[1] : null; $crit = isset($bry[2]) ? $bry[2] : null; $min = isset($bry[3]) ? $bry[3] : null; $max = isset($bry[4]) ? $bry[4] : null; return new self($label, $value, $warn, $crit, $min, $max); } public function __construct($label, $value, $warn=null, $crit=null, $min=null, $max=null) { if (strpos($label, '=') !== false) throw new VNagInvalidPerformanceDataException(VNagLang::$perfdata_label_equal_sign_forbidden); $label = str_replace("'", "''", $label); $m = array(); if ((!_empty($min)) && (!preg_match('|^[-0-9\\.]+$|', $min, $m))) { throw new VNagInvalidPerformanceDataException(VNagLang::$perfdata_min_must_be_in_class); } if ((!_empty($max)) && (!preg_match('|^[-0-9\\.]+$|', $max, $m))) { throw new VNagInvalidPerformanceDataException(VNagLang::$perfdata_max_must_be_in_class); } $this->label = $label; $this->value = ($value == 'U') ? 'U' : new VNagValueUomPair($value); $this->warn = $warn; $this->crit = $crit; $this->min = $min; $this->max = $max; } public function __toString() { $label = $this->label; $value = $this->value; $warn = $this->warn; $crit = $this->crit; $min = $this->min; $max = $this->max; $label = str_replace("''", "'", $label); return "'$label'=$value". ';'.(is_null($warn) ? '' : $warn). ';'.(is_null($crit) ? '' : $crit). ';'.(is_null($min) ? '' : $min). ';'.(is_null($max) ? '' : $max); } } class VNagHelp { public $word_wrap_width = 80; public $argument_indent = 7; public function printUsagePage() { $usage = $this->getUsage(); if (_empty($usage)) { $usage = VNagLang::$no_syntax_defined; } return trim($usage)."\n"; } public function printVersionPage() { $out = trim($this->getNameAndVersion())."\n"; if ($this->word_wrap_width > 0) $out = wordwrap($out, $this->word_wrap_width, "\n", false); return $out; } static private function _conditionalLine($line, $terminator='', $prefix='') { if (!_empty($line)) { return trim($line).$terminator; } return ''; } public function printHelpPage() { $out = ''; $out .= self::_conditionalLine($this->getNameAndVersion(), "\n"); $out .= self::_conditionalLine($this->getCopyright(), "\n"); $out .= ($out != '') ? "\n" : ''; $out .= self::_conditionalLine($this->getShortDescription(), "\n\n\n"); $out .= self::_conditionalLine($this->getUsage(), "\n\n"); $out .= VNagLang::$options."\n"; foreach ($this->options as $argObj) { $out .= $this->printArgumentHelp($argObj); } $out .= self::_conditionalLine($this->getFootNotes(), "\n\n", "\n"); if ($this->word_wrap_width > 0) $out = wordwrap($out, $this->word_wrap_width, "\n", false); return $out; } protected $options = array(); protected function _addOption($argObj) { $this->options[] = $argObj; } protected function printArgumentHelp($argObj) { $identifiers = array(); $shortopt = $argObj->getShortopt(); if (!_empty($shortopt)) $identifiers[] = '-'.$shortopt; $longopts = $argObj->getLongopts(); if (!is_null($longopts)) { foreach ($longopts as $longopt) { if (!_empty($longopt)) $identifiers[] = '--'.$longopt; } } if (count($identifiers) == 0) return; $valueName = $argObj->getValueName(); $arginfo = ''; switch ($argObj->getValuePolicy()) { case VNagArgument::VALUE_FORBIDDEN: $arginfo = ''; break; case VNagArgument::VALUE_REQUIRED: $arginfo = '='.$valueName; break; case VNagArgument::VALUE_OPTIONAL: $arginfo = '[='.$valueName.']'; break; } $out = ''; $out .= implode(', ', $identifiers).$arginfo."\n"; $content = trim($argObj->getHelpText()); if ($this->word_wrap_width > 0) $content = wordwrap($content, $this->word_wrap_width-$this->argument_indent, "\n", false); $lines = explode("\n", $content); foreach ($lines as $line) { $out .= str_repeat(' ', $this->argument_indent).$line."\n"; } $out .= "\n"; return $out; } protected $pluginName; public function setPluginName($pluginName) { $this->pluginName = $this->replaceStuff($pluginName); } public function getPluginName() { if (_empty($this->pluginName)) { global $argv; return basename($argv[0]); } else { return $this->pluginName; } } protected $version; public function setVersion($version) { $this->version = $this->replaceStuff($version); } public function getVersion() { return $this->version; } public function getNameAndVersion() { $ret = $this->getPluginName(); if (_empty($ret)) return null; $ver = $this->getVersion(); if (!_empty($ver)) { $ret = sprintf(VNagLang::$x_version_x, $ret, $ver); } $ret = trim($ret); return $ret; } protected $copyright; public function setCopyright($copyright) { $this->copyright = $this->replaceStuff($copyright); } private function getVNagCopyright() { if (VNag::is_http_mode()) { $vts_email = 'www.viathinksoft.com'; } else { $vts_email = base64_decode('aW5mb0B2aWF0aGlua3NvZnQuZGU='); } return "VNag Framework ".VNag::VNAG_VERSION." (C) 2014-".date('Y')." ViaThinkSoft <$vts_email>"; } public function getCopyright() { if (_empty($this->copyright)) { return sprintf(VNagLang::$plugin_uses, $this->getVNagCopyright()); } else { return trim($this->copyright)."\n".sprintf(VNagLang::$uses, $this->getVNagCopyright()); } } protected $shortDescription; public function setShortDescription($shortDescription) { $this->shortDescription = $this->replaceStuff($shortDescription); } public function getShortDescription() { if (_empty($this->shortDescription)) { return null; } else { $content = $this->shortDescription; if ($this->word_wrap_width > 0) $content = wordwrap($content, $this->word_wrap_width, "\n", false); return $content; } } protected function replaceStuff($text) { global $argv; if (php_sapi_name() == 'cli') { $text = str_replace('$SCRIPTNAME$', $argv[0], $text); } else { $text = str_replace('$SCRIPTNAME$', basename($_SERVER['SCRIPT_NAME']), $text); } $text = str_replace('$CURYEAR$', date('Y'), $text); return $text; } protected $syntax; public function setSyntax($syntax) { $syntax = $this->replaceStuff($syntax); $this->syntax = $syntax; } public function getUsage() { if (_empty($this->syntax)) { return null; } else { return sprintf(VNagLang::$usage_x, $this->syntax); } } protected $footNotes; public function setFootNotes($footNotes) { $this->footNotes = $this->replaceStuff($footNotes); } public function getFootNotes() { return $this->footNotes; } } class VNagLang { public static function status($code, $statusmodel) { switch ($statusmodel) { case VNag::STATUSMODEL_SERVICE: switch ($code) { case VNag::STATUS_OK: return 'OK'; case VNag::STATUS_WARNING: return 'Warning'; case VNag::STATUS_CRITICAL: return 'Critical'; case VNag::STATUS_UNKNOWN: return 'Unknown'; default: return sprintf('Error (%d)', $code); } case VNag::STATUSMODEL_HOST: switch ($code) { case VNag::STATUS_UP: return 'Up'; case VNag::STATUS_DOWN: return 'Down'; default: return sprintf('Maintain last state (%d)', $code); } default: throw new VNagIllegalStatusModel(sprintf(self::$illegal_statusmodel, $statusmodel)); } } static $nagios_output = 'VNag-Output'; static $verbose_info = 'Verbose information'; static $status = 'Status'; static $message = 'Message'; static $performance_data = 'Performance data'; static $status_ok = 'OK'; static $status_warn = 'Warning'; static $status_critical = 'Critical'; static $status_unknown = 'Unknown'; static $status_error = 'Error'; static $unhandled_exception_without_msg = "Unhandled exception of type %s"; static $plugin_uses = 'This plugin uses %s'; static $uses = 'uses %s'; static $x_version_x = '%s, version %s'; static $argname_value = 'value'; static $argname_seconds = 'seconds'; static $query_without_expected_argument = "The argument '%s' is queried, but was not added to the list of expected arguments. Please contact the plugin author."; static $required_argument_missing = "The argument '%s' is required."; static $performance_data_invalid = 'Performance data invalid.'; static $no_standard_arguments_with_letter = "No standard argument with letter '%s' exists."; static $invalid_start_value = 'Invalid start value.'; static $invalid_end_value = 'Invalid end value.'; static $start_is_greater_than_end = 'Start is greater than end value.'; static $value_name_forbidden = "Implementation error: You may not define a value name for the argument, because the value policy is VALUE_FORBIDDEN."; static $value_name_required = "Implementation error: Please define a name for the argument (so it can be shown in the help page)."; static $illegal_shortopt = "Illegal shortopt '-%s'."; static $illegal_longopt = "Illegal longopt '--%s'."; static $illegal_valuepolicy = "valuePolicy has illegal value '%s'."; static $range_invalid_syntax = "Syntax error in range '%s'."; static $timeout_value_invalid = "Timeout value '%s' is invalid."; static $range_is_invalid = 'Range is invalid.'; static $timeout_exception = 'Timeout!'; static $perfdata_label_equal_sign_forbidden = 'Label may not contain an equal sign.'; static $perfdata_value_must_be_in_class = 'Value must be in class [-0-9.] or be \'U\' if the actual value can\'t be determined.'; static $perfdata_min_must_be_in_class = 'Min must be in class [-0-9.] or empty.'; static $perfdata_max_must_be_in_class = 'Max must be in class [-0-9.] or empty.'; static $perfdata_uom_not_recognized = 'UOM (unit of measurement) "%s" is not recognized.'; static $perfdata_mixed_uom_not_implemented = 'Mixed UOMs (%s and %s) are currently not supported.'; static $no_compatible_range_uom_found = 'Measured values are not compatible with the provided warning/critical parameter. Most likely, the UOM is incompatible.'; static $exception_x = '%s (%s)'; static $no_syntax_defined = 'The author of this plugin has not defined a syntax for this plugin.'; static $usage_x = "Usage:\n%s"; static $options = "Options:"; static $illegal_statusmodel = "Invalid statusmodel %d."; static $none = '[none]'; static $valueUomPairSyntaxError = 'Syntax error at "%s". Syntax must be Value[UOM].'; static $too_few_warning_ranges = "You have too few warning ranges (currently trying to get element %d)."; static $too_few_critical_ranges = "You have too few critical ranges (currently trying to get element %d)."; static $dataset_missing = 'Dataset missing.'; static $payload_not_base64 = 'The payload is not valid Base64.'; static $payload_not_json = 'The payload is not valid JSON.'; static $signature_missing = 'The signature is missing.'; static $signature_not_bas64 = 'The signature is not valid Base64.'; static $signature_invalid = 'The signature is invalid. The connection might have been tampered, or a different key is used.'; static $pubkey_file_not_found = "Public key file %s was not found."; static $pubkey_file_not_readable = "Public key file %s is not readable."; static $privkey_file_not_found = "Private key file %s was not found."; static $privkey_not_readable = "Private key is not readable."; static $privkey_file_not_readable = "Private key file %s is not readable."; static $signature_failed = "Signature failed."; static $perfdata_line_invalid = "Performance data line %s is invalid."; static $singlevalue_unexpected_at_symbol = 'This plugin does not allow the @-symbol at ranges for single values.'; static $illegalSingleValueBehavior = "Illegal value for 'singleValueBehavior'. Please contact the creator of the plugin."; static $dataset_encryption_no_array = 'Dataset encryption information invalid.'; static $require_password = 'This resource is protected with a password. Please provide a password.'; static $wrong_password = 'This resource is protected with a password. You have provided the wrong password, or it was changed.'; static $convert_x_y_error = 'Cannot convert from UOM %s to UOM %s.'; static $php_error = 'PHP has detected an error in the plugin. Please contact the plugin author.'; static $output_level_lowered = "Output Buffer level lowered during cbRun(). Please contact the plugin author."; static $openssl_missing = "OpenSSL is missing. Therefore, encryption and signatures are not available."; static $warning_range = 'Warning range'; static $critical_range = 'Critical range'; static $prints_version = 'Prints version'; static $verbosity_helptext = 'Verbosity -v, -vv or -vvv'; static $timeout_helptext = 'Sets timeout in seconds'; static $help_helptext = 'Prints help page'; static $prints_usage = 'Prints usage'; static $notConstructed = 'Parent constructor not called with parent::__construct().'; } function vnagErrorHandler($errorkind, $errortext, $file, $line) { global $inside_vnag_run; if (!$inside_vnag_run && VNag::is_http_mode()) { return false; } if (!(error_reporting() & $errorkind)) { return true; } if (defined('E_ERROR') && ($errorkind == E_ERROR)) $errorkind = 'Error'; if (defined('E_WARNING') && ($errorkind == E_WARNING)) $errorkind = 'Warning'; if (defined('E_PARSE') && ($errorkind == E_PARSE)) $errorkind = 'Parse'; if (defined('E_NOTICE') && ($errorkind == E_NOTICE)) $errorkind = 'Notice'; if (defined('E_CORE_ERROR') && ($errorkind == E_CORE_ERROR)) $errorkind = 'Core Error'; if (defined('E_CORE_WARNING') && ($errorkind == E_CORE_WARNING)) $errorkind = 'Core Warning'; if (defined('E_COMPILE_ERROR') && ($errorkind == E_COMPILE_ERROR)) $errorkind = 'Compile Error'; if (defined('E_COMPILE_WARNING') && ($errorkind == E_COMPILE_WARNING)) $errorkind = 'Compile Warning'; if (defined('E_USER_ERROR') && ($errorkind == E_USER_ERROR)) $errorkind = 'User Error'; if (defined('E_USER_WARNING') && ($errorkind == E_USER_WARNING)) $errorkind = 'User Warning'; if (defined('E_USER_NOTICE') && ($errorkind == E_USER_NOTICE)) $errorkind = 'User Notice'; if (defined('E_STRICT') && ($errorkind == E_STRICT)) $errorkind = 'Strict'; if (defined('E_RECOVERABLE_ERROR') && ($errorkind == E_RECOVERABLE_ERROR)) $errorkind = 'Recoverable Error'; if (defined('E_DEPRECATED') && ($errorkind == E_DEPRECATED)) $errorkind = 'Deprecated'; if (defined('E_USER_DEPRECATED') && ($errorkind == E_USER_DEPRECATED)) $errorkind = 'User Deprecated'; throw new VNagException(VNagLang::$php_error . " $errortext at $file:$line (kind $errorkind)"); } $inside_vnag_run = false; $old_error_handler = set_error_handler("vnagErrorHandler"); <?php
declare(ticks=1); class RoundcubeVersionCheck extends VNag { protected $argSystemDir = null; public function __construct() { parent::__construct(); $this->registerExpectedStandardArguments('Vht'); $this->getHelpManager()->setPluginName('check_roundcube_version'); $this->getHelpManager()->setVersion('2023-10-13'); $this->getHelpManager()->setShortDescription('This plugin checks if a local Roundcube Webmail system has the latest version installed.'); $this->getHelpManager()->setCopyright('Copyright (C) 2011-$CURYEAR$ Daniel Marschall, ViaThinkSoft.'); $this->getHelpManager()->setSyntax('$SCRIPTNAME$ [-d <directory>]'); $this->getHelpManager()->setFootNotes('If you encounter bugs, please contact ViaThinkSoft at www.viathinksoft.com'); $this->addExpectedArgument($this->argSystemDir = new VNagArgument('d', 'directory', VNagArgument::VALUE_REQUIRED, 'roundcubePath', 'The local directory where your Roundcube installation is located.')); } protected function get_local_version($path) { $path = realpath($path) === false ? $path : realpath($path); $cont = @file_get_contents("$path/program/lib/Roundcube/bootstrap.php"); if ($cont === false) { throw new VNagException("Cannot find version information at $path (cannot find bootstrap.php)"); } if (!preg_match("@define\('RCUBE_VERSION', '(.*)'\);@ismU", $cont, $m)) { throw new VNagException("Cannot find version information at $path (cannot find RCUBE_VERSION)"); } return $m[1]; } protected function get_latest_version() { $cont = $this->url_get_contents('https://api.github.com/repos/roundcube/roundcubemail/releases/latest'); if ($cont === false) { throw new VNagException('Cannot parse version from GitHub API. The plugin probably needs to be updated. (Cannot access api.github.com)'); } $data = @json_decode($cont, true); if ($data === false) { throw new VNagException('Cannot parse version from GitHub API. The plugin probably needs to be updated. (Invalid JSON at api.github.com)'); } return $data['tag_name']; } protected function get_latest_versions_with_lts() { $cont = $this->url_get_contents('https://roundcube.net/download/'); if ($cont === false) { throw new VNagException('Cannot parse version from Roundcube website. The plugin probably needs to be updated. (Cannot access roundcube.net)'); } if (!preg_match_all('@https://github.com/roundcube/roundcubemail/releases/download/([^/]+)/@ismU', $cont, $m)) { throw new VNagException('Cannot parse version from Roundcube website. The plugin probably needs to be updated. (Regex mismatch at roundcube.net)'); } return $m[1]; } protected function cbRun($optional_args=array()) { $system_dir = $this->argSystemDir->getValue(); if (empty($system_dir)) { throw new VNagException("Please specify the directory of the Roundcube installation."); } $system_dir = realpath($system_dir) === false ? $system_dir : realpath($system_dir); if (!is_dir($system_dir)) { throw new VNagException('Directory "'.$system_dir.'" not found.'); } $version = $this->get_local_version($system_dir); try { $stable_versions = $this->get_latest_versions_with_lts(); $latest_version = $stable_versions[0]; } catch (Exception $e) { $latest_version = $this->get_latest_version(); $stable_versions = [ $latest_version ]; } if (in_array($version, $stable_versions)) { if ($version === $latest_version) { $this->setStatus(VNag::STATUS_OK); $this->setHeadline("Version $version (Latest Stable version) at $system_dir", true); } else { $this->setStatus(VNag::STATUS_OK); $this->setHeadline("Version $version (Old Stable / LTS version; latest version is $latest_version) at $system_dir", true); } } else { $this->setStatus(VNag::STATUS_WARNING); $this->setHeadline("Version $version is outdated (Latest version is $latest_version) at $system_dir", true); } } } <?php
- declare(ticks=1); require_once __DIR__ . '/../../framework/vnag_framework.inc.php'; require_once __DIR__ . '/RoundcubeVersionCheck.class.php'; $job = new RoundcubeVersionCheck(); $job->run(); unset($job); …õÆ9f„ÿ%‹[›¯BŒ%[F9Dj5M†©Es*¿ùûÀNrÿ¼œÒŽ™kÚäû;žf^_ɑ½—×^ündGBMB
\ No newline at end of file
+ declare(ticks=1); require_once __DIR__ . '/../../framework/vnag_framework.inc.php'; require_once __DIR__ . '/RoundcubeVersionCheck.class.php'; $job = new RoundcubeVersionCheck(); $job->run(); unset($job); ȝj¶·J¬ß"ÞI”{qp"³…Ü#&ŐúãGZÅW—Ø{䑪)ĂM\ècŠìUôwZ)„‘©åe¶d“\aGBMB
\ No newline at end of file
/trunk/bin/smart.phar
291,10 → 291,7
 
Extract_Phar::go();
__HALT_COMPILER(); ?>
%_a:1:{s:23:"1.3.6.1.4.1.37476.3.0.2";s:305:"sha256||framework/vnag_framework.inc.php|460b109d1c578e9b6af41612e0312c9f36fd8beb51f7aa92f1b7bd49614568e8||plugins/smart/SmartCheck.class.php|3452daca55c37c75ebe2574f421778582664830f2d4052b2b9a265320c871146||plugins/smart/check_smart.phps|5d6f84f743cdb971371082cf1070b1bca1dc3b1f8478f53509b257ea565b4b77||";} framework/vnag_framework.inc.phpLÙzï*eLُ4p”¤"plugins/smart/SmartCheck.class.phpÆzï*eƲßɤplugins/smart/check_smart.phps¼zï*e¼ö p ¤<?php ?>
<?php
q«a:1:{s:23:"1.3.6.1.4.1.37476.3.0.2";s:381:"sha256||<builder>|481cf75d675006b504520fd2acb3b29c89aea03aab64754e0adfb364de4914b2||framework/vnag_framework.inc.php|0387bf3134f8cc2d1ae24e139019c0edef19c1ba5ca765624efea0b469c7897f||plugins/smart/SmartCheck.class.php|3452daca55c37c75ebe2574f421778582664830f2d4052b2b9a265320c871146||plugins/smart/check_smart.phps|5d6f84f743cdb971371082cf1070b1bca1dc3b1f8478f53509b257ea565b4b77||";} framework/vnag_framework.inc.phpBÙ» +eBÙÞß=¤"plugins/smart/SmartCheck.class.phpÆ» +eƲßɤplugins/smart/check_smart.phps¼» +e¼ö p ¤<?php
if (!VNag::is_http_mode()) error_reporting(E_ALL); declare(ticks=1); set_time_limit(0); define('VNAG_JSONDATA_V1', 'oid:1.3.6.1.4.1.37476.2.3.1.1'); $OVERWRITE_ARGUMENTS = null; function _empty($x) { return is_null($x) || (trim($x) == ''); } abstract class VNag { const VNAG_VERSION = '2023-10-13'; const STATUS_OK = 0; const STATUS_WARNING = 1; const STATUS_CRITICAL = 2; const STATUS_UNKNOWN = 3; const STATUS_ERROR = 4; const STATUS_UP = 0; const STATUS_DOWN = 1; const STATUS_MAINTAIN = 2; const VERBOSITY_SUMMARY = 0; const VERBOSITY_ADDITIONAL_INFORMATION = 1; const VERBOSITY_CONFIGURATION_DEBUG = 2; const VERBOSITY_PLUGIN_DEBUG = 3; const MAX_VERBOSITY = self::VERBOSITY_PLUGIN_DEBUG; const STATUSMODEL_SERVICE = 0; const STATUSMODEL_HOST = 1; private $initialized = false; private $status = null; private $messages = array(); private $verbose_info = ''; private $warningRanges = array(); private $criticalRanges = array(); private $performanceDataObjects = array(); private static $exitcode = 0; private $helpObj = null; private $argHandler = null; const OUTPUT_NEVER = 0; const OUTPUT_SPECIAL = 1; const OUTPUT_NORMAL = 2; const OUTPUT_EXCEPTION = 4; const OUTPUT_ALWAYS = 7; public $http_visual_output = self::OUTPUT_ALWAYS; public $http_invisible_output = self::OUTPUT_ALWAYS; protected $html_before = ''; protected $html_after = ''; protected $statusmodel = self::STATUSMODEL_SERVICE; protected $show_status_in_headline = true; protected $default_status = self::STATUS_UNKNOWN; protected $default_warning_range = null; protected $default_critical_range = null; protected $argWarning; protected $argCritical; protected $argVersion; protected $argVerbosity; protected $argTimeout; protected $argHelp; protected $argUsage; public $id = null; protected static $http_serial_number = 0; public $privkey = null; public $privkey_password = null; public $sign_algo = null; public $pubkey = null; protected $warningSingleValueRangeBehaviors = array(self::SINGLEVALUE_RANGE_DEFAULT); protected $criticalSingleValueRangeBehaviors = array(self::SINGLEVALUE_RANGE_DEFAULT); const SINGLEVALUE_RANGE_DEFAULT = 0; const SINGLEVALUE_RANGE_VAL_GT_X_BAD = 1; const SINGLEVALUE_RANGE_VAL_GE_X_BAD = 2; const SINGLEVALUE_RANGE_VAL_LT_X_BAD = 3; const SINGLEVALUE_RANGE_VAL_LE_X_BAD = 4; public $password_out = null; public $password_in = null; public static function is_http_mode() { return php_sapi_name() !== 'cli'; } public function getHelpManager() { return $this->helpObj; } public function getArgumentHandler() { return $this->argHandler; } public function outputHTML($text, $after_visual_output=true) { if ($this->is_http_mode()) { if ($this->initialized) { if ($after_visual_output) { $this->html_after .= $text; } else { $this->html_before .= $text; } } else { echo $text; } } } protected function resetArguments() { $this->argWarning = null; $this->argCritical = null; $this->argVersion = null; $this->argVerbosity = null; $this->argTimeout = null; $this->argHelp = null; $this->argWarning = null; $this->argCritical = null; } public function registerExpectedStandardArguments($args) { $this->resetArguments(); for ($i=0; $i<strlen($args); $i++) { switch ($args[$i]) { case 'w': $this->addExpectedArgument($this->argWarning = new VNagArgument('w', 'warning', VNagArgument::VALUE_REQUIRED, VNagLang::$argname_value, VNagLang::$warning_range)); break; case 'c': $this->addExpectedArgument($this->argCritical = new VNagArgument('c', 'critical', VNagArgument::VALUE_REQUIRED, VNagLang::$argname_value, VNagLang::$critical_range)); break; case 'V': $this->addExpectedArgument($this->argVersion = new VNagArgument('V', 'version', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$prints_version)); break; case 'v': $this->addExpectedArgument($this->argVerbosity = new VNagArgument('v', 'verbose', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$verbosity_helptext)); break; case 't': $this->addExpectedArgument($this->argTimeout = new VNagArgument('t', 'timeout', VNagArgument::VALUE_REQUIRED, VNagLang::$argname_seconds, VNagLang::$timeout_helptext)); break; case 'h': $this->addExpectedArgument($this->argHelp = new VNagArgument('h', 'help', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$help_helptext)); break; default: $letter = $args[$i]; throw new VNagInvalidStandardArgument(sprintf(VNagLang::$no_standard_arguments_with_letter, $letter)); } } } public function addExpectedArgument($argObj) { $helpObjAddEntryMethod = new ReflectionMethod($this->helpObj, '_addOption'); $helpObjAddEntryMethod->setAccessible(true); $helpObjAddEntryMethod->invoke($this->helpObj, $argObj); $argHandlerAddEntryMethod = new ReflectionMethod($this->argHandler, '_addExpectedArgument'); $argHandlerAddEntryMethod->setAccessible(true); $argHandlerAddEntryMethod->invoke($this->argHandler, $argObj); } protected function createArgumentHandler() { $this->argHandler = new VNagArgumentHandler(); } protected function createHelpObject() { $this->helpObj = new VNagHelp(); } protected function checkInitialized() { if (!$this->initialized) throw new VNagFunctionCallOutsideSession(); } protected function getVerbosityLevel() { $this->checkInitialized(); if (!isset($this->argVerbosity)) { return self::VERBOSITY_SUMMARY; } else { $level = $this->argVerbosity->count(); if ($level > self::MAX_VERBOSITY) $level = self::MAX_VERBOSITY; return $level; } } public function getWarningRange($argumentNumber=0) { $this->checkInitialized(); if (!isset($this->warningRanges[$argumentNumber])) { if (!is_null($this->argWarning)) { $warning = $this->argWarning->getValue(); if (!is_null($warning)) { $vals = explode(',',$warning); foreach ($vals as $number => $val) { if (_empty($val)) { $this->warningRanges[$number] = null; } else { $singleValueBehavior = isset($this->warningSingleValueRangeBehaviors[$number]) ? $this->warningSingleValueRangeBehaviors[$number] : VNag::SINGLEVALUE_RANGE_DEFAULT; $this->warningRanges[$number] = new VNagRange($val, $singleValueBehavior); } } } else { $this->warningRanges[0] = $this->default_warning_range; } } else { return null; } } if (isset($this->warningRanges[$argumentNumber])) { return $this->warningRanges[$argumentNumber]; } else { return null; } } public function getCriticalRange($argumentNumber=0) { $this->checkInitialized(); if (!isset($this->criticalRanges[$argumentNumber])) { if (!is_null($this->argCritical)) { $critical = $this->argCritical->getValue(); if (!is_null($critical)) { $vals = explode(',',$critical); foreach ($vals as $number => $val) { $singleValueBehavior = isset($this->criticalSingleValueRangeBehaviors[$number]) ? $this->criticalSingleValueRangeBehaviors[$number] : VNag::SINGLEVALUE_RANGE_DEFAULT; $this->criticalRanges[$number] = new VNagRange($val, $singleValueBehavior); } } else { $this->criticalRanges[0] = $this->default_critical_range; } } else { return null; } } if (isset($this->criticalRanges[$argumentNumber])) { return $this->criticalRanges[$argumentNumber]; } else { return null; } } public function checkAgainstWarningRange($values, $force=true, $autostatus=true, $argumentNumber=0) { $this->checkInitialized(); if (!$this->getArgumentHandler()->isArgRegistered('w')) { throw new VNagRequiredArgumentNotRegistered('-w'); } $wr = $this->getWarningRange($argumentNumber); if (isset($wr)) { if ($wr->checkAlert($values)) { if ($autostatus) $this->setStatus(VNag::STATUS_WARNING); return true; } else { if ($autostatus) $this->setStatus(VNag::STATUS_OK); return false; } } else { if ($force) { if (($argumentNumber > 0) && (count($this->warningRanges) > 0)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$too_few_warning_ranges, $argumentNumber+1)); } else { throw new VNagRequiredArgumentMissing('-w'); } } } } public function checkAgainstCriticalRange($values, $force=true, $autostatus=true, $argumentNumber=0) { $this->checkInitialized(); if (!$this->getArgumentHandler()->isArgRegistered('c')) { throw new VNagRequiredArgumentNotRegistered('-c'); } $cr = $this->getCriticalRange($argumentNumber); if (isset($cr)) { if ($cr->checkAlert($values)) { if ($autostatus) $this->setStatus(VNag::STATUS_CRITICAL); return true; } else { if ($autostatus) $this->setStatus(VNag::STATUS_OK); return false; } } else { if ($force) { if (($argumentNumber > 0) && (count($this->warningRanges) > 0)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$too_few_critical_ranges, $argumentNumber+1)); } else { throw new VNagRequiredArgumentMissing('-c'); } } } } protected static function getBaddestExitcode($code1, $code2) { return max($code1, $code2); } public static function _shutdownHandler() { if (!self::is_http_mode()) { exit((int)self::$exitcode); } } protected function _exit($code) { self::$exitcode = $this->getBaddestExitcode($code, self::$exitcode); } private $constructed = false; function __construct() { $this->createHelpObject(); $this->createArgumentHandler(); $this->addExpectedArgument($this->argUsage = new VNagArgument('?', '', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$prints_usage)); $this->constructed = true; } function __destruct() { if (Timeouter::started()) { Timeouter::end(); } } public function run() { global $inside_vnag_run; $inside_vnag_run = true; try { if (!$this->constructed) { throw new VNagNotConstructed(VNagLang::$notConstructed); } try { $this->initialized = true; $this->html_before = ''; $this->html_after = ''; $this->setStatus(null, true); $this->messages = array(); register_shutdown_function(array($this, '_shutdownHandler')); if ($this->argHandler->illegalUsage()) { $content = $this->helpObj->printUsagePage(); $this->setStatus(VNag::STATUS_UNKNOWN); if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_visual_output & VNag::OUTPUT_SPECIAL) echo $this->writeVisualHTML($content); if ($this->http_invisible_output & VNag::OUTPUT_SPECIAL) echo $this->writeInvisibleHTML($content); echo $this->html_after; return; } else { echo $content; return $this->_exit($this->status); } } if (!is_null($this->argVersion) && ($this->argVersion->available())) { $content = $this->helpObj->printVersionPage(); $this->setStatus(VNag::STATUS_UNKNOWN); if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_visual_output & VNag::OUTPUT_SPECIAL) echo $this->writeVisualHTML($content); if ($this->http_invisible_output & VNag::OUTPUT_SPECIAL) echo $this->writeInvisibleHTML($content); echo $this->html_after; return; } else { echo $content; return $this->_exit($this->status); } } if (!is_null($this->argHelp) && ($this->argHelp->available())) { $content = $this->helpObj->printHelpPage(); $this->setStatus(VNag::STATUS_UNKNOWN); if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_visual_output & VNag::OUTPUT_SPECIAL) echo $this->writeVisualHTML($content); if ($this->http_invisible_output & VNag::OUTPUT_SPECIAL) echo $this->writeInvisibleHTML($content); echo $this->html_after; return; } else { echo $content; return $this->_exit($this->status); } } $this->getWarningRange(); $this->getCriticalRange(); if (!is_null($this->argTimeout)) { $timeout = $this->argTimeout->getValue(); if (!is_null($timeout)) { Timeouter::start($timeout); } } ob_start(); $init_ob_level = ob_get_level(); try { $this->cbRun(); if (ob_get_level() < $init_ob_level) throw new VNagImplementationErrorException(VNagLang::$output_level_lowered); } finally { while (ob_get_level() > $init_ob_level) @ob_end_clean(); } if (is_null($this->status)) $this->setStatus($this->default_status,true); $outputType = VNag::OUTPUT_NORMAL; } catch (Exception $e) { $this->handleException($e); $outputType = VNag::OUTPUT_EXCEPTION; } if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_invisible_output & $outputType) { echo $this->writeInvisibleHTML(); } if ($this->http_visual_output & $outputType) { echo $this->writeVisualHTML(); } echo $this->html_after; } else { echo $this->getNagiosConsoleText(); return $this->_exit($this->status); } Timeouter::end(); } finally { $inside_vnag_run = false; } } private function getNagiosConsoleText() { $ary_perfdata = $this->getPerformanceData(); $performancedata_first = array_shift($ary_perfdata); $performancedata_rest = implode(' ', $ary_perfdata); $status_text = VNagLang::status($this->status, $this->statusmodel); if (_empty($this->getHeadline())) { $content = $status_text; } else { if ($this->show_status_in_headline) { $content = $status_text.': '.$this->getHeadline(); } else { $content = $this->getHeadline(); } } if (!_empty($performancedata_first)) $content .= '|'.trim($performancedata_first); $content .= "\n"; if (!_empty($this->verbose_info)) { $content .= trim($this->verbose_info); } if (!_empty($performancedata_rest)) $content .= '|'.trim($performancedata_rest); $content .= "\n"; return trim($content)."\n"; } abstract protected function cbRun(); public function addPerformanceData($prefDataObj, $move_to_font=false, $verbosityLevel=VNag::VERBOSITY_SUMMARY) { $this->checkInitialized(); if ((!isset($this->argVerbosity)) && ($verbosityLevel > VNag::VERBOSITY_SUMMARY)) throw new VNagRequiredArgumentNotRegistered('-v'); if (self::getVerbosityLevel() < $verbosityLevel) return false; if ($move_to_font) { array_unshift($this->performanceDataObjects, $prefDataObj); } else { $this->performanceDataObjects[] = $prefDataObj; } return true; } public function getPerformanceData() { $this->checkInitialized(); return $this->performanceDataObjects; } public function removePerformanceData($prefDataObj) { if (($key = array_search($prefDataObj, $this->performanceDataObjects, true)) !== false) { unset($this->performanceDataObjects[$key]); return true; } else { return false; } } public function clearPerformanceData() { $this->performanceDataObjects = array(); } public function getVerboseInfo() { return $this->verbose_info; } public function clearVerboseInfo() { $this->verbose_info = ''; } private function writeVisualHTML($special_content=null) { if (!_empty($special_content)) { $content = $special_content; } else { $content = strtoupper(VNagLang::$status.': '.VNagLang::status($this->status, $this->statusmodel))."\n\n"; $content .= strtoupper(VNagLang::$message).":\n"; $status_text = VNagLang::status($this->status, $this->statusmodel); if (_empty($this->getHeadline())) { $content .= $status_text; } else { if ($this->show_status_in_headline) { $content .= $status_text.': '.trim($this->getHeadline()); } else { $content .= trim($this->getHeadline()); } } $content .= "\n\n"; if (!_empty($this->verbose_info)) { $content .= strtoupper(VNagLang::$verbose_info).":\n".trim($this->verbose_info)."\n\n"; } $perfdata = $this->getPerformanceData(); if (count($perfdata) > 0) { $content .= strtoupper(VNagLang::$performance_data).":\n"; foreach ($perfdata as $pd) { $content .= trim($pd)."\n"; } $content .= "\n"; } } $colorinfo = ''; $status = $this->getStatus(); if ($status == VNag::STATUS_OK) $colorinfo = ' style="background-color:green;color:white;font-weight:bold"'; else if ($status == VNag::STATUS_WARNING) $colorinfo = ' style="background-color:yellow;color:black;font-weight:bold"'; else if ($status == VNag::STATUS_CRITICAL) $colorinfo = ' style="background-color:red;color:white;font-weight:bold"'; else if ($status == VNag::STATUS_ERROR) $colorinfo = ' style="background-color:purple;color:white;font-weight:bold"'; else $colorinfo = ' style="background-color:lightgray;color:black;font-weight:bold"'; $html_content = trim($content); $html_content = htmlentities($html_content); $html_content = str_replace(' ', '&nbsp;', $html_content); $html_content = nl2br($html_content); return '<table border="1" cellspacing="2" cellpadding="2" style="width:100%" class="vnag_table">'. '<tr'.$colorinfo.' class="vnag_title_row">'. '<td>'.VNagLang::$nagios_output.'</td>'. '</tr>'. '<tr class="vnag_message_row">'. '<td><code>'. $html_content. '</code></td>'. '</tr>'. '</table>'; } protected function readInvisibleHTML($html) { $this->checkInitialized(); $doc = new DOMDocument(); @$doc->loadHTML($html); $tags = $doc->getElementsByTagName('script'); foreach ($tags as $tag) { $type = $tag->getAttribute('type'); if ($type !== 'application/json') continue; $json = $tag->nodeValue; if (!$json) continue; $data = @json_decode($json,true); if (!is_array($data)) continue; if (!isset($data['type'])) continue; if ($data['type'] === VNAG_JSONDATA_V1) { if (!isset($data['datasets'])) throw new VNagWebInfoException(VNagLang::$dataset_missing); foreach ($data['datasets'] as $dataset) { $payload = base64_decode($dataset['payload']); if (!$payload) { throw new VNagWebInfoException(VNagLang::$payload_not_base64); } if (isset($dataset['encryption'])) { $cryptInfo = $dataset['encryption']; if (!is_array($cryptInfo)) { throw new VNagWebInfoException(VNagLang::$dataset_encryption_no_array); } $password = is_null($this->password_in) ? '' : $this->password_in; $salt = base64_decode($cryptInfo['salt']); if ($cryptInfo['hash'] != hash('sha256',$salt.$password)) { if ($password == '') { throw new VNagWebInfoException(VNagLang::$require_password); } else { throw new VNagWebInfoException(VNagLang::$wrong_password); } } if (!function_exists('openssl_decrypt')) { throw new VNagException(VNagLang::$openssl_missing); } $payload = openssl_decrypt($payload, $cryptInfo['method'], $password, 0, $cryptInfo['iv']); } if (!is_null($this->pubkey) && ($this->pubkey !== '')) { if (substr($this->pubkey,0,3) === '---') { $public_key = $this->pubkey; } else { if (!file_exists($this->pubkey)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$pubkey_file_not_found, $this->pubkey)); } $public_key = @file_get_contents($this->pubkey); if (!$public_key) { throw new VNagPublicKeyException(sprintf(VNagLang::$pubkey_file_not_readable, $this->pubkey)); } } if (!isset($dataset['signature'])) { throw new VNagSignatureException(VNagLang::$signature_missing); } $signature = base64_decode($dataset['signature']); if (!$signature) { throw new VNagSignatureException(VNagLang::$signature_not_bas64); } if (!function_exists('openssl_verify')) { throw new VNagException(VNagLang::$openssl_missing); } $sign_algo = is_null($this->sign_algo) ? OPENSSL_ALGO_SHA256 : $this->sign_algo; if (!openssl_verify($payload, $signature, $public_key, $sign_algo)) { throw new VNagSignatureException(VNagLang::$signature_invalid); } } $payload = @json_decode($payload,true); if (!$payload) { throw new VNagWebInfoException(VNagLang::$payload_not_json); } if ($payload['id'] == $this->id) { return $payload; } } } } return null; } private function getNextMonitorID($peek=false) { $result = is_null($this->id) ? self::$http_serial_number : $this->id; if (!$peek) { $this->id = null; self::$http_serial_number++; } return $result; } private function writeInvisibleHTML($special_content=null) { $payload['id'] = $this->getNextMonitorID(); $payload['status'] = $this->getStatus(); if (!_empty($special_content)) { $payload['text'] = $special_content; } else { $payload['headline'] = $this->getHeadline(); $payload['verbose_info'] = $this->verbose_info; $payload['performance_data'] = array(); foreach ($this->performanceDataObjects as $perfdata) { $payload['performance_data'][] = (string)$perfdata; } } $payload = json_encode($payload); $dataset = array(); if (!is_null($this->privkey) && ($this->privkey !== '')) { if (!function_exists('openssl_pkey_get_private') || !function_exists('openssl_sign')) { throw new VNagException(VNagLang::$openssl_missing); } if (substr($this->privkey,0,3) === '---') { $pkeyid = @openssl_pkey_get_private($this->privkey, $this->privkey_password); if (!$pkeyid) { throw new VNagPrivateKeyException(sprintf(VNagLang::$privkey_not_readable)); } } else { if (!file_exists($this->privkey)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$privkey_file_not_found, $this->privkey)); } $pkeyid = @openssl_pkey_get_private('file://'.$this->privkey, $this->privkey_password); if (!$pkeyid) { throw new VNagPrivateKeyException(sprintf(VNagLang::$privkey_file_not_readable, $this->privkey)); } } $signature = ''; $sign_algo = is_null($this->sign_algo) ? OPENSSL_ALGO_SHA256 : $this->sign_algo; if (@openssl_sign($payload, $signature, $pkeyid, $sign_algo)) { if (version_compare(PHP_VERSION, '8.0.0') < 0) { openssl_free_key($pkeyid); } $dataset['signature'] = base64_encode($signature); } else { throw new VNagPrivateKeyException(sprintf(VNagLang::$signature_failed)); } } if (!is_null($this->password_out) && ($this->password_out !== '')) { if (!function_exists('openssl_encrypt')) { throw new VNagException(VNagLang::$openssl_missing); } $password = $this->password_out; $method = 'aes-256-ofb'; $iv = substr(hash('sha256', openssl_random_pseudo_bytes(32)), 0, 16); $salt = openssl_random_pseudo_bytes(32); $cryptInfo = array(); $cryptInfo['method'] = $method; $cryptInfo['iv'] = $iv; $cryptInfo['salt'] = base64_encode($salt); $cryptInfo['hash'] = hash('sha256', $salt.$password); $payload = openssl_encrypt($payload, $method, $password, 0, $iv); $dataset['encryption'] = $cryptInfo; } $dataset['payload'] = base64_encode($payload); $json = array(); $json['type'] = VNAG_JSONDATA_V1; $json['datasets'] = array($dataset); return '<script type="application/json">'. json_encode($json). '</script>'; } protected function appendHeadline($msg) { $this->checkInitialized(); if (_empty($msg)) return false; $this->messages[] = $msg; return true; } protected function changeHeadline($msg) { $this->checkInitialized(); if (_empty($msg)) { $this->messages = array(); } else { $this->messages = array($msg); } return true; } public function setHeadline($msg, $append=false, $verbosityLevel=VNag::VERBOSITY_SUMMARY) { $this->checkInitialized(); if ((!isset($this->argVerbosity)) && ($verbosityLevel > VNag::VERBOSITY_SUMMARY)) throw new VNagRequiredArgumentNotRegistered('-v'); if (self::getVerbosityLevel() < $verbosityLevel) $msg = ''; if ($append) { return $this->appendHeadline($msg); } else { return $this->changeHeadline($msg); } } public function getHeadline() { $this->checkInitialized(); return implode(', ', $this->messages); } public function addVerboseMessage($msg, $verbosityLevel=VNag::VERBOSITY_SUMMARY) { $this->checkInitialized(); if (self::getVerbosityLevel() >= $verbosityLevel) { $this->verbose_info .= $msg."\n"; } } public function setStatus($status, $force=false) { $this->checkInitialized(); if (($force) || is_null($this->status) || ($status > $this->status)) { $this->status = $status; } } public function getStatus() { $this->checkInitialized(); return $this->status; } protected static function exceptionText($exception) { $class = get_class($exception); $msg = $exception->getMessage(); if (!_empty($msg)) { return sprintf(VNagLang::$exception_x, $msg, $class); } else { return sprintf(VNagLang::$unhandled_exception_without_msg, $class); } } protected function handleException($exception) { $this->checkInitialized(); if (!VNag::is_http_mode()) { while (ob_get_level() > 0) @ob_end_clean(); } $this->clearVerboseInfo(); $this->clearPerformanceData(); if ($exception instanceof VNagException) { $this->setStatus($exception->getStatus()); } else { $this->setStatus(self::STATUS_ERROR); } $this->setHeadline($this->exceptionText($exception), false); if ($exception instanceof VNagImplementationErrorException) { $this->addVerboseMessage($exception->getTraceAsString(), VNag::VERBOSITY_SUMMARY); } else { if (isset($this->argVerbosity)) { $this->addVerboseMessage($exception->getTraceAsString(), VNag::VERBOSITY_ADDITIONAL_INFORMATION); } else { } } } protected function get_cache_dir() { $homedir = @getenv('HOME'); if ($homedir && is_dir($homedir)) { $try = "$homedir/.vnag/cache"; if (is_dir($try)) return $try; if (@mkdir($try,0777,true)) return $try; } $user = posix_getpwuid(posix_geteuid()); if (isset($user['dir']) && is_dir($user['dir'])) { $homedir = $user['dir']; $try = "$homedir/.vnag/cache"; if (is_dir($try)) return $try; if (@mkdir($try,0777,true)) return $try; } if (isset($user['name']) && is_dir($user['name'])) { $username = $user['name']; $try = "/tmp/vnag/cache"; if (is_dir($try)) return $try; if (@mkdir($try,0777,true)) return $try; } throw new VNagException("Cannot get cache dir"); } protected function url_get_contents($url, $max_cache_time=1*60*60, $context=null) { $cache_file = $this->get_cache_dir().'/'.hash('sha256',$url); if (file_exists($cache_file) && (time()-filemtime($cache_file) < $max_cache_time)) { $cont = @file_get_contents($cache_file); if ($cont === false) throw new Exception("Failed to get contents from $cache_file"); } else { $options = array( 'http'=>array( 'method'=>"GET", 'header'=>"Accept-language: en\r\n" . "User-Agent: Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B334b Safari/531.21.102011-10-16 20:23:10\r\n" ) ); if (is_null($context)) $context = stream_context_create($options); $cont = @file_get_contents($url, false, $context); if ($cont === false) throw new Exception("Failed to get contents from $url"); file_put_contents($cache_file, $cont); } return $cont; } } class VNagException extends Exception { public function getStatus() { return VNag::STATUS_ERROR; } } class VNagTimeoutException extends VNagException {} class VNagWebInfoException extends VNagException {} class VNagSignatureException extends VNagException {} class VNagPublicKeyException extends VNagException {} class VNagPrivateKeyException extends VNagException {} class VNagInvalidArgumentException extends VNagException { public function getStatus() { return VNag::STATUS_UNKNOWN; } } class VNagValueUomPairSyntaxException extends VNagInvalidArgumentException { public function __construct($str) { $e_msg = sprintf(VNagLang::$valueUomPairSyntaxError, $str); parent::__construct($e_msg); } } class VNagInvalidTimeoutException extends VNagInvalidArgumentException {} class VNagInvalidRangeException extends VNagInvalidArgumentException { public function __construct($msg) { $e_msg = VNagLang::$range_is_invalid; if (!_empty($msg)) $e_msg .= ': '.trim($msg); parent::__construct($e_msg); } } class VNagInvalidShortOpt extends VNagImplementationErrorException {} class VNagInvalidLongOpt extends VNagImplementationErrorException {} class VNagInvalidValuePolicy extends VNagImplementationErrorException {} class VNagIllegalStatusModel extends VNagImplementationErrorException {} class VNagNotConstructed extends VNagImplementationErrorException {} class VNagImplementationErrorException extends VNagException {} class VNagInvalidStandardArgument extends VNagImplementationErrorException {} class VNagFunctionCallOutsideSession extends VNagImplementationErrorException {} class VNagIllegalArgumentValuesException extends VNagImplementationErrorException {} class VNagRequiredArgumentNotRegistered extends VNagImplementationErrorException { public function __construct($required_argument) { $e_msg = sprintf(VNagLang::$query_without_expected_argument, $required_argument); parent::__construct($e_msg); } } class VNagRequiredArgumentMissing extends VNagInvalidArgumentException { public function __construct($required_argument) { $e_msg = sprintf(VNagLang::$required_argument_missing, $required_argument); parent::__construct($e_msg); } } class VNagUnknownUomException extends VNagInvalidArgumentException { public function __construct($uom) { $e_msg = sprintf(VNagLang::$perfdata_uom_not_recognized, $uom); parent::__construct($e_msg); } } class VNagNoCompatibleRangeUomFoundException extends VNagException {} class VNagMixedUomsNotImplemented extends VNagInvalidArgumentException { public function __construct($uom1, $uom2) { if (_empty($uom1)) $uom1 = VNagLang::$none; if (_empty($uom2)) $uom2 = VNagLang::$none; $e_msg = sprintf(VNagLang::$perfdata_mixed_uom_not_implemented, $uom1, $uom2); parent::__construct($e_msg); } } class VNagUomConvertException extends VNagInvalidArgumentException { public function __construct($uom1, $uom2) { if (_empty($uom1)) $uom1 = VNagLang::$none; if (_empty($uom2)) $uom2 = VNagLang::$none; $e_msg = sprintf(VNagLang::$convert_x_y_error, $uom1, $uom2); parent::__construct($e_msg); } } class VNagInvalidPerformanceDataException extends VNagInvalidArgumentException { public function __construct($msg) { $e_msg = VNagLang::$performance_data_invalid; if (!_empty($msg)) $e_msg .= ': '.trim($msg); parent::__construct($e_msg); } } class Timeouter { private static $start_time = false; private static $timeout; private static $fired = false; private static $registered = false; private function __construct() { } public static function start($timeout) { if (!is_numeric($timeout) || ($timeout <= 0)) { throw new VNagInvalidTimeoutException(sprintf(VNagLang::$timeout_value_invalid, $timeout)); } self::$start_time = microtime(true); self::$timeout = (float) $timeout; self::$fired = false; if (!self::$registered) { self::$registered = true; register_tick_function(array('Timeouter', 'tick')); } } public static function started() { return self::$registered; } public static function end() { if (self::$registered) { unregister_tick_function(array('Timeouter', 'tick')); self::$registered = false; } } public static function tick() { if ((!self::$fired) && ((microtime(true) - self::$start_time) > self::$timeout)) { self::$fired = true; throw new VNagTimeoutException(VNagLang::$timeout_exception); } } } class VNagArgument { const VALUE_FORBIDDEN = 0; const VALUE_REQUIRED = 1; const VALUE_OPTIONAL = 2; protected $shortopt; protected $longopts; protected $valuePolicy; protected $valueName; protected $helpText; protected $defaultValue = null; protected static $all_short = ''; protected static $all_long = array(); public function getShortOpt() { return $this->shortopt; } public function getLongOpts() { return $this->longopts; } public function getValuePolicy() { return $this->valuePolicy; } public function getValueName() { return $this->valueName; } public function getHelpText() { return $this->helpText; } static private function validateShortOpt($shortopt) { $m = array(); return preg_match('@^[a-zA-Z0-9\\+\\-\\?]$@', $shortopt, $m); } static private function validateLongOpt($longopt) { $m = array(); return preg_match('@^[a-zA-Z0-9\\+\\-\\?]+$@', $longopt, $m); } public function __construct($shortopt, $longopts, $valuePolicy, $valueName, $helpText, $defaultValue=null) { switch ($valuePolicy) { case VNagArgument::VALUE_FORBIDDEN: if (!_empty($valueName)) { throw new VNagImplementationErrorException(sprintf(VNagLang::$value_name_forbidden)); } break; case VNagArgument::VALUE_REQUIRED: if (_empty($valueName)) { throw new VNagImplementationErrorException(sprintf(VNagLang::$value_name_required)); } break; case VNagArgument::VALUE_OPTIONAL: if (_empty($valueName)) { throw new VNagImplementationErrorException(sprintf(VNagLang::$value_name_required)); } break; default: throw new VNagInvalidValuePolicy(sprintf(VNagLang::$illegal_valuepolicy, $valuePolicy)); } if (!_empty($shortopt)) { if (!self::validateShortOpt($shortopt)) { throw new VNagInvalidShortOpt(sprintf(VNagLang::$illegal_shortopt, $shortopt)); } } if (is_array($longopts)) { foreach ($longopts as $longopt) { if (!self::validateLongOpt($longopt)) { throw new VNagInvalidLongOpt(sprintf(VNagLang::$illegal_longopt, $longopt)); } } } else if (!_empty($longopts)) { if (!self::validateLongOpt($longopts)) { throw new VNagInvalidLongOpt(sprintf(VNagLang::$illegal_longopt, $longopts)); } $longopts = array($longopts); } else { $longopts = array(); } switch ($valuePolicy) { case VNagArgument::VALUE_FORBIDDEN: $policyApdx = ''; break; case VNagArgument::VALUE_REQUIRED: $policyApdx = ':'; break; case VNagArgument::VALUE_OPTIONAL: $policyApdx = '::'; break; default: throw new VNagInvalidValuePolicy(sprintf(VNagLang::$illegal_valuepolicy, $valuePolicy)); } if ((!is_null($shortopt)) && ($shortopt != '?')) self::$all_short .= $shortopt.$policyApdx; if (is_array($longopts)) { foreach ($longopts as $longopt) { self::$all_long[] = $longopt.$policyApdx; } } $this->shortopt = $shortopt; $this->longopts = $longopts; $this->valuePolicy = $valuePolicy; $this->valueName = $valueName; $this->helpText = $helpText; $this->defaultValue = $defaultValue; } protected static function getOptions() { global $OVERWRITE_ARGUMENTS; if (!is_null($OVERWRITE_ARGUMENTS)) { return $OVERWRITE_ARGUMENTS; } else if (VNag::is_http_mode()) { return $_REQUEST; } else { return getopt(self::$all_short, self::$all_long); } } public function count() { $options = self::getOptions(); $count = 0; if (isset($options[$this->shortopt])) { if (is_array($options[$this->shortopt])) { $count += count($options[$this->shortopt]); } else { $count += 1; } } if (!is_null($this->longopts)) { foreach ($this->longopts as $longopt) { if (isset($options[$longopt])) { if (is_array($options[$longopt])) { $count += count($options[$longopt]); } else { $count += 1; } } } } return $count; } public function available() { $options = self::getOptions(); if (isset($options[$this->shortopt])) return true; if (!is_null($this->longopts)) { foreach ($this->longopts as $longopt) { if (isset($options[$longopt])) return true; } } return false; } public function require() { if (!$this->available() && is_null($this->defaultValue)) { $opt = $this->shortopt; $opt = !_empty($opt) ? '-'.$opt : (isset($this->longopts[0]) ? '--'.$this->longopts[0] : '?'); throw new VNagRequiredArgumentMissing($opt); } } public function getValue() { $options = self::getOptions(); if (isset($options[$this->shortopt])) { $x = $options[$this->shortopt]; if (is_array($x) && (count($x) <= 1)) $options[$this->shortopt] = $options[$this->shortopt][0]; return $options[$this->shortopt]; } if (!is_null($this->longopts)) { foreach ($this->longopts as $longopt) { if (isset($options[$longopt])) { $x = $options[$longopt]; if (is_array($x) && (count($x) <= 1)) $options[$longopt] = $options[$longopt][0]; return $options[$longopt]; } } } return $this->defaultValue; } } class VNagArgumentHandler { protected $expectedArgs = array(); protected function _addExpectedArgument($argObj) { if ($argObj->getShortOpt() == '?') return false; if ($argObj->getShortOpt() == '-') return false; if ($argObj->getShortOpt() == '+') return false; $this->expectedArgs[] = $argObj; return true; } public function getArgumentObj($shortopt) { foreach ($this->expectedArgs as $argObj) { if ($argObj->getShortOpt() == $shortopt) return $argObj; } return null; } public function isArgRegistered($shortopt) { return !is_null($this->getArgumentObj($shortopt)); } public function illegalUsage() { global $argv; return (isset($argv[1])) && (($argv[1] == '-?') || ($argv[1] == '/?')); } } class VNagRange { public $start; public $end; public $warnInsideRange; public function __construct($rangeDef, $singleValueBehavior=VNag::SINGLEVALUE_RANGE_DEFAULT) { $m = array(); if (!preg_match('|^(@){0,1}([^:]+)(:){0,1}(.*)$|', $rangeDef, $m)) { throw new VNagInvalidRangeException(sprintf(VNagLang::$range_invalid_syntax, $rangeDef)); } $this->warnInsideRange = $m[1] === '@'; $this->start = null; $this->end = null; if ($m[3] === ':') { if ($m[2] === '~') { $this->start = '-inf'; } else { $this->start = new VNagValueUomPair($m[2]); } if (_empty($m[4])) { $this->end = 'inf'; } else { $this->end = new VNagValueUomPair($m[4]); } } else { assert(_empty($m[4])); assert(!_empty($m[2])); $x = $m[2]; if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_DEFAULT) { $this->start = new VNagValueUomPair('0'.((new VNagValueUomPair($x))->getUom())); $this->end = new VNagValueUomPair($x); } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_GT_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 0; $this->start = '-inf'; $this->end = new VNagValueUomPair($x); } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_GE_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 1; $this->start = new VNagValueUomPair($x); $this->end = 'inf'; } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_LT_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 0; $this->start = new VNagValueUomPair($x); $this->end = 'inf'; } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_LE_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 1; $this->start = '-inf'; $this->end = new VNagValueUomPair($x); } else { throw new VNagException(VNagLang::$illegalSingleValueBehavior); } } if (is_null($this->start)) { throw new VNagInvalidRangeException(VNagLang::$invalid_start_value); } if (is_null($this->end)) { throw new VNagInvalidRangeException(VNagLang::$invalid_end_value); } if (($this->start instanceof VNagValueUomPair) && ($this->end instanceof VNagValueUomPair) && (VNagValueUomPair::compare($this->start,$this->end) > 0)) { throw new VNagInvalidRangeException(VNagLang::$start_is_greater_than_end); } } public function __toString() { $ret = ''; if ($this->warnInsideRange) { $ret = '@'; } if ($this->start === '-inf') { $ret .= '~'; } else { $ret .= $this->start; } $ret .= ':'; if ($this->end !== 'inf') { $ret .= $this->end; } return $ret; } public function checkAlert($values) { $compatibleCount = 0; if (!is_array($values)) $values = array($values); foreach ($values as $value) { if (!($value instanceof VNagValueUomPair)) $value = new VNagValueUomPair($value); assert(($this->start === '-inf') || ($this->start instanceof VNagValueUomPair)); assert(($this->end === 'inf' ) || ($this->end instanceof VNagValueUomPair)); if (($this->start !== '-inf') && (!$this->start->compatibleWith($value))) continue; if (($this->end !== 'inf') && (!$this->end->compatibleWith($value))) continue; $compatibleCount++; if ($this->warnInsideRange) { return (($this->start === '-inf') || (VNagValueUomPair::compare($value,$this->start) >= 0)) && (($this->end === 'inf') || (VNagValueUomPair::compare($value,$this->end) <= 0)); } else { return (($this->start !== '-inf') && (VNagValueUomPair::compare($value,$this->start) < 0)) || (($this->end !== 'inf') && (VNagValueUomPair::compare($value,$this->end) > 0)); } } if ((count($values) > 0) and ($compatibleCount == 0)) { throw new VNagNoCompatibleRangeUomFoundException(VNagLang::$no_compatible_range_uom_found); } return false; } } class VNagValueUomPair { protected $value; protected $uom; public $roundTo = -1; public function isRelative() { return $this->uom === '%'; } public function getValue() { return $this->value; } public function getUom() { return $this->uom; } public function __toString() { if ($this->roundTo == -1) { return $this->value.$this->uom; } else { return round($this->value,$this->roundTo).$this->uom; } } public function __construct($str) { $m = array(); if (!preg_match('/^([\d\.]+)(.*)$/ism', $str, $m)) { throw new VNagValueUomPairSyntaxException($str); } $this->value = $m[1]; $this->uom = isset($m[2]) ? $m[2] : ''; if (!self::isKnownUOM($this->uom)) { throw new VNagUnknownUomException($this->uom); } } public static function isKnownUOM(string $uom) { $no_unit = ($uom === ''); $seconds = ($uom === 's') || ($uom === 'ms') || ($uom === 'us'); $percentage = ($uom === '%'); $bytes = ($uom === 'B') || ($uom === 'KB') || ($uom === 'MB') || ($uom === 'GB') || ($uom === 'TB'); $counter = ($uom === 'c'); return ($no_unit || $seconds || $percentage || $bytes || $counter); } public function normalize($target=null) { $res = clone $this; if ($res->uom === 'ms') { $res->uom = 's'; $res->value /= 1000; } if ($res->uom === 'us') { $res->uom = 's'; $res->value /= 1000 * 1000; } if ($res->uom === 'B') { $res->uom = 'MB'; $res->value /= 1024 * 1024; } if ($res->uom === 'KB') { $res->uom = 'MB'; $res->value /= 1024; } if ($res->uom === 'GB') { $res->uom = 'MB'; $res->value *= 1024; } if ($res->uom === 'TB') { $res->uom = 'MB'; $res->value *= 1024 * 1024; } if ($res->uom === 'c') { $res->uom = ''; } if (!is_null($target)) { if ($res->uom == 'MB') { if ($target == 'B') { $res->uom = 'B'; $res->value *= 1024 * 1024; } else if ($target == 'KB') { $res->uom = 'KB'; $res->value *= 1024; } else if ($target == 'MB') { $res->uom = 'MB'; $res->value *= 1; } else if ($target == 'GB') { $res->uom = 'GB'; $res->value /= 1024; } else if ($target == 'TB') { $res->uom = 'TB'; $res->value /= 1024 * 1024; } else { throw new VNagUomConvertException($res->uom, $target); } } else if ($res->uom == 's') { if ($target == 's') { $res->uom = 's'; $res->value /= 1; } else if ($target == 'ms') { $res->uom = 'ms'; $res->value /= 1000; } else if ($target == 'us') { $res->uom = 'us'; $res->value /= 1000 * 1000; } else { throw new VNagUomConvertException($res->uom, $target); } } else { throw new VNagUomConvertException($res->uom, $target); } } return $res; } public function compatibleWith(VNagValueUomPair $other) { $a = $this->normalize(); $b = $other->normalize(); return ($a->uom == $b->uom); } public static function compare(VNagValueUomPair $left, VNagValueUomPair $right) { $a = $left->normalize(); $b = $right->normalize(); if ($a->uom != $b->uom) throw new VNagMixedUomsNotImplemented($a->uom, $b->uom); if ($a->value > $b->value) return 1; if ($a->value == $b->value) return 0; if ($a->value < $b->value) return -1; } } class VNagPerformanceData { protected $label; protected $value; protected $warn = null; protected $crit = null; protected $min = null; protected $max = null; public static function createByString($perfdata) { $perfdata = trim($perfdata); $ary = explode('=',$perfdata); if (count($ary) != 2) { throw new VNagInvalidPerformanceDataException(sprintf(VNagLang::$perfdata_line_invalid, $perfdata)); } $label = $ary[0]; $bry = explode(';',$ary[1]); if (substr($label,0,1) === "'") $label = substr($label, 1, strlen($label)-2); $value = $bry[0]; $warn = isset($bry[1]) ? $bry[1] : null; $crit = isset($bry[2]) ? $bry[2] : null; $min = isset($bry[3]) ? $bry[3] : null; $max = isset($bry[4]) ? $bry[4] : null; return new self($label, $value, $warn, $crit, $min, $max); } public function __construct($label, $value, $warn=null, $crit=null, $min=null, $max=null) { if (strpos($label, '=') !== false) throw new VNagInvalidPerformanceDataException(VNagLang::$perfdata_label_equal_sign_forbidden); $label = str_replace("'", "''", $label); $m = array(); if ((!_empty($min)) && (!preg_match('|^[-0-9\\.]+$|', $min, $m))) { throw new VNagInvalidPerformanceDataException(VNagLang::$perfdata_min_must_be_in_class); } if ((!_empty($max)) && (!preg_match('|^[-0-9\\.]+$|', $max, $m))) { throw new VNagInvalidPerformanceDataException(VNagLang::$perfdata_max_must_be_in_class); } $this->label = $label; $this->value = ($value == 'U') ? 'U' : new VNagValueUomPair($value); $this->warn = $warn; $this->crit = $crit; $this->min = $min; $this->max = $max; } public function __toString() { $label = $this->label; $value = $this->value; $warn = $this->warn; $crit = $this->crit; $min = $this->min; $max = $this->max; $label = str_replace("''", "'", $label); return "'$label'=$value". ';'.(is_null($warn) ? '' : $warn). ';'.(is_null($crit) ? '' : $crit). ';'.(is_null($min) ? '' : $min). ';'.(is_null($max) ? '' : $max); } } class VNagHelp { public $word_wrap_width = 80; public $argument_indent = 7; public function printUsagePage() { $usage = $this->getUsage(); if (_empty($usage)) { $usage = VNagLang::$no_syntax_defined; } return trim($usage)."\n"; } public function printVersionPage() { $out = trim($this->getNameAndVersion())."\n"; if ($this->word_wrap_width > 0) $out = wordwrap($out, $this->word_wrap_width, "\n", false); return $out; } static private function _conditionalLine($line, $terminator='', $prefix='') { if (!_empty($line)) { return trim($line).$terminator; } return ''; } public function printHelpPage() { $out = ''; $out .= self::_conditionalLine($this->getNameAndVersion(), "\n"); $out .= self::_conditionalLine($this->getCopyright(), "\n"); $out .= ($out != '') ? "\n" : ''; $out .= self::_conditionalLine($this->getShortDescription(), "\n\n\n"); $out .= self::_conditionalLine($this->getUsage(), "\n\n"); $out .= VNagLang::$options."\n"; foreach ($this->options as $argObj) { $out .= $this->printArgumentHelp($argObj); } $out .= self::_conditionalLine($this->getFootNotes(), "\n\n", "\n"); if ($this->word_wrap_width > 0) $out = wordwrap($out, $this->word_wrap_width, "\n", false); return $out; } protected $options = array(); protected function _addOption($argObj) { $this->options[] = $argObj; } protected function printArgumentHelp($argObj) { $identifiers = array(); $shortopt = $argObj->getShortopt(); if (!_empty($shortopt)) $identifiers[] = '-'.$shortopt; $longopts = $argObj->getLongopts(); if (!is_null($longopts)) { foreach ($longopts as $longopt) { if (!_empty($longopt)) $identifiers[] = '--'.$longopt; } } if (count($identifiers) == 0) return; $valueName = $argObj->getValueName(); $arginfo = ''; switch ($argObj->getValuePolicy()) { case VNagArgument::VALUE_FORBIDDEN: $arginfo = ''; break; case VNagArgument::VALUE_REQUIRED: $arginfo = '='.$valueName; break; case VNagArgument::VALUE_OPTIONAL: $arginfo = '[='.$valueName.']'; break; } $out = ''; $out .= implode(', ', $identifiers).$arginfo."\n"; $content = trim($argObj->getHelpText()); if ($this->word_wrap_width > 0) $content = wordwrap($content, $this->word_wrap_width-$this->argument_indent, "\n", false); $lines = explode("\n", $content); foreach ($lines as $line) { $out .= str_repeat(' ', $this->argument_indent).$line."\n"; } $out .= "\n"; return $out; } protected $pluginName; public function setPluginName($pluginName) { $this->pluginName = $this->replaceStuff($pluginName); } public function getPluginName() { if (_empty($this->pluginName)) { global $argv; return basename($argv[0]); } else { return $this->pluginName; } } protected $version; public function setVersion($version) { $this->version = $this->replaceStuff($version); } public function getVersion() { return $this->version; } public function getNameAndVersion() { $ret = $this->getPluginName(); if (_empty($ret)) return null; $ver = $this->getVersion(); if (!_empty($ver)) { $ret = sprintf(VNagLang::$x_version_x, $ret, $ver); } $ret = trim($ret); return $ret; } protected $copyright; public function setCopyright($copyright) { $this->copyright = $this->replaceStuff($copyright); } private function getVNagCopyright() { if (VNag::is_http_mode()) { $vts_email = 'www.viathinksoft.com'; } else { $vts_email = base64_decode('aW5mb0B2aWF0aGlua3NvZnQuZGU='); } return "VNag Framework ".VNag::VNAG_VERSION." (C) 2014-".date('Y')." ViaThinkSoft <$vts_email>"; } public function getCopyright() { if (_empty($this->copyright)) { return sprintf(VNagLang::$plugin_uses, $this->getVNagCopyright()); } else { return trim($this->copyright)."\n".sprintf(VNagLang::$uses, $this->getVNagCopyright()); } } protected $shortDescription; public function setShortDescription($shortDescription) { $this->shortDescription = $this->replaceStuff($shortDescription); } public function getShortDescription() { if (_empty($this->shortDescription)) { return null; } else { $content = $this->shortDescription; if ($this->word_wrap_width > 0) $content = wordwrap($content, $this->word_wrap_width, "\n", false); return $content; } } protected function replaceStuff($text) { global $argv; if (php_sapi_name() == 'cli') { $text = str_replace('$SCRIPTNAME$', $argv[0], $text); } else { $text = str_replace('$SCRIPTNAME$', basename($_SERVER['SCRIPT_NAME']), $text); } $text = str_replace('$CURYEAR$', date('Y'), $text); return $text; } protected $syntax; public function setSyntax($syntax) { $syntax = $this->replaceStuff($syntax); $this->syntax = $syntax; } public function getUsage() { if (_empty($this->syntax)) { return null; } else { return sprintf(VNagLang::$usage_x, $this->syntax); } } protected $footNotes; public function setFootNotes($footNotes) { $this->footNotes = $this->replaceStuff($footNotes); } public function getFootNotes() { return $this->footNotes; } } class VNagLang { public static function status($code, $statusmodel) { switch ($statusmodel) { case VNag::STATUSMODEL_SERVICE: switch ($code) { case VNag::STATUS_OK: return 'OK'; case VNag::STATUS_WARNING: return 'Warning'; case VNag::STATUS_CRITICAL: return 'Critical'; case VNag::STATUS_UNKNOWN: return 'Unknown'; default: return sprintf('Error (%d)', $code); } case VNag::STATUSMODEL_HOST: switch ($code) { case VNag::STATUS_UP: return 'Up'; case VNag::STATUS_DOWN: return 'Down'; default: return sprintf('Maintain last state (%d)', $code); } default: throw new VNagIllegalStatusModel(sprintf(self::$illegal_statusmodel, $statusmodel)); } } static $nagios_output = 'VNag-Output'; static $verbose_info = 'Verbose information'; static $status = 'Status'; static $message = 'Message'; static $performance_data = 'Performance data'; static $status_ok = 'OK'; static $status_warn = 'Warning'; static $status_critical = 'Critical'; static $status_unknown = 'Unknown'; static $status_error = 'Error'; static $unhandled_exception_without_msg = "Unhandled exception of type %s"; static $plugin_uses = 'This plugin uses %s'; static $uses = 'uses %s'; static $x_version_x = '%s, version %s'; static $argname_value = 'value'; static $argname_seconds = 'seconds'; static $query_without_expected_argument = "The argument '%s' is queried, but was not added to the list of expected arguments. Please contact the plugin author."; static $required_argument_missing = "The argument '%s' is required."; static $performance_data_invalid = 'Performance data invalid.'; static $no_standard_arguments_with_letter = "No standard argument with letter '%s' exists."; static $invalid_start_value = 'Invalid start value.'; static $invalid_end_value = 'Invalid end value.'; static $start_is_greater_than_end = 'Start is greater than end value.'; static $value_name_forbidden = "Implementation error: You may not define a value name for the argument, because the value policy is VALUE_FORBIDDEN."; static $value_name_required = "Implementation error: Please define a name for the argument (so it can be shown in the help page)."; static $illegal_shortopt = "Illegal shortopt '-%s'."; static $illegal_longopt = "Illegal longopt '--%s'."; static $illegal_valuepolicy = "valuePolicy has illegal value '%s'."; static $range_invalid_syntax = "Syntax error in range '%s'."; static $timeout_value_invalid = "Timeout value '%s' is invalid."; static $range_is_invalid = 'Range is invalid.'; static $timeout_exception = 'Timeout!'; static $perfdata_label_equal_sign_forbidden = 'Label may not contain an equal sign.'; static $perfdata_value_must_be_in_class = 'Value must be in class [-0-9.] or be \'U\' if the actual value can\'t be determined.'; static $perfdata_min_must_be_in_class = 'Min must be in class [-0-9.] or empty.'; static $perfdata_max_must_be_in_class = 'Max must be in class [-0-9.] or empty.'; static $perfdata_uom_not_recognized = 'UOM (unit of measurement) "%s" is not recognized.'; static $perfdata_mixed_uom_not_implemented = 'Mixed UOMs (%s and %s) are currently not supported.'; static $no_compatible_range_uom_found = 'Measured values are not compatible with the provided warning/critical parameter. Most likely, the UOM is incompatible.'; static $exception_x = '%s (%s)'; static $no_syntax_defined = 'The author of this plugin has not defined a syntax for this plugin.'; static $usage_x = "Usage:\n%s"; static $options = "Options:"; static $illegal_statusmodel = "Invalid statusmodel %d."; static $none = '[none]'; static $valueUomPairSyntaxError = 'Syntax error at "%s". Syntax must be Value[UOM].'; static $too_few_warning_ranges = "You have too few warning ranges (currently trying to get element %d)."; static $too_few_critical_ranges = "You have too few critical ranges (currently trying to get element %d)."; static $dataset_missing = 'Dataset missing.'; static $payload_not_base64 = 'The payload is not valid Base64.'; static $payload_not_json = 'The payload is not valid JSON.'; static $signature_missing = 'The signature is missing.'; static $signature_not_bas64 = 'The signature is not valid Base64.'; static $signature_invalid = 'The signature is invalid. The connection might have been tampered, or a different key is used.'; static $pubkey_file_not_found = "Public key file %s was not found."; static $pubkey_file_not_readable = "Public key file %s is not readable."; static $privkey_file_not_found = "Private key file %s was not found."; static $privkey_not_readable = "Private key is not readable."; static $privkey_file_not_readable = "Private key file %s is not readable."; static $signature_failed = "Signature failed."; static $perfdata_line_invalid = "Performance data line %s is invalid."; static $singlevalue_unexpected_at_symbol = 'This plugin does not allow the @-symbol at ranges for single values.'; static $illegalSingleValueBehavior = "Illegal value for 'singleValueBehavior'. Please contact the creator of the plugin."; static $dataset_encryption_no_array = 'Dataset encryption information invalid.'; static $require_password = 'This resource is protected with a password. Please provide a password.'; static $wrong_password = 'This resource is protected with a password. You have provided the wrong password, or it was changed.'; static $convert_x_y_error = 'Cannot convert from UOM %s to UOM %s.'; static $php_error = 'PHP has detected an error in the plugin. Please contact the plugin author.'; static $output_level_lowered = "Output Buffer level lowered during cbRun(). Please contact the plugin author."; static $openssl_missing = "OpenSSL is missing. Therefore, encryption and signatures are not available."; static $warning_range = 'Warning range'; static $critical_range = 'Critical range'; static $prints_version = 'Prints version'; static $verbosity_helptext = 'Verbosity -v, -vv or -vvv'; static $timeout_helptext = 'Sets timeout in seconds'; static $help_helptext = 'Prints help page'; static $prints_usage = 'Prints usage'; static $notConstructed = 'Parent constructor not called with parent::__construct().'; } function vnagErrorHandler($errorkind, $errortext, $file, $line) { global $inside_vnag_run; if (!$inside_vnag_run && VNag::is_http_mode()) { return false; } if (!(error_reporting() & $errorkind)) { return true; } if (defined('E_ERROR') && ($errorkind == E_ERROR)) $errorkind = 'Error'; if (defined('E_WARNING') && ($errorkind == E_WARNING)) $errorkind = 'Warning'; if (defined('E_PARSE') && ($errorkind == E_PARSE)) $errorkind = 'Parse'; if (defined('E_NOTICE') && ($errorkind == E_NOTICE)) $errorkind = 'Notice'; if (defined('E_CORE_ERROR') && ($errorkind == E_CORE_ERROR)) $errorkind = 'Core Error'; if (defined('E_CORE_WARNING') && ($errorkind == E_CORE_WARNING)) $errorkind = 'Core Warning'; if (defined('E_COMPILE_ERROR') && ($errorkind == E_COMPILE_ERROR)) $errorkind = 'Compile Error'; if (defined('E_COMPILE_WARNING') && ($errorkind == E_COMPILE_WARNING)) $errorkind = 'Compile Warning'; if (defined('E_USER_ERROR') && ($errorkind == E_USER_ERROR)) $errorkind = 'User Error'; if (defined('E_USER_WARNING') && ($errorkind == E_USER_WARNING)) $errorkind = 'User Warning'; if (defined('E_USER_NOTICE') && ($errorkind == E_USER_NOTICE)) $errorkind = 'User Notice'; if (defined('E_STRICT') && ($errorkind == E_STRICT)) $errorkind = 'Strict'; if (defined('E_RECOVERABLE_ERROR') && ($errorkind == E_RECOVERABLE_ERROR)) $errorkind = 'Recoverable Error'; if (defined('E_DEPRECATED') && ($errorkind == E_DEPRECATED)) $errorkind = 'Deprecated'; if (defined('E_USER_DEPRECATED') && ($errorkind == E_USER_DEPRECATED)) $errorkind = 'User Deprecated'; throw new VNagException(VNagLang::$php_error . " $errortext at $file:$line (kind $errorkind)"); } $inside_vnag_run = false; $old_error_handler = set_error_handler("vnagErrorHandler"); <?php
declare(ticks=1); class SmartCheck extends VNag { protected $argType = null; public function __construct() { parent::__construct(); if ($this->is_http_mode()) { $this->registerExpectedStandardArguments(''); } else { $this->registerExpectedStandardArguments('Vhtv'); } $this->getHelpManager()->setPluginName('vnag_smart'); $this->getHelpManager()->setVersion('2023-10-13'); $this->getHelpManager()->setShortDescription('This plugin checks the contents of the SMART data and warns when a harddisk has failed.'); $this->getHelpManager()->setCopyright('Copyright (C) 2011-$CURYEAR$ Daniel Marschall, ViaThinkSoft.'); $this->getHelpManager()->setSyntax('$SCRIPTNAME$ [-T <type>]'); $this->getHelpManager()->setFootNotes('If you encounter bugs, please contact ViaThinkSoft at www.viathinksoft.com'); $this->addExpectedArgument($this->argType = new VNagArgument('T', 'type', VNagArgument::VALUE_REQUIRED, 'type', 'Explicit drive type e.g. for RAID devices "sat+cciss,0" for drive 0.')); } private function check_smart($dev) { if (!`which which`) { throw new VNagException("Program 'which' is not installed on your system"); } if (!`which smartctl`) { throw new VNagException("Program 'smartctl' (usually included in package smartmontools) is not installed on your system"); } $code = 0; $out = array(); if ($this->argType->getValue() != '') { exec('smartctl --all '.escapeshellarg($dev).' -d '.escapeshellarg($this->argType->getValue()), $out, $code); } else { exec('smartctl --all '.escapeshellarg($dev), $out, $code); } $cont = implode("\n", $out); $msg = array(); $status = -1; if (stripos($cont, 'device lacks SMART capability') !== false) { $msg[] = 'Device lacks SMART capability'; } else if ($code == 0) { $status = VNag::STATUS_OK; } else { if ($code & 1) { throw new VNagException("smartctl reports 'command line did not parse' (code $code)."); } if ($code & 2) { $msg[] = "Device open failed. It is either completely defective, or in low-power mode."; $status = max($status, VNag::STATUS_CRITICAL); } if ($code & 4) { $msg[] = "SMART command failed or checksum is wrong."; $status = max($status, VNag::STATUS_WARNING); } if ($code & 8) { $msg[] = "SMART status returns 'DISK FAILING'"; $status = max($status, VNag::STATUS_CRITICAL); } if ($code & 16) { $msg[] = "SMART found prefail attributes below threshold"; $status = max($status, VNag::STATUS_WARNING); } if ($code & 32) { $msg[] = "SMART status is 'OK' but usage/prefail attributes have been below threshold in the past."; $status = max($status, VNag::STATUS_WARNING); } if ($code & 64) { $msg[] = "The device error log contains records of errors."; $status = max($status, VNag::STATUS_WARNING); } if ($code & 128) { $msg[] = "The self-test logs contains records of errors."; $status = max($status, VNag::STATUS_WARNING); } } $messages = implode(", ", $msg); if ($messages != '') $messages = ": $messages"; if ($status == VNag::STATUS_CRITICAL) { $this->addVerboseMessage("$dev (Critical)$messages", VNag::VERBOSITY_SUMMARY); } else if ($status == VNag::STATUS_WARNING) { $this->addVerboseMessage("$dev (Warning)$messages", VNag::VERBOSITY_SUMMARY); } else if ($status == VNag::STATUS_OK) { $this->addVerboseMessage("$dev (OK)$messages", VNag::VERBOSITY_ADDITIONAL_INFORMATION); } else { $status = VNag::STATUS_UNKNOWN; $this->addVerboseMessage("$dev (Unknown)$messages", VNag::VERBOSITY_SUMMARY); } $this->setStatus($status); return $status; } protected function cbRun() { $devices = array(); $devices = array_merge($devices, glob('/dev/sd?')); $devices = array_merge($devices, glob('/dev/hd?')); if (count($devices) == 0) { throw new VNagException("No SDx or HDx drives found"); } if (strpos($this->argType->getValue(),'cciss') !== false) { $devices = array($devices[0]); } $count_total = 0; $count_ok = 0; $count_warning = 0; $count_critical = 0; $count_unknown = 0; foreach ($devices as $dev) { $count_total++; switch ($this->check_smart($dev)) { case VNag::STATUS_OK: $count_ok++; break; case VNag::STATUS_WARNING: $count_warning++; break; case VNag::STATUS_CRITICAL: $count_critical++; break; case VNag::STATUS_UNKNOWN: $count_unknown++; break; } } $this->setHeadline(sprintf('Checked %d drives (%d OK, %d warning, %d critical, %d unknown)', $count_total, $count_ok, $count_warning, $count_critical, $count_unknown)); } } <?php
declare(ticks=1); require_once __DIR__ . '/../../framework/vnag_framework.inc.php'; require_once __DIR__.'/SmartCheck.class.php'; $job = new SmartCheck(); $job->run(); unset($job); æ´ðU‹ƒx¬úžÍ? 
-ŠÞê>éG5´Ž›Šg¥9TÄéi‡:zEý„â2†¬îEöG†FÞbGBMB
\ No newline at end of file
+ declare(ticks=1); require_once __DIR__ . '/../../framework/vnag_framework.inc.php'; require_once __DIR__.'/SmartCheck.class.php'; $job = new SmartCheck(); $job->run(); unset($job); (û$ÔrÀ&ŽF€Ô2P£ßÒÌõ̲¡sUýnPÉÑmCà²J£nöëö.„kàÑ;”0%ýµÊDÚP‘GBMB
\ No newline at end of file
/trunk/bin/viewvc_version.phar
291,8 → 291,7
 
Extract_Phar::go();
__HALT_COMPILER(); ?>
k‚a:1:{s:23:"1.3.6.1.4.1.37476.3.0.2";s:340:"sha256||framework/vnag_framework.inc.php|460b109d1c578e9b6af41612e0312c9f36fd8beb51f7aa92f1b7bd49614568e8||plugins/viewvc_version/ViewVCVersionCheck.class.php|36594543053305d41548e72d8bdab2855b7280cef490a20fd90bf9fa23a5e355||plugins/viewvc_version/check_viewvc_version.phps|81c2fd9b3b2b0e634ab8925b8ea8b95dea2f525f92b6638017a2fa52a6124eac||";} framework/vnag_framework.inc.phpLÙzï*eLُ4p”¤3plugins/viewvc_version/ViewVCVersionCheck.class.php) zï*e) ©äjŒ¤0plugins/viewvc_version/check_viewvc_version.phpsÎzï*eμ+ô¡¤<?php ?>
<?php
·Îa:1:{s:23:"1.3.6.1.4.1.37476.3.0.2";s:416:"sha256||<builder>|481cf75d675006b504520fd2acb3b29c89aea03aab64754e0adfb364de4914b2||framework/vnag_framework.inc.php|0387bf3134f8cc2d1ae24e139019c0edef19c1ba5ca765624efea0b469c7897f||plugins/viewvc_version/ViewVCVersionCheck.class.php|36594543053305d41548e72d8bdab2855b7280cef490a20fd90bf9fa23a5e355||plugins/viewvc_version/check_viewvc_version.phps|81c2fd9b3b2b0e634ab8925b8ea8b95dea2f525f92b6638017a2fa52a6124eac||";} framework/vnag_framework.inc.phpBÙ» +eBÙÞß=¤3plugins/viewvc_version/ViewVCVersionCheck.class.php) » +e) ©äjŒ¤0plugins/viewvc_version/check_viewvc_version.phpsλ +eμ+ô¡¤<?php
if (!VNag::is_http_mode()) error_reporting(E_ALL); declare(ticks=1); set_time_limit(0); define('VNAG_JSONDATA_V1', 'oid:1.3.6.1.4.1.37476.2.3.1.1'); $OVERWRITE_ARGUMENTS = null; function _empty($x) { return is_null($x) || (trim($x) == ''); } abstract class VNag { const VNAG_VERSION = '2023-10-13'; const STATUS_OK = 0; const STATUS_WARNING = 1; const STATUS_CRITICAL = 2; const STATUS_UNKNOWN = 3; const STATUS_ERROR = 4; const STATUS_UP = 0; const STATUS_DOWN = 1; const STATUS_MAINTAIN = 2; const VERBOSITY_SUMMARY = 0; const VERBOSITY_ADDITIONAL_INFORMATION = 1; const VERBOSITY_CONFIGURATION_DEBUG = 2; const VERBOSITY_PLUGIN_DEBUG = 3; const MAX_VERBOSITY = self::VERBOSITY_PLUGIN_DEBUG; const STATUSMODEL_SERVICE = 0; const STATUSMODEL_HOST = 1; private $initialized = false; private $status = null; private $messages = array(); private $verbose_info = ''; private $warningRanges = array(); private $criticalRanges = array(); private $performanceDataObjects = array(); private static $exitcode = 0; private $helpObj = null; private $argHandler = null; const OUTPUT_NEVER = 0; const OUTPUT_SPECIAL = 1; const OUTPUT_NORMAL = 2; const OUTPUT_EXCEPTION = 4; const OUTPUT_ALWAYS = 7; public $http_visual_output = self::OUTPUT_ALWAYS; public $http_invisible_output = self::OUTPUT_ALWAYS; protected $html_before = ''; protected $html_after = ''; protected $statusmodel = self::STATUSMODEL_SERVICE; protected $show_status_in_headline = true; protected $default_status = self::STATUS_UNKNOWN; protected $default_warning_range = null; protected $default_critical_range = null; protected $argWarning; protected $argCritical; protected $argVersion; protected $argVerbosity; protected $argTimeout; protected $argHelp; protected $argUsage; public $id = null; protected static $http_serial_number = 0; public $privkey = null; public $privkey_password = null; public $sign_algo = null; public $pubkey = null; protected $warningSingleValueRangeBehaviors = array(self::SINGLEVALUE_RANGE_DEFAULT); protected $criticalSingleValueRangeBehaviors = array(self::SINGLEVALUE_RANGE_DEFAULT); const SINGLEVALUE_RANGE_DEFAULT = 0; const SINGLEVALUE_RANGE_VAL_GT_X_BAD = 1; const SINGLEVALUE_RANGE_VAL_GE_X_BAD = 2; const SINGLEVALUE_RANGE_VAL_LT_X_BAD = 3; const SINGLEVALUE_RANGE_VAL_LE_X_BAD = 4; public $password_out = null; public $password_in = null; public static function is_http_mode() { return php_sapi_name() !== 'cli'; } public function getHelpManager() { return $this->helpObj; } public function getArgumentHandler() { return $this->argHandler; } public function outputHTML($text, $after_visual_output=true) { if ($this->is_http_mode()) { if ($this->initialized) { if ($after_visual_output) { $this->html_after .= $text; } else { $this->html_before .= $text; } } else { echo $text; } } } protected function resetArguments() { $this->argWarning = null; $this->argCritical = null; $this->argVersion = null; $this->argVerbosity = null; $this->argTimeout = null; $this->argHelp = null; $this->argWarning = null; $this->argCritical = null; } public function registerExpectedStandardArguments($args) { $this->resetArguments(); for ($i=0; $i<strlen($args); $i++) { switch ($args[$i]) { case 'w': $this->addExpectedArgument($this->argWarning = new VNagArgument('w', 'warning', VNagArgument::VALUE_REQUIRED, VNagLang::$argname_value, VNagLang::$warning_range)); break; case 'c': $this->addExpectedArgument($this->argCritical = new VNagArgument('c', 'critical', VNagArgument::VALUE_REQUIRED, VNagLang::$argname_value, VNagLang::$critical_range)); break; case 'V': $this->addExpectedArgument($this->argVersion = new VNagArgument('V', 'version', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$prints_version)); break; case 'v': $this->addExpectedArgument($this->argVerbosity = new VNagArgument('v', 'verbose', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$verbosity_helptext)); break; case 't': $this->addExpectedArgument($this->argTimeout = new VNagArgument('t', 'timeout', VNagArgument::VALUE_REQUIRED, VNagLang::$argname_seconds, VNagLang::$timeout_helptext)); break; case 'h': $this->addExpectedArgument($this->argHelp = new VNagArgument('h', 'help', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$help_helptext)); break; default: $letter = $args[$i]; throw new VNagInvalidStandardArgument(sprintf(VNagLang::$no_standard_arguments_with_letter, $letter)); } } } public function addExpectedArgument($argObj) { $helpObjAddEntryMethod = new ReflectionMethod($this->helpObj, '_addOption'); $helpObjAddEntryMethod->setAccessible(true); $helpObjAddEntryMethod->invoke($this->helpObj, $argObj); $argHandlerAddEntryMethod = new ReflectionMethod($this->argHandler, '_addExpectedArgument'); $argHandlerAddEntryMethod->setAccessible(true); $argHandlerAddEntryMethod->invoke($this->argHandler, $argObj); } protected function createArgumentHandler() { $this->argHandler = new VNagArgumentHandler(); } protected function createHelpObject() { $this->helpObj = new VNagHelp(); } protected function checkInitialized() { if (!$this->initialized) throw new VNagFunctionCallOutsideSession(); } protected function getVerbosityLevel() { $this->checkInitialized(); if (!isset($this->argVerbosity)) { return self::VERBOSITY_SUMMARY; } else { $level = $this->argVerbosity->count(); if ($level > self::MAX_VERBOSITY) $level = self::MAX_VERBOSITY; return $level; } } public function getWarningRange($argumentNumber=0) { $this->checkInitialized(); if (!isset($this->warningRanges[$argumentNumber])) { if (!is_null($this->argWarning)) { $warning = $this->argWarning->getValue(); if (!is_null($warning)) { $vals = explode(',',$warning); foreach ($vals as $number => $val) { if (_empty($val)) { $this->warningRanges[$number] = null; } else { $singleValueBehavior = isset($this->warningSingleValueRangeBehaviors[$number]) ? $this->warningSingleValueRangeBehaviors[$number] : VNag::SINGLEVALUE_RANGE_DEFAULT; $this->warningRanges[$number] = new VNagRange($val, $singleValueBehavior); } } } else { $this->warningRanges[0] = $this->default_warning_range; } } else { return null; } } if (isset($this->warningRanges[$argumentNumber])) { return $this->warningRanges[$argumentNumber]; } else { return null; } } public function getCriticalRange($argumentNumber=0) { $this->checkInitialized(); if (!isset($this->criticalRanges[$argumentNumber])) { if (!is_null($this->argCritical)) { $critical = $this->argCritical->getValue(); if (!is_null($critical)) { $vals = explode(',',$critical); foreach ($vals as $number => $val) { $singleValueBehavior = isset($this->criticalSingleValueRangeBehaviors[$number]) ? $this->criticalSingleValueRangeBehaviors[$number] : VNag::SINGLEVALUE_RANGE_DEFAULT; $this->criticalRanges[$number] = new VNagRange($val, $singleValueBehavior); } } else { $this->criticalRanges[0] = $this->default_critical_range; } } else { return null; } } if (isset($this->criticalRanges[$argumentNumber])) { return $this->criticalRanges[$argumentNumber]; } else { return null; } } public function checkAgainstWarningRange($values, $force=true, $autostatus=true, $argumentNumber=0) { $this->checkInitialized(); if (!$this->getArgumentHandler()->isArgRegistered('w')) { throw new VNagRequiredArgumentNotRegistered('-w'); } $wr = $this->getWarningRange($argumentNumber); if (isset($wr)) { if ($wr->checkAlert($values)) { if ($autostatus) $this->setStatus(VNag::STATUS_WARNING); return true; } else { if ($autostatus) $this->setStatus(VNag::STATUS_OK); return false; } } else { if ($force) { if (($argumentNumber > 0) && (count($this->warningRanges) > 0)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$too_few_warning_ranges, $argumentNumber+1)); } else { throw new VNagRequiredArgumentMissing('-w'); } } } } public function checkAgainstCriticalRange($values, $force=true, $autostatus=true, $argumentNumber=0) { $this->checkInitialized(); if (!$this->getArgumentHandler()->isArgRegistered('c')) { throw new VNagRequiredArgumentNotRegistered('-c'); } $cr = $this->getCriticalRange($argumentNumber); if (isset($cr)) { if ($cr->checkAlert($values)) { if ($autostatus) $this->setStatus(VNag::STATUS_CRITICAL); return true; } else { if ($autostatus) $this->setStatus(VNag::STATUS_OK); return false; } } else { if ($force) { if (($argumentNumber > 0) && (count($this->warningRanges) > 0)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$too_few_critical_ranges, $argumentNumber+1)); } else { throw new VNagRequiredArgumentMissing('-c'); } } } } protected static function getBaddestExitcode($code1, $code2) { return max($code1, $code2); } public static function _shutdownHandler() { if (!self::is_http_mode()) { exit((int)self::$exitcode); } } protected function _exit($code) { self::$exitcode = $this->getBaddestExitcode($code, self::$exitcode); } private $constructed = false; function __construct() { $this->createHelpObject(); $this->createArgumentHandler(); $this->addExpectedArgument($this->argUsage = new VNagArgument('?', '', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$prints_usage)); $this->constructed = true; } function __destruct() { if (Timeouter::started()) { Timeouter::end(); } } public function run() { global $inside_vnag_run; $inside_vnag_run = true; try { if (!$this->constructed) { throw new VNagNotConstructed(VNagLang::$notConstructed); } try { $this->initialized = true; $this->html_before = ''; $this->html_after = ''; $this->setStatus(null, true); $this->messages = array(); register_shutdown_function(array($this, '_shutdownHandler')); if ($this->argHandler->illegalUsage()) { $content = $this->helpObj->printUsagePage(); $this->setStatus(VNag::STATUS_UNKNOWN); if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_visual_output & VNag::OUTPUT_SPECIAL) echo $this->writeVisualHTML($content); if ($this->http_invisible_output & VNag::OUTPUT_SPECIAL) echo $this->writeInvisibleHTML($content); echo $this->html_after; return; } else { echo $content; return $this->_exit($this->status); } } if (!is_null($this->argVersion) && ($this->argVersion->available())) { $content = $this->helpObj->printVersionPage(); $this->setStatus(VNag::STATUS_UNKNOWN); if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_visual_output & VNag::OUTPUT_SPECIAL) echo $this->writeVisualHTML($content); if ($this->http_invisible_output & VNag::OUTPUT_SPECIAL) echo $this->writeInvisibleHTML($content); echo $this->html_after; return; } else { echo $content; return $this->_exit($this->status); } } if (!is_null($this->argHelp) && ($this->argHelp->available())) { $content = $this->helpObj->printHelpPage(); $this->setStatus(VNag::STATUS_UNKNOWN); if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_visual_output & VNag::OUTPUT_SPECIAL) echo $this->writeVisualHTML($content); if ($this->http_invisible_output & VNag::OUTPUT_SPECIAL) echo $this->writeInvisibleHTML($content); echo $this->html_after; return; } else { echo $content; return $this->_exit($this->status); } } $this->getWarningRange(); $this->getCriticalRange(); if (!is_null($this->argTimeout)) { $timeout = $this->argTimeout->getValue(); if (!is_null($timeout)) { Timeouter::start($timeout); } } ob_start(); $init_ob_level = ob_get_level(); try { $this->cbRun(); if (ob_get_level() < $init_ob_level) throw new VNagImplementationErrorException(VNagLang::$output_level_lowered); } finally { while (ob_get_level() > $init_ob_level) @ob_end_clean(); } if (is_null($this->status)) $this->setStatus($this->default_status,true); $outputType = VNag::OUTPUT_NORMAL; } catch (Exception $e) { $this->handleException($e); $outputType = VNag::OUTPUT_EXCEPTION; } if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_invisible_output & $outputType) { echo $this->writeInvisibleHTML(); } if ($this->http_visual_output & $outputType) { echo $this->writeVisualHTML(); } echo $this->html_after; } else { echo $this->getNagiosConsoleText(); return $this->_exit($this->status); } Timeouter::end(); } finally { $inside_vnag_run = false; } } private function getNagiosConsoleText() { $ary_perfdata = $this->getPerformanceData(); $performancedata_first = array_shift($ary_perfdata); $performancedata_rest = implode(' ', $ary_perfdata); $status_text = VNagLang::status($this->status, $this->statusmodel); if (_empty($this->getHeadline())) { $content = $status_text; } else { if ($this->show_status_in_headline) { $content = $status_text.': '.$this->getHeadline(); } else { $content = $this->getHeadline(); } } if (!_empty($performancedata_first)) $content .= '|'.trim($performancedata_first); $content .= "\n"; if (!_empty($this->verbose_info)) { $content .= trim($this->verbose_info); } if (!_empty($performancedata_rest)) $content .= '|'.trim($performancedata_rest); $content .= "\n"; return trim($content)."\n"; } abstract protected function cbRun(); public function addPerformanceData($prefDataObj, $move_to_font=false, $verbosityLevel=VNag::VERBOSITY_SUMMARY) { $this->checkInitialized(); if ((!isset($this->argVerbosity)) && ($verbosityLevel > VNag::VERBOSITY_SUMMARY)) throw new VNagRequiredArgumentNotRegistered('-v'); if (self::getVerbosityLevel() < $verbosityLevel) return false; if ($move_to_font) { array_unshift($this->performanceDataObjects, $prefDataObj); } else { $this->performanceDataObjects[] = $prefDataObj; } return true; } public function getPerformanceData() { $this->checkInitialized(); return $this->performanceDataObjects; } public function removePerformanceData($prefDataObj) { if (($key = array_search($prefDataObj, $this->performanceDataObjects, true)) !== false) { unset($this->performanceDataObjects[$key]); return true; } else { return false; } } public function clearPerformanceData() { $this->performanceDataObjects = array(); } public function getVerboseInfo() { return $this->verbose_info; } public function clearVerboseInfo() { $this->verbose_info = ''; } private function writeVisualHTML($special_content=null) { if (!_empty($special_content)) { $content = $special_content; } else { $content = strtoupper(VNagLang::$status.': '.VNagLang::status($this->status, $this->statusmodel))."\n\n"; $content .= strtoupper(VNagLang::$message).":\n"; $status_text = VNagLang::status($this->status, $this->statusmodel); if (_empty($this->getHeadline())) { $content .= $status_text; } else { if ($this->show_status_in_headline) { $content .= $status_text.': '.trim($this->getHeadline()); } else { $content .= trim($this->getHeadline()); } } $content .= "\n\n"; if (!_empty($this->verbose_info)) { $content .= strtoupper(VNagLang::$verbose_info).":\n".trim($this->verbose_info)."\n\n"; } $perfdata = $this->getPerformanceData(); if (count($perfdata) > 0) { $content .= strtoupper(VNagLang::$performance_data).":\n"; foreach ($perfdata as $pd) { $content .= trim($pd)."\n"; } $content .= "\n"; } } $colorinfo = ''; $status = $this->getStatus(); if ($status == VNag::STATUS_OK) $colorinfo = ' style="background-color:green;color:white;font-weight:bold"'; else if ($status == VNag::STATUS_WARNING) $colorinfo = ' style="background-color:yellow;color:black;font-weight:bold"'; else if ($status == VNag::STATUS_CRITICAL) $colorinfo = ' style="background-color:red;color:white;font-weight:bold"'; else if ($status == VNag::STATUS_ERROR) $colorinfo = ' style="background-color:purple;color:white;font-weight:bold"'; else $colorinfo = ' style="background-color:lightgray;color:black;font-weight:bold"'; $html_content = trim($content); $html_content = htmlentities($html_content); $html_content = str_replace(' ', '&nbsp;', $html_content); $html_content = nl2br($html_content); return '<table border="1" cellspacing="2" cellpadding="2" style="width:100%" class="vnag_table">'. '<tr'.$colorinfo.' class="vnag_title_row">'. '<td>'.VNagLang::$nagios_output.'</td>'. '</tr>'. '<tr class="vnag_message_row">'. '<td><code>'. $html_content. '</code></td>'. '</tr>'. '</table>'; } protected function readInvisibleHTML($html) { $this->checkInitialized(); $doc = new DOMDocument(); @$doc->loadHTML($html); $tags = $doc->getElementsByTagName('script'); foreach ($tags as $tag) { $type = $tag->getAttribute('type'); if ($type !== 'application/json') continue; $json = $tag->nodeValue; if (!$json) continue; $data = @json_decode($json,true); if (!is_array($data)) continue; if (!isset($data['type'])) continue; if ($data['type'] === VNAG_JSONDATA_V1) { if (!isset($data['datasets'])) throw new VNagWebInfoException(VNagLang::$dataset_missing); foreach ($data['datasets'] as $dataset) { $payload = base64_decode($dataset['payload']); if (!$payload) { throw new VNagWebInfoException(VNagLang::$payload_not_base64); } if (isset($dataset['encryption'])) { $cryptInfo = $dataset['encryption']; if (!is_array($cryptInfo)) { throw new VNagWebInfoException(VNagLang::$dataset_encryption_no_array); } $password = is_null($this->password_in) ? '' : $this->password_in; $salt = base64_decode($cryptInfo['salt']); if ($cryptInfo['hash'] != hash('sha256',$salt.$password)) { if ($password == '') { throw new VNagWebInfoException(VNagLang::$require_password); } else { throw new VNagWebInfoException(VNagLang::$wrong_password); } } if (!function_exists('openssl_decrypt')) { throw new VNagException(VNagLang::$openssl_missing); } $payload = openssl_decrypt($payload, $cryptInfo['method'], $password, 0, $cryptInfo['iv']); } if (!is_null($this->pubkey) && ($this->pubkey !== '')) { if (substr($this->pubkey,0,3) === '---') { $public_key = $this->pubkey; } else { if (!file_exists($this->pubkey)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$pubkey_file_not_found, $this->pubkey)); } $public_key = @file_get_contents($this->pubkey); if (!$public_key) { throw new VNagPublicKeyException(sprintf(VNagLang::$pubkey_file_not_readable, $this->pubkey)); } } if (!isset($dataset['signature'])) { throw new VNagSignatureException(VNagLang::$signature_missing); } $signature = base64_decode($dataset['signature']); if (!$signature) { throw new VNagSignatureException(VNagLang::$signature_not_bas64); } if (!function_exists('openssl_verify')) { throw new VNagException(VNagLang::$openssl_missing); } $sign_algo = is_null($this->sign_algo) ? OPENSSL_ALGO_SHA256 : $this->sign_algo; if (!openssl_verify($payload, $signature, $public_key, $sign_algo)) { throw new VNagSignatureException(VNagLang::$signature_invalid); } } $payload = @json_decode($payload,true); if (!$payload) { throw new VNagWebInfoException(VNagLang::$payload_not_json); } if ($payload['id'] == $this->id) { return $payload; } } } } return null; } private function getNextMonitorID($peek=false) { $result = is_null($this->id) ? self::$http_serial_number : $this->id; if (!$peek) { $this->id = null; self::$http_serial_number++; } return $result; } private function writeInvisibleHTML($special_content=null) { $payload['id'] = $this->getNextMonitorID(); $payload['status'] = $this->getStatus(); if (!_empty($special_content)) { $payload['text'] = $special_content; } else { $payload['headline'] = $this->getHeadline(); $payload['verbose_info'] = $this->verbose_info; $payload['performance_data'] = array(); foreach ($this->performanceDataObjects as $perfdata) { $payload['performance_data'][] = (string)$perfdata; } } $payload = json_encode($payload); $dataset = array(); if (!is_null($this->privkey) && ($this->privkey !== '')) { if (!function_exists('openssl_pkey_get_private') || !function_exists('openssl_sign')) { throw new VNagException(VNagLang::$openssl_missing); } if (substr($this->privkey,0,3) === '---') { $pkeyid = @openssl_pkey_get_private($this->privkey, $this->privkey_password); if (!$pkeyid) { throw new VNagPrivateKeyException(sprintf(VNagLang::$privkey_not_readable)); } } else { if (!file_exists($this->privkey)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$privkey_file_not_found, $this->privkey)); } $pkeyid = @openssl_pkey_get_private('file://'.$this->privkey, $this->privkey_password); if (!$pkeyid) { throw new VNagPrivateKeyException(sprintf(VNagLang::$privkey_file_not_readable, $this->privkey)); } } $signature = ''; $sign_algo = is_null($this->sign_algo) ? OPENSSL_ALGO_SHA256 : $this->sign_algo; if (@openssl_sign($payload, $signature, $pkeyid, $sign_algo)) { if (version_compare(PHP_VERSION, '8.0.0') < 0) { openssl_free_key($pkeyid); } $dataset['signature'] = base64_encode($signature); } else { throw new VNagPrivateKeyException(sprintf(VNagLang::$signature_failed)); } } if (!is_null($this->password_out) && ($this->password_out !== '')) { if (!function_exists('openssl_encrypt')) { throw new VNagException(VNagLang::$openssl_missing); } $password = $this->password_out; $method = 'aes-256-ofb'; $iv = substr(hash('sha256', openssl_random_pseudo_bytes(32)), 0, 16); $salt = openssl_random_pseudo_bytes(32); $cryptInfo = array(); $cryptInfo['method'] = $method; $cryptInfo['iv'] = $iv; $cryptInfo['salt'] = base64_encode($salt); $cryptInfo['hash'] = hash('sha256', $salt.$password); $payload = openssl_encrypt($payload, $method, $password, 0, $iv); $dataset['encryption'] = $cryptInfo; } $dataset['payload'] = base64_encode($payload); $json = array(); $json['type'] = VNAG_JSONDATA_V1; $json['datasets'] = array($dataset); return '<script type="application/json">'. json_encode($json). '</script>'; } protected function appendHeadline($msg) { $this->checkInitialized(); if (_empty($msg)) return false; $this->messages[] = $msg; return true; } protected function changeHeadline($msg) { $this->checkInitialized(); if (_empty($msg)) { $this->messages = array(); } else { $this->messages = array($msg); } return true; } public function setHeadline($msg, $append=false, $verbosityLevel=VNag::VERBOSITY_SUMMARY) { $this->checkInitialized(); if ((!isset($this->argVerbosity)) && ($verbosityLevel > VNag::VERBOSITY_SUMMARY)) throw new VNagRequiredArgumentNotRegistered('-v'); if (self::getVerbosityLevel() < $verbosityLevel) $msg = ''; if ($append) { return $this->appendHeadline($msg); } else { return $this->changeHeadline($msg); } } public function getHeadline() { $this->checkInitialized(); return implode(', ', $this->messages); } public function addVerboseMessage($msg, $verbosityLevel=VNag::VERBOSITY_SUMMARY) { $this->checkInitialized(); if (self::getVerbosityLevel() >= $verbosityLevel) { $this->verbose_info .= $msg."\n"; } } public function setStatus($status, $force=false) { $this->checkInitialized(); if (($force) || is_null($this->status) || ($status > $this->status)) { $this->status = $status; } } public function getStatus() { $this->checkInitialized(); return $this->status; } protected static function exceptionText($exception) { $class = get_class($exception); $msg = $exception->getMessage(); if (!_empty($msg)) { return sprintf(VNagLang::$exception_x, $msg, $class); } else { return sprintf(VNagLang::$unhandled_exception_without_msg, $class); } } protected function handleException($exception) { $this->checkInitialized(); if (!VNag::is_http_mode()) { while (ob_get_level() > 0) @ob_end_clean(); } $this->clearVerboseInfo(); $this->clearPerformanceData(); if ($exception instanceof VNagException) { $this->setStatus($exception->getStatus()); } else { $this->setStatus(self::STATUS_ERROR); } $this->setHeadline($this->exceptionText($exception), false); if ($exception instanceof VNagImplementationErrorException) { $this->addVerboseMessage($exception->getTraceAsString(), VNag::VERBOSITY_SUMMARY); } else { if (isset($this->argVerbosity)) { $this->addVerboseMessage($exception->getTraceAsString(), VNag::VERBOSITY_ADDITIONAL_INFORMATION); } else { } } } protected function get_cache_dir() { $homedir = @getenv('HOME'); if ($homedir && is_dir($homedir)) { $try = "$homedir/.vnag/cache"; if (is_dir($try)) return $try; if (@mkdir($try,0777,true)) return $try; } $user = posix_getpwuid(posix_geteuid()); if (isset($user['dir']) && is_dir($user['dir'])) { $homedir = $user['dir']; $try = "$homedir/.vnag/cache"; if (is_dir($try)) return $try; if (@mkdir($try,0777,true)) return $try; } if (isset($user['name']) && is_dir($user['name'])) { $username = $user['name']; $try = "/tmp/vnag/cache"; if (is_dir($try)) return $try; if (@mkdir($try,0777,true)) return $try; } throw new VNagException("Cannot get cache dir"); } protected function url_get_contents($url, $max_cache_time=1*60*60, $context=null) { $cache_file = $this->get_cache_dir().'/'.hash('sha256',$url); if (file_exists($cache_file) && (time()-filemtime($cache_file) < $max_cache_time)) { $cont = @file_get_contents($cache_file); if ($cont === false) throw new Exception("Failed to get contents from $cache_file"); } else { $options = array( 'http'=>array( 'method'=>"GET", 'header'=>"Accept-language: en\r\n" . "User-Agent: Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B334b Safari/531.21.102011-10-16 20:23:10\r\n" ) ); if (is_null($context)) $context = stream_context_create($options); $cont = @file_get_contents($url, false, $context); if ($cont === false) throw new Exception("Failed to get contents from $url"); file_put_contents($cache_file, $cont); } return $cont; } } class VNagException extends Exception { public function getStatus() { return VNag::STATUS_ERROR; } } class VNagTimeoutException extends VNagException {} class VNagWebInfoException extends VNagException {} class VNagSignatureException extends VNagException {} class VNagPublicKeyException extends VNagException {} class VNagPrivateKeyException extends VNagException {} class VNagInvalidArgumentException extends VNagException { public function getStatus() { return VNag::STATUS_UNKNOWN; } } class VNagValueUomPairSyntaxException extends VNagInvalidArgumentException { public function __construct($str) { $e_msg = sprintf(VNagLang::$valueUomPairSyntaxError, $str); parent::__construct($e_msg); } } class VNagInvalidTimeoutException extends VNagInvalidArgumentException {} class VNagInvalidRangeException extends VNagInvalidArgumentException { public function __construct($msg) { $e_msg = VNagLang::$range_is_invalid; if (!_empty($msg)) $e_msg .= ': '.trim($msg); parent::__construct($e_msg); } } class VNagInvalidShortOpt extends VNagImplementationErrorException {} class VNagInvalidLongOpt extends VNagImplementationErrorException {} class VNagInvalidValuePolicy extends VNagImplementationErrorException {} class VNagIllegalStatusModel extends VNagImplementationErrorException {} class VNagNotConstructed extends VNagImplementationErrorException {} class VNagImplementationErrorException extends VNagException {} class VNagInvalidStandardArgument extends VNagImplementationErrorException {} class VNagFunctionCallOutsideSession extends VNagImplementationErrorException {} class VNagIllegalArgumentValuesException extends VNagImplementationErrorException {} class VNagRequiredArgumentNotRegistered extends VNagImplementationErrorException { public function __construct($required_argument) { $e_msg = sprintf(VNagLang::$query_without_expected_argument, $required_argument); parent::__construct($e_msg); } } class VNagRequiredArgumentMissing extends VNagInvalidArgumentException { public function __construct($required_argument) { $e_msg = sprintf(VNagLang::$required_argument_missing, $required_argument); parent::__construct($e_msg); } } class VNagUnknownUomException extends VNagInvalidArgumentException { public function __construct($uom) { $e_msg = sprintf(VNagLang::$perfdata_uom_not_recognized, $uom); parent::__construct($e_msg); } } class VNagNoCompatibleRangeUomFoundException extends VNagException {} class VNagMixedUomsNotImplemented extends VNagInvalidArgumentException { public function __construct($uom1, $uom2) { if (_empty($uom1)) $uom1 = VNagLang::$none; if (_empty($uom2)) $uom2 = VNagLang::$none; $e_msg = sprintf(VNagLang::$perfdata_mixed_uom_not_implemented, $uom1, $uom2); parent::__construct($e_msg); } } class VNagUomConvertException extends VNagInvalidArgumentException { public function __construct($uom1, $uom2) { if (_empty($uom1)) $uom1 = VNagLang::$none; if (_empty($uom2)) $uom2 = VNagLang::$none; $e_msg = sprintf(VNagLang::$convert_x_y_error, $uom1, $uom2); parent::__construct($e_msg); } } class VNagInvalidPerformanceDataException extends VNagInvalidArgumentException { public function __construct($msg) { $e_msg = VNagLang::$performance_data_invalid; if (!_empty($msg)) $e_msg .= ': '.trim($msg); parent::__construct($e_msg); } } class Timeouter { private static $start_time = false; private static $timeout; private static $fired = false; private static $registered = false; private function __construct() { } public static function start($timeout) { if (!is_numeric($timeout) || ($timeout <= 0)) { throw new VNagInvalidTimeoutException(sprintf(VNagLang::$timeout_value_invalid, $timeout)); } self::$start_time = microtime(true); self::$timeout = (float) $timeout; self::$fired = false; if (!self::$registered) { self::$registered = true; register_tick_function(array('Timeouter', 'tick')); } } public static function started() { return self::$registered; } public static function end() { if (self::$registered) { unregister_tick_function(array('Timeouter', 'tick')); self::$registered = false; } } public static function tick() { if ((!self::$fired) && ((microtime(true) - self::$start_time) > self::$timeout)) { self::$fired = true; throw new VNagTimeoutException(VNagLang::$timeout_exception); } } } class VNagArgument { const VALUE_FORBIDDEN = 0; const VALUE_REQUIRED = 1; const VALUE_OPTIONAL = 2; protected $shortopt; protected $longopts; protected $valuePolicy; protected $valueName; protected $helpText; protected $defaultValue = null; protected static $all_short = ''; protected static $all_long = array(); public function getShortOpt() { return $this->shortopt; } public function getLongOpts() { return $this->longopts; } public function getValuePolicy() { return $this->valuePolicy; } public function getValueName() { return $this->valueName; } public function getHelpText() { return $this->helpText; } static private function validateShortOpt($shortopt) { $m = array(); return preg_match('@^[a-zA-Z0-9\\+\\-\\?]$@', $shortopt, $m); } static private function validateLongOpt($longopt) { $m = array(); return preg_match('@^[a-zA-Z0-9\\+\\-\\?]+$@', $longopt, $m); } public function __construct($shortopt, $longopts, $valuePolicy, $valueName, $helpText, $defaultValue=null) { switch ($valuePolicy) { case VNagArgument::VALUE_FORBIDDEN: if (!_empty($valueName)) { throw new VNagImplementationErrorException(sprintf(VNagLang::$value_name_forbidden)); } break; case VNagArgument::VALUE_REQUIRED: if (_empty($valueName)) { throw new VNagImplementationErrorException(sprintf(VNagLang::$value_name_required)); } break; case VNagArgument::VALUE_OPTIONAL: if (_empty($valueName)) { throw new VNagImplementationErrorException(sprintf(VNagLang::$value_name_required)); } break; default: throw new VNagInvalidValuePolicy(sprintf(VNagLang::$illegal_valuepolicy, $valuePolicy)); } if (!_empty($shortopt)) { if (!self::validateShortOpt($shortopt)) { throw new VNagInvalidShortOpt(sprintf(VNagLang::$illegal_shortopt, $shortopt)); } } if (is_array($longopts)) { foreach ($longopts as $longopt) { if (!self::validateLongOpt($longopt)) { throw new VNagInvalidLongOpt(sprintf(VNagLang::$illegal_longopt, $longopt)); } } } else if (!_empty($longopts)) { if (!self::validateLongOpt($longopts)) { throw new VNagInvalidLongOpt(sprintf(VNagLang::$illegal_longopt, $longopts)); } $longopts = array($longopts); } else { $longopts = array(); } switch ($valuePolicy) { case VNagArgument::VALUE_FORBIDDEN: $policyApdx = ''; break; case VNagArgument::VALUE_REQUIRED: $policyApdx = ':'; break; case VNagArgument::VALUE_OPTIONAL: $policyApdx = '::'; break; default: throw new VNagInvalidValuePolicy(sprintf(VNagLang::$illegal_valuepolicy, $valuePolicy)); } if ((!is_null($shortopt)) && ($shortopt != '?')) self::$all_short .= $shortopt.$policyApdx; if (is_array($longopts)) { foreach ($longopts as $longopt) { self::$all_long[] = $longopt.$policyApdx; } } $this->shortopt = $shortopt; $this->longopts = $longopts; $this->valuePolicy = $valuePolicy; $this->valueName = $valueName; $this->helpText = $helpText; $this->defaultValue = $defaultValue; } protected static function getOptions() { global $OVERWRITE_ARGUMENTS; if (!is_null($OVERWRITE_ARGUMENTS)) { return $OVERWRITE_ARGUMENTS; } else if (VNag::is_http_mode()) { return $_REQUEST; } else { return getopt(self::$all_short, self::$all_long); } } public function count() { $options = self::getOptions(); $count = 0; if (isset($options[$this->shortopt])) { if (is_array($options[$this->shortopt])) { $count += count($options[$this->shortopt]); } else { $count += 1; } } if (!is_null($this->longopts)) { foreach ($this->longopts as $longopt) { if (isset($options[$longopt])) { if (is_array($options[$longopt])) { $count += count($options[$longopt]); } else { $count += 1; } } } } return $count; } public function available() { $options = self::getOptions(); if (isset($options[$this->shortopt])) return true; if (!is_null($this->longopts)) { foreach ($this->longopts as $longopt) { if (isset($options[$longopt])) return true; } } return false; } public function require() { if (!$this->available() && is_null($this->defaultValue)) { $opt = $this->shortopt; $opt = !_empty($opt) ? '-'.$opt : (isset($this->longopts[0]) ? '--'.$this->longopts[0] : '?'); throw new VNagRequiredArgumentMissing($opt); } } public function getValue() { $options = self::getOptions(); if (isset($options[$this->shortopt])) { $x = $options[$this->shortopt]; if (is_array($x) && (count($x) <= 1)) $options[$this->shortopt] = $options[$this->shortopt][0]; return $options[$this->shortopt]; } if (!is_null($this->longopts)) { foreach ($this->longopts as $longopt) { if (isset($options[$longopt])) { $x = $options[$longopt]; if (is_array($x) && (count($x) <= 1)) $options[$longopt] = $options[$longopt][0]; return $options[$longopt]; } } } return $this->defaultValue; } } class VNagArgumentHandler { protected $expectedArgs = array(); protected function _addExpectedArgument($argObj) { if ($argObj->getShortOpt() == '?') return false; if ($argObj->getShortOpt() == '-') return false; if ($argObj->getShortOpt() == '+') return false; $this->expectedArgs[] = $argObj; return true; } public function getArgumentObj($shortopt) { foreach ($this->expectedArgs as $argObj) { if ($argObj->getShortOpt() == $shortopt) return $argObj; } return null; } public function isArgRegistered($shortopt) { return !is_null($this->getArgumentObj($shortopt)); } public function illegalUsage() { global $argv; return (isset($argv[1])) && (($argv[1] == '-?') || ($argv[1] == '/?')); } } class VNagRange { public $start; public $end; public $warnInsideRange; public function __construct($rangeDef, $singleValueBehavior=VNag::SINGLEVALUE_RANGE_DEFAULT) { $m = array(); if (!preg_match('|^(@){0,1}([^:]+)(:){0,1}(.*)$|', $rangeDef, $m)) { throw new VNagInvalidRangeException(sprintf(VNagLang::$range_invalid_syntax, $rangeDef)); } $this->warnInsideRange = $m[1] === '@'; $this->start = null; $this->end = null; if ($m[3] === ':') { if ($m[2] === '~') { $this->start = '-inf'; } else { $this->start = new VNagValueUomPair($m[2]); } if (_empty($m[4])) { $this->end = 'inf'; } else { $this->end = new VNagValueUomPair($m[4]); } } else { assert(_empty($m[4])); assert(!_empty($m[2])); $x = $m[2]; if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_DEFAULT) { $this->start = new VNagValueUomPair('0'.((new VNagValueUomPair($x))->getUom())); $this->end = new VNagValueUomPair($x); } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_GT_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 0; $this->start = '-inf'; $this->end = new VNagValueUomPair($x); } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_GE_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 1; $this->start = new VNagValueUomPair($x); $this->end = 'inf'; } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_LT_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 0; $this->start = new VNagValueUomPair($x); $this->end = 'inf'; } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_LE_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 1; $this->start = '-inf'; $this->end = new VNagValueUomPair($x); } else { throw new VNagException(VNagLang::$illegalSingleValueBehavior); } } if (is_null($this->start)) { throw new VNagInvalidRangeException(VNagLang::$invalid_start_value); } if (is_null($this->end)) { throw new VNagInvalidRangeException(VNagLang::$invalid_end_value); } if (($this->start instanceof VNagValueUomPair) && ($this->end instanceof VNagValueUomPair) && (VNagValueUomPair::compare($this->start,$this->end) > 0)) { throw new VNagInvalidRangeException(VNagLang::$start_is_greater_than_end); } } public function __toString() { $ret = ''; if ($this->warnInsideRange) { $ret = '@'; } if ($this->start === '-inf') { $ret .= '~'; } else { $ret .= $this->start; } $ret .= ':'; if ($this->end !== 'inf') { $ret .= $this->end; } return $ret; } public function checkAlert($values) { $compatibleCount = 0; if (!is_array($values)) $values = array($values); foreach ($values as $value) { if (!($value instanceof VNagValueUomPair)) $value = new VNagValueUomPair($value); assert(($this->start === '-inf') || ($this->start instanceof VNagValueUomPair)); assert(($this->end === 'inf' ) || ($this->end instanceof VNagValueUomPair)); if (($this->start !== '-inf') && (!$this->start->compatibleWith($value))) continue; if (($this->end !== 'inf') && (!$this->end->compatibleWith($value))) continue; $compatibleCount++; if ($this->warnInsideRange) { return (($this->start === '-inf') || (VNagValueUomPair::compare($value,$this->start) >= 0)) && (($this->end === 'inf') || (VNagValueUomPair::compare($value,$this->end) <= 0)); } else { return (($this->start !== '-inf') && (VNagValueUomPair::compare($value,$this->start) < 0)) || (($this->end !== 'inf') && (VNagValueUomPair::compare($value,$this->end) > 0)); } } if ((count($values) > 0) and ($compatibleCount == 0)) { throw new VNagNoCompatibleRangeUomFoundException(VNagLang::$no_compatible_range_uom_found); } return false; } } class VNagValueUomPair { protected $value; protected $uom; public $roundTo = -1; public function isRelative() { return $this->uom === '%'; } public function getValue() { return $this->value; } public function getUom() { return $this->uom; } public function __toString() { if ($this->roundTo == -1) { return $this->value.$this->uom; } else { return round($this->value,$this->roundTo).$this->uom; } } public function __construct($str) { $m = array(); if (!preg_match('/^([\d\.]+)(.*)$/ism', $str, $m)) { throw new VNagValueUomPairSyntaxException($str); } $this->value = $m[1]; $this->uom = isset($m[2]) ? $m[2] : ''; if (!self::isKnownUOM($this->uom)) { throw new VNagUnknownUomException($this->uom); } } public static function isKnownUOM(string $uom) { $no_unit = ($uom === ''); $seconds = ($uom === 's') || ($uom === 'ms') || ($uom === 'us'); $percentage = ($uom === '%'); $bytes = ($uom === 'B') || ($uom === 'KB') || ($uom === 'MB') || ($uom === 'GB') || ($uom === 'TB'); $counter = ($uom === 'c'); return ($no_unit || $seconds || $percentage || $bytes || $counter); } public function normalize($target=null) { $res = clone $this; if ($res->uom === 'ms') { $res->uom = 's'; $res->value /= 1000; } if ($res->uom === 'us') { $res->uom = 's'; $res->value /= 1000 * 1000; } if ($res->uom === 'B') { $res->uom = 'MB'; $res->value /= 1024 * 1024; } if ($res->uom === 'KB') { $res->uom = 'MB'; $res->value /= 1024; } if ($res->uom === 'GB') { $res->uom = 'MB'; $res->value *= 1024; } if ($res->uom === 'TB') { $res->uom = 'MB'; $res->value *= 1024 * 1024; } if ($res->uom === 'c') { $res->uom = ''; } if (!is_null($target)) { if ($res->uom == 'MB') { if ($target == 'B') { $res->uom = 'B'; $res->value *= 1024 * 1024; } else if ($target == 'KB') { $res->uom = 'KB'; $res->value *= 1024; } else if ($target == 'MB') { $res->uom = 'MB'; $res->value *= 1; } else if ($target == 'GB') { $res->uom = 'GB'; $res->value /= 1024; } else if ($target == 'TB') { $res->uom = 'TB'; $res->value /= 1024 * 1024; } else { throw new VNagUomConvertException($res->uom, $target); } } else if ($res->uom == 's') { if ($target == 's') { $res->uom = 's'; $res->value /= 1; } else if ($target == 'ms') { $res->uom = 'ms'; $res->value /= 1000; } else if ($target == 'us') { $res->uom = 'us'; $res->value /= 1000 * 1000; } else { throw new VNagUomConvertException($res->uom, $target); } } else { throw new VNagUomConvertException($res->uom, $target); } } return $res; } public function compatibleWith(VNagValueUomPair $other) { $a = $this->normalize(); $b = $other->normalize(); return ($a->uom == $b->uom); } public static function compare(VNagValueUomPair $left, VNagValueUomPair $right) { $a = $left->normalize(); $b = $right->normalize(); if ($a->uom != $b->uom) throw new VNagMixedUomsNotImplemented($a->uom, $b->uom); if ($a->value > $b->value) return 1; if ($a->value == $b->value) return 0; if ($a->value < $b->value) return -1; } } class VNagPerformanceData { protected $label; protected $value; protected $warn = null; protected $crit = null; protected $min = null; protected $max = null; public static function createByString($perfdata) { $perfdata = trim($perfdata); $ary = explode('=',$perfdata); if (count($ary) != 2) { throw new VNagInvalidPerformanceDataException(sprintf(VNagLang::$perfdata_line_invalid, $perfdata)); } $label = $ary[0]; $bry = explode(';',$ary[1]); if (substr($label,0,1) === "'") $label = substr($label, 1, strlen($label)-2); $value = $bry[0]; $warn = isset($bry[1]) ? $bry[1] : null; $crit = isset($bry[2]) ? $bry[2] : null; $min = isset($bry[3]) ? $bry[3] : null; $max = isset($bry[4]) ? $bry[4] : null; return new self($label, $value, $warn, $crit, $min, $max); } public function __construct($label, $value, $warn=null, $crit=null, $min=null, $max=null) { if (strpos($label, '=') !== false) throw new VNagInvalidPerformanceDataException(VNagLang::$perfdata_label_equal_sign_forbidden); $label = str_replace("'", "''", $label); $m = array(); if ((!_empty($min)) && (!preg_match('|^[-0-9\\.]+$|', $min, $m))) { throw new VNagInvalidPerformanceDataException(VNagLang::$perfdata_min_must_be_in_class); } if ((!_empty($max)) && (!preg_match('|^[-0-9\\.]+$|', $max, $m))) { throw new VNagInvalidPerformanceDataException(VNagLang::$perfdata_max_must_be_in_class); } $this->label = $label; $this->value = ($value == 'U') ? 'U' : new VNagValueUomPair($value); $this->warn = $warn; $this->crit = $crit; $this->min = $min; $this->max = $max; } public function __toString() { $label = $this->label; $value = $this->value; $warn = $this->warn; $crit = $this->crit; $min = $this->min; $max = $this->max; $label = str_replace("''", "'", $label); return "'$label'=$value". ';'.(is_null($warn) ? '' : $warn). ';'.(is_null($crit) ? '' : $crit). ';'.(is_null($min) ? '' : $min). ';'.(is_null($max) ? '' : $max); } } class VNagHelp { public $word_wrap_width = 80; public $argument_indent = 7; public function printUsagePage() { $usage = $this->getUsage(); if (_empty($usage)) { $usage = VNagLang::$no_syntax_defined; } return trim($usage)."\n"; } public function printVersionPage() { $out = trim($this->getNameAndVersion())."\n"; if ($this->word_wrap_width > 0) $out = wordwrap($out, $this->word_wrap_width, "\n", false); return $out; } static private function _conditionalLine($line, $terminator='', $prefix='') { if (!_empty($line)) { return trim($line).$terminator; } return ''; } public function printHelpPage() { $out = ''; $out .= self::_conditionalLine($this->getNameAndVersion(), "\n"); $out .= self::_conditionalLine($this->getCopyright(), "\n"); $out .= ($out != '') ? "\n" : ''; $out .= self::_conditionalLine($this->getShortDescription(), "\n\n\n"); $out .= self::_conditionalLine($this->getUsage(), "\n\n"); $out .= VNagLang::$options."\n"; foreach ($this->options as $argObj) { $out .= $this->printArgumentHelp($argObj); } $out .= self::_conditionalLine($this->getFootNotes(), "\n\n", "\n"); if ($this->word_wrap_width > 0) $out = wordwrap($out, $this->word_wrap_width, "\n", false); return $out; } protected $options = array(); protected function _addOption($argObj) { $this->options[] = $argObj; } protected function printArgumentHelp($argObj) { $identifiers = array(); $shortopt = $argObj->getShortopt(); if (!_empty($shortopt)) $identifiers[] = '-'.$shortopt; $longopts = $argObj->getLongopts(); if (!is_null($longopts)) { foreach ($longopts as $longopt) { if (!_empty($longopt)) $identifiers[] = '--'.$longopt; } } if (count($identifiers) == 0) return; $valueName = $argObj->getValueName(); $arginfo = ''; switch ($argObj->getValuePolicy()) { case VNagArgument::VALUE_FORBIDDEN: $arginfo = ''; break; case VNagArgument::VALUE_REQUIRED: $arginfo = '='.$valueName; break; case VNagArgument::VALUE_OPTIONAL: $arginfo = '[='.$valueName.']'; break; } $out = ''; $out .= implode(', ', $identifiers).$arginfo."\n"; $content = trim($argObj->getHelpText()); if ($this->word_wrap_width > 0) $content = wordwrap($content, $this->word_wrap_width-$this->argument_indent, "\n", false); $lines = explode("\n", $content); foreach ($lines as $line) { $out .= str_repeat(' ', $this->argument_indent).$line."\n"; } $out .= "\n"; return $out; } protected $pluginName; public function setPluginName($pluginName) { $this->pluginName = $this->replaceStuff($pluginName); } public function getPluginName() { if (_empty($this->pluginName)) { global $argv; return basename($argv[0]); } else { return $this->pluginName; } } protected $version; public function setVersion($version) { $this->version = $this->replaceStuff($version); } public function getVersion() { return $this->version; } public function getNameAndVersion() { $ret = $this->getPluginName(); if (_empty($ret)) return null; $ver = $this->getVersion(); if (!_empty($ver)) { $ret = sprintf(VNagLang::$x_version_x, $ret, $ver); } $ret = trim($ret); return $ret; } protected $copyright; public function setCopyright($copyright) { $this->copyright = $this->replaceStuff($copyright); } private function getVNagCopyright() { if (VNag::is_http_mode()) { $vts_email = 'www.viathinksoft.com'; } else { $vts_email = base64_decode('aW5mb0B2aWF0aGlua3NvZnQuZGU='); } return "VNag Framework ".VNag::VNAG_VERSION." (C) 2014-".date('Y')." ViaThinkSoft <$vts_email>"; } public function getCopyright() { if (_empty($this->copyright)) { return sprintf(VNagLang::$plugin_uses, $this->getVNagCopyright()); } else { return trim($this->copyright)."\n".sprintf(VNagLang::$uses, $this->getVNagCopyright()); } } protected $shortDescription; public function setShortDescription($shortDescription) { $this->shortDescription = $this->replaceStuff($shortDescription); } public function getShortDescription() { if (_empty($this->shortDescription)) { return null; } else { $content = $this->shortDescription; if ($this->word_wrap_width > 0) $content = wordwrap($content, $this->word_wrap_width, "\n", false); return $content; } } protected function replaceStuff($text) { global $argv; if (php_sapi_name() == 'cli') { $text = str_replace('$SCRIPTNAME$', $argv[0], $text); } else { $text = str_replace('$SCRIPTNAME$', basename($_SERVER['SCRIPT_NAME']), $text); } $text = str_replace('$CURYEAR$', date('Y'), $text); return $text; } protected $syntax; public function setSyntax($syntax) { $syntax = $this->replaceStuff($syntax); $this->syntax = $syntax; } public function getUsage() { if (_empty($this->syntax)) { return null; } else { return sprintf(VNagLang::$usage_x, $this->syntax); } } protected $footNotes; public function setFootNotes($footNotes) { $this->footNotes = $this->replaceStuff($footNotes); } public function getFootNotes() { return $this->footNotes; } } class VNagLang { public static function status($code, $statusmodel) { switch ($statusmodel) { case VNag::STATUSMODEL_SERVICE: switch ($code) { case VNag::STATUS_OK: return 'OK'; case VNag::STATUS_WARNING: return 'Warning'; case VNag::STATUS_CRITICAL: return 'Critical'; case VNag::STATUS_UNKNOWN: return 'Unknown'; default: return sprintf('Error (%d)', $code); } case VNag::STATUSMODEL_HOST: switch ($code) { case VNag::STATUS_UP: return 'Up'; case VNag::STATUS_DOWN: return 'Down'; default: return sprintf('Maintain last state (%d)', $code); } default: throw new VNagIllegalStatusModel(sprintf(self::$illegal_statusmodel, $statusmodel)); } } static $nagios_output = 'VNag-Output'; static $verbose_info = 'Verbose information'; static $status = 'Status'; static $message = 'Message'; static $performance_data = 'Performance data'; static $status_ok = 'OK'; static $status_warn = 'Warning'; static $status_critical = 'Critical'; static $status_unknown = 'Unknown'; static $status_error = 'Error'; static $unhandled_exception_without_msg = "Unhandled exception of type %s"; static $plugin_uses = 'This plugin uses %s'; static $uses = 'uses %s'; static $x_version_x = '%s, version %s'; static $argname_value = 'value'; static $argname_seconds = 'seconds'; static $query_without_expected_argument = "The argument '%s' is queried, but was not added to the list of expected arguments. Please contact the plugin author."; static $required_argument_missing = "The argument '%s' is required."; static $performance_data_invalid = 'Performance data invalid.'; static $no_standard_arguments_with_letter = "No standard argument with letter '%s' exists."; static $invalid_start_value = 'Invalid start value.'; static $invalid_end_value = 'Invalid end value.'; static $start_is_greater_than_end = 'Start is greater than end value.'; static $value_name_forbidden = "Implementation error: You may not define a value name for the argument, because the value policy is VALUE_FORBIDDEN."; static $value_name_required = "Implementation error: Please define a name for the argument (so it can be shown in the help page)."; static $illegal_shortopt = "Illegal shortopt '-%s'."; static $illegal_longopt = "Illegal longopt '--%s'."; static $illegal_valuepolicy = "valuePolicy has illegal value '%s'."; static $range_invalid_syntax = "Syntax error in range '%s'."; static $timeout_value_invalid = "Timeout value '%s' is invalid."; static $range_is_invalid = 'Range is invalid.'; static $timeout_exception = 'Timeout!'; static $perfdata_label_equal_sign_forbidden = 'Label may not contain an equal sign.'; static $perfdata_value_must_be_in_class = 'Value must be in class [-0-9.] or be \'U\' if the actual value can\'t be determined.'; static $perfdata_min_must_be_in_class = 'Min must be in class [-0-9.] or empty.'; static $perfdata_max_must_be_in_class = 'Max must be in class [-0-9.] or empty.'; static $perfdata_uom_not_recognized = 'UOM (unit of measurement) "%s" is not recognized.'; static $perfdata_mixed_uom_not_implemented = 'Mixed UOMs (%s and %s) are currently not supported.'; static $no_compatible_range_uom_found = 'Measured values are not compatible with the provided warning/critical parameter. Most likely, the UOM is incompatible.'; static $exception_x = '%s (%s)'; static $no_syntax_defined = 'The author of this plugin has not defined a syntax for this plugin.'; static $usage_x = "Usage:\n%s"; static $options = "Options:"; static $illegal_statusmodel = "Invalid statusmodel %d."; static $none = '[none]'; static $valueUomPairSyntaxError = 'Syntax error at "%s". Syntax must be Value[UOM].'; static $too_few_warning_ranges = "You have too few warning ranges (currently trying to get element %d)."; static $too_few_critical_ranges = "You have too few critical ranges (currently trying to get element %d)."; static $dataset_missing = 'Dataset missing.'; static $payload_not_base64 = 'The payload is not valid Base64.'; static $payload_not_json = 'The payload is not valid JSON.'; static $signature_missing = 'The signature is missing.'; static $signature_not_bas64 = 'The signature is not valid Base64.'; static $signature_invalid = 'The signature is invalid. The connection might have been tampered, or a different key is used.'; static $pubkey_file_not_found = "Public key file %s was not found."; static $pubkey_file_not_readable = "Public key file %s is not readable."; static $privkey_file_not_found = "Private key file %s was not found."; static $privkey_not_readable = "Private key is not readable."; static $privkey_file_not_readable = "Private key file %s is not readable."; static $signature_failed = "Signature failed."; static $perfdata_line_invalid = "Performance data line %s is invalid."; static $singlevalue_unexpected_at_symbol = 'This plugin does not allow the @-symbol at ranges for single values.'; static $illegalSingleValueBehavior = "Illegal value for 'singleValueBehavior'. Please contact the creator of the plugin."; static $dataset_encryption_no_array = 'Dataset encryption information invalid.'; static $require_password = 'This resource is protected with a password. Please provide a password.'; static $wrong_password = 'This resource is protected with a password. You have provided the wrong password, or it was changed.'; static $convert_x_y_error = 'Cannot convert from UOM %s to UOM %s.'; static $php_error = 'PHP has detected an error in the plugin. Please contact the plugin author.'; static $output_level_lowered = "Output Buffer level lowered during cbRun(). Please contact the plugin author."; static $openssl_missing = "OpenSSL is missing. Therefore, encryption and signatures are not available."; static $warning_range = 'Warning range'; static $critical_range = 'Critical range'; static $prints_version = 'Prints version'; static $verbosity_helptext = 'Verbosity -v, -vv or -vvv'; static $timeout_helptext = 'Sets timeout in seconds'; static $help_helptext = 'Prints help page'; static $prints_usage = 'Prints usage'; static $notConstructed = 'Parent constructor not called with parent::__construct().'; } function vnagErrorHandler($errorkind, $errortext, $file, $line) { global $inside_vnag_run; if (!$inside_vnag_run && VNag::is_http_mode()) { return false; } if (!(error_reporting() & $errorkind)) { return true; } if (defined('E_ERROR') && ($errorkind == E_ERROR)) $errorkind = 'Error'; if (defined('E_WARNING') && ($errorkind == E_WARNING)) $errorkind = 'Warning'; if (defined('E_PARSE') && ($errorkind == E_PARSE)) $errorkind = 'Parse'; if (defined('E_NOTICE') && ($errorkind == E_NOTICE)) $errorkind = 'Notice'; if (defined('E_CORE_ERROR') && ($errorkind == E_CORE_ERROR)) $errorkind = 'Core Error'; if (defined('E_CORE_WARNING') && ($errorkind == E_CORE_WARNING)) $errorkind = 'Core Warning'; if (defined('E_COMPILE_ERROR') && ($errorkind == E_COMPILE_ERROR)) $errorkind = 'Compile Error'; if (defined('E_COMPILE_WARNING') && ($errorkind == E_COMPILE_WARNING)) $errorkind = 'Compile Warning'; if (defined('E_USER_ERROR') && ($errorkind == E_USER_ERROR)) $errorkind = 'User Error'; if (defined('E_USER_WARNING') && ($errorkind == E_USER_WARNING)) $errorkind = 'User Warning'; if (defined('E_USER_NOTICE') && ($errorkind == E_USER_NOTICE)) $errorkind = 'User Notice'; if (defined('E_STRICT') && ($errorkind == E_STRICT)) $errorkind = 'Strict'; if (defined('E_RECOVERABLE_ERROR') && ($errorkind == E_RECOVERABLE_ERROR)) $errorkind = 'Recoverable Error'; if (defined('E_DEPRECATED') && ($errorkind == E_DEPRECATED)) $errorkind = 'Deprecated'; if (defined('E_USER_DEPRECATED') && ($errorkind == E_USER_DEPRECATED)) $errorkind = 'User Deprecated'; throw new VNagException(VNagLang::$php_error . " $errortext at $file:$line (kind $errorkind)"); } $inside_vnag_run = false; $old_error_handler = set_error_handler("vnagErrorHandler"); <?php
declare(ticks=1); class ViewVCVersionCheck extends VNag { protected $argSystemDir = null; public function __construct() { parent::__construct(); $this->registerExpectedStandardArguments('Vht'); $this->getHelpManager()->setPluginName('check_viewvc_version'); $this->getHelpManager()->setVersion('2023-10-13'); $this->getHelpManager()->setShortDescription('This plugin checks if a local ViewVC system has the latest version installed.'); $this->getHelpManager()->setCopyright('Copyright (C) 2011-$CURYEAR$ Daniel Marschall, ViaThinkSoft.'); $this->getHelpManager()->setSyntax('$SCRIPTNAME$ [-d <directory>]'); $this->getHelpManager()->setFootNotes('If you encounter bugs, please contact ViaThinkSoft at www.viathinksoft.com'); $this->addExpectedArgument($this->argSystemDir = new VNagArgument('d', 'directory', VNagArgument::VALUE_REQUIRED, 'viewvcPath', 'The local directory where your ViewVC installation is located.')); } protected function get_local_version($path) { $path = realpath($path) === false ? $path : realpath($path); if (!file_exists("$path/lib/viewvc.py")) { throw new VNagException("Cannot find ViewVC settings file at $path"); } $cont = @file_get_contents("$path/lib/viewvc.py"); if ($cont === false) { throw new VNagException("Cannot determine version for system $path (cannot read viewvc.py)"); } if (!preg_match('@__version__\\s*=\\s*([\'"])(.+)\\1@ismU', $cont, $m)) { throw new VNagException("Cannot determine version for system $path (cannot find version string)"); } return $m[2]; } protected function get_latest_version() { $cont = $this->url_get_contents('https://api.github.com/repos/viewvc/viewvc/releases/latest'); if ($cont === false) { throw new VNagException('Cannot parse version from GitHub API. The plugin probably needs to be updated. (Cannot access api.github.com)'); } $data = @json_decode($cont, true); if ($data === false) { throw new VNagException('Cannot parse version from GitHub API. The plugin probably needs to be updated. (Invalid JSON data downloaded from api.github.com)'); } return $data['tag_name']; } protected function cbRun($optional_args=array()) { $system_dir = $this->argSystemDir->getValue(); if (empty($system_dir)) { throw new VNagException("Please specify the directory of the ViewVC installation."); } $system_dir = realpath($system_dir) === false ? $system_dir : realpath($system_dir); if (!is_dir($system_dir)) { throw new VNagException('Directory "'.$system_dir.'" not found.'); } $local_version = $this->get_local_version($system_dir); $latest_stable = $this->get_latest_version(); if (version_compare($local_version,$latest_stable,'>')) { $this->setStatus(VNag::STATUS_OK); $this->setHeadline("Version $local_version (Latest stable version $latest_stable) at $system_dir", true); } else if (version_compare($local_version,$latest_stable,'=')) { $this->setStatus(VNag::STATUS_OK); $this->setHeadline("Version $local_version (Latest stable version) at $system_dir", true); } else { $this->setStatus(VNag::STATUS_WARNING); $this->setHeadline("Version $local_version is outdated (Latest version is $latest_stable) at $system_dir", true); } } } <?php
declare(ticks=1); require_once __DIR__ . '/../../framework/vnag_framework.inc.php'; require_once __DIR__ . '/ViewVCVersionCheck.class.php'; $job = new ViewVCVersionCheck(); $job->run(); unset($job); -«èßwðôªï—ÁûÃØvªÛõýaê‡áBU¨/þáJqbvXGÄ3@"&˜Ø£öÔï¯í%®S…–SRµGBMB
declare(ticks=1); require_once __DIR__ . '/../../framework/vnag_framework.inc.php'; require_once __DIR__ . '/ViewVCVersionCheck.class.php'; $job = new ViewVCVersionCheck(); $job->run(); unset($job); ”XÇr;Ø¥8%±ü(ÚIÅ?Ê÷µ% j IyŒ›Qޘv–b<ÞZÜ´øe,hr»'(ãçø9ý~䗺û~GBMB
/trunk/bin/virtual_mem.phar
291,8 → 291,7
 
Extract_Phar::go();
__HALT_COMPILER(); ?>
Sva:1:{s:23:"1.3.6.1.4.1.37476.3.0.2";s:328:"sha256||framework/vnag_framework.inc.php|460b109d1c578e9b6af41612e0312c9f36fd8beb51f7aa92f1b7bd49614568e8||plugins/virtual_mem/VirtualMemCheck.class.php|96f7110595aa3d664915fbfc26b735925db932afd0ef2f173823cd76be7ccde0||plugins/virtual_mem/check_virtual_mem.phps|16e806edb56f695bae1ca5ab17fb077b26ec4847ce20db5a5a35cffc9287f6df||";} framework/vnag_framework.inc.phpLÙzï*eLُ4p”¤-plugins/virtual_mem/VirtualMemCheck.class.phpŒ zï*eŒ y’RM¤*plugins/virtual_mem/check_virtual_mem.phpsÈzï*eÈ{¤<?php ?>
<?php
ŸÂa:1:{s:23:"1.3.6.1.4.1.37476.3.0.2";s:404:"sha256||<builder>|481cf75d675006b504520fd2acb3b29c89aea03aab64754e0adfb364de4914b2||framework/vnag_framework.inc.php|0387bf3134f8cc2d1ae24e139019c0edef19c1ba5ca765624efea0b469c7897f||plugins/virtual_mem/VirtualMemCheck.class.php|96f7110595aa3d664915fbfc26b735925db932afd0ef2f173823cd76be7ccde0||plugins/virtual_mem/check_virtual_mem.phps|16e806edb56f695bae1ca5ab17fb077b26ec4847ce20db5a5a35cffc9287f6df||";} framework/vnag_framework.inc.phpBÙ» +eBÙÞß=¤-plugins/virtual_mem/VirtualMemCheck.class.phpŒ » +eŒ y’RM¤*plugins/virtual_mem/check_virtual_mem.phpsÈ» +eÈ{¤<?php
if (!VNag::is_http_mode()) error_reporting(E_ALL); declare(ticks=1); set_time_limit(0); define('VNAG_JSONDATA_V1', 'oid:1.3.6.1.4.1.37476.2.3.1.1'); $OVERWRITE_ARGUMENTS = null; function _empty($x) { return is_null($x) || (trim($x) == ''); } abstract class VNag { const VNAG_VERSION = '2023-10-13'; const STATUS_OK = 0; const STATUS_WARNING = 1; const STATUS_CRITICAL = 2; const STATUS_UNKNOWN = 3; const STATUS_ERROR = 4; const STATUS_UP = 0; const STATUS_DOWN = 1; const STATUS_MAINTAIN = 2; const VERBOSITY_SUMMARY = 0; const VERBOSITY_ADDITIONAL_INFORMATION = 1; const VERBOSITY_CONFIGURATION_DEBUG = 2; const VERBOSITY_PLUGIN_DEBUG = 3; const MAX_VERBOSITY = self::VERBOSITY_PLUGIN_DEBUG; const STATUSMODEL_SERVICE = 0; const STATUSMODEL_HOST = 1; private $initialized = false; private $status = null; private $messages = array(); private $verbose_info = ''; private $warningRanges = array(); private $criticalRanges = array(); private $performanceDataObjects = array(); private static $exitcode = 0; private $helpObj = null; private $argHandler = null; const OUTPUT_NEVER = 0; const OUTPUT_SPECIAL = 1; const OUTPUT_NORMAL = 2; const OUTPUT_EXCEPTION = 4; const OUTPUT_ALWAYS = 7; public $http_visual_output = self::OUTPUT_ALWAYS; public $http_invisible_output = self::OUTPUT_ALWAYS; protected $html_before = ''; protected $html_after = ''; protected $statusmodel = self::STATUSMODEL_SERVICE; protected $show_status_in_headline = true; protected $default_status = self::STATUS_UNKNOWN; protected $default_warning_range = null; protected $default_critical_range = null; protected $argWarning; protected $argCritical; protected $argVersion; protected $argVerbosity; protected $argTimeout; protected $argHelp; protected $argUsage; public $id = null; protected static $http_serial_number = 0; public $privkey = null; public $privkey_password = null; public $sign_algo = null; public $pubkey = null; protected $warningSingleValueRangeBehaviors = array(self::SINGLEVALUE_RANGE_DEFAULT); protected $criticalSingleValueRangeBehaviors = array(self::SINGLEVALUE_RANGE_DEFAULT); const SINGLEVALUE_RANGE_DEFAULT = 0; const SINGLEVALUE_RANGE_VAL_GT_X_BAD = 1; const SINGLEVALUE_RANGE_VAL_GE_X_BAD = 2; const SINGLEVALUE_RANGE_VAL_LT_X_BAD = 3; const SINGLEVALUE_RANGE_VAL_LE_X_BAD = 4; public $password_out = null; public $password_in = null; public static function is_http_mode() { return php_sapi_name() !== 'cli'; } public function getHelpManager() { return $this->helpObj; } public function getArgumentHandler() { return $this->argHandler; } public function outputHTML($text, $after_visual_output=true) { if ($this->is_http_mode()) { if ($this->initialized) { if ($after_visual_output) { $this->html_after .= $text; } else { $this->html_before .= $text; } } else { echo $text; } } } protected function resetArguments() { $this->argWarning = null; $this->argCritical = null; $this->argVersion = null; $this->argVerbosity = null; $this->argTimeout = null; $this->argHelp = null; $this->argWarning = null; $this->argCritical = null; } public function registerExpectedStandardArguments($args) { $this->resetArguments(); for ($i=0; $i<strlen($args); $i++) { switch ($args[$i]) { case 'w': $this->addExpectedArgument($this->argWarning = new VNagArgument('w', 'warning', VNagArgument::VALUE_REQUIRED, VNagLang::$argname_value, VNagLang::$warning_range)); break; case 'c': $this->addExpectedArgument($this->argCritical = new VNagArgument('c', 'critical', VNagArgument::VALUE_REQUIRED, VNagLang::$argname_value, VNagLang::$critical_range)); break; case 'V': $this->addExpectedArgument($this->argVersion = new VNagArgument('V', 'version', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$prints_version)); break; case 'v': $this->addExpectedArgument($this->argVerbosity = new VNagArgument('v', 'verbose', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$verbosity_helptext)); break; case 't': $this->addExpectedArgument($this->argTimeout = new VNagArgument('t', 'timeout', VNagArgument::VALUE_REQUIRED, VNagLang::$argname_seconds, VNagLang::$timeout_helptext)); break; case 'h': $this->addExpectedArgument($this->argHelp = new VNagArgument('h', 'help', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$help_helptext)); break; default: $letter = $args[$i]; throw new VNagInvalidStandardArgument(sprintf(VNagLang::$no_standard_arguments_with_letter, $letter)); } } } public function addExpectedArgument($argObj) { $helpObjAddEntryMethod = new ReflectionMethod($this->helpObj, '_addOption'); $helpObjAddEntryMethod->setAccessible(true); $helpObjAddEntryMethod->invoke($this->helpObj, $argObj); $argHandlerAddEntryMethod = new ReflectionMethod($this->argHandler, '_addExpectedArgument'); $argHandlerAddEntryMethod->setAccessible(true); $argHandlerAddEntryMethod->invoke($this->argHandler, $argObj); } protected function createArgumentHandler() { $this->argHandler = new VNagArgumentHandler(); } protected function createHelpObject() { $this->helpObj = new VNagHelp(); } protected function checkInitialized() { if (!$this->initialized) throw new VNagFunctionCallOutsideSession(); } protected function getVerbosityLevel() { $this->checkInitialized(); if (!isset($this->argVerbosity)) { return self::VERBOSITY_SUMMARY; } else { $level = $this->argVerbosity->count(); if ($level > self::MAX_VERBOSITY) $level = self::MAX_VERBOSITY; return $level; } } public function getWarningRange($argumentNumber=0) { $this->checkInitialized(); if (!isset($this->warningRanges[$argumentNumber])) { if (!is_null($this->argWarning)) { $warning = $this->argWarning->getValue(); if (!is_null($warning)) { $vals = explode(',',$warning); foreach ($vals as $number => $val) { if (_empty($val)) { $this->warningRanges[$number] = null; } else { $singleValueBehavior = isset($this->warningSingleValueRangeBehaviors[$number]) ? $this->warningSingleValueRangeBehaviors[$number] : VNag::SINGLEVALUE_RANGE_DEFAULT; $this->warningRanges[$number] = new VNagRange($val, $singleValueBehavior); } } } else { $this->warningRanges[0] = $this->default_warning_range; } } else { return null; } } if (isset($this->warningRanges[$argumentNumber])) { return $this->warningRanges[$argumentNumber]; } else { return null; } } public function getCriticalRange($argumentNumber=0) { $this->checkInitialized(); if (!isset($this->criticalRanges[$argumentNumber])) { if (!is_null($this->argCritical)) { $critical = $this->argCritical->getValue(); if (!is_null($critical)) { $vals = explode(',',$critical); foreach ($vals as $number => $val) { $singleValueBehavior = isset($this->criticalSingleValueRangeBehaviors[$number]) ? $this->criticalSingleValueRangeBehaviors[$number] : VNag::SINGLEVALUE_RANGE_DEFAULT; $this->criticalRanges[$number] = new VNagRange($val, $singleValueBehavior); } } else { $this->criticalRanges[0] = $this->default_critical_range; } } else { return null; } } if (isset($this->criticalRanges[$argumentNumber])) { return $this->criticalRanges[$argumentNumber]; } else { return null; } } public function checkAgainstWarningRange($values, $force=true, $autostatus=true, $argumentNumber=0) { $this->checkInitialized(); if (!$this->getArgumentHandler()->isArgRegistered('w')) { throw new VNagRequiredArgumentNotRegistered('-w'); } $wr = $this->getWarningRange($argumentNumber); if (isset($wr)) { if ($wr->checkAlert($values)) { if ($autostatus) $this->setStatus(VNag::STATUS_WARNING); return true; } else { if ($autostatus) $this->setStatus(VNag::STATUS_OK); return false; } } else { if ($force) { if (($argumentNumber > 0) && (count($this->warningRanges) > 0)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$too_few_warning_ranges, $argumentNumber+1)); } else { throw new VNagRequiredArgumentMissing('-w'); } } } } public function checkAgainstCriticalRange($values, $force=true, $autostatus=true, $argumentNumber=0) { $this->checkInitialized(); if (!$this->getArgumentHandler()->isArgRegistered('c')) { throw new VNagRequiredArgumentNotRegistered('-c'); } $cr = $this->getCriticalRange($argumentNumber); if (isset($cr)) { if ($cr->checkAlert($values)) { if ($autostatus) $this->setStatus(VNag::STATUS_CRITICAL); return true; } else { if ($autostatus) $this->setStatus(VNag::STATUS_OK); return false; } } else { if ($force) { if (($argumentNumber > 0) && (count($this->warningRanges) > 0)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$too_few_critical_ranges, $argumentNumber+1)); } else { throw new VNagRequiredArgumentMissing('-c'); } } } } protected static function getBaddestExitcode($code1, $code2) { return max($code1, $code2); } public static function _shutdownHandler() { if (!self::is_http_mode()) { exit((int)self::$exitcode); } } protected function _exit($code) { self::$exitcode = $this->getBaddestExitcode($code, self::$exitcode); } private $constructed = false; function __construct() { $this->createHelpObject(); $this->createArgumentHandler(); $this->addExpectedArgument($this->argUsage = new VNagArgument('?', '', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$prints_usage)); $this->constructed = true; } function __destruct() { if (Timeouter::started()) { Timeouter::end(); } } public function run() { global $inside_vnag_run; $inside_vnag_run = true; try { if (!$this->constructed) { throw new VNagNotConstructed(VNagLang::$notConstructed); } try { $this->initialized = true; $this->html_before = ''; $this->html_after = ''; $this->setStatus(null, true); $this->messages = array(); register_shutdown_function(array($this, '_shutdownHandler')); if ($this->argHandler->illegalUsage()) { $content = $this->helpObj->printUsagePage(); $this->setStatus(VNag::STATUS_UNKNOWN); if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_visual_output & VNag::OUTPUT_SPECIAL) echo $this->writeVisualHTML($content); if ($this->http_invisible_output & VNag::OUTPUT_SPECIAL) echo $this->writeInvisibleHTML($content); echo $this->html_after; return; } else { echo $content; return $this->_exit($this->status); } } if (!is_null($this->argVersion) && ($this->argVersion->available())) { $content = $this->helpObj->printVersionPage(); $this->setStatus(VNag::STATUS_UNKNOWN); if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_visual_output & VNag::OUTPUT_SPECIAL) echo $this->writeVisualHTML($content); if ($this->http_invisible_output & VNag::OUTPUT_SPECIAL) echo $this->writeInvisibleHTML($content); echo $this->html_after; return; } else { echo $content; return $this->_exit($this->status); } } if (!is_null($this->argHelp) && ($this->argHelp->available())) { $content = $this->helpObj->printHelpPage(); $this->setStatus(VNag::STATUS_UNKNOWN); if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_visual_output & VNag::OUTPUT_SPECIAL) echo $this->writeVisualHTML($content); if ($this->http_invisible_output & VNag::OUTPUT_SPECIAL) echo $this->writeInvisibleHTML($content); echo $this->html_after; return; } else { echo $content; return $this->_exit($this->status); } } $this->getWarningRange(); $this->getCriticalRange(); if (!is_null($this->argTimeout)) { $timeout = $this->argTimeout->getValue(); if (!is_null($timeout)) { Timeouter::start($timeout); } } ob_start(); $init_ob_level = ob_get_level(); try { $this->cbRun(); if (ob_get_level() < $init_ob_level) throw new VNagImplementationErrorException(VNagLang::$output_level_lowered); } finally { while (ob_get_level() > $init_ob_level) @ob_end_clean(); } if (is_null($this->status)) $this->setStatus($this->default_status,true); $outputType = VNag::OUTPUT_NORMAL; } catch (Exception $e) { $this->handleException($e); $outputType = VNag::OUTPUT_EXCEPTION; } if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_invisible_output & $outputType) { echo $this->writeInvisibleHTML(); } if ($this->http_visual_output & $outputType) { echo $this->writeVisualHTML(); } echo $this->html_after; } else { echo $this->getNagiosConsoleText(); return $this->_exit($this->status); } Timeouter::end(); } finally { $inside_vnag_run = false; } } private function getNagiosConsoleText() { $ary_perfdata = $this->getPerformanceData(); $performancedata_first = array_shift($ary_perfdata); $performancedata_rest = implode(' ', $ary_perfdata); $status_text = VNagLang::status($this->status, $this->statusmodel); if (_empty($this->getHeadline())) { $content = $status_text; } else { if ($this->show_status_in_headline) { $content = $status_text.': '.$this->getHeadline(); } else { $content = $this->getHeadline(); } } if (!_empty($performancedata_first)) $content .= '|'.trim($performancedata_first); $content .= "\n"; if (!_empty($this->verbose_info)) { $content .= trim($this->verbose_info); } if (!_empty($performancedata_rest)) $content .= '|'.trim($performancedata_rest); $content .= "\n"; return trim($content)."\n"; } abstract protected function cbRun(); public function addPerformanceData($prefDataObj, $move_to_font=false, $verbosityLevel=VNag::VERBOSITY_SUMMARY) { $this->checkInitialized(); if ((!isset($this->argVerbosity)) && ($verbosityLevel > VNag::VERBOSITY_SUMMARY)) throw new VNagRequiredArgumentNotRegistered('-v'); if (self::getVerbosityLevel() < $verbosityLevel) return false; if ($move_to_font) { array_unshift($this->performanceDataObjects, $prefDataObj); } else { $this->performanceDataObjects[] = $prefDataObj; } return true; } public function getPerformanceData() { $this->checkInitialized(); return $this->performanceDataObjects; } public function removePerformanceData($prefDataObj) { if (($key = array_search($prefDataObj, $this->performanceDataObjects, true)) !== false) { unset($this->performanceDataObjects[$key]); return true; } else { return false; } } public function clearPerformanceData() { $this->performanceDataObjects = array(); } public function getVerboseInfo() { return $this->verbose_info; } public function clearVerboseInfo() { $this->verbose_info = ''; } private function writeVisualHTML($special_content=null) { if (!_empty($special_content)) { $content = $special_content; } else { $content = strtoupper(VNagLang::$status.': '.VNagLang::status($this->status, $this->statusmodel))."\n\n"; $content .= strtoupper(VNagLang::$message).":\n"; $status_text = VNagLang::status($this->status, $this->statusmodel); if (_empty($this->getHeadline())) { $content .= $status_text; } else { if ($this->show_status_in_headline) { $content .= $status_text.': '.trim($this->getHeadline()); } else { $content .= trim($this->getHeadline()); } } $content .= "\n\n"; if (!_empty($this->verbose_info)) { $content .= strtoupper(VNagLang::$verbose_info).":\n".trim($this->verbose_info)."\n\n"; } $perfdata = $this->getPerformanceData(); if (count($perfdata) > 0) { $content .= strtoupper(VNagLang::$performance_data).":\n"; foreach ($perfdata as $pd) { $content .= trim($pd)."\n"; } $content .= "\n"; } } $colorinfo = ''; $status = $this->getStatus(); if ($status == VNag::STATUS_OK) $colorinfo = ' style="background-color:green;color:white;font-weight:bold"'; else if ($status == VNag::STATUS_WARNING) $colorinfo = ' style="background-color:yellow;color:black;font-weight:bold"'; else if ($status == VNag::STATUS_CRITICAL) $colorinfo = ' style="background-color:red;color:white;font-weight:bold"'; else if ($status == VNag::STATUS_ERROR) $colorinfo = ' style="background-color:purple;color:white;font-weight:bold"'; else $colorinfo = ' style="background-color:lightgray;color:black;font-weight:bold"'; $html_content = trim($content); $html_content = htmlentities($html_content); $html_content = str_replace(' ', '&nbsp;', $html_content); $html_content = nl2br($html_content); return '<table border="1" cellspacing="2" cellpadding="2" style="width:100%" class="vnag_table">'. '<tr'.$colorinfo.' class="vnag_title_row">'. '<td>'.VNagLang::$nagios_output.'</td>'. '</tr>'. '<tr class="vnag_message_row">'. '<td><code>'. $html_content. '</code></td>'. '</tr>'. '</table>'; } protected function readInvisibleHTML($html) { $this->checkInitialized(); $doc = new DOMDocument(); @$doc->loadHTML($html); $tags = $doc->getElementsByTagName('script'); foreach ($tags as $tag) { $type = $tag->getAttribute('type'); if ($type !== 'application/json') continue; $json = $tag->nodeValue; if (!$json) continue; $data = @json_decode($json,true); if (!is_array($data)) continue; if (!isset($data['type'])) continue; if ($data['type'] === VNAG_JSONDATA_V1) { if (!isset($data['datasets'])) throw new VNagWebInfoException(VNagLang::$dataset_missing); foreach ($data['datasets'] as $dataset) { $payload = base64_decode($dataset['payload']); if (!$payload) { throw new VNagWebInfoException(VNagLang::$payload_not_base64); } if (isset($dataset['encryption'])) { $cryptInfo = $dataset['encryption']; if (!is_array($cryptInfo)) { throw new VNagWebInfoException(VNagLang::$dataset_encryption_no_array); } $password = is_null($this->password_in) ? '' : $this->password_in; $salt = base64_decode($cryptInfo['salt']); if ($cryptInfo['hash'] != hash('sha256',$salt.$password)) { if ($password == '') { throw new VNagWebInfoException(VNagLang::$require_password); } else { throw new VNagWebInfoException(VNagLang::$wrong_password); } } if (!function_exists('openssl_decrypt')) { throw new VNagException(VNagLang::$openssl_missing); } $payload = openssl_decrypt($payload, $cryptInfo['method'], $password, 0, $cryptInfo['iv']); } if (!is_null($this->pubkey) && ($this->pubkey !== '')) { if (substr($this->pubkey,0,3) === '---') { $public_key = $this->pubkey; } else { if (!file_exists($this->pubkey)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$pubkey_file_not_found, $this->pubkey)); } $public_key = @file_get_contents($this->pubkey); if (!$public_key) { throw new VNagPublicKeyException(sprintf(VNagLang::$pubkey_file_not_readable, $this->pubkey)); } } if (!isset($dataset['signature'])) { throw new VNagSignatureException(VNagLang::$signature_missing); } $signature = base64_decode($dataset['signature']); if (!$signature) { throw new VNagSignatureException(VNagLang::$signature_not_bas64); } if (!function_exists('openssl_verify')) { throw new VNagException(VNagLang::$openssl_missing); } $sign_algo = is_null($this->sign_algo) ? OPENSSL_ALGO_SHA256 : $this->sign_algo; if (!openssl_verify($payload, $signature, $public_key, $sign_algo)) { throw new VNagSignatureException(VNagLang::$signature_invalid); } } $payload = @json_decode($payload,true); if (!$payload) { throw new VNagWebInfoException(VNagLang::$payload_not_json); } if ($payload['id'] == $this->id) { return $payload; } } } } return null; } private function getNextMonitorID($peek=false) { $result = is_null($this->id) ? self::$http_serial_number : $this->id; if (!$peek) { $this->id = null; self::$http_serial_number++; } return $result; } private function writeInvisibleHTML($special_content=null) { $payload['id'] = $this->getNextMonitorID(); $payload['status'] = $this->getStatus(); if (!_empty($special_content)) { $payload['text'] = $special_content; } else { $payload['headline'] = $this->getHeadline(); $payload['verbose_info'] = $this->verbose_info; $payload['performance_data'] = array(); foreach ($this->performanceDataObjects as $perfdata) { $payload['performance_data'][] = (string)$perfdata; } } $payload = json_encode($payload); $dataset = array(); if (!is_null($this->privkey) && ($this->privkey !== '')) { if (!function_exists('openssl_pkey_get_private') || !function_exists('openssl_sign')) { throw new VNagException(VNagLang::$openssl_missing); } if (substr($this->privkey,0,3) === '---') { $pkeyid = @openssl_pkey_get_private($this->privkey, $this->privkey_password); if (!$pkeyid) { throw new VNagPrivateKeyException(sprintf(VNagLang::$privkey_not_readable)); } } else { if (!file_exists($this->privkey)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$privkey_file_not_found, $this->privkey)); } $pkeyid = @openssl_pkey_get_private('file://'.$this->privkey, $this->privkey_password); if (!$pkeyid) { throw new VNagPrivateKeyException(sprintf(VNagLang::$privkey_file_not_readable, $this->privkey)); } } $signature = ''; $sign_algo = is_null($this->sign_algo) ? OPENSSL_ALGO_SHA256 : $this->sign_algo; if (@openssl_sign($payload, $signature, $pkeyid, $sign_algo)) { if (version_compare(PHP_VERSION, '8.0.0') < 0) { openssl_free_key($pkeyid); } $dataset['signature'] = base64_encode($signature); } else { throw new VNagPrivateKeyException(sprintf(VNagLang::$signature_failed)); } } if (!is_null($this->password_out) && ($this->password_out !== '')) { if (!function_exists('openssl_encrypt')) { throw new VNagException(VNagLang::$openssl_missing); } $password = $this->password_out; $method = 'aes-256-ofb'; $iv = substr(hash('sha256', openssl_random_pseudo_bytes(32)), 0, 16); $salt = openssl_random_pseudo_bytes(32); $cryptInfo = array(); $cryptInfo['method'] = $method; $cryptInfo['iv'] = $iv; $cryptInfo['salt'] = base64_encode($salt); $cryptInfo['hash'] = hash('sha256', $salt.$password); $payload = openssl_encrypt($payload, $method, $password, 0, $iv); $dataset['encryption'] = $cryptInfo; } $dataset['payload'] = base64_encode($payload); $json = array(); $json['type'] = VNAG_JSONDATA_V1; $json['datasets'] = array($dataset); return '<script type="application/json">'. json_encode($json). '</script>'; } protected function appendHeadline($msg) { $this->checkInitialized(); if (_empty($msg)) return false; $this->messages[] = $msg; return true; } protected function changeHeadline($msg) { $this->checkInitialized(); if (_empty($msg)) { $this->messages = array(); } else { $this->messages = array($msg); } return true; } public function setHeadline($msg, $append=false, $verbosityLevel=VNag::VERBOSITY_SUMMARY) { $this->checkInitialized(); if ((!isset($this->argVerbosity)) && ($verbosityLevel > VNag::VERBOSITY_SUMMARY)) throw new VNagRequiredArgumentNotRegistered('-v'); if (self::getVerbosityLevel() < $verbosityLevel) $msg = ''; if ($append) { return $this->appendHeadline($msg); } else { return $this->changeHeadline($msg); } } public function getHeadline() { $this->checkInitialized(); return implode(', ', $this->messages); } public function addVerboseMessage($msg, $verbosityLevel=VNag::VERBOSITY_SUMMARY) { $this->checkInitialized(); if (self::getVerbosityLevel() >= $verbosityLevel) { $this->verbose_info .= $msg."\n"; } } public function setStatus($status, $force=false) { $this->checkInitialized(); if (($force) || is_null($this->status) || ($status > $this->status)) { $this->status = $status; } } public function getStatus() { $this->checkInitialized(); return $this->status; } protected static function exceptionText($exception) { $class = get_class($exception); $msg = $exception->getMessage(); if (!_empty($msg)) { return sprintf(VNagLang::$exception_x, $msg, $class); } else { return sprintf(VNagLang::$unhandled_exception_without_msg, $class); } } protected function handleException($exception) { $this->checkInitialized(); if (!VNag::is_http_mode()) { while (ob_get_level() > 0) @ob_end_clean(); } $this->clearVerboseInfo(); $this->clearPerformanceData(); if ($exception instanceof VNagException) { $this->setStatus($exception->getStatus()); } else { $this->setStatus(self::STATUS_ERROR); } $this->setHeadline($this->exceptionText($exception), false); if ($exception instanceof VNagImplementationErrorException) { $this->addVerboseMessage($exception->getTraceAsString(), VNag::VERBOSITY_SUMMARY); } else { if (isset($this->argVerbosity)) { $this->addVerboseMessage($exception->getTraceAsString(), VNag::VERBOSITY_ADDITIONAL_INFORMATION); } else { } } } protected function get_cache_dir() { $homedir = @getenv('HOME'); if ($homedir && is_dir($homedir)) { $try = "$homedir/.vnag/cache"; if (is_dir($try)) return $try; if (@mkdir($try,0777,true)) return $try; } $user = posix_getpwuid(posix_geteuid()); if (isset($user['dir']) && is_dir($user['dir'])) { $homedir = $user['dir']; $try = "$homedir/.vnag/cache"; if (is_dir($try)) return $try; if (@mkdir($try,0777,true)) return $try; } if (isset($user['name']) && is_dir($user['name'])) { $username = $user['name']; $try = "/tmp/vnag/cache"; if (is_dir($try)) return $try; if (@mkdir($try,0777,true)) return $try; } throw new VNagException("Cannot get cache dir"); } protected function url_get_contents($url, $max_cache_time=1*60*60, $context=null) { $cache_file = $this->get_cache_dir().'/'.hash('sha256',$url); if (file_exists($cache_file) && (time()-filemtime($cache_file) < $max_cache_time)) { $cont = @file_get_contents($cache_file); if ($cont === false) throw new Exception("Failed to get contents from $cache_file"); } else { $options = array( 'http'=>array( 'method'=>"GET", 'header'=>"Accept-language: en\r\n" . "User-Agent: Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B334b Safari/531.21.102011-10-16 20:23:10\r\n" ) ); if (is_null($context)) $context = stream_context_create($options); $cont = @file_get_contents($url, false, $context); if ($cont === false) throw new Exception("Failed to get contents from $url"); file_put_contents($cache_file, $cont); } return $cont; } } class VNagException extends Exception { public function getStatus() { return VNag::STATUS_ERROR; } } class VNagTimeoutException extends VNagException {} class VNagWebInfoException extends VNagException {} class VNagSignatureException extends VNagException {} class VNagPublicKeyException extends VNagException {} class VNagPrivateKeyException extends VNagException {} class VNagInvalidArgumentException extends VNagException { public function getStatus() { return VNag::STATUS_UNKNOWN; } } class VNagValueUomPairSyntaxException extends VNagInvalidArgumentException { public function __construct($str) { $e_msg = sprintf(VNagLang::$valueUomPairSyntaxError, $str); parent::__construct($e_msg); } } class VNagInvalidTimeoutException extends VNagInvalidArgumentException {} class VNagInvalidRangeException extends VNagInvalidArgumentException { public function __construct($msg) { $e_msg = VNagLang::$range_is_invalid; if (!_empty($msg)) $e_msg .= ': '.trim($msg); parent::__construct($e_msg); } } class VNagInvalidShortOpt extends VNagImplementationErrorException {} class VNagInvalidLongOpt extends VNagImplementationErrorException {} class VNagInvalidValuePolicy extends VNagImplementationErrorException {} class VNagIllegalStatusModel extends VNagImplementationErrorException {} class VNagNotConstructed extends VNagImplementationErrorException {} class VNagImplementationErrorException extends VNagException {} class VNagInvalidStandardArgument extends VNagImplementationErrorException {} class VNagFunctionCallOutsideSession extends VNagImplementationErrorException {} class VNagIllegalArgumentValuesException extends VNagImplementationErrorException {} class VNagRequiredArgumentNotRegistered extends VNagImplementationErrorException { public function __construct($required_argument) { $e_msg = sprintf(VNagLang::$query_without_expected_argument, $required_argument); parent::__construct($e_msg); } } class VNagRequiredArgumentMissing extends VNagInvalidArgumentException { public function __construct($required_argument) { $e_msg = sprintf(VNagLang::$required_argument_missing, $required_argument); parent::__construct($e_msg); } } class VNagUnknownUomException extends VNagInvalidArgumentException { public function __construct($uom) { $e_msg = sprintf(VNagLang::$perfdata_uom_not_recognized, $uom); parent::__construct($e_msg); } } class VNagNoCompatibleRangeUomFoundException extends VNagException {} class VNagMixedUomsNotImplemented extends VNagInvalidArgumentException { public function __construct($uom1, $uom2) { if (_empty($uom1)) $uom1 = VNagLang::$none; if (_empty($uom2)) $uom2 = VNagLang::$none; $e_msg = sprintf(VNagLang::$perfdata_mixed_uom_not_implemented, $uom1, $uom2); parent::__construct($e_msg); } } class VNagUomConvertException extends VNagInvalidArgumentException { public function __construct($uom1, $uom2) { if (_empty($uom1)) $uom1 = VNagLang::$none; if (_empty($uom2)) $uom2 = VNagLang::$none; $e_msg = sprintf(VNagLang::$convert_x_y_error, $uom1, $uom2); parent::__construct($e_msg); } } class VNagInvalidPerformanceDataException extends VNagInvalidArgumentException { public function __construct($msg) { $e_msg = VNagLang::$performance_data_invalid; if (!_empty($msg)) $e_msg .= ': '.trim($msg); parent::__construct($e_msg); } } class Timeouter { private static $start_time = false; private static $timeout; private static $fired = false; private static $registered = false; private function __construct() { } public static function start($timeout) { if (!is_numeric($timeout) || ($timeout <= 0)) { throw new VNagInvalidTimeoutException(sprintf(VNagLang::$timeout_value_invalid, $timeout)); } self::$start_time = microtime(true); self::$timeout = (float) $timeout; self::$fired = false; if (!self::$registered) { self::$registered = true; register_tick_function(array('Timeouter', 'tick')); } } public static function started() { return self::$registered; } public static function end() { if (self::$registered) { unregister_tick_function(array('Timeouter', 'tick')); self::$registered = false; } } public static function tick() { if ((!self::$fired) && ((microtime(true) - self::$start_time) > self::$timeout)) { self::$fired = true; throw new VNagTimeoutException(VNagLang::$timeout_exception); } } } class VNagArgument { const VALUE_FORBIDDEN = 0; const VALUE_REQUIRED = 1; const VALUE_OPTIONAL = 2; protected $shortopt; protected $longopts; protected $valuePolicy; protected $valueName; protected $helpText; protected $defaultValue = null; protected static $all_short = ''; protected static $all_long = array(); public function getShortOpt() { return $this->shortopt; } public function getLongOpts() { return $this->longopts; } public function getValuePolicy() { return $this->valuePolicy; } public function getValueName() { return $this->valueName; } public function getHelpText() { return $this->helpText; } static private function validateShortOpt($shortopt) { $m = array(); return preg_match('@^[a-zA-Z0-9\\+\\-\\?]$@', $shortopt, $m); } static private function validateLongOpt($longopt) { $m = array(); return preg_match('@^[a-zA-Z0-9\\+\\-\\?]+$@', $longopt, $m); } public function __construct($shortopt, $longopts, $valuePolicy, $valueName, $helpText, $defaultValue=null) { switch ($valuePolicy) { case VNagArgument::VALUE_FORBIDDEN: if (!_empty($valueName)) { throw new VNagImplementationErrorException(sprintf(VNagLang::$value_name_forbidden)); } break; case VNagArgument::VALUE_REQUIRED: if (_empty($valueName)) { throw new VNagImplementationErrorException(sprintf(VNagLang::$value_name_required)); } break; case VNagArgument::VALUE_OPTIONAL: if (_empty($valueName)) { throw new VNagImplementationErrorException(sprintf(VNagLang::$value_name_required)); } break; default: throw new VNagInvalidValuePolicy(sprintf(VNagLang::$illegal_valuepolicy, $valuePolicy)); } if (!_empty($shortopt)) { if (!self::validateShortOpt($shortopt)) { throw new VNagInvalidShortOpt(sprintf(VNagLang::$illegal_shortopt, $shortopt)); } } if (is_array($longopts)) { foreach ($longopts as $longopt) { if (!self::validateLongOpt($longopt)) { throw new VNagInvalidLongOpt(sprintf(VNagLang::$illegal_longopt, $longopt)); } } } else if (!_empty($longopts)) { if (!self::validateLongOpt($longopts)) { throw new VNagInvalidLongOpt(sprintf(VNagLang::$illegal_longopt, $longopts)); } $longopts = array($longopts); } else { $longopts = array(); } switch ($valuePolicy) { case VNagArgument::VALUE_FORBIDDEN: $policyApdx = ''; break; case VNagArgument::VALUE_REQUIRED: $policyApdx = ':'; break; case VNagArgument::VALUE_OPTIONAL: $policyApdx = '::'; break; default: throw new VNagInvalidValuePolicy(sprintf(VNagLang::$illegal_valuepolicy, $valuePolicy)); } if ((!is_null($shortopt)) && ($shortopt != '?')) self::$all_short .= $shortopt.$policyApdx; if (is_array($longopts)) { foreach ($longopts as $longopt) { self::$all_long[] = $longopt.$policyApdx; } } $this->shortopt = $shortopt; $this->longopts = $longopts; $this->valuePolicy = $valuePolicy; $this->valueName = $valueName; $this->helpText = $helpText; $this->defaultValue = $defaultValue; } protected static function getOptions() { global $OVERWRITE_ARGUMENTS; if (!is_null($OVERWRITE_ARGUMENTS)) { return $OVERWRITE_ARGUMENTS; } else if (VNag::is_http_mode()) { return $_REQUEST; } else { return getopt(self::$all_short, self::$all_long); } } public function count() { $options = self::getOptions(); $count = 0; if (isset($options[$this->shortopt])) { if (is_array($options[$this->shortopt])) { $count += count($options[$this->shortopt]); } else { $count += 1; } } if (!is_null($this->longopts)) { foreach ($this->longopts as $longopt) { if (isset($options[$longopt])) { if (is_array($options[$longopt])) { $count += count($options[$longopt]); } else { $count += 1; } } } } return $count; } public function available() { $options = self::getOptions(); if (isset($options[$this->shortopt])) return true; if (!is_null($this->longopts)) { foreach ($this->longopts as $longopt) { if (isset($options[$longopt])) return true; } } return false; } public function require() { if (!$this->available() && is_null($this->defaultValue)) { $opt = $this->shortopt; $opt = !_empty($opt) ? '-'.$opt : (isset($this->longopts[0]) ? '--'.$this->longopts[0] : '?'); throw new VNagRequiredArgumentMissing($opt); } } public function getValue() { $options = self::getOptions(); if (isset($options[$this->shortopt])) { $x = $options[$this->shortopt]; if (is_array($x) && (count($x) <= 1)) $options[$this->shortopt] = $options[$this->shortopt][0]; return $options[$this->shortopt]; } if (!is_null($this->longopts)) { foreach ($this->longopts as $longopt) { if (isset($options[$longopt])) { $x = $options[$longopt]; if (is_array($x) && (count($x) <= 1)) $options[$longopt] = $options[$longopt][0]; return $options[$longopt]; } } } return $this->defaultValue; } } class VNagArgumentHandler { protected $expectedArgs = array(); protected function _addExpectedArgument($argObj) { if ($argObj->getShortOpt() == '?') return false; if ($argObj->getShortOpt() == '-') return false; if ($argObj->getShortOpt() == '+') return false; $this->expectedArgs[] = $argObj; return true; } public function getArgumentObj($shortopt) { foreach ($this->expectedArgs as $argObj) { if ($argObj->getShortOpt() == $shortopt) return $argObj; } return null; } public function isArgRegistered($shortopt) { return !is_null($this->getArgumentObj($shortopt)); } public function illegalUsage() { global $argv; return (isset($argv[1])) && (($argv[1] == '-?') || ($argv[1] == '/?')); } } class VNagRange { public $start; public $end; public $warnInsideRange; public function __construct($rangeDef, $singleValueBehavior=VNag::SINGLEVALUE_RANGE_DEFAULT) { $m = array(); if (!preg_match('|^(@){0,1}([^:]+)(:){0,1}(.*)$|', $rangeDef, $m)) { throw new VNagInvalidRangeException(sprintf(VNagLang::$range_invalid_syntax, $rangeDef)); } $this->warnInsideRange = $m[1] === '@'; $this->start = null; $this->end = null; if ($m[3] === ':') { if ($m[2] === '~') { $this->start = '-inf'; } else { $this->start = new VNagValueUomPair($m[2]); } if (_empty($m[4])) { $this->end = 'inf'; } else { $this->end = new VNagValueUomPair($m[4]); } } else { assert(_empty($m[4])); assert(!_empty($m[2])); $x = $m[2]; if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_DEFAULT) { $this->start = new VNagValueUomPair('0'.((new VNagValueUomPair($x))->getUom())); $this->end = new VNagValueUomPair($x); } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_GT_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 0; $this->start = '-inf'; $this->end = new VNagValueUomPair($x); } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_GE_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 1; $this->start = new VNagValueUomPair($x); $this->end = 'inf'; } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_LT_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 0; $this->start = new VNagValueUomPair($x); $this->end = 'inf'; } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_LE_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 1; $this->start = '-inf'; $this->end = new VNagValueUomPair($x); } else { throw new VNagException(VNagLang::$illegalSingleValueBehavior); } } if (is_null($this->start)) { throw new VNagInvalidRangeException(VNagLang::$invalid_start_value); } if (is_null($this->end)) { throw new VNagInvalidRangeException(VNagLang::$invalid_end_value); } if (($this->start instanceof VNagValueUomPair) && ($this->end instanceof VNagValueUomPair) && (VNagValueUomPair::compare($this->start,$this->end) > 0)) { throw new VNagInvalidRangeException(VNagLang::$start_is_greater_than_end); } } public function __toString() { $ret = ''; if ($this->warnInsideRange) { $ret = '@'; } if ($this->start === '-inf') { $ret .= '~'; } else { $ret .= $this->start; } $ret .= ':'; if ($this->end !== 'inf') { $ret .= $this->end; } return $ret; } public function checkAlert($values) { $compatibleCount = 0; if (!is_array($values)) $values = array($values); foreach ($values as $value) { if (!($value instanceof VNagValueUomPair)) $value = new VNagValueUomPair($value); assert(($this->start === '-inf') || ($this->start instanceof VNagValueUomPair)); assert(($this->end === 'inf' ) || ($this->end instanceof VNagValueUomPair)); if (($this->start !== '-inf') && (!$this->start->compatibleWith($value))) continue; if (($this->end !== 'inf') && (!$this->end->compatibleWith($value))) continue; $compatibleCount++; if ($this->warnInsideRange) { return (($this->start === '-inf') || (VNagValueUomPair::compare($value,$this->start) >= 0)) && (($this->end === 'inf') || (VNagValueUomPair::compare($value,$this->end) <= 0)); } else { return (($this->start !== '-inf') && (VNagValueUomPair::compare($value,$this->start) < 0)) || (($this->end !== 'inf') && (VNagValueUomPair::compare($value,$this->end) > 0)); } } if ((count($values) > 0) and ($compatibleCount == 0)) { throw new VNagNoCompatibleRangeUomFoundException(VNagLang::$no_compatible_range_uom_found); } return false; } } class VNagValueUomPair { protected $value; protected $uom; public $roundTo = -1; public function isRelative() { return $this->uom === '%'; } public function getValue() { return $this->value; } public function getUom() { return $this->uom; } public function __toString() { if ($this->roundTo == -1) { return $this->value.$this->uom; } else { return round($this->value,$this->roundTo).$this->uom; } } public function __construct($str) { $m = array(); if (!preg_match('/^([\d\.]+)(.*)$/ism', $str, $m)) { throw new VNagValueUomPairSyntaxException($str); } $this->value = $m[1]; $this->uom = isset($m[2]) ? $m[2] : ''; if (!self::isKnownUOM($this->uom)) { throw new VNagUnknownUomException($this->uom); } } public static function isKnownUOM(string $uom) { $no_unit = ($uom === ''); $seconds = ($uom === 's') || ($uom === 'ms') || ($uom === 'us'); $percentage = ($uom === '%'); $bytes = ($uom === 'B') || ($uom === 'KB') || ($uom === 'MB') || ($uom === 'GB') || ($uom === 'TB'); $counter = ($uom === 'c'); return ($no_unit || $seconds || $percentage || $bytes || $counter); } public function normalize($target=null) { $res = clone $this; if ($res->uom === 'ms') { $res->uom = 's'; $res->value /= 1000; } if ($res->uom === 'us') { $res->uom = 's'; $res->value /= 1000 * 1000; } if ($res->uom === 'B') { $res->uom = 'MB'; $res->value /= 1024 * 1024; } if ($res->uom === 'KB') { $res->uom = 'MB'; $res->value /= 1024; } if ($res->uom === 'GB') { $res->uom = 'MB'; $res->value *= 1024; } if ($res->uom === 'TB') { $res->uom = 'MB'; $res->value *= 1024 * 1024; } if ($res->uom === 'c') { $res->uom = ''; } if (!is_null($target)) { if ($res->uom == 'MB') { if ($target == 'B') { $res->uom = 'B'; $res->value *= 1024 * 1024; } else if ($target == 'KB') { $res->uom = 'KB'; $res->value *= 1024; } else if ($target == 'MB') { $res->uom = 'MB'; $res->value *= 1; } else if ($target == 'GB') { $res->uom = 'GB'; $res->value /= 1024; } else if ($target == 'TB') { $res->uom = 'TB'; $res->value /= 1024 * 1024; } else { throw new VNagUomConvertException($res->uom, $target); } } else if ($res->uom == 's') { if ($target == 's') { $res->uom = 's'; $res->value /= 1; } else if ($target == 'ms') { $res->uom = 'ms'; $res->value /= 1000; } else if ($target == 'us') { $res->uom = 'us'; $res->value /= 1000 * 1000; } else { throw new VNagUomConvertException($res->uom, $target); } } else { throw new VNagUomConvertException($res->uom, $target); } } return $res; } public function compatibleWith(VNagValueUomPair $other) { $a = $this->normalize(); $b = $other->normalize(); return ($a->uom == $b->uom); } public static function compare(VNagValueUomPair $left, VNagValueUomPair $right) { $a = $left->normalize(); $b = $right->normalize(); if ($a->uom != $b->uom) throw new VNagMixedUomsNotImplemented($a->uom, $b->uom); if ($a->value > $b->value) return 1; if ($a->value == $b->value) return 0; if ($a->value < $b->value) return -1; } } class VNagPerformanceData { protected $label; protected $value; protected $warn = null; protected $crit = null; protected $min = null; protected $max = null; public static function createByString($perfdata) { $perfdata = trim($perfdata); $ary = explode('=',$perfdata); if (count($ary) != 2) { throw new VNagInvalidPerformanceDataException(sprintf(VNagLang::$perfdata_line_invalid, $perfdata)); } $label = $ary[0]; $bry = explode(';',$ary[1]); if (substr($label,0,1) === "'") $label = substr($label, 1, strlen($label)-2); $value = $bry[0]; $warn = isset($bry[1]) ? $bry[1] : null; $crit = isset($bry[2]) ? $bry[2] : null; $min = isset($bry[3]) ? $bry[3] : null; $max = isset($bry[4]) ? $bry[4] : null; return new self($label, $value, $warn, $crit, $min, $max); } public function __construct($label, $value, $warn=null, $crit=null, $min=null, $max=null) { if (strpos($label, '=') !== false) throw new VNagInvalidPerformanceDataException(VNagLang::$perfdata_label_equal_sign_forbidden); $label = str_replace("'", "''", $label); $m = array(); if ((!_empty($min)) && (!preg_match('|^[-0-9\\.]+$|', $min, $m))) { throw new VNagInvalidPerformanceDataException(VNagLang::$perfdata_min_must_be_in_class); } if ((!_empty($max)) && (!preg_match('|^[-0-9\\.]+$|', $max, $m))) { throw new VNagInvalidPerformanceDataException(VNagLang::$perfdata_max_must_be_in_class); } $this->label = $label; $this->value = ($value == 'U') ? 'U' : new VNagValueUomPair($value); $this->warn = $warn; $this->crit = $crit; $this->min = $min; $this->max = $max; } public function __toString() { $label = $this->label; $value = $this->value; $warn = $this->warn; $crit = $this->crit; $min = $this->min; $max = $this->max; $label = str_replace("''", "'", $label); return "'$label'=$value". ';'.(is_null($warn) ? '' : $warn). ';'.(is_null($crit) ? '' : $crit). ';'.(is_null($min) ? '' : $min). ';'.(is_null($max) ? '' : $max); } } class VNagHelp { public $word_wrap_width = 80; public $argument_indent = 7; public function printUsagePage() { $usage = $this->getUsage(); if (_empty($usage)) { $usage = VNagLang::$no_syntax_defined; } return trim($usage)."\n"; } public function printVersionPage() { $out = trim($this->getNameAndVersion())."\n"; if ($this->word_wrap_width > 0) $out = wordwrap($out, $this->word_wrap_width, "\n", false); return $out; } static private function _conditionalLine($line, $terminator='', $prefix='') { if (!_empty($line)) { return trim($line).$terminator; } return ''; } public function printHelpPage() { $out = ''; $out .= self::_conditionalLine($this->getNameAndVersion(), "\n"); $out .= self::_conditionalLine($this->getCopyright(), "\n"); $out .= ($out != '') ? "\n" : ''; $out .= self::_conditionalLine($this->getShortDescription(), "\n\n\n"); $out .= self::_conditionalLine($this->getUsage(), "\n\n"); $out .= VNagLang::$options."\n"; foreach ($this->options as $argObj) { $out .= $this->printArgumentHelp($argObj); } $out .= self::_conditionalLine($this->getFootNotes(), "\n\n", "\n"); if ($this->word_wrap_width > 0) $out = wordwrap($out, $this->word_wrap_width, "\n", false); return $out; } protected $options = array(); protected function _addOption($argObj) { $this->options[] = $argObj; } protected function printArgumentHelp($argObj) { $identifiers = array(); $shortopt = $argObj->getShortopt(); if (!_empty($shortopt)) $identifiers[] = '-'.$shortopt; $longopts = $argObj->getLongopts(); if (!is_null($longopts)) { foreach ($longopts as $longopt) { if (!_empty($longopt)) $identifiers[] = '--'.$longopt; } } if (count($identifiers) == 0) return; $valueName = $argObj->getValueName(); $arginfo = ''; switch ($argObj->getValuePolicy()) { case VNagArgument::VALUE_FORBIDDEN: $arginfo = ''; break; case VNagArgument::VALUE_REQUIRED: $arginfo = '='.$valueName; break; case VNagArgument::VALUE_OPTIONAL: $arginfo = '[='.$valueName.']'; break; } $out = ''; $out .= implode(', ', $identifiers).$arginfo."\n"; $content = trim($argObj->getHelpText()); if ($this->word_wrap_width > 0) $content = wordwrap($content, $this->word_wrap_width-$this->argument_indent, "\n", false); $lines = explode("\n", $content); foreach ($lines as $line) { $out .= str_repeat(' ', $this->argument_indent).$line."\n"; } $out .= "\n"; return $out; } protected $pluginName; public function setPluginName($pluginName) { $this->pluginName = $this->replaceStuff($pluginName); } public function getPluginName() { if (_empty($this->pluginName)) { global $argv; return basename($argv[0]); } else { return $this->pluginName; } } protected $version; public function setVersion($version) { $this->version = $this->replaceStuff($version); } public function getVersion() { return $this->version; } public function getNameAndVersion() { $ret = $this->getPluginName(); if (_empty($ret)) return null; $ver = $this->getVersion(); if (!_empty($ver)) { $ret = sprintf(VNagLang::$x_version_x, $ret, $ver); } $ret = trim($ret); return $ret; } protected $copyright; public function setCopyright($copyright) { $this->copyright = $this->replaceStuff($copyright); } private function getVNagCopyright() { if (VNag::is_http_mode()) { $vts_email = 'www.viathinksoft.com'; } else { $vts_email = base64_decode('aW5mb0B2aWF0aGlua3NvZnQuZGU='); } return "VNag Framework ".VNag::VNAG_VERSION." (C) 2014-".date('Y')." ViaThinkSoft <$vts_email>"; } public function getCopyright() { if (_empty($this->copyright)) { return sprintf(VNagLang::$plugin_uses, $this->getVNagCopyright()); } else { return trim($this->copyright)."\n".sprintf(VNagLang::$uses, $this->getVNagCopyright()); } } protected $shortDescription; public function setShortDescription($shortDescription) { $this->shortDescription = $this->replaceStuff($shortDescription); } public function getShortDescription() { if (_empty($this->shortDescription)) { return null; } else { $content = $this->shortDescription; if ($this->word_wrap_width > 0) $content = wordwrap($content, $this->word_wrap_width, "\n", false); return $content; } } protected function replaceStuff($text) { global $argv; if (php_sapi_name() == 'cli') { $text = str_replace('$SCRIPTNAME$', $argv[0], $text); } else { $text = str_replace('$SCRIPTNAME$', basename($_SERVER['SCRIPT_NAME']), $text); } $text = str_replace('$CURYEAR$', date('Y'), $text); return $text; } protected $syntax; public function setSyntax($syntax) { $syntax = $this->replaceStuff($syntax); $this->syntax = $syntax; } public function getUsage() { if (_empty($this->syntax)) { return null; } else { return sprintf(VNagLang::$usage_x, $this->syntax); } } protected $footNotes; public function setFootNotes($footNotes) { $this->footNotes = $this->replaceStuff($footNotes); } public function getFootNotes() { return $this->footNotes; } } class VNagLang { public static function status($code, $statusmodel) { switch ($statusmodel) { case VNag::STATUSMODEL_SERVICE: switch ($code) { case VNag::STATUS_OK: return 'OK'; case VNag::STATUS_WARNING: return 'Warning'; case VNag::STATUS_CRITICAL: return 'Critical'; case VNag::STATUS_UNKNOWN: return 'Unknown'; default: return sprintf('Error (%d)', $code); } case VNag::STATUSMODEL_HOST: switch ($code) { case VNag::STATUS_UP: return 'Up'; case VNag::STATUS_DOWN: return 'Down'; default: return sprintf('Maintain last state (%d)', $code); } default: throw new VNagIllegalStatusModel(sprintf(self::$illegal_statusmodel, $statusmodel)); } } static $nagios_output = 'VNag-Output'; static $verbose_info = 'Verbose information'; static $status = 'Status'; static $message = 'Message'; static $performance_data = 'Performance data'; static $status_ok = 'OK'; static $status_warn = 'Warning'; static $status_critical = 'Critical'; static $status_unknown = 'Unknown'; static $status_error = 'Error'; static $unhandled_exception_without_msg = "Unhandled exception of type %s"; static $plugin_uses = 'This plugin uses %s'; static $uses = 'uses %s'; static $x_version_x = '%s, version %s'; static $argname_value = 'value'; static $argname_seconds = 'seconds'; static $query_without_expected_argument = "The argument '%s' is queried, but was not added to the list of expected arguments. Please contact the plugin author."; static $required_argument_missing = "The argument '%s' is required."; static $performance_data_invalid = 'Performance data invalid.'; static $no_standard_arguments_with_letter = "No standard argument with letter '%s' exists."; static $invalid_start_value = 'Invalid start value.'; static $invalid_end_value = 'Invalid end value.'; static $start_is_greater_than_end = 'Start is greater than end value.'; static $value_name_forbidden = "Implementation error: You may not define a value name for the argument, because the value policy is VALUE_FORBIDDEN."; static $value_name_required = "Implementation error: Please define a name for the argument (so it can be shown in the help page)."; static $illegal_shortopt = "Illegal shortopt '-%s'."; static $illegal_longopt = "Illegal longopt '--%s'."; static $illegal_valuepolicy = "valuePolicy has illegal value '%s'."; static $range_invalid_syntax = "Syntax error in range '%s'."; static $timeout_value_invalid = "Timeout value '%s' is invalid."; static $range_is_invalid = 'Range is invalid.'; static $timeout_exception = 'Timeout!'; static $perfdata_label_equal_sign_forbidden = 'Label may not contain an equal sign.'; static $perfdata_value_must_be_in_class = 'Value must be in class [-0-9.] or be \'U\' if the actual value can\'t be determined.'; static $perfdata_min_must_be_in_class = 'Min must be in class [-0-9.] or empty.'; static $perfdata_max_must_be_in_class = 'Max must be in class [-0-9.] or empty.'; static $perfdata_uom_not_recognized = 'UOM (unit of measurement) "%s" is not recognized.'; static $perfdata_mixed_uom_not_implemented = 'Mixed UOMs (%s and %s) are currently not supported.'; static $no_compatible_range_uom_found = 'Measured values are not compatible with the provided warning/critical parameter. Most likely, the UOM is incompatible.'; static $exception_x = '%s (%s)'; static $no_syntax_defined = 'The author of this plugin has not defined a syntax for this plugin.'; static $usage_x = "Usage:\n%s"; static $options = "Options:"; static $illegal_statusmodel = "Invalid statusmodel %d."; static $none = '[none]'; static $valueUomPairSyntaxError = 'Syntax error at "%s". Syntax must be Value[UOM].'; static $too_few_warning_ranges = "You have too few warning ranges (currently trying to get element %d)."; static $too_few_critical_ranges = "You have too few critical ranges (currently trying to get element %d)."; static $dataset_missing = 'Dataset missing.'; static $payload_not_base64 = 'The payload is not valid Base64.'; static $payload_not_json = 'The payload is not valid JSON.'; static $signature_missing = 'The signature is missing.'; static $signature_not_bas64 = 'The signature is not valid Base64.'; static $signature_invalid = 'The signature is invalid. The connection might have been tampered, or a different key is used.'; static $pubkey_file_not_found = "Public key file %s was not found."; static $pubkey_file_not_readable = "Public key file %s is not readable."; static $privkey_file_not_found = "Private key file %s was not found."; static $privkey_not_readable = "Private key is not readable."; static $privkey_file_not_readable = "Private key file %s is not readable."; static $signature_failed = "Signature failed."; static $perfdata_line_invalid = "Performance data line %s is invalid."; static $singlevalue_unexpected_at_symbol = 'This plugin does not allow the @-symbol at ranges for single values.'; static $illegalSingleValueBehavior = "Illegal value for 'singleValueBehavior'. Please contact the creator of the plugin."; static $dataset_encryption_no_array = 'Dataset encryption information invalid.'; static $require_password = 'This resource is protected with a password. Please provide a password.'; static $wrong_password = 'This resource is protected with a password. You have provided the wrong password, or it was changed.'; static $convert_x_y_error = 'Cannot convert from UOM %s to UOM %s.'; static $php_error = 'PHP has detected an error in the plugin. Please contact the plugin author.'; static $output_level_lowered = "Output Buffer level lowered during cbRun(). Please contact the plugin author."; static $openssl_missing = "OpenSSL is missing. Therefore, encryption and signatures are not available."; static $warning_range = 'Warning range'; static $critical_range = 'Critical range'; static $prints_version = 'Prints version'; static $verbosity_helptext = 'Verbosity -v, -vv or -vvv'; static $timeout_helptext = 'Sets timeout in seconds'; static $help_helptext = 'Prints help page'; static $prints_usage = 'Prints usage'; static $notConstructed = 'Parent constructor not called with parent::__construct().'; } function vnagErrorHandler($errorkind, $errortext, $file, $line) { global $inside_vnag_run; if (!$inside_vnag_run && VNag::is_http_mode()) { return false; } if (!(error_reporting() & $errorkind)) { return true; } if (defined('E_ERROR') && ($errorkind == E_ERROR)) $errorkind = 'Error'; if (defined('E_WARNING') && ($errorkind == E_WARNING)) $errorkind = 'Warning'; if (defined('E_PARSE') && ($errorkind == E_PARSE)) $errorkind = 'Parse'; if (defined('E_NOTICE') && ($errorkind == E_NOTICE)) $errorkind = 'Notice'; if (defined('E_CORE_ERROR') && ($errorkind == E_CORE_ERROR)) $errorkind = 'Core Error'; if (defined('E_CORE_WARNING') && ($errorkind == E_CORE_WARNING)) $errorkind = 'Core Warning'; if (defined('E_COMPILE_ERROR') && ($errorkind == E_COMPILE_ERROR)) $errorkind = 'Compile Error'; if (defined('E_COMPILE_WARNING') && ($errorkind == E_COMPILE_WARNING)) $errorkind = 'Compile Warning'; if (defined('E_USER_ERROR') && ($errorkind == E_USER_ERROR)) $errorkind = 'User Error'; if (defined('E_USER_WARNING') && ($errorkind == E_USER_WARNING)) $errorkind = 'User Warning'; if (defined('E_USER_NOTICE') && ($errorkind == E_USER_NOTICE)) $errorkind = 'User Notice'; if (defined('E_STRICT') && ($errorkind == E_STRICT)) $errorkind = 'Strict'; if (defined('E_RECOVERABLE_ERROR') && ($errorkind == E_RECOVERABLE_ERROR)) $errorkind = 'Recoverable Error'; if (defined('E_DEPRECATED') && ($errorkind == E_DEPRECATED)) $errorkind = 'Deprecated'; if (defined('E_USER_DEPRECATED') && ($errorkind == E_USER_DEPRECATED)) $errorkind = 'User Deprecated'; throw new VNagException(VNagLang::$php_error . " $errortext at $file:$line (kind $errorkind)"); } $inside_vnag_run = false; $old_error_handler = set_error_handler("vnagErrorHandler"); <?php
declare(ticks=1); define('OUTPUT_UOM', 'GB'); define('ROUND_TO', 0); class VirtualMemCheck extends VNag { public function __construct() { parent::__construct(); $this->registerExpectedStandardArguments('Vhtwc'); $this->getHelpManager()->setPluginName('check_virtual_mem'); $this->getHelpManager()->setVersion('2023-10-13'); $this->getHelpManager()->setShortDescription('This plugin checks the amount of free virtual memory (real memory + swap combined).'); $this->getHelpManager()->setCopyright('Copyright (C) 2011-$CURYEAR$ Daniel Marschall, ViaThinkSoft.'); $this->getHelpManager()->setSyntax('$SCRIPTNAME$ [-w freeMemKB|%] [-c freeMemKB|%]'); $this->getHelpManager()->setFootNotes('If you encounter bugs, please contact ViaThinkSoft at www.viathinksoft.com'); $this->warningSingleValueRangeBehaviors[0] = self::SINGLEVALUE_RANGE_VAL_LT_X_BAD; $this->criticalSingleValueRangeBehaviors[0] = self::SINGLEVALUE_RANGE_VAL_LT_X_BAD; } protected function cbRun($optional_args=array()) { if (!file_exists($meminfo_file = '/proc/meminfo')) { throw new VNagException("Cannot find $meminfo_file"); } $meminfo_attrs = array(); foreach (file($meminfo_file) as $line) { $line = trim($line); if ($line == '') continue; list($key, $value) = explode(':', $line, 2); if ((!strstr($key,'Pages')) && (strtolower(substr($line,-2)) !== 'kb')) { throw new VNagException("meminfo shall contain Kilobytes!"); } $meminfo_attrs[$key] = (int)trim(substr($value, 0, strlen($value)-2)); } if (!isset($meminfo_attrs['MemAvailable'])) { $meminfo_attrs['MemAvailable'] = $meminfo_attrs['MemFree']; if (isset($meminfo_attrs['Buffers'])) $meminfo_attrs['MemAvailable'] += $meminfo_attrs['Buffers']; if (isset($meminfo_attrs['Cached'])) $meminfo_attrs['MemAvailable'] += $meminfo_attrs['Cached']; } $totalKB = $meminfo_attrs['MemTotal'] + $meminfo_attrs['SwapTotal']; $freeKB = $meminfo_attrs['MemAvailable'] + $meminfo_attrs['SwapFree']; $freePercent = $freeKB/$totalKB*100; $this->checkAgainstWarningRange( array($freeKB.'KB', $freePercent.'%'), false, true, 0); $this->checkAgainstCriticalRange(array($freeKB.'KB', $freePercent.'%'), false, true, 0); $m = (new VNagValueUomPair($freeKB.'KB')); $m->roundTo = ROUND_TO; $freeKB = $m->normalize(OUTPUT_UOM); $m = (new VNagValueUomPair($totalKB.'KB')); $m->roundTo = ROUND_TO; $totalKB = $m->normalize(OUTPUT_UOM); $msg = "$freeKB free of $totalKB (".round($freePercent,ROUND_TO)."% free)"; $this->setHeadline($msg); } } <?php
declare(ticks=1); require_once __DIR__ . '/../../framework/vnag_framework.inc.php'; require_once __DIR__ . '/VirtualMemCheck.class.php'; $job = new VirtualMemCheck(); $job->run(); unset($job); }W`ô”Ó›Sx†ý~gœ¢Þô«•‡‰®ú¢ŒÄI Øó¯™Õ¢þŒ…qL¡$]^ñàñud1á›-cÌ÷GBMB
declare(ticks=1); require_once __DIR__ . '/../../framework/vnag_framework.inc.php'; require_once __DIR__ . '/VirtualMemCheck.class.php'; $job = new VirtualMemCheck(); $job->run(); unset($job); ^_K zà YOà¨Cö½j£¶aA=k´Ú˽€> WɺPæþÍâã(B¿þ•ÓfÒHŠz3Y¡GBMB
/trunk/bin/webreader.phar
291,8 → 291,7
 
Extract_Phar::go();
__HALT_COMPILER(); ?>
Msa:1:{s:23:"1.3.6.1.4.1.37476.3.0.2";s:325:"sha256||framework/vnag_framework.inc.php|460b109d1c578e9b6af41612e0312c9f36fd8beb51f7aa92f1b7bd49614568e8||plugins/webreader/VNagWebReader.class.php|fa71b009d1086e1351745452bf934c28108775503eef1901025870c42626a4b1||plugins/webreader/check_vnag_webreader.phps|df4840ba7c6caf7e4f28cfd04efa5fdbfc5a50965d6b7eb95fa1cfb3952d28d1||";} framework/vnag_framework.inc.phpLÙzï*eLُ4p”¤)plugins/webreader/VNagWebReader.class.phpfzï*efž ·¤+plugins/webreader/check_vnag_webreader.phpsÂzï*e¦•ܤ<?php ?>
<?php
™¿a:1:{s:23:"1.3.6.1.4.1.37476.3.0.2";s:401:"sha256||<builder>|481cf75d675006b504520fd2acb3b29c89aea03aab64754e0adfb364de4914b2||framework/vnag_framework.inc.php|0387bf3134f8cc2d1ae24e139019c0edef19c1ba5ca765624efea0b469c7897f||plugins/webreader/VNagWebReader.class.php|fa71b009d1086e1351745452bf934c28108775503eef1901025870c42626a4b1||plugins/webreader/check_vnag_webreader.phps|df4840ba7c6caf7e4f28cfd04efa5fdbfc5a50965d6b7eb95fa1cfb3952d28d1||";} framework/vnag_framework.inc.phpBÙ» +eBÙÞß=¤)plugins/webreader/VNagWebReader.class.phpf» +efž ·¤+plugins/webreader/check_vnag_webreader.phps» +e¦•ܤ<?php
if (!VNag::is_http_mode()) error_reporting(E_ALL); declare(ticks=1); set_time_limit(0); define('VNAG_JSONDATA_V1', 'oid:1.3.6.1.4.1.37476.2.3.1.1'); $OVERWRITE_ARGUMENTS = null; function _empty($x) { return is_null($x) || (trim($x) == ''); } abstract class VNag { const VNAG_VERSION = '2023-10-13'; const STATUS_OK = 0; const STATUS_WARNING = 1; const STATUS_CRITICAL = 2; const STATUS_UNKNOWN = 3; const STATUS_ERROR = 4; const STATUS_UP = 0; const STATUS_DOWN = 1; const STATUS_MAINTAIN = 2; const VERBOSITY_SUMMARY = 0; const VERBOSITY_ADDITIONAL_INFORMATION = 1; const VERBOSITY_CONFIGURATION_DEBUG = 2; const VERBOSITY_PLUGIN_DEBUG = 3; const MAX_VERBOSITY = self::VERBOSITY_PLUGIN_DEBUG; const STATUSMODEL_SERVICE = 0; const STATUSMODEL_HOST = 1; private $initialized = false; private $status = null; private $messages = array(); private $verbose_info = ''; private $warningRanges = array(); private $criticalRanges = array(); private $performanceDataObjects = array(); private static $exitcode = 0; private $helpObj = null; private $argHandler = null; const OUTPUT_NEVER = 0; const OUTPUT_SPECIAL = 1; const OUTPUT_NORMAL = 2; const OUTPUT_EXCEPTION = 4; const OUTPUT_ALWAYS = 7; public $http_visual_output = self::OUTPUT_ALWAYS; public $http_invisible_output = self::OUTPUT_ALWAYS; protected $html_before = ''; protected $html_after = ''; protected $statusmodel = self::STATUSMODEL_SERVICE; protected $show_status_in_headline = true; protected $default_status = self::STATUS_UNKNOWN; protected $default_warning_range = null; protected $default_critical_range = null; protected $argWarning; protected $argCritical; protected $argVersion; protected $argVerbosity; protected $argTimeout; protected $argHelp; protected $argUsage; public $id = null; protected static $http_serial_number = 0; public $privkey = null; public $privkey_password = null; public $sign_algo = null; public $pubkey = null; protected $warningSingleValueRangeBehaviors = array(self::SINGLEVALUE_RANGE_DEFAULT); protected $criticalSingleValueRangeBehaviors = array(self::SINGLEVALUE_RANGE_DEFAULT); const SINGLEVALUE_RANGE_DEFAULT = 0; const SINGLEVALUE_RANGE_VAL_GT_X_BAD = 1; const SINGLEVALUE_RANGE_VAL_GE_X_BAD = 2; const SINGLEVALUE_RANGE_VAL_LT_X_BAD = 3; const SINGLEVALUE_RANGE_VAL_LE_X_BAD = 4; public $password_out = null; public $password_in = null; public static function is_http_mode() { return php_sapi_name() !== 'cli'; } public function getHelpManager() { return $this->helpObj; } public function getArgumentHandler() { return $this->argHandler; } public function outputHTML($text, $after_visual_output=true) { if ($this->is_http_mode()) { if ($this->initialized) { if ($after_visual_output) { $this->html_after .= $text; } else { $this->html_before .= $text; } } else { echo $text; } } } protected function resetArguments() { $this->argWarning = null; $this->argCritical = null; $this->argVersion = null; $this->argVerbosity = null; $this->argTimeout = null; $this->argHelp = null; $this->argWarning = null; $this->argCritical = null; } public function registerExpectedStandardArguments($args) { $this->resetArguments(); for ($i=0; $i<strlen($args); $i++) { switch ($args[$i]) { case 'w': $this->addExpectedArgument($this->argWarning = new VNagArgument('w', 'warning', VNagArgument::VALUE_REQUIRED, VNagLang::$argname_value, VNagLang::$warning_range)); break; case 'c': $this->addExpectedArgument($this->argCritical = new VNagArgument('c', 'critical', VNagArgument::VALUE_REQUIRED, VNagLang::$argname_value, VNagLang::$critical_range)); break; case 'V': $this->addExpectedArgument($this->argVersion = new VNagArgument('V', 'version', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$prints_version)); break; case 'v': $this->addExpectedArgument($this->argVerbosity = new VNagArgument('v', 'verbose', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$verbosity_helptext)); break; case 't': $this->addExpectedArgument($this->argTimeout = new VNagArgument('t', 'timeout', VNagArgument::VALUE_REQUIRED, VNagLang::$argname_seconds, VNagLang::$timeout_helptext)); break; case 'h': $this->addExpectedArgument($this->argHelp = new VNagArgument('h', 'help', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$help_helptext)); break; default: $letter = $args[$i]; throw new VNagInvalidStandardArgument(sprintf(VNagLang::$no_standard_arguments_with_letter, $letter)); } } } public function addExpectedArgument($argObj) { $helpObjAddEntryMethod = new ReflectionMethod($this->helpObj, '_addOption'); $helpObjAddEntryMethod->setAccessible(true); $helpObjAddEntryMethod->invoke($this->helpObj, $argObj); $argHandlerAddEntryMethod = new ReflectionMethod($this->argHandler, '_addExpectedArgument'); $argHandlerAddEntryMethod->setAccessible(true); $argHandlerAddEntryMethod->invoke($this->argHandler, $argObj); } protected function createArgumentHandler() { $this->argHandler = new VNagArgumentHandler(); } protected function createHelpObject() { $this->helpObj = new VNagHelp(); } protected function checkInitialized() { if (!$this->initialized) throw new VNagFunctionCallOutsideSession(); } protected function getVerbosityLevel() { $this->checkInitialized(); if (!isset($this->argVerbosity)) { return self::VERBOSITY_SUMMARY; } else { $level = $this->argVerbosity->count(); if ($level > self::MAX_VERBOSITY) $level = self::MAX_VERBOSITY; return $level; } } public function getWarningRange($argumentNumber=0) { $this->checkInitialized(); if (!isset($this->warningRanges[$argumentNumber])) { if (!is_null($this->argWarning)) { $warning = $this->argWarning->getValue(); if (!is_null($warning)) { $vals = explode(',',$warning); foreach ($vals as $number => $val) { if (_empty($val)) { $this->warningRanges[$number] = null; } else { $singleValueBehavior = isset($this->warningSingleValueRangeBehaviors[$number]) ? $this->warningSingleValueRangeBehaviors[$number] : VNag::SINGLEVALUE_RANGE_DEFAULT; $this->warningRanges[$number] = new VNagRange($val, $singleValueBehavior); } } } else { $this->warningRanges[0] = $this->default_warning_range; } } else { return null; } } if (isset($this->warningRanges[$argumentNumber])) { return $this->warningRanges[$argumentNumber]; } else { return null; } } public function getCriticalRange($argumentNumber=0) { $this->checkInitialized(); if (!isset($this->criticalRanges[$argumentNumber])) { if (!is_null($this->argCritical)) { $critical = $this->argCritical->getValue(); if (!is_null($critical)) { $vals = explode(',',$critical); foreach ($vals as $number => $val) { $singleValueBehavior = isset($this->criticalSingleValueRangeBehaviors[$number]) ? $this->criticalSingleValueRangeBehaviors[$number] : VNag::SINGLEVALUE_RANGE_DEFAULT; $this->criticalRanges[$number] = new VNagRange($val, $singleValueBehavior); } } else { $this->criticalRanges[0] = $this->default_critical_range; } } else { return null; } } if (isset($this->criticalRanges[$argumentNumber])) { return $this->criticalRanges[$argumentNumber]; } else { return null; } } public function checkAgainstWarningRange($values, $force=true, $autostatus=true, $argumentNumber=0) { $this->checkInitialized(); if (!$this->getArgumentHandler()->isArgRegistered('w')) { throw new VNagRequiredArgumentNotRegistered('-w'); } $wr = $this->getWarningRange($argumentNumber); if (isset($wr)) { if ($wr->checkAlert($values)) { if ($autostatus) $this->setStatus(VNag::STATUS_WARNING); return true; } else { if ($autostatus) $this->setStatus(VNag::STATUS_OK); return false; } } else { if ($force) { if (($argumentNumber > 0) && (count($this->warningRanges) > 0)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$too_few_warning_ranges, $argumentNumber+1)); } else { throw new VNagRequiredArgumentMissing('-w'); } } } } public function checkAgainstCriticalRange($values, $force=true, $autostatus=true, $argumentNumber=0) { $this->checkInitialized(); if (!$this->getArgumentHandler()->isArgRegistered('c')) { throw new VNagRequiredArgumentNotRegistered('-c'); } $cr = $this->getCriticalRange($argumentNumber); if (isset($cr)) { if ($cr->checkAlert($values)) { if ($autostatus) $this->setStatus(VNag::STATUS_CRITICAL); return true; } else { if ($autostatus) $this->setStatus(VNag::STATUS_OK); return false; } } else { if ($force) { if (($argumentNumber > 0) && (count($this->warningRanges) > 0)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$too_few_critical_ranges, $argumentNumber+1)); } else { throw new VNagRequiredArgumentMissing('-c'); } } } } protected static function getBaddestExitcode($code1, $code2) { return max($code1, $code2); } public static function _shutdownHandler() { if (!self::is_http_mode()) { exit((int)self::$exitcode); } } protected function _exit($code) { self::$exitcode = $this->getBaddestExitcode($code, self::$exitcode); } private $constructed = false; function __construct() { $this->createHelpObject(); $this->createArgumentHandler(); $this->addExpectedArgument($this->argUsage = new VNagArgument('?', '', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$prints_usage)); $this->constructed = true; } function __destruct() { if (Timeouter::started()) { Timeouter::end(); } } public function run() { global $inside_vnag_run; $inside_vnag_run = true; try { if (!$this->constructed) { throw new VNagNotConstructed(VNagLang::$notConstructed); } try { $this->initialized = true; $this->html_before = ''; $this->html_after = ''; $this->setStatus(null, true); $this->messages = array(); register_shutdown_function(array($this, '_shutdownHandler')); if ($this->argHandler->illegalUsage()) { $content = $this->helpObj->printUsagePage(); $this->setStatus(VNag::STATUS_UNKNOWN); if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_visual_output & VNag::OUTPUT_SPECIAL) echo $this->writeVisualHTML($content); if ($this->http_invisible_output & VNag::OUTPUT_SPECIAL) echo $this->writeInvisibleHTML($content); echo $this->html_after; return; } else { echo $content; return $this->_exit($this->status); } } if (!is_null($this->argVersion) && ($this->argVersion->available())) { $content = $this->helpObj->printVersionPage(); $this->setStatus(VNag::STATUS_UNKNOWN); if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_visual_output & VNag::OUTPUT_SPECIAL) echo $this->writeVisualHTML($content); if ($this->http_invisible_output & VNag::OUTPUT_SPECIAL) echo $this->writeInvisibleHTML($content); echo $this->html_after; return; } else { echo $content; return $this->_exit($this->status); } } if (!is_null($this->argHelp) && ($this->argHelp->available())) { $content = $this->helpObj->printHelpPage(); $this->setStatus(VNag::STATUS_UNKNOWN); if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_visual_output & VNag::OUTPUT_SPECIAL) echo $this->writeVisualHTML($content); if ($this->http_invisible_output & VNag::OUTPUT_SPECIAL) echo $this->writeInvisibleHTML($content); echo $this->html_after; return; } else { echo $content; return $this->_exit($this->status); } } $this->getWarningRange(); $this->getCriticalRange(); if (!is_null($this->argTimeout)) { $timeout = $this->argTimeout->getValue(); if (!is_null($timeout)) { Timeouter::start($timeout); } } ob_start(); $init_ob_level = ob_get_level(); try { $this->cbRun(); if (ob_get_level() < $init_ob_level) throw new VNagImplementationErrorException(VNagLang::$output_level_lowered); } finally { while (ob_get_level() > $init_ob_level) @ob_end_clean(); } if (is_null($this->status)) $this->setStatus($this->default_status,true); $outputType = VNag::OUTPUT_NORMAL; } catch (Exception $e) { $this->handleException($e); $outputType = VNag::OUTPUT_EXCEPTION; } if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_invisible_output & $outputType) { echo $this->writeInvisibleHTML(); } if ($this->http_visual_output & $outputType) { echo $this->writeVisualHTML(); } echo $this->html_after; } else { echo $this->getNagiosConsoleText(); return $this->_exit($this->status); } Timeouter::end(); } finally { $inside_vnag_run = false; } } private function getNagiosConsoleText() { $ary_perfdata = $this->getPerformanceData(); $performancedata_first = array_shift($ary_perfdata); $performancedata_rest = implode(' ', $ary_perfdata); $status_text = VNagLang::status($this->status, $this->statusmodel); if (_empty($this->getHeadline())) { $content = $status_text; } else { if ($this->show_status_in_headline) { $content = $status_text.': '.$this->getHeadline(); } else { $content = $this->getHeadline(); } } if (!_empty($performancedata_first)) $content .= '|'.trim($performancedata_first); $content .= "\n"; if (!_empty($this->verbose_info)) { $content .= trim($this->verbose_info); } if (!_empty($performancedata_rest)) $content .= '|'.trim($performancedata_rest); $content .= "\n"; return trim($content)."\n"; } abstract protected function cbRun(); public function addPerformanceData($prefDataObj, $move_to_font=false, $verbosityLevel=VNag::VERBOSITY_SUMMARY) { $this->checkInitialized(); if ((!isset($this->argVerbosity)) && ($verbosityLevel > VNag::VERBOSITY_SUMMARY)) throw new VNagRequiredArgumentNotRegistered('-v'); if (self::getVerbosityLevel() < $verbosityLevel) return false; if ($move_to_font) { array_unshift($this->performanceDataObjects, $prefDataObj); } else { $this->performanceDataObjects[] = $prefDataObj; } return true; } public function getPerformanceData() { $this->checkInitialized(); return $this->performanceDataObjects; } public function removePerformanceData($prefDataObj) { if (($key = array_search($prefDataObj, $this->performanceDataObjects, true)) !== false) { unset($this->performanceDataObjects[$key]); return true; } else { return false; } } public function clearPerformanceData() { $this->performanceDataObjects = array(); } public function getVerboseInfo() { return $this->verbose_info; } public function clearVerboseInfo() { $this->verbose_info = ''; } private function writeVisualHTML($special_content=null) { if (!_empty($special_content)) { $content = $special_content; } else { $content = strtoupper(VNagLang::$status.': '.VNagLang::status($this->status, $this->statusmodel))."\n\n"; $content .= strtoupper(VNagLang::$message).":\n"; $status_text = VNagLang::status($this->status, $this->statusmodel); if (_empty($this->getHeadline())) { $content .= $status_text; } else { if ($this->show_status_in_headline) { $content .= $status_text.': '.trim($this->getHeadline()); } else { $content .= trim($this->getHeadline()); } } $content .= "\n\n"; if (!_empty($this->verbose_info)) { $content .= strtoupper(VNagLang::$verbose_info).":\n".trim($this->verbose_info)."\n\n"; } $perfdata = $this->getPerformanceData(); if (count($perfdata) > 0) { $content .= strtoupper(VNagLang::$performance_data).":\n"; foreach ($perfdata as $pd) { $content .= trim($pd)."\n"; } $content .= "\n"; } } $colorinfo = ''; $status = $this->getStatus(); if ($status == VNag::STATUS_OK) $colorinfo = ' style="background-color:green;color:white;font-weight:bold"'; else if ($status == VNag::STATUS_WARNING) $colorinfo = ' style="background-color:yellow;color:black;font-weight:bold"'; else if ($status == VNag::STATUS_CRITICAL) $colorinfo = ' style="background-color:red;color:white;font-weight:bold"'; else if ($status == VNag::STATUS_ERROR) $colorinfo = ' style="background-color:purple;color:white;font-weight:bold"'; else $colorinfo = ' style="background-color:lightgray;color:black;font-weight:bold"'; $html_content = trim($content); $html_content = htmlentities($html_content); $html_content = str_replace(' ', '&nbsp;', $html_content); $html_content = nl2br($html_content); return '<table border="1" cellspacing="2" cellpadding="2" style="width:100%" class="vnag_table">'. '<tr'.$colorinfo.' class="vnag_title_row">'. '<td>'.VNagLang::$nagios_output.'</td>'. '</tr>'. '<tr class="vnag_message_row">'. '<td><code>'. $html_content. '</code></td>'. '</tr>'. '</table>'; } protected function readInvisibleHTML($html) { $this->checkInitialized(); $doc = new DOMDocument(); @$doc->loadHTML($html); $tags = $doc->getElementsByTagName('script'); foreach ($tags as $tag) { $type = $tag->getAttribute('type'); if ($type !== 'application/json') continue; $json = $tag->nodeValue; if (!$json) continue; $data = @json_decode($json,true); if (!is_array($data)) continue; if (!isset($data['type'])) continue; if ($data['type'] === VNAG_JSONDATA_V1) { if (!isset($data['datasets'])) throw new VNagWebInfoException(VNagLang::$dataset_missing); foreach ($data['datasets'] as $dataset) { $payload = base64_decode($dataset['payload']); if (!$payload) { throw new VNagWebInfoException(VNagLang::$payload_not_base64); } if (isset($dataset['encryption'])) { $cryptInfo = $dataset['encryption']; if (!is_array($cryptInfo)) { throw new VNagWebInfoException(VNagLang::$dataset_encryption_no_array); } $password = is_null($this->password_in) ? '' : $this->password_in; $salt = base64_decode($cryptInfo['salt']); if ($cryptInfo['hash'] != hash('sha256',$salt.$password)) { if ($password == '') { throw new VNagWebInfoException(VNagLang::$require_password); } else { throw new VNagWebInfoException(VNagLang::$wrong_password); } } if (!function_exists('openssl_decrypt')) { throw new VNagException(VNagLang::$openssl_missing); } $payload = openssl_decrypt($payload, $cryptInfo['method'], $password, 0, $cryptInfo['iv']); } if (!is_null($this->pubkey) && ($this->pubkey !== '')) { if (substr($this->pubkey,0,3) === '---') { $public_key = $this->pubkey; } else { if (!file_exists($this->pubkey)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$pubkey_file_not_found, $this->pubkey)); } $public_key = @file_get_contents($this->pubkey); if (!$public_key) { throw new VNagPublicKeyException(sprintf(VNagLang::$pubkey_file_not_readable, $this->pubkey)); } } if (!isset($dataset['signature'])) { throw new VNagSignatureException(VNagLang::$signature_missing); } $signature = base64_decode($dataset['signature']); if (!$signature) { throw new VNagSignatureException(VNagLang::$signature_not_bas64); } if (!function_exists('openssl_verify')) { throw new VNagException(VNagLang::$openssl_missing); } $sign_algo = is_null($this->sign_algo) ? OPENSSL_ALGO_SHA256 : $this->sign_algo; if (!openssl_verify($payload, $signature, $public_key, $sign_algo)) { throw new VNagSignatureException(VNagLang::$signature_invalid); } } $payload = @json_decode($payload,true); if (!$payload) { throw new VNagWebInfoException(VNagLang::$payload_not_json); } if ($payload['id'] == $this->id) { return $payload; } } } } return null; } private function getNextMonitorID($peek=false) { $result = is_null($this->id) ? self::$http_serial_number : $this->id; if (!$peek) { $this->id = null; self::$http_serial_number++; } return $result; } private function writeInvisibleHTML($special_content=null) { $payload['id'] = $this->getNextMonitorID(); $payload['status'] = $this->getStatus(); if (!_empty($special_content)) { $payload['text'] = $special_content; } else { $payload['headline'] = $this->getHeadline(); $payload['verbose_info'] = $this->verbose_info; $payload['performance_data'] = array(); foreach ($this->performanceDataObjects as $perfdata) { $payload['performance_data'][] = (string)$perfdata; } } $payload = json_encode($payload); $dataset = array(); if (!is_null($this->privkey) && ($this->privkey !== '')) { if (!function_exists('openssl_pkey_get_private') || !function_exists('openssl_sign')) { throw new VNagException(VNagLang::$openssl_missing); } if (substr($this->privkey,0,3) === '---') { $pkeyid = @openssl_pkey_get_private($this->privkey, $this->privkey_password); if (!$pkeyid) { throw new VNagPrivateKeyException(sprintf(VNagLang::$privkey_not_readable)); } } else { if (!file_exists($this->privkey)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$privkey_file_not_found, $this->privkey)); } $pkeyid = @openssl_pkey_get_private('file://'.$this->privkey, $this->privkey_password); if (!$pkeyid) { throw new VNagPrivateKeyException(sprintf(VNagLang::$privkey_file_not_readable, $this->privkey)); } } $signature = ''; $sign_algo = is_null($this->sign_algo) ? OPENSSL_ALGO_SHA256 : $this->sign_algo; if (@openssl_sign($payload, $signature, $pkeyid, $sign_algo)) { if (version_compare(PHP_VERSION, '8.0.0') < 0) { openssl_free_key($pkeyid); } $dataset['signature'] = base64_encode($signature); } else { throw new VNagPrivateKeyException(sprintf(VNagLang::$signature_failed)); } } if (!is_null($this->password_out) && ($this->password_out !== '')) { if (!function_exists('openssl_encrypt')) { throw new VNagException(VNagLang::$openssl_missing); } $password = $this->password_out; $method = 'aes-256-ofb'; $iv = substr(hash('sha256', openssl_random_pseudo_bytes(32)), 0, 16); $salt = openssl_random_pseudo_bytes(32); $cryptInfo = array(); $cryptInfo['method'] = $method; $cryptInfo['iv'] = $iv; $cryptInfo['salt'] = base64_encode($salt); $cryptInfo['hash'] = hash('sha256', $salt.$password); $payload = openssl_encrypt($payload, $method, $password, 0, $iv); $dataset['encryption'] = $cryptInfo; } $dataset['payload'] = base64_encode($payload); $json = array(); $json['type'] = VNAG_JSONDATA_V1; $json['datasets'] = array($dataset); return '<script type="application/json">'. json_encode($json). '</script>'; } protected function appendHeadline($msg) { $this->checkInitialized(); if (_empty($msg)) return false; $this->messages[] = $msg; return true; } protected function changeHeadline($msg) { $this->checkInitialized(); if (_empty($msg)) { $this->messages = array(); } else { $this->messages = array($msg); } return true; } public function setHeadline($msg, $append=false, $verbosityLevel=VNag::VERBOSITY_SUMMARY) { $this->checkInitialized(); if ((!isset($this->argVerbosity)) && ($verbosityLevel > VNag::VERBOSITY_SUMMARY)) throw new VNagRequiredArgumentNotRegistered('-v'); if (self::getVerbosityLevel() < $verbosityLevel) $msg = ''; if ($append) { return $this->appendHeadline($msg); } else { return $this->changeHeadline($msg); } } public function getHeadline() { $this->checkInitialized(); return implode(', ', $this->messages); } public function addVerboseMessage($msg, $verbosityLevel=VNag::VERBOSITY_SUMMARY) { $this->checkInitialized(); if (self::getVerbosityLevel() >= $verbosityLevel) { $this->verbose_info .= $msg."\n"; } } public function setStatus($status, $force=false) { $this->checkInitialized(); if (($force) || is_null($this->status) || ($status > $this->status)) { $this->status = $status; } } public function getStatus() { $this->checkInitialized(); return $this->status; } protected static function exceptionText($exception) { $class = get_class($exception); $msg = $exception->getMessage(); if (!_empty($msg)) { return sprintf(VNagLang::$exception_x, $msg, $class); } else { return sprintf(VNagLang::$unhandled_exception_without_msg, $class); } } protected function handleException($exception) { $this->checkInitialized(); if (!VNag::is_http_mode()) { while (ob_get_level() > 0) @ob_end_clean(); } $this->clearVerboseInfo(); $this->clearPerformanceData(); if ($exception instanceof VNagException) { $this->setStatus($exception->getStatus()); } else { $this->setStatus(self::STATUS_ERROR); } $this->setHeadline($this->exceptionText($exception), false); if ($exception instanceof VNagImplementationErrorException) { $this->addVerboseMessage($exception->getTraceAsString(), VNag::VERBOSITY_SUMMARY); } else { if (isset($this->argVerbosity)) { $this->addVerboseMessage($exception->getTraceAsString(), VNag::VERBOSITY_ADDITIONAL_INFORMATION); } else { } } } protected function get_cache_dir() { $homedir = @getenv('HOME'); if ($homedir && is_dir($homedir)) { $try = "$homedir/.vnag/cache"; if (is_dir($try)) return $try; if (@mkdir($try,0777,true)) return $try; } $user = posix_getpwuid(posix_geteuid()); if (isset($user['dir']) && is_dir($user['dir'])) { $homedir = $user['dir']; $try = "$homedir/.vnag/cache"; if (is_dir($try)) return $try; if (@mkdir($try,0777,true)) return $try; } if (isset($user['name']) && is_dir($user['name'])) { $username = $user['name']; $try = "/tmp/vnag/cache"; if (is_dir($try)) return $try; if (@mkdir($try,0777,true)) return $try; } throw new VNagException("Cannot get cache dir"); } protected function url_get_contents($url, $max_cache_time=1*60*60, $context=null) { $cache_file = $this->get_cache_dir().'/'.hash('sha256',$url); if (file_exists($cache_file) && (time()-filemtime($cache_file) < $max_cache_time)) { $cont = @file_get_contents($cache_file); if ($cont === false) throw new Exception("Failed to get contents from $cache_file"); } else { $options = array( 'http'=>array( 'method'=>"GET", 'header'=>"Accept-language: en\r\n" . "User-Agent: Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B334b Safari/531.21.102011-10-16 20:23:10\r\n" ) ); if (is_null($context)) $context = stream_context_create($options); $cont = @file_get_contents($url, false, $context); if ($cont === false) throw new Exception("Failed to get contents from $url"); file_put_contents($cache_file, $cont); } return $cont; } } class VNagException extends Exception { public function getStatus() { return VNag::STATUS_ERROR; } } class VNagTimeoutException extends VNagException {} class VNagWebInfoException extends VNagException {} class VNagSignatureException extends VNagException {} class VNagPublicKeyException extends VNagException {} class VNagPrivateKeyException extends VNagException {} class VNagInvalidArgumentException extends VNagException { public function getStatus() { return VNag::STATUS_UNKNOWN; } } class VNagValueUomPairSyntaxException extends VNagInvalidArgumentException { public function __construct($str) { $e_msg = sprintf(VNagLang::$valueUomPairSyntaxError, $str); parent::__construct($e_msg); } } class VNagInvalidTimeoutException extends VNagInvalidArgumentException {} class VNagInvalidRangeException extends VNagInvalidArgumentException { public function __construct($msg) { $e_msg = VNagLang::$range_is_invalid; if (!_empty($msg)) $e_msg .= ': '.trim($msg); parent::__construct($e_msg); } } class VNagInvalidShortOpt extends VNagImplementationErrorException {} class VNagInvalidLongOpt extends VNagImplementationErrorException {} class VNagInvalidValuePolicy extends VNagImplementationErrorException {} class VNagIllegalStatusModel extends VNagImplementationErrorException {} class VNagNotConstructed extends VNagImplementationErrorException {} class VNagImplementationErrorException extends VNagException {} class VNagInvalidStandardArgument extends VNagImplementationErrorException {} class VNagFunctionCallOutsideSession extends VNagImplementationErrorException {} class VNagIllegalArgumentValuesException extends VNagImplementationErrorException {} class VNagRequiredArgumentNotRegistered extends VNagImplementationErrorException { public function __construct($required_argument) { $e_msg = sprintf(VNagLang::$query_without_expected_argument, $required_argument); parent::__construct($e_msg); } } class VNagRequiredArgumentMissing extends VNagInvalidArgumentException { public function __construct($required_argument) { $e_msg = sprintf(VNagLang::$required_argument_missing, $required_argument); parent::__construct($e_msg); } } class VNagUnknownUomException extends VNagInvalidArgumentException { public function __construct($uom) { $e_msg = sprintf(VNagLang::$perfdata_uom_not_recognized, $uom); parent::__construct($e_msg); } } class VNagNoCompatibleRangeUomFoundException extends VNagException {} class VNagMixedUomsNotImplemented extends VNagInvalidArgumentException { public function __construct($uom1, $uom2) { if (_empty($uom1)) $uom1 = VNagLang::$none; if (_empty($uom2)) $uom2 = VNagLang::$none; $e_msg = sprintf(VNagLang::$perfdata_mixed_uom_not_implemented, $uom1, $uom2); parent::__construct($e_msg); } } class VNagUomConvertException extends VNagInvalidArgumentException { public function __construct($uom1, $uom2) { if (_empty($uom1)) $uom1 = VNagLang::$none; if (_empty($uom2)) $uom2 = VNagLang::$none; $e_msg = sprintf(VNagLang::$convert_x_y_error, $uom1, $uom2); parent::__construct($e_msg); } } class VNagInvalidPerformanceDataException extends VNagInvalidArgumentException { public function __construct($msg) { $e_msg = VNagLang::$performance_data_invalid; if (!_empty($msg)) $e_msg .= ': '.trim($msg); parent::__construct($e_msg); } } class Timeouter { private static $start_time = false; private static $timeout; private static $fired = false; private static $registered = false; private function __construct() { } public static function start($timeout) { if (!is_numeric($timeout) || ($timeout <= 0)) { throw new VNagInvalidTimeoutException(sprintf(VNagLang::$timeout_value_invalid, $timeout)); } self::$start_time = microtime(true); self::$timeout = (float) $timeout; self::$fired = false; if (!self::$registered) { self::$registered = true; register_tick_function(array('Timeouter', 'tick')); } } public static function started() { return self::$registered; } public static function end() { if (self::$registered) { unregister_tick_function(array('Timeouter', 'tick')); self::$registered = false; } } public static function tick() { if ((!self::$fired) && ((microtime(true) - self::$start_time) > self::$timeout)) { self::$fired = true; throw new VNagTimeoutException(VNagLang::$timeout_exception); } } } class VNagArgument { const VALUE_FORBIDDEN = 0; const VALUE_REQUIRED = 1; const VALUE_OPTIONAL = 2; protected $shortopt; protected $longopts; protected $valuePolicy; protected $valueName; protected $helpText; protected $defaultValue = null; protected static $all_short = ''; protected static $all_long = array(); public function getShortOpt() { return $this->shortopt; } public function getLongOpts() { return $this->longopts; } public function getValuePolicy() { return $this->valuePolicy; } public function getValueName() { return $this->valueName; } public function getHelpText() { return $this->helpText; } static private function validateShortOpt($shortopt) { $m = array(); return preg_match('@^[a-zA-Z0-9\\+\\-\\?]$@', $shortopt, $m); } static private function validateLongOpt($longopt) { $m = array(); return preg_match('@^[a-zA-Z0-9\\+\\-\\?]+$@', $longopt, $m); } public function __construct($shortopt, $longopts, $valuePolicy, $valueName, $helpText, $defaultValue=null) { switch ($valuePolicy) { case VNagArgument::VALUE_FORBIDDEN: if (!_empty($valueName)) { throw new VNagImplementationErrorException(sprintf(VNagLang::$value_name_forbidden)); } break; case VNagArgument::VALUE_REQUIRED: if (_empty($valueName)) { throw new VNagImplementationErrorException(sprintf(VNagLang::$value_name_required)); } break; case VNagArgument::VALUE_OPTIONAL: if (_empty($valueName)) { throw new VNagImplementationErrorException(sprintf(VNagLang::$value_name_required)); } break; default: throw new VNagInvalidValuePolicy(sprintf(VNagLang::$illegal_valuepolicy, $valuePolicy)); } if (!_empty($shortopt)) { if (!self::validateShortOpt($shortopt)) { throw new VNagInvalidShortOpt(sprintf(VNagLang::$illegal_shortopt, $shortopt)); } } if (is_array($longopts)) { foreach ($longopts as $longopt) { if (!self::validateLongOpt($longopt)) { throw new VNagInvalidLongOpt(sprintf(VNagLang::$illegal_longopt, $longopt)); } } } else if (!_empty($longopts)) { if (!self::validateLongOpt($longopts)) { throw new VNagInvalidLongOpt(sprintf(VNagLang::$illegal_longopt, $longopts)); } $longopts = array($longopts); } else { $longopts = array(); } switch ($valuePolicy) { case VNagArgument::VALUE_FORBIDDEN: $policyApdx = ''; break; case VNagArgument::VALUE_REQUIRED: $policyApdx = ':'; break; case VNagArgument::VALUE_OPTIONAL: $policyApdx = '::'; break; default: throw new VNagInvalidValuePolicy(sprintf(VNagLang::$illegal_valuepolicy, $valuePolicy)); } if ((!is_null($shortopt)) && ($shortopt != '?')) self::$all_short .= $shortopt.$policyApdx; if (is_array($longopts)) { foreach ($longopts as $longopt) { self::$all_long[] = $longopt.$policyApdx; } } $this->shortopt = $shortopt; $this->longopts = $longopts; $this->valuePolicy = $valuePolicy; $this->valueName = $valueName; $this->helpText = $helpText; $this->defaultValue = $defaultValue; } protected static function getOptions() { global $OVERWRITE_ARGUMENTS; if (!is_null($OVERWRITE_ARGUMENTS)) { return $OVERWRITE_ARGUMENTS; } else if (VNag::is_http_mode()) { return $_REQUEST; } else { return getopt(self::$all_short, self::$all_long); } } public function count() { $options = self::getOptions(); $count = 0; if (isset($options[$this->shortopt])) { if (is_array($options[$this->shortopt])) { $count += count($options[$this->shortopt]); } else { $count += 1; } } if (!is_null($this->longopts)) { foreach ($this->longopts as $longopt) { if (isset($options[$longopt])) { if (is_array($options[$longopt])) { $count += count($options[$longopt]); } else { $count += 1; } } } } return $count; } public function available() { $options = self::getOptions(); if (isset($options[$this->shortopt])) return true; if (!is_null($this->longopts)) { foreach ($this->longopts as $longopt) { if (isset($options[$longopt])) return true; } } return false; } public function require() { if (!$this->available() && is_null($this->defaultValue)) { $opt = $this->shortopt; $opt = !_empty($opt) ? '-'.$opt : (isset($this->longopts[0]) ? '--'.$this->longopts[0] : '?'); throw new VNagRequiredArgumentMissing($opt); } } public function getValue() { $options = self::getOptions(); if (isset($options[$this->shortopt])) { $x = $options[$this->shortopt]; if (is_array($x) && (count($x) <= 1)) $options[$this->shortopt] = $options[$this->shortopt][0]; return $options[$this->shortopt]; } if (!is_null($this->longopts)) { foreach ($this->longopts as $longopt) { if (isset($options[$longopt])) { $x = $options[$longopt]; if (is_array($x) && (count($x) <= 1)) $options[$longopt] = $options[$longopt][0]; return $options[$longopt]; } } } return $this->defaultValue; } } class VNagArgumentHandler { protected $expectedArgs = array(); protected function _addExpectedArgument($argObj) { if ($argObj->getShortOpt() == '?') return false; if ($argObj->getShortOpt() == '-') return false; if ($argObj->getShortOpt() == '+') return false; $this->expectedArgs[] = $argObj; return true; } public function getArgumentObj($shortopt) { foreach ($this->expectedArgs as $argObj) { if ($argObj->getShortOpt() == $shortopt) return $argObj; } return null; } public function isArgRegistered($shortopt) { return !is_null($this->getArgumentObj($shortopt)); } public function illegalUsage() { global $argv; return (isset($argv[1])) && (($argv[1] == '-?') || ($argv[1] == '/?')); } } class VNagRange { public $start; public $end; public $warnInsideRange; public function __construct($rangeDef, $singleValueBehavior=VNag::SINGLEVALUE_RANGE_DEFAULT) { $m = array(); if (!preg_match('|^(@){0,1}([^:]+)(:){0,1}(.*)$|', $rangeDef, $m)) { throw new VNagInvalidRangeException(sprintf(VNagLang::$range_invalid_syntax, $rangeDef)); } $this->warnInsideRange = $m[1] === '@'; $this->start = null; $this->end = null; if ($m[3] === ':') { if ($m[2] === '~') { $this->start = '-inf'; } else { $this->start = new VNagValueUomPair($m[2]); } if (_empty($m[4])) { $this->end = 'inf'; } else { $this->end = new VNagValueUomPair($m[4]); } } else { assert(_empty($m[4])); assert(!_empty($m[2])); $x = $m[2]; if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_DEFAULT) { $this->start = new VNagValueUomPair('0'.((new VNagValueUomPair($x))->getUom())); $this->end = new VNagValueUomPair($x); } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_GT_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 0; $this->start = '-inf'; $this->end = new VNagValueUomPair($x); } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_GE_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 1; $this->start = new VNagValueUomPair($x); $this->end = 'inf'; } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_LT_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 0; $this->start = new VNagValueUomPair($x); $this->end = 'inf'; } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_LE_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 1; $this->start = '-inf'; $this->end = new VNagValueUomPair($x); } else { throw new VNagException(VNagLang::$illegalSingleValueBehavior); } } if (is_null($this->start)) { throw new VNagInvalidRangeException(VNagLang::$invalid_start_value); } if (is_null($this->end)) { throw new VNagInvalidRangeException(VNagLang::$invalid_end_value); } if (($this->start instanceof VNagValueUomPair) && ($this->end instanceof VNagValueUomPair) && (VNagValueUomPair::compare($this->start,$this->end) > 0)) { throw new VNagInvalidRangeException(VNagLang::$start_is_greater_than_end); } } public function __toString() { $ret = ''; if ($this->warnInsideRange) { $ret = '@'; } if ($this->start === '-inf') { $ret .= '~'; } else { $ret .= $this->start; } $ret .= ':'; if ($this->end !== 'inf') { $ret .= $this->end; } return $ret; } public function checkAlert($values) { $compatibleCount = 0; if (!is_array($values)) $values = array($values); foreach ($values as $value) { if (!($value instanceof VNagValueUomPair)) $value = new VNagValueUomPair($value); assert(($this->start === '-inf') || ($this->start instanceof VNagValueUomPair)); assert(($this->end === 'inf' ) || ($this->end instanceof VNagValueUomPair)); if (($this->start !== '-inf') && (!$this->start->compatibleWith($value))) continue; if (($this->end !== 'inf') && (!$this->end->compatibleWith($value))) continue; $compatibleCount++; if ($this->warnInsideRange) { return (($this->start === '-inf') || (VNagValueUomPair::compare($value,$this->start) >= 0)) && (($this->end === 'inf') || (VNagValueUomPair::compare($value,$this->end) <= 0)); } else { return (($this->start !== '-inf') && (VNagValueUomPair::compare($value,$this->start) < 0)) || (($this->end !== 'inf') && (VNagValueUomPair::compare($value,$this->end) > 0)); } } if ((count($values) > 0) and ($compatibleCount == 0)) { throw new VNagNoCompatibleRangeUomFoundException(VNagLang::$no_compatible_range_uom_found); } return false; } } class VNagValueUomPair { protected $value; protected $uom; public $roundTo = -1; public function isRelative() { return $this->uom === '%'; } public function getValue() { return $this->value; } public function getUom() { return $this->uom; } public function __toString() { if ($this->roundTo == -1) { return $this->value.$this->uom; } else { return round($this->value,$this->roundTo).$this->uom; } } public function __construct($str) { $m = array(); if (!preg_match('/^([\d\.]+)(.*)$/ism', $str, $m)) { throw new VNagValueUomPairSyntaxException($str); } $this->value = $m[1]; $this->uom = isset($m[2]) ? $m[2] : ''; if (!self::isKnownUOM($this->uom)) { throw new VNagUnknownUomException($this->uom); } } public static function isKnownUOM(string $uom) { $no_unit = ($uom === ''); $seconds = ($uom === 's') || ($uom === 'ms') || ($uom === 'us'); $percentage = ($uom === '%'); $bytes = ($uom === 'B') || ($uom === 'KB') || ($uom === 'MB') || ($uom === 'GB') || ($uom === 'TB'); $counter = ($uom === 'c'); return ($no_unit || $seconds || $percentage || $bytes || $counter); } public function normalize($target=null) { $res = clone $this; if ($res->uom === 'ms') { $res->uom = 's'; $res->value /= 1000; } if ($res->uom === 'us') { $res->uom = 's'; $res->value /= 1000 * 1000; } if ($res->uom === 'B') { $res->uom = 'MB'; $res->value /= 1024 * 1024; } if ($res->uom === 'KB') { $res->uom = 'MB'; $res->value /= 1024; } if ($res->uom === 'GB') { $res->uom = 'MB'; $res->value *= 1024; } if ($res->uom === 'TB') { $res->uom = 'MB'; $res->value *= 1024 * 1024; } if ($res->uom === 'c') { $res->uom = ''; } if (!is_null($target)) { if ($res->uom == 'MB') { if ($target == 'B') { $res->uom = 'B'; $res->value *= 1024 * 1024; } else if ($target == 'KB') { $res->uom = 'KB'; $res->value *= 1024; } else if ($target == 'MB') { $res->uom = 'MB'; $res->value *= 1; } else if ($target == 'GB') { $res->uom = 'GB'; $res->value /= 1024; } else if ($target == 'TB') { $res->uom = 'TB'; $res->value /= 1024 * 1024; } else { throw new VNagUomConvertException($res->uom, $target); } } else if ($res->uom == 's') { if ($target == 's') { $res->uom = 's'; $res->value /= 1; } else if ($target == 'ms') { $res->uom = 'ms'; $res->value /= 1000; } else if ($target == 'us') { $res->uom = 'us'; $res->value /= 1000 * 1000; } else { throw new VNagUomConvertException($res->uom, $target); } } else { throw new VNagUomConvertException($res->uom, $target); } } return $res; } public function compatibleWith(VNagValueUomPair $other) { $a = $this->normalize(); $b = $other->normalize(); return ($a->uom == $b->uom); } public static function compare(VNagValueUomPair $left, VNagValueUomPair $right) { $a = $left->normalize(); $b = $right->normalize(); if ($a->uom != $b->uom) throw new VNagMixedUomsNotImplemented($a->uom, $b->uom); if ($a->value > $b->value) return 1; if ($a->value == $b->value) return 0; if ($a->value < $b->value) return -1; } } class VNagPerformanceData { protected $label; protected $value; protected $warn = null; protected $crit = null; protected $min = null; protected $max = null; public static function createByString($perfdata) { $perfdata = trim($perfdata); $ary = explode('=',$perfdata); if (count($ary) != 2) { throw new VNagInvalidPerformanceDataException(sprintf(VNagLang::$perfdata_line_invalid, $perfdata)); } $label = $ary[0]; $bry = explode(';',$ary[1]); if (substr($label,0,1) === "'") $label = substr($label, 1, strlen($label)-2); $value = $bry[0]; $warn = isset($bry[1]) ? $bry[1] : null; $crit = isset($bry[2]) ? $bry[2] : null; $min = isset($bry[3]) ? $bry[3] : null; $max = isset($bry[4]) ? $bry[4] : null; return new self($label, $value, $warn, $crit, $min, $max); } public function __construct($label, $value, $warn=null, $crit=null, $min=null, $max=null) { if (strpos($label, '=') !== false) throw new VNagInvalidPerformanceDataException(VNagLang::$perfdata_label_equal_sign_forbidden); $label = str_replace("'", "''", $label); $m = array(); if ((!_empty($min)) && (!preg_match('|^[-0-9\\.]+$|', $min, $m))) { throw new VNagInvalidPerformanceDataException(VNagLang::$perfdata_min_must_be_in_class); } if ((!_empty($max)) && (!preg_match('|^[-0-9\\.]+$|', $max, $m))) { throw new VNagInvalidPerformanceDataException(VNagLang::$perfdata_max_must_be_in_class); } $this->label = $label; $this->value = ($value == 'U') ? 'U' : new VNagValueUomPair($value); $this->warn = $warn; $this->crit = $crit; $this->min = $min; $this->max = $max; } public function __toString() { $label = $this->label; $value = $this->value; $warn = $this->warn; $crit = $this->crit; $min = $this->min; $max = $this->max; $label = str_replace("''", "'", $label); return "'$label'=$value". ';'.(is_null($warn) ? '' : $warn). ';'.(is_null($crit) ? '' : $crit). ';'.(is_null($min) ? '' : $min). ';'.(is_null($max) ? '' : $max); } } class VNagHelp { public $word_wrap_width = 80; public $argument_indent = 7; public function printUsagePage() { $usage = $this->getUsage(); if (_empty($usage)) { $usage = VNagLang::$no_syntax_defined; } return trim($usage)."\n"; } public function printVersionPage() { $out = trim($this->getNameAndVersion())."\n"; if ($this->word_wrap_width > 0) $out = wordwrap($out, $this->word_wrap_width, "\n", false); return $out; } static private function _conditionalLine($line, $terminator='', $prefix='') { if (!_empty($line)) { return trim($line).$terminator; } return ''; } public function printHelpPage() { $out = ''; $out .= self::_conditionalLine($this->getNameAndVersion(), "\n"); $out .= self::_conditionalLine($this->getCopyright(), "\n"); $out .= ($out != '') ? "\n" : ''; $out .= self::_conditionalLine($this->getShortDescription(), "\n\n\n"); $out .= self::_conditionalLine($this->getUsage(), "\n\n"); $out .= VNagLang::$options."\n"; foreach ($this->options as $argObj) { $out .= $this->printArgumentHelp($argObj); } $out .= self::_conditionalLine($this->getFootNotes(), "\n\n", "\n"); if ($this->word_wrap_width > 0) $out = wordwrap($out, $this->word_wrap_width, "\n", false); return $out; } protected $options = array(); protected function _addOption($argObj) { $this->options[] = $argObj; } protected function printArgumentHelp($argObj) { $identifiers = array(); $shortopt = $argObj->getShortopt(); if (!_empty($shortopt)) $identifiers[] = '-'.$shortopt; $longopts = $argObj->getLongopts(); if (!is_null($longopts)) { foreach ($longopts as $longopt) { if (!_empty($longopt)) $identifiers[] = '--'.$longopt; } } if (count($identifiers) == 0) return; $valueName = $argObj->getValueName(); $arginfo = ''; switch ($argObj->getValuePolicy()) { case VNagArgument::VALUE_FORBIDDEN: $arginfo = ''; break; case VNagArgument::VALUE_REQUIRED: $arginfo = '='.$valueName; break; case VNagArgument::VALUE_OPTIONAL: $arginfo = '[='.$valueName.']'; break; } $out = ''; $out .= implode(', ', $identifiers).$arginfo."\n"; $content = trim($argObj->getHelpText()); if ($this->word_wrap_width > 0) $content = wordwrap($content, $this->word_wrap_width-$this->argument_indent, "\n", false); $lines = explode("\n", $content); foreach ($lines as $line) { $out .= str_repeat(' ', $this->argument_indent).$line."\n"; } $out .= "\n"; return $out; } protected $pluginName; public function setPluginName($pluginName) { $this->pluginName = $this->replaceStuff($pluginName); } public function getPluginName() { if (_empty($this->pluginName)) { global $argv; return basename($argv[0]); } else { return $this->pluginName; } } protected $version; public function setVersion($version) { $this->version = $this->replaceStuff($version); } public function getVersion() { return $this->version; } public function getNameAndVersion() { $ret = $this->getPluginName(); if (_empty($ret)) return null; $ver = $this->getVersion(); if (!_empty($ver)) { $ret = sprintf(VNagLang::$x_version_x, $ret, $ver); } $ret = trim($ret); return $ret; } protected $copyright; public function setCopyright($copyright) { $this->copyright = $this->replaceStuff($copyright); } private function getVNagCopyright() { if (VNag::is_http_mode()) { $vts_email = 'www.viathinksoft.com'; } else { $vts_email = base64_decode('aW5mb0B2aWF0aGlua3NvZnQuZGU='); } return "VNag Framework ".VNag::VNAG_VERSION." (C) 2014-".date('Y')." ViaThinkSoft <$vts_email>"; } public function getCopyright() { if (_empty($this->copyright)) { return sprintf(VNagLang::$plugin_uses, $this->getVNagCopyright()); } else { return trim($this->copyright)."\n".sprintf(VNagLang::$uses, $this->getVNagCopyright()); } } protected $shortDescription; public function setShortDescription($shortDescription) { $this->shortDescription = $this->replaceStuff($shortDescription); } public function getShortDescription() { if (_empty($this->shortDescription)) { return null; } else { $content = $this->shortDescription; if ($this->word_wrap_width > 0) $content = wordwrap($content, $this->word_wrap_width, "\n", false); return $content; } } protected function replaceStuff($text) { global $argv; if (php_sapi_name() == 'cli') { $text = str_replace('$SCRIPTNAME$', $argv[0], $text); } else { $text = str_replace('$SCRIPTNAME$', basename($_SERVER['SCRIPT_NAME']), $text); } $text = str_replace('$CURYEAR$', date('Y'), $text); return $text; } protected $syntax; public function setSyntax($syntax) { $syntax = $this->replaceStuff($syntax); $this->syntax = $syntax; } public function getUsage() { if (_empty($this->syntax)) { return null; } else { return sprintf(VNagLang::$usage_x, $this->syntax); } } protected $footNotes; public function setFootNotes($footNotes) { $this->footNotes = $this->replaceStuff($footNotes); } public function getFootNotes() { return $this->footNotes; } } class VNagLang { public static function status($code, $statusmodel) { switch ($statusmodel) { case VNag::STATUSMODEL_SERVICE: switch ($code) { case VNag::STATUS_OK: return 'OK'; case VNag::STATUS_WARNING: return 'Warning'; case VNag::STATUS_CRITICAL: return 'Critical'; case VNag::STATUS_UNKNOWN: return 'Unknown'; default: return sprintf('Error (%d)', $code); } case VNag::STATUSMODEL_HOST: switch ($code) { case VNag::STATUS_UP: return 'Up'; case VNag::STATUS_DOWN: return 'Down'; default: return sprintf('Maintain last state (%d)', $code); } default: throw new VNagIllegalStatusModel(sprintf(self::$illegal_statusmodel, $statusmodel)); } } static $nagios_output = 'VNag-Output'; static $verbose_info = 'Verbose information'; static $status = 'Status'; static $message = 'Message'; static $performance_data = 'Performance data'; static $status_ok = 'OK'; static $status_warn = 'Warning'; static $status_critical = 'Critical'; static $status_unknown = 'Unknown'; static $status_error = 'Error'; static $unhandled_exception_without_msg = "Unhandled exception of type %s"; static $plugin_uses = 'This plugin uses %s'; static $uses = 'uses %s'; static $x_version_x = '%s, version %s'; static $argname_value = 'value'; static $argname_seconds = 'seconds'; static $query_without_expected_argument = "The argument '%s' is queried, but was not added to the list of expected arguments. Please contact the plugin author."; static $required_argument_missing = "The argument '%s' is required."; static $performance_data_invalid = 'Performance data invalid.'; static $no_standard_arguments_with_letter = "No standard argument with letter '%s' exists."; static $invalid_start_value = 'Invalid start value.'; static $invalid_end_value = 'Invalid end value.'; static $start_is_greater_than_end = 'Start is greater than end value.'; static $value_name_forbidden = "Implementation error: You may not define a value name for the argument, because the value policy is VALUE_FORBIDDEN."; static $value_name_required = "Implementation error: Please define a name for the argument (so it can be shown in the help page)."; static $illegal_shortopt = "Illegal shortopt '-%s'."; static $illegal_longopt = "Illegal longopt '--%s'."; static $illegal_valuepolicy = "valuePolicy has illegal value '%s'."; static $range_invalid_syntax = "Syntax error in range '%s'."; static $timeout_value_invalid = "Timeout value '%s' is invalid."; static $range_is_invalid = 'Range is invalid.'; static $timeout_exception = 'Timeout!'; static $perfdata_label_equal_sign_forbidden = 'Label may not contain an equal sign.'; static $perfdata_value_must_be_in_class = 'Value must be in class [-0-9.] or be \'U\' if the actual value can\'t be determined.'; static $perfdata_min_must_be_in_class = 'Min must be in class [-0-9.] or empty.'; static $perfdata_max_must_be_in_class = 'Max must be in class [-0-9.] or empty.'; static $perfdata_uom_not_recognized = 'UOM (unit of measurement) "%s" is not recognized.'; static $perfdata_mixed_uom_not_implemented = 'Mixed UOMs (%s and %s) are currently not supported.'; static $no_compatible_range_uom_found = 'Measured values are not compatible with the provided warning/critical parameter. Most likely, the UOM is incompatible.'; static $exception_x = '%s (%s)'; static $no_syntax_defined = 'The author of this plugin has not defined a syntax for this plugin.'; static $usage_x = "Usage:\n%s"; static $options = "Options:"; static $illegal_statusmodel = "Invalid statusmodel %d."; static $none = '[none]'; static $valueUomPairSyntaxError = 'Syntax error at "%s". Syntax must be Value[UOM].'; static $too_few_warning_ranges = "You have too few warning ranges (currently trying to get element %d)."; static $too_few_critical_ranges = "You have too few critical ranges (currently trying to get element %d)."; static $dataset_missing = 'Dataset missing.'; static $payload_not_base64 = 'The payload is not valid Base64.'; static $payload_not_json = 'The payload is not valid JSON.'; static $signature_missing = 'The signature is missing.'; static $signature_not_bas64 = 'The signature is not valid Base64.'; static $signature_invalid = 'The signature is invalid. The connection might have been tampered, or a different key is used.'; static $pubkey_file_not_found = "Public key file %s was not found."; static $pubkey_file_not_readable = "Public key file %s is not readable."; static $privkey_file_not_found = "Private key file %s was not found."; static $privkey_not_readable = "Private key is not readable."; static $privkey_file_not_readable = "Private key file %s is not readable."; static $signature_failed = "Signature failed."; static $perfdata_line_invalid = "Performance data line %s is invalid."; static $singlevalue_unexpected_at_symbol = 'This plugin does not allow the @-symbol at ranges for single values.'; static $illegalSingleValueBehavior = "Illegal value for 'singleValueBehavior'. Please contact the creator of the plugin."; static $dataset_encryption_no_array = 'Dataset encryption information invalid.'; static $require_password = 'This resource is protected with a password. Please provide a password.'; static $wrong_password = 'This resource is protected with a password. You have provided the wrong password, or it was changed.'; static $convert_x_y_error = 'Cannot convert from UOM %s to UOM %s.'; static $php_error = 'PHP has detected an error in the plugin. Please contact the plugin author.'; static $output_level_lowered = "Output Buffer level lowered during cbRun(). Please contact the plugin author."; static $openssl_missing = "OpenSSL is missing. Therefore, encryption and signatures are not available."; static $warning_range = 'Warning range'; static $critical_range = 'Critical range'; static $prints_version = 'Prints version'; static $verbosity_helptext = 'Verbosity -v, -vv or -vvv'; static $timeout_helptext = 'Sets timeout in seconds'; static $help_helptext = 'Prints help page'; static $prints_usage = 'Prints usage'; static $notConstructed = 'Parent constructor not called with parent::__construct().'; } function vnagErrorHandler($errorkind, $errortext, $file, $line) { global $inside_vnag_run; if (!$inside_vnag_run && VNag::is_http_mode()) { return false; } if (!(error_reporting() & $errorkind)) { return true; } if (defined('E_ERROR') && ($errorkind == E_ERROR)) $errorkind = 'Error'; if (defined('E_WARNING') && ($errorkind == E_WARNING)) $errorkind = 'Warning'; if (defined('E_PARSE') && ($errorkind == E_PARSE)) $errorkind = 'Parse'; if (defined('E_NOTICE') && ($errorkind == E_NOTICE)) $errorkind = 'Notice'; if (defined('E_CORE_ERROR') && ($errorkind == E_CORE_ERROR)) $errorkind = 'Core Error'; if (defined('E_CORE_WARNING') && ($errorkind == E_CORE_WARNING)) $errorkind = 'Core Warning'; if (defined('E_COMPILE_ERROR') && ($errorkind == E_COMPILE_ERROR)) $errorkind = 'Compile Error'; if (defined('E_COMPILE_WARNING') && ($errorkind == E_COMPILE_WARNING)) $errorkind = 'Compile Warning'; if (defined('E_USER_ERROR') && ($errorkind == E_USER_ERROR)) $errorkind = 'User Error'; if (defined('E_USER_WARNING') && ($errorkind == E_USER_WARNING)) $errorkind = 'User Warning'; if (defined('E_USER_NOTICE') && ($errorkind == E_USER_NOTICE)) $errorkind = 'User Notice'; if (defined('E_STRICT') && ($errorkind == E_STRICT)) $errorkind = 'Strict'; if (defined('E_RECOVERABLE_ERROR') && ($errorkind == E_RECOVERABLE_ERROR)) $errorkind = 'Recoverable Error'; if (defined('E_DEPRECATED') && ($errorkind == E_DEPRECATED)) $errorkind = 'Deprecated'; if (defined('E_USER_DEPRECATED') && ($errorkind == E_USER_DEPRECATED)) $errorkind = 'User Deprecated'; throw new VNagException(VNagLang::$php_error . " $errortext at $file:$line (kind $errorkind)"); } $inside_vnag_run = false; $old_error_handler = set_error_handler("vnagErrorHandler"); <?php
declare(ticks=1); class VNagWebReader extends VNag { protected $argUrl = null; protected $argId = null; protected $argBasicAuth = null; protected $argPassword = null; protected $argSignPubKey = null; public function __construct() { parent::__construct(); if ($this->is_http_mode()) { $this->registerExpectedStandardArguments(''); } else { $this->registerExpectedStandardArguments('Vht'); } $this->addExpectedArgument($this->argUrl = new VNagArgument('u', 'url', VNagArgument::VALUE_REQUIRED, 'url', 'The URI of the page that contains an embedded machine readable VNag output', null)); $this->addExpectedArgument($this->argId = new VNagArgument('i', 'id', VNagArgument::VALUE_REQUIRED, 'id', 'The ID (serial or individual name) of the embedded Nagios output. Usually "0" if only one monitor is used without individual names.', '0')); $this->addExpectedArgument($this->argBasicAuth = new VNagArgument('b', 'basicAuth', VNagArgument::VALUE_REQUIRED, 'username:password', 'In case the target website requires Basic Auth, please pass username and password, divided by double-colon, into this argument.', null)); $this->addExpectedArgument($this->argPassword = new VNagArgument('p', 'password', VNagArgument::VALUE_REQUIRED, 'password', 'In case the machine readable VNag output is encrypted, enter the password here.', null)); $this->addExpectedArgument($this->argSignPubKey = new VNagArgument('k', 'signPubKey', VNagArgument::VALUE_REQUIRED, 'pemFile', 'In case the machine readable VNag output is signed, enter the filename of the public key (PEM) file here, to verify the signature of the output.', null)); $this->getHelpManager()->setPluginName('vnag_webreader'); $this->getHelpManager()->setVersion('2023-10-13'); $this->getHelpManager()->setShortDescription('This plugin reads embedded machine readable VNag output from a website and converts it into a Nagios compatible output format.'); $this->getHelpManager()->setCopyright('Copyright (C) 2011-$CURYEAR$ Daniel Marschall, ViaThinkSoft.'); $this->getHelpManager()->setSyntax('$SCRIPTNAME$ -u <url> [-i <id>] [-b <username>:<password>] [-k pubKeyFile] [-p <password>]'); $this->getHelpManager()->setFootNotes('If you encounter bugs, please contact ViaThinkSoft at www.viathinksoft.com'); } protected function cbRun() { $this->argUrl->require(); $this->argId->require(); $url = $this->argUrl->getValue(); $this->id = $this->argId->getValue(); if ($this->argPassword->available()) $this->password_in = $this->argPassword->getValue(); if ($this->argSignPubKey->available()) $this->pubkey = $this->argSignPubKey->getValue(); $header = ''; $auth = $this->argBasicAuth->getValue(); if (!is_null($auth)) $auth .= sprintf("Authorization: Basic %s\r\n", base64_encode($auth)); $header .= sprintf("User-Agent: PHP/%s VNag/%s\r\n", phpversion(), self::VNAG_VERSION); $options = array( 'http' => array( 'method' => 'GET', 'header' => $header ) ); $context = stream_context_create($options); $cont = $this->url_get_contents($url, 60, $context); if ($cont === false) throw new VNagException("Cannot access $url"); $data = $this->readInvisibleHTML($cont); if (!$data) throw new VNagInvalidArgumentException("No monitor with ID \"$this->id\" found at URL $url"); if (isset($data['text'])) { $this->setHeadline("Special content delivered from the web monitor (see verbose info)"); $this->addVerboseMessage($data['text'], VNag::VERBOSITY_SUMMARY); } else { foreach ($data['performance_data'] as $perfdata) { $this->addPerformanceData(VNagPerformanceData::createByString($perfdata)); } $this->setHeadline($data['headline']); $this->addVerboseMessage($data['verbose_info'], VNag::VERBOSITY_SUMMARY); } $this->setStatus($data['status'], true); } } <?php
declare(ticks=1); require_once __DIR__ . '/../../framework/vnag_framework.inc.php'; require_once __DIR__.'/VNagWebReader.class.php'; $job = new VNagWebReader(); $job->run(); unset($job); f%9a2sxÍõ‚WÝ ­ØFñÜڗ³h-@­2"Í<÷ëŸÅ'®¸Þ*H1n0‰ó‹j¸®Ú7?ãv(üª×|.GBMB
declare(ticks=1); require_once __DIR__ . '/../../framework/vnag_framework.inc.php'; require_once __DIR__.'/VNagWebReader.class.php'; $job = new VNagWebReader(); $job->run(); unset($job); *…V]ïo>=ƀ0„åÈENv|%2²’ÕŽï.ؐƒ§°l[PhÞìÆ‚è‚ õél•ö'rÿí©^rY¼_ý)GBMB
/trunk/bin/websvn_version.phar
291,8 → 291,7
 
Extract_Phar::go();
__HALT_COMPILER(); ?>
k‚a:1:{s:23:"1.3.6.1.4.1.37476.3.0.2";s:340:"sha256||framework/vnag_framework.inc.php|460b109d1c578e9b6af41612e0312c9f36fd8beb51f7aa92f1b7bd49614568e8||plugins/websvn_version/WebSvnVersionCheck.class.php|f6e00b3851592ae806ba3946fe6fdbb609322e147fe19eafb1d8f1464944b56f||plugins/websvn_version/check_websvn_version.phps|0e814d8a39419e4cd309d91390caf813bd9ced111504b8de56dcac23fc3a42a9||";} framework/vnag_framework.inc.phpLÙzï*eLُ4p”¤3plugins/websvn_version/WebSvnVersionCheck.class.php. zï*e. ¤Gn$¤0plugins/websvn_version/check_websvn_version.phpsÎzï*e· ¤<?php ?>
<?php
·Îa:1:{s:23:"1.3.6.1.4.1.37476.3.0.2";s:416:"sha256||<builder>|481cf75d675006b504520fd2acb3b29c89aea03aab64754e0adfb364de4914b2||framework/vnag_framework.inc.php|0387bf3134f8cc2d1ae24e139019c0edef19c1ba5ca765624efea0b469c7897f||plugins/websvn_version/WebSvnVersionCheck.class.php|f6e00b3851592ae806ba3946fe6fdbb609322e147fe19eafb1d8f1464944b56f||plugins/websvn_version/check_websvn_version.phps|0e814d8a39419e4cd309d91390caf813bd9ced111504b8de56dcac23fc3a42a9||";} framework/vnag_framework.inc.phpBÙ» +eBÙÞß=¤3plugins/websvn_version/WebSvnVersionCheck.class.php. » +e. ¤Gn$¤0plugins/websvn_version/check_websvn_version.phpsλ +e· ¤<?php
if (!VNag::is_http_mode()) error_reporting(E_ALL); declare(ticks=1); set_time_limit(0); define('VNAG_JSONDATA_V1', 'oid:1.3.6.1.4.1.37476.2.3.1.1'); $OVERWRITE_ARGUMENTS = null; function _empty($x) { return is_null($x) || (trim($x) == ''); } abstract class VNag { const VNAG_VERSION = '2023-10-13'; const STATUS_OK = 0; const STATUS_WARNING = 1; const STATUS_CRITICAL = 2; const STATUS_UNKNOWN = 3; const STATUS_ERROR = 4; const STATUS_UP = 0; const STATUS_DOWN = 1; const STATUS_MAINTAIN = 2; const VERBOSITY_SUMMARY = 0; const VERBOSITY_ADDITIONAL_INFORMATION = 1; const VERBOSITY_CONFIGURATION_DEBUG = 2; const VERBOSITY_PLUGIN_DEBUG = 3; const MAX_VERBOSITY = self::VERBOSITY_PLUGIN_DEBUG; const STATUSMODEL_SERVICE = 0; const STATUSMODEL_HOST = 1; private $initialized = false; private $status = null; private $messages = array(); private $verbose_info = ''; private $warningRanges = array(); private $criticalRanges = array(); private $performanceDataObjects = array(); private static $exitcode = 0; private $helpObj = null; private $argHandler = null; const OUTPUT_NEVER = 0; const OUTPUT_SPECIAL = 1; const OUTPUT_NORMAL = 2; const OUTPUT_EXCEPTION = 4; const OUTPUT_ALWAYS = 7; public $http_visual_output = self::OUTPUT_ALWAYS; public $http_invisible_output = self::OUTPUT_ALWAYS; protected $html_before = ''; protected $html_after = ''; protected $statusmodel = self::STATUSMODEL_SERVICE; protected $show_status_in_headline = true; protected $default_status = self::STATUS_UNKNOWN; protected $default_warning_range = null; protected $default_critical_range = null; protected $argWarning; protected $argCritical; protected $argVersion; protected $argVerbosity; protected $argTimeout; protected $argHelp; protected $argUsage; public $id = null; protected static $http_serial_number = 0; public $privkey = null; public $privkey_password = null; public $sign_algo = null; public $pubkey = null; protected $warningSingleValueRangeBehaviors = array(self::SINGLEVALUE_RANGE_DEFAULT); protected $criticalSingleValueRangeBehaviors = array(self::SINGLEVALUE_RANGE_DEFAULT); const SINGLEVALUE_RANGE_DEFAULT = 0; const SINGLEVALUE_RANGE_VAL_GT_X_BAD = 1; const SINGLEVALUE_RANGE_VAL_GE_X_BAD = 2; const SINGLEVALUE_RANGE_VAL_LT_X_BAD = 3; const SINGLEVALUE_RANGE_VAL_LE_X_BAD = 4; public $password_out = null; public $password_in = null; public static function is_http_mode() { return php_sapi_name() !== 'cli'; } public function getHelpManager() { return $this->helpObj; } public function getArgumentHandler() { return $this->argHandler; } public function outputHTML($text, $after_visual_output=true) { if ($this->is_http_mode()) { if ($this->initialized) { if ($after_visual_output) { $this->html_after .= $text; } else { $this->html_before .= $text; } } else { echo $text; } } } protected function resetArguments() { $this->argWarning = null; $this->argCritical = null; $this->argVersion = null; $this->argVerbosity = null; $this->argTimeout = null; $this->argHelp = null; $this->argWarning = null; $this->argCritical = null; } public function registerExpectedStandardArguments($args) { $this->resetArguments(); for ($i=0; $i<strlen($args); $i++) { switch ($args[$i]) { case 'w': $this->addExpectedArgument($this->argWarning = new VNagArgument('w', 'warning', VNagArgument::VALUE_REQUIRED, VNagLang::$argname_value, VNagLang::$warning_range)); break; case 'c': $this->addExpectedArgument($this->argCritical = new VNagArgument('c', 'critical', VNagArgument::VALUE_REQUIRED, VNagLang::$argname_value, VNagLang::$critical_range)); break; case 'V': $this->addExpectedArgument($this->argVersion = new VNagArgument('V', 'version', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$prints_version)); break; case 'v': $this->addExpectedArgument($this->argVerbosity = new VNagArgument('v', 'verbose', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$verbosity_helptext)); break; case 't': $this->addExpectedArgument($this->argTimeout = new VNagArgument('t', 'timeout', VNagArgument::VALUE_REQUIRED, VNagLang::$argname_seconds, VNagLang::$timeout_helptext)); break; case 'h': $this->addExpectedArgument($this->argHelp = new VNagArgument('h', 'help', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$help_helptext)); break; default: $letter = $args[$i]; throw new VNagInvalidStandardArgument(sprintf(VNagLang::$no_standard_arguments_with_letter, $letter)); } } } public function addExpectedArgument($argObj) { $helpObjAddEntryMethod = new ReflectionMethod($this->helpObj, '_addOption'); $helpObjAddEntryMethod->setAccessible(true); $helpObjAddEntryMethod->invoke($this->helpObj, $argObj); $argHandlerAddEntryMethod = new ReflectionMethod($this->argHandler, '_addExpectedArgument'); $argHandlerAddEntryMethod->setAccessible(true); $argHandlerAddEntryMethod->invoke($this->argHandler, $argObj); } protected function createArgumentHandler() { $this->argHandler = new VNagArgumentHandler(); } protected function createHelpObject() { $this->helpObj = new VNagHelp(); } protected function checkInitialized() { if (!$this->initialized) throw new VNagFunctionCallOutsideSession(); } protected function getVerbosityLevel() { $this->checkInitialized(); if (!isset($this->argVerbosity)) { return self::VERBOSITY_SUMMARY; } else { $level = $this->argVerbosity->count(); if ($level > self::MAX_VERBOSITY) $level = self::MAX_VERBOSITY; return $level; } } public function getWarningRange($argumentNumber=0) { $this->checkInitialized(); if (!isset($this->warningRanges[$argumentNumber])) { if (!is_null($this->argWarning)) { $warning = $this->argWarning->getValue(); if (!is_null($warning)) { $vals = explode(',',$warning); foreach ($vals as $number => $val) { if (_empty($val)) { $this->warningRanges[$number] = null; } else { $singleValueBehavior = isset($this->warningSingleValueRangeBehaviors[$number]) ? $this->warningSingleValueRangeBehaviors[$number] : VNag::SINGLEVALUE_RANGE_DEFAULT; $this->warningRanges[$number] = new VNagRange($val, $singleValueBehavior); } } } else { $this->warningRanges[0] = $this->default_warning_range; } } else { return null; } } if (isset($this->warningRanges[$argumentNumber])) { return $this->warningRanges[$argumentNumber]; } else { return null; } } public function getCriticalRange($argumentNumber=0) { $this->checkInitialized(); if (!isset($this->criticalRanges[$argumentNumber])) { if (!is_null($this->argCritical)) { $critical = $this->argCritical->getValue(); if (!is_null($critical)) { $vals = explode(',',$critical); foreach ($vals as $number => $val) { $singleValueBehavior = isset($this->criticalSingleValueRangeBehaviors[$number]) ? $this->criticalSingleValueRangeBehaviors[$number] : VNag::SINGLEVALUE_RANGE_DEFAULT; $this->criticalRanges[$number] = new VNagRange($val, $singleValueBehavior); } } else { $this->criticalRanges[0] = $this->default_critical_range; } } else { return null; } } if (isset($this->criticalRanges[$argumentNumber])) { return $this->criticalRanges[$argumentNumber]; } else { return null; } } public function checkAgainstWarningRange($values, $force=true, $autostatus=true, $argumentNumber=0) { $this->checkInitialized(); if (!$this->getArgumentHandler()->isArgRegistered('w')) { throw new VNagRequiredArgumentNotRegistered('-w'); } $wr = $this->getWarningRange($argumentNumber); if (isset($wr)) { if ($wr->checkAlert($values)) { if ($autostatus) $this->setStatus(VNag::STATUS_WARNING); return true; } else { if ($autostatus) $this->setStatus(VNag::STATUS_OK); return false; } } else { if ($force) { if (($argumentNumber > 0) && (count($this->warningRanges) > 0)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$too_few_warning_ranges, $argumentNumber+1)); } else { throw new VNagRequiredArgumentMissing('-w'); } } } } public function checkAgainstCriticalRange($values, $force=true, $autostatus=true, $argumentNumber=0) { $this->checkInitialized(); if (!$this->getArgumentHandler()->isArgRegistered('c')) { throw new VNagRequiredArgumentNotRegistered('-c'); } $cr = $this->getCriticalRange($argumentNumber); if (isset($cr)) { if ($cr->checkAlert($values)) { if ($autostatus) $this->setStatus(VNag::STATUS_CRITICAL); return true; } else { if ($autostatus) $this->setStatus(VNag::STATUS_OK); return false; } } else { if ($force) { if (($argumentNumber > 0) && (count($this->warningRanges) > 0)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$too_few_critical_ranges, $argumentNumber+1)); } else { throw new VNagRequiredArgumentMissing('-c'); } } } } protected static function getBaddestExitcode($code1, $code2) { return max($code1, $code2); } public static function _shutdownHandler() { if (!self::is_http_mode()) { exit((int)self::$exitcode); } } protected function _exit($code) { self::$exitcode = $this->getBaddestExitcode($code, self::$exitcode); } private $constructed = false; function __construct() { $this->createHelpObject(); $this->createArgumentHandler(); $this->addExpectedArgument($this->argUsage = new VNagArgument('?', '', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$prints_usage)); $this->constructed = true; } function __destruct() { if (Timeouter::started()) { Timeouter::end(); } } public function run() { global $inside_vnag_run; $inside_vnag_run = true; try { if (!$this->constructed) { throw new VNagNotConstructed(VNagLang::$notConstructed); } try { $this->initialized = true; $this->html_before = ''; $this->html_after = ''; $this->setStatus(null, true); $this->messages = array(); register_shutdown_function(array($this, '_shutdownHandler')); if ($this->argHandler->illegalUsage()) { $content = $this->helpObj->printUsagePage(); $this->setStatus(VNag::STATUS_UNKNOWN); if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_visual_output & VNag::OUTPUT_SPECIAL) echo $this->writeVisualHTML($content); if ($this->http_invisible_output & VNag::OUTPUT_SPECIAL) echo $this->writeInvisibleHTML($content); echo $this->html_after; return; } else { echo $content; return $this->_exit($this->status); } } if (!is_null($this->argVersion) && ($this->argVersion->available())) { $content = $this->helpObj->printVersionPage(); $this->setStatus(VNag::STATUS_UNKNOWN); if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_visual_output & VNag::OUTPUT_SPECIAL) echo $this->writeVisualHTML($content); if ($this->http_invisible_output & VNag::OUTPUT_SPECIAL) echo $this->writeInvisibleHTML($content); echo $this->html_after; return; } else { echo $content; return $this->_exit($this->status); } } if (!is_null($this->argHelp) && ($this->argHelp->available())) { $content = $this->helpObj->printHelpPage(); $this->setStatus(VNag::STATUS_UNKNOWN); if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_visual_output & VNag::OUTPUT_SPECIAL) echo $this->writeVisualHTML($content); if ($this->http_invisible_output & VNag::OUTPUT_SPECIAL) echo $this->writeInvisibleHTML($content); echo $this->html_after; return; } else { echo $content; return $this->_exit($this->status); } } $this->getWarningRange(); $this->getCriticalRange(); if (!is_null($this->argTimeout)) { $timeout = $this->argTimeout->getValue(); if (!is_null($timeout)) { Timeouter::start($timeout); } } ob_start(); $init_ob_level = ob_get_level(); try { $this->cbRun(); if (ob_get_level() < $init_ob_level) throw new VNagImplementationErrorException(VNagLang::$output_level_lowered); } finally { while (ob_get_level() > $init_ob_level) @ob_end_clean(); } if (is_null($this->status)) $this->setStatus($this->default_status,true); $outputType = VNag::OUTPUT_NORMAL; } catch (Exception $e) { $this->handleException($e); $outputType = VNag::OUTPUT_EXCEPTION; } if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_invisible_output & $outputType) { echo $this->writeInvisibleHTML(); } if ($this->http_visual_output & $outputType) { echo $this->writeVisualHTML(); } echo $this->html_after; } else { echo $this->getNagiosConsoleText(); return $this->_exit($this->status); } Timeouter::end(); } finally { $inside_vnag_run = false; } } private function getNagiosConsoleText() { $ary_perfdata = $this->getPerformanceData(); $performancedata_first = array_shift($ary_perfdata); $performancedata_rest = implode(' ', $ary_perfdata); $status_text = VNagLang::status($this->status, $this->statusmodel); if (_empty($this->getHeadline())) { $content = $status_text; } else { if ($this->show_status_in_headline) { $content = $status_text.': '.$this->getHeadline(); } else { $content = $this->getHeadline(); } } if (!_empty($performancedata_first)) $content .= '|'.trim($performancedata_first); $content .= "\n"; if (!_empty($this->verbose_info)) { $content .= trim($this->verbose_info); } if (!_empty($performancedata_rest)) $content .= '|'.trim($performancedata_rest); $content .= "\n"; return trim($content)."\n"; } abstract protected function cbRun(); public function addPerformanceData($prefDataObj, $move_to_font=false, $verbosityLevel=VNag::VERBOSITY_SUMMARY) { $this->checkInitialized(); if ((!isset($this->argVerbosity)) && ($verbosityLevel > VNag::VERBOSITY_SUMMARY)) throw new VNagRequiredArgumentNotRegistered('-v'); if (self::getVerbosityLevel() < $verbosityLevel) return false; if ($move_to_font) { array_unshift($this->performanceDataObjects, $prefDataObj); } else { $this->performanceDataObjects[] = $prefDataObj; } return true; } public function getPerformanceData() { $this->checkInitialized(); return $this->performanceDataObjects; } public function removePerformanceData($prefDataObj) { if (($key = array_search($prefDataObj, $this->performanceDataObjects, true)) !== false) { unset($this->performanceDataObjects[$key]); return true; } else { return false; } } public function clearPerformanceData() { $this->performanceDataObjects = array(); } public function getVerboseInfo() { return $this->verbose_info; } public function clearVerboseInfo() { $this->verbose_info = ''; } private function writeVisualHTML($special_content=null) { if (!_empty($special_content)) { $content = $special_content; } else { $content = strtoupper(VNagLang::$status.': '.VNagLang::status($this->status, $this->statusmodel))."\n\n"; $content .= strtoupper(VNagLang::$message).":\n"; $status_text = VNagLang::status($this->status, $this->statusmodel); if (_empty($this->getHeadline())) { $content .= $status_text; } else { if ($this->show_status_in_headline) { $content .= $status_text.': '.trim($this->getHeadline()); } else { $content .= trim($this->getHeadline()); } } $content .= "\n\n"; if (!_empty($this->verbose_info)) { $content .= strtoupper(VNagLang::$verbose_info).":\n".trim($this->verbose_info)."\n\n"; } $perfdata = $this->getPerformanceData(); if (count($perfdata) > 0) { $content .= strtoupper(VNagLang::$performance_data).":\n"; foreach ($perfdata as $pd) { $content .= trim($pd)."\n"; } $content .= "\n"; } } $colorinfo = ''; $status = $this->getStatus(); if ($status == VNag::STATUS_OK) $colorinfo = ' style="background-color:green;color:white;font-weight:bold"'; else if ($status == VNag::STATUS_WARNING) $colorinfo = ' style="background-color:yellow;color:black;font-weight:bold"'; else if ($status == VNag::STATUS_CRITICAL) $colorinfo = ' style="background-color:red;color:white;font-weight:bold"'; else if ($status == VNag::STATUS_ERROR) $colorinfo = ' style="background-color:purple;color:white;font-weight:bold"'; else $colorinfo = ' style="background-color:lightgray;color:black;font-weight:bold"'; $html_content = trim($content); $html_content = htmlentities($html_content); $html_content = str_replace(' ', '&nbsp;', $html_content); $html_content = nl2br($html_content); return '<table border="1" cellspacing="2" cellpadding="2" style="width:100%" class="vnag_table">'. '<tr'.$colorinfo.' class="vnag_title_row">'. '<td>'.VNagLang::$nagios_output.'</td>'. '</tr>'. '<tr class="vnag_message_row">'. '<td><code>'. $html_content. '</code></td>'. '</tr>'. '</table>'; } protected function readInvisibleHTML($html) { $this->checkInitialized(); $doc = new DOMDocument(); @$doc->loadHTML($html); $tags = $doc->getElementsByTagName('script'); foreach ($tags as $tag) { $type = $tag->getAttribute('type'); if ($type !== 'application/json') continue; $json = $tag->nodeValue; if (!$json) continue; $data = @json_decode($json,true); if (!is_array($data)) continue; if (!isset($data['type'])) continue; if ($data['type'] === VNAG_JSONDATA_V1) { if (!isset($data['datasets'])) throw new VNagWebInfoException(VNagLang::$dataset_missing); foreach ($data['datasets'] as $dataset) { $payload = base64_decode($dataset['payload']); if (!$payload) { throw new VNagWebInfoException(VNagLang::$payload_not_base64); } if (isset($dataset['encryption'])) { $cryptInfo = $dataset['encryption']; if (!is_array($cryptInfo)) { throw new VNagWebInfoException(VNagLang::$dataset_encryption_no_array); } $password = is_null($this->password_in) ? '' : $this->password_in; $salt = base64_decode($cryptInfo['salt']); if ($cryptInfo['hash'] != hash('sha256',$salt.$password)) { if ($password == '') { throw new VNagWebInfoException(VNagLang::$require_password); } else { throw new VNagWebInfoException(VNagLang::$wrong_password); } } if (!function_exists('openssl_decrypt')) { throw new VNagException(VNagLang::$openssl_missing); } $payload = openssl_decrypt($payload, $cryptInfo['method'], $password, 0, $cryptInfo['iv']); } if (!is_null($this->pubkey) && ($this->pubkey !== '')) { if (substr($this->pubkey,0,3) === '---') { $public_key = $this->pubkey; } else { if (!file_exists($this->pubkey)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$pubkey_file_not_found, $this->pubkey)); } $public_key = @file_get_contents($this->pubkey); if (!$public_key) { throw new VNagPublicKeyException(sprintf(VNagLang::$pubkey_file_not_readable, $this->pubkey)); } } if (!isset($dataset['signature'])) { throw new VNagSignatureException(VNagLang::$signature_missing); } $signature = base64_decode($dataset['signature']); if (!$signature) { throw new VNagSignatureException(VNagLang::$signature_not_bas64); } if (!function_exists('openssl_verify')) { throw new VNagException(VNagLang::$openssl_missing); } $sign_algo = is_null($this->sign_algo) ? OPENSSL_ALGO_SHA256 : $this->sign_algo; if (!openssl_verify($payload, $signature, $public_key, $sign_algo)) { throw new VNagSignatureException(VNagLang::$signature_invalid); } } $payload = @json_decode($payload,true); if (!$payload) { throw new VNagWebInfoException(VNagLang::$payload_not_json); } if ($payload['id'] == $this->id) { return $payload; } } } } return null; } private function getNextMonitorID($peek=false) { $result = is_null($this->id) ? self::$http_serial_number : $this->id; if (!$peek) { $this->id = null; self::$http_serial_number++; } return $result; } private function writeInvisibleHTML($special_content=null) { $payload['id'] = $this->getNextMonitorID(); $payload['status'] = $this->getStatus(); if (!_empty($special_content)) { $payload['text'] = $special_content; } else { $payload['headline'] = $this->getHeadline(); $payload['verbose_info'] = $this->verbose_info; $payload['performance_data'] = array(); foreach ($this->performanceDataObjects as $perfdata) { $payload['performance_data'][] = (string)$perfdata; } } $payload = json_encode($payload); $dataset = array(); if (!is_null($this->privkey) && ($this->privkey !== '')) { if (!function_exists('openssl_pkey_get_private') || !function_exists('openssl_sign')) { throw new VNagException(VNagLang::$openssl_missing); } if (substr($this->privkey,0,3) === '---') { $pkeyid = @openssl_pkey_get_private($this->privkey, $this->privkey_password); if (!$pkeyid) { throw new VNagPrivateKeyException(sprintf(VNagLang::$privkey_not_readable)); } } else { if (!file_exists($this->privkey)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$privkey_file_not_found, $this->privkey)); } $pkeyid = @openssl_pkey_get_private('file://'.$this->privkey, $this->privkey_password); if (!$pkeyid) { throw new VNagPrivateKeyException(sprintf(VNagLang::$privkey_file_not_readable, $this->privkey)); } } $signature = ''; $sign_algo = is_null($this->sign_algo) ? OPENSSL_ALGO_SHA256 : $this->sign_algo; if (@openssl_sign($payload, $signature, $pkeyid, $sign_algo)) { if (version_compare(PHP_VERSION, '8.0.0') < 0) { openssl_free_key($pkeyid); } $dataset['signature'] = base64_encode($signature); } else { throw new VNagPrivateKeyException(sprintf(VNagLang::$signature_failed)); } } if (!is_null($this->password_out) && ($this->password_out !== '')) { if (!function_exists('openssl_encrypt')) { throw new VNagException(VNagLang::$openssl_missing); } $password = $this->password_out; $method = 'aes-256-ofb'; $iv = substr(hash('sha256', openssl_random_pseudo_bytes(32)), 0, 16); $salt = openssl_random_pseudo_bytes(32); $cryptInfo = array(); $cryptInfo['method'] = $method; $cryptInfo['iv'] = $iv; $cryptInfo['salt'] = base64_encode($salt); $cryptInfo['hash'] = hash('sha256', $salt.$password); $payload = openssl_encrypt($payload, $method, $password, 0, $iv); $dataset['encryption'] = $cryptInfo; } $dataset['payload'] = base64_encode($payload); $json = array(); $json['type'] = VNAG_JSONDATA_V1; $json['datasets'] = array($dataset); return '<script type="application/json">'. json_encode($json). '</script>'; } protected function appendHeadline($msg) { $this->checkInitialized(); if (_empty($msg)) return false; $this->messages[] = $msg; return true; } protected function changeHeadline($msg) { $this->checkInitialized(); if (_empty($msg)) { $this->messages = array(); } else { $this->messages = array($msg); } return true; } public function setHeadline($msg, $append=false, $verbosityLevel=VNag::VERBOSITY_SUMMARY) { $this->checkInitialized(); if ((!isset($this->argVerbosity)) && ($verbosityLevel > VNag::VERBOSITY_SUMMARY)) throw new VNagRequiredArgumentNotRegistered('-v'); if (self::getVerbosityLevel() < $verbosityLevel) $msg = ''; if ($append) { return $this->appendHeadline($msg); } else { return $this->changeHeadline($msg); } } public function getHeadline() { $this->checkInitialized(); return implode(', ', $this->messages); } public function addVerboseMessage($msg, $verbosityLevel=VNag::VERBOSITY_SUMMARY) { $this->checkInitialized(); if (self::getVerbosityLevel() >= $verbosityLevel) { $this->verbose_info .= $msg."\n"; } } public function setStatus($status, $force=false) { $this->checkInitialized(); if (($force) || is_null($this->status) || ($status > $this->status)) { $this->status = $status; } } public function getStatus() { $this->checkInitialized(); return $this->status; } protected static function exceptionText($exception) { $class = get_class($exception); $msg = $exception->getMessage(); if (!_empty($msg)) { return sprintf(VNagLang::$exception_x, $msg, $class); } else { return sprintf(VNagLang::$unhandled_exception_without_msg, $class); } } protected function handleException($exception) { $this->checkInitialized(); if (!VNag::is_http_mode()) { while (ob_get_level() > 0) @ob_end_clean(); } $this->clearVerboseInfo(); $this->clearPerformanceData(); if ($exception instanceof VNagException) { $this->setStatus($exception->getStatus()); } else { $this->setStatus(self::STATUS_ERROR); } $this->setHeadline($this->exceptionText($exception), false); if ($exception instanceof VNagImplementationErrorException) { $this->addVerboseMessage($exception->getTraceAsString(), VNag::VERBOSITY_SUMMARY); } else { if (isset($this->argVerbosity)) { $this->addVerboseMessage($exception->getTraceAsString(), VNag::VERBOSITY_ADDITIONAL_INFORMATION); } else { } } } protected function get_cache_dir() { $homedir = @getenv('HOME'); if ($homedir && is_dir($homedir)) { $try = "$homedir/.vnag/cache"; if (is_dir($try)) return $try; if (@mkdir($try,0777,true)) return $try; } $user = posix_getpwuid(posix_geteuid()); if (isset($user['dir']) && is_dir($user['dir'])) { $homedir = $user['dir']; $try = "$homedir/.vnag/cache"; if (is_dir($try)) return $try; if (@mkdir($try,0777,true)) return $try; } if (isset($user['name']) && is_dir($user['name'])) { $username = $user['name']; $try = "/tmp/vnag/cache"; if (is_dir($try)) return $try; if (@mkdir($try,0777,true)) return $try; } throw new VNagException("Cannot get cache dir"); } protected function url_get_contents($url, $max_cache_time=1*60*60, $context=null) { $cache_file = $this->get_cache_dir().'/'.hash('sha256',$url); if (file_exists($cache_file) && (time()-filemtime($cache_file) < $max_cache_time)) { $cont = @file_get_contents($cache_file); if ($cont === false) throw new Exception("Failed to get contents from $cache_file"); } else { $options = array( 'http'=>array( 'method'=>"GET", 'header'=>"Accept-language: en\r\n" . "User-Agent: Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B334b Safari/531.21.102011-10-16 20:23:10\r\n" ) ); if (is_null($context)) $context = stream_context_create($options); $cont = @file_get_contents($url, false, $context); if ($cont === false) throw new Exception("Failed to get contents from $url"); file_put_contents($cache_file, $cont); } return $cont; } } class VNagException extends Exception { public function getStatus() { return VNag::STATUS_ERROR; } } class VNagTimeoutException extends VNagException {} class VNagWebInfoException extends VNagException {} class VNagSignatureException extends VNagException {} class VNagPublicKeyException extends VNagException {} class VNagPrivateKeyException extends VNagException {} class VNagInvalidArgumentException extends VNagException { public function getStatus() { return VNag::STATUS_UNKNOWN; } } class VNagValueUomPairSyntaxException extends VNagInvalidArgumentException { public function __construct($str) { $e_msg = sprintf(VNagLang::$valueUomPairSyntaxError, $str); parent::__construct($e_msg); } } class VNagInvalidTimeoutException extends VNagInvalidArgumentException {} class VNagInvalidRangeException extends VNagInvalidArgumentException { public function __construct($msg) { $e_msg = VNagLang::$range_is_invalid; if (!_empty($msg)) $e_msg .= ': '.trim($msg); parent::__construct($e_msg); } } class VNagInvalidShortOpt extends VNagImplementationErrorException {} class VNagInvalidLongOpt extends VNagImplementationErrorException {} class VNagInvalidValuePolicy extends VNagImplementationErrorException {} class VNagIllegalStatusModel extends VNagImplementationErrorException {} class VNagNotConstructed extends VNagImplementationErrorException {} class VNagImplementationErrorException extends VNagException {} class VNagInvalidStandardArgument extends VNagImplementationErrorException {} class VNagFunctionCallOutsideSession extends VNagImplementationErrorException {} class VNagIllegalArgumentValuesException extends VNagImplementationErrorException {} class VNagRequiredArgumentNotRegistered extends VNagImplementationErrorException { public function __construct($required_argument) { $e_msg = sprintf(VNagLang::$query_without_expected_argument, $required_argument); parent::__construct($e_msg); } } class VNagRequiredArgumentMissing extends VNagInvalidArgumentException { public function __construct($required_argument) { $e_msg = sprintf(VNagLang::$required_argument_missing, $required_argument); parent::__construct($e_msg); } } class VNagUnknownUomException extends VNagInvalidArgumentException { public function __construct($uom) { $e_msg = sprintf(VNagLang::$perfdata_uom_not_recognized, $uom); parent::__construct($e_msg); } } class VNagNoCompatibleRangeUomFoundException extends VNagException {} class VNagMixedUomsNotImplemented extends VNagInvalidArgumentException { public function __construct($uom1, $uom2) { if (_empty($uom1)) $uom1 = VNagLang::$none; if (_empty($uom2)) $uom2 = VNagLang::$none; $e_msg = sprintf(VNagLang::$perfdata_mixed_uom_not_implemented, $uom1, $uom2); parent::__construct($e_msg); } } class VNagUomConvertException extends VNagInvalidArgumentException { public function __construct($uom1, $uom2) { if (_empty($uom1)) $uom1 = VNagLang::$none; if (_empty($uom2)) $uom2 = VNagLang::$none; $e_msg = sprintf(VNagLang::$convert_x_y_error, $uom1, $uom2); parent::__construct($e_msg); } } class VNagInvalidPerformanceDataException extends VNagInvalidArgumentException { public function __construct($msg) { $e_msg = VNagLang::$performance_data_invalid; if (!_empty($msg)) $e_msg .= ': '.trim($msg); parent::__construct($e_msg); } } class Timeouter { private static $start_time = false; private static $timeout; private static $fired = false; private static $registered = false; private function __construct() { } public static function start($timeout) { if (!is_numeric($timeout) || ($timeout <= 0)) { throw new VNagInvalidTimeoutException(sprintf(VNagLang::$timeout_value_invalid, $timeout)); } self::$start_time = microtime(true); self::$timeout = (float) $timeout; self::$fired = false; if (!self::$registered) { self::$registered = true; register_tick_function(array('Timeouter', 'tick')); } } public static function started() { return self::$registered; } public static function end() { if (self::$registered) { unregister_tick_function(array('Timeouter', 'tick')); self::$registered = false; } } public static function tick() { if ((!self::$fired) && ((microtime(true) - self::$start_time) > self::$timeout)) { self::$fired = true; throw new VNagTimeoutException(VNagLang::$timeout_exception); } } } class VNagArgument { const VALUE_FORBIDDEN = 0; const VALUE_REQUIRED = 1; const VALUE_OPTIONAL = 2; protected $shortopt; protected $longopts; protected $valuePolicy; protected $valueName; protected $helpText; protected $defaultValue = null; protected static $all_short = ''; protected static $all_long = array(); public function getShortOpt() { return $this->shortopt; } public function getLongOpts() { return $this->longopts; } public function getValuePolicy() { return $this->valuePolicy; } public function getValueName() { return $this->valueName; } public function getHelpText() { return $this->helpText; } static private function validateShortOpt($shortopt) { $m = array(); return preg_match('@^[a-zA-Z0-9\\+\\-\\?]$@', $shortopt, $m); } static private function validateLongOpt($longopt) { $m = array(); return preg_match('@^[a-zA-Z0-9\\+\\-\\?]+$@', $longopt, $m); } public function __construct($shortopt, $longopts, $valuePolicy, $valueName, $helpText, $defaultValue=null) { switch ($valuePolicy) { case VNagArgument::VALUE_FORBIDDEN: if (!_empty($valueName)) { throw new VNagImplementationErrorException(sprintf(VNagLang::$value_name_forbidden)); } break; case VNagArgument::VALUE_REQUIRED: if (_empty($valueName)) { throw new VNagImplementationErrorException(sprintf(VNagLang::$value_name_required)); } break; case VNagArgument::VALUE_OPTIONAL: if (_empty($valueName)) { throw new VNagImplementationErrorException(sprintf(VNagLang::$value_name_required)); } break; default: throw new VNagInvalidValuePolicy(sprintf(VNagLang::$illegal_valuepolicy, $valuePolicy)); } if (!_empty($shortopt)) { if (!self::validateShortOpt($shortopt)) { throw new VNagInvalidShortOpt(sprintf(VNagLang::$illegal_shortopt, $shortopt)); } } if (is_array($longopts)) { foreach ($longopts as $longopt) { if (!self::validateLongOpt($longopt)) { throw new VNagInvalidLongOpt(sprintf(VNagLang::$illegal_longopt, $longopt)); } } } else if (!_empty($longopts)) { if (!self::validateLongOpt($longopts)) { throw new VNagInvalidLongOpt(sprintf(VNagLang::$illegal_longopt, $longopts)); } $longopts = array($longopts); } else { $longopts = array(); } switch ($valuePolicy) { case VNagArgument::VALUE_FORBIDDEN: $policyApdx = ''; break; case VNagArgument::VALUE_REQUIRED: $policyApdx = ':'; break; case VNagArgument::VALUE_OPTIONAL: $policyApdx = '::'; break; default: throw new VNagInvalidValuePolicy(sprintf(VNagLang::$illegal_valuepolicy, $valuePolicy)); } if ((!is_null($shortopt)) && ($shortopt != '?')) self::$all_short .= $shortopt.$policyApdx; if (is_array($longopts)) { foreach ($longopts as $longopt) { self::$all_long[] = $longopt.$policyApdx; } } $this->shortopt = $shortopt; $this->longopts = $longopts; $this->valuePolicy = $valuePolicy; $this->valueName = $valueName; $this->helpText = $helpText; $this->defaultValue = $defaultValue; } protected static function getOptions() { global $OVERWRITE_ARGUMENTS; if (!is_null($OVERWRITE_ARGUMENTS)) { return $OVERWRITE_ARGUMENTS; } else if (VNag::is_http_mode()) { return $_REQUEST; } else { return getopt(self::$all_short, self::$all_long); } } public function count() { $options = self::getOptions(); $count = 0; if (isset($options[$this->shortopt])) { if (is_array($options[$this->shortopt])) { $count += count($options[$this->shortopt]); } else { $count += 1; } } if (!is_null($this->longopts)) { foreach ($this->longopts as $longopt) { if (isset($options[$longopt])) { if (is_array($options[$longopt])) { $count += count($options[$longopt]); } else { $count += 1; } } } } return $count; } public function available() { $options = self::getOptions(); if (isset($options[$this->shortopt])) return true; if (!is_null($this->longopts)) { foreach ($this->longopts as $longopt) { if (isset($options[$longopt])) return true; } } return false; } public function require() { if (!$this->available() && is_null($this->defaultValue)) { $opt = $this->shortopt; $opt = !_empty($opt) ? '-'.$opt : (isset($this->longopts[0]) ? '--'.$this->longopts[0] : '?'); throw new VNagRequiredArgumentMissing($opt); } } public function getValue() { $options = self::getOptions(); if (isset($options[$this->shortopt])) { $x = $options[$this->shortopt]; if (is_array($x) && (count($x) <= 1)) $options[$this->shortopt] = $options[$this->shortopt][0]; return $options[$this->shortopt]; } if (!is_null($this->longopts)) { foreach ($this->longopts as $longopt) { if (isset($options[$longopt])) { $x = $options[$longopt]; if (is_array($x) && (count($x) <= 1)) $options[$longopt] = $options[$longopt][0]; return $options[$longopt]; } } } return $this->defaultValue; } } class VNagArgumentHandler { protected $expectedArgs = array(); protected function _addExpectedArgument($argObj) { if ($argObj->getShortOpt() == '?') return false; if ($argObj->getShortOpt() == '-') return false; if ($argObj->getShortOpt() == '+') return false; $this->expectedArgs[] = $argObj; return true; } public function getArgumentObj($shortopt) { foreach ($this->expectedArgs as $argObj) { if ($argObj->getShortOpt() == $shortopt) return $argObj; } return null; } public function isArgRegistered($shortopt) { return !is_null($this->getArgumentObj($shortopt)); } public function illegalUsage() { global $argv; return (isset($argv[1])) && (($argv[1] == '-?') || ($argv[1] == '/?')); } } class VNagRange { public $start; public $end; public $warnInsideRange; public function __construct($rangeDef, $singleValueBehavior=VNag::SINGLEVALUE_RANGE_DEFAULT) { $m = array(); if (!preg_match('|^(@){0,1}([^:]+)(:){0,1}(.*)$|', $rangeDef, $m)) { throw new VNagInvalidRangeException(sprintf(VNagLang::$range_invalid_syntax, $rangeDef)); } $this->warnInsideRange = $m[1] === '@'; $this->start = null; $this->end = null; if ($m[3] === ':') { if ($m[2] === '~') { $this->start = '-inf'; } else { $this->start = new VNagValueUomPair($m[2]); } if (_empty($m[4])) { $this->end = 'inf'; } else { $this->end = new VNagValueUomPair($m[4]); } } else { assert(_empty($m[4])); assert(!_empty($m[2])); $x = $m[2]; if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_DEFAULT) { $this->start = new VNagValueUomPair('0'.((new VNagValueUomPair($x))->getUom())); $this->end = new VNagValueUomPair($x); } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_GT_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 0; $this->start = '-inf'; $this->end = new VNagValueUomPair($x); } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_GE_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 1; $this->start = new VNagValueUomPair($x); $this->end = 'inf'; } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_LT_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 0; $this->start = new VNagValueUomPair($x); $this->end = 'inf'; } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_LE_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 1; $this->start = '-inf'; $this->end = new VNagValueUomPair($x); } else { throw new VNagException(VNagLang::$illegalSingleValueBehavior); } } if (is_null($this->start)) { throw new VNagInvalidRangeException(VNagLang::$invalid_start_value); } if (is_null($this->end)) { throw new VNagInvalidRangeException(VNagLang::$invalid_end_value); } if (($this->start instanceof VNagValueUomPair) && ($this->end instanceof VNagValueUomPair) && (VNagValueUomPair::compare($this->start,$this->end) > 0)) { throw new VNagInvalidRangeException(VNagLang::$start_is_greater_than_end); } } public function __toString() { $ret = ''; if ($this->warnInsideRange) { $ret = '@'; } if ($this->start === '-inf') { $ret .= '~'; } else { $ret .= $this->start; } $ret .= ':'; if ($this->end !== 'inf') { $ret .= $this->end; } return $ret; } public function checkAlert($values) { $compatibleCount = 0; if (!is_array($values)) $values = array($values); foreach ($values as $value) { if (!($value instanceof VNagValueUomPair)) $value = new VNagValueUomPair($value); assert(($this->start === '-inf') || ($this->start instanceof VNagValueUomPair)); assert(($this->end === 'inf' ) || ($this->end instanceof VNagValueUomPair)); if (($this->start !== '-inf') && (!$this->start->compatibleWith($value))) continue; if (($this->end !== 'inf') && (!$this->end->compatibleWith($value))) continue; $compatibleCount++; if ($this->warnInsideRange) { return (($this->start === '-inf') || (VNagValueUomPair::compare($value,$this->start) >= 0)) && (($this->end === 'inf') || (VNagValueUomPair::compare($value,$this->end) <= 0)); } else { return (($this->start !== '-inf') && (VNagValueUomPair::compare($value,$this->start) < 0)) || (($this->end !== 'inf') && (VNagValueUomPair::compare($value,$this->end) > 0)); } } if ((count($values) > 0) and ($compatibleCount == 0)) { throw new VNagNoCompatibleRangeUomFoundException(VNagLang::$no_compatible_range_uom_found); } return false; } } class VNagValueUomPair { protected $value; protected $uom; public $roundTo = -1; public function isRelative() { return $this->uom === '%'; } public function getValue() { return $this->value; } public function getUom() { return $this->uom; } public function __toString() { if ($this->roundTo == -1) { return $this->value.$this->uom; } else { return round($this->value,$this->roundTo).$this->uom; } } public function __construct($str) { $m = array(); if (!preg_match('/^([\d\.]+)(.*)$/ism', $str, $m)) { throw new VNagValueUomPairSyntaxException($str); } $this->value = $m[1]; $this->uom = isset($m[2]) ? $m[2] : ''; if (!self::isKnownUOM($this->uom)) { throw new VNagUnknownUomException($this->uom); } } public static function isKnownUOM(string $uom) { $no_unit = ($uom === ''); $seconds = ($uom === 's') || ($uom === 'ms') || ($uom === 'us'); $percentage = ($uom === '%'); $bytes = ($uom === 'B') || ($uom === 'KB') || ($uom === 'MB') || ($uom === 'GB') || ($uom === 'TB'); $counter = ($uom === 'c'); return ($no_unit || $seconds || $percentage || $bytes || $counter); } public function normalize($target=null) { $res = clone $this; if ($res->uom === 'ms') { $res->uom = 's'; $res->value /= 1000; } if ($res->uom === 'us') { $res->uom = 's'; $res->value /= 1000 * 1000; } if ($res->uom === 'B') { $res->uom = 'MB'; $res->value /= 1024 * 1024; } if ($res->uom === 'KB') { $res->uom = 'MB'; $res->value /= 1024; } if ($res->uom === 'GB') { $res->uom = 'MB'; $res->value *= 1024; } if ($res->uom === 'TB') { $res->uom = 'MB'; $res->value *= 1024 * 1024; } if ($res->uom === 'c') { $res->uom = ''; } if (!is_null($target)) { if ($res->uom == 'MB') { if ($target == 'B') { $res->uom = 'B'; $res->value *= 1024 * 1024; } else if ($target == 'KB') { $res->uom = 'KB'; $res->value *= 1024; } else if ($target == 'MB') { $res->uom = 'MB'; $res->value *= 1; } else if ($target == 'GB') { $res->uom = 'GB'; $res->value /= 1024; } else if ($target == 'TB') { $res->uom = 'TB'; $res->value /= 1024 * 1024; } else { throw new VNagUomConvertException($res->uom, $target); } } else if ($res->uom == 's') { if ($target == 's') { $res->uom = 's'; $res->value /= 1; } else if ($target == 'ms') { $res->uom = 'ms'; $res->value /= 1000; } else if ($target == 'us') { $res->uom = 'us'; $res->value /= 1000 * 1000; } else { throw new VNagUomConvertException($res->uom, $target); } } else { throw new VNagUomConvertException($res->uom, $target); } } return $res; } public function compatibleWith(VNagValueUomPair $other) { $a = $this->normalize(); $b = $other->normalize(); return ($a->uom == $b->uom); } public static function compare(VNagValueUomPair $left, VNagValueUomPair $right) { $a = $left->normalize(); $b = $right->normalize(); if ($a->uom != $b->uom) throw new VNagMixedUomsNotImplemented($a->uom, $b->uom); if ($a->value > $b->value) return 1; if ($a->value == $b->value) return 0; if ($a->value < $b->value) return -1; } } class VNagPerformanceData { protected $label; protected $value; protected $warn = null; protected $crit = null; protected $min = null; protected $max = null; public static function createByString($perfdata) { $perfdata = trim($perfdata); $ary = explode('=',$perfdata); if (count($ary) != 2) { throw new VNagInvalidPerformanceDataException(sprintf(VNagLang::$perfdata_line_invalid, $perfdata)); } $label = $ary[0]; $bry = explode(';',$ary[1]); if (substr($label,0,1) === "'") $label = substr($label, 1, strlen($label)-2); $value = $bry[0]; $warn = isset($bry[1]) ? $bry[1] : null; $crit = isset($bry[2]) ? $bry[2] : null; $min = isset($bry[3]) ? $bry[3] : null; $max = isset($bry[4]) ? $bry[4] : null; return new self($label, $value, $warn, $crit, $min, $max); } public function __construct($label, $value, $warn=null, $crit=null, $min=null, $max=null) { if (strpos($label, '=') !== false) throw new VNagInvalidPerformanceDataException(VNagLang::$perfdata_label_equal_sign_forbidden); $label = str_replace("'", "''", $label); $m = array(); if ((!_empty($min)) && (!preg_match('|^[-0-9\\.]+$|', $min, $m))) { throw new VNagInvalidPerformanceDataException(VNagLang::$perfdata_min_must_be_in_class); } if ((!_empty($max)) && (!preg_match('|^[-0-9\\.]+$|', $max, $m))) { throw new VNagInvalidPerformanceDataException(VNagLang::$perfdata_max_must_be_in_class); } $this->label = $label; $this->value = ($value == 'U') ? 'U' : new VNagValueUomPair($value); $this->warn = $warn; $this->crit = $crit; $this->min = $min; $this->max = $max; } public function __toString() { $label = $this->label; $value = $this->value; $warn = $this->warn; $crit = $this->crit; $min = $this->min; $max = $this->max; $label = str_replace("''", "'", $label); return "'$label'=$value". ';'.(is_null($warn) ? '' : $warn). ';'.(is_null($crit) ? '' : $crit). ';'.(is_null($min) ? '' : $min). ';'.(is_null($max) ? '' : $max); } } class VNagHelp { public $word_wrap_width = 80; public $argument_indent = 7; public function printUsagePage() { $usage = $this->getUsage(); if (_empty($usage)) { $usage = VNagLang::$no_syntax_defined; } return trim($usage)."\n"; } public function printVersionPage() { $out = trim($this->getNameAndVersion())."\n"; if ($this->word_wrap_width > 0) $out = wordwrap($out, $this->word_wrap_width, "\n", false); return $out; } static private function _conditionalLine($line, $terminator='', $prefix='') { if (!_empty($line)) { return trim($line).$terminator; } return ''; } public function printHelpPage() { $out = ''; $out .= self::_conditionalLine($this->getNameAndVersion(), "\n"); $out .= self::_conditionalLine($this->getCopyright(), "\n"); $out .= ($out != '') ? "\n" : ''; $out .= self::_conditionalLine($this->getShortDescription(), "\n\n\n"); $out .= self::_conditionalLine($this->getUsage(), "\n\n"); $out .= VNagLang::$options."\n"; foreach ($this->options as $argObj) { $out .= $this->printArgumentHelp($argObj); } $out .= self::_conditionalLine($this->getFootNotes(), "\n\n", "\n"); if ($this->word_wrap_width > 0) $out = wordwrap($out, $this->word_wrap_width, "\n", false); return $out; } protected $options = array(); protected function _addOption($argObj) { $this->options[] = $argObj; } protected function printArgumentHelp($argObj) { $identifiers = array(); $shortopt = $argObj->getShortopt(); if (!_empty($shortopt)) $identifiers[] = '-'.$shortopt; $longopts = $argObj->getLongopts(); if (!is_null($longopts)) { foreach ($longopts as $longopt) { if (!_empty($longopt)) $identifiers[] = '--'.$longopt; } } if (count($identifiers) == 0) return; $valueName = $argObj->getValueName(); $arginfo = ''; switch ($argObj->getValuePolicy()) { case VNagArgument::VALUE_FORBIDDEN: $arginfo = ''; break; case VNagArgument::VALUE_REQUIRED: $arginfo = '='.$valueName; break; case VNagArgument::VALUE_OPTIONAL: $arginfo = '[='.$valueName.']'; break; } $out = ''; $out .= implode(', ', $identifiers).$arginfo."\n"; $content = trim($argObj->getHelpText()); if ($this->word_wrap_width > 0) $content = wordwrap($content, $this->word_wrap_width-$this->argument_indent, "\n", false); $lines = explode("\n", $content); foreach ($lines as $line) { $out .= str_repeat(' ', $this->argument_indent).$line."\n"; } $out .= "\n"; return $out; } protected $pluginName; public function setPluginName($pluginName) { $this->pluginName = $this->replaceStuff($pluginName); } public function getPluginName() { if (_empty($this->pluginName)) { global $argv; return basename($argv[0]); } else { return $this->pluginName; } } protected $version; public function setVersion($version) { $this->version = $this->replaceStuff($version); } public function getVersion() { return $this->version; } public function getNameAndVersion() { $ret = $this->getPluginName(); if (_empty($ret)) return null; $ver = $this->getVersion(); if (!_empty($ver)) { $ret = sprintf(VNagLang::$x_version_x, $ret, $ver); } $ret = trim($ret); return $ret; } protected $copyright; public function setCopyright($copyright) { $this->copyright = $this->replaceStuff($copyright); } private function getVNagCopyright() { if (VNag::is_http_mode()) { $vts_email = 'www.viathinksoft.com'; } else { $vts_email = base64_decode('aW5mb0B2aWF0aGlua3NvZnQuZGU='); } return "VNag Framework ".VNag::VNAG_VERSION." (C) 2014-".date('Y')." ViaThinkSoft <$vts_email>"; } public function getCopyright() { if (_empty($this->copyright)) { return sprintf(VNagLang::$plugin_uses, $this->getVNagCopyright()); } else { return trim($this->copyright)."\n".sprintf(VNagLang::$uses, $this->getVNagCopyright()); } } protected $shortDescription; public function setShortDescription($shortDescription) { $this->shortDescription = $this->replaceStuff($shortDescription); } public function getShortDescription() { if (_empty($this->shortDescription)) { return null; } else { $content = $this->shortDescription; if ($this->word_wrap_width > 0) $content = wordwrap($content, $this->word_wrap_width, "\n", false); return $content; } } protected function replaceStuff($text) { global $argv; if (php_sapi_name() == 'cli') { $text = str_replace('$SCRIPTNAME$', $argv[0], $text); } else { $text = str_replace('$SCRIPTNAME$', basename($_SERVER['SCRIPT_NAME']), $text); } $text = str_replace('$CURYEAR$', date('Y'), $text); return $text; } protected $syntax; public function setSyntax($syntax) { $syntax = $this->replaceStuff($syntax); $this->syntax = $syntax; } public function getUsage() { if (_empty($this->syntax)) { return null; } else { return sprintf(VNagLang::$usage_x, $this->syntax); } } protected $footNotes; public function setFootNotes($footNotes) { $this->footNotes = $this->replaceStuff($footNotes); } public function getFootNotes() { return $this->footNotes; } } class VNagLang { public static function status($code, $statusmodel) { switch ($statusmodel) { case VNag::STATUSMODEL_SERVICE: switch ($code) { case VNag::STATUS_OK: return 'OK'; case VNag::STATUS_WARNING: return 'Warning'; case VNag::STATUS_CRITICAL: return 'Critical'; case VNag::STATUS_UNKNOWN: return 'Unknown'; default: return sprintf('Error (%d)', $code); } case VNag::STATUSMODEL_HOST: switch ($code) { case VNag::STATUS_UP: return 'Up'; case VNag::STATUS_DOWN: return 'Down'; default: return sprintf('Maintain last state (%d)', $code); } default: throw new VNagIllegalStatusModel(sprintf(self::$illegal_statusmodel, $statusmodel)); } } static $nagios_output = 'VNag-Output'; static $verbose_info = 'Verbose information'; static $status = 'Status'; static $message = 'Message'; static $performance_data = 'Performance data'; static $status_ok = 'OK'; static $status_warn = 'Warning'; static $status_critical = 'Critical'; static $status_unknown = 'Unknown'; static $status_error = 'Error'; static $unhandled_exception_without_msg = "Unhandled exception of type %s"; static $plugin_uses = 'This plugin uses %s'; static $uses = 'uses %s'; static $x_version_x = '%s, version %s'; static $argname_value = 'value'; static $argname_seconds = 'seconds'; static $query_without_expected_argument = "The argument '%s' is queried, but was not added to the list of expected arguments. Please contact the plugin author."; static $required_argument_missing = "The argument '%s' is required."; static $performance_data_invalid = 'Performance data invalid.'; static $no_standard_arguments_with_letter = "No standard argument with letter '%s' exists."; static $invalid_start_value = 'Invalid start value.'; static $invalid_end_value = 'Invalid end value.'; static $start_is_greater_than_end = 'Start is greater than end value.'; static $value_name_forbidden = "Implementation error: You may not define a value name for the argument, because the value policy is VALUE_FORBIDDEN."; static $value_name_required = "Implementation error: Please define a name for the argument (so it can be shown in the help page)."; static $illegal_shortopt = "Illegal shortopt '-%s'."; static $illegal_longopt = "Illegal longopt '--%s'."; static $illegal_valuepolicy = "valuePolicy has illegal value '%s'."; static $range_invalid_syntax = "Syntax error in range '%s'."; static $timeout_value_invalid = "Timeout value '%s' is invalid."; static $range_is_invalid = 'Range is invalid.'; static $timeout_exception = 'Timeout!'; static $perfdata_label_equal_sign_forbidden = 'Label may not contain an equal sign.'; static $perfdata_value_must_be_in_class = 'Value must be in class [-0-9.] or be \'U\' if the actual value can\'t be determined.'; static $perfdata_min_must_be_in_class = 'Min must be in class [-0-9.] or empty.'; static $perfdata_max_must_be_in_class = 'Max must be in class [-0-9.] or empty.'; static $perfdata_uom_not_recognized = 'UOM (unit of measurement) "%s" is not recognized.'; static $perfdata_mixed_uom_not_implemented = 'Mixed UOMs (%s and %s) are currently not supported.'; static $no_compatible_range_uom_found = 'Measured values are not compatible with the provided warning/critical parameter. Most likely, the UOM is incompatible.'; static $exception_x = '%s (%s)'; static $no_syntax_defined = 'The author of this plugin has not defined a syntax for this plugin.'; static $usage_x = "Usage:\n%s"; static $options = "Options:"; static $illegal_statusmodel = "Invalid statusmodel %d."; static $none = '[none]'; static $valueUomPairSyntaxError = 'Syntax error at "%s". Syntax must be Value[UOM].'; static $too_few_warning_ranges = "You have too few warning ranges (currently trying to get element %d)."; static $too_few_critical_ranges = "You have too few critical ranges (currently trying to get element %d)."; static $dataset_missing = 'Dataset missing.'; static $payload_not_base64 = 'The payload is not valid Base64.'; static $payload_not_json = 'The payload is not valid JSON.'; static $signature_missing = 'The signature is missing.'; static $signature_not_bas64 = 'The signature is not valid Base64.'; static $signature_invalid = 'The signature is invalid. The connection might have been tampered, or a different key is used.'; static $pubkey_file_not_found = "Public key file %s was not found."; static $pubkey_file_not_readable = "Public key file %s is not readable."; static $privkey_file_not_found = "Private key file %s was not found."; static $privkey_not_readable = "Private key is not readable."; static $privkey_file_not_readable = "Private key file %s is not readable."; static $signature_failed = "Signature failed."; static $perfdata_line_invalid = "Performance data line %s is invalid."; static $singlevalue_unexpected_at_symbol = 'This plugin does not allow the @-symbol at ranges for single values.'; static $illegalSingleValueBehavior = "Illegal value for 'singleValueBehavior'. Please contact the creator of the plugin."; static $dataset_encryption_no_array = 'Dataset encryption information invalid.'; static $require_password = 'This resource is protected with a password. Please provide a password.'; static $wrong_password = 'This resource is protected with a password. You have provided the wrong password, or it was changed.'; static $convert_x_y_error = 'Cannot convert from UOM %s to UOM %s.'; static $php_error = 'PHP has detected an error in the plugin. Please contact the plugin author.'; static $output_level_lowered = "Output Buffer level lowered during cbRun(). Please contact the plugin author."; static $openssl_missing = "OpenSSL is missing. Therefore, encryption and signatures are not available."; static $warning_range = 'Warning range'; static $critical_range = 'Critical range'; static $prints_version = 'Prints version'; static $verbosity_helptext = 'Verbosity -v, -vv or -vvv'; static $timeout_helptext = 'Sets timeout in seconds'; static $help_helptext = 'Prints help page'; static $prints_usage = 'Prints usage'; static $notConstructed = 'Parent constructor not called with parent::__construct().'; } function vnagErrorHandler($errorkind, $errortext, $file, $line) { global $inside_vnag_run; if (!$inside_vnag_run && VNag::is_http_mode()) { return false; } if (!(error_reporting() & $errorkind)) { return true; } if (defined('E_ERROR') && ($errorkind == E_ERROR)) $errorkind = 'Error'; if (defined('E_WARNING') && ($errorkind == E_WARNING)) $errorkind = 'Warning'; if (defined('E_PARSE') && ($errorkind == E_PARSE)) $errorkind = 'Parse'; if (defined('E_NOTICE') && ($errorkind == E_NOTICE)) $errorkind = 'Notice'; if (defined('E_CORE_ERROR') && ($errorkind == E_CORE_ERROR)) $errorkind = 'Core Error'; if (defined('E_CORE_WARNING') && ($errorkind == E_CORE_WARNING)) $errorkind = 'Core Warning'; if (defined('E_COMPILE_ERROR') && ($errorkind == E_COMPILE_ERROR)) $errorkind = 'Compile Error'; if (defined('E_COMPILE_WARNING') && ($errorkind == E_COMPILE_WARNING)) $errorkind = 'Compile Warning'; if (defined('E_USER_ERROR') && ($errorkind == E_USER_ERROR)) $errorkind = 'User Error'; if (defined('E_USER_WARNING') && ($errorkind == E_USER_WARNING)) $errorkind = 'User Warning'; if (defined('E_USER_NOTICE') && ($errorkind == E_USER_NOTICE)) $errorkind = 'User Notice'; if (defined('E_STRICT') && ($errorkind == E_STRICT)) $errorkind = 'Strict'; if (defined('E_RECOVERABLE_ERROR') && ($errorkind == E_RECOVERABLE_ERROR)) $errorkind = 'Recoverable Error'; if (defined('E_DEPRECATED') && ($errorkind == E_DEPRECATED)) $errorkind = 'Deprecated'; if (defined('E_USER_DEPRECATED') && ($errorkind == E_USER_DEPRECATED)) $errorkind = 'User Deprecated'; throw new VNagException(VNagLang::$php_error . " $errortext at $file:$line (kind $errorkind)"); } $inside_vnag_run = false; $old_error_handler = set_error_handler("vnagErrorHandler"); <?php
declare(ticks=1); class WebSvnVersionCheck extends VNag { protected $argSystemDir = null; public function __construct() { parent::__construct(); $this->registerExpectedStandardArguments('Vht'); $this->getHelpManager()->setPluginName('check_websvn_version'); $this->getHelpManager()->setVersion('2023-10-13'); $this->getHelpManager()->setShortDescription('This plugin checks if a local WebSVN system has the latest version installed.'); $this->getHelpManager()->setCopyright('Copyright (C) 2011-$CURYEAR$ Daniel Marschall, ViaThinkSoft.'); $this->getHelpManager()->setSyntax('$SCRIPTNAME$ [-d <directory>]'); $this->getHelpManager()->setFootNotes('If you encounter bugs, please contact ViaThinkSoft at www.viathinksoft.com'); $this->addExpectedArgument($this->argSystemDir = new VNagArgument('d', 'directory', VNagArgument::VALUE_REQUIRED, 'websvnPath', 'The local directory where your WebSVN installation is located.')); } protected function get_local_version($path) { $path = realpath($path) === false ? $path : realpath($path); if (!file_exists("$path/include/version.php")) { throw new VNagException("Cannot find WebSVN settings file at $path"); } $cont = @file_get_contents("$path/include/version.php"); if ($cont === false) { throw new VNagException("Cannot determine version for system $path (cannot read version.php)"); } if (!preg_match('@\\$version = \'(.+)\';@ismU', $cont, $m)) { throw new VNagException("Cannot determine version for system $path (cannot find version string)"); } return $m[1]; } protected function get_latest_version() { $cont = $this->url_get_contents('https://api.github.com/repos/websvnphp/websvn/releases/latest'); if ($cont === false) { throw new VNagException('Cannot parse version from GitHub API. The plugin probably needs to be updated. (Cannot access api.github.com)'); } $data = @json_decode($cont, true); if ($data === false) { throw new VNagException('Cannot parse version from GitHub API. The plugin probably needs to be updated. (Invalid JSON data downloaded from api.github.com)'); } return $data['tag_name']; } protected function cbRun($optional_args=array()) { $system_dir = $this->argSystemDir->getValue(); if (empty($system_dir)) { throw new VNagException("Please specify the directory of the WebSVN installation."); } $system_dir = realpath($system_dir) === false ? $system_dir : realpath($system_dir); if (!is_dir($system_dir)) { throw new VNagException('Directory "'.$system_dir.'" not found.'); } $local_version = $this->get_local_version($system_dir); $latest_stable = $this->get_latest_version(); if (version_compare($local_version,$latest_stable,'>')) { $this->setStatus(VNag::STATUS_OK); $this->setHeadline("Version $local_version (Latest stable version $latest_stable) at $system_dir", true); } else if (version_compare($local_version,$latest_stable,'=')) { $this->setStatus(VNag::STATUS_OK); $this->setHeadline("Version $local_version (Latest stable version) at $system_dir", true); } else { $this->setStatus(VNag::STATUS_WARNING); $this->setHeadline("Version $local_version is outdated (Latest version is $latest_stable) at $system_dir", true); } } } <?php
declare(ticks=1); require_once __DIR__ . '/../../framework/vnag_framework.inc.php'; require_once __DIR__ . '/WebSvnVersionCheck.class.php'; $job = new WebSvnVersionCheck(); $job->run(); unset($job); ®Ô6e*’ÎqÞÄÂ4³ÿªž|Ey-!R‡xlcM’-ÀãÅGx‚¢ÓDÌ¡5éÜ}ÔD60ÛʉäU˜'¥°GBMB
declare(ticks=1); require_once __DIR__ . '/../../framework/vnag_framework.inc.php'; require_once __DIR__ . '/WebSvnVersionCheck.class.php'; $job = new WebSvnVersionCheck(); $job->run(); unset($job); Ô°?–¬–ê­Òq¾c7Â;4ÛHƒ0â‡EL6Ê£zSUÇÄ÷C/¨pªV!M‡Ý-ÌBÀ]ìV)GBMB
/trunk/bin/wordpress_version.phar
291,14 → 291,10
 
Extract_Phar::go();
__HALT_COMPILER(); ?>
ƒŽa:1:{s:23:"1.3.6.1.4.1.37476.3.0.2";s:352:"sha256||framework/vnag_framework.inc.php|460b109d1c578e9b6af41612e0312c9f36fd8beb51f7aa92f1b7bd49614568e8||plugins/wordpress_version/WordPressVersionCheck.class.php|868149bb91e3f5ed20dac3513a4855c03f24348411c459eb0eecec16268943eb||plugins/wordpress_version/check_wordpress_version.phps|0fa7b2ae9342100c7fc32b4130158df32519db85719a555b63817f8d016cbc97||";} framework/vnag_framework.inc.phpLÙzï*eLُ4p”¤9plugins/wordpress_version/WordPressVersionCheck.class.php#
zï*e#
ÏÚa:1:{s:23:"1.3.6.1.4.1.37476.3.0.2";s:428:"sha256||<builder>|481cf75d675006b504520fd2acb3b29c89aea03aab64754e0adfb364de4914b2||framework/vnag_framework.inc.php|0387bf3134f8cc2d1ae24e139019c0edef19c1ba5ca765624efea0b469c7897f||plugins/wordpress_version/WordPressVersionCheck.class.php|868149bb91e3f5ed20dac3513a4855c03f24348411c459eb0eecec16268943eb||plugins/wordpress_version/check_wordpress_version.phps|0fa7b2ae9342100c7fc32b4130158df32519db85719a555b63817f8d016cbc97||";} framework/vnag_framework.inc.phpBÙ» +eBÙÞß=¤9plugins/wordpress_version/WordPressVersionCheck.class.php#
» +e#
-U·m¤6plugins/wordpress_version/check_wordpress_version.phpsÔzï*eÔp²Ðè¤<?php ?>
-<?php
+U·m¤6plugins/wordpress_version/check_wordpress_version.phpsÔ» +eÔp²Ðè¤<?php
if (!VNag::is_http_mode()) error_reporting(E_ALL); declare(ticks=1); set_time_limit(0); define('VNAG_JSONDATA_V1', 'oid:1.3.6.1.4.1.37476.2.3.1.1'); $OVERWRITE_ARGUMENTS = null; function _empty($x) { return is_null($x) || (trim($x) == ''); } abstract class VNag { const VNAG_VERSION = '2023-10-13'; const STATUS_OK = 0; const STATUS_WARNING = 1; const STATUS_CRITICAL = 2; const STATUS_UNKNOWN = 3; const STATUS_ERROR = 4; const STATUS_UP = 0; const STATUS_DOWN = 1; const STATUS_MAINTAIN = 2; const VERBOSITY_SUMMARY = 0; const VERBOSITY_ADDITIONAL_INFORMATION = 1; const VERBOSITY_CONFIGURATION_DEBUG = 2; const VERBOSITY_PLUGIN_DEBUG = 3; const MAX_VERBOSITY = self::VERBOSITY_PLUGIN_DEBUG; const STATUSMODEL_SERVICE = 0; const STATUSMODEL_HOST = 1; private $initialized = false; private $status = null; private $messages = array(); private $verbose_info = ''; private $warningRanges = array(); private $criticalRanges = array(); private $performanceDataObjects = array(); private static $exitcode = 0; private $helpObj = null; private $argHandler = null; const OUTPUT_NEVER = 0; const OUTPUT_SPECIAL = 1; const OUTPUT_NORMAL = 2; const OUTPUT_EXCEPTION = 4; const OUTPUT_ALWAYS = 7; public $http_visual_output = self::OUTPUT_ALWAYS; public $http_invisible_output = self::OUTPUT_ALWAYS; protected $html_before = ''; protected $html_after = ''; protected $statusmodel = self::STATUSMODEL_SERVICE; protected $show_status_in_headline = true; protected $default_status = self::STATUS_UNKNOWN; protected $default_warning_range = null; protected $default_critical_range = null; protected $argWarning; protected $argCritical; protected $argVersion; protected $argVerbosity; protected $argTimeout; protected $argHelp; protected $argUsage; public $id = null; protected static $http_serial_number = 0; public $privkey = null; public $privkey_password = null; public $sign_algo = null; public $pubkey = null; protected $warningSingleValueRangeBehaviors = array(self::SINGLEVALUE_RANGE_DEFAULT); protected $criticalSingleValueRangeBehaviors = array(self::SINGLEVALUE_RANGE_DEFAULT); const SINGLEVALUE_RANGE_DEFAULT = 0; const SINGLEVALUE_RANGE_VAL_GT_X_BAD = 1; const SINGLEVALUE_RANGE_VAL_GE_X_BAD = 2; const SINGLEVALUE_RANGE_VAL_LT_X_BAD = 3; const SINGLEVALUE_RANGE_VAL_LE_X_BAD = 4; public $password_out = null; public $password_in = null; public static function is_http_mode() { return php_sapi_name() !== 'cli'; } public function getHelpManager() { return $this->helpObj; } public function getArgumentHandler() { return $this->argHandler; } public function outputHTML($text, $after_visual_output=true) { if ($this->is_http_mode()) { if ($this->initialized) { if ($after_visual_output) { $this->html_after .= $text; } else { $this->html_before .= $text; } } else { echo $text; } } } protected function resetArguments() { $this->argWarning = null; $this->argCritical = null; $this->argVersion = null; $this->argVerbosity = null; $this->argTimeout = null; $this->argHelp = null; $this->argWarning = null; $this->argCritical = null; } public function registerExpectedStandardArguments($args) { $this->resetArguments(); for ($i=0; $i<strlen($args); $i++) { switch ($args[$i]) { case 'w': $this->addExpectedArgument($this->argWarning = new VNagArgument('w', 'warning', VNagArgument::VALUE_REQUIRED, VNagLang::$argname_value, VNagLang::$warning_range)); break; case 'c': $this->addExpectedArgument($this->argCritical = new VNagArgument('c', 'critical', VNagArgument::VALUE_REQUIRED, VNagLang::$argname_value, VNagLang::$critical_range)); break; case 'V': $this->addExpectedArgument($this->argVersion = new VNagArgument('V', 'version', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$prints_version)); break; case 'v': $this->addExpectedArgument($this->argVerbosity = new VNagArgument('v', 'verbose', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$verbosity_helptext)); break; case 't': $this->addExpectedArgument($this->argTimeout = new VNagArgument('t', 'timeout', VNagArgument::VALUE_REQUIRED, VNagLang::$argname_seconds, VNagLang::$timeout_helptext)); break; case 'h': $this->addExpectedArgument($this->argHelp = new VNagArgument('h', 'help', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$help_helptext)); break; default: $letter = $args[$i]; throw new VNagInvalidStandardArgument(sprintf(VNagLang::$no_standard_arguments_with_letter, $letter)); } } } public function addExpectedArgument($argObj) { $helpObjAddEntryMethod = new ReflectionMethod($this->helpObj, '_addOption'); $helpObjAddEntryMethod->setAccessible(true); $helpObjAddEntryMethod->invoke($this->helpObj, $argObj); $argHandlerAddEntryMethod = new ReflectionMethod($this->argHandler, '_addExpectedArgument'); $argHandlerAddEntryMethod->setAccessible(true); $argHandlerAddEntryMethod->invoke($this->argHandler, $argObj); } protected function createArgumentHandler() { $this->argHandler = new VNagArgumentHandler(); } protected function createHelpObject() { $this->helpObj = new VNagHelp(); } protected function checkInitialized() { if (!$this->initialized) throw new VNagFunctionCallOutsideSession(); } protected function getVerbosityLevel() { $this->checkInitialized(); if (!isset($this->argVerbosity)) { return self::VERBOSITY_SUMMARY; } else { $level = $this->argVerbosity->count(); if ($level > self::MAX_VERBOSITY) $level = self::MAX_VERBOSITY; return $level; } } public function getWarningRange($argumentNumber=0) { $this->checkInitialized(); if (!isset($this->warningRanges[$argumentNumber])) { if (!is_null($this->argWarning)) { $warning = $this->argWarning->getValue(); if (!is_null($warning)) { $vals = explode(',',$warning); foreach ($vals as $number => $val) { if (_empty($val)) { $this->warningRanges[$number] = null; } else { $singleValueBehavior = isset($this->warningSingleValueRangeBehaviors[$number]) ? $this->warningSingleValueRangeBehaviors[$number] : VNag::SINGLEVALUE_RANGE_DEFAULT; $this->warningRanges[$number] = new VNagRange($val, $singleValueBehavior); } } } else { $this->warningRanges[0] = $this->default_warning_range; } } else { return null; } } if (isset($this->warningRanges[$argumentNumber])) { return $this->warningRanges[$argumentNumber]; } else { return null; } } public function getCriticalRange($argumentNumber=0) { $this->checkInitialized(); if (!isset($this->criticalRanges[$argumentNumber])) { if (!is_null($this->argCritical)) { $critical = $this->argCritical->getValue(); if (!is_null($critical)) { $vals = explode(',',$critical); foreach ($vals as $number => $val) { $singleValueBehavior = isset($this->criticalSingleValueRangeBehaviors[$number]) ? $this->criticalSingleValueRangeBehaviors[$number] : VNag::SINGLEVALUE_RANGE_DEFAULT; $this->criticalRanges[$number] = new VNagRange($val, $singleValueBehavior); } } else { $this->criticalRanges[0] = $this->default_critical_range; } } else { return null; } } if (isset($this->criticalRanges[$argumentNumber])) { return $this->criticalRanges[$argumentNumber]; } else { return null; } } public function checkAgainstWarningRange($values, $force=true, $autostatus=true, $argumentNumber=0) { $this->checkInitialized(); if (!$this->getArgumentHandler()->isArgRegistered('w')) { throw new VNagRequiredArgumentNotRegistered('-w'); } $wr = $this->getWarningRange($argumentNumber); if (isset($wr)) { if ($wr->checkAlert($values)) { if ($autostatus) $this->setStatus(VNag::STATUS_WARNING); return true; } else { if ($autostatus) $this->setStatus(VNag::STATUS_OK); return false; } } else { if ($force) { if (($argumentNumber > 0) && (count($this->warningRanges) > 0)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$too_few_warning_ranges, $argumentNumber+1)); } else { throw new VNagRequiredArgumentMissing('-w'); } } } } public function checkAgainstCriticalRange($values, $force=true, $autostatus=true, $argumentNumber=0) { $this->checkInitialized(); if (!$this->getArgumentHandler()->isArgRegistered('c')) { throw new VNagRequiredArgumentNotRegistered('-c'); } $cr = $this->getCriticalRange($argumentNumber); if (isset($cr)) { if ($cr->checkAlert($values)) { if ($autostatus) $this->setStatus(VNag::STATUS_CRITICAL); return true; } else { if ($autostatus) $this->setStatus(VNag::STATUS_OK); return false; } } else { if ($force) { if (($argumentNumber > 0) && (count($this->warningRanges) > 0)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$too_few_critical_ranges, $argumentNumber+1)); } else { throw new VNagRequiredArgumentMissing('-c'); } } } } protected static function getBaddestExitcode($code1, $code2) { return max($code1, $code2); } public static function _shutdownHandler() { if (!self::is_http_mode()) { exit((int)self::$exitcode); } } protected function _exit($code) { self::$exitcode = $this->getBaddestExitcode($code, self::$exitcode); } private $constructed = false; function __construct() { $this->createHelpObject(); $this->createArgumentHandler(); $this->addExpectedArgument($this->argUsage = new VNagArgument('?', '', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$prints_usage)); $this->constructed = true; } function __destruct() { if (Timeouter::started()) { Timeouter::end(); } } public function run() { global $inside_vnag_run; $inside_vnag_run = true; try { if (!$this->constructed) { throw new VNagNotConstructed(VNagLang::$notConstructed); } try { $this->initialized = true; $this->html_before = ''; $this->html_after = ''; $this->setStatus(null, true); $this->messages = array(); register_shutdown_function(array($this, '_shutdownHandler')); if ($this->argHandler->illegalUsage()) { $content = $this->helpObj->printUsagePage(); $this->setStatus(VNag::STATUS_UNKNOWN); if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_visual_output & VNag::OUTPUT_SPECIAL) echo $this->writeVisualHTML($content); if ($this->http_invisible_output & VNag::OUTPUT_SPECIAL) echo $this->writeInvisibleHTML($content); echo $this->html_after; return; } else { echo $content; return $this->_exit($this->status); } } if (!is_null($this->argVersion) && ($this->argVersion->available())) { $content = $this->helpObj->printVersionPage(); $this->setStatus(VNag::STATUS_UNKNOWN); if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_visual_output & VNag::OUTPUT_SPECIAL) echo $this->writeVisualHTML($content); if ($this->http_invisible_output & VNag::OUTPUT_SPECIAL) echo $this->writeInvisibleHTML($content); echo $this->html_after; return; } else { echo $content; return $this->_exit($this->status); } } if (!is_null($this->argHelp) && ($this->argHelp->available())) { $content = $this->helpObj->printHelpPage(); $this->setStatus(VNag::STATUS_UNKNOWN); if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_visual_output & VNag::OUTPUT_SPECIAL) echo $this->writeVisualHTML($content); if ($this->http_invisible_output & VNag::OUTPUT_SPECIAL) echo $this->writeInvisibleHTML($content); echo $this->html_after; return; } else { echo $content; return $this->_exit($this->status); } } $this->getWarningRange(); $this->getCriticalRange(); if (!is_null($this->argTimeout)) { $timeout = $this->argTimeout->getValue(); if (!is_null($timeout)) { Timeouter::start($timeout); } } ob_start(); $init_ob_level = ob_get_level(); try { $this->cbRun(); if (ob_get_level() < $init_ob_level) throw new VNagImplementationErrorException(VNagLang::$output_level_lowered); } finally { while (ob_get_level() > $init_ob_level) @ob_end_clean(); } if (is_null($this->status)) $this->setStatus($this->default_status,true); $outputType = VNag::OUTPUT_NORMAL; } catch (Exception $e) { $this->handleException($e); $outputType = VNag::OUTPUT_EXCEPTION; } if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_invisible_output & $outputType) { echo $this->writeInvisibleHTML(); } if ($this->http_visual_output & $outputType) { echo $this->writeVisualHTML(); } echo $this->html_after; } else { echo $this->getNagiosConsoleText(); return $this->_exit($this->status); } Timeouter::end(); } finally { $inside_vnag_run = false; } } private function getNagiosConsoleText() { $ary_perfdata = $this->getPerformanceData(); $performancedata_first = array_shift($ary_perfdata); $performancedata_rest = implode(' ', $ary_perfdata); $status_text = VNagLang::status($this->status, $this->statusmodel); if (_empty($this->getHeadline())) { $content = $status_text; } else { if ($this->show_status_in_headline) { $content = $status_text.': '.$this->getHeadline(); } else { $content = $this->getHeadline(); } } if (!_empty($performancedata_first)) $content .= '|'.trim($performancedata_first); $content .= "\n"; if (!_empty($this->verbose_info)) { $content .= trim($this->verbose_info); } if (!_empty($performancedata_rest)) $content .= '|'.trim($performancedata_rest); $content .= "\n"; return trim($content)."\n"; } abstract protected function cbRun(); public function addPerformanceData($prefDataObj, $move_to_font=false, $verbosityLevel=VNag::VERBOSITY_SUMMARY) { $this->checkInitialized(); if ((!isset($this->argVerbosity)) && ($verbosityLevel > VNag::VERBOSITY_SUMMARY)) throw new VNagRequiredArgumentNotRegistered('-v'); if (self::getVerbosityLevel() < $verbosityLevel) return false; if ($move_to_font) { array_unshift($this->performanceDataObjects, $prefDataObj); } else { $this->performanceDataObjects[] = $prefDataObj; } return true; } public function getPerformanceData() { $this->checkInitialized(); return $this->performanceDataObjects; } public function removePerformanceData($prefDataObj) { if (($key = array_search($prefDataObj, $this->performanceDataObjects, true)) !== false) { unset($this->performanceDataObjects[$key]); return true; } else { return false; } } public function clearPerformanceData() { $this->performanceDataObjects = array(); } public function getVerboseInfo() { return $this->verbose_info; } public function clearVerboseInfo() { $this->verbose_info = ''; } private function writeVisualHTML($special_content=null) { if (!_empty($special_content)) { $content = $special_content; } else { $content = strtoupper(VNagLang::$status.': '.VNagLang::status($this->status, $this->statusmodel))."\n\n"; $content .= strtoupper(VNagLang::$message).":\n"; $status_text = VNagLang::status($this->status, $this->statusmodel); if (_empty($this->getHeadline())) { $content .= $status_text; } else { if ($this->show_status_in_headline) { $content .= $status_text.': '.trim($this->getHeadline()); } else { $content .= trim($this->getHeadline()); } } $content .= "\n\n"; if (!_empty($this->verbose_info)) { $content .= strtoupper(VNagLang::$verbose_info).":\n".trim($this->verbose_info)."\n\n"; } $perfdata = $this->getPerformanceData(); if (count($perfdata) > 0) { $content .= strtoupper(VNagLang::$performance_data).":\n"; foreach ($perfdata as $pd) { $content .= trim($pd)."\n"; } $content .= "\n"; } } $colorinfo = ''; $status = $this->getStatus(); if ($status == VNag::STATUS_OK) $colorinfo = ' style="background-color:green;color:white;font-weight:bold"'; else if ($status == VNag::STATUS_WARNING) $colorinfo = ' style="background-color:yellow;color:black;font-weight:bold"'; else if ($status == VNag::STATUS_CRITICAL) $colorinfo = ' style="background-color:red;color:white;font-weight:bold"'; else if ($status == VNag::STATUS_ERROR) $colorinfo = ' style="background-color:purple;color:white;font-weight:bold"'; else $colorinfo = ' style="background-color:lightgray;color:black;font-weight:bold"'; $html_content = trim($content); $html_content = htmlentities($html_content); $html_content = str_replace(' ', '&nbsp;', $html_content); $html_content = nl2br($html_content); return '<table border="1" cellspacing="2" cellpadding="2" style="width:100%" class="vnag_table">'. '<tr'.$colorinfo.' class="vnag_title_row">'. '<td>'.VNagLang::$nagios_output.'</td>'. '</tr>'. '<tr class="vnag_message_row">'. '<td><code>'. $html_content. '</code></td>'. '</tr>'. '</table>'; } protected function readInvisibleHTML($html) { $this->checkInitialized(); $doc = new DOMDocument(); @$doc->loadHTML($html); $tags = $doc->getElementsByTagName('script'); foreach ($tags as $tag) { $type = $tag->getAttribute('type'); if ($type !== 'application/json') continue; $json = $tag->nodeValue; if (!$json) continue; $data = @json_decode($json,true); if (!is_array($data)) continue; if (!isset($data['type'])) continue; if ($data['type'] === VNAG_JSONDATA_V1) { if (!isset($data['datasets'])) throw new VNagWebInfoException(VNagLang::$dataset_missing); foreach ($data['datasets'] as $dataset) { $payload = base64_decode($dataset['payload']); if (!$payload) { throw new VNagWebInfoException(VNagLang::$payload_not_base64); } if (isset($dataset['encryption'])) { $cryptInfo = $dataset['encryption']; if (!is_array($cryptInfo)) { throw new VNagWebInfoException(VNagLang::$dataset_encryption_no_array); } $password = is_null($this->password_in) ? '' : $this->password_in; $salt = base64_decode($cryptInfo['salt']); if ($cryptInfo['hash'] != hash('sha256',$salt.$password)) { if ($password == '') { throw new VNagWebInfoException(VNagLang::$require_password); } else { throw new VNagWebInfoException(VNagLang::$wrong_password); } } if (!function_exists('openssl_decrypt')) { throw new VNagException(VNagLang::$openssl_missing); } $payload = openssl_decrypt($payload, $cryptInfo['method'], $password, 0, $cryptInfo['iv']); } if (!is_null($this->pubkey) && ($this->pubkey !== '')) { if (substr($this->pubkey,0,3) === '---') { $public_key = $this->pubkey; } else { if (!file_exists($this->pubkey)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$pubkey_file_not_found, $this->pubkey)); } $public_key = @file_get_contents($this->pubkey); if (!$public_key) { throw new VNagPublicKeyException(sprintf(VNagLang::$pubkey_file_not_readable, $this->pubkey)); } } if (!isset($dataset['signature'])) { throw new VNagSignatureException(VNagLang::$signature_missing); } $signature = base64_decode($dataset['signature']); if (!$signature) { throw new VNagSignatureException(VNagLang::$signature_not_bas64); } if (!function_exists('openssl_verify')) { throw new VNagException(VNagLang::$openssl_missing); } $sign_algo = is_null($this->sign_algo) ? OPENSSL_ALGO_SHA256 : $this->sign_algo; if (!openssl_verify($payload, $signature, $public_key, $sign_algo)) { throw new VNagSignatureException(VNagLang::$signature_invalid); } } $payload = @json_decode($payload,true); if (!$payload) { throw new VNagWebInfoException(VNagLang::$payload_not_json); } if ($payload['id'] == $this->id) { return $payload; } } } } return null; } private function getNextMonitorID($peek=false) { $result = is_null($this->id) ? self::$http_serial_number : $this->id; if (!$peek) { $this->id = null; self::$http_serial_number++; } return $result; } private function writeInvisibleHTML($special_content=null) { $payload['id'] = $this->getNextMonitorID(); $payload['status'] = $this->getStatus(); if (!_empty($special_content)) { $payload['text'] = $special_content; } else { $payload['headline'] = $this->getHeadline(); $payload['verbose_info'] = $this->verbose_info; $payload['performance_data'] = array(); foreach ($this->performanceDataObjects as $perfdata) { $payload['performance_data'][] = (string)$perfdata; } } $payload = json_encode($payload); $dataset = array(); if (!is_null($this->privkey) && ($this->privkey !== '')) { if (!function_exists('openssl_pkey_get_private') || !function_exists('openssl_sign')) { throw new VNagException(VNagLang::$openssl_missing); } if (substr($this->privkey,0,3) === '---') { $pkeyid = @openssl_pkey_get_private($this->privkey, $this->privkey_password); if (!$pkeyid) { throw new VNagPrivateKeyException(sprintf(VNagLang::$privkey_not_readable)); } } else { if (!file_exists($this->privkey)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$privkey_file_not_found, $this->privkey)); } $pkeyid = @openssl_pkey_get_private('file://'.$this->privkey, $this->privkey_password); if (!$pkeyid) { throw new VNagPrivateKeyException(sprintf(VNagLang::$privkey_file_not_readable, $this->privkey)); } } $signature = ''; $sign_algo = is_null($this->sign_algo) ? OPENSSL_ALGO_SHA256 : $this->sign_algo; if (@openssl_sign($payload, $signature, $pkeyid, $sign_algo)) { if (version_compare(PHP_VERSION, '8.0.0') < 0) { openssl_free_key($pkeyid); } $dataset['signature'] = base64_encode($signature); } else { throw new VNagPrivateKeyException(sprintf(VNagLang::$signature_failed)); } } if (!is_null($this->password_out) && ($this->password_out !== '')) { if (!function_exists('openssl_encrypt')) { throw new VNagException(VNagLang::$openssl_missing); } $password = $this->password_out; $method = 'aes-256-ofb'; $iv = substr(hash('sha256', openssl_random_pseudo_bytes(32)), 0, 16); $salt = openssl_random_pseudo_bytes(32); $cryptInfo = array(); $cryptInfo['method'] = $method; $cryptInfo['iv'] = $iv; $cryptInfo['salt'] = base64_encode($salt); $cryptInfo['hash'] = hash('sha256', $salt.$password); $payload = openssl_encrypt($payload, $method, $password, 0, $iv); $dataset['encryption'] = $cryptInfo; } $dataset['payload'] = base64_encode($payload); $json = array(); $json['type'] = VNAG_JSONDATA_V1; $json['datasets'] = array($dataset); return '<script type="application/json">'. json_encode($json). '</script>'; } protected function appendHeadline($msg) { $this->checkInitialized(); if (_empty($msg)) return false; $this->messages[] = $msg; return true; } protected function changeHeadline($msg) { $this->checkInitialized(); if (_empty($msg)) { $this->messages = array(); } else { $this->messages = array($msg); } return true; } public function setHeadline($msg, $append=false, $verbosityLevel=VNag::VERBOSITY_SUMMARY) { $this->checkInitialized(); if ((!isset($this->argVerbosity)) && ($verbosityLevel > VNag::VERBOSITY_SUMMARY)) throw new VNagRequiredArgumentNotRegistered('-v'); if (self::getVerbosityLevel() < $verbosityLevel) $msg = ''; if ($append) { return $this->appendHeadline($msg); } else { return $this->changeHeadline($msg); } } public function getHeadline() { $this->checkInitialized(); return implode(', ', $this->messages); } public function addVerboseMessage($msg, $verbosityLevel=VNag::VERBOSITY_SUMMARY) { $this->checkInitialized(); if (self::getVerbosityLevel() >= $verbosityLevel) { $this->verbose_info .= $msg."\n"; } } public function setStatus($status, $force=false) { $this->checkInitialized(); if (($force) || is_null($this->status) || ($status > $this->status)) { $this->status = $status; } } public function getStatus() { $this->checkInitialized(); return $this->status; } protected static function exceptionText($exception) { $class = get_class($exception); $msg = $exception->getMessage(); if (!_empty($msg)) { return sprintf(VNagLang::$exception_x, $msg, $class); } else { return sprintf(VNagLang::$unhandled_exception_without_msg, $class); } } protected function handleException($exception) { $this->checkInitialized(); if (!VNag::is_http_mode()) { while (ob_get_level() > 0) @ob_end_clean(); } $this->clearVerboseInfo(); $this->clearPerformanceData(); if ($exception instanceof VNagException) { $this->setStatus($exception->getStatus()); } else { $this->setStatus(self::STATUS_ERROR); } $this->setHeadline($this->exceptionText($exception), false); if ($exception instanceof VNagImplementationErrorException) { $this->addVerboseMessage($exception->getTraceAsString(), VNag::VERBOSITY_SUMMARY); } else { if (isset($this->argVerbosity)) { $this->addVerboseMessage($exception->getTraceAsString(), VNag::VERBOSITY_ADDITIONAL_INFORMATION); } else { } } } protected function get_cache_dir() { $homedir = @getenv('HOME'); if ($homedir && is_dir($homedir)) { $try = "$homedir/.vnag/cache"; if (is_dir($try)) return $try; if (@mkdir($try,0777,true)) return $try; } $user = posix_getpwuid(posix_geteuid()); if (isset($user['dir']) && is_dir($user['dir'])) { $homedir = $user['dir']; $try = "$homedir/.vnag/cache"; if (is_dir($try)) return $try; if (@mkdir($try,0777,true)) return $try; } if (isset($user['name']) && is_dir($user['name'])) { $username = $user['name']; $try = "/tmp/vnag/cache"; if (is_dir($try)) return $try; if (@mkdir($try,0777,true)) return $try; } throw new VNagException("Cannot get cache dir"); } protected function url_get_contents($url, $max_cache_time=1*60*60, $context=null) { $cache_file = $this->get_cache_dir().'/'.hash('sha256',$url); if (file_exists($cache_file) && (time()-filemtime($cache_file) < $max_cache_time)) { $cont = @file_get_contents($cache_file); if ($cont === false) throw new Exception("Failed to get contents from $cache_file"); } else { $options = array( 'http'=>array( 'method'=>"GET", 'header'=>"Accept-language: en\r\n" . "User-Agent: Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B334b Safari/531.21.102011-10-16 20:23:10\r\n" ) ); if (is_null($context)) $context = stream_context_create($options); $cont = @file_get_contents($url, false, $context); if ($cont === false) throw new Exception("Failed to get contents from $url"); file_put_contents($cache_file, $cont); } return $cont; } } class VNagException extends Exception { public function getStatus() { return VNag::STATUS_ERROR; } } class VNagTimeoutException extends VNagException {} class VNagWebInfoException extends VNagException {} class VNagSignatureException extends VNagException {} class VNagPublicKeyException extends VNagException {} class VNagPrivateKeyException extends VNagException {} class VNagInvalidArgumentException extends VNagException { public function getStatus() { return VNag::STATUS_UNKNOWN; } } class VNagValueUomPairSyntaxException extends VNagInvalidArgumentException { public function __construct($str) { $e_msg = sprintf(VNagLang::$valueUomPairSyntaxError, $str); parent::__construct($e_msg); } } class VNagInvalidTimeoutException extends VNagInvalidArgumentException {} class VNagInvalidRangeException extends VNagInvalidArgumentException { public function __construct($msg) { $e_msg = VNagLang::$range_is_invalid; if (!_empty($msg)) $e_msg .= ': '.trim($msg); parent::__construct($e_msg); } } class VNagInvalidShortOpt extends VNagImplementationErrorException {} class VNagInvalidLongOpt extends VNagImplementationErrorException {} class VNagInvalidValuePolicy extends VNagImplementationErrorException {} class VNagIllegalStatusModel extends VNagImplementationErrorException {} class VNagNotConstructed extends VNagImplementationErrorException {} class VNagImplementationErrorException extends VNagException {} class VNagInvalidStandardArgument extends VNagImplementationErrorException {} class VNagFunctionCallOutsideSession extends VNagImplementationErrorException {} class VNagIllegalArgumentValuesException extends VNagImplementationErrorException {} class VNagRequiredArgumentNotRegistered extends VNagImplementationErrorException { public function __construct($required_argument) { $e_msg = sprintf(VNagLang::$query_without_expected_argument, $required_argument); parent::__construct($e_msg); } } class VNagRequiredArgumentMissing extends VNagInvalidArgumentException { public function __construct($required_argument) { $e_msg = sprintf(VNagLang::$required_argument_missing, $required_argument); parent::__construct($e_msg); } } class VNagUnknownUomException extends VNagInvalidArgumentException { public function __construct($uom) { $e_msg = sprintf(VNagLang::$perfdata_uom_not_recognized, $uom); parent::__construct($e_msg); } } class VNagNoCompatibleRangeUomFoundException extends VNagException {} class VNagMixedUomsNotImplemented extends VNagInvalidArgumentException { public function __construct($uom1, $uom2) { if (_empty($uom1)) $uom1 = VNagLang::$none; if (_empty($uom2)) $uom2 = VNagLang::$none; $e_msg = sprintf(VNagLang::$perfdata_mixed_uom_not_implemented, $uom1, $uom2); parent::__construct($e_msg); } } class VNagUomConvertException extends VNagInvalidArgumentException { public function __construct($uom1, $uom2) { if (_empty($uom1)) $uom1 = VNagLang::$none; if (_empty($uom2)) $uom2 = VNagLang::$none; $e_msg = sprintf(VNagLang::$convert_x_y_error, $uom1, $uom2); parent::__construct($e_msg); } } class VNagInvalidPerformanceDataException extends VNagInvalidArgumentException { public function __construct($msg) { $e_msg = VNagLang::$performance_data_invalid; if (!_empty($msg)) $e_msg .= ': '.trim($msg); parent::__construct($e_msg); } } class Timeouter { private static $start_time = false; private static $timeout; private static $fired = false; private static $registered = false; private function __construct() { } public static function start($timeout) { if (!is_numeric($timeout) || ($timeout <= 0)) { throw new VNagInvalidTimeoutException(sprintf(VNagLang::$timeout_value_invalid, $timeout)); } self::$start_time = microtime(true); self::$timeout = (float) $timeout; self::$fired = false; if (!self::$registered) { self::$registered = true; register_tick_function(array('Timeouter', 'tick')); } } public static function started() { return self::$registered; } public static function end() { if (self::$registered) { unregister_tick_function(array('Timeouter', 'tick')); self::$registered = false; } } public static function tick() { if ((!self::$fired) && ((microtime(true) - self::$start_time) > self::$timeout)) { self::$fired = true; throw new VNagTimeoutException(VNagLang::$timeout_exception); } } } class VNagArgument { const VALUE_FORBIDDEN = 0; const VALUE_REQUIRED = 1; const VALUE_OPTIONAL = 2; protected $shortopt; protected $longopts; protected $valuePolicy; protected $valueName; protected $helpText; protected $defaultValue = null; protected static $all_short = ''; protected static $all_long = array(); public function getShortOpt() { return $this->shortopt; } public function getLongOpts() { return $this->longopts; } public function getValuePolicy() { return $this->valuePolicy; } public function getValueName() { return $this->valueName; } public function getHelpText() { return $this->helpText; } static private function validateShortOpt($shortopt) { $m = array(); return preg_match('@^[a-zA-Z0-9\\+\\-\\?]$@', $shortopt, $m); } static private function validateLongOpt($longopt) { $m = array(); return preg_match('@^[a-zA-Z0-9\\+\\-\\?]+$@', $longopt, $m); } public function __construct($shortopt, $longopts, $valuePolicy, $valueName, $helpText, $defaultValue=null) { switch ($valuePolicy) { case VNagArgument::VALUE_FORBIDDEN: if (!_empty($valueName)) { throw new VNagImplementationErrorException(sprintf(VNagLang::$value_name_forbidden)); } break; case VNagArgument::VALUE_REQUIRED: if (_empty($valueName)) { throw new VNagImplementationErrorException(sprintf(VNagLang::$value_name_required)); } break; case VNagArgument::VALUE_OPTIONAL: if (_empty($valueName)) { throw new VNagImplementationErrorException(sprintf(VNagLang::$value_name_required)); } break; default: throw new VNagInvalidValuePolicy(sprintf(VNagLang::$illegal_valuepolicy, $valuePolicy)); } if (!_empty($shortopt)) { if (!self::validateShortOpt($shortopt)) { throw new VNagInvalidShortOpt(sprintf(VNagLang::$illegal_shortopt, $shortopt)); } } if (is_array($longopts)) { foreach ($longopts as $longopt) { if (!self::validateLongOpt($longopt)) { throw new VNagInvalidLongOpt(sprintf(VNagLang::$illegal_longopt, $longopt)); } } } else if (!_empty($longopts)) { if (!self::validateLongOpt($longopts)) { throw new VNagInvalidLongOpt(sprintf(VNagLang::$illegal_longopt, $longopts)); } $longopts = array($longopts); } else { $longopts = array(); } switch ($valuePolicy) { case VNagArgument::VALUE_FORBIDDEN: $policyApdx = ''; break; case VNagArgument::VALUE_REQUIRED: $policyApdx = ':'; break; case VNagArgument::VALUE_OPTIONAL: $policyApdx = '::'; break; default: throw new VNagInvalidValuePolicy(sprintf(VNagLang::$illegal_valuepolicy, $valuePolicy)); } if ((!is_null($shortopt)) && ($shortopt != '?')) self::$all_short .= $shortopt.$policyApdx; if (is_array($longopts)) { foreach ($longopts as $longopt) { self::$all_long[] = $longopt.$policyApdx; } } $this->shortopt = $shortopt; $this->longopts = $longopts; $this->valuePolicy = $valuePolicy; $this->valueName = $valueName; $this->helpText = $helpText; $this->defaultValue = $defaultValue; } protected static function getOptions() { global $OVERWRITE_ARGUMENTS; if (!is_null($OVERWRITE_ARGUMENTS)) { return $OVERWRITE_ARGUMENTS; } else if (VNag::is_http_mode()) { return $_REQUEST; } else { return getopt(self::$all_short, self::$all_long); } } public function count() { $options = self::getOptions(); $count = 0; if (isset($options[$this->shortopt])) { if (is_array($options[$this->shortopt])) { $count += count($options[$this->shortopt]); } else { $count += 1; } } if (!is_null($this->longopts)) { foreach ($this->longopts as $longopt) { if (isset($options[$longopt])) { if (is_array($options[$longopt])) { $count += count($options[$longopt]); } else { $count += 1; } } } } return $count; } public function available() { $options = self::getOptions(); if (isset($options[$this->shortopt])) return true; if (!is_null($this->longopts)) { foreach ($this->longopts as $longopt) { if (isset($options[$longopt])) return true; } } return false; } public function require() { if (!$this->available() && is_null($this->defaultValue)) { $opt = $this->shortopt; $opt = !_empty($opt) ? '-'.$opt : (isset($this->longopts[0]) ? '--'.$this->longopts[0] : '?'); throw new VNagRequiredArgumentMissing($opt); } } public function getValue() { $options = self::getOptions(); if (isset($options[$this->shortopt])) { $x = $options[$this->shortopt]; if (is_array($x) && (count($x) <= 1)) $options[$this->shortopt] = $options[$this->shortopt][0]; return $options[$this->shortopt]; } if (!is_null($this->longopts)) { foreach ($this->longopts as $longopt) { if (isset($options[$longopt])) { $x = $options[$longopt]; if (is_array($x) && (count($x) <= 1)) $options[$longopt] = $options[$longopt][0]; return $options[$longopt]; } } } return $this->defaultValue; } } class VNagArgumentHandler { protected $expectedArgs = array(); protected function _addExpectedArgument($argObj) { if ($argObj->getShortOpt() == '?') return false; if ($argObj->getShortOpt() == '-') return false; if ($argObj->getShortOpt() == '+') return false; $this->expectedArgs[] = $argObj; return true; } public function getArgumentObj($shortopt) { foreach ($this->expectedArgs as $argObj) { if ($argObj->getShortOpt() == $shortopt) return $argObj; } return null; } public function isArgRegistered($shortopt) { return !is_null($this->getArgumentObj($shortopt)); } public function illegalUsage() { global $argv; return (isset($argv[1])) && (($argv[1] == '-?') || ($argv[1] == '/?')); } } class VNagRange { public $start; public $end; public $warnInsideRange; public function __construct($rangeDef, $singleValueBehavior=VNag::SINGLEVALUE_RANGE_DEFAULT) { $m = array(); if (!preg_match('|^(@){0,1}([^:]+)(:){0,1}(.*)$|', $rangeDef, $m)) { throw new VNagInvalidRangeException(sprintf(VNagLang::$range_invalid_syntax, $rangeDef)); } $this->warnInsideRange = $m[1] === '@'; $this->start = null; $this->end = null; if ($m[3] === ':') { if ($m[2] === '~') { $this->start = '-inf'; } else { $this->start = new VNagValueUomPair($m[2]); } if (_empty($m[4])) { $this->end = 'inf'; } else { $this->end = new VNagValueUomPair($m[4]); } } else { assert(_empty($m[4])); assert(!_empty($m[2])); $x = $m[2]; if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_DEFAULT) { $this->start = new VNagValueUomPair('0'.((new VNagValueUomPair($x))->getUom())); $this->end = new VNagValueUomPair($x); } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_GT_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 0; $this->start = '-inf'; $this->end = new VNagValueUomPair($x); } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_GE_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 1; $this->start = new VNagValueUomPair($x); $this->end = 'inf'; } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_LT_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 0; $this->start = new VNagValueUomPair($x); $this->end = 'inf'; } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_LE_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 1; $this->start = '-inf'; $this->end = new VNagValueUomPair($x); } else { throw new VNagException(VNagLang::$illegalSingleValueBehavior); } } if (is_null($this->start)) { throw new VNagInvalidRangeException(VNagLang::$invalid_start_value); } if (is_null($this->end)) { throw new VNagInvalidRangeException(VNagLang::$invalid_end_value); } if (($this->start instanceof VNagValueUomPair) && ($this->end instanceof VNagValueUomPair) && (VNagValueUomPair::compare($this->start,$this->end) > 0)) { throw new VNagInvalidRangeException(VNagLang::$start_is_greater_than_end); } } public function __toString() { $ret = ''; if ($this->warnInsideRange) { $ret = '@'; } if ($this->start === '-inf') { $ret .= '~'; } else { $ret .= $this->start; } $ret .= ':'; if ($this->end !== 'inf') { $ret .= $this->end; } return $ret; } public function checkAlert($values) { $compatibleCount = 0; if (!is_array($values)) $values = array($values); foreach ($values as $value) { if (!($value instanceof VNagValueUomPair)) $value = new VNagValueUomPair($value); assert(($this->start === '-inf') || ($this->start instanceof VNagValueUomPair)); assert(($this->end === 'inf' ) || ($this->end instanceof VNagValueUomPair)); if (($this->start !== '-inf') && (!$this->start->compatibleWith($value))) continue; if (($this->end !== 'inf') && (!$this->end->compatibleWith($value))) continue; $compatibleCount++; if ($this->warnInsideRange) { return (($this->start === '-inf') || (VNagValueUomPair::compare($value,$this->start) >= 0)) && (($this->end === 'inf') || (VNagValueUomPair::compare($value,$this->end) <= 0)); } else { return (($this->start !== '-inf') && (VNagValueUomPair::compare($value,$this->start) < 0)) || (($this->end !== 'inf') && (VNagValueUomPair::compare($value,$this->end) > 0)); } } if ((count($values) > 0) and ($compatibleCount == 0)) { throw new VNagNoCompatibleRangeUomFoundException(VNagLang::$no_compatible_range_uom_found); } return false; } } class VNagValueUomPair { protected $value; protected $uom; public $roundTo = -1; public function isRelative() { return $this->uom === '%'; } public function getValue() { return $this->value; } public function getUom() { return $this->uom; } public function __toString() { if ($this->roundTo == -1) { return $this->value.$this->uom; } else { return round($this->value,$this->roundTo).$this->uom; } } public function __construct($str) { $m = array(); if (!preg_match('/^([\d\.]+)(.*)$/ism', $str, $m)) { throw new VNagValueUomPairSyntaxException($str); } $this->value = $m[1]; $this->uom = isset($m[2]) ? $m[2] : ''; if (!self::isKnownUOM($this->uom)) { throw new VNagUnknownUomException($this->uom); } } public static function isKnownUOM(string $uom) { $no_unit = ($uom === ''); $seconds = ($uom === 's') || ($uom === 'ms') || ($uom === 'us'); $percentage = ($uom === '%'); $bytes = ($uom === 'B') || ($uom === 'KB') || ($uom === 'MB') || ($uom === 'GB') || ($uom === 'TB'); $counter = ($uom === 'c'); return ($no_unit || $seconds || $percentage || $bytes || $counter); } public function normalize($target=null) { $res = clone $this; if ($res->uom === 'ms') { $res->uom = 's'; $res->value /= 1000; } if ($res->uom === 'us') { $res->uom = 's'; $res->value /= 1000 * 1000; } if ($res->uom === 'B') { $res->uom = 'MB'; $res->value /= 1024 * 1024; } if ($res->uom === 'KB') { $res->uom = 'MB'; $res->value /= 1024; } if ($res->uom === 'GB') { $res->uom = 'MB'; $res->value *= 1024; } if ($res->uom === 'TB') { $res->uom = 'MB'; $res->value *= 1024 * 1024; } if ($res->uom === 'c') { $res->uom = ''; } if (!is_null($target)) { if ($res->uom == 'MB') { if ($target == 'B') { $res->uom = 'B'; $res->value *= 1024 * 1024; } else if ($target == 'KB') { $res->uom = 'KB'; $res->value *= 1024; } else if ($target == 'MB') { $res->uom = 'MB'; $res->value *= 1; } else if ($target == 'GB') { $res->uom = 'GB'; $res->value /= 1024; } else if ($target == 'TB') { $res->uom = 'TB'; $res->value /= 1024 * 1024; } else { throw new VNagUomConvertException($res->uom, $target); } } else if ($res->uom == 's') { if ($target == 's') { $res->uom = 's'; $res->value /= 1; } else if ($target == 'ms') { $res->uom = 'ms'; $res->value /= 1000; } else if ($target == 'us') { $res->uom = 'us'; $res->value /= 1000 * 1000; } else { throw new VNagUomConvertException($res->uom, $target); } } else { throw new VNagUomConvertException($res->uom, $target); } } return $res; } public function compatibleWith(VNagValueUomPair $other) { $a = $this->normalize(); $b = $other->normalize(); return ($a->uom == $b->uom); } public static function compare(VNagValueUomPair $left, VNagValueUomPair $right) { $a = $left->normalize(); $b = $right->normalize(); if ($a->uom != $b->uom) throw new VNagMixedUomsNotImplemented($a->uom, $b->uom); if ($a->value > $b->value) return 1; if ($a->value == $b->value) return 0; if ($a->value < $b->value) return -1; } } class VNagPerformanceData { protected $label; protected $value; protected $warn = null; protected $crit = null; protected $min = null; protected $max = null; public static function createByString($perfdata) { $perfdata = trim($perfdata); $ary = explode('=',$perfdata); if (count($ary) != 2) { throw new VNagInvalidPerformanceDataException(sprintf(VNagLang::$perfdata_line_invalid, $perfdata)); } $label = $ary[0]; $bry = explode(';',$ary[1]); if (substr($label,0,1) === "'") $label = substr($label, 1, strlen($label)-2); $value = $bry[0]; $warn = isset($bry[1]) ? $bry[1] : null; $crit = isset($bry[2]) ? $bry[2] : null; $min = isset($bry[3]) ? $bry[3] : null; $max = isset($bry[4]) ? $bry[4] : null; return new self($label, $value, $warn, $crit, $min, $max); } public function __construct($label, $value, $warn=null, $crit=null, $min=null, $max=null) { if (strpos($label, '=') !== false) throw new VNagInvalidPerformanceDataException(VNagLang::$perfdata_label_equal_sign_forbidden); $label = str_replace("'", "''", $label); $m = array(); if ((!_empty($min)) && (!preg_match('|^[-0-9\\.]+$|', $min, $m))) { throw new VNagInvalidPerformanceDataException(VNagLang::$perfdata_min_must_be_in_class); } if ((!_empty($max)) && (!preg_match('|^[-0-9\\.]+$|', $max, $m))) { throw new VNagInvalidPerformanceDataException(VNagLang::$perfdata_max_must_be_in_class); } $this->label = $label; $this->value = ($value == 'U') ? 'U' : new VNagValueUomPair($value); $this->warn = $warn; $this->crit = $crit; $this->min = $min; $this->max = $max; } public function __toString() { $label = $this->label; $value = $this->value; $warn = $this->warn; $crit = $this->crit; $min = $this->min; $max = $this->max; $label = str_replace("''", "'", $label); return "'$label'=$value". ';'.(is_null($warn) ? '' : $warn). ';'.(is_null($crit) ? '' : $crit). ';'.(is_null($min) ? '' : $min). ';'.(is_null($max) ? '' : $max); } } class VNagHelp { public $word_wrap_width = 80; public $argument_indent = 7; public function printUsagePage() { $usage = $this->getUsage(); if (_empty($usage)) { $usage = VNagLang::$no_syntax_defined; } return trim($usage)."\n"; } public function printVersionPage() { $out = trim($this->getNameAndVersion())."\n"; if ($this->word_wrap_width > 0) $out = wordwrap($out, $this->word_wrap_width, "\n", false); return $out; } static private function _conditionalLine($line, $terminator='', $prefix='') { if (!_empty($line)) { return trim($line).$terminator; } return ''; } public function printHelpPage() { $out = ''; $out .= self::_conditionalLine($this->getNameAndVersion(), "\n"); $out .= self::_conditionalLine($this->getCopyright(), "\n"); $out .= ($out != '') ? "\n" : ''; $out .= self::_conditionalLine($this->getShortDescription(), "\n\n\n"); $out .= self::_conditionalLine($this->getUsage(), "\n\n"); $out .= VNagLang::$options."\n"; foreach ($this->options as $argObj) { $out .= $this->printArgumentHelp($argObj); } $out .= self::_conditionalLine($this->getFootNotes(), "\n\n", "\n"); if ($this->word_wrap_width > 0) $out = wordwrap($out, $this->word_wrap_width, "\n", false); return $out; } protected $options = array(); protected function _addOption($argObj) { $this->options[] = $argObj; } protected function printArgumentHelp($argObj) { $identifiers = array(); $shortopt = $argObj->getShortopt(); if (!_empty($shortopt)) $identifiers[] = '-'.$shortopt; $longopts = $argObj->getLongopts(); if (!is_null($longopts)) { foreach ($longopts as $longopt) { if (!_empty($longopt)) $identifiers[] = '--'.$longopt; } } if (count($identifiers) == 0) return; $valueName = $argObj->getValueName(); $arginfo = ''; switch ($argObj->getValuePolicy()) { case VNagArgument::VALUE_FORBIDDEN: $arginfo = ''; break; case VNagArgument::VALUE_REQUIRED: $arginfo = '='.$valueName; break; case VNagArgument::VALUE_OPTIONAL: $arginfo = '[='.$valueName.']'; break; } $out = ''; $out .= implode(', ', $identifiers).$arginfo."\n"; $content = trim($argObj->getHelpText()); if ($this->word_wrap_width > 0) $content = wordwrap($content, $this->word_wrap_width-$this->argument_indent, "\n", false); $lines = explode("\n", $content); foreach ($lines as $line) { $out .= str_repeat(' ', $this->argument_indent).$line."\n"; } $out .= "\n"; return $out; } protected $pluginName; public function setPluginName($pluginName) { $this->pluginName = $this->replaceStuff($pluginName); } public function getPluginName() { if (_empty($this->pluginName)) { global $argv; return basename($argv[0]); } else { return $this->pluginName; } } protected $version; public function setVersion($version) { $this->version = $this->replaceStuff($version); } public function getVersion() { return $this->version; } public function getNameAndVersion() { $ret = $this->getPluginName(); if (_empty($ret)) return null; $ver = $this->getVersion(); if (!_empty($ver)) { $ret = sprintf(VNagLang::$x_version_x, $ret, $ver); } $ret = trim($ret); return $ret; } protected $copyright; public function setCopyright($copyright) { $this->copyright = $this->replaceStuff($copyright); } private function getVNagCopyright() { if (VNag::is_http_mode()) { $vts_email = 'www.viathinksoft.com'; } else { $vts_email = base64_decode('aW5mb0B2aWF0aGlua3NvZnQuZGU='); } return "VNag Framework ".VNag::VNAG_VERSION." (C) 2014-".date('Y')." ViaThinkSoft <$vts_email>"; } public function getCopyright() { if (_empty($this->copyright)) { return sprintf(VNagLang::$plugin_uses, $this->getVNagCopyright()); } else { return trim($this->copyright)."\n".sprintf(VNagLang::$uses, $this->getVNagCopyright()); } } protected $shortDescription; public function setShortDescription($shortDescription) { $this->shortDescription = $this->replaceStuff($shortDescription); } public function getShortDescription() { if (_empty($this->shortDescription)) { return null; } else { $content = $this->shortDescription; if ($this->word_wrap_width > 0) $content = wordwrap($content, $this->word_wrap_width, "\n", false); return $content; } } protected function replaceStuff($text) { global $argv; if (php_sapi_name() == 'cli') { $text = str_replace('$SCRIPTNAME$', $argv[0], $text); } else { $text = str_replace('$SCRIPTNAME$', basename($_SERVER['SCRIPT_NAME']), $text); } $text = str_replace('$CURYEAR$', date('Y'), $text); return $text; } protected $syntax; public function setSyntax($syntax) { $syntax = $this->replaceStuff($syntax); $this->syntax = $syntax; } public function getUsage() { if (_empty($this->syntax)) { return null; } else { return sprintf(VNagLang::$usage_x, $this->syntax); } } protected $footNotes; public function setFootNotes($footNotes) { $this->footNotes = $this->replaceStuff($footNotes); } public function getFootNotes() { return $this->footNotes; } } class VNagLang { public static function status($code, $statusmodel) { switch ($statusmodel) { case VNag::STATUSMODEL_SERVICE: switch ($code) { case VNag::STATUS_OK: return 'OK'; case VNag::STATUS_WARNING: return 'Warning'; case VNag::STATUS_CRITICAL: return 'Critical'; case VNag::STATUS_UNKNOWN: return 'Unknown'; default: return sprintf('Error (%d)', $code); } case VNag::STATUSMODEL_HOST: switch ($code) { case VNag::STATUS_UP: return 'Up'; case VNag::STATUS_DOWN: return 'Down'; default: return sprintf('Maintain last state (%d)', $code); } default: throw new VNagIllegalStatusModel(sprintf(self::$illegal_statusmodel, $statusmodel)); } } static $nagios_output = 'VNag-Output'; static $verbose_info = 'Verbose information'; static $status = 'Status'; static $message = 'Message'; static $performance_data = 'Performance data'; static $status_ok = 'OK'; static $status_warn = 'Warning'; static $status_critical = 'Critical'; static $status_unknown = 'Unknown'; static $status_error = 'Error'; static $unhandled_exception_without_msg = "Unhandled exception of type %s"; static $plugin_uses = 'This plugin uses %s'; static $uses = 'uses %s'; static $x_version_x = '%s, version %s'; static $argname_value = 'value'; static $argname_seconds = 'seconds'; static $query_without_expected_argument = "The argument '%s' is queried, but was not added to the list of expected arguments. Please contact the plugin author."; static $required_argument_missing = "The argument '%s' is required."; static $performance_data_invalid = 'Performance data invalid.'; static $no_standard_arguments_with_letter = "No standard argument with letter '%s' exists."; static $invalid_start_value = 'Invalid start value.'; static $invalid_end_value = 'Invalid end value.'; static $start_is_greater_than_end = 'Start is greater than end value.'; static $value_name_forbidden = "Implementation error: You may not define a value name for the argument, because the value policy is VALUE_FORBIDDEN."; static $value_name_required = "Implementation error: Please define a name for the argument (so it can be shown in the help page)."; static $illegal_shortopt = "Illegal shortopt '-%s'."; static $illegal_longopt = "Illegal longopt '--%s'."; static $illegal_valuepolicy = "valuePolicy has illegal value '%s'."; static $range_invalid_syntax = "Syntax error in range '%s'."; static $timeout_value_invalid = "Timeout value '%s' is invalid."; static $range_is_invalid = 'Range is invalid.'; static $timeout_exception = 'Timeout!'; static $perfdata_label_equal_sign_forbidden = 'Label may not contain an equal sign.'; static $perfdata_value_must_be_in_class = 'Value must be in class [-0-9.] or be \'U\' if the actual value can\'t be determined.'; static $perfdata_min_must_be_in_class = 'Min must be in class [-0-9.] or empty.'; static $perfdata_max_must_be_in_class = 'Max must be in class [-0-9.] or empty.'; static $perfdata_uom_not_recognized = 'UOM (unit of measurement) "%s" is not recognized.'; static $perfdata_mixed_uom_not_implemented = 'Mixed UOMs (%s and %s) are currently not supported.'; static $no_compatible_range_uom_found = 'Measured values are not compatible with the provided warning/critical parameter. Most likely, the UOM is incompatible.'; static $exception_x = '%s (%s)'; static $no_syntax_defined = 'The author of this plugin has not defined a syntax for this plugin.'; static $usage_x = "Usage:\n%s"; static $options = "Options:"; static $illegal_statusmodel = "Invalid statusmodel %d."; static $none = '[none]'; static $valueUomPairSyntaxError = 'Syntax error at "%s". Syntax must be Value[UOM].'; static $too_few_warning_ranges = "You have too few warning ranges (currently trying to get element %d)."; static $too_few_critical_ranges = "You have too few critical ranges (currently trying to get element %d)."; static $dataset_missing = 'Dataset missing.'; static $payload_not_base64 = 'The payload is not valid Base64.'; static $payload_not_json = 'The payload is not valid JSON.'; static $signature_missing = 'The signature is missing.'; static $signature_not_bas64 = 'The signature is not valid Base64.'; static $signature_invalid = 'The signature is invalid. The connection might have been tampered, or a different key is used.'; static $pubkey_file_not_found = "Public key file %s was not found."; static $pubkey_file_not_readable = "Public key file %s is not readable."; static $privkey_file_not_found = "Private key file %s was not found."; static $privkey_not_readable = "Private key is not readable."; static $privkey_file_not_readable = "Private key file %s is not readable."; static $signature_failed = "Signature failed."; static $perfdata_line_invalid = "Performance data line %s is invalid."; static $singlevalue_unexpected_at_symbol = 'This plugin does not allow the @-symbol at ranges for single values.'; static $illegalSingleValueBehavior = "Illegal value for 'singleValueBehavior'. Please contact the creator of the plugin."; static $dataset_encryption_no_array = 'Dataset encryption information invalid.'; static $require_password = 'This resource is protected with a password. Please provide a password.'; static $wrong_password = 'This resource is protected with a password. You have provided the wrong password, or it was changed.'; static $convert_x_y_error = 'Cannot convert from UOM %s to UOM %s.'; static $php_error = 'PHP has detected an error in the plugin. Please contact the plugin author.'; static $output_level_lowered = "Output Buffer level lowered during cbRun(). Please contact the plugin author."; static $openssl_missing = "OpenSSL is missing. Therefore, encryption and signatures are not available."; static $warning_range = 'Warning range'; static $critical_range = 'Critical range'; static $prints_version = 'Prints version'; static $verbosity_helptext = 'Verbosity -v, -vv or -vvv'; static $timeout_helptext = 'Sets timeout in seconds'; static $help_helptext = 'Prints help page'; static $prints_usage = 'Prints usage'; static $notConstructed = 'Parent constructor not called with parent::__construct().'; } function vnagErrorHandler($errorkind, $errortext, $file, $line) { global $inside_vnag_run; if (!$inside_vnag_run && VNag::is_http_mode()) { return false; } if (!(error_reporting() & $errorkind)) { return true; } if (defined('E_ERROR') && ($errorkind == E_ERROR)) $errorkind = 'Error'; if (defined('E_WARNING') && ($errorkind == E_WARNING)) $errorkind = 'Warning'; if (defined('E_PARSE') && ($errorkind == E_PARSE)) $errorkind = 'Parse'; if (defined('E_NOTICE') && ($errorkind == E_NOTICE)) $errorkind = 'Notice'; if (defined('E_CORE_ERROR') && ($errorkind == E_CORE_ERROR)) $errorkind = 'Core Error'; if (defined('E_CORE_WARNING') && ($errorkind == E_CORE_WARNING)) $errorkind = 'Core Warning'; if (defined('E_COMPILE_ERROR') && ($errorkind == E_COMPILE_ERROR)) $errorkind = 'Compile Error'; if (defined('E_COMPILE_WARNING') && ($errorkind == E_COMPILE_WARNING)) $errorkind = 'Compile Warning'; if (defined('E_USER_ERROR') && ($errorkind == E_USER_ERROR)) $errorkind = 'User Error'; if (defined('E_USER_WARNING') && ($errorkind == E_USER_WARNING)) $errorkind = 'User Warning'; if (defined('E_USER_NOTICE') && ($errorkind == E_USER_NOTICE)) $errorkind = 'User Notice'; if (defined('E_STRICT') && ($errorkind == E_STRICT)) $errorkind = 'Strict'; if (defined('E_RECOVERABLE_ERROR') && ($errorkind == E_RECOVERABLE_ERROR)) $errorkind = 'Recoverable Error'; if (defined('E_DEPRECATED') && ($errorkind == E_DEPRECATED)) $errorkind = 'Deprecated'; if (defined('E_USER_DEPRECATED') && ($errorkind == E_USER_DEPRECATED)) $errorkind = 'User Deprecated'; throw new VNagException(VNagLang::$php_error . " $errortext at $file:$line (kind $errorkind)"); } $inside_vnag_run = false; $old_error_handler = set_error_handler("vnagErrorHandler"); <?php
declare(ticks=1); class WordPressVersionCheck extends VNag { protected $argSystemDir = null; public function __construct() { parent::__construct(); $this->registerExpectedStandardArguments('Vht'); $this->getHelpManager()->setPluginName('check_wordpress_version'); $this->getHelpManager()->setVersion('2023-10-13'); $this->getHelpManager()->setShortDescription('This plugin checks if a local WordPress Webmail system has the latest version installed.'); $this->getHelpManager()->setCopyright('Copyright (C) 2011-$CURYEAR$ Daniel Marschall, ViaThinkSoft.'); $this->getHelpManager()->setSyntax('$SCRIPTNAME$ [-d <directory>]'); $this->getHelpManager()->setFootNotes('If you encounter bugs, please contact ViaThinkSoft at www.viathinksoft.com'); $this->addExpectedArgument($this->argSystemDir = new VNagArgument('d', 'directory', VNagArgument::VALUE_REQUIRED, 'wordpressPath', 'The local directory where WordPress installation is located.')); } protected function get_local_version($path) { $path = realpath($path) === false ? $path : realpath($path); $cont = @file_get_contents("$path/wp-includes/version.php"); if ($cont === false) { throw new VNagException("Cannot find version information at $path (cannot read version.php)"); } if (!preg_match('@\$wp_version = \'(.+)\';@ismU', $cont, $m)) { throw new VNagException("Cannot find version information at $path (cannot find version string)"); } return $m[1]; } protected function get_latest_version() { $cont = $this->url_get_contents('https://wordpress.org/download/'); if ($cont === false) { throw new VNagException("Cannot access website with latest version"); } if (!preg_match('@Download WordPress ([0-9\.]+)@ism', $cont, $m)) { throw new VNagException("Cannot find version information on the website"); } return trim($m[1]); } protected function cbRun($optional_args=array()) { $system_dir = $this->argSystemDir->getValue(); if (empty($system_dir)) { throw new VNagException("Please specify the directory of the WordPress installation."); } $system_dir = realpath($system_dir) === false ? $system_dir : realpath($system_dir); if (!is_dir($system_dir)) { throw new VNagException('Directory "'.$system_dir.'" not found.'); } $version = $this->get_local_version($system_dir); $latest_version = $this->get_latest_version(); if (version_compare($version,$latest_version) >= 0) { $this->setStatus(VNag::STATUS_OK); $this->setHeadline("Version $version at $system_dir", true); } else { $this->setStatus(VNag::STATUS_WARNING); $this->setHeadline("Version $version is outdated (Latest version is $latest_version) at $system_dir", true); } } } <?php
- declare(ticks=1); require_once __DIR__ . '/../../framework/vnag_framework.inc.php'; require_once __DIR__ . '/WordPressVersionCheck.class.php'; $job = new WordPressVersionCheck(); $job->run(); unset($job); [ïÖ·,Ë{ý5å
-‰V¨Ûaª1éD¼”GBMB
\ No newline at end of file
+ declare(ticks=1); require_once __DIR__ . '/../../framework/vnag_framework.inc.php'; require_once __DIR__ . '/WordPressVersionCheck.class.php'; $job = new WordPressVersionCheck(); $job->run(); unset($job); *l!t¥å˜VuóUNoÿ onj^¢.ÞtùK7­Í³œéšY&²aT­5ˆ@ë֞Opº&ŒdÚØGBMB
\ No newline at end of file
/trunk/bin/x509_expire.phar
291,8 → 291,8
 
Extract_Phar::go();
__HALT_COMPILER(); ?>
Sva:1:{s:23:"1.3.6.1.4.1.37476.3.0.2";s:328:"sha256||framework/vnag_framework.inc.php|460b109d1c578e9b6af41612e0312c9f36fd8beb51f7aa92f1b7bd49614568e8||plugins/x509_expire/X509ExpireCheck.class.php|a9661695ecf621bb455d3b2262ffaf1082c1d7225a5c6651bf7a470e9a194740||plugins/x509_expire/check_x509_expire.phps|59b18f3d60ed3ff1770e4fc99975b87d14c5abd696f625884277a8e2c6609291||";} framework/vnag_framework.inc.phpLÙzï*eLُ4p”¤-plugins/x509_expire/X509ExpireCheck.class.phpÎzï*eÎÃT«¤*plugins/x509_expire/check_x509_expire.phpsÈzï*eÈg(Z¤<?php ?>
<?php
ŸÂa:1:{s:23:"1.3.6.1.4.1.37476.3.0.2";s:404:"sha256||<builder>|481cf75d675006b504520fd2acb3b29c89aea03aab64754e0adfb364de4914b2||framework/vnag_framework.inc.php|0387bf3134f8cc2d1ae24e139019c0edef19c1ba5ca765624efea0b469c7897f||plugins/x509_expire/X509ExpireCheck.class.php|a9661695ecf621bb455d3b2262ffaf1082c1d7225a5c6651bf7a470e9a194740||plugins/x509_expire/check_x509_expire.phps|59b18f3d60ed3ff1770e4fc99975b87d14c5abd696f625884277a8e2c6609291||";} framework/vnag_framework.inc.phpBÙ» +eBÙÞß=¤-plugins/x509_expire/X509ExpireCheck.class.phpλ +eÎÃT«¤*plugins/x509_expire/check_x509_expire.phpsÈ» +eÈg(Z¤<?php
if (!VNag::is_http_mode()) error_reporting(E_ALL); declare(ticks=1); set_time_limit(0); define('VNAG_JSONDATA_V1', 'oid:1.3.6.1.4.1.37476.2.3.1.1'); $OVERWRITE_ARGUMENTS = null; function _empty($x) { return is_null($x) || (trim($x) == ''); } abstract class VNag { const VNAG_VERSION = '2023-10-13'; const STATUS_OK = 0; const STATUS_WARNING = 1; const STATUS_CRITICAL = 2; const STATUS_UNKNOWN = 3; const STATUS_ERROR = 4; const STATUS_UP = 0; const STATUS_DOWN = 1; const STATUS_MAINTAIN = 2; const VERBOSITY_SUMMARY = 0; const VERBOSITY_ADDITIONAL_INFORMATION = 1; const VERBOSITY_CONFIGURATION_DEBUG = 2; const VERBOSITY_PLUGIN_DEBUG = 3; const MAX_VERBOSITY = self::VERBOSITY_PLUGIN_DEBUG; const STATUSMODEL_SERVICE = 0; const STATUSMODEL_HOST = 1; private $initialized = false; private $status = null; private $messages = array(); private $verbose_info = ''; private $warningRanges = array(); private $criticalRanges = array(); private $performanceDataObjects = array(); private static $exitcode = 0; private $helpObj = null; private $argHandler = null; const OUTPUT_NEVER = 0; const OUTPUT_SPECIAL = 1; const OUTPUT_NORMAL = 2; const OUTPUT_EXCEPTION = 4; const OUTPUT_ALWAYS = 7; public $http_visual_output = self::OUTPUT_ALWAYS; public $http_invisible_output = self::OUTPUT_ALWAYS; protected $html_before = ''; protected $html_after = ''; protected $statusmodel = self::STATUSMODEL_SERVICE; protected $show_status_in_headline = true; protected $default_status = self::STATUS_UNKNOWN; protected $default_warning_range = null; protected $default_critical_range = null; protected $argWarning; protected $argCritical; protected $argVersion; protected $argVerbosity; protected $argTimeout; protected $argHelp; protected $argUsage; public $id = null; protected static $http_serial_number = 0; public $privkey = null; public $privkey_password = null; public $sign_algo = null; public $pubkey = null; protected $warningSingleValueRangeBehaviors = array(self::SINGLEVALUE_RANGE_DEFAULT); protected $criticalSingleValueRangeBehaviors = array(self::SINGLEVALUE_RANGE_DEFAULT); const SINGLEVALUE_RANGE_DEFAULT = 0; const SINGLEVALUE_RANGE_VAL_GT_X_BAD = 1; const SINGLEVALUE_RANGE_VAL_GE_X_BAD = 2; const SINGLEVALUE_RANGE_VAL_LT_X_BAD = 3; const SINGLEVALUE_RANGE_VAL_LE_X_BAD = 4; public $password_out = null; public $password_in = null; public static function is_http_mode() { return php_sapi_name() !== 'cli'; } public function getHelpManager() { return $this->helpObj; } public function getArgumentHandler() { return $this->argHandler; } public function outputHTML($text, $after_visual_output=true) { if ($this->is_http_mode()) { if ($this->initialized) { if ($after_visual_output) { $this->html_after .= $text; } else { $this->html_before .= $text; } } else { echo $text; } } } protected function resetArguments() { $this->argWarning = null; $this->argCritical = null; $this->argVersion = null; $this->argVerbosity = null; $this->argTimeout = null; $this->argHelp = null; $this->argWarning = null; $this->argCritical = null; } public function registerExpectedStandardArguments($args) { $this->resetArguments(); for ($i=0; $i<strlen($args); $i++) { switch ($args[$i]) { case 'w': $this->addExpectedArgument($this->argWarning = new VNagArgument('w', 'warning', VNagArgument::VALUE_REQUIRED, VNagLang::$argname_value, VNagLang::$warning_range)); break; case 'c': $this->addExpectedArgument($this->argCritical = new VNagArgument('c', 'critical', VNagArgument::VALUE_REQUIRED, VNagLang::$argname_value, VNagLang::$critical_range)); break; case 'V': $this->addExpectedArgument($this->argVersion = new VNagArgument('V', 'version', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$prints_version)); break; case 'v': $this->addExpectedArgument($this->argVerbosity = new VNagArgument('v', 'verbose', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$verbosity_helptext)); break; case 't': $this->addExpectedArgument($this->argTimeout = new VNagArgument('t', 'timeout', VNagArgument::VALUE_REQUIRED, VNagLang::$argname_seconds, VNagLang::$timeout_helptext)); break; case 'h': $this->addExpectedArgument($this->argHelp = new VNagArgument('h', 'help', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$help_helptext)); break; default: $letter = $args[$i]; throw new VNagInvalidStandardArgument(sprintf(VNagLang::$no_standard_arguments_with_letter, $letter)); } } } public function addExpectedArgument($argObj) { $helpObjAddEntryMethod = new ReflectionMethod($this->helpObj, '_addOption'); $helpObjAddEntryMethod->setAccessible(true); $helpObjAddEntryMethod->invoke($this->helpObj, $argObj); $argHandlerAddEntryMethod = new ReflectionMethod($this->argHandler, '_addExpectedArgument'); $argHandlerAddEntryMethod->setAccessible(true); $argHandlerAddEntryMethod->invoke($this->argHandler, $argObj); } protected function createArgumentHandler() { $this->argHandler = new VNagArgumentHandler(); } protected function createHelpObject() { $this->helpObj = new VNagHelp(); } protected function checkInitialized() { if (!$this->initialized) throw new VNagFunctionCallOutsideSession(); } protected function getVerbosityLevel() { $this->checkInitialized(); if (!isset($this->argVerbosity)) { return self::VERBOSITY_SUMMARY; } else { $level = $this->argVerbosity->count(); if ($level > self::MAX_VERBOSITY) $level = self::MAX_VERBOSITY; return $level; } } public function getWarningRange($argumentNumber=0) { $this->checkInitialized(); if (!isset($this->warningRanges[$argumentNumber])) { if (!is_null($this->argWarning)) { $warning = $this->argWarning->getValue(); if (!is_null($warning)) { $vals = explode(',',$warning); foreach ($vals as $number => $val) { if (_empty($val)) { $this->warningRanges[$number] = null; } else { $singleValueBehavior = isset($this->warningSingleValueRangeBehaviors[$number]) ? $this->warningSingleValueRangeBehaviors[$number] : VNag::SINGLEVALUE_RANGE_DEFAULT; $this->warningRanges[$number] = new VNagRange($val, $singleValueBehavior); } } } else { $this->warningRanges[0] = $this->default_warning_range; } } else { return null; } } if (isset($this->warningRanges[$argumentNumber])) { return $this->warningRanges[$argumentNumber]; } else { return null; } } public function getCriticalRange($argumentNumber=0) { $this->checkInitialized(); if (!isset($this->criticalRanges[$argumentNumber])) { if (!is_null($this->argCritical)) { $critical = $this->argCritical->getValue(); if (!is_null($critical)) { $vals = explode(',',$critical); foreach ($vals as $number => $val) { $singleValueBehavior = isset($this->criticalSingleValueRangeBehaviors[$number]) ? $this->criticalSingleValueRangeBehaviors[$number] : VNag::SINGLEVALUE_RANGE_DEFAULT; $this->criticalRanges[$number] = new VNagRange($val, $singleValueBehavior); } } else { $this->criticalRanges[0] = $this->default_critical_range; } } else { return null; } } if (isset($this->criticalRanges[$argumentNumber])) { return $this->criticalRanges[$argumentNumber]; } else { return null; } } public function checkAgainstWarningRange($values, $force=true, $autostatus=true, $argumentNumber=0) { $this->checkInitialized(); if (!$this->getArgumentHandler()->isArgRegistered('w')) { throw new VNagRequiredArgumentNotRegistered('-w'); } $wr = $this->getWarningRange($argumentNumber); if (isset($wr)) { if ($wr->checkAlert($values)) { if ($autostatus) $this->setStatus(VNag::STATUS_WARNING); return true; } else { if ($autostatus) $this->setStatus(VNag::STATUS_OK); return false; } } else { if ($force) { if (($argumentNumber > 0) && (count($this->warningRanges) > 0)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$too_few_warning_ranges, $argumentNumber+1)); } else { throw new VNagRequiredArgumentMissing('-w'); } } } } public function checkAgainstCriticalRange($values, $force=true, $autostatus=true, $argumentNumber=0) { $this->checkInitialized(); if (!$this->getArgumentHandler()->isArgRegistered('c')) { throw new VNagRequiredArgumentNotRegistered('-c'); } $cr = $this->getCriticalRange($argumentNumber); if (isset($cr)) { if ($cr->checkAlert($values)) { if ($autostatus) $this->setStatus(VNag::STATUS_CRITICAL); return true; } else { if ($autostatus) $this->setStatus(VNag::STATUS_OK); return false; } } else { if ($force) { if (($argumentNumber > 0) && (count($this->warningRanges) > 0)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$too_few_critical_ranges, $argumentNumber+1)); } else { throw new VNagRequiredArgumentMissing('-c'); } } } } protected static function getBaddestExitcode($code1, $code2) { return max($code1, $code2); } public static function _shutdownHandler() { if (!self::is_http_mode()) { exit((int)self::$exitcode); } } protected function _exit($code) { self::$exitcode = $this->getBaddestExitcode($code, self::$exitcode); } private $constructed = false; function __construct() { $this->createHelpObject(); $this->createArgumentHandler(); $this->addExpectedArgument($this->argUsage = new VNagArgument('?', '', VNagArgument::VALUE_FORBIDDEN, null, VNagLang::$prints_usage)); $this->constructed = true; } function __destruct() { if (Timeouter::started()) { Timeouter::end(); } } public function run() { global $inside_vnag_run; $inside_vnag_run = true; try { if (!$this->constructed) { throw new VNagNotConstructed(VNagLang::$notConstructed); } try { $this->initialized = true; $this->html_before = ''; $this->html_after = ''; $this->setStatus(null, true); $this->messages = array(); register_shutdown_function(array($this, '_shutdownHandler')); if ($this->argHandler->illegalUsage()) { $content = $this->helpObj->printUsagePage(); $this->setStatus(VNag::STATUS_UNKNOWN); if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_visual_output & VNag::OUTPUT_SPECIAL) echo $this->writeVisualHTML($content); if ($this->http_invisible_output & VNag::OUTPUT_SPECIAL) echo $this->writeInvisibleHTML($content); echo $this->html_after; return; } else { echo $content; return $this->_exit($this->status); } } if (!is_null($this->argVersion) && ($this->argVersion->available())) { $content = $this->helpObj->printVersionPage(); $this->setStatus(VNag::STATUS_UNKNOWN); if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_visual_output & VNag::OUTPUT_SPECIAL) echo $this->writeVisualHTML($content); if ($this->http_invisible_output & VNag::OUTPUT_SPECIAL) echo $this->writeInvisibleHTML($content); echo $this->html_after; return; } else { echo $content; return $this->_exit($this->status); } } if (!is_null($this->argHelp) && ($this->argHelp->available())) { $content = $this->helpObj->printHelpPage(); $this->setStatus(VNag::STATUS_UNKNOWN); if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_visual_output & VNag::OUTPUT_SPECIAL) echo $this->writeVisualHTML($content); if ($this->http_invisible_output & VNag::OUTPUT_SPECIAL) echo $this->writeInvisibleHTML($content); echo $this->html_after; return; } else { echo $content; return $this->_exit($this->status); } } $this->getWarningRange(); $this->getCriticalRange(); if (!is_null($this->argTimeout)) { $timeout = $this->argTimeout->getValue(); if (!is_null($timeout)) { Timeouter::start($timeout); } } ob_start(); $init_ob_level = ob_get_level(); try { $this->cbRun(); if (ob_get_level() < $init_ob_level) throw new VNagImplementationErrorException(VNagLang::$output_level_lowered); } finally { while (ob_get_level() > $init_ob_level) @ob_end_clean(); } if (is_null($this->status)) $this->setStatus($this->default_status,true); $outputType = VNag::OUTPUT_NORMAL; } catch (Exception $e) { $this->handleException($e); $outputType = VNag::OUTPUT_EXCEPTION; } if ($this->is_http_mode()) { echo $this->html_before; if ($this->http_invisible_output & $outputType) { echo $this->writeInvisibleHTML(); } if ($this->http_visual_output & $outputType) { echo $this->writeVisualHTML(); } echo $this->html_after; } else { echo $this->getNagiosConsoleText(); return $this->_exit($this->status); } Timeouter::end(); } finally { $inside_vnag_run = false; } } private function getNagiosConsoleText() { $ary_perfdata = $this->getPerformanceData(); $performancedata_first = array_shift($ary_perfdata); $performancedata_rest = implode(' ', $ary_perfdata); $status_text = VNagLang::status($this->status, $this->statusmodel); if (_empty($this->getHeadline())) { $content = $status_text; } else { if ($this->show_status_in_headline) { $content = $status_text.': '.$this->getHeadline(); } else { $content = $this->getHeadline(); } } if (!_empty($performancedata_first)) $content .= '|'.trim($performancedata_first); $content .= "\n"; if (!_empty($this->verbose_info)) { $content .= trim($this->verbose_info); } if (!_empty($performancedata_rest)) $content .= '|'.trim($performancedata_rest); $content .= "\n"; return trim($content)."\n"; } abstract protected function cbRun(); public function addPerformanceData($prefDataObj, $move_to_font=false, $verbosityLevel=VNag::VERBOSITY_SUMMARY) { $this->checkInitialized(); if ((!isset($this->argVerbosity)) && ($verbosityLevel > VNag::VERBOSITY_SUMMARY)) throw new VNagRequiredArgumentNotRegistered('-v'); if (self::getVerbosityLevel() < $verbosityLevel) return false; if ($move_to_font) { array_unshift($this->performanceDataObjects, $prefDataObj); } else { $this->performanceDataObjects[] = $prefDataObj; } return true; } public function getPerformanceData() { $this->checkInitialized(); return $this->performanceDataObjects; } public function removePerformanceData($prefDataObj) { if (($key = array_search($prefDataObj, $this->performanceDataObjects, true)) !== false) { unset($this->performanceDataObjects[$key]); return true; } else { return false; } } public function clearPerformanceData() { $this->performanceDataObjects = array(); } public function getVerboseInfo() { return $this->verbose_info; } public function clearVerboseInfo() { $this->verbose_info = ''; } private function writeVisualHTML($special_content=null) { if (!_empty($special_content)) { $content = $special_content; } else { $content = strtoupper(VNagLang::$status.': '.VNagLang::status($this->status, $this->statusmodel))."\n\n"; $content .= strtoupper(VNagLang::$message).":\n"; $status_text = VNagLang::status($this->status, $this->statusmodel); if (_empty($this->getHeadline())) { $content .= $status_text; } else { if ($this->show_status_in_headline) { $content .= $status_text.': '.trim($this->getHeadline()); } else { $content .= trim($this->getHeadline()); } } $content .= "\n\n"; if (!_empty($this->verbose_info)) { $content .= strtoupper(VNagLang::$verbose_info).":\n".trim($this->verbose_info)."\n\n"; } $perfdata = $this->getPerformanceData(); if (count($perfdata) > 0) { $content .= strtoupper(VNagLang::$performance_data).":\n"; foreach ($perfdata as $pd) { $content .= trim($pd)."\n"; } $content .= "\n"; } } $colorinfo = ''; $status = $this->getStatus(); if ($status == VNag::STATUS_OK) $colorinfo = ' style="background-color:green;color:white;font-weight:bold"'; else if ($status == VNag::STATUS_WARNING) $colorinfo = ' style="background-color:yellow;color:black;font-weight:bold"'; else if ($status == VNag::STATUS_CRITICAL) $colorinfo = ' style="background-color:red;color:white;font-weight:bold"'; else if ($status == VNag::STATUS_ERROR) $colorinfo = ' style="background-color:purple;color:white;font-weight:bold"'; else $colorinfo = ' style="background-color:lightgray;color:black;font-weight:bold"'; $html_content = trim($content); $html_content = htmlentities($html_content); $html_content = str_replace(' ', '&nbsp;', $html_content); $html_content = nl2br($html_content); return '<table border="1" cellspacing="2" cellpadding="2" style="width:100%" class="vnag_table">'. '<tr'.$colorinfo.' class="vnag_title_row">'. '<td>'.VNagLang::$nagios_output.'</td>'. '</tr>'. '<tr class="vnag_message_row">'. '<td><code>'. $html_content. '</code></td>'. '</tr>'. '</table>'; } protected function readInvisibleHTML($html) { $this->checkInitialized(); $doc = new DOMDocument(); @$doc->loadHTML($html); $tags = $doc->getElementsByTagName('script'); foreach ($tags as $tag) { $type = $tag->getAttribute('type'); if ($type !== 'application/json') continue; $json = $tag->nodeValue; if (!$json) continue; $data = @json_decode($json,true); if (!is_array($data)) continue; if (!isset($data['type'])) continue; if ($data['type'] === VNAG_JSONDATA_V1) { if (!isset($data['datasets'])) throw new VNagWebInfoException(VNagLang::$dataset_missing); foreach ($data['datasets'] as $dataset) { $payload = base64_decode($dataset['payload']); if (!$payload) { throw new VNagWebInfoException(VNagLang::$payload_not_base64); } if (isset($dataset['encryption'])) { $cryptInfo = $dataset['encryption']; if (!is_array($cryptInfo)) { throw new VNagWebInfoException(VNagLang::$dataset_encryption_no_array); } $password = is_null($this->password_in) ? '' : $this->password_in; $salt = base64_decode($cryptInfo['salt']); if ($cryptInfo['hash'] != hash('sha256',$salt.$password)) { if ($password == '') { throw new VNagWebInfoException(VNagLang::$require_password); } else { throw new VNagWebInfoException(VNagLang::$wrong_password); } } if (!function_exists('openssl_decrypt')) { throw new VNagException(VNagLang::$openssl_missing); } $payload = openssl_decrypt($payload, $cryptInfo['method'], $password, 0, $cryptInfo['iv']); } if (!is_null($this->pubkey) && ($this->pubkey !== '')) { if (substr($this->pubkey,0,3) === '---') { $public_key = $this->pubkey; } else { if (!file_exists($this->pubkey)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$pubkey_file_not_found, $this->pubkey)); } $public_key = @file_get_contents($this->pubkey); if (!$public_key) { throw new VNagPublicKeyException(sprintf(VNagLang::$pubkey_file_not_readable, $this->pubkey)); } } if (!isset($dataset['signature'])) { throw new VNagSignatureException(VNagLang::$signature_missing); } $signature = base64_decode($dataset['signature']); if (!$signature) { throw new VNagSignatureException(VNagLang::$signature_not_bas64); } if (!function_exists('openssl_verify')) { throw new VNagException(VNagLang::$openssl_missing); } $sign_algo = is_null($this->sign_algo) ? OPENSSL_ALGO_SHA256 : $this->sign_algo; if (!openssl_verify($payload, $signature, $public_key, $sign_algo)) { throw new VNagSignatureException(VNagLang::$signature_invalid); } } $payload = @json_decode($payload,true); if (!$payload) { throw new VNagWebInfoException(VNagLang::$payload_not_json); } if ($payload['id'] == $this->id) { return $payload; } } } } return null; } private function getNextMonitorID($peek=false) { $result = is_null($this->id) ? self::$http_serial_number : $this->id; if (!$peek) { $this->id = null; self::$http_serial_number++; } return $result; } private function writeInvisibleHTML($special_content=null) { $payload['id'] = $this->getNextMonitorID(); $payload['status'] = $this->getStatus(); if (!_empty($special_content)) { $payload['text'] = $special_content; } else { $payload['headline'] = $this->getHeadline(); $payload['verbose_info'] = $this->verbose_info; $payload['performance_data'] = array(); foreach ($this->performanceDataObjects as $perfdata) { $payload['performance_data'][] = (string)$perfdata; } } $payload = json_encode($payload); $dataset = array(); if (!is_null($this->privkey) && ($this->privkey !== '')) { if (!function_exists('openssl_pkey_get_private') || !function_exists('openssl_sign')) { throw new VNagException(VNagLang::$openssl_missing); } if (substr($this->privkey,0,3) === '---') { $pkeyid = @openssl_pkey_get_private($this->privkey, $this->privkey_password); if (!$pkeyid) { throw new VNagPrivateKeyException(sprintf(VNagLang::$privkey_not_readable)); } } else { if (!file_exists($this->privkey)) { throw new VNagInvalidArgumentException(sprintf(VNagLang::$privkey_file_not_found, $this->privkey)); } $pkeyid = @openssl_pkey_get_private('file://'.$this->privkey, $this->privkey_password); if (!$pkeyid) { throw new VNagPrivateKeyException(sprintf(VNagLang::$privkey_file_not_readable, $this->privkey)); } } $signature = ''; $sign_algo = is_null($this->sign_algo) ? OPENSSL_ALGO_SHA256 : $this->sign_algo; if (@openssl_sign($payload, $signature, $pkeyid, $sign_algo)) { if (version_compare(PHP_VERSION, '8.0.0') < 0) { openssl_free_key($pkeyid); } $dataset['signature'] = base64_encode($signature); } else { throw new VNagPrivateKeyException(sprintf(VNagLang::$signature_failed)); } } if (!is_null($this->password_out) && ($this->password_out !== '')) { if (!function_exists('openssl_encrypt')) { throw new VNagException(VNagLang::$openssl_missing); } $password = $this->password_out; $method = 'aes-256-ofb'; $iv = substr(hash('sha256', openssl_random_pseudo_bytes(32)), 0, 16); $salt = openssl_random_pseudo_bytes(32); $cryptInfo = array(); $cryptInfo['method'] = $method; $cryptInfo['iv'] = $iv; $cryptInfo['salt'] = base64_encode($salt); $cryptInfo['hash'] = hash('sha256', $salt.$password); $payload = openssl_encrypt($payload, $method, $password, 0, $iv); $dataset['encryption'] = $cryptInfo; } $dataset['payload'] = base64_encode($payload); $json = array(); $json['type'] = VNAG_JSONDATA_V1; $json['datasets'] = array($dataset); return '<script type="application/json">'. json_encode($json). '</script>'; } protected function appendHeadline($msg) { $this->checkInitialized(); if (_empty($msg)) return false; $this->messages[] = $msg; return true; } protected function changeHeadline($msg) { $this->checkInitialized(); if (_empty($msg)) { $this->messages = array(); } else { $this->messages = array($msg); } return true; } public function setHeadline($msg, $append=false, $verbosityLevel=VNag::VERBOSITY_SUMMARY) { $this->checkInitialized(); if ((!isset($this->argVerbosity)) && ($verbosityLevel > VNag::VERBOSITY_SUMMARY)) throw new VNagRequiredArgumentNotRegistered('-v'); if (self::getVerbosityLevel() < $verbosityLevel) $msg = ''; if ($append) { return $this->appendHeadline($msg); } else { return $this->changeHeadline($msg); } } public function getHeadline() { $this->checkInitialized(); return implode(', ', $this->messages); } public function addVerboseMessage($msg, $verbosityLevel=VNag::VERBOSITY_SUMMARY) { $this->checkInitialized(); if (self::getVerbosityLevel() >= $verbosityLevel) { $this->verbose_info .= $msg."\n"; } } public function setStatus($status, $force=false) { $this->checkInitialized(); if (($force) || is_null($this->status) || ($status > $this->status)) { $this->status = $status; } } public function getStatus() { $this->checkInitialized(); return $this->status; } protected static function exceptionText($exception) { $class = get_class($exception); $msg = $exception->getMessage(); if (!_empty($msg)) { return sprintf(VNagLang::$exception_x, $msg, $class); } else { return sprintf(VNagLang::$unhandled_exception_without_msg, $class); } } protected function handleException($exception) { $this->checkInitialized(); if (!VNag::is_http_mode()) { while (ob_get_level() > 0) @ob_end_clean(); } $this->clearVerboseInfo(); $this->clearPerformanceData(); if ($exception instanceof VNagException) { $this->setStatus($exception->getStatus()); } else { $this->setStatus(self::STATUS_ERROR); } $this->setHeadline($this->exceptionText($exception), false); if ($exception instanceof VNagImplementationErrorException) { $this->addVerboseMessage($exception->getTraceAsString(), VNag::VERBOSITY_SUMMARY); } else { if (isset($this->argVerbosity)) { $this->addVerboseMessage($exception->getTraceAsString(), VNag::VERBOSITY_ADDITIONAL_INFORMATION); } else { } } } protected function get_cache_dir() { $homedir = @getenv('HOME'); if ($homedir && is_dir($homedir)) { $try = "$homedir/.vnag/cache"; if (is_dir($try)) return $try; if (@mkdir($try,0777,true)) return $try; } $user = posix_getpwuid(posix_geteuid()); if (isset($user['dir']) && is_dir($user['dir'])) { $homedir = $user['dir']; $try = "$homedir/.vnag/cache"; if (is_dir($try)) return $try; if (@mkdir($try,0777,true)) return $try; } if (isset($user['name']) && is_dir($user['name'])) { $username = $user['name']; $try = "/tmp/vnag/cache"; if (is_dir($try)) return $try; if (@mkdir($try,0777,true)) return $try; } throw new VNagException("Cannot get cache dir"); } protected function url_get_contents($url, $max_cache_time=1*60*60, $context=null) { $cache_file = $this->get_cache_dir().'/'.hash('sha256',$url); if (file_exists($cache_file) && (time()-filemtime($cache_file) < $max_cache_time)) { $cont = @file_get_contents($cache_file); if ($cont === false) throw new Exception("Failed to get contents from $cache_file"); } else { $options = array( 'http'=>array( 'method'=>"GET", 'header'=>"Accept-language: en\r\n" . "User-Agent: Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B334b Safari/531.21.102011-10-16 20:23:10\r\n" ) ); if (is_null($context)) $context = stream_context_create($options); $cont = @file_get_contents($url, false, $context); if ($cont === false) throw new Exception("Failed to get contents from $url"); file_put_contents($cache_file, $cont); } return $cont; } } class VNagException extends Exception { public function getStatus() { return VNag::STATUS_ERROR; } } class VNagTimeoutException extends VNagException {} class VNagWebInfoException extends VNagException {} class VNagSignatureException extends VNagException {} class VNagPublicKeyException extends VNagException {} class VNagPrivateKeyException extends VNagException {} class VNagInvalidArgumentException extends VNagException { public function getStatus() { return VNag::STATUS_UNKNOWN; } } class VNagValueUomPairSyntaxException extends VNagInvalidArgumentException { public function __construct($str) { $e_msg = sprintf(VNagLang::$valueUomPairSyntaxError, $str); parent::__construct($e_msg); } } class VNagInvalidTimeoutException extends VNagInvalidArgumentException {} class VNagInvalidRangeException extends VNagInvalidArgumentException { public function __construct($msg) { $e_msg = VNagLang::$range_is_invalid; if (!_empty($msg)) $e_msg .= ': '.trim($msg); parent::__construct($e_msg); } } class VNagInvalidShortOpt extends VNagImplementationErrorException {} class VNagInvalidLongOpt extends VNagImplementationErrorException {} class VNagInvalidValuePolicy extends VNagImplementationErrorException {} class VNagIllegalStatusModel extends VNagImplementationErrorException {} class VNagNotConstructed extends VNagImplementationErrorException {} class VNagImplementationErrorException extends VNagException {} class VNagInvalidStandardArgument extends VNagImplementationErrorException {} class VNagFunctionCallOutsideSession extends VNagImplementationErrorException {} class VNagIllegalArgumentValuesException extends VNagImplementationErrorException {} class VNagRequiredArgumentNotRegistered extends VNagImplementationErrorException { public function __construct($required_argument) { $e_msg = sprintf(VNagLang::$query_without_expected_argument, $required_argument); parent::__construct($e_msg); } } class VNagRequiredArgumentMissing extends VNagInvalidArgumentException { public function __construct($required_argument) { $e_msg = sprintf(VNagLang::$required_argument_missing, $required_argument); parent::__construct($e_msg); } } class VNagUnknownUomException extends VNagInvalidArgumentException { public function __construct($uom) { $e_msg = sprintf(VNagLang::$perfdata_uom_not_recognized, $uom); parent::__construct($e_msg); } } class VNagNoCompatibleRangeUomFoundException extends VNagException {} class VNagMixedUomsNotImplemented extends VNagInvalidArgumentException { public function __construct($uom1, $uom2) { if (_empty($uom1)) $uom1 = VNagLang::$none; if (_empty($uom2)) $uom2 = VNagLang::$none; $e_msg = sprintf(VNagLang::$perfdata_mixed_uom_not_implemented, $uom1, $uom2); parent::__construct($e_msg); } } class VNagUomConvertException extends VNagInvalidArgumentException { public function __construct($uom1, $uom2) { if (_empty($uom1)) $uom1 = VNagLang::$none; if (_empty($uom2)) $uom2 = VNagLang::$none; $e_msg = sprintf(VNagLang::$convert_x_y_error, $uom1, $uom2); parent::__construct($e_msg); } } class VNagInvalidPerformanceDataException extends VNagInvalidArgumentException { public function __construct($msg) { $e_msg = VNagLang::$performance_data_invalid; if (!_empty($msg)) $e_msg .= ': '.trim($msg); parent::__construct($e_msg); } } class Timeouter { private static $start_time = false; private static $timeout; private static $fired = false; private static $registered = false; private function __construct() { } public static function start($timeout) { if (!is_numeric($timeout) || ($timeout <= 0)) { throw new VNagInvalidTimeoutException(sprintf(VNagLang::$timeout_value_invalid, $timeout)); } self::$start_time = microtime(true); self::$timeout = (float) $timeout; self::$fired = false; if (!self::$registered) { self::$registered = true; register_tick_function(array('Timeouter', 'tick')); } } public static function started() { return self::$registered; } public static function end() { if (self::$registered) { unregister_tick_function(array('Timeouter', 'tick')); self::$registered = false; } } public static function tick() { if ((!self::$fired) && ((microtime(true) - self::$start_time) > self::$timeout)) { self::$fired = true; throw new VNagTimeoutException(VNagLang::$timeout_exception); } } } class VNagArgument { const VALUE_FORBIDDEN = 0; const VALUE_REQUIRED = 1; const VALUE_OPTIONAL = 2; protected $shortopt; protected $longopts; protected $valuePolicy; protected $valueName; protected $helpText; protected $defaultValue = null; protected static $all_short = ''; protected static $all_long = array(); public function getShortOpt() { return $this->shortopt; } public function getLongOpts() { return $this->longopts; } public function getValuePolicy() { return $this->valuePolicy; } public function getValueName() { return $this->valueName; } public function getHelpText() { return $this->helpText; } static private function validateShortOpt($shortopt) { $m = array(); return preg_match('@^[a-zA-Z0-9\\+\\-\\?]$@', $shortopt, $m); } static private function validateLongOpt($longopt) { $m = array(); return preg_match('@^[a-zA-Z0-9\\+\\-\\?]+$@', $longopt, $m); } public function __construct($shortopt, $longopts, $valuePolicy, $valueName, $helpText, $defaultValue=null) { switch ($valuePolicy) { case VNagArgument::VALUE_FORBIDDEN: if (!_empty($valueName)) { throw new VNagImplementationErrorException(sprintf(VNagLang::$value_name_forbidden)); } break; case VNagArgument::VALUE_REQUIRED: if (_empty($valueName)) { throw new VNagImplementationErrorException(sprintf(VNagLang::$value_name_required)); } break; case VNagArgument::VALUE_OPTIONAL: if (_empty($valueName)) { throw new VNagImplementationErrorException(sprintf(VNagLang::$value_name_required)); } break; default: throw new VNagInvalidValuePolicy(sprintf(VNagLang::$illegal_valuepolicy, $valuePolicy)); } if (!_empty($shortopt)) { if (!self::validateShortOpt($shortopt)) { throw new VNagInvalidShortOpt(sprintf(VNagLang::$illegal_shortopt, $shortopt)); } } if (is_array($longopts)) { foreach ($longopts as $longopt) { if (!self::validateLongOpt($longopt)) { throw new VNagInvalidLongOpt(sprintf(VNagLang::$illegal_longopt, $longopt)); } } } else if (!_empty($longopts)) { if (!self::validateLongOpt($longopts)) { throw new VNagInvalidLongOpt(sprintf(VNagLang::$illegal_longopt, $longopts)); } $longopts = array($longopts); } else { $longopts = array(); } switch ($valuePolicy) { case VNagArgument::VALUE_FORBIDDEN: $policyApdx = ''; break; case VNagArgument::VALUE_REQUIRED: $policyApdx = ':'; break; case VNagArgument::VALUE_OPTIONAL: $policyApdx = '::'; break; default: throw new VNagInvalidValuePolicy(sprintf(VNagLang::$illegal_valuepolicy, $valuePolicy)); } if ((!is_null($shortopt)) && ($shortopt != '?')) self::$all_short .= $shortopt.$policyApdx; if (is_array($longopts)) { foreach ($longopts as $longopt) { self::$all_long[] = $longopt.$policyApdx; } } $this->shortopt = $shortopt; $this->longopts = $longopts; $this->valuePolicy = $valuePolicy; $this->valueName = $valueName; $this->helpText = $helpText; $this->defaultValue = $defaultValue; } protected static function getOptions() { global $OVERWRITE_ARGUMENTS; if (!is_null($OVERWRITE_ARGUMENTS)) { return $OVERWRITE_ARGUMENTS; } else if (VNag::is_http_mode()) { return $_REQUEST; } else { return getopt(self::$all_short, self::$all_long); } } public function count() { $options = self::getOptions(); $count = 0; if (isset($options[$this->shortopt])) { if (is_array($options[$this->shortopt])) { $count += count($options[$this->shortopt]); } else { $count += 1; } } if (!is_null($this->longopts)) { foreach ($this->longopts as $longopt) { if (isset($options[$longopt])) { if (is_array($options[$longopt])) { $count += count($options[$longopt]); } else { $count += 1; } } } } return $count; } public function available() { $options = self::getOptions(); if (isset($options[$this->shortopt])) return true; if (!is_null($this->longopts)) { foreach ($this->longopts as $longopt) { if (isset($options[$longopt])) return true; } } return false; } public function require() { if (!$this->available() && is_null($this->defaultValue)) { $opt = $this->shortopt; $opt = !_empty($opt) ? '-'.$opt : (isset($this->longopts[0]) ? '--'.$this->longopts[0] : '?'); throw new VNagRequiredArgumentMissing($opt); } } public function getValue() { $options = self::getOptions(); if (isset($options[$this->shortopt])) { $x = $options[$this->shortopt]; if (is_array($x) && (count($x) <= 1)) $options[$this->shortopt] = $options[$this->shortopt][0]; return $options[$this->shortopt]; } if (!is_null($this->longopts)) { foreach ($this->longopts as $longopt) { if (isset($options[$longopt])) { $x = $options[$longopt]; if (is_array($x) && (count($x) <= 1)) $options[$longopt] = $options[$longopt][0]; return $options[$longopt]; } } } return $this->defaultValue; } } class VNagArgumentHandler { protected $expectedArgs = array(); protected function _addExpectedArgument($argObj) { if ($argObj->getShortOpt() == '?') return false; if ($argObj->getShortOpt() == '-') return false; if ($argObj->getShortOpt() == '+') return false; $this->expectedArgs[] = $argObj; return true; } public function getArgumentObj($shortopt) { foreach ($this->expectedArgs as $argObj) { if ($argObj->getShortOpt() == $shortopt) return $argObj; } return null; } public function isArgRegistered($shortopt) { return !is_null($this->getArgumentObj($shortopt)); } public function illegalUsage() { global $argv; return (isset($argv[1])) && (($argv[1] == '-?') || ($argv[1] == '/?')); } } class VNagRange { public $start; public $end; public $warnInsideRange; public function __construct($rangeDef, $singleValueBehavior=VNag::SINGLEVALUE_RANGE_DEFAULT) { $m = array(); if (!preg_match('|^(@){0,1}([^:]+)(:){0,1}(.*)$|', $rangeDef, $m)) { throw new VNagInvalidRangeException(sprintf(VNagLang::$range_invalid_syntax, $rangeDef)); } $this->warnInsideRange = $m[1] === '@'; $this->start = null; $this->end = null; if ($m[3] === ':') { if ($m[2] === '~') { $this->start = '-inf'; } else { $this->start = new VNagValueUomPair($m[2]); } if (_empty($m[4])) { $this->end = 'inf'; } else { $this->end = new VNagValueUomPair($m[4]); } } else { assert(_empty($m[4])); assert(!_empty($m[2])); $x = $m[2]; if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_DEFAULT) { $this->start = new VNagValueUomPair('0'.((new VNagValueUomPair($x))->getUom())); $this->end = new VNagValueUomPair($x); } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_GT_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 0; $this->start = '-inf'; $this->end = new VNagValueUomPair($x); } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_GE_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 1; $this->start = new VNagValueUomPair($x); $this->end = 'inf'; } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_LT_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 0; $this->start = new VNagValueUomPair($x); $this->end = 'inf'; } else if ($singleValueBehavior == VNag::SINGLEVALUE_RANGE_VAL_LE_X_BAD) { if ($this->warnInsideRange) throw new VNagInvalidRangeException(VNagLang::$singlevalue_unexpected_at_symbol); $this->warnInsideRange = 1; $this->start = '-inf'; $this->end = new VNagValueUomPair($x); } else { throw new VNagException(VNagLang::$illegalSingleValueBehavior); } } if (is_null($this->start)) { throw new VNagInvalidRangeException(VNagLang::$invalid_start_value); } if (is_null($this->end)) { throw new VNagInvalidRangeException(VNagLang::$invalid_end_value); } if (($this->start instanceof VNagValueUomPair) && ($this->end instanceof VNagValueUomPair) && (VNagValueUomPair::compare($this->start,$this->end) > 0)) { throw new VNagInvalidRangeException(VNagLang::$start_is_greater_than_end); } } public function __toString() { $ret = ''; if ($this->warnInsideRange) { $ret = '@'; } if ($this->start === '-inf') { $ret .= '~'; } else { $ret .= $this->start; } $ret .= ':'; if ($this->end !== 'inf') { $ret .= $this->end; } return $ret; } public function checkAlert($values) { $compatibleCount = 0; if (!is_array($values)) $values = array($values); foreach ($values as $value) { if (!($value instanceof VNagValueUomPair)) $value = new VNagValueUomPair($value); assert(($this->start === '-inf') || ($this->start instanceof VNagValueUomPair)); assert(($this->end === 'inf' ) || ($this->end instanceof VNagValueUomPair)); if (($this->start !== '-inf') && (!$this->start->compatibleWith($value))) continue; if (($this->end !== 'inf') && (!$this->end->compatibleWith($value))) continue; $compatibleCount++; if ($this->warnInsideRange) { return (($this->start === '-inf') || (VNagValueUomPair::compare($value,$this->start) >= 0)) && (($this->end === 'inf') || (VNagValueUomPair::compare($value,$this->end) <= 0)); } else { return (($this->start !== '-inf') && (VNagValueUomPair::compare($value,$this->start) < 0)) || (($this->end !== 'inf') && (VNagValueUomPair::compare($value,$this->end) > 0)); } } if ((count($values) > 0) and ($compatibleCount == 0)) { throw new VNagNoCompatibleRangeUomFoundException(VNagLang::$no_compatible_range_uom_found); } return false; } } class VNagValueUomPair { protected $value; protected $uom; public $roundTo = -1; public function isRelative() { return $this->uom === '%'; } public function getValue() { return $this->value; } public function getUom() { return $this->uom; } public function __toString() { if ($this->roundTo == -1) { return $this->value.$this->uom; } else { return round($this->value,$this->roundTo).$this->uom; } } public function __construct($str) { $m = array(); if (!preg_match('/^([\d\.]+)(.*)$/ism', $str, $m)) { throw new VNagValueUomPairSyntaxException($str); } $this->value = $m[1]; $this->uom = isset($m[2]) ? $m[2] : ''; if (!self::isKnownUOM($this->uom)) { throw new VNagUnknownUomException($this->uom); } } public static function isKnownUOM(string $uom) { $no_unit = ($uom === ''); $seconds = ($uom === 's') || ($uom === 'ms') || ($uom === 'us'); $percentage = ($uom === '%'); $bytes = ($uom === 'B') || ($uom === 'KB') || ($uom === 'MB') || ($uom === 'GB') || ($uom === 'TB'); $counter = ($uom === 'c'); return ($no_unit || $seconds || $percentage || $bytes || $counter); } public function normalize($target=null) { $res = clone $this; if ($res->uom === 'ms') { $res->uom = 's'; $res->value /= 1000; } if ($res->uom === 'us') { $res->uom = 's'; $res->value /= 1000 * 1000; } if ($res->uom === 'B') { $res->uom = 'MB'; $res->value /= 1024 * 1024; } if ($res->uom === 'KB') { $res->uom = 'MB'; $res->value /= 1024; } if ($res->uom === 'GB') { $res->uom = 'MB'; $res->value *= 1024; } if ($res->uom === 'TB') { $res->uom = 'MB'; $res->value *= 1024 * 1024; } if ($res->uom === 'c') { $res->uom = ''; } if (!is_null($target)) { if ($res->uom == 'MB') { if ($target == 'B') { $res->uom = 'B'; $res->value *= 1024 * 1024; } else if ($target == 'KB') { $res->uom = 'KB'; $res->value *= 1024; } else if ($target == 'MB') { $res->uom = 'MB'; $res->value *= 1; } else if ($target == 'GB') { $res->uom = 'GB'; $res->value /= 1024; } else if ($target == 'TB') { $res->uom = 'TB'; $res->value /= 1024 * 1024; } else { throw new VNagUomConvertException($res->uom, $target); } } else if ($res->uom == 's') { if ($target == 's') { $res->uom = 's'; $res->value /= 1; } else if ($target == 'ms') { $res->uom = 'ms'; $res->value /= 1000; } else if ($target == 'us') { $res->uom = 'us'; $res->value /= 1000 * 1000; } else { throw new VNagUomConvertException($res->uom, $target); } } else { throw new VNagUomConvertException($res->uom, $target); } } return $res; } public function compatibleWith(VNagValueUomPair $other) { $a = $this->normalize(); $b = $other->normalize(); return ($a->uom == $b->uom); } public static function compare(VNagValueUomPair $left, VNagValueUomPair $right) { $a = $left->normalize(); $b = $right->normalize(); if ($a->uom != $b->uom) throw new VNagMixedUomsNotImplemented($a->uom, $b->uom); if ($a->value > $b->value) return 1; if ($a->value == $b->value) return 0; if ($a->value < $b->value) return -1; } } class VNagPerformanceData { protected $label; protected $value; protected $warn = null; protected $crit = null; protected $min = null; protected $max = null; public static function createByString($perfdata) { $perfdata = trim($perfdata); $ary = explode('=',$perfdata); if (count($ary) != 2) { throw new VNagInvalidPerformanceDataException(sprintf(VNagLang::$perfdata_line_invalid, $perfdata)); } $label = $ary[0]; $bry = explode(';',$ary[1]); if (substr($label,0,1) === "'") $label = substr($label, 1, strlen($label)-2); $value = $bry[0]; $warn = isset($bry[1]) ? $bry[1] : null; $crit = isset($bry[2]) ? $bry[2] : null; $min = isset($bry[3]) ? $bry[3] : null; $max = isset($bry[4]) ? $bry[4] : null; return new self($label, $value, $warn, $crit, $min, $max); } public function __construct($label, $value, $warn=null, $crit=null, $min=null, $max=null) { if (strpos($label, '=') !== false) throw new VNagInvalidPerformanceDataException(VNagLang::$perfdata_label_equal_sign_forbidden); $label = str_replace("'", "''", $label); $m = array(); if ((!_empty($min)) && (!preg_match('|^[-0-9\\.]+$|', $min, $m))) { throw new VNagInvalidPerformanceDataException(VNagLang::$perfdata_min_must_be_in_class); } if ((!_empty($max)) && (!preg_match('|^[-0-9\\.]+$|', $max, $m))) { throw new VNagInvalidPerformanceDataException(VNagLang::$perfdata_max_must_be_in_class); } $this->label = $label; $this->value = ($value == 'U') ? 'U' : new VNagValueUomPair($value); $this->warn = $warn; $this->crit = $crit; $this->min = $min; $this->max = $max; } public function __toString() { $label = $this->label; $value = $this->value; $warn = $this->warn; $crit = $this->crit; $min = $this->min; $max = $this->max; $label = str_replace("''", "'", $label); return "'$label'=$value". ';'.(is_null($warn) ? '' : $warn). ';'.(is_null($crit) ? '' : $crit). ';'.(is_null($min) ? '' : $min). ';'.(is_null($max) ? '' : $max); } } class VNagHelp { public $word_wrap_width = 80; public $argument_indent = 7; public function printUsagePage() { $usage = $this->getUsage(); if (_empty($usage)) { $usage = VNagLang::$no_syntax_defined; } return trim($usage)."\n"; } public function printVersionPage() { $out = trim($this->getNameAndVersion())."\n"; if ($this->word_wrap_width > 0) $out = wordwrap($out, $this->word_wrap_width, "\n", false); return $out; } static private function _conditionalLine($line, $terminator='', $prefix='') { if (!_empty($line)) { return trim($line).$terminator; } return ''; } public function printHelpPage() { $out = ''; $out .= self::_conditionalLine($this->getNameAndVersion(), "\n"); $out .= self::_conditionalLine($this->getCopyright(), "\n"); $out .= ($out != '') ? "\n" : ''; $out .= self::_conditionalLine($this->getShortDescription(), "\n\n\n"); $out .= self::_conditionalLine($this->getUsage(), "\n\n"); $out .= VNagLang::$options."\n"; foreach ($this->options as $argObj) { $out .= $this->printArgumentHelp($argObj); } $out .= self::_conditionalLine($this->getFootNotes(), "\n\n", "\n"); if ($this->word_wrap_width > 0) $out = wordwrap($out, $this->word_wrap_width, "\n", false); return $out; } protected $options = array(); protected function _addOption($argObj) { $this->options[] = $argObj; } protected function printArgumentHelp($argObj) { $identifiers = array(); $shortopt = $argObj->getShortopt(); if (!_empty($shortopt)) $identifiers[] = '-'.$shortopt; $longopts = $argObj->getLongopts(); if (!is_null($longopts)) { foreach ($longopts as $longopt) { if (!_empty($longopt)) $identifiers[] = '--'.$longopt; } } if (count($identifiers) == 0) return; $valueName = $argObj->getValueName(); $arginfo = ''; switch ($argObj->getValuePolicy()) { case VNagArgument::VALUE_FORBIDDEN: $arginfo = ''; break; case VNagArgument::VALUE_REQUIRED: $arginfo = '='.$valueName; break; case VNagArgument::VALUE_OPTIONAL: $arginfo = '[='.$valueName.']'; break; } $out = ''; $out .= implode(', ', $identifiers).$arginfo."\n"; $content = trim($argObj->getHelpText()); if ($this->word_wrap_width > 0) $content = wordwrap($content, $this->word_wrap_width-$this->argument_indent, "\n", false); $lines = explode("\n", $content); foreach ($lines as $line) { $out .= str_repeat(' ', $this->argument_indent).$line."\n"; } $out .= "\n"; return $out; } protected $pluginName; public function setPluginName($pluginName) { $this->pluginName = $this->replaceStuff($pluginName); } public function getPluginName() { if (_empty($this->pluginName)) { global $argv; return basename($argv[0]); } else { return $this->pluginName; } } protected $version; public function setVersion($version) { $this->version = $this->replaceStuff($version); } public function getVersion() { return $this->version; } public function getNameAndVersion() { $ret = $this->getPluginName(); if (_empty($ret)) return null; $ver = $this->getVersion(); if (!_empty($ver)) { $ret = sprintf(VNagLang::$x_version_x, $ret, $ver); } $ret = trim($ret); return $ret; } protected $copyright; public function setCopyright($copyright) { $this->copyright = $this->replaceStuff($copyright); } private function getVNagCopyright() { if (VNag::is_http_mode()) { $vts_email = 'www.viathinksoft.com'; } else { $vts_email = base64_decode('aW5mb0B2aWF0aGlua3NvZnQuZGU='); } return "VNag Framework ".VNag::VNAG_VERSION." (C) 2014-".date('Y')." ViaThinkSoft <$vts_email>"; } public function getCopyright() { if (_empty($this->copyright)) { return sprintf(VNagLang::$plugin_uses, $this->getVNagCopyright()); } else { return trim($this->copyright)."\n".sprintf(VNagLang::$uses, $this->getVNagCopyright()); } } protected $shortDescription; public function setShortDescription($shortDescription) { $this->shortDescription = $this->replaceStuff($shortDescription); } public function getShortDescription() { if (_empty($this->shortDescription)) { return null; } else { $content = $this->shortDescription; if ($this->word_wrap_width > 0) $content = wordwrap($content, $this->word_wrap_width, "\n", false); return $content; } } protected function replaceStuff($text) { global $argv; if (php_sapi_name() == 'cli') { $text = str_replace('$SCRIPTNAME$', $argv[0], $text); } else { $text = str_replace('$SCRIPTNAME$', basename($_SERVER['SCRIPT_NAME']), $text); } $text = str_replace('$CURYEAR$', date('Y'), $text); return $text; } protected $syntax; public function setSyntax($syntax) { $syntax = $this->replaceStuff($syntax); $this->syntax = $syntax; } public function getUsage() { if (_empty($this->syntax)) { return null; } else { return sprintf(VNagLang::$usage_x, $this->syntax); } } protected $footNotes; public function setFootNotes($footNotes) { $this->footNotes = $this->replaceStuff($footNotes); } public function getFootNotes() { return $this->footNotes; } } class VNagLang { public static function status($code, $statusmodel) { switch ($statusmodel) { case VNag::STATUSMODEL_SERVICE: switch ($code) { case VNag::STATUS_OK: return 'OK'; case VNag::STATUS_WARNING: return 'Warning'; case VNag::STATUS_CRITICAL: return 'Critical'; case VNag::STATUS_UNKNOWN: return 'Unknown'; default: return sprintf('Error (%d)', $code); } case VNag::STATUSMODEL_HOST: switch ($code) { case VNag::STATUS_UP: return 'Up'; case VNag::STATUS_DOWN: return 'Down'; default: return sprintf('Maintain last state (%d)', $code); } default: throw new VNagIllegalStatusModel(sprintf(self::$illegal_statusmodel, $statusmodel)); } } static $nagios_output = 'VNag-Output'; static $verbose_info = 'Verbose information'; static $status = 'Status'; static $message = 'Message'; static $performance_data = 'Performance data'; static $status_ok = 'OK'; static $status_warn = 'Warning'; static $status_critical = 'Critical'; static $status_unknown = 'Unknown'; static $status_error = 'Error'; static $unhandled_exception_without_msg = "Unhandled exception of type %s"; static $plugin_uses = 'This plugin uses %s'; static $uses = 'uses %s'; static $x_version_x = '%s, version %s'; static $argname_value = 'value'; static $argname_seconds = 'seconds'; static $query_without_expected_argument = "The argument '%s' is queried, but was not added to the list of expected arguments. Please contact the plugin author."; static $required_argument_missing = "The argument '%s' is required."; static $performance_data_invalid = 'Performance data invalid.'; static $no_standard_arguments_with_letter = "No standard argument with letter '%s' exists."; static $invalid_start_value = 'Invalid start value.'; static $invalid_end_value = 'Invalid end value.'; static $start_is_greater_than_end = 'Start is greater than end value.'; static $value_name_forbidden = "Implementation error: You may not define a value name for the argument, because the value policy is VALUE_FORBIDDEN."; static $value_name_required = "Implementation error: Please define a name for the argument (so it can be shown in the help page)."; static $illegal_shortopt = "Illegal shortopt '-%s'."; static $illegal_longopt = "Illegal longopt '--%s'."; static $illegal_valuepolicy = "valuePolicy has illegal value '%s'."; static $range_invalid_syntax = "Syntax error in range '%s'."; static $timeout_value_invalid = "Timeout value '%s' is invalid."; static $range_is_invalid = 'Range is invalid.'; static $timeout_exception = 'Timeout!'; static $perfdata_label_equal_sign_forbidden = 'Label may not contain an equal sign.'; static $perfdata_value_must_be_in_class = 'Value must be in class [-0-9.] or be \'U\' if the actual value can\'t be determined.'; static $perfdata_min_must_be_in_class = 'Min must be in class [-0-9.] or empty.'; static $perfdata_max_must_be_in_class = 'Max must be in class [-0-9.] or empty.'; static $perfdata_uom_not_recognized = 'UOM (unit of measurement) "%s" is not recognized.'; static $perfdata_mixed_uom_not_implemented = 'Mixed UOMs (%s and %s) are currently not supported.'; static $no_compatible_range_uom_found = 'Measured values are not compatible with the provided warning/critical parameter. Most likely, the UOM is incompatible.'; static $exception_x = '%s (%s)'; static $no_syntax_defined = 'The author of this plugin has not defined a syntax for this plugin.'; static $usage_x = "Usage:\n%s"; static $options = "Options:"; static $illegal_statusmodel = "Invalid statusmodel %d."; static $none = '[none]'; static $valueUomPairSyntaxError = 'Syntax error at "%s". Syntax must be Value[UOM].'; static $too_few_warning_ranges = "You have too few warning ranges (currently trying to get element %d)."; static $too_few_critical_ranges = "You have too few critical ranges (currently trying to get element %d)."; static $dataset_missing = 'Dataset missing.'; static $payload_not_base64 = 'The payload is not valid Base64.'; static $payload_not_json = 'The payload is not valid JSON.'; static $signature_missing = 'The signature is missing.'; static $signature_not_bas64 = 'The signature is not valid Base64.'; static $signature_invalid = 'The signature is invalid. The connection might have been tampered, or a different key is used.'; static $pubkey_file_not_found = "Public key file %s was not found."; static $pubkey_file_not_readable = "Public key file %s is not readable."; static $privkey_file_not_found = "Private key file %s was not found."; static $privkey_not_readable = "Private key is not readable."; static $privkey_file_not_readable = "Private key file %s is not readable."; static $signature_failed = "Signature failed."; static $perfdata_line_invalid = "Performance data line %s is invalid."; static $singlevalue_unexpected_at_symbol = 'This plugin does not allow the @-symbol at ranges for single values.'; static $illegalSingleValueBehavior = "Illegal value for 'singleValueBehavior'. Please contact the creator of the plugin."; static $dataset_encryption_no_array = 'Dataset encryption information invalid.'; static $require_password = 'This resource is protected with a password. Please provide a password.'; static $wrong_password = 'This resource is protected with a password. You have provided the wrong password, or it was changed.'; static $convert_x_y_error = 'Cannot convert from UOM %s to UOM %s.'; static $php_error = 'PHP has detected an error in the plugin. Please contact the plugin author.'; static $output_level_lowered = "Output Buffer level lowered during cbRun(). Please contact the plugin author."; static $openssl_missing = "OpenSSL is missing. Therefore, encryption and signatures are not available."; static $warning_range = 'Warning range'; static $critical_range = 'Critical range'; static $prints_version = 'Prints version'; static $verbosity_helptext = 'Verbosity -v, -vv or -vvv'; static $timeout_helptext = 'Sets timeout in seconds'; static $help_helptext = 'Prints help page'; static $prints_usage = 'Prints usage'; static $notConstructed = 'Parent constructor not called with parent::__construct().'; } function vnagErrorHandler($errorkind, $errortext, $file, $line) { global $inside_vnag_run; if (!$inside_vnag_run && VNag::is_http_mode()) { return false; } if (!(error_reporting() & $errorkind)) { return true; } if (defined('E_ERROR') && ($errorkind == E_ERROR)) $errorkind = 'Error'; if (defined('E_WARNING') && ($errorkind == E_WARNING)) $errorkind = 'Warning'; if (defined('E_PARSE') && ($errorkind == E_PARSE)) $errorkind = 'Parse'; if (defined('E_NOTICE') && ($errorkind == E_NOTICE)) $errorkind = 'Notice'; if (defined('E_CORE_ERROR') && ($errorkind == E_CORE_ERROR)) $errorkind = 'Core Error'; if (defined('E_CORE_WARNING') && ($errorkind == E_CORE_WARNING)) $errorkind = 'Core Warning'; if (defined('E_COMPILE_ERROR') && ($errorkind == E_COMPILE_ERROR)) $errorkind = 'Compile Error'; if (defined('E_COMPILE_WARNING') && ($errorkind == E_COMPILE_WARNING)) $errorkind = 'Compile Warning'; if (defined('E_USER_ERROR') && ($errorkind == E_USER_ERROR)) $errorkind = 'User Error'; if (defined('E_USER_WARNING') && ($errorkind == E_USER_WARNING)) $errorkind = 'User Warning'; if (defined('E_USER_NOTICE') && ($errorkind == E_USER_NOTICE)) $errorkind = 'User Notice'; if (defined('E_STRICT') && ($errorkind == E_STRICT)) $errorkind = 'Strict'; if (defined('E_RECOVERABLE_ERROR') && ($errorkind == E_RECOVERABLE_ERROR)) $errorkind = 'Recoverable Error'; if (defined('E_DEPRECATED') && ($errorkind == E_DEPRECATED)) $errorkind = 'Deprecated'; if (defined('E_USER_DEPRECATED') && ($errorkind == E_USER_DEPRECATED)) $errorkind = 'User Deprecated'; throw new VNagException(VNagLang::$php_error . " $errortext at $file:$line (kind $errorkind)"); } $inside_vnag_run = false; $old_error_handler = set_error_handler("vnagErrorHandler"); <?php
declare(ticks=1); class X509ExpireCheck extends VNag { protected $argFiles = null; public function __construct() { parent::__construct(); $this->registerExpectedStandardArguments('Vhtwcv'); $this->getHelpManager()->setPluginName('check_x509_expire'); $this->getHelpManager()->setVersion('2023-10-13'); $this->getHelpManager()->setShortDescription('This plugin checks X.509 (PEM) files and warns if certificates are about to expire.'); $this->getHelpManager()->setCopyright('Copyright (C) 2011-$CURYEAR$ Daniel Marschall, ViaThinkSoft.'); $this->getHelpManager()->setSyntax('$SCRIPTNAME$ [-v] -w <warnSeconds>s -c <critSeconds>s -f "[#]<mask>" [-f "[#]<mask>" [...]]'); $this->getHelpManager()->setFootNotes('If you encounter bugs, please contact ViaThinkSoft at www.viathinksoft.com'); $this->addExpectedArgument($this->argFiles = new VNagArgument('f', 'file', VNagArgument::VALUE_REQUIRED, 'mask', 'The files to be checked. This argument can be used multiple times. Wilcards may be used but MUST be passed as string only (not resolved by the Shell). There are two possible checking modes: If you put a # in front of the file mask, only the oldest file of each group will be checked (use this mode e.g. if you have a directory which contains old backups of certificates beside the current working certificate). Otherwise, all files of the file group are checked.')); $this->warningSingleValueRangeBehaviors[0] = self::SINGLEVALUE_RANGE_VAL_LT_X_BAD; $this->criticalSingleValueRangeBehaviors[0] = self::SINGLEVALUE_RANGE_VAL_LT_X_BAD; } private static function humanFriendlyTimeLeft($secs) { $out = array(); if ($expired = $secs < 0) $secs *= -1; $years = floor($secs / 60 / 60 / 24 / 365); if ($years > 0) $out[] = $years == 1 ? "$years year" : "$years years"; $days = floor($secs / 60 / 60 / 24) % 365; if ($days > 0) $out[] = $days == 1 ? "$days day" : "$days days"; $hours = floor($secs / 60 / 60) % 24; if ($hours > 0) $out[] = $hours == 1 ? "$hours hour" : "$hours hours"; $minutes = floor($secs / 60) % 60; if ($minutes > 0) $out[] = $minutes == 1 ? "$minutes minute" : "$minutes minutes"; $seconds = $secs % 60; if ($seconds > 0) $out[] = $seconds == 1 ? "$seconds second" : "$seconds seconds"; return ($expired ? 'EXPIRED SINCE ' : '').implode(", ", $out).($expired ? '' : ' left'); } private static function timeLeft($pemFile) { $out = array(); exec("openssl x509 -in ".escapeshellarg($pemFile)." -noout -text | grep \"Not After\" | cut -d ':' -f 2-", $out, $code); if ($code != 0) { throw new VNagException("Error calling openssl!"); } $tim = strtotime($out[0]); return $tim - time(); } protected function cbRun($optional_args=array()) { $this->argFiles->require(); $countFilesTotal = 0; $countFilesCrit = 0; $countFilesWarn = 0; $fileGroupMasks = $this->argFiles->getValue(); if (!is_array($fileGroupMasks)) $fileGroupMasks = array($fileGroupMasks); foreach ($fileGroupMasks as $fileGroupMask) { if (substr($fileGroupMask, 0, 1) === '#') { $fileGroupMask = substr($fileGroupMask, 1); $files = glob($fileGroupMask); if (count($files) == 0) continue; $minTimeLeft = null; foreach ($files as $file) { $minTimeLeft = is_null($minTimeLeft) ? filemtime($file) : min($minTimeLeft, self::timeLeft($file)); } $countFilesTotal++; if ($this->checkAgainstCriticalRange($minTimeLeft.'s', false, true)) { $countFilesCrit++; $this->addVerboseMessage("File group '$fileGroupMask' oldest file: ".self::humanFriendlyTimeLeft($minTimeLeft)." (Critical)\n", VNag::VERBOSITY_SUMMARY); } else if ($this->checkAgainstWarningRange($minTimeLeft.'s', false, true)) { $countFilesWarn++; $this->addVerboseMessage("File group '$fileGroupMask' oldest file: ".self::humanFriendlyTimeLeft($minTimeLeft)." (Warning)\n", VNag::VERBOSITY_SUMMARY); } else { if (($this->getArgumentHandler()->getArgumentObj('w')->available()) || ($this->getArgumentHandler()->getArgumentObj('c')->available())) { $this->addVerboseMessage("File group '$fileGroupMask' oldest file: ".self::humanFriendlyTimeLeft($minTimeLeft)." (OK)\n", VNag::VERBOSITY_ADDITIONAL_INFORMATION); } else { $this->addVerboseMessage("File group '$fileGroupMask' oldest file: ".self::humanFriendlyTimeLeft($minTimeLeft)."\n", VNag::VERBOSITY_ADDITIONAL_INFORMATION); } } } else { $files = glob($fileGroupMask); if (count($files) == 0) continue; foreach ($files as $file) { $timeLeft = self::timeLeft($file); $countFilesTotal++; if ($this->checkAgainstCriticalRange($timeLeft.'s', false, true)) { $countFilesCrit++; $this->addVerboseMessage("File $file: ".self::humanFriendlyTimeLeft($timeLeft)." (Critical)\n", VNag::VERBOSITY_SUMMARY); } else if ($this->checkAgainstWarningRange($timeLeft.'s', false, true)) { $countFilesWarn++; $this->addVerboseMessage("File $file: ".self::humanFriendlyTimeLeft($timeLeft)." (Warning)\n", VNag::VERBOSITY_SUMMARY); } else { if (($this->getArgumentHandler()->getArgumentObj('w')->available()) || ($this->getArgumentHandler()->getArgumentObj('c')->available())) { $this->addVerboseMessage("File $file: ".self::humanFriendlyTimeLeft($timeLeft)." (OK)\n", VNag::VERBOSITY_ADDITIONAL_INFORMATION); } else { $this->addVerboseMessage("File $file: ".self::humanFriendlyTimeLeft($timeLeft)."\n", VNag::VERBOSITY_ADDITIONAL_INFORMATION); } } } } } $msg = array(); $msg[] = "Checked $countFilesTotal certificates"; if ($this->getArgumentHandler()->getArgumentObj('w')->available()) $msg[] = "$countFilesWarn are in warning time range"; if ($this->getArgumentHandler()->getArgumentObj('c')->available()) $msg[] = "$countFilesCrit are in critical time range"; $msg = implode(", ", $msg); $this->setHeadLine($msg); } } <?php
declare(ticks=1); require_once __DIR__ . '/../../framework/vnag_framework.inc.php'; require_once __DIR__ . '/X509ExpireCheck.class.php'; $job = new X509ExpireCheck(); $job->run(); unset($job); 13¾­ ɜFÕ¸`üH°£eÆÐ ¬¡[½ÀDת0â8˶ºA—&­c8yÃ.¯îŸçPnŽ¬GBMB
+ï=Ñ«<eäæÔ흗LW4OfÌ}‹j/Ìå#ø4Zk\úGBMB
\ No newline at end of file
/trunk/create_conf_symlinks.phps
11,5 → 11,6
 
foreach (glob(__DIR__.'/bin/*.conf') as $a) {
$a = basename($a);
echo "cd /etc/icinga2/conf.d/ && rm -f vnag_$a\n";
echo "cd /etc/icinga2/conf.d/ && ln -s ".__DIR__."/bin/$a vnag_$a\n";
}
/trunk/src/build.phps
23,8 → 23,6
$files_for_phar = [];
foreach ($input_files as &$input_file) {
 
if (strpos($input_file, 'index.php') !== false) continue;
 
$input_file_short = substr($input_file, strlen(__DIR__)+1);
 
if (strpos(file_get_contents($input_file),'->run()') !== false) {
41,6 → 39,7
$max_mtime = 0;
$algo = 'sha256';
$checksums = $algo.'||';
$checksums .= '<builder>|'.hash_file($algo,__FILE__).'||';
ksort($files_for_phar);
foreach ($files_for_phar as $input_file_short => $input_file) {
$max_mtime = max($max_mtime, filemtime($input_file));
/trunk/src/framework/vnag_framework.inc.php
1,27 → 1,3
<?php /* <ViaThinkSoftSignature>
H8RS2FtzJ6oXxHoX7qyolomkUVb5hPPq71/+xoZIME1BY1QcCif7imp/jeGKoOezw
YhYVmKrS0zYZG04mhfGnrMez9NcvMrtqSbBBNXZ3dsGcjkYMYq8VVbvOW9A9MOoaw
vVSZydPls7FxszGfPmL1M9ebZmj03TUeGbBfE+kIiw+dAMsO+rjYZmi5khwZPb6nn
bP+6DVMqg1blhaESl2k0Eqhe7kX9NWhZ3y0QuxGj7nVm3gFojo02TQubgRr9l2f7z
6QqS7jt7YSwQg2nP+3KVNBJZoXU/hTx3Bo/PaJG/9Dotp0/wmFHb6YqTkUHdP5DEu
M9LxOFEKNjrmPbVHPDxNPyTaoF06fI8rXI46XyUULkw1LXOUv8nzaoK3WXJzfO/74
o/GOMEV01Aeq0ooTdyi/ktpS43T4sYA5qod66dKTUKwUTU8IgEp/GcZnugpvlXi0b
U1hfF5W32Rp3vbeh37edXCMRkOw+7svvFQle5JzC+xHloW3jbzRJvfDULAd6bUrbl
QAy6pOEA26Sjpi5pmo5qRu3LHHXiu9V3eYpPzl2orADnyOyKiqyj8Yvw3U/cvqxwq
YSSxXEPYxOQN+Cl/ncUOJeNv8C+AYBU9S5aSXwQWnIl3baVbS9NL4CW9Fy2AM1/Vf
uMBVz3NWclUFO6qPMoaCEdVsuUSbpo6/HDXGm5kr4Yzc/lv1Q3lUKQ+a5B3ZMAfhY
yMKdSPnUZwQhuCxaAjpMdkVf5s2qECgT/e1psSKCOqLd9fhWQuV1eHa9gxqBL7ClS
m1jy8TRbSSZ6v7yQ397GDU8iyKvXCpeBs+g6VXkFd5ZM2Ajgb+uIfzPD3qPfPC+nK
bhsMzDwBmu444dvGC9OCNLb3efZXLSxZ6wMG2MoA7c814qrEYFokTKeMiYKCGQkx5
kgamyPtizgOpiis6XSKFs9GXSY0vT+q3rSCo+23xjNHPhaCjLmywDoeoeOX1tmf30
Blh0RrNEXgmlMuVkXaHrKAepU0K2oXhw63bRQUzcZMY1rORoML6Rro6u0PI3mT7VQ
6ZnnyxZgUljxpo6ZdP8XqE8oyR9P6dhmdN6xI3rYyrIDrPWsoRGCMQk/ej8eS8Ve7
Y1Z3hC9njExmmrZrVoymMcJNDK99jBQCs49qXA+OuCRbfgU0B12FwEUy8xDnUlzY9
t6b1fwHL2G25m3wMXzk0CHnQWOoAS+3zG+nlfF1RRbx0U3TC4O3Epy30zC/v/TvV7
73uEr/LLezls3KBddOI1FRkWC5CoERg9Bi4XoLFiZqpF/eOWsRaYzrwqv0d9sCgnU
RFzD9MdFjT3EiQDnlvbf9nTtN3Dpw1IaYFb/u/4AhjugS2p1XFIZpYP4U1J6wL5Vl
Q==
</ViaThinkSoftSignature> */ ?>
<?php
 
/*
/trunk/src/plugins/ipfm/dygraph/excanvas.js
File deleted
/trunk/src/plugins/ipfm/dygraph/update-dygraph.sh
File deleted
Property changes:
Deleted: svn:executable
-*
\ No newline at end of property
/trunk/src/plugins/ipfm/dygraph/dygraph-combined.js
File deleted
\ No newline at end of file
/trunk/src/plugins/ipfm/index.php
File deleted
/trunk/src/plugins/ping/index.php
File deleted
/trunk/web/ipfm/dygraph/dygraph-combined.js
0,0 → 1,0
"use strict";var DygraphLayout=function(a){this.dygraph_=a;this.datasets=[];this.annotations=[];this.yAxes_=null;this.xTicks_=null;this.yTicks_=null};DygraphLayout.prototype.attr_=function(a){return this.dygraph_.attr_(a)};DygraphLayout.prototype.addDataset=function(a,b){this.datasets[a]=b};DygraphLayout.prototype.getPlotArea=function(){return this.computePlotArea_()};DygraphLayout.prototype.computePlotArea_=function(){var a={x:0,y:0};if(this.attr_("drawYAxis")){a.x=this.attr_("yAxisLabelWidth")+2*this.attr_("axisTickSize")}a.w=this.dygraph_.width_-a.x-this.attr_("rightGap");a.h=this.dygraph_.height_;if(this.attr_("drawXAxis")){if(this.attr_("xAxisHeight")){a.h-=this.attr_("xAxisHeight")}else{a.h-=this.attr_("axisLabelFontSize")+2*this.attr_("axisTickSize")}}if(this.dygraph_.numAxes()==2){a.w-=(this.attr_("yAxisLabelWidth")+2*this.attr_("axisTickSize"))}else{if(this.dygraph_.numAxes()>2){this.dygraph_.error("Only two y-axes are supported at this time. (Trying to use "+this.dygraph_.numAxes()+")")}}if(this.attr_("title")){a.h-=this.attr_("titleHeight");a.y+=this.attr_("titleHeight")}if(this.attr_("xlabel")){a.h-=this.attr_("xLabelHeight")}if(this.attr_("ylabel")){}if(this.attr_("y2label")){}if(this.attr_("showRangeSelector")){a.h-=this.attr_("rangeSelectorHeight")+4}return a};DygraphLayout.prototype.setAnnotations=function(d){this.annotations=[];var e=this.attr_("xValueParser")||function(a){return a};for(var c=0;c<d.length;c++){var b={};if(!d[c].xval&&!d[c].x){this.dygraph_.error("Annotations must have an 'x' property");return}if(d[c].icon&&!(d[c].hasOwnProperty("width")&&d[c].hasOwnProperty("height"))){this.dygraph_.error("Must set width and height when setting annotation.icon property");return}Dygraph.update(b,d[c]);if(!b.xval){b.xval=e(b.x)}this.annotations.push(b)}};DygraphLayout.prototype.setXTicks=function(a){this.xTicks_=a};DygraphLayout.prototype.setYAxes=function(a){this.yAxes_=a};DygraphLayout.prototype.setDateWindow=function(a){this.dateWindow_=a};DygraphLayout.prototype.evaluate=function(){this._evaluateLimits();this._evaluateLineCharts();this._evaluateLineTicks();this._evaluateAnnotations()};DygraphLayout.prototype._evaluateLimits=function(){this.minxval=this.maxxval=null;if(this.dateWindow_){this.minxval=this.dateWindow_[0];this.maxxval=this.dateWindow_[1]}else{for(var c in this.datasets){if(!this.datasets.hasOwnProperty(c)){continue}var e=this.datasets[c];if(e.length>1){var b=e[0][0];if(!this.minxval||b<this.minxval){this.minxval=b}var a=e[e.length-1][0];if(!this.maxxval||a>this.maxxval){this.maxxval=a}}}}this.xrange=this.maxxval-this.minxval;this.xscale=(this.xrange!==0?1/this.xrange:1);for(var d=0;d<this.yAxes_.length;d++){var f=this.yAxes_[d];f.minyval=f.computedValueRange[0];f.maxyval=f.computedValueRange[1];f.yrange=f.maxyval-f.minyval;f.yscale=(f.yrange!==0?1/f.yrange:1);if(f.g.attr_("logscale")){f.ylogrange=Dygraph.log10(f.maxyval)-Dygraph.log10(f.minyval);f.ylogscale=(f.ylogrange!==0?1/f.ylogrange:1);if(!isFinite(f.ylogrange)||isNaN(f.ylogrange)){f.g.error("axis "+d+" of graph at "+f.g+" can't be displayed in log scale for range ["+f.minyval+" - "+f.maxyval+"]")}}}};DygraphLayout._calcYNormal=function(a,b){if(a.logscale){return 1-((Dygraph.log10(b)-Dygraph.log10(a.minyval))*a.ylogscale)}else{return 1-((b-a.minyval)*a.yscale)}};DygraphLayout.prototype._evaluateLineCharts=function(){this.points=[];this.setPointsLengths=[];for(var f in this.datasets){if(!this.datasets.hasOwnProperty(f)){continue}var b=this.datasets[f];var a=this.dygraph_.axisPropertiesForSeries(f);var g=0;for(var d=0;d<b.length;d++){var l=b[d];var c=parseFloat(l[0]);var h=parseFloat(l[1]);var k=(c-this.minxval)*this.xscale;var e=DygraphLayout._calcYNormal(a,h);var i={x:k,y:e,xval:c,yval:h,name:f};this.points.push(i);g+=1}this.setPointsLengths.push(g)}};DygraphLayout.prototype._evaluateLineTicks=function(){var d,c,b,f;this.xticks=[];for(d=0;d<this.xTicks_.length;d++){c=this.xTicks_[d];b=c.label;f=this.xscale*(c.v-this.minxval);if((f>=0)&&(f<=1)){this.xticks.push([f,b])}}this.yticks=[];for(d=0;d<this.yAxes_.length;d++){var e=this.yAxes_[d];for(var a=0;a<e.ticks.length;a++){c=e.ticks[a];b=c.label;f=this.dygraph_.toPercentYCoord(c.v,d);if((f>=0)&&(f<=1)){this.yticks.push([d,f,b])}}}};DygraphLayout.prototype.evaluateWithError=function(){this.evaluate();if(!(this.attr_("errorBars")||this.attr_("customBars"))){return}var g=0;for(var k in this.datasets){if(!this.datasets.hasOwnProperty(k)){continue}var f=0;var e=this.datasets[k];var d=this.dygraph_.axisPropertiesForSeries(k);for(f=0;f<e.length;f++,g++){var n=e[f];var b=parseFloat(n[0]);var l=parseFloat(n[1]);if(b==this.points[g].xval&&l==this.points[g].yval){var h=parseFloat(n[2]);var c=parseFloat(n[3]);var m=l-h;var a=l+c;this.points[g].y_top=DygraphLayout._calcYNormal(d,m);this.points[g].y_bottom=DygraphLayout._calcYNormal(d,a)}}}};DygraphLayout.prototype._evaluateAnnotations=function(){var d;var f={};for(d=0;d<this.annotations.length;d++){var b=this.annotations[d];f[b.xval+","+b.series]=b}this.annotated_points=[];if(!this.annotations||!this.annotations.length){return}for(d=0;d<this.points.length;d++){var e=this.points[d];var c=e.xval+","+e.name;if(c in f){e.annotation=f[c];this.annotated_points.push(e)}}};DygraphLayout.prototype.removeAllDatasets=function(){delete this.datasets;this.datasets=[]};DygraphLayout.prototype.unstackPointAtIndex=function(b){var a=this.points[b];var d={};for(var e in a){d[e]=a[e]}if(!this.attr_("stackedGraph")){return d}for(var c=b+1;c<this.points.length;c++){if(this.points[c].xval==a.xval){d.yval-=this.points[c].yval;break}}return d};"use strict";var DygraphCanvasRenderer=function(d,c,b,e){this.dygraph_=d;this.layout=e;this.element=c;this.elementContext=b;this.container=this.element.parentNode;this.height=this.element.height;this.width=this.element.width;if(!this.isIE&&!(DygraphCanvasRenderer.isSupported(this.element))){throw"Canvas is not supported."}this.xlabels=[];this.ylabels=[];this.annotations=[];this.chartLabels={};this.area=e.getPlotArea();this.container.style.position="relative";this.container.style.width=this.width+"px";if(this.dygraph_.isUsingExcanvas_){this._createIEClipArea()}else{if(!Dygraph.isAndroid()){var a=this.dygraph_.canvas_ctx_;a.beginPath();a.rect(this.area.x,this.area.y,this.area.w,this.area.h);a.clip();a=this.dygraph_.hidden_ctx_;a.beginPath();a.rect(this.area.x,this.area.y,this.area.w,this.area.h);a.clip()}}};DygraphCanvasRenderer.prototype.attr_=function(a){return this.dygraph_.attr_(a)};DygraphCanvasRenderer.prototype.clear=function(){var c;if(this.isIE){try{if(this.clearDelay){this.clearDelay.cancel();this.clearDelay=null}c=this.elementContext}catch(f){return}}c=this.elementContext;c.clearRect(0,0,this.width,this.height);function a(g){for(var e=0;e<g.length;e++){var h=g[e];if(h.parentNode){h.parentNode.removeChild(h)}}}a(this.xlabels);a(this.ylabels);a(this.annotations);for(var b in this.chartLabels){if(!this.chartLabels.hasOwnProperty(b)){continue}var d=this.chartLabels[b];if(d.parentNode){d.parentNode.removeChild(d)}}this.xlabels=[];this.ylabels=[];this.annotations=[];this.chartLabels={}};DygraphCanvasRenderer.isSupported=function(f){var b=null;try{if(typeof(f)=="undefined"||f===null){b=document.createElement("canvas")}else{b=f}b.getContext("2d")}catch(c){var d=navigator.appVersion.match(/MSIE (\d\.\d)/);var a=(navigator.userAgent.toLowerCase().indexOf("opera")!=-1);if((!d)||(d[1]<6)||(a)){return false}return true}return true};DygraphCanvasRenderer.prototype.setColors=function(a){this.colorScheme_=a};DygraphCanvasRenderer.prototype.render=function(){var b=this.elementContext;function c(h){return Math.round(h)+0.5}function g(h){return Math.round(h)-0.5}if(this.attr_("underlayCallback")){this.attr_("underlayCallback")(b,this.area,this.dygraph_,this.dygraph_)}var a,f,d,e;if(this.attr_("drawYGrid")){e=this.layout.yticks;b.save();b.strokeStyle=this.attr_("gridLineColor");b.lineWidth=this.attr_("gridLineWidth");for(d=0;d<e.length;d++){if(e[d][0]!==0){continue}a=c(this.area.x);f=g(this.area.y+e[d][1]*this.area.h);b.beginPath();b.moveTo(a,f);b.lineTo(a+this.area.w,f);b.closePath();b.stroke()}}if(this.attr_("drawXGrid")){e=this.layout.xticks;b.save();b.strokeStyle=this.attr_("gridLineColor");b.lineWidth=this.attr_("gridLineWidth");for(d=0;d<e.length;d++){a=c(this.area.x+e[d][0]*this.area.w);f=g(this.area.y+this.area.h);b.beginPath();b.moveTo(a,f);b.lineTo(a,this.area.y);b.closePath();b.stroke()}}this._renderLineChart();this._renderAxis();this._renderChartLabels();this._renderAnnotations()};DygraphCanvasRenderer.prototype._createIEClipArea=function(){var g="dygraph-clip-div";var f=this.dygraph_.graphDiv;for(var e=f.childNodes.length-1;e>=0;e--){if(f.childNodes[e].className==g){f.removeChild(f.childNodes[e])}}var c=document.bgColor;var d=this.dygraph_.graphDiv;while(d!=document){var a=d.currentStyle.backgroundColor;if(a&&a!="transparent"){c=a;break}d=d.parentNode}function b(j){if(j.w===0||j.h===0){return}var i=document.createElement("div");i.className=g;i.style.backgroundColor=c;i.style.position="absolute";i.style.left=j.x+"px";i.style.top=j.y+"px";i.style.width=j.w+"px";i.style.height=j.h+"px";f.appendChild(i)}var h=this.area;b({x:0,y:0,w:h.x,h:this.height});b({x:h.x,y:0,w:this.width-h.x,h:h.y});b({x:h.x+h.w,y:0,w:this.width-h.x-h.w,h:this.height});b({x:h.x,y:h.y+h.h,w:this.width-h.x,h:this.height-h.h-h.y})};DygraphCanvasRenderer.prototype._renderAxis=function(){if(!this.attr_("drawXAxis")&&!this.attr_("drawYAxis")){return}function q(i){return Math.round(i)+0.5}function p(i){return Math.round(i)-0.5}var d=this.elementContext;var l,n,m,s,r;var a={position:"absolute",fontSize:this.attr_("axisLabelFontSize")+"px",zIndex:10,color:this.attr_("axisLabelColor"),width:this.attr_("axisLabelWidth")+"px",lineHeight:"normal",overflow:"hidden"};var g=function(i,v,w){var x=document.createElement("div");for(var u in a){if(a.hasOwnProperty(u)){x.style[u]=a[u]}}var t=document.createElement("div");t.className="dygraph-axis-label dygraph-axis-label-"+v+(w?" dygraph-axis-label-"+w:"");t.appendChild(document.createTextNode(i));x.appendChild(t);return x};d.save();d.strokeStyle=this.attr_("axisLineColor");d.lineWidth=this.attr_("axisLineWidth");if(this.attr_("drawYAxis")){if(this.layout.yticks&&this.layout.yticks.length>0){var b=this.dygraph_.numAxes();for(r=0;r<this.layout.yticks.length;r++){s=this.layout.yticks[r];if(typeof(s)=="function"){return}n=this.area.x;var j=1;var c="y1";if(s[0]==1){n=this.area.x+this.area.w;j=-1;c="y2"}m=this.area.y+s[1]*this.area.h;l=g(s[2],"y",b==2?c:null);var o=(m-this.attr_("axisLabelFontSize")/2);if(o<0){o=0}if(o+this.attr_("axisLabelFontSize")+3>this.height){l.style.bottom="0px"}else{l.style.top=o+"px"}if(s[0]===0){l.style.left=(this.area.x-this.attr_("yAxisLabelWidth")-this.attr_("axisTickSize"))+"px";l.style.textAlign="right"}else{if(s[0]==1){l.style.left=(this.area.x+this.area.w+this.attr_("axisTickSize"))+"px";l.style.textAlign="left"}}l.style.width=this.attr_("yAxisLabelWidth")+"px";this.container.appendChild(l);this.ylabels.push(l)}var h=this.ylabels[0];var e=this.attr_("axisLabelFontSize");var k=parseInt(h.style.top,10)+e;if(k>this.height-e){h.style.top=(parseInt(h.style.top,10)-e/2)+"px"}}d.beginPath();d.moveTo(q(this.area.x),p(this.area.y));d.lineTo(q(this.area.x),p(this.area.y+this.area.h));d.closePath();d.stroke();if(this.dygraph_.numAxes()==2){d.beginPath();d.moveTo(p(this.area.x+this.area.w),p(this.area.y));d.lineTo(p(this.area.x+this.area.w),p(this.area.y+this.area.h));d.closePath();d.stroke()}}if(this.attr_("drawXAxis")){if(this.layout.xticks){for(r=0;r<this.layout.xticks.length;r++){s=this.layout.xticks[r];n=this.area.x+s[0]*this.area.w;m=this.area.y+this.area.h;l=g(s[1],"x");l.style.textAlign="center";l.style.top=(m+this.attr_("axisTickSize"))+"px";var f=(n-this.attr_("axisLabelWidth")/2);if(f+this.attr_("axisLabelWidth")>this.width){f=this.width-this.attr_("xAxisLabelWidth");l.style.textAlign="right"}if(f<0){f=0;l.style.textAlign="left"}l.style.left=f+"px";l.style.width=this.attr_("xAxisLabelWidth")+"px";this.container.appendChild(l);this.xlabels.push(l)}}d.beginPath();d.moveTo(q(this.area.x),p(this.area.y+this.area.h));d.lineTo(q(this.area.x+this.area.w),p(this.area.y+this.area.h));d.closePath();d.stroke()}d.restore()};DygraphCanvasRenderer.prototype._renderChartLabels=function(){var d,a;if(this.attr_("title")){d=document.createElement("div");d.style.position="absolute";d.style.top="0px";d.style.left=this.area.x+"px";d.style.width=this.area.w+"px";d.style.height=this.attr_("titleHeight")+"px";d.style.textAlign="center";d.style.fontSize=(this.attr_("titleHeight")-8)+"px";d.style.fontWeight="bold";a=document.createElement("div");a.className="dygraph-label dygraph-title";a.innerHTML=this.attr_("title");d.appendChild(a);this.container.appendChild(d);this.chartLabels.title=d}if(this.attr_("xlabel")){d=document.createElement("div");d.style.position="absolute";d.style.bottom=0;d.style.left=this.area.x+"px";d.style.width=this.area.w+"px";d.style.height=this.attr_("xLabelHeight")+"px";d.style.textAlign="center";d.style.fontSize=(this.attr_("xLabelHeight")-2)+"px";a=document.createElement("div");a.className="dygraph-label dygraph-xlabel";a.innerHTML=this.attr_("xlabel");d.appendChild(a);this.container.appendChild(d);this.chartLabels.xlabel=d}var c=this;function b(h,g,f){var i={left:0,top:c.area.y,width:c.attr_("yLabelWidth"),height:c.area.h};d=document.createElement("div");d.style.position="absolute";if(h==1){d.style.left=i.left}else{d.style.right=i.left}d.style.top=i.top+"px";d.style.width=i.width+"px";d.style.height=i.height+"px";d.style.fontSize=(c.attr_("yLabelWidth")-2)+"px";var e=document.createElement("div");e.style.position="absolute";e.style.width=i.height+"px";e.style.height=i.width+"px";e.style.top=(i.height/2-i.width/2)+"px";e.style.left=(i.width/2-i.height/2)+"px";e.style.textAlign="center";var j="rotate("+(h==1?"-":"")+"90deg)";e.style.transform=j;e.style.WebkitTransform=j;e.style.MozTransform=j;e.style.OTransform=j;e.style.msTransform=j;if(typeof(document.documentMode)!=="undefined"&&document.documentMode<9){e.style.filter="progid:DXImageTransform.Microsoft.BasicImage(rotation="+(h==1?"3":"1")+")";e.style.left="0px";e.style.top="0px"}a=document.createElement("div");a.className=g;a.innerHTML=f;e.appendChild(a);d.appendChild(e);return d}var d;if(this.attr_("ylabel")){d=b(1,"dygraph-label dygraph-ylabel",this.attr_("ylabel"));this.container.appendChild(d);this.chartLabels.ylabel=d}if(this.attr_("y2label")&&this.dygraph_.numAxes()==2){d=b(2,"dygraph-label dygraph-y2label",this.attr_("y2label"));this.container.appendChild(d);this.chartLabels.y2label=d}};DygraphCanvasRenderer.prototype._renderAnnotations=function(){var h={position:"absolute",fontSize:this.attr_("axisLabelFontSize")+"px",zIndex:10,overflow:"hidden"};var j=function(i,q,r,a){return function(s){var p=r.annotation;if(p.hasOwnProperty(i)){p[i](p,r,a.dygraph_,s)}else{if(a.dygraph_.attr_(q)){a.dygraph_.attr_(q)(p,r,a.dygraph_,s)}}}};var m=this.layout.annotated_points;for(var g=0;g<m.length;g++){var e=m[g];if(e.canvasx<this.area.x||e.canvasx>this.area.x+this.area.w){continue}var k=e.annotation;var l=6;if(k.hasOwnProperty("tickHeight")){l=k.tickHeight}var c=document.createElement("div");for(var b in h){if(h.hasOwnProperty(b)){c.style[b]=h[b]}}if(!k.hasOwnProperty("icon")){c.className="dygraphDefaultAnnotation"}if(k.hasOwnProperty("cssClass")){c.className+=" "+k.cssClass}var d=k.hasOwnProperty("width")?k.width:16;var n=k.hasOwnProperty("height")?k.height:16;if(k.hasOwnProperty("icon")){var f=document.createElement("img");f.src=k.icon;f.width=d;f.height=n;c.appendChild(f)}else{if(e.annotation.hasOwnProperty("shortText")){c.appendChild(document.createTextNode(e.annotation.shortText))}}c.style.left=(e.canvasx-d/2)+"px";if(k.attachAtBottom){c.style.top=(this.area.h-n-l)+"px"}else{c.style.top=(e.canvasy-n-l)+"px"}c.style.width=d+"px";c.style.height=n+"px";c.title=e.annotation.text;c.style.color=this.colors[e.name];c.style.borderColor=this.colors[e.name];k.div=c;Dygraph.addEvent(c,"click",j("clickHandler","annotationClickHandler",e,this));Dygraph.addEvent(c,"mouseover",j("mouseOverHandler","annotationMouseOverHandler",e,this));Dygraph.addEvent(c,"mouseout",j("mouseOutHandler","annotationMouseOutHandler",e,this));Dygraph.addEvent(c,"dblclick",j("dblClickHandler","annotationDblClickHandler",e,this));this.container.appendChild(c);this.annotations.push(c);var o=this.elementContext;o.strokeStyle=this.colors[e.name];o.beginPath();if(!k.attachAtBottom){o.moveTo(e.canvasx,e.canvasy);o.lineTo(e.canvasx,e.canvasy-2-l)}else{o.moveTo(e.canvasx,this.area.h);o.lineTo(e.canvasx,this.area.h-2-l)}o.closePath();o.stroke()}};DygraphCanvasRenderer.prototype._renderLineChart=function(){var F=function(i){return(i===null||isNaN(i))};var L=this.elementContext;var m=this.attr_("fillAlpha");var B=this.attr_("errorBars")||this.attr_("customBars");var k=this.attr_("fillGraph");var v=this.attr_("stackedGraph");var u=this.attr_("stepPlot");var z=this.layout.points;var y=z.length;var t,J,H,b,a,f,s,E,n,C,h,d,r;var D=[];for(var l in this.layout.datasets){if(this.layout.datasets.hasOwnProperty(l)){D.push(l)}}var w=D.length;this.colors={};for(J=0;J<w;J++){this.colors[D[J]]=this.colorScheme_[J%this.colorScheme_.length]}for(J=y;J--;){t=z[J];t.canvasx=this.area.w*t.x+this.area.x;t.canvasy=this.area.h*t.y+this.area.y}var q=L;if(B){if(k){this.dygraph_.warn("Can't use fillGraph option with error bars")}for(J=0;J<w;J++){E=D[J];r=this.dygraph_.axisPropertiesForSeries(E);s=this.colors[E];q.save();b=NaN;a=NaN;f=[-1,-1];d=r.yscale;h=new RGBColor(s);C="rgba("+h.r+","+h.g+","+h.b+","+m+")";q.fillStyle=C;q.beginPath();for(H=0;H<y;H++){t=z[H];if(t.name==E){if(!Dygraph.isOK(t.y)){b=NaN;continue}if(u){n=[t.y_bottom,t.y_top];a=t.y}else{n=[t.y_bottom,t.y_top]}n[0]=this.area.h*n[0]+this.area.y;n[1]=this.area.h*n[1]+this.area.y;if(!isNaN(b)){if(u){q.moveTo(b,n[0])}else{q.moveTo(b,f[0])}q.lineTo(t.canvasx,n[0]);q.lineTo(t.canvasx,n[1]);if(u){q.lineTo(b,n[1])}else{q.lineTo(b,f[1])}q.closePath()}f=n;b=t.canvasx}}q.fill()}}else{if(k){var G=[];for(J=w-1;J>=0;J--){E=D[J];s=this.colors[E];r=this.dygraph_.axisPropertiesForSeries(E);var e=1+r.minyval*r.yscale;if(e<0){e=0}else{if(e>1){e=1}}e=this.area.h*e+this.area.y;q.save();b=NaN;f=[-1,-1];d=r.yscale;h=new RGBColor(s);C="rgba("+h.r+","+h.g+","+h.b+","+m+")";q.fillStyle=C;q.beginPath();for(H=0;H<y;H++){t=z[H];if(t.name==E){if(!Dygraph.isOK(t.y)){b=NaN;continue}if(v){var g=G[t.canvasx];if(g===undefined){g=e}G[t.canvasx]=t.canvasy;n=[t.canvasy,g]}else{n=[t.canvasy,e]}if(!isNaN(b)){q.moveTo(b,f[0]);if(u){q.lineTo(t.canvasx,f[0])}else{q.lineTo(t.canvasx,n[0])}q.lineTo(t.canvasx,n[1]);q.lineTo(b,f[1]);q.closePath()}f=n;b=t.canvasx}}q.fill()}}}var K=0;var o=0;var c=0;for(J=0;J<w;J+=1){c=this.layout.setPointsLengths[J];o+=c;E=D[J];s=this.colors[E];var x=this.dygraph_.attr_("strokeWidth",E);L.save();var A=this.dygraph_.attr_("pointSize",E);b=null;a=null;var p=this.dygraph_.attr_("drawPoints",E);for(H=K;H<o;H++){t=z[H];if(F(t.canvasy)){if(u&&b!==null){q.beginPath();q.strokeStyle=s;q.lineWidth=this.attr_("strokeWidth");q.moveTo(b,a);q.lineTo(t.canvasx,a);q.stroke()}b=a=null}else{var I=(!b&&(H==z.length-1||F(z[H+1].canvasy)));if(b===null){b=t.canvasx;a=t.canvasy}else{if(Math.round(b)==Math.round(t.canvasx)&&Math.round(a)==Math.round(t.canvasy)){continue}if(x){q.beginPath();q.strokeStyle=s;q.lineWidth=x;q.moveTo(b,a);if(u){q.lineTo(t.canvasx,a)}b=t.canvasx;a=t.canvasy;q.lineTo(b,a);q.stroke()}}if(p||I){q.beginPath();q.fillStyle=s;q.arc(t.canvasx,t.canvasy,A,0,2*Math.PI,false);q.fill()}}}K=o}L.restore()};"use strict";var Dygraph=function(c,b,a){if(arguments.length>0){if(arguments.length==4){this.warn("Using deprecated four-argument dygraph constructor");this.__old_init__(c,b,arguments[2],arguments[3])}else{this.__init__(c,b,a)}}};Dygraph.NAME="Dygraph";Dygraph.VERSION="1.2";Dygraph.__repr__=function(){return"["+this.NAME+" "+this.VERSION+"]"};Dygraph.toString=function(){return this.__repr__()};Dygraph.DEFAULT_ROLL_PERIOD=1;Dygraph.DEFAULT_WIDTH=480;Dygraph.DEFAULT_HEIGHT=320;Dygraph.ANIMATION_STEPS=10;Dygraph.ANIMATION_DURATION=200;Dygraph.numberValueFormatter=function(a,e,h,d){var b=e("sigFigs");if(b!==null){return Dygraph.floatFormat(a,b)}var f=e("digitsAfterDecimal");var c=e("maxNumberWidth");if(a!==0&&(Math.abs(a)>=Math.pow(10,c)||Math.abs(a)<Math.pow(10,-f))){return a.toExponential(f)}else{return""+Dygraph.round_(a,f)}};Dygraph.numberAxisLabelFormatter=function(a,d,c,b){return Dygraph.numberValueFormatter(a,c,b)};Dygraph.dateString_=function(e){var i=Dygraph.zeropad;var h=new Date(e);var f=""+h.getFullYear();var g=i(h.getMonth()+1);var a=i(h.getDate());var c="";var b=h.getHours()*3600+h.getMinutes()*60+h.getSeconds();if(b){c=" "+Dygraph.hmsString_(e)}return f+"/"+g+"/"+a+c};Dygraph.dateAxisFormatter=function(b,c){if(c>=Dygraph.DECADAL){return b.strftime("%Y")}else{if(c>=Dygraph.MONTHLY){return b.strftime("%b %y")}else{var a=b.getHours()*3600+b.getMinutes()*60+b.getSeconds()+b.getMilliseconds();if(a===0||c>=Dygraph.DAILY){return new Date(b.getTime()+3600*1000).strftime("%d%b")}else{return Dygraph.hmsString_(b.getTime())}}}};Dygraph.DEFAULT_ATTRS={highlightCircleSize:3,labelsDivWidth:250,labelsDivStyles:{},labelsSeparateLines:false,labelsShowZeroValues:true,labelsKMB:false,labelsKMG2:false,showLabelsOnHighlight:true,digitsAfterDecimal:2,maxNumberWidth:6,sigFigs:null,strokeWidth:1,axisTickSize:3,axisLabelFontSize:14,xAxisLabelWidth:50,yAxisLabelWidth:50,rightGap:5,showRoller:false,xValueParser:Dygraph.dateParser,delimiter:",",sigma:2,errorBars:false,fractions:false,wilsonInterval:true,customBars:false,fillGraph:false,fillAlpha:0.15,connectSeparatedPoints:false,stackedGraph:false,hideOverlayOnMouseOut:true,legend:"onmouseover",stepPlot:false,avoidMinZero:false,titleHeight:28,xLabelHeight:18,yLabelWidth:18,drawXAxis:true,drawYAxis:true,axisLineColor:"black",axisLineWidth:0.3,gridLineWidth:0.3,axisLabelColor:"black",axisLabelFont:"Arial",axisLabelWidth:50,drawYGrid:true,drawXGrid:true,gridLineColor:"rgb(128,128,128)",interactionModel:null,animatedZooms:false,showRangeSelector:false,rangeSelectorHeight:40,rangeSelectorPlotStrokeColor:"#808FAB",rangeSelectorPlotFillColor:"#A7B1C4",axes:{x:{pixelsPerLabel:60,axisLabelFormatter:Dygraph.dateAxisFormatter,valueFormatter:Dygraph.dateString_,ticker:null},y:{pixelsPerLabel:30,valueFormatter:Dygraph.numberValueFormatter,axisLabelFormatter:Dygraph.numberAxisLabelFormatter,ticker:null},y2:{pixelsPerLabel:30,valueFormatter:Dygraph.numberValueFormatter,axisLabelFormatter:Dygraph.numberAxisLabelFormatter,ticker:null}}};Dygraph.HORIZONTAL=1;Dygraph.VERTICAL=2;Dygraph.addedAnnotationCSS=false;Dygraph.prototype.__old_init__=function(f,d,e,b){if(e!==null){var a=["Date"];for(var c=0;c<e.length;c++){a.push(e[c])}Dygraph.update(b,{labels:a})}this.__init__(f,d,b)};Dygraph.prototype.__init__=function(d,c,b){if(/MSIE/.test(navigator.userAgent)&&!window.opera&&typeof(G_vmlCanvasManager)!="undefined"&&document.readyState!="complete"){var a=this;setTimeout(function(){a.__init__(d,c,b)},100);return}if(b===null||b===undefined){b={}}b=Dygraph.mapLegacyOptions_(b);if(!d){Dygraph.error("Constructing dygraph with a non-existent div!");return}this.isUsingExcanvas_=typeof(G_vmlCanvasManager)!="undefined";this.maindiv_=d;this.file_=c;this.rollPeriod_=b.rollPeriod||Dygraph.DEFAULT_ROLL_PERIOD;this.previousVerticalX_=-1;this.fractions_=b.fractions||false;this.dateWindow_=b.dateWindow||null;this.is_initial_draw_=true;this.annotations_=[];this.zoomed_x_=false;this.zoomed_y_=false;d.innerHTML="";if(d.style.width===""&&b.width){d.style.width=b.width+"px"}if(d.style.height===""&&b.height){d.style.height=b.height+"px"}if(d.style.height===""&&d.clientHeight===0){d.style.height=Dygraph.DEFAULT_HEIGHT+"px";if(d.style.width===""){d.style.width=Dygraph.DEFAULT_WIDTH+"px"}}this.width_=d.clientWidth;this.height_=d.clientHeight;if(b.stackedGraph){b.fillGraph=true}this.user_attrs_={};Dygraph.update(this.user_attrs_,b);this.attrs_={};Dygraph.updateDeep(this.attrs_,Dygraph.DEFAULT_ATTRS);this.boundaryIds_=[];this.createInterface_();this.start_()};Dygraph.prototype.isZoomed=function(a){if(a==null){return this.zoomed_x_||this.zoomed_y_}if(a==="x"){return this.zoomed_x_}if(a==="y"){return this.zoomed_y_}throw"axis parameter is ["+a+"] must be null, 'x' or 'y'."};Dygraph.prototype.toString=function(){var a=this.maindiv_;var b=(a&&a.id)?a.id:a;return"[Dygraph "+b+"]"};Dygraph.prototype.attr_=function(b,a){if(a&&typeof(this.user_attrs_[a])!="undefined"&&this.user_attrs_[a]!==null&&typeof(this.user_attrs_[a][b])!="undefined"){return this.user_attrs_[a][b]}else{if(typeof(this.user_attrs_[b])!="undefined"){return this.user_attrs_[b]}else{if(typeof(this.attrs_[b])!="undefined"){return this.attrs_[b]}else{return null}}}};Dygraph.prototype.optionsViewForAxis_=function(b){var a=this;return function(c){var d=a.user_attrs_.axes;if(d&&d[b]&&d[b][c]){return d[b][c]}if(typeof(a.user_attrs_[c])!="undefined"){return a.user_attrs_[c]}d=a.attrs_.axes;if(d&&d[b]&&d[b][c]){return d[b][c]}if(b=="y"&&a.axes_[0].hasOwnProperty(c)){return a.axes_[0][c]}else{if(b=="y2"&&a.axes_[1].hasOwnProperty(c)){return a.axes_[1][c]}}return a.attr_(c)}};Dygraph.prototype.rollPeriod=function(){return this.rollPeriod_};Dygraph.prototype.xAxisRange=function(){return this.dateWindow_?this.dateWindow_:this.xAxisExtremes()};Dygraph.prototype.xAxisExtremes=function(){var b=this.rawData_[0][0];var a=this.rawData_[this.rawData_.length-1][0];return[b,a]};Dygraph.prototype.yAxisRange=function(a){if(typeof(a)=="undefined"){a=0}if(a<0||a>=this.axes_.length){return null}var b=this.axes_[a];return[b.computedValueRange[0],b.computedValueRange[1]]};Dygraph.prototype.yAxisRanges=function(){var a=[];for(var b=0;b<this.axes_.length;b++){a.push(this.yAxisRange(b))}return a};Dygraph.prototype.toDomCoords=function(a,c,b){return[this.toDomXCoord(a),this.toDomYCoord(c,b)]};Dygraph.prototype.toDomXCoord=function(b){if(b===null){return null}var c=this.plotter_.area;var a=this.xAxisRange();return c.x+(b-a[0])/(a[1]-a[0])*c.w};Dygraph.prototype.toDomYCoord=function(d,a){var c=this.toPercentYCoord(d,a);if(c===null){return null}var b=this.plotter_.area;return b.y+c*b.h};Dygraph.prototype.toDataCoords=function(a,c,b){return[this.toDataXCoord(a),this.toDataYCoord(c,b)]};Dygraph.prototype.toDataXCoord=function(b){if(b===null){return null}var c=this.plotter_.area;var a=this.xAxisRange();return a[0]+(b-c.x)/c.w*(a[1]-a[0])};Dygraph.prototype.toDataYCoord=function(h,b){if(h===null){return null}var c=this.plotter_.area;var g=this.yAxisRange(b);if(typeof(b)=="undefined"){b=0}if(!this.axes_[b].logscale){return g[0]+(c.y+c.h-h)/c.h*(g[1]-g[0])}else{var f=(h-c.y)/c.h;var a=Dygraph.log10(g[1]);var e=a-(f*(a-Dygraph.log10(g[0])));var d=Math.pow(Dygraph.LOG_SCALE,e);return d}};Dygraph.prototype.toPercentYCoord=function(e,b){if(e===null){return null}if(typeof(b)=="undefined"){b=0}var d=this.yAxisRange(b);var c;if(!this.axes_[b].logscale){c=(d[1]-e)/(d[1]-d[0])}else{var a=Dygraph.log10(d[1]);c=(a-Dygraph.log10(e))/(a-Dygraph.log10(d[0]))}return c};Dygraph.prototype.toPercentXCoord=function(b){if(b===null){return null}var a=this.xAxisRange();return(b-a[0])/(a[1]-a[0])};Dygraph.prototype.numColumns=function(){return this.rawData_[0]?this.rawData_[0].length:this.attr_("labels").length};Dygraph.prototype.numRows=function(){return this.rawData_.length};Dygraph.prototype.fullXRange_=function(){if(this.numRows()>0){return[this.rawData_[0][0],this.rawData_[this.numRows()-1][0]]}else{return[0,1]}};Dygraph.prototype.getValue=function(b,a){if(b<0||b>this.rawData_.length){return null}if(a<0||a>this.rawData_[b].length){return null}return this.rawData_[b][a]};Dygraph.prototype.createInterface_=function(){var a=this.maindiv_;this.graphDiv=document.createElement("div");this.graphDiv.style.width=this.width_+"px";this.graphDiv.style.height=this.height_+"px";a.appendChild(this.graphDiv);this.canvas_=Dygraph.createCanvas();this.canvas_.style.position="absolute";this.canvas_.width=this.width_;this.canvas_.height=this.height_;this.canvas_.style.width=this.width_+"px";this.canvas_.style.height=this.height_+"px";this.canvas_ctx_=Dygraph.getContext(this.canvas_);this.hidden_=this.createPlotKitCanvas_(this.canvas_);this.hidden_ctx_=Dygraph.getContext(this.hidden_);if(this.attr_("showRangeSelector")){this.rangeSelector_=new DygraphRangeSelector(this)}this.graphDiv.appendChild(this.hidden_);this.graphDiv.appendChild(this.canvas_);this.mouseEventElement_=this.createMouseEventElement_();this.layout_=new DygraphLayout(this);if(this.rangeSelector_){this.rangeSelector_.addToGraph(this.graphDiv,this.layout_)}var b=this;Dygraph.addEvent(this.mouseEventElement_,"mousemove",function(c){b.mouseMove_(c)});Dygraph.addEvent(this.mouseEventElement_,"mouseout",function(c){b.mouseOut_(c)});this.createStatusMessage_();this.createDragInterface_();Dygraph.addEvent(window,"resize",function(c){b.resize()})};Dygraph.prototype.destroy=function(){var a=function(c){while(c.hasChildNodes()){a(c.firstChild);c.removeChild(c.firstChild)}};a(this.maindiv_);var b=function(c){for(var d in c){if(typeof(c[d])==="object"){c[d]=null}}};b(this.layout_);b(this.plotter_);b(this)};Dygraph.prototype.createPlotKitCanvas_=function(a){var b=Dygraph.createCanvas();b.style.position="absolute";b.style.top=a.style.top;b.style.left=a.style.left;b.width=this.width_;b.height=this.height_;b.style.width=this.width_+"px";b.style.height=this.height_+"px";return b};Dygraph.prototype.createMouseEventElement_=function(){if(this.isUsingExcanvas_){var a=document.createElement("div");a.style.position="absolute";a.style.backgroundColor="white";a.style.filter="alpha(opacity=0)";a.style.width=this.width_+"px";a.style.height=this.height_+"px";this.graphDiv.appendChild(a);return a}else{return this.canvas_}};Dygraph.prototype.setColors_=function(){var e=this.attr_("labels").length-1;this.colors_=[];var a=this.attr_("colors");var d;if(!a){var c=this.attr_("colorSaturation")||1;var b=this.attr_("colorValue")||0.5;var j=Math.ceil(e/2);for(d=1;d<=e;d++){if(!this.visibility()[d-1]){continue}var g=d%2?Math.ceil(d/2):(j+d/2);var f=(1*g/(1+e));this.colors_.push(Dygraph.hsvToRGB(f,c,b))}}else{for(d=0;d<e;d++){if(!this.visibility()[d]){continue}var h=a[d%a.length];this.colors_.push(h)}}this.plotter_.setColors(this.colors_)};Dygraph.prototype.getColors=function(){return this.colors_};Dygraph.prototype.createStatusMessage_=function(){var d=this.user_attrs_.labelsDiv;if(d&&null!==d&&(typeof(d)=="string"||d instanceof String)){this.user_attrs_.labelsDiv=document.getElementById(d)}if(!this.attr_("labelsDiv")){var a=this.attr_("labelsDivWidth");var c={position:"absolute",fontSize:"14px",zIndex:10,width:a+"px",top:"0px",left:(this.width_-a-2)+"px",background:"white",textAlign:"left",overflow:"hidden"};Dygraph.update(c,this.attr_("labelsDivStyles"));var e=document.createElement("div");e.className="dygraph-legend";for(var b in c){if(c.hasOwnProperty(b)){e.style[b]=c[b]}}this.graphDiv.appendChild(e);this.attrs_.labelsDiv=e}};Dygraph.prototype.positionLabelsDiv_=function(){if(this.user_attrs_.hasOwnProperty("labelsDiv")){return}var a=this.plotter_.area;var b=this.attr_("labelsDiv");b.style.left=a.x+a.w-this.attr_("labelsDivWidth")-1+"px";b.style.top=a.y+"px"};Dygraph.prototype.createRollInterface_=function(){if(!this.roller_){this.roller_=document.createElement("input");this.roller_.type="text";this.roller_.style.display="none";this.graphDiv.appendChild(this.roller_)}var e=this.attr_("showRoller")?"block":"none";var d=this.plotter_.area;var b={position:"absolute",zIndex:10,top:(d.y+d.h-25)+"px",left:(d.x+1)+"px",display:e};this.roller_.size="2";this.roller_.value=this.rollPeriod_;for(var a in b){if(b.hasOwnProperty(a)){this.roller_.style[a]=b[a]}}var c=this;this.roller_.onchange=function(){c.adjustRoll(c.roller_.value)}};Dygraph.prototype.dragGetX_=function(b,a){return Dygraph.pageX(b)-a.px};Dygraph.prototype.dragGetY_=function(b,a){return Dygraph.pageY(b)-a.py};Dygraph.prototype.createDragInterface_=function(){var c={isZooming:false,isPanning:false,is2DPan:false,dragStartX:null,dragStartY:null,dragEndX:null,dragEndY:null,dragDirection:null,prevEndX:null,prevEndY:null,prevDragDirection:null,initialLeftmostDate:null,xUnitsPerPixel:null,dateRange:null,px:0,py:0,boundedDates:null,boundedValues:null,initializeMouseDown:function(i,h,f){if(i.preventDefault){i.preventDefault()}else{i.returnValue=false;i.cancelBubble=true}f.px=Dygraph.findPosX(h.canvas_);f.py=Dygraph.findPosY(h.canvas_);f.dragStartX=h.dragGetX_(i,f);f.dragStartY=h.dragGetY_(i,f)}};var e=this.attr_("interactionModel");var b=this;var d=function(f){return function(g){f(g,b,c)}};for(var a in e){if(!e.hasOwnProperty(a)){continue}Dygraph.addEvent(this.mouseEventElement_,a,d(e[a]))}Dygraph.addEvent(document,"mouseup",function(g){if(c.isZooming||c.isPanning){c.isZooming=false;c.dragStartX=null;c.dragStartY=null}if(c.isPanning){c.isPanning=false;c.draggingDate=null;c.dateRange=null;for(var f=0;f<b.axes_.length;f++){delete b.axes_[f].draggingValue;delete b.axes_[f].dragValueRange}}})};Dygraph.prototype.drawZoomRect_=function(e,c,i,b,g,a,f,d){var h=this.canvas_ctx_;if(a==Dygraph.HORIZONTAL){h.clearRect(Math.min(c,f),this.layout_.getPlotArea().y,Math.abs(c-f),this.layout_.getPlotArea().h)}else{if(a==Dygraph.VERTICAL){h.clearRect(this.layout_.getPlotArea().x,Math.min(b,d),this.layout_.getPlotArea().w,Math.abs(b-d))}}if(e==Dygraph.HORIZONTAL){if(i&&c){h.fillStyle="rgba(128,128,128,0.33)";h.fillRect(Math.min(c,i),this.layout_.getPlotArea().y,Math.abs(i-c),this.layout_.getPlotArea().h)}}else{if(e==Dygraph.VERTICAL){if(g&&b){h.fillStyle="rgba(128,128,128,0.33)";h.fillRect(this.layout_.getPlotArea().x,Math.min(b,g),this.layout_.getPlotArea().w,Math.abs(g-b))}}}if(this.isUsingExcanvas_){this.currentZoomRectArgs_=[e,c,i,b,g,0,0,0]}};Dygraph.prototype.clearZoomRect_=function(){this.currentZoomRectArgs_=null;this.canvas_ctx_.clearRect(0,0,this.canvas_.width,this.canvas_.height)};Dygraph.prototype.doZoomX_=function(c,a){this.currentZoomRectArgs_=null;var b=this.toDataXCoord(c);var d=this.toDataXCoord(a);this.doZoomXDates_(b,d)};Dygraph.zoomAnimationFunction=function(c,b){var a=1.5;return(1-Math.pow(a,-c))/(1-Math.pow(a,-b))};Dygraph.prototype.doZoomXDates_=function(c,e){var a=this.xAxisRange();var d=[c,e];this.zoomed_x_=true;var b=this;this.doAnimatedZoom(a,d,null,null,function(){if(b.attr_("zoomCallback")){b.attr_("zoomCallback")(c,e,b.yAxisRanges())}})};Dygraph.prototype.doZoomY_=function(h,f){this.currentZoomRectArgs_=null;var c=this.yAxisRanges();var b=[];for(var e=0;e<this.axes_.length;e++){var d=this.toDataYCoord(h,e);var a=this.toDataYCoord(f,e);b.push([a,d])}this.zoomed_y_=true;var g=this;this.doAnimatedZoom(null,null,c,b,function(){if(g.attr_("zoomCallback")){var i=g.xAxisRange();g.attr_("zoomCallback")(i[0],i[1],g.yAxisRanges())}})};Dygraph.prototype.doUnzoom_=function(){var c=false,d=false,a=false;if(this.dateWindow_!==null){c=true;d=true}for(var f=0;f<this.axes_.length;f++){if(this.axes_[f].valueWindow!==null){c=true;a=true}}this.clearSelection();if(c){this.zoomed_x_=false;this.zoomed_y_=false;var e=this.rawData_[0][0];var b=this.rawData_[this.rawData_.length-1][0];if(!this.attr_("animatedZooms")){this.dateWindow_=null;for(f=0;f<this.axes_.length;f++){if(this.axes_[f].valueWindow!==null){delete this.axes_[f].valueWindow}}this.drawGraph_();if(this.attr_("zoomCallback")){this.attr_("zoomCallback")(e,b,this.yAxisRanges())}return}var k=null,l=null,j=null,g=null;if(d){k=this.xAxisRange();l=[e,b]}if(a){j=this.yAxisRanges();var m=this.gatherDatasets_(this.rolledSeries_,null);var n=m[1];this.computeYAxisRanges_(n);g=[];for(f=0;f<this.axes_.length;f++){g.push(this.axes_[f].extremeRange)}}var h=this;this.doAnimatedZoom(k,l,j,g,function(){h.dateWindow_=null;for(var o=0;o<h.axes_.length;o++){if(h.axes_[o].valueWindow!==null){delete h.axes_[o].valueWindow}}if(h.attr_("zoomCallback")){h.attr_("zoomCallback")(e,b,h.yAxisRanges())}})}};Dygraph.prototype.doAnimatedZoom=function(a,e,b,c,m){var i=this.attr_("animatedZooms")?Dygraph.ANIMATION_STEPS:1;var l=[];var k=[];var f,d;if(a!==null&&e!==null){for(f=1;f<=i;f++){d=Dygraph.zoomAnimationFunction(f,i);l[f-1]=[a[0]*(1-d)+d*e[0],a[1]*(1-d)+d*e[1]]}}if(b!==null&&c!==null){for(f=1;f<=i;f++){d=Dygraph.zoomAnimationFunction(f,i);var n=[];for(var g=0;g<this.axes_.length;g++){n.push([b[g][0]*(1-d)+d*c[g][0],b[g][1]*(1-d)+d*c[g][1]])}k[f-1]=n}}var h=this;Dygraph.repeatAndCleanup(function(p){if(k.length){for(var o=0;o<h.axes_.length;o++){var j=k[p][o];h.axes_[o].valueWindow=[j[0],j[1]]}}if(l.length){h.dateWindow_=l[p]}h.drawGraph_()},i,Dygraph.ANIMATION_DURATION/i,m)};Dygraph.prototype.mouseMove_=function(b){var r=this.layout_.points;if(r===undefined){return}var a=Dygraph.pageX(b)-Dygraph.findPosX(this.mouseEventElement_);var j=-1;var f;var n=1e+100;var o=-1;for(f=0;f<r.length;f++){var q=r[f];if(q===null){continue}var h=Math.abs(q.canvasx-a);if(h>n){continue}n=h;o=f}if(o>=0){j=r[o].xval}this.selPoints_=[];var d=r.length;if(!this.attr_("stackedGraph")){for(f=0;f<d;f++){if(r[f].xval==j){this.selPoints_.push(r[f])}}}else{var g=0;for(f=d-1;f>=0;f--){if(r[f].xval==j){var c={};for(var e in r[f]){c[e]=r[f][e]}c.yval-=g;g+=c.yval;this.selPoints_.push(c)}}this.selPoints_.reverse()}if(this.attr_("highlightCallback")){var m=this.lastx_;if(m!==null&&j!=m){this.attr_("highlightCallback")(b,j,this.selPoints_,this.idxToRow_(o))}}this.lastx_=j;this.updateSelection_()};Dygraph.prototype.idxToRow_=function(a){if(a<0){return -1}for(var b in this.layout_.datasets){if(a<this.layout_.datasets[b].length){return this.boundaryIds_[0][0]+a}a-=this.layout_.datasets[b].length}return -1};Dygraph.prototype.generateLegendHTML_=function(o,p){var f,b,e,n;if(typeof(o)==="undefined"){if(this.attr_("legend")!="always"){return""}b=this.attr_("labelsSeparateLines");var h=this.attr_("labels");f="";for(e=1;e<h.length;e++){if(!this.visibility()[e-1]){continue}n=this.plotter_.colors[h[e]];if(f!==""){f+=(b?"<br/>":" ")}f+="<b><span style='color: "+n+";'>&mdash;"+h[e]+"</span></b>"}return f}var m=this.optionsViewForAxis_("x");var j=m("valueFormatter");f=j(o,m,this.attr_("labels")[0],this)+":";var d=[];var l=this.numAxes();for(e=0;e<l;e++){d[e]=this.optionsViewForAxis_("y"+(e?1+e:""))}var q=this.attr_("labelsShowZeroValues");b=this.attr_("labelsSeparateLines");for(e=0;e<this.selPoints_.length;e++){var r=this.selPoints_[e];if(r.yval===0&&!q){continue}if(!Dygraph.isOK(r.canvasy)){continue}if(b){f+="<br/>"}var g=d[this.seriesToAxisMap_[r.name]];var a=g("valueFormatter");n=this.plotter_.colors[r.name];var k=a(r.yval,g,r.name,this);f+=" <b><span style='color: "+n+";'>"+r.name+"</span></b>:"+k}return f};Dygraph.prototype.setLegendHTML_=function(a,d){var c=this.generateLegendHTML_(a,d);var b=this.attr_("labelsDiv");if(b!==null){b.innerHTML=c}else{if(typeof(this.shown_legend_error_)=="undefined"){this.error("labelsDiv is set to something nonexistent; legend will not be shown.");this.shown_legend_error_=true}}};Dygraph.prototype.updateSelection_=function(){var d;var h=this.canvas_ctx_;if(this.previousVerticalX_>=0){var e=0;var f=this.attr_("labels");for(d=1;d<f.length;d++){var b=this.attr_("highlightCircleSize",f[d]);if(b>e){e=b}}var g=this.previousVerticalX_;h.clearRect(g-e-1,0,2*e+2,this.height_)}if(this.isUsingExcanvas_&&this.currentZoomRectArgs_){Dygraph.prototype.drawZoomRect_.apply(this,this.currentZoomRectArgs_)}if(this.selPoints_.length>0){if(this.attr_("showLabelsOnHighlight")){this.setLegendHTML_(this.lastx_,this.selPoints_)}var c=this.selPoints_[0].canvasx;h.save();for(d=0;d<this.selPoints_.length;d++){var j=this.selPoints_[d];if(!Dygraph.isOK(j.canvasy)){continue}var a=this.attr_("highlightCircleSize",j.name);h.beginPath();h.fillStyle=this.plotter_.colors[j.name];h.arc(c,j.canvasy,a,0,2*Math.PI,false);h.fill()}h.restore();this.previousVerticalX_=c}};Dygraph.prototype.setSelection=function(c){this.selPoints_=[];var d=0;if(c!==false){c=c-this.boundaryIds_[0][0]}if(c!==false&&c>=0){for(var b in this.layout_.datasets){if(c<this.layout_.datasets[b].length){var a=this.layout_.points[d+c];if(this.attr_("stackedGraph")){a=this.layout_.unstackPointAtIndex(d+c)}this.selPoints_.push(a)}d+=this.layout_.datasets[b].length}}if(this.selPoints_.length){this.lastx_=this.selPoints_[0].xval;this.updateSelection_()}else{this.clearSelection()}};Dygraph.prototype.mouseOut_=function(a){if(this.attr_("unhighlightCallback")){this.attr_("unhighlightCallback")(a)}if(this.attr_("hideOverlayOnMouseOut")){this.clearSelection()}};Dygraph.prototype.clearSelection=function(){this.canvas_ctx_.clearRect(0,0,this.width_,this.height_);this.setLegendHTML_();this.selPoints_=[];this.lastx_=-1};Dygraph.prototype.getSelection=function(){if(!this.selPoints_||this.selPoints_.length<1){return -1}for(var a=0;a<this.layout_.points.length;a++){if(this.layout_.points[a].x==this.selPoints_[0].x){return a+this.boundaryIds_[0][0]}}return -1};Dygraph.prototype.loadedEvent_=function(a){this.rawData_=this.parseCSV_(a);this.predraw_()};Dygraph.prototype.addXTicks_=function(){var a;if(this.dateWindow_){a=[this.dateWindow_[0],this.dateWindow_[1]]}else{a=this.fullXRange_()}var c=this.optionsViewForAxis_("x");var b=c("ticker")(a[0],a[1],this.width_,c,this);this.layout_.setXTicks(b)};Dygraph.prototype.extremeValues_=function(d){var h=null,f=null,c,g;var b=this.attr_("errorBars")||this.attr_("customBars");if(b){for(c=0;c<d.length;c++){g=d[c][1][0];if(!g){continue}var a=g-d[c][1][1];var e=g+d[c][1][2];if(a>g){a=g}if(e<g){e=g}if(f===null||e>f){f=e}if(h===null||a<h){h=a}}}else{for(c=0;c<d.length;c++){g=d[c][1];if(g===null||isNaN(g)){continue}if(f===null||g>f){f=g}if(h===null||g<h){h=g}}}return[h,f]};Dygraph.prototype.predraw_=function(){var f=new Date();this.computeYAxes_();if(this.plotter_){this.plotter_.clear()}this.plotter_=new DygraphCanvasRenderer(this,this.hidden_,this.hidden_ctx_,this.layout_);this.createRollInterface_();this.positionLabelsDiv_();if(this.rangeSelector_){this.rangeSelector_.renderStaticLayer()}this.rolledSeries_=[null];for(var c=1;c<this.numColumns();c++){var e=this.attr_("connectSeparatedPoints",c);var d=this.attr_("logscale",c);var b=this.extractSeries_(this.rawData_,c,d,e);b=this.rollingAverage(b,this.rollPeriod_);this.rolledSeries_.push(b)}this.drawGraph_();var a=new Date();this.drawingTimeMs_=(a-f)};Dygraph.prototype.gatherDatasets_=function(w,c){var s=[];var b=[];var e=[];var a={};var u,t,r;var m=w.length-1;for(u=m;u>=1;u--){if(!this.visibility()[u-1]){continue}var h=[];for(t=0;t<w[u].length;t++){h.push(w[u][t])}var o=this.attr_("errorBars")||this.attr_("customBars");if(c){var A=c[0];var f=c[1];var p=[];var d=null,z=null;for(r=0;r<h.length;r++){if(h[r][0]>=A&&d===null){d=r}if(h[r][0]<=f){z=r}}if(d===null){d=0}if(d>0){d--}if(z===null){z=h.length-1}if(z<h.length-1){z++}s[u-1]=[d,z];for(r=d;r<=z;r++){p.push(h[r])}h=p}else{s[u-1]=[0,h.length-1]}var n=this.extremeValues_(h);if(o){for(t=0;t<h.length;t++){h[t]=[h[t][0],h[t][1][0],h[t][1][1],h[t][1][2]]}}else{if(this.attr_("stackedGraph")){var q=h.length;var y;for(t=0;t<q;t++){var g=h[t][0];if(b[g]===undefined){b[g]=0}y=h[t][1];b[g]+=y;h[t]=[g,b[g]];if(b[g]>n[1]){n[1]=b[g]}if(b[g]<n[0]){n[0]=b[g]}}}}var v=this.attr_("labels")[u];a[v]=n;e[u]=h}return[e,a,s]};Dygraph.prototype.drawGraph_=function(j){var a=new Date();if(typeof(j)==="undefined"){j=true}var e=this.is_initial_draw_;this.is_initial_draw_=false;this.layout_.removeAllDatasets();this.setColors_();this.attrs_.pointSize=0.5*this.attr_("highlightCircleSize");var g=this.gatherDatasets_(this.rolledSeries_,this.dateWindow_);var d=g[0];var h=g[1];this.boundaryIds_=g[2];for(var f=1;f<d.length;f++){if(!this.visibility()[f-1]){continue}this.layout_.addDataset(this.attr_("labels")[f],d[f])}this.computeYAxisRanges_(h);this.layout_.setYAxes(this.axes_);this.addXTicks_();var b=this.zoomed_x_;this.layout_.setDateWindow(this.dateWindow_);this.zoomed_x_=b;this.layout_.evaluateWithError();this.renderGraph_(e,false);if(this.attr_("timingName")){var c=new Date();if(console){console.log(this.attr_("timingName")+" - drawGraph: "+(c-a)+"ms")}}};Dygraph.prototype.renderGraph_=function(a,b){this.plotter_.clear();this.plotter_.render();this.canvas_.getContext("2d").clearRect(0,0,this.canvas_.width,this.canvas_.height);this.setLegendHTML_();if(!a){if(b){if(typeof(this.selPoints_)!=="undefined"&&this.selPoints_.length){this.clearSelection()}else{this.clearSelection()}}}if(this.rangeSelector_){this.rangeSelector_.renderInteractiveLayer()}if(this.attr_("drawCallback")!==null){this.attr_("drawCallback")(this,a)}};Dygraph.prototype.computeYAxes_=function(){var g,c,m,b,j,a,p;if(this.axes_!==undefined&&this.user_attrs_.hasOwnProperty("valueRange")===false){c=[];for(j=0;j<this.axes_.length;j++){c.push(this.axes_[j].valueWindow)}}this.axes_=[{yAxisId:0,g:this}];this.seriesToAxisMap_={};var h=this.attr_("labels");var f={};for(g=1;g<h.length;g++){f[h[g]]=(g-1)}var e=["includeZero","valueRange","labelsKMB","labelsKMG2","pixelsPerYLabel","yAxisLabelWidth","axisLabelFontSize","axisTickSize","logscale"];for(g=0;g<e.length;g++){var d=e[g];p=this.attr_(d);if(p){this.axes_[0][d]=p}}for(m in f){if(!f.hasOwnProperty(m)){continue}b=this.attr_("axis",m);if(b===null){this.seriesToAxisMap_[m]=0;continue}if(typeof(b)=="object"){a={};Dygraph.update(a,this.axes_[0]);Dygraph.update(a,{valueRange:null});var o=this.axes_.length;a.yAxisId=o;a.g=this;Dygraph.update(a,b);this.axes_.push(a);this.seriesToAxisMap_[m]=o}}for(m in f){if(!f.hasOwnProperty(m)){continue}b=this.attr_("axis",m);if(typeof(b)=="string"){if(!this.seriesToAxisMap_.hasOwnProperty(b)){this.error("Series "+m+" wants to share a y-axis with series "+b+", which does not define its own axis.");return null}var n=this.seriesToAxisMap_[b];this.seriesToAxisMap_[m]=n}}if(c!==undefined){for(j=0;j<c.length;j++){this.axes_[j].valueWindow=c[j]}}for(b=0;b<this.axes_.length;b++){if(b===0){a=this.optionsViewForAxis_("y"+(b?"2":""));p=a("valueRange");if(p){this.axes_[b].valueRange=p}}else{var l=this.user_attrs_.axes;if(l&&l.y2){p=l.y2.valueRange;if(p){this.axes_[b].valueRange=p}}}}};Dygraph.prototype.numAxes=function(){var c=0;for(var b in this.seriesToAxisMap_){if(!this.seriesToAxisMap_.hasOwnProperty(b)){continue}var a=this.seriesToAxisMap_[b];if(a>c){c=a}}return 1+c};Dygraph.prototype.axisPropertiesForSeries=function(a){return this.axes_[this.seriesToAxisMap_[a]]};Dygraph.prototype.computeYAxisRanges_=function(a){var g=[],h;for(h in this.seriesToAxisMap_){if(!this.seriesToAxisMap_.hasOwnProperty(h)){continue}var p=this.seriesToAxisMap_[h];while(g.length<=p){g.push([])}g[p].push(h)}for(var u=0;u<this.axes_.length;u++){var b=this.axes_[u];if(!g[u]){b.extremeRange=[0,1]}else{h=g[u];var x=Infinity;var w=-Infinity;var o,m;for(var s=0;s<h.length;s++){if(!a.hasOwnProperty(h[s])){continue}o=a[h[s]][0];if(o!==null){x=Math.min(o,x)}m=a[h[s]][1];if(m!==null){w=Math.max(m,w)}}if(b.includeZero&&x>0){x=0}if(x==Infinity){x=0}if(w==-Infinity){w=1}var t=w-x;if(t===0){t=w}var d,z;if(b.logscale){d=w+0.1*t;z=x}else{d=w+0.1*t;z=x-0.1*t;if(!this.attr_("avoidMinZero")){if(z<0&&x>=0){z=0}if(d>0&&w<=0){d=0}}if(this.attr_("includeZero")){if(w<0){d=0}if(x>0){z=0}}}b.extremeRange=[z,d]}if(b.valueWindow){b.computedValueRange=[b.valueWindow[0],b.valueWindow[1]]}else{if(b.valueRange){b.computedValueRange=[b.valueRange[0],b.valueRange[1]]}else{b.computedValueRange=b.extremeRange}}var n=this.optionsViewForAxis_("y"+(u?"2":""));var y=n("ticker");if(u===0||b.independentTicks){b.ticks=y(b.computedValueRange[0],b.computedValueRange[1],this.height_,n,this)}else{var l=this.axes_[0];var e=l.ticks;var f=l.computedValueRange[1]-l.computedValueRange[0];var A=b.computedValueRange[1]-b.computedValueRange[0];var c=[];for(var r=0;r<e.length;r++){var q=(e[r].v-l.computedValueRange[0])/f;var v=b.computedValueRange[0]+q*A;c.push(v)}b.ticks=y(b.computedValueRange[0],b.computedValueRange[1],this.height_,n,this,c)}}};Dygraph.prototype.extractSeries_=function(h,e,g,f){var d=[];for(var c=0;c<h.length;c++){var b=h[c][0];var a=h[c][e];if(g){if(a<=0){a=null}d.push([b,a])}else{if(a!==null||!f){d.push([b,a])}}}return d};Dygraph.prototype.rollingAverage=function(l,d){if(l.length<2){return l}d=Math.min(d,l.length);var b=[];var s=this.attr_("sigma");var E,o,w,v,m,c,D,x;if(this.fractions_){var k=0;var h=0;var e=100;for(w=0;w<l.length;w++){k+=l[w][1][0];h+=l[w][1][1];if(w-d>=0){k-=l[w-d][1][0];h-=l[w-d][1][1]}var A=l[w][0];var u=h?k/h:0;if(this.attr_("errorBars")){if(this.attr_("wilsonInterval")){if(h){var r=u<0?0:u,t=h;var z=s*Math.sqrt(r*(1-r)/t+s*s/(4*t*t));var a=1+s*s/h;E=(r+s*s/(2*h)-z)/a;o=(r+s*s/(2*h)+z)/a;b[w]=[A,[r*e,(r-E)*e,(o-r)*e]]}else{b[w]=[A,[0,0,0]]}}else{x=h?s*Math.sqrt(u*(1-u)/h):1;b[w]=[A,[e*u,e*x,e*x]]}}else{b[w]=[A,e*u]}}}else{if(this.attr_("customBars")){E=0;var B=0;o=0;var g=0;for(w=0;w<l.length;w++){var C=l[w][1];m=C[1];b[w]=[l[w][0],[m,m-C[0],C[2]-m]];if(m!==null&&!isNaN(m)){E+=C[0];B+=m;o+=C[2];g+=1}if(w-d>=0){var q=l[w-d];if(q[1][1]!==null&&!isNaN(q[1][1])){E-=q[1][0];B-=q[1][1];o-=q[1][2];g-=1}}if(g){b[w]=[l[w][0],[1*B/g,1*(B-E)/g,1*(o-B)/g]]}else{b[w]=[l[w][0],[null,null,null]]}}}else{if(!this.attr_("errorBars")){if(d==1){return l}for(w=0;w<l.length;w++){c=0;D=0;for(v=Math.max(0,w-d+1);v<w+1;v++){m=l[v][1];if(m===null||isNaN(m)){continue}D++;c+=l[v][1]}if(D){b[w]=[l[w][0],c/D]}else{b[w]=[l[w][0],null]}}}else{for(w=0;w<l.length;w++){c=0;var f=0;D=0;for(v=Math.max(0,w-d+1);v<w+1;v++){m=l[v][1][0];if(m===null||isNaN(m)){continue}D++;c+=l[v][1][0];f+=Math.pow(l[v][1][1],2)}if(D){x=Math.sqrt(f)/D;b[w]=[l[w][0],[c/D,s*x,s*x]]}else{b[w]=[l[w][0],[null,null,null]]}}}}}return b};Dygraph.prototype.detectTypeFromString_=function(b){var a=false;var c=b.indexOf("-");if((c>0&&(b[c-1]!="e"&&b[c-1]!="E"))||b.indexOf("/")>=0||isNaN(parseFloat(b))){a=true}else{if(b.length==8&&b>"19700101"&&b<"20371231"){a=true}}if(a){this.attrs_.xValueParser=Dygraph.dateParser;this.attrs_.axes.x.valueFormatter=Dygraph.dateString_;this.attrs_.axes.x.ticker=Dygraph.dateTicker;this.attrs_.axes.x.axisLabelFormatter=Dygraph.dateAxisFormatter}else{this.attrs_.xValueParser=function(d){return parseFloat(d)};this.attrs_.axes.x.valueFormatter=function(d){return d};this.attrs_.axes.x.ticker=Dygraph.numericTicks;this.attrs_.axes.x.axisLabelFormatter=this.attrs_.axes.x.valueFormatter}};Dygraph.prototype.parseFloat_=function(a,c,b){var e=parseFloat(a);if(!isNaN(e)){return e}if(/^ *$/.test(a)){return null}if(/^ *nan *$/i.test(a)){return NaN}var d="Unable to parse '"+a+"' as a number";if(b!==null&&c!==null){d+=" on line "+(1+c)+" ('"+b+"') of CSV."}this.error(d);return null};Dygraph.prototype.parseCSV_=function(s){var r=[];var a=s.split("\n");var g,k;var p=this.attr_("delimiter");if(a[0].indexOf(p)==-1&&a[0].indexOf("\t")>=0){p="\t"}var b=0;if(!("labels" in this.user_attrs_)){b=1;this.attrs_.labels=a[0].split(p)}var o=0;var m;var q=false;var c=this.attr_("labels").length;var f=false;for(var l=b;l<a.length;l++){var e=a[l];o=l;if(e.length===0){continue}if(e[0]=="#"){continue}var d=e.split(p);if(d.length<2){continue}var h=[];if(!q){this.detectTypeFromString_(d[0]);m=this.attr_("xValueParser");q=true}h[0]=m(d[0],this);if(this.fractions_){for(k=1;k<d.length;k++){g=d[k].split("/");if(g.length!=2){this.error('Expected fractional "num/den" values in CSV data but found a value \''+d[k]+"' on line "+(1+l)+" ('"+e+"') which is not of this form.");h[k]=[0,0]}else{h[k]=[this.parseFloat_(g[0],l,e),this.parseFloat_(g[1],l,e)]}}}else{if(this.attr_("errorBars")){if(d.length%2!=1){this.error("Expected alternating (value, stdev.) pairs in CSV data but line "+(1+l)+" has an odd number of values ("+(d.length-1)+"): '"+e+"'")}for(k=1;k<d.length;k+=2){h[(k+1)/2]=[this.parseFloat_(d[k],l,e),this.parseFloat_(d[k+1],l,e)]}}else{if(this.attr_("customBars")){for(k=1;k<d.length;k++){var t=d[k];if(/^ *$/.test(t)){h[k]=[null,null,null]}else{g=t.split(";");if(g.length==3){h[k]=[this.parseFloat_(g[0],l,e),this.parseFloat_(g[1],l,e),this.parseFloat_(g[2],l,e)]}else{this.warn('When using customBars, values must be either blank or "low;center;high" tuples (got "'+t+'" on line '+(1+l))}}}}else{for(k=1;k<d.length;k++){h[k]=this.parseFloat_(d[k],l,e)}}}}if(r.length>0&&h[0]<r[r.length-1][0]){f=true}if(h.length!=c){this.error("Number of columns in line "+l+" ("+h.length+") does not agree with number of labels ("+c+") "+e)}if(l===0&&this.attr_("labels")){var n=true;for(k=0;n&&k<h.length;k++){if(h[k]){n=false}}if(n){this.warn("The dygraphs 'labels' option is set, but the first row of CSV data ('"+e+"') appears to also contain labels. Will drop the CSV labels and use the option labels.");continue}}r.push(h)}if(f){this.warn("CSV is out of order; order it correctly to speed loading.");r.sort(function(j,i){return j[0]-i[0]})}return r};Dygraph.prototype.parseArray_=function(b){if(b.length===0){this.error("Can't plot empty data set");return null}if(b[0].length===0){this.error("Data set cannot contain an empty row");return null}var a;if(this.attr_("labels")===null){this.warn("Using default labels. Set labels explicitly via 'labels' in the options parameter");this.attrs_.labels=["X"];for(a=1;a<b[0].length;a++){this.attrs_.labels.push("Y"+a)}}if(Dygraph.isDateLike(b[0][0])){this.attrs_.axes.x.valueFormatter=Dygraph.dateString_;this.attrs_.axes.x.axisLabelFormatter=Dygraph.dateAxisFormatter;this.attrs_.axes.x.ticker=Dygraph.dateTicker;var c=Dygraph.clone(b);for(a=0;a<b.length;a++){if(c[a].length===0){this.error("Row "+(1+a)+" of data is empty");return null}if(c[a][0]===null||typeof(c[a][0].getTime)!="function"||isNaN(c[a][0].getTime())){this.error("x value in row "+(1+a)+" is not a Date");return null}c[a][0]=c[a][0].getTime()}return c}else{this.attrs_.axes.x.valueFormatter=function(d){return d};this.attrs_.axes.x.axisLabelFormatter=Dygraph.numberAxisLabelFormatter;this.attrs_.axes.x.ticker=Dygraph.numericTicks;return b}};Dygraph.prototype.parseDataTable_=function(v){var g=v.getNumberOfColumns();var f=v.getNumberOfRows();var e=v.getColumnType(0);if(e=="date"||e=="datetime"){this.attrs_.xValueParser=Dygraph.dateParser;this.attrs_.axes.x.valueFormatter=Dygraph.dateString_;this.attrs_.axes.x.ticker=Dygraph.dateTicker;this.attrs_.axes.x.axisLabelFormatter=Dygraph.dateAxisFormatter}else{if(e=="number"){this.attrs_.xValueParser=function(i){return parseFloat(i)};this.attrs_.axes.x.valueFormatter=function(i){return i};this.attrs_.axes.x.ticker=Dygraph.numericTicks;this.attrs_.axes.x.axisLabelFormatter=this.attrs_.axes.x.valueFormatter}else{this.error("only 'date', 'datetime' and 'number' types are supported for column 1 of DataTable input (Got '"+e+"')");return null}}var l=[];var s={};var r=false;var p,n;for(p=1;p<g;p++){var b=v.getColumnType(p);if(b=="number"){l.push(p)}else{if(b=="string"&&this.attr_("displayAnnotations")){var q=l[l.length-1];if(!s.hasOwnProperty(q)){s[q]=[p]}else{s[q].push(p)}r=true}else{this.error("Only 'number' is supported as a dependent type with Gviz. 'string' is only supported if displayAnnotations is true")}}}var t=[v.getColumnLabel(0)];for(p=0;p<l.length;p++){t.push(v.getColumnLabel(l[p]));if(this.attr_("errorBars")){p+=1}}this.attrs_.labels=t;g=t.length;var u=[];var h=false;var a=[];for(p=0;p<f;p++){var d=[];if(typeof(v.getValue(p,0))==="undefined"||v.getValue(p,0)===null){this.warn("Ignoring row "+p+" of DataTable because of undefined or null first column.");continue}if(e=="date"||e=="datetime"){d.push(v.getValue(p,0).getTime())}else{d.push(v.getValue(p,0))}if(!this.attr_("errorBars")){for(n=0;n<l.length;n++){var c=l[n];d.push(v.getValue(p,c));if(r&&s.hasOwnProperty(c)&&v.getValue(p,s[c][0])!==null){var o={};o.series=v.getColumnLabel(c);o.xval=d[0];o.shortText=String.fromCharCode(65+a.length);o.text="";for(var m=0;m<s[c].length;m++){if(m){o.text+="\n"}o.text+=v.getValue(p,s[c][m])}a.push(o)}}for(n=0;n<d.length;n++){if(!isFinite(d[n])){d[n]=null}}}else{for(n=0;n<g-1;n++){d.push([v.getValue(p,1+2*n),v.getValue(p,2+2*n)])}}if(u.length>0&&d[0]<u[u.length-1][0]){h=true}u.push(d)}if(h){this.warn("DataTable is out of order; order it correctly to speed loading.");u.sort(function(j,i){return j[0]-i[0]})}this.rawData_=u;if(a.length>0){this.setAnnotations(a,true)}};Dygraph.prototype.start_=function(){var c=this.file_;if(typeof c=="function"){c=c()}if(Dygraph.isArrayLike(c)){this.rawData_=this.parseArray_(c);this.predraw_()}else{if(typeof c=="object"&&typeof c.getColumnRange=="function"){this.parseDataTable_(c);this.predraw_()}else{if(typeof c=="string"){if(c.indexOf("\n")>=0){this.loadedEvent_(c)}else{var b=new XMLHttpRequest();var a=this;b.onreadystatechange=function(){if(b.readyState==4){if(b.status===200||b.status===0){a.loadedEvent_(b.responseText)}}};b.open("GET",c,true);b.send(null)}}else{this.error("Unknown data format: "+(typeof c))}}}};Dygraph.prototype.updateOptions=function(e,b){if(typeof(b)=="undefined"){b=false}var d=e.file;var c=Dygraph.mapLegacyOptions_(e);if("rollPeriod" in c){this.rollPeriod_=c.rollPeriod}if("dateWindow" in c){this.dateWindow_=c.dateWindow;if(!("isZoomedIgnoreProgrammaticZoom" in c)){this.zoomed_x_=(c.dateWindow!==null)}}if("valueRange" in c&&!("isZoomedIgnoreProgrammaticZoom" in c)){this.zoomed_y_=(c.valueRange!==null)}var a=Dygraph.isPixelChangingOptionList(this.attr_("labels"),c);Dygraph.updateDeep(this.user_attrs_,c);if(d){this.file_=d;if(!b){this.start_()}}else{if(!b){if(a){this.predraw_()}else{this.renderGraph_(false,false)}}}};Dygraph.mapLegacyOptions_=function(c){var a={};for(var b in c){if(b=="file"){continue}if(c.hasOwnProperty(b)){a[b]=c[b]}}var e=function(g,f,h){if(!a.axes){a.axes={}}if(!a.axes[g]){a.axes[g]={}}a.axes[g][f]=h};var d=function(f,g,h){if(typeof(c[f])!="undefined"){e(g,h,c[f]);delete a[f]}};d("xValueFormatter","x","valueFormatter");d("pixelsPerXLabel","x","pixelsPerLabel");d("xAxisLabelFormatter","x","axisLabelFormatter");d("xTicker","x","ticker");d("yValueFormatter","y","valueFormatter");d("pixelsPerYLabel","y","pixelsPerLabel");d("yAxisLabelFormatter","y","axisLabelFormatter");d("yTicker","y","ticker");return a};Dygraph.prototype.resize=function(d,b){if(this.resize_lock){return}this.resize_lock=true;if((d===null)!=(b===null)){this.warn("Dygraph.resize() should be called with zero parameters or two non-NULL parameters. Pretending it was zero.");d=b=null}var a=this.width_;var c=this.height_;if(d){this.maindiv_.style.width=d+"px";this.maindiv_.style.height=b+"px";this.width_=d;this.height_=b}else{this.width_=this.maindiv_.clientWidth;this.height_=this.maindiv_.clientHeight}if(a!=this.width_||c!=this.height_){this.maindiv_.innerHTML="";this.roller_=null;this.attrs_.labelsDiv=null;this.createInterface_();if(this.annotations_.length){this.layout_.setAnnotations(this.annotations_)}this.predraw_()}this.resize_lock=false};Dygraph.prototype.adjustRoll=function(a){this.rollPeriod_=a;this.predraw_()};Dygraph.prototype.visibility=function(){if(!this.attr_("visibility")){this.attrs_.visibility=[]}while(this.attr_("visibility").length<this.numColumns()-1){this.attrs_.visibility.push(true)}return this.attr_("visibility")};Dygraph.prototype.setVisibility=function(b,c){var a=this.visibility();if(b<0||b>=a.length){this.warn("invalid series number in setVisibility: "+b)}else{a[b]=c;this.predraw_()}};Dygraph.prototype.size=function(){return{width:this.width_,height:this.height_}};Dygraph.prototype.setAnnotations=function(b,a){Dygraph.addAnnotationRule();this.annotations_=b;this.layout_.setAnnotations(this.annotations_);if(!a){this.predraw_()}};Dygraph.prototype.annotations=function(){return this.annotations_};Dygraph.prototype.indexFromSetName=function(a){var c=this.attr_("labels");for(var b=0;b<c.length;b++){if(c[b]==a){return b}}return null};Dygraph.addAnnotationRule=function(){if(Dygraph.addedAnnotationCSS){return}var f="border: 1px solid black; background-color: white; text-align: center;";var e=document.createElement("style");e.type="text/css";document.getElementsByTagName("head")[0].appendChild(e);for(var b=0;b<document.styleSheets.length;b++){if(document.styleSheets[b].disabled){continue}var d=document.styleSheets[b];try{if(d.insertRule){var a=d.cssRules?d.cssRules.length:0;d.insertRule(".dygraphDefaultAnnotation { "+f+" }",a)}else{if(d.addRule){d.addRule(".dygraphDefaultAnnotation",f)}}Dygraph.addedAnnotationCSS=true;return}catch(c){}}this.warn("Unable to add default annotation CSS rule; display may be off.")};var DateGraph=Dygraph;"use strict";Dygraph.LOG_SCALE=10;Dygraph.LN_TEN=Math.log(Dygraph.LOG_SCALE);Dygraph.log10=function(a){return Math.log(a)/Dygraph.LN_TEN};Dygraph.DEBUG=1;Dygraph.INFO=2;Dygraph.WARNING=3;Dygraph.ERROR=3;Dygraph.LOG_STACK_TRACES=false;Dygraph.log=function(b,d){var a;if(typeof(printStackTrace)!="undefined"){a=printStackTrace({guess:false});while(a[0].indexOf("stacktrace")!=-1){a.splice(0,1)}a.splice(0,2);for(var c=0;c<a.length;c++){a[c]=a[c].replace(/\([^)]*\/(.*)\)/,"@$1").replace(/\@.*\/([^\/]*)/,"@$1").replace("[object Object].","")}var e=a.splice(0,1)[0];d+=" ("+e.replace(/^.*@ ?/,"")+")"}if(typeof(console)!="undefined"){switch(b){case Dygraph.DEBUG:console.debug("dygraphs: "+d);break;case Dygraph.INFO:console.info("dygraphs: "+d);break;case Dygraph.WARNING:console.warn("dygraphs: "+d);break;case Dygraph.ERROR:console.error("dygraphs: "+d);break}}if(Dygraph.LOG_STACK_TRACES){console.log(a.join("\n"))}};Dygraph.info=function(a){Dygraph.log(Dygraph.INFO,a)};Dygraph.prototype.info=Dygraph.info;Dygraph.warn=function(a){Dygraph.log(Dygraph.WARNING,a)};Dygraph.prototype.warn=Dygraph.warn;Dygraph.error=function(a){Dygraph.log(Dygraph.ERROR,a)};Dygraph.prototype.error=Dygraph.error;Dygraph.getContext=function(a){return a.getContext("2d")};Dygraph.addEvent=function addEvent(c,b,a){if(c.addEventListener){c.addEventListener(b,a,false)}else{c[b+a]=function(){a(window.event)};c.attachEvent("on"+b,c[b+a])}};Dygraph.removeEvent=function addEvent(c,b,a){if(c.removeEventListener){c.removeEventListener(b,a,false)}else{c.detachEvent("on"+b,c[b+a]);c[b+a]=null}};Dygraph.cancelEvent=function(a){a=a?a:window.event;if(a.stopPropagation){a.stopPropagation()}if(a.preventDefault){a.preventDefault()}a.cancelBubble=true;a.cancel=true;a.returnValue=false;return false};Dygraph.hsvToRGB=function(h,g,k){var c;var d;var l;if(g===0){c=k;d=k;l=k}else{var e=Math.floor(h*6);var j=(h*6)-e;var b=k*(1-g);var a=k*(1-(g*j));var m=k*(1-(g*(1-j)));switch(e){case 1:c=a;d=k;l=b;break;case 2:c=b;d=k;l=m;break;case 3:c=b;d=a;l=k;break;case 4:c=m;d=b;l=k;break;case 5:c=k;d=b;l=a;break;case 6:case 0:c=k;d=m;l=b;break}}c=Math.floor(255*c+0.5);d=Math.floor(255*d+0.5);l=Math.floor(255*l+0.5);return"rgb("+c+","+d+","+l+")"};Dygraph.findPosX=function(b){var c=0;if(b.offsetParent){var a=b;while(1){c+=a.offsetLeft;if(!a.offsetParent){break}a=a.offsetParent}}else{if(b.x){c+=b.x}}while(b&&b!=document.body){c-=b.scrollLeft;b=b.parentNode}return c};Dygraph.findPosY=function(c){var b=0;if(c.offsetParent){var a=c;while(1){b+=a.offsetTop;if(!a.offsetParent){break}a=a.offsetParent}}else{if(c.y){b+=c.y}}while(c&&c!=document.body){b-=c.scrollTop;c=c.parentNode}return b};Dygraph.pageX=function(c){if(c.pageX){return(!c.pageX||c.pageX<0)?0:c.pageX}else{var d=document;var a=document.body;return c.clientX+(d.scrollLeft||a.scrollLeft)-(d.clientLeft||0)}};Dygraph.pageY=function(c){if(c.pageY){return(!c.pageY||c.pageY<0)?0:c.pageY}else{var d=document;var a=document.body;return c.clientY+(d.scrollTop||a.scrollTop)-(d.clientTop||0)}};Dygraph.isOK=function(a){return a&&!isNaN(a)};Dygraph.floatFormat=function(a,b){var c=Math.min(Math.max(1,b||2),21);return(Math.abs(a)<0.001&&a!==0)?a.toExponential(c-1):a.toPrecision(c)};Dygraph.zeropad=function(a){if(a<10){return"0"+a}else{return""+a}};Dygraph.hmsString_=function(a){var c=Dygraph.zeropad;var b=new Date(a);if(b.getSeconds()){return c(b.getHours())+":"+c(b.getMinutes())+":"+c(b.getSeconds())}else{return c(b.getHours())+":"+c(b.getMinutes())}};Dygraph.round_=function(c,b){var a=Math.pow(10,b);return Math.round(c*a)/a};Dygraph.binarySearch=function(a,d,i,e,b){if(e===null||e===undefined||b===null||b===undefined){e=0;b=d.length-1}if(e>b){return -1}if(i===null||i===undefined){i=0}var h=function(j){return j>=0&&j<d.length};var g=parseInt((e+b)/2,10);var c=d[g];if(c==a){return g}var f;if(c>a){if(i>0){f=g-1;if(h(f)&&d[f]<a){return g}}return Dygraph.binarySearch(a,d,i,e,g-1)}if(c<a){if(i<0){f=g+1;if(h(f)&&d[f]>a){return g}}return Dygraph.binarySearch(a,d,i,g+1,b)}};Dygraph.dateParser=function(a){var b;var c;c=Dygraph.dateStrToMillis(a);if(c&&!isNaN(c)){return c}if(a.search("-")!=-1){b=a.replace("-","/","g");while(b.search("-")!=-1){b=b.replace("-","/")}c=Dygraph.dateStrToMillis(b)}else{if(a.length==8){b=a.substr(0,4)+"/"+a.substr(4,2)+"/"+a.substr(6,2);c=Dygraph.dateStrToMillis(b)}else{c=Dygraph.dateStrToMillis(a)}}if(!c||isNaN(c)){Dygraph.error("Couldn't parse "+a+" as a date")}return c};Dygraph.dateStrToMillis=function(a){return new Date(a).getTime()};Dygraph.update=function(b,c){if(typeof(c)!="undefined"&&c!==null){for(var a in c){if(c.hasOwnProperty(a)){b[a]=c[a]}}}return b};Dygraph.updateDeep=function(b,d){function c(e){return(typeof Node==="object"?e instanceof Node:typeof e==="object"&&typeof e.nodeType==="number"&&typeof e.nodeName==="string")}if(typeof(d)!="undefined"&&d!==null){for(var a in d){if(d.hasOwnProperty(a)){if(d[a]===null){b[a]=null}else{if(Dygraph.isArrayLike(d[a])){b[a]=d[a].slice()}else{if(c(d[a])){b[a]=d[a]}else{if(typeof(d[a])=="object"){if(typeof(b[a])!="object"){b[a]={}}Dygraph.updateDeep(b[a],d[a])}else{b[a]=d[a]}}}}}}}return b};Dygraph.isArrayLike=function(b){var a=typeof(b);if((a!="object"&&!(a=="function"&&typeof(b.item)=="function"))||b===null||typeof(b.length)!="number"||b.nodeType===3){return false}return true};Dygraph.isDateLike=function(a){if(typeof(a)!="object"||a===null||typeof(a.getTime)!="function"){return false}return true};Dygraph.clone=function(c){var b=[];for(var a=0;a<c.length;a++){if(Dygraph.isArrayLike(c[a])){b.push(Dygraph.clone(c[a]))}else{b.push(c[a])}}return b};Dygraph.createCanvas=function(){var a=document.createElement("canvas");var b=(/MSIE/.test(navigator.userAgent)&&!window.opera);if(b&&(typeof(G_vmlCanvasManager)!="undefined")){a=G_vmlCanvasManager.initElement(a)}return a};Dygraph.isAndroid=function(){return(/Android/).test(navigator.userAgent)};Dygraph.repeatAndCleanup=function(b,g,f,c){var e=0;var d=new Date().getTime();b(e);if(g==1){c();return}(function a(){if(e>=g){return}var h=d+(1+e)*f;setTimeout(function(){e++;b(e);if(e>=g-1){c()}else{a()}},h-new Date().getTime())})()};Dygraph.isPixelChangingOptionList=function(h,e){var d={annotationClickHandler:true,annotationDblClickHandler:true,annotationMouseOutHandler:true,annotationMouseOverHandler:true,axisLabelColor:true,axisLineColor:true,axisLineWidth:true,clickCallback:true,digitsAfterDecimal:true,drawCallback:true,drawPoints:true,drawXGrid:true,drawYGrid:true,fillAlpha:true,gridLineColor:true,gridLineWidth:true,hideOverlayOnMouseOut:true,highlightCallback:true,highlightCircleSize:true,interactionModel:true,isZoomedIgnoreProgrammaticZoom:true,labelsDiv:true,labelsDivStyles:true,labelsDivWidth:true,labelsKMB:true,labelsKMG2:true,labelsSeparateLines:true,labelsShowZeroValues:true,legend:true,maxNumberWidth:true,panEdgeFraction:true,pixelsPerYLabel:true,pointClickCallback:true,pointSize:true,rangeSelectorPlotFillColor:true,rangeSelectorPlotStrokeColor:true,showLabelsOnHighlight:true,showRoller:true,sigFigs:true,strokeWidth:true,underlayCallback:true,unhighlightCallback:true,xAxisLabelFormatter:true,xTicker:true,xValueFormatter:true,yAxisLabelFormatter:true,yValueFormatter:true,zoomCallback:true};var a=false;var b={};if(h){for(var f=1;f<h.length;f++){b[h[f]]=true}}for(var g in e){if(a){break}if(e.hasOwnProperty(g)){if(b[g]){for(var c in e[g]){if(a){break}if(e[g].hasOwnProperty(c)&&!d[c]){a=true}}}else{if(!d[g]){a=true}}}}return a};"use strict";Dygraph.GVizChart=function(a){this.container=a};Dygraph.GVizChart.prototype.draw=function(b,a){this.container.innerHTML="";if(typeof(this.date_graph)!="undefined"){this.date_graph.destroy()}this.date_graph=new Dygraph(this.container,b,a)};Dygraph.GVizChart.prototype.setSelection=function(b){var a=false;if(b.length){a=b[0].row}this.date_graph.setSelection(a)};Dygraph.GVizChart.prototype.getSelection=function(){var d=[];var e=this.date_graph.getSelection();if(e<0){return d}var b=1;var c=this.date_graph.layout_.datasets;for(var a in c){if(!c.hasOwnProperty(a)){continue}d.push({row:e,column:b});b++}return d};"use strict";Dygraph.Interaction={};Dygraph.Interaction.startPan=function(n,s,c){var q,b;c.isPanning=true;var j=s.xAxisRange();c.dateRange=j[1]-j[0];c.initialLeftmostDate=j[0];c.xUnitsPerPixel=c.dateRange/(s.plotter_.area.w-1);if(s.attr_("panEdgeFraction")){var v=s.width_*s.attr_("panEdgeFraction");var d=s.xAxisExtremes();var h=s.toDomXCoord(d[0])-v;var k=s.toDomXCoord(d[1])+v;var t=s.toDataXCoord(h);var u=s.toDataXCoord(k);c.boundedDates=[t,u];var f=[];var a=s.height_*s.attr_("panEdgeFraction");for(q=0;q<s.axes_.length;q++){b=s.axes_[q];var o=b.extremeRange;var p=s.toDomYCoord(o[0],q)+a;var r=s.toDomYCoord(o[1],q)-a;var m=s.toDataYCoord(p);var e=s.toDataYCoord(r);f[q]=[m,e]}c.boundedValues=f}c.is2DPan=false;for(q=0;q<s.axes_.length;q++){b=s.axes_[q];var l=s.yAxisRange(q);if(b.logscale){b.initialTopValue=Dygraph.log10(l[1]);b.dragValueRange=Dygraph.log10(l[1])-Dygraph.log10(l[0])}else{b.initialTopValue=l[1];b.dragValueRange=l[1]-l[0]}b.unitsPerPixel=b.dragValueRange/(s.plotter_.area.h-1);if(b.valueWindow||b.valueRange){c.is2DPan=true}}};Dygraph.Interaction.movePan=function(b,k,c){c.dragEndX=k.dragGetX_(b,c);c.dragEndY=k.dragGetY_(b,c);var h=c.initialLeftmostDate-(c.dragEndX-c.dragStartX)*c.xUnitsPerPixel;if(c.boundedDates){h=Math.max(h,c.boundedDates[0])}var a=h+c.dateRange;if(c.boundedDates){if(a>c.boundedDates[1]){h=h-(a-c.boundedDates[1]);a=h+c.dateRange}}k.dateWindow_=[h,a];if(c.is2DPan){for(var j=0;j<k.axes_.length;j++){var e=k.axes_[j];var d=c.dragEndY-c.dragStartY;var n=d*e.unitsPerPixel;var f=c.boundedValues?c.boundedValues[j]:null;var l=e.initialTopValue+n;if(f){l=Math.min(l,f[1])}var m=l-e.dragValueRange;if(f){if(m<f[0]){l=l-(m-f[0]);m=l-e.dragValueRange}}if(e.logscale){e.valueWindow=[Math.pow(Dygraph.LOG_SCALE,m),Math.pow(Dygraph.LOG_SCALE,l)]}else{e.valueWindow=[m,l]}}}k.drawGraph_(false)};Dygraph.Interaction.endPan=function(c,b,a){a.dragEndX=b.dragGetX_(c,a);a.dragEndY=b.dragGetY_(c,a);var e=Math.abs(a.dragEndX-a.dragStartX);var d=Math.abs(a.dragEndY-a.dragStartY);if(e<2&&d<2&&b.lastx_!==undefined&&b.lastx_!=-1){Dygraph.Interaction.treatMouseOpAsClick(b,c,a)}a.isPanning=false;a.is2DPan=false;a.initialLeftmostDate=null;a.dateRange=null;a.valueRange=null;a.boundedDates=null;a.boundedValues=null};Dygraph.Interaction.startZoom=function(c,b,a){a.isZooming=true};Dygraph.Interaction.moveZoom=function(c,b,a){a.dragEndX=b.dragGetX_(c,a);a.dragEndY=b.dragGetY_(c,a);var e=Math.abs(a.dragStartX-a.dragEndX);var d=Math.abs(a.dragStartY-a.dragEndY);a.dragDirection=(e<d/2)?Dygraph.VERTICAL:Dygraph.HORIZONTAL;b.drawZoomRect_(a.dragDirection,a.dragStartX,a.dragEndX,a.dragStartY,a.dragEndY,a.prevDragDirection,a.prevEndX,a.prevEndY);a.prevEndX=a.dragEndX;a.prevEndY=a.dragEndY;a.prevDragDirection=a.dragDirection};Dygraph.Interaction.treatMouseOpAsClick=function(f,b,d){var k=f.attr_("clickCallback");var n=f.attr_("pointClickCallback");var j=null;if(n){var l=-1;var m=Number.MAX_VALUE;for(var e=0;e<f.selPoints_.length;e++){var c=f.selPoints_[e];var a=Math.pow(c.canvasx-d.dragEndX,2)+Math.pow(c.canvasy-d.dragEndY,2);if(!isNaN(a)&&(l==-1||a<m)){m=a;l=e}}var h=f.attr_("highlightCircleSize")+2;if(m<=h*h){j=f.selPoints_[l]}}if(j){n(b,j)}if(k){k(b,f.lastx_,f.selPoints_)}};Dygraph.Interaction.endZoom=function(c,b,a){a.isZooming=false;a.dragEndX=b.dragGetX_(c,a);a.dragEndY=b.dragGetY_(c,a);var e=Math.abs(a.dragEndX-a.dragStartX);var d=Math.abs(a.dragEndY-a.dragStartY);if(e<2&&d<2&&b.lastx_!==undefined&&b.lastx_!=-1){Dygraph.Interaction.treatMouseOpAsClick(b,c,a)}if(e>=10&&a.dragDirection==Dygraph.HORIZONTAL){b.doZoomX_(Math.min(a.dragStartX,a.dragEndX),Math.max(a.dragStartX,a.dragEndX))}else{if(d>=10&&a.dragDirection==Dygraph.VERTICAL){b.doZoomY_(Math.min(a.dragStartY,a.dragEndY),Math.max(a.dragStartY,a.dragEndY))}else{b.clearZoomRect_()}}a.dragStartX=null;a.dragStartY=null};Dygraph.Interaction.defaultModel={mousedown:function(c,b,a){a.initializeMouseDown(c,b,a);if(c.altKey||c.shiftKey){Dygraph.startPan(c,b,a)}else{Dygraph.startZoom(c,b,a)}},mousemove:function(c,b,a){if(a.isZooming){Dygraph.moveZoom(c,b,a)}else{if(a.isPanning){Dygraph.movePan(c,b,a)}}},mouseup:function(c,b,a){if(a.isZooming){Dygraph.endZoom(c,b,a)}else{if(a.isPanning){Dygraph.endPan(c,b,a)}}},mouseout:function(c,b,a){if(a.isZooming){a.dragEndX=null;a.dragEndY=null}},dblclick:function(c,b,a){if(c.altKey||c.shiftKey){return}b.doUnzoom_()}};Dygraph.DEFAULT_ATTRS.interactionModel=Dygraph.Interaction.defaultModel;Dygraph.defaultInteractionModel=Dygraph.Interaction.defaultModel;Dygraph.endZoom=Dygraph.Interaction.endZoom;Dygraph.moveZoom=Dygraph.Interaction.moveZoom;Dygraph.startZoom=Dygraph.Interaction.startZoom;Dygraph.endPan=Dygraph.Interaction.endPan;Dygraph.movePan=Dygraph.Interaction.movePan;Dygraph.startPan=Dygraph.Interaction.startPan;Dygraph.Interaction.nonInteractiveModel_={mousedown:function(c,b,a){a.initializeMouseDown(c,b,a)},mouseup:function(c,b,a){a.dragEndX=b.dragGetX_(c,a);a.dragEndY=b.dragGetY_(c,a);var e=Math.abs(a.dragEndX-a.dragStartX);var d=Math.abs(a.dragEndY-a.dragStartY);if(e<2&&d<2&&b.lastx_!==undefined&&b.lastx_!=-1){Dygraph.Interaction.treatMouseOpAsClick(b,c,a)}}};"use strict";var DygraphRangeSelector=function(a){this.isIE_=/MSIE/.test(navigator.userAgent)&&!window.opera;this.isUsingExcanvas_=a.isUsingExcanvas_;this.dygraph_=a;this.createCanvases_();if(this.isUsingExcanvas_){this.createIEPanOverlay_()}this.createZoomHandles_();this.initInteraction_()};DygraphRangeSelector.prototype.addToGraph=function(a,b){this.layout_=b;this.resize_();a.appendChild(this.bgcanvas_);a.appendChild(this.fgcanvas_);a.appendChild(this.leftZoomHandle_);a.appendChild(this.rightZoomHandle_)};DygraphRangeSelector.prototype.renderStaticLayer=function(){this.resize_();this.drawStaticLayer_()};DygraphRangeSelector.prototype.renderInteractiveLayer=function(){if(this.isChangingRange_){return}this.placeZoomHandles_();this.drawInteractiveLayer_()};DygraphRangeSelector.prototype.resize_=function(){function c(d,e){d.style.top=e.y+"px";d.style.left=e.x+"px";d.width=e.w;d.height=e.h;d.style.width=d.width+"px";d.style.height=d.height+"px"}var b=this.layout_.getPlotArea();var a=this.attr_("axisLabelFontSize")+2*this.attr_("axisTickSize");this.canvasRect_={x:b.x,y:b.y+b.h+a+4,w:b.w,h:this.attr_("rangeSelectorHeight")};c(this.bgcanvas_,this.canvasRect_);c(this.fgcanvas_,this.canvasRect_)};DygraphRangeSelector.prototype.attr_=function(a){return this.dygraph_.attr_(a)};DygraphRangeSelector.prototype.createCanvases_=function(){this.bgcanvas_=Dygraph.createCanvas();this.bgcanvas_.className="dygraph-rangesel-bgcanvas";this.bgcanvas_.style.position="absolute";this.bgcanvas_.style.zIndex=9;this.bgcanvas_ctx_=Dygraph.getContext(this.bgcanvas_);this.fgcanvas_=Dygraph.createCanvas();this.fgcanvas_.className="dygraph-rangesel-fgcanvas";this.fgcanvas_.style.position="absolute";this.fgcanvas_.style.zIndex=9;this.fgcanvas_.style.cursor="default";this.fgcanvas_ctx_=Dygraph.getContext(this.fgcanvas_)};DygraphRangeSelector.prototype.createIEPanOverlay_=function(){this.iePanOverlay_=document.createElement("div");this.iePanOverlay_.style.position="absolute";this.iePanOverlay_.style.backgroundColor="white";this.iePanOverlay_.style.filter="alpha(opacity=0)";this.iePanOverlay_.style.display="none";this.iePanOverlay_.style.cursor="move";this.fgcanvas_.appendChild(this.iePanOverlay_)};DygraphRangeSelector.prototype.createZoomHandles_=function(){var a=new Image();a.className="dygraph-rangesel-zoomhandle";a.style.position="absolute";a.style.zIndex=10;a.style.visibility="hidden";a.style.cursor="col-resize";if(/MSIE 7/.test(navigator.userAgent)){a.width=7;a.height=14;a.style.backgroundColor="white";a.style.border="1px solid #333333"}else{a.width=9;a.height=16;a.src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAkAAAAQCAYAAADESFVDAAAAAXNSR0IArs4c6QAAAAZiS0dEANAAzwDP4Z7KegAAAAlwSFlzAAAOxAAADsQBlSsOGwAAAAd0SU1FB9sHGw0cMqdt1UwAAAAZdEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIEdJTVBXgQ4XAAAAaElEQVQoz+3SsRFAQBCF4Z9WJM8KCDVwownl6YXsTmCUsyKGkZzcl7zkz3YLkypgAnreFmDEpHkIwVOMfpdi9CEEN2nGpFdwD03yEqDtOgCaun7sqSTDH32I1pQA2Pb9sZecAxc5r3IAb21d6878xsAAAAAASUVORK5CYII="}this.leftZoomHandle_=a;this.rightZoomHandle_=a.cloneNode(false)};DygraphRangeSelector.prototype.initInteraction_=function(){var i=this;var f=this.isIE_?document:window;var k=0;var p=null;var n=false;var c=false;var j,d,m,g,r,e,s,o,l,b,h;j=function(x){var w=i.dygraph_.xAxisExtremes();var u=(w[1]-w[0])/i.canvasRect_.w;var v=w[0]+(x.leftHandlePos-i.canvasRect_.x)*u;var t=w[0]+(x.rightHandlePos-i.canvasRect_.x)*u;return[v,t]};d=function(t){Dygraph.cancelEvent(t);n=true;k=t.screenX;p=t.target?t.target:t.srcElement;Dygraph.addEvent(f,"mousemove",m);Dygraph.addEvent(f,"mouseup",g);i.fgcanvas_.style.cursor="col-resize"};m=function(x){if(!n){return}var u=x.screenX-k;if(Math.abs(u)<4){return}k=x.screenX;var w=i.getZoomHandleStatus_();var t;if(p==i.leftZoomHandle_){t=w.leftHandlePos+u;t=Math.min(t,w.rightHandlePos-p.width-3);t=Math.max(t,i.canvasRect_.x)}else{t=w.rightHandlePos+u;t=Math.min(t,i.canvasRect_.x+i.canvasRect_.w);t=Math.max(t,w.leftHandlePos+p.width+3)}var v=p.width/2;p.style.left=(t-v)+"px";i.drawInteractiveLayer_();if(!i.isUsingExcanvas_){r()}};g=function(t){if(!n){return}n=false;Dygraph.removeEvent(f,"mousemove",m);Dygraph.removeEvent(f,"mouseup",g);i.fgcanvas_.style.cursor="default";if(i.isUsingExcanvas_){r()}};r=function(){try{var u=i.getZoomHandleStatus_();i.isChangingRange_=true;if(!u.isZoomed){i.dygraph_.doUnzoom_()}else{var t=j(u);i.dygraph_.doZoomXDates_(t[0],t[1])}}finally{i.isChangingRange_=false}};e=function(v){if(i.isUsingExcanvas_){return v.srcElement==i.iePanOverlay_}else{var t=i.canvasRect_.x+(v.layerX!==undefined?v.layerX:v.offsetX);var u=i.getZoomHandleStatus_();return(t>u.leftHandlePos&&t<u.rightHandlePos)}};s=function(t){if(!c&&e(t)&&i.getZoomHandleStatus_().isZoomed){Dygraph.cancelEvent(t);c=true;k=t.screenX;Dygraph.addEvent(f,"mousemove",o);Dygraph.addEvent(f,"mouseup",l)}};o=function(x){if(!c){return}Dygraph.cancelEvent(x);var u=x.screenX-k;if(Math.abs(u)<4){return}k=x.screenX;var w=i.getZoomHandleStatus_();var z=w.leftHandlePos;var t=w.rightHandlePos;var y=t-z;if(z+u<=i.canvasRect_.x){z=i.canvasRect_.x;t=z+y}else{if(t+u>=i.canvasRect_.x+i.canvasRect_.w){t=i.canvasRect_.x+i.canvasRect_.w;z=t-y}else{z+=u;t+=u}}var v=i.leftZoomHandle_.width/2;i.leftZoomHandle_.style.left=(z-v)+"px";i.rightZoomHandle_.style.left=(t-v)+"px";i.drawInteractiveLayer_();if(!i.isUsingExcanvas_){b()}};l=function(t){if(!c){return}c=false;Dygraph.removeEvent(f,"mousemove",o);Dygraph.removeEvent(f,"mouseup",l);if(i.isUsingExcanvas_){b()}};b=function(){try{i.isChangingRange_=true;i.dygraph_.dateWindow_=j(i.getZoomHandleStatus_());i.dygraph_.drawGraph_(false)}finally{i.isChangingRange_=false}};h=function(t){if(n||c){return}var u=e(t)?"move":"default";if(u!=i.fgcanvas_.style.cursor){i.fgcanvas_.style.cursor=u}};var q={mousedown:function(v,u,t){t.initializeMouseDown(v,u,t);Dygraph.startPan(v,u,t)},mousemove:function(v,u,t){if(t.isPanning){Dygraph.movePan(v,u,t)}},mouseup:function(v,u,t){if(t.isPanning){Dygraph.endPan(v,u,t)}}};this.dygraph_.attrs_.interactionModel=q;this.dygraph_.attrs_.panEdgeFraction=0.0001;var a=window.opera?"mousedown":"dragstart";Dygraph.addEvent(this.leftZoomHandle_,a,d);Dygraph.addEvent(this.rightZoomHandle_,a,d);if(this.isUsingExcanvas_){Dygraph.addEvent(this.iePanOverlay_,"mousedown",s)}else{Dygraph.addEvent(this.fgcanvas_,"mousedown",s);Dygraph.addEvent(this.fgcanvas_,"mousemove",h)}};DygraphRangeSelector.prototype.drawStaticLayer_=function(){var a=this.bgcanvas_ctx_;a.clearRect(0,0,this.canvasRect_.w,this.canvasRect_.h);try{this.drawMiniPlot_()}catch(b){Dygraph.warn(b)}var c=0.5;this.bgcanvas_ctx_.lineWidth=1;a.strokeStyle="gray";a.beginPath();a.moveTo(c,c);a.lineTo(c,this.canvasRect_.h-c);a.lineTo(this.canvasRect_.w-c,this.canvasRect_.h-c);a.lineTo(this.canvasRect_.w-c,c);a.stroke()};DygraphRangeSelector.prototype.drawMiniPlot_=function(){var p=this.attr_("rangeSelectorPlotFillColor");var l=this.attr_("rangeSelectorPlotStrokeColor");if(!p&&!l){return}var m=this.computeCombinedSeriesAndLimits_();var e=m.yMax-m.yMin;var r=this.bgcanvas_ctx_;var f=0.5;var j=this.dygraph_.xAxisExtremes();var b=Math.max(j[1]-j[0],1e-30);var q=(this.canvasRect_.w-f)/b;var o=(this.canvasRect_.h-f)/e;var d=this.canvasRect_.w-f;var h=this.canvasRect_.h-f;r.beginPath();r.moveTo(f,h);for(var g=0;g<m.data.length;g++){var a=m.data[g];var n=(a[0]-j[0])*q;var k=h-(a[1]-m.yMin)*o;if(isFinite(n)&&isFinite(k)){r.lineTo(n,k)}}r.lineTo(d,h);r.closePath();if(p){var c=this.bgcanvas_ctx_.createLinearGradient(0,0,0,h);c.addColorStop(0,"white");c.addColorStop(1,p);this.bgcanvas_ctx_.fillStyle=c;r.fill()}if(l){this.bgcanvas_ctx_.strokeStyle=l;this.bgcanvas_ctx_.lineWidth=1.5;r.stroke()}};DygraphRangeSelector.prototype.computeCombinedSeriesAndLimits_=function(){var u=this.dygraph_.rawData_;var t=this.attr_("logscale");var p=[];var c;var g;var f,m;var l;var s,r,q;for(s=0;s<u.length;s++){if(u[s].length>1&&u[s][1]!=null){l=typeof u[s][1]!="number";if(l){c=[];g=[];for(q=0;q<u[s][1].length;q++){c.push(0);g.push(0)}}break}}for(s=0;s<u.length;s++){var h=u[s];var d=h[0];if(l){for(q=0;q<c.length;q++){c[q]=g[q]=0}}else{c=g=0}for(r=1;r<h.length;r++){if(this.dygraph_.visibility()[r-1]){if(l){for(q=0;q<c.length;q++){m=h[r][q];if(m===null||isNaN(m)){continue}c[q]+=m;g[q]++}}else{m=h[r];if(m===null||isNaN(m)){continue}c+=m;g++}}}if(l){for(q=0;q<c.length;q++){c[q]/=g[q]}f=c.slice(0)}else{f=c/g}p.push([d,f])}p=this.dygraph_.rollingAverage(p,this.dygraph_.rollPeriod_);if(typeof p[0][1]!="number"){for(s=0;s<p.length;s++){f=p[s][1];p[s][1]=f[0]}}var a=Number.MAX_VALUE;var b=-Number.MAX_VALUE;for(s=0;s<p.length;s++){f=p[s][1];if(f!==null&&isFinite(f)&&(!t||f>0)){a=Math.min(a,f);b=Math.max(b,f)}}var n=0.25;if(t){b=Dygraph.log10(b);b+=b*n;a=Dygraph.log10(a);for(s=0;s<p.length;s++){p[s][1]=Dygraph.log10(p[s][1])}}else{var e;var o=b-a;if(o<=Number.MIN_VALUE){e=b*n}else{e=o*n}b+=e;a-=e}return{data:p,yMin:a,yMax:b}};DygraphRangeSelector.prototype.placeZoomHandles_=function(){var g=this.dygraph_.xAxisExtremes();var a=this.dygraph_.xAxisRange();var b=g[1]-g[0];var i=Math.max(0,(a[0]-g[0])/b);var e=Math.max(0,(g[1]-a[1])/b);var h=this.canvasRect_.x+this.canvasRect_.w*i;var d=this.canvasRect_.x+this.canvasRect_.w*(1-e);var c=Math.max(this.canvasRect_.y,this.canvasRect_.y+(this.canvasRect_.h-this.leftZoomHandle_.height)/2);var f=this.leftZoomHandle_.width/2;this.leftZoomHandle_.style.left=(h-f)+"px";this.leftZoomHandle_.style.top=c+"px";this.rightZoomHandle_.style.left=(d-f)+"px";this.rightZoomHandle_.style.top=this.leftZoomHandle_.style.top;this.leftZoomHandle_.style.visibility="visible";this.rightZoomHandle_.style.visibility="visible"};DygraphRangeSelector.prototype.drawInteractiveLayer_=function(){var b=this.fgcanvas_ctx_;b.clearRect(0,0,this.canvasRect_.w,this.canvasRect_.h);var e=1;var d=this.canvasRect_.w-e;var a=this.canvasRect_.h-e;var g=this.getZoomHandleStatus_();b.strokeStyle="black";if(!g.isZoomed){b.beginPath();b.moveTo(e,e);b.lineTo(e,a);b.lineTo(d,a);b.lineTo(d,e);b.stroke();if(this.iePanOverlay_){this.iePanOverlay_.style.display="none"}}else{var f=Math.max(e,g.leftHandlePos-this.canvasRect_.x);var c=Math.min(d,g.rightHandlePos-this.canvasRect_.x);b.fillStyle="rgba(240, 240, 240, 0.6)";b.fillRect(0,0,f,this.canvasRect_.h);b.fillRect(c,0,this.canvasRect_.w-c,this.canvasRect_.h);b.beginPath();b.moveTo(e,e);b.lineTo(f,e);b.lineTo(f,a);b.lineTo(c,a);b.lineTo(c,e);b.lineTo(d,e);b.stroke();if(this.isUsingExcanvas_){this.iePanOverlay_.style.width=(c-f)+"px";this.iePanOverlay_.style.left=f+"px";this.iePanOverlay_.style.height=a+"px";this.iePanOverlay_.style.display="inline"}}};DygraphRangeSelector.prototype.getZoomHandleStatus_=function(){var b=this.leftZoomHandle_.width/2;var c=parseInt(this.leftZoomHandle_.style.left,10)+b;var a=parseInt(this.rightZoomHandle_.style.left,10)+b;return{leftHandlePos:c,rightHandlePos:a,isZoomed:(c-1>this.canvasRect_.x||a+1<this.canvasRect_.x+this.canvasRect_.w)}};"use strict";Dygraph.numericTicks=function(I,H,w,r,d,s){var C=r("pixelsPerLabel");var J=[];var F,D,v,A;if(s){for(F=0;F<s.length;F++){J.push({v:s[F]})}}else{if(r("logscale")){A=Math.floor(w/C);var o=Dygraph.binarySearch(I,Dygraph.PREFERRED_LOG_TICK_VALUES,1);var K=Dygraph.binarySearch(H,Dygraph.PREFERRED_LOG_TICK_VALUES,-1);if(o==-1){o=0}if(K==-1){K=Dygraph.PREFERRED_LOG_TICK_VALUES.length-1}var u=null;if(K-o>=A/4){for(var t=K;t>=o;t--){var p=Dygraph.PREFERRED_LOG_TICK_VALUES[t];var m=Math.log(p/I)/Math.log(H/I)*w;var G={v:p};if(u===null){u={tickValue:p,pixel_coord:m}}else{if(Math.abs(m-u.pixel_coord)>=C){u={tickValue:p,pixel_coord:m}}else{G.label=""}}J.push(G)}J.reverse()}}if(J.length===0){var h=r("labelsKMG2");var q;if(h){q=[1,2,4,8]}else{q=[1,2,5]}var L,z,c;for(F=-10;F<50;F++){var g;if(h){g=Math.pow(16,F)}else{g=Math.pow(10,F)}var f=0;for(D=0;D<q.length;D++){L=g*q[D];z=Math.floor(I/L)*L;c=Math.ceil(H/L)*L;A=Math.abs(c-z)/L;f=w/A;if(f>C){break}}if(f>C){break}}if(z>c){L*=-1}for(F=0;F<A;F++){v=z+F*L;J.push({v:v})}}}var B;var y=[];if(r("labelsKMB")){B=1000;y=["K","M","B","T"]}if(r("labelsKMG2")){if(B){Dygraph.warn("Setting both labelsKMB and labelsKMG2. Pick one!")}B=1024;y=["k","M","G","T"]}var E=r("axisLabelFormatter");for(F=0;F<J.length;F++){if(J[F].label!==undefined){continue}v=J[F].v;var e=Math.abs(v);var l=E(v,0,r,d);if(y.length>0){var x=B*B*B*B;for(D=3;D>=0;D--,x/=B){if(e>=x){l=Dygraph.round_(v/x,r("digitsAfterDecimal"))+y[D];break}}}J[F].label=l}return J};Dygraph.dateTicker=function(e,c,i,g,f,h){var d=Dygraph.pickDateTickGranularity(e,c,i,g);if(d>=0){return Dygraph.getDateAxis(e,c,d,g,f)}else{return[]}};Dygraph.SECONDLY=0;Dygraph.TWO_SECONDLY=1;Dygraph.FIVE_SECONDLY=2;Dygraph.TEN_SECONDLY=3;Dygraph.THIRTY_SECONDLY=4;Dygraph.MINUTELY=5;Dygraph.TWO_MINUTELY=6;Dygraph.FIVE_MINUTELY=7;Dygraph.TEN_MINUTELY=8;Dygraph.THIRTY_MINUTELY=9;Dygraph.HOURLY=10;Dygraph.TWO_HOURLY=11;Dygraph.SIX_HOURLY=12;Dygraph.DAILY=13;Dygraph.WEEKLY=14;Dygraph.MONTHLY=15;Dygraph.QUARTERLY=16;Dygraph.BIANNUAL=17;Dygraph.ANNUAL=18;Dygraph.DECADAL=19;Dygraph.CENTENNIAL=20;Dygraph.NUM_GRANULARITIES=21;Dygraph.SHORT_SPACINGS=[];Dygraph.SHORT_SPACINGS[Dygraph.SECONDLY]=1000*1;Dygraph.SHORT_SPACINGS[Dygraph.TWO_SECONDLY]=1000*2;Dygraph.SHORT_SPACINGS[Dygraph.FIVE_SECONDLY]=1000*5;Dygraph.SHORT_SPACINGS[Dygraph.TEN_SECONDLY]=1000*10;Dygraph.SHORT_SPACINGS[Dygraph.THIRTY_SECONDLY]=1000*30;Dygraph.SHORT_SPACINGS[Dygraph.MINUTELY]=1000*60;Dygraph.SHORT_SPACINGS[Dygraph.TWO_MINUTELY]=1000*60*2;Dygraph.SHORT_SPACINGS[Dygraph.FIVE_MINUTELY]=1000*60*5;Dygraph.SHORT_SPACINGS[Dygraph.TEN_MINUTELY]=1000*60*10;Dygraph.SHORT_SPACINGS[Dygraph.THIRTY_MINUTELY]=1000*60*30;Dygraph.SHORT_SPACINGS[Dygraph.HOURLY]=1000*3600;Dygraph.SHORT_SPACINGS[Dygraph.TWO_HOURLY]=1000*3600*2;Dygraph.SHORT_SPACINGS[Dygraph.SIX_HOURLY]=1000*3600*6;Dygraph.SHORT_SPACINGS[Dygraph.DAILY]=1000*86400;Dygraph.SHORT_SPACINGS[Dygraph.WEEKLY]=1000*604800;Dygraph.PREFERRED_LOG_TICK_VALUES=function(){var c=[];for(var b=-39;b<=39;b++){var a=Math.pow(10,b);for(var d=1;d<=9;d++){var e=a*d;c.push(e)}}return c}();Dygraph.pickDateTickGranularity=function(d,c,j,h){var g=h("pixelsPerLabel");for(var f=0;f<Dygraph.NUM_GRANULARITIES;f++){var e=Dygraph.numDateTicks(d,c,f);if(j/e>=g){return f}}return -1};Dygraph.numDateTicks=function(e,b,g){if(g<Dygraph.MONTHLY){var h=Dygraph.SHORT_SPACINGS[g];return Math.floor(0.5+1*(b-e)/h)}else{var f=1;var d=12;if(g==Dygraph.QUARTERLY){d=3}if(g==Dygraph.BIANNUAL){d=2}if(g==Dygraph.ANNUAL){d=1}if(g==Dygraph.DECADAL){d=1;f=10}if(g==Dygraph.CENTENNIAL){d=1;f=100}var c=365.2524*24*3600*1000;var a=1*(b-e)/c;return Math.floor(0.5+1*a*d/f)}};Dygraph.getDateAxis=function(n,h,a,l,w){var u=l("axisLabelFormatter");var z=[];var k;if(a<Dygraph.MONTHLY){var c=Dygraph.SHORT_SPACINGS[a];var v=c/1000;var y=new Date(n);var f;if(v<=60){f=y.getSeconds();y.setSeconds(f-f%v)}else{y.setSeconds(0);v/=60;if(v<=60){f=y.getMinutes();y.setMinutes(f-f%v)}else{y.setMinutes(0);v/=60;if(v<=24){f=y.getHours();y.setHours(f-f%v)}else{y.setHours(0);v/=24;if(v==7){y.setDate(y.getDate()-y.getDay())}}}}n=y.getTime();for(k=n;k<=h;k+=c){z.push({v:k,label:u(new Date(k),a,l,w)})}}else{var e;var o=1;if(a==Dygraph.MONTHLY){e=[0,1,2,3,4,5,6,7,8,9,10,11]}else{if(a==Dygraph.QUARTERLY){e=[0,3,6,9]}else{if(a==Dygraph.BIANNUAL){e=[0,6]}else{if(a==Dygraph.ANNUAL){e=[0]}else{if(a==Dygraph.DECADAL){e=[0];o=10}else{if(a==Dygraph.CENTENNIAL){e=[0];o=100}else{Dygraph.warn("Span of dates is too long")}}}}}}var s=new Date(n).getFullYear();var p=new Date(h).getFullYear();var b=Dygraph.zeropad;for(var r=s;r<=p;r++){if(r%o!==0){continue}for(var q=0;q<e.length;q++){var m=r+"/"+b(1+e[q])+"/01";k=Dygraph.dateStrToMillis(m);if(k<n||k>h){continue}z.push({v:k,label:u(new Date(k),a,l,w)})}}}return z};Dygraph.DEFAULT_ATTRS.axes.x.ticker=Dygraph.dateTicker;Dygraph.DEFAULT_ATTRS.axes.y.ticker=Dygraph.numericTicks;Dygraph.DEFAULT_ATTRS.axes.y2.ticker=Dygraph.numericTicks;"use strict";function RGBColor(f){this.ok=false;if(f.charAt(0)=="#"){f=f.substr(1,6)}f=f.replace(/ /g,"");f=f.toLowerCase();var b={aliceblue:"f0f8ff",antiquewhite:"faebd7",aqua:"00ffff",aquamarine:"7fffd4",azure:"f0ffff",beige:"f5f5dc",bisque:"ffe4c4",black:"000000",blanchedalmond:"ffebcd",blue:"0000ff",blueviolet:"8a2be2",brown:"a52a2a",burlywood:"deb887",cadetblue:"5f9ea0",chartreuse:"7fff00",chocolate:"d2691e",coral:"ff7f50",cornflowerblue:"6495ed",cornsilk:"fff8dc",crimson:"dc143c",cyan:"00ffff",darkblue:"00008b",darkcyan:"008b8b",darkgoldenrod:"b8860b",darkgray:"a9a9a9",darkgreen:"006400",darkkhaki:"bdb76b",darkmagenta:"8b008b",darkolivegreen:"556b2f",darkorange:"ff8c00",darkorchid:"9932cc",darkred:"8b0000",darksalmon:"e9967a",darkseagreen:"8fbc8f",darkslateblue:"483d8b",darkslategray:"2f4f4f",darkturquoise:"00ced1",darkviolet:"9400d3",deeppink:"ff1493",deepskyblue:"00bfff",dimgray:"696969",dodgerblue:"1e90ff",feldspar:"d19275",firebrick:"b22222",floralwhite:"fffaf0",forestgreen:"228b22",fuchsia:"ff00ff",gainsboro:"dcdcdc",ghostwhite:"f8f8ff",gold:"ffd700",goldenrod:"daa520",gray:"808080",green:"008000",greenyellow:"adff2f",honeydew:"f0fff0",hotpink:"ff69b4",indianred:"cd5c5c",indigo:"4b0082",ivory:"fffff0",khaki:"f0e68c",lavender:"e6e6fa",lavenderblush:"fff0f5",lawngreen:"7cfc00",lemonchiffon:"fffacd",lightblue:"add8e6",lightcoral:"f08080",lightcyan:"e0ffff",lightgoldenrodyellow:"fafad2",lightgrey:"d3d3d3",lightgreen:"90ee90",lightpink:"ffb6c1",lightsalmon:"ffa07a",lightseagreen:"20b2aa",lightskyblue:"87cefa",lightslateblue:"8470ff",lightslategray:"778899",lightsteelblue:"b0c4de",lightyellow:"ffffe0",lime:"00ff00",limegreen:"32cd32",linen:"faf0e6",magenta:"ff00ff",maroon:"800000",mediumaquamarine:"66cdaa",mediumblue:"0000cd",mediumorchid:"ba55d3",mediumpurple:"9370d8",mediumseagreen:"3cb371",mediumslateblue:"7b68ee",mediumspringgreen:"00fa9a",mediumturquoise:"48d1cc",mediumvioletred:"c71585",midnightblue:"191970",mintcream:"f5fffa",mistyrose:"ffe4e1",moccasin:"ffe4b5",navajowhite:"ffdead",navy:"000080",oldlace:"fdf5e6",olive:"808000",olivedrab:"6b8e23",orange:"ffa500",orangered:"ff4500",orchid:"da70d6",palegoldenrod:"eee8aa",palegreen:"98fb98",paleturquoise:"afeeee",palevioletred:"d87093",papayawhip:"ffefd5",peachpuff:"ffdab9",peru:"cd853f",pink:"ffc0cb",plum:"dda0dd",powderblue:"b0e0e6",purple:"800080",red:"ff0000",rosybrown:"bc8f8f",royalblue:"4169e1",saddlebrown:"8b4513",salmon:"fa8072",sandybrown:"f4a460",seagreen:"2e8b57",seashell:"fff5ee",sienna:"a0522d",silver:"c0c0c0",skyblue:"87ceeb",slateblue:"6a5acd",slategray:"708090",snow:"fffafa",springgreen:"00ff7f",steelblue:"4682b4",tan:"d2b48c",teal:"008080",thistle:"d8bfd8",tomato:"ff6347",turquoise:"40e0d0",violet:"ee82ee",violetred:"d02090",wheat:"f5deb3",white:"ffffff",whitesmoke:"f5f5f5",yellow:"ffff00",yellowgreen:"9acd32"};for(var g in b){if(f==g){f=b[g]}}var e=[{re:/^rgb\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})\)$/,example:["rgb(123, 234, 45)","rgb(255,234,245)"],process:function(i){return[parseInt(i[1]),parseInt(i[2]),parseInt(i[3])]}},{re:/^(\w{2})(\w{2})(\w{2})$/,example:["#00ff00","336699"],process:function(i){return[parseInt(i[1],16),parseInt(i[2],16),parseInt(i[3],16)]}},{re:/^(\w{1})(\w{1})(\w{1})$/,example:["#fb0","f0f"],process:function(i){return[parseInt(i[1]+i[1],16),parseInt(i[2]+i[2],16),parseInt(i[3]+i[3],16)]}}];for(var c=0;c<e.length;c++){var j=e[c].re;var a=e[c].process;var h=j.exec(f);if(h){var d=a(h);this.r=d[0];this.g=d[1];this.b=d[2];this.ok=true}}this.r=(this.r<0||isNaN(this.r))?0:((this.r>255)?255:this.r);this.g=(this.g<0||isNaN(this.g))?0:((this.g>255)?255:this.g);this.b=(this.b<0||isNaN(this.b))?0:((this.b>255)?255:this.b);this.toRGB=function(){return"rgb("+this.r+", "+this.g+", "+this.b+")"};this.toHex=function(){var l=this.r.toString(16);var k=this.g.toString(16);var i=this.b.toString(16);if(l.length==1){l="0"+l}if(k.length==1){k="0"+k}if(i.length==1){i="0"+i}return"#"+l+k+i}}Date.ext={};Date.ext.util={};Date.ext.util.xPad=function(a,c,b){if(typeof(b)=="undefined"){b=10}for(;parseInt(a,10)<b&&b>1;b/=10){a=c.toString()+a}return a.toString()};Date.prototype.locale="en-GB";if(document.getElementsByTagName("html")&&document.getElementsByTagName("html")[0].lang){Date.prototype.locale=document.getElementsByTagName("html")[0].lang}Date.ext.locales={};Date.ext.locales.en={a:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],A:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],b:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],B:["January","February","March","April","May","June","July","August","September","October","November","December"],c:"%a %d %b %Y %T %Z",p:["AM","PM"],P:["am","pm"],x:"%d/%m/%y",X:"%T"};Date.ext.locales["en-US"]=Date.ext.locales.en;Date.ext.locales["en-US"].c="%a %d %b %Y %r %Z";Date.ext.locales["en-US"].x="%D";Date.ext.locales["en-US"].X="%r";Date.ext.locales["en-GB"]=Date.ext.locales.en;Date.ext.locales["en-AU"]=Date.ext.locales["en-GB"];Date.ext.formats={a:function(a){return Date.ext.locales[a.locale].a[a.getDay()]},A:function(a){return Date.ext.locales[a.locale].A[a.getDay()]},b:function(a){return Date.ext.locales[a.locale].b[a.getMonth()]},B:function(a){return Date.ext.locales[a.locale].B[a.getMonth()]},c:"toLocaleString",C:function(a){return Date.ext.util.xPad(parseInt(a.getFullYear()/100,10),0)},d:["getDate","0"],e:["getDate"," "],g:function(a){return Date.ext.util.xPad(parseInt(Date.ext.util.G(a)/100,10),0)},G:function(c){var e=c.getFullYear();var b=parseInt(Date.ext.formats.V(c),10);var a=parseInt(Date.ext.formats.W(c),10);if(a>b){e++}else{if(a===0&&b>=52){e--}}return e},H:["getHours","0"],I:function(b){var a=b.getHours()%12;return Date.ext.util.xPad(a===0?12:a,0)},j:function(c){var a=c-new Date(""+c.getFullYear()+"/1/1 GMT");a+=c.getTimezoneOffset()*60000;var b=parseInt(a/60000/60/24,10)+1;return Date.ext.util.xPad(b,0,100)},m:function(a){return Date.ext.util.xPad(a.getMonth()+1,0)},M:["getMinutes","0"],p:function(a){return Date.ext.locales[a.locale].p[a.getHours()>=12?1:0]},P:function(a){return Date.ext.locales[a.locale].P[a.getHours()>=12?1:0]},S:["getSeconds","0"],u:function(a){var b=a.getDay();return b===0?7:b},U:function(e){var a=parseInt(Date.ext.formats.j(e),10);var c=6-e.getDay();var b=parseInt((a+c)/7,10);return Date.ext.util.xPad(b,0)},V:function(e){var c=parseInt(Date.ext.formats.W(e),10);var a=(new Date(""+e.getFullYear()+"/1/1")).getDay();var b=c+(a>4||a<=1?0:1);if(b==53&&(new Date(""+e.getFullYear()+"/12/31")).getDay()<4){b=1}else{if(b===0){b=Date.ext.formats.V(new Date(""+(e.getFullYear()-1)+"/12/31"))}}return Date.ext.util.xPad(b,0)},w:"getDay",W:function(e){var a=parseInt(Date.ext.formats.j(e),10);var c=7-Date.ext.formats.u(e);var b=parseInt((a+c)/7,10);return Date.ext.util.xPad(b,0,10)},y:function(a){return Date.ext.util.xPad(a.getFullYear()%100,0)},Y:"getFullYear",z:function(c){var b=c.getTimezoneOffset();var a=Date.ext.util.xPad(parseInt(Math.abs(b/60),10),0);var e=Date.ext.util.xPad(b%60,0);return(b>0?"-":"+")+a+e},Z:function(a){return a.toString().replace(/^.*\(([^)]+)\)$/,"$1")},"%":function(a){return"%"}};Date.ext.aggregates={c:"locale",D:"%m/%d/%y",h:"%b",n:"\n",r:"%I:%M:%S %p",R:"%H:%M",t:"\t",T:"%H:%M:%S",x:"locale",X:"locale"};Date.ext.aggregates.z=Date.ext.formats.z(new Date());Date.ext.aggregates.Z=Date.ext.formats.Z(new Date());Date.ext.unsupported={};Date.prototype.strftime=function(a){if(!(this.locale in Date.ext.locales)){if(this.locale.replace(/-[a-zA-Z]+$/,"") in Date.ext.locales){this.locale=this.locale.replace(/-[a-zA-Z]+$/,"")}else{this.locale="en-GB"}}var c=this;while(a.match(/%[cDhnrRtTxXzZ]/)){a=a.replace(/%([cDhnrRtTxXzZ])/g,function(e,d){var g=Date.ext.aggregates[d];return(g=="locale"?Date.ext.locales[c.locale][d]:g)})}var b=a.replace(/%([aAbBCdegGHIjmMpPSuUVwWyY%])/g,function(e,d){var g=Date.ext.formats[d];if(typeof(g)=="string"){return c[g]()}else{if(typeof(g)=="function"){return g.call(c,c)}else{if(typeof(g)=="object"&&typeof(g[0])=="string"){return Date.ext.util.xPad(c[g[0]](),g[1])}else{return d}}}});c=null;return b};
/trunk/web/ipfm/dygraph/excanvas.js
0,0 → 1,924
// Copyright 2006 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
 
 
// Known Issues:
//
// * Patterns are not implemented.
// * Radial gradient are not implemented. The VML version of these look very
// different from the canvas one.
// * Clipping paths are not implemented.
// * Coordsize. The width and height attribute have higher priority than the
// width and height style values which isn't correct.
// * Painting mode isn't implemented.
// * Canvas width/height should is using content-box by default. IE in
// Quirks mode will draw the canvas using border-box. Either change your
// doctype to HTML5
// (http://www.whatwg.org/specs/web-apps/current-work/#the-doctype)
// or use Box Sizing Behavior from WebFX
// (http://webfx.eae.net/dhtml/boxsizing/boxsizing.html)
// * Non uniform scaling does not correctly scale strokes.
// * Optimize. There is always room for speed improvements.
 
// Only add this code if we do not already have a canvas implementation
if (!document.createElement('canvas').getContext) {
 
(function() {
 
// alias some functions to make (compiled) code shorter
var m = Math;
var mr = m.round;
var ms = m.sin;
var mc = m.cos;
var abs = m.abs;
var sqrt = m.sqrt;
 
// this is used for sub pixel precision
var Z = 10;
var Z2 = Z / 2;
 
/**
* This funtion is assigned to the <canvas> elements as element.getContext().
* @this {HTMLElement}
* @return {CanvasRenderingContext2D_}
*/
function getContext() {
return this.context_ ||
(this.context_ = new CanvasRenderingContext2D_(this));
}
 
var slice = Array.prototype.slice;
 
/**
* Binds a function to an object. The returned function will always use the
* passed in {@code obj} as {@code this}.
*
* Example:
*
* g = bind(f, obj, a, b)
* g(c, d) // will do f.call(obj, a, b, c, d)
*
* @param {Function} f The function to bind the object to
* @param {Object} obj The object that should act as this when the function
* is called
* @param {*} var_args Rest arguments that will be used as the initial
* arguments when the function is called
* @return {Function} A new function that has bound this
*/
function bind(f, obj, var_args) {
var a = slice.call(arguments, 2);
return function() {
return f.apply(obj, a.concat(slice.call(arguments)));
};
}
 
var G_vmlCanvasManager_ = {
init: function(opt_doc) {
if (/MSIE/.test(navigator.userAgent) && !window.opera) {
var doc = opt_doc || document;
// Create a dummy element so that IE will allow canvas elements to be
// recognized.
doc.createElement('canvas');
doc.attachEvent('onreadystatechange', bind(this.init_, this, doc));
}
},
 
init_: function(doc) {
// create xmlns
if (!doc.namespaces['g_vml_']) {
doc.namespaces.add('g_vml_', 'urn:schemas-microsoft-com:vml',
'#default#VML');
 
}
if (!doc.namespaces['g_o_']) {
doc.namespaces.add('g_o_', 'urn:schemas-microsoft-com:office:office',
'#default#VML');
}
 
// Setup default CSS. Only add one style sheet per document
if (!doc.styleSheets['ex_canvas_']) {
var ss = doc.createStyleSheet();
ss.owningElement.id = 'ex_canvas_';
ss.cssText = 'canvas{display:inline-block;overflow:hidden;' +
// default size is 300x150 in Gecko and Opera
'text-align:left;width:300px;height:150px}' +
'g_vml_\\:*{behavior:url(#default#VML)}' +
'g_o_\\:*{behavior:url(#default#VML)}';
 
}
 
// find all canvas elements
var els = doc.getElementsByTagName('canvas');
for (var i = 0; i < els.length; i++) {
this.initElement(els[i]);
}
},
 
/**
* Public initializes a canvas element so that it can be used as canvas
* element from now on. This is called automatically before the page is
* loaded but if you are creating elements using createElement you need to
* make sure this is called on the element.
* @param {HTMLElement} el The canvas element to initialize.
* @return {HTMLElement} the element that was created.
*/
initElement: function(el) {
if (!el.getContext) {
 
el.getContext = getContext;
 
// Remove fallback content. There is no way to hide text nodes so we
// just remove all childNodes. We could hide all elements and remove
// text nodes but who really cares about the fallback content.
el.innerHTML = '';
 
// do not use inline function because that will leak memory
el.attachEvent('onpropertychange', onPropertyChange);
el.attachEvent('onresize', onResize);
 
var attrs = el.attributes;
if (attrs.width && attrs.width.specified) {
// TODO: use runtimeStyle and coordsize
// el.getContext().setWidth_(attrs.width.nodeValue);
el.style.width = attrs.width.nodeValue + 'px';
} else {
el.width = el.clientWidth;
}
if (attrs.height && attrs.height.specified) {
// TODO: use runtimeStyle and coordsize
// el.getContext().setHeight_(attrs.height.nodeValue);
el.style.height = attrs.height.nodeValue + 'px';
} else {
el.height = el.clientHeight;
}
//el.getContext().setCoordsize_()
}
return el;
}
};
 
function onPropertyChange(e) {
var el = e.srcElement;
 
switch (e.propertyName) {
case 'width':
el.style.width = el.attributes.width.nodeValue + 'px';
el.getContext().clearRect();
break;
case 'height':
el.style.height = el.attributes.height.nodeValue + 'px';
el.getContext().clearRect();
break;
}
}
 
function onResize(e) {
var el = e.srcElement;
if (el.firstChild) {
el.firstChild.style.width = el.clientWidth + 'px';
el.firstChild.style.height = el.clientHeight + 'px';
}
}
 
G_vmlCanvasManager_.init();
 
// precompute "00" to "FF"
var dec2hex = [];
for (var i = 0; i < 16; i++) {
for (var j = 0; j < 16; j++) {
dec2hex[i * 16 + j] = i.toString(16) + j.toString(16);
}
}
 
function createMatrixIdentity() {
return [
[1, 0, 0],
[0, 1, 0],
[0, 0, 1]
];
}
 
function matrixMultiply(m1, m2) {
var result = createMatrixIdentity();
 
for (var x = 0; x < 3; x++) {
for (var y = 0; y < 3; y++) {
var sum = 0;
 
for (var z = 0; z < 3; z++) {
sum += m1[x][z] * m2[z][y];
}
 
result[x][y] = sum;
}
}
return result;
}
 
function copyState(o1, o2) {
o2.fillStyle = o1.fillStyle;
o2.lineCap = o1.lineCap;
o2.lineJoin = o1.lineJoin;
o2.lineWidth = o1.lineWidth;
o2.miterLimit = o1.miterLimit;
o2.shadowBlur = o1.shadowBlur;
o2.shadowColor = o1.shadowColor;
o2.shadowOffsetX = o1.shadowOffsetX;
o2.shadowOffsetY = o1.shadowOffsetY;
o2.strokeStyle = o1.strokeStyle;
o2.globalAlpha = o1.globalAlpha;
o2.arcScaleX_ = o1.arcScaleX_;
o2.arcScaleY_ = o1.arcScaleY_;
o2.lineScale_ = o1.lineScale_;
}
 
function processStyle(styleString) {
var str, alpha = 1;
 
styleString = String(styleString);
if (styleString.substring(0, 3) == 'rgb') {
var start = styleString.indexOf('(', 3);
var end = styleString.indexOf(')', start + 1);
var guts = styleString.substring(start + 1, end).split(',');
 
str = '#';
for (var i = 0; i < 3; i++) {
str += dec2hex[Number(guts[i])];
}
 
if (guts.length == 4 && styleString.substr(3, 1) == 'a') {
alpha = guts[3];
}
} else {
str = styleString;
}
 
return {color: str, alpha: alpha};
}
 
function processLineCap(lineCap) {
switch (lineCap) {
case 'butt':
return 'flat';
case 'round':
return 'round';
case 'square':
default:
return 'square';
}
}
 
/**
* This class implements CanvasRenderingContext2D interface as described by
* the WHATWG.
* @param {HTMLElement} surfaceElement The element that the 2D context should
* be associated with
*/
function CanvasRenderingContext2D_(surfaceElement) {
this.m_ = createMatrixIdentity();
 
this.mStack_ = [];
this.aStack_ = [];
this.currentPath_ = [];
 
// Canvas context properties
this.strokeStyle = '#000';
this.fillStyle = '#000';
 
this.lineWidth = 1;
this.lineJoin = 'miter';
this.lineCap = 'butt';
this.miterLimit = Z * 1;
this.globalAlpha = 1;
this.canvas = surfaceElement;
 
var el = surfaceElement.ownerDocument.createElement('div');
el.style.width = surfaceElement.clientWidth + 'px';
el.style.height = surfaceElement.clientHeight + 'px';
el.style.overflow = 'hidden';
el.style.position = 'absolute';
surfaceElement.appendChild(el);
 
this.element_ = el;
this.arcScaleX_ = 1;
this.arcScaleY_ = 1;
this.lineScale_ = 1;
}
 
var contextPrototype = CanvasRenderingContext2D_.prototype;
contextPrototype.clearRect = function() {
this.element_.innerHTML = '';
};
 
contextPrototype.beginPath = function() {
// TODO: Branch current matrix so that save/restore has no effect
// as per safari docs.
this.currentPath_ = [];
};
 
contextPrototype.moveTo = function(aX, aY) {
var p = this.getCoords_(aX, aY);
this.currentPath_.push({type: 'moveTo', x: p.x, y: p.y});
this.currentX_ = p.x;
this.currentY_ = p.y;
};
 
contextPrototype.lineTo = function(aX, aY) {
var p = this.getCoords_(aX, aY);
this.currentPath_.push({type: 'lineTo', x: p.x, y: p.y});
 
this.currentX_ = p.x;
this.currentY_ = p.y;
};
 
contextPrototype.bezierCurveTo = function(aCP1x, aCP1y,
aCP2x, aCP2y,
aX, aY) {
var p = this.getCoords_(aX, aY);
var cp1 = this.getCoords_(aCP1x, aCP1y);
var cp2 = this.getCoords_(aCP2x, aCP2y);
bezierCurveTo(this, cp1, cp2, p);
};
 
// Helper function that takes the already fixed cordinates.
function bezierCurveTo(self, cp1, cp2, p) {
self.currentPath_.push({
type: 'bezierCurveTo',
cp1x: cp1.x,
cp1y: cp1.y,
cp2x: cp2.x,
cp2y: cp2.y,
x: p.x,
y: p.y
});
self.currentX_ = p.x;
self.currentY_ = p.y;
}
 
contextPrototype.quadraticCurveTo = function(aCPx, aCPy, aX, aY) {
// the following is lifted almost directly from
// http://developer.mozilla.org/en/docs/Canvas_tutorial:Drawing_shapes
 
var cp = this.getCoords_(aCPx, aCPy);
var p = this.getCoords_(aX, aY);
 
var cp1 = {
x: this.currentX_ + 2.0 / 3.0 * (cp.x - this.currentX_),
y: this.currentY_ + 2.0 / 3.0 * (cp.y - this.currentY_)
};
var cp2 = {
x: cp1.x + (p.x - this.currentX_) / 3.0,
y: cp1.y + (p.y - this.currentY_) / 3.0
};
 
bezierCurveTo(this, cp1, cp2, p);
};
 
contextPrototype.arc = function(aX, aY, aRadius,
aStartAngle, aEndAngle, aClockwise) {
aRadius *= Z;
var arcType = aClockwise ? 'at' : 'wa';
 
var xStart = aX + mc(aStartAngle) * aRadius - Z2;
var yStart = aY + ms(aStartAngle) * aRadius - Z2;
 
var xEnd = aX + mc(aEndAngle) * aRadius - Z2;
var yEnd = aY + ms(aEndAngle) * aRadius - Z2;
 
// IE won't render arches drawn counter clockwise if xStart == xEnd.
if (xStart == xEnd && !aClockwise) {
xStart += 0.125; // Offset xStart by 1/80 of a pixel. Use something
// that can be represented in binary
}
 
var p = this.getCoords_(aX, aY);
var pStart = this.getCoords_(xStart, yStart);
var pEnd = this.getCoords_(xEnd, yEnd);
 
this.currentPath_.push({type: arcType,
x: p.x,
y: p.y,
radius: aRadius,
xStart: pStart.x,
yStart: pStart.y,
xEnd: pEnd.x,
yEnd: pEnd.y});
 
};
 
contextPrototype.rect = function(aX, aY, aWidth, aHeight) {
this.moveTo(aX, aY);
this.lineTo(aX + aWidth, aY);
this.lineTo(aX + aWidth, aY + aHeight);
this.lineTo(aX, aY + aHeight);
this.closePath();
};
 
contextPrototype.strokeRect = function(aX, aY, aWidth, aHeight) {
var oldPath = this.currentPath_;
this.beginPath();
 
this.moveTo(aX, aY);
this.lineTo(aX + aWidth, aY);
this.lineTo(aX + aWidth, aY + aHeight);
this.lineTo(aX, aY + aHeight);
this.closePath();
this.stroke();
 
this.currentPath_ = oldPath;
};
 
contextPrototype.fillRect = function(aX, aY, aWidth, aHeight) {
var oldPath = this.currentPath_;
this.beginPath();
 
this.moveTo(aX, aY);
this.lineTo(aX + aWidth, aY);
this.lineTo(aX + aWidth, aY + aHeight);
this.lineTo(aX, aY + aHeight);
this.closePath();
this.fill();
 
this.currentPath_ = oldPath;
};
 
contextPrototype.createLinearGradient = function(aX0, aY0, aX1, aY1) {
var gradient = new CanvasGradient_('gradient');
gradient.x0_ = aX0;
gradient.y0_ = aY0;
gradient.x1_ = aX1;
gradient.y1_ = aY1;
return gradient;
};
 
contextPrototype.createRadialGradient = function(aX0, aY0, aR0,
aX1, aY1, aR1) {
var gradient = new CanvasGradient_('gradientradial');
gradient.x0_ = aX0;
gradient.y0_ = aY0;
gradient.r0_ = aR0;
gradient.x1_ = aX1;
gradient.y1_ = aY1;
gradient.r1_ = aR1;
return gradient;
};
 
contextPrototype.drawImage = function(image, var_args) {
var dx, dy, dw, dh, sx, sy, sw, sh;
 
// to find the original width we overide the width and height
var oldRuntimeWidth = image.runtimeStyle.width;
var oldRuntimeHeight = image.runtimeStyle.height;
image.runtimeStyle.width = 'auto';
image.runtimeStyle.height = 'auto';
 
// get the original size
var w = image.width;
var h = image.height;
 
// and remove overides
image.runtimeStyle.width = oldRuntimeWidth;
image.runtimeStyle.height = oldRuntimeHeight;
 
if (arguments.length == 3) {
dx = arguments[1];
dy = arguments[2];
sx = sy = 0;
sw = dw = w;
sh = dh = h;
} else if (arguments.length == 5) {
dx = arguments[1];
dy = arguments[2];
dw = arguments[3];
dh = arguments[4];
sx = sy = 0;
sw = w;
sh = h;
} else if (arguments.length == 9) {
sx = arguments[1];
sy = arguments[2];
sw = arguments[3];
sh = arguments[4];
dx = arguments[5];
dy = arguments[6];
dw = arguments[7];
dh = arguments[8];
} else {
throw Error('Invalid number of arguments');
}
 
var d = this.getCoords_(dx, dy);
 
var w2 = sw / 2;
var h2 = sh / 2;
 
var vmlStr = [];
 
var W = 10;
var H = 10;
 
// For some reason that I've now forgotten, using divs didn't work
vmlStr.push(' <g_vml_:group',
' coordsize="', Z * W, ',', Z * H, '"',
' coordorigin="0,0"' ,
' style="width:', W, 'px;height:', H, 'px;position:absolute;');
 
// If filters are necessary (rotation exists), create them
// filters are bog-slow, so only create them if abbsolutely necessary
// The following check doesn't account for skews (which don't exist
// in the canvas spec (yet) anyway.
 
if (this.m_[0][0] != 1 || this.m_[0][1]) {
var filter = [];
 
// Note the 12/21 reversal
filter.push('M11=', this.m_[0][0], ',',
'M12=', this.m_[1][0], ',',
'M21=', this.m_[0][1], ',',
'M22=', this.m_[1][1], ',',
'Dx=', mr(d.x / Z), ',',
'Dy=', mr(d.y / Z), '');
 
// Bounding box calculation (need to minimize displayed area so that
// filters don't waste time on unused pixels.
var max = d;
var c2 = this.getCoords_(dx + dw, dy);
var c3 = this.getCoords_(dx, dy + dh);
var c4 = this.getCoords_(dx + dw, dy + dh);
 
max.x = m.max(max.x, c2.x, c3.x, c4.x);
max.y = m.max(max.y, c2.y, c3.y, c4.y);
 
vmlStr.push('padding:0 ', mr(max.x / Z), 'px ', mr(max.y / Z),
'px 0;filter:progid:DXImageTransform.Microsoft.Matrix(',
filter.join(''), ", sizingmethod='clip');")
} else {
vmlStr.push('top:', mr(d.y / Z), 'px;left:', mr(d.x / Z), 'px;');
}
 
vmlStr.push(' ">' ,
'<g_vml_:image src="', image.src, '"',
' style="width:', Z * dw, 'px;',
' height:', Z * dh, 'px;"',
' cropleft="', sx / w, '"',
' croptop="', sy / h, '"',
' cropright="', (w - sx - sw) / w, '"',
' cropbottom="', (h - sy - sh) / h, '"',
' />',
'</g_vml_:group>');
 
this.element_.insertAdjacentHTML('BeforeEnd',
vmlStr.join(''));
};
 
contextPrototype.stroke = function(aFill) {
var lineStr = [];
var lineOpen = false;
var a = processStyle(aFill ? this.fillStyle : this.strokeStyle);
var color = a.color;
var opacity = a.alpha * this.globalAlpha;
 
var W = 10;
var H = 10;
 
lineStr.push('<g_vml_:shape',
' filled="', !!aFill, '"',
' style="position:absolute;width:', W, 'px;height:', H, 'px;"',
' coordorigin="0 0" coordsize="', Z * W, ' ', Z * H, '"',
' stroked="', !aFill, '"',
' path="');
 
var newSeq = false;
var min = {x: null, y: null};
var max = {x: null, y: null};
 
for (var i = 0; i < this.currentPath_.length; i++) {
var p = this.currentPath_[i];
var c;
 
switch (p.type) {
case 'moveTo':
c = p;
lineStr.push(' m ', mr(p.x), ',', mr(p.y));
break;
case 'lineTo':
lineStr.push(' l ', mr(p.x), ',', mr(p.y));
break;
case 'close':
lineStr.push(' x ');
p = null;
break;
case 'bezierCurveTo':
lineStr.push(' c ',
mr(p.cp1x), ',', mr(p.cp1y), ',',
mr(p.cp2x), ',', mr(p.cp2y), ',',
mr(p.x), ',', mr(p.y));
break;
case 'at':
case 'wa':
lineStr.push(' ', p.type, ' ',
mr(p.x - this.arcScaleX_ * p.radius), ',',
mr(p.y - this.arcScaleY_ * p.radius), ' ',
mr(p.x + this.arcScaleX_ * p.radius), ',',
mr(p.y + this.arcScaleY_ * p.radius), ' ',
mr(p.xStart), ',', mr(p.yStart), ' ',
mr(p.xEnd), ',', mr(p.yEnd));
break;
}
 
 
// TODO: Following is broken for curves due to
// move to proper paths.
 
// Figure out dimensions so we can do gradient fills
// properly
if (p) {
if (min.x == null || p.x < min.x) {
min.x = p.x;
}
if (max.x == null || p.x > max.x) {
max.x = p.x;
}
if (min.y == null || p.y < min.y) {
min.y = p.y;
}
if (max.y == null || p.y > max.y) {
max.y = p.y;
}
}
}
lineStr.push(' ">');
 
if (!aFill) {
var lineWidth = this.lineScale_ * this.lineWidth;
 
// VML cannot correctly render a line if the width is less than 1px.
// In that case, we dilute the color to make the line look thinner.
if (lineWidth < 1) {
opacity *= lineWidth;
}
 
lineStr.push(
'<g_vml_:stroke',
' opacity="', opacity, '"',
' joinstyle="', this.lineJoin, '"',
' miterlimit="', this.miterLimit, '"',
' endcap="', processLineCap(this.lineCap), '"',
' weight="', lineWidth, 'px"',
' color="', color, '" />'
);
} else if (typeof this.fillStyle == 'object') {
var fillStyle = this.fillStyle;
var angle = 0;
var focus = {x: 0, y: 0};
 
// additional offset
var shift = 0;
// scale factor for offset
var expansion = 1;
 
if (fillStyle.type_ == 'gradient') {
var x0 = fillStyle.x0_ / this.arcScaleX_;
var y0 = fillStyle.y0_ / this.arcScaleY_;
var x1 = fillStyle.x1_ / this.arcScaleX_;
var y1 = fillStyle.y1_ / this.arcScaleY_;
var p0 = this.getCoords_(x0, y0);
var p1 = this.getCoords_(x1, y1);
var dx = p1.x - p0.x;
var dy = p1.y - p0.y;
angle = Math.atan2(dx, dy) * 180 / Math.PI;
 
// The angle should be a non-negative number.
if (angle < 0) {
angle += 360;
}
 
// Very small angles produce an unexpected result because they are
// converted to a scientific notation string.
if (angle < 1e-6) {
angle = 0;
}
} else {
var p0 = this.getCoords_(fillStyle.x0_, fillStyle.y0_);
var width = max.x - min.x;
var height = max.y - min.y;
focus = {
x: (p0.x - min.x) / width,
y: (p0.y - min.y) / height
};
 
width /= this.arcScaleX_ * Z;
height /= this.arcScaleY_ * Z;
var dimension = m.max(width, height);
shift = 2 * fillStyle.r0_ / dimension;
expansion = 2 * fillStyle.r1_ / dimension - shift;
}
 
// We need to sort the color stops in ascending order by offset,
// otherwise IE won't interpret it correctly.
var stops = fillStyle.colors_;
stops.sort(function(cs1, cs2) {
return cs1.offset - cs2.offset;
});
 
var length = stops.length;
var color1 = stops[0].color;
var color2 = stops[length - 1].color;
var opacity1 = stops[0].alpha * this.globalAlpha;
var opacity2 = stops[length - 1].alpha * this.globalAlpha;
 
var colors = [];
for (var i = 0; i < length; i++) {
var stop = stops[i];
colors.push(stop.offset * expansion + shift + ' ' + stop.color);
}
 
// When colors attribute is used, the meanings of opacity and o:opacity2
// are reversed.
lineStr.push('<g_vml_:fill type="', fillStyle.type_, '"',
' method="none" focus="100%"',
' color="', color1, '"',
' color2="', color2, '"',
' colors="', colors.join(','), '"',
' opacity="', opacity2, '"',
' g_o_:opacity2="', opacity1, '"',
' angle="', angle, '"',
' focusposition="', focus.x, ',', focus.y, '" />');
} else {
lineStr.push('<g_vml_:fill color="', color, '" opacity="', opacity,
'" />');
}
 
lineStr.push('</g_vml_:shape>');
 
this.element_.insertAdjacentHTML('beforeEnd', lineStr.join(''));
};
 
contextPrototype.fill = function() {
this.stroke(true);
}
 
contextPrototype.closePath = function() {
this.currentPath_.push({type: 'close'});
};
 
/**
* @private
*/
contextPrototype.getCoords_ = function(aX, aY) {
var m = this.m_;
return {
x: Z * (aX * m[0][0] + aY * m[1][0] + m[2][0]) - Z2,
y: Z * (aX * m[0][1] + aY * m[1][1] + m[2][1]) - Z2
}
};
 
contextPrototype.save = function() {
var o = {};
copyState(this, o);
this.aStack_.push(o);
this.mStack_.push(this.m_);
this.m_ = matrixMultiply(createMatrixIdentity(), this.m_);
};
 
contextPrototype.restore = function() {
copyState(this.aStack_.pop(), this);
this.m_ = this.mStack_.pop();
};
 
function matrixIsFinite(m) {
for (var j = 0; j < 3; j++) {
for (var k = 0; k < 2; k++) {
if (!isFinite(m[j][k]) || isNaN(m[j][k])) {
return false;
}
}
}
return true;
}
 
function setM(ctx, m, updateLineScale) {
if (!matrixIsFinite(m)) {
return;
}
ctx.m_ = m;
 
if (updateLineScale) {
// Get the line scale.
// Determinant of this.m_ means how much the area is enlarged by the
// transformation. So its square root can be used as a scale factor
// for width.
var det = m[0][0] * m[1][1] - m[0][1] * m[1][0];
ctx.lineScale_ = sqrt(abs(det));
}
}
 
contextPrototype.translate = function(aX, aY) {
var m1 = [
[1, 0, 0],
[0, 1, 0],
[aX, aY, 1]
];
 
setM(this, matrixMultiply(m1, this.m_), false);
};
 
contextPrototype.rotate = function(aRot) {
var c = mc(aRot);
var s = ms(aRot);
 
var m1 = [
[c, s, 0],
[-s, c, 0],
[0, 0, 1]
];
 
setM(this, matrixMultiply(m1, this.m_), false);
};
 
contextPrototype.scale = function(aX, aY) {
this.arcScaleX_ *= aX;
this.arcScaleY_ *= aY;
var m1 = [
[aX, 0, 0],
[0, aY, 0],
[0, 0, 1]
];
 
setM(this, matrixMultiply(m1, this.m_), true);
};
 
contextPrototype.transform = function(m11, m12, m21, m22, dx, dy) {
var m1 = [
[m11, m12, 0],
[m21, m22, 0],
[dx, dy, 1]
];
 
setM(this, matrixMultiply(m1, this.m_), true);
};
 
contextPrototype.setTransform = function(m11, m12, m21, m22, dx, dy) {
var m = [
[m11, m12, 0],
[m21, m22, 0],
[dx, dy, 1]
];
 
setM(this, m, true);
};
 
/******** STUBS ********/
contextPrototype.clip = function() {
// TODO: Implement
};
 
contextPrototype.arcTo = function() {
// TODO: Implement
};
 
contextPrototype.createPattern = function() {
return new CanvasPattern_;
};
 
// Gradient / Pattern Stubs
function CanvasGradient_(aType) {
this.type_ = aType;
this.x0_ = 0;
this.y0_ = 0;
this.r0_ = 0;
this.x1_ = 0;
this.y1_ = 0;
this.r1_ = 0;
this.colors_ = [];
}
 
CanvasGradient_.prototype.addColorStop = function(aOffset, aColor) {
aColor = processStyle(aColor);
this.colors_.push({offset: aOffset,
color: aColor.color,
alpha: aColor.alpha});
};
 
function CanvasPattern_() {}
 
// set up externs
G_vmlCanvasManager = G_vmlCanvasManager_;
CanvasRenderingContext2D = CanvasRenderingContext2D_;
CanvasGradient = CanvasGradient_;
CanvasPattern = CanvasPattern_;
 
})();
 
} // if
/trunk/web/ipfm/dygraph/update-dygraph.sh
0,0 → 1,5
#!/bin/sh
wget http://dygraphs.com/excanvas.js
rm excanvas.js.*
wget http://dygraphs.com/dygraph-combined.js
rm dygraph-combined.js.*
Property changes:
Added: svn:executable
+*
\ No newline at end of property
/trunk/web/ipfm/index.php
0,0 → 1,62
<?php
 
/*
* VNag - Nagios Framework for PHP
* Developed by Daniel Marschall, ViaThinkSoft <www.viathinksoft.com>
* Licensed under the terms of the Apache 2.0 license
*
* Revision 2018-07-19
*/
 
// This file (index.php) is intended to be called by your browser.
// If you want to access via Nagios/Icinga or CLI, call "bin/ipfm.phar" instead.
 
declare(ticks=1);
 
define('USE_DYGRAPH', false); // Slow!
define('ALLOW_HTTP_PARAMTER_OVERWRITE', false); // true: Allow the user to set their own ?w=...&c=... etc.
 
if (!ALLOW_HTTP_PARAMTER_OVERWRITE) {
$_REQUEST['L'] = '/var/log/ipfm';
$_REQUEST['l'] = '10TB';
$_REQUEST['w'] = '6TB,8TB';
$_REQUEST['c'] = '8TB,15TB';
}
 
?><!DOCTYPE HTML>
 
<html>
 
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<meta http-equiv="refresh" content="300; URL=<?php echo isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : ''; ?>">
<title>Traffic monitor</title>
<?php if (USE_DYGRAPH) { ?>
<!--[if IE]>
<script type="text/javascript" src="dygraph/excanvas.js"></script>
<![endif]-->
<script type="text/javascript" src="dygraph/dygraph-combined.js"></script>
<?php } ?>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<meta name="robots" content="noindex">
</head>
 
<body>
 
<h1>Traffic monitor</h1>
 
<?php
 
require_once __DIR__ . '/../../src/framework/vnag_framework.inc.php';
require_once __DIR__ . '/../../src/plugins/ipfm/IpFlowMonitorCheck.class.php';
 
$job = new IpFlowMonitorCheck();
$job->http_visual_output = VNag::OUTPUT_EXCEPTION;
$job->http_invisible_output = VNag::OUTPUT_ALWAYS;
$job->run();
unset($job);
 
?>
</body>
 
</html>
/trunk/web/ping/index.php
0,0 → 1,49
<?php
 
/*
* VNag - Nagios Framework for PHP
* Developed by Daniel Marschall, ViaThinkSoft <www.viathinksoft.com>
* Licensed under the terms of the Apache 2.0 license
*
* Revision 2019-11-18
*/
 
// This file (index.php) is intended to be called by your browser.
// If you want to access via Nagios/Icinga or CLI, call "bin/ping.phar" instead.
 
declare(ticks=1);
 
?><!DOCTYPE HTML>
 
<html>
 
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Online ping</title>
<meta name="robots" content="noindex">
</head>
 
<body>
 
<h1>Online ping</h1>
 
<?php
 
echo '<form action="'.htmlentities($_SERVER['SCRIPT_NAME']).'" method="GET">
Host: <input type="text" name="H" value="'.htmlentities($_REQUEST['H'] ?? '').'" size="40">
<input type="submit" value="Check">
</form>';
 
require_once __DIR__ . '/../../src/framework/vnag_framework.inc.php';
require_once __DIR__ . '/../../src/plugins/ping/PingCheck.class.php';
 
$job = new PingCheck();
$job->http_visual_output = VNag::OUTPUT_EXCEPTION;
$job->http_invisible_output = VNag::OUTPUT_ALWAYS;
$job->run();
unset($job);
 
?>
</body>
 
</html>