Port #8166 SNMP credential cache + procedural SNMPv3 (with #8171/#8172 follow-ups) to develop (#8174)

* Port #8166 SNMP credential cache + procedural SNMPv3 to develop

Ports the shared SNMPv3 credential cache and procedural SNMPv3 routing from the
1.2.x feature (merged as #8166) onto develop, adapted to develop's refactored
SNMP layer. Parts of the 1.2.x change that do not apply to develop are omitted:
the cacti_exec() idle-timeout rewrite (develop has no cacti_exec()), the PHP
floor bump and composer/doc changes (develop is already 8.3+), and the cmd.php
max_oids batching (develop's cmd.php already collects SNMP in-process through
persistent sessions, so the per-item spawn the batching removed does not occur).

- lib/cache.php: new cross-process \Cacti\Cache\SharedCache (file + POSIX
  shared-memory + process-local tiers, optional AES-256-GCM sealing). Loaded via
  lib/snmp.php (the Cacti\Cache\ namespace is not PSR-4 autoloaded). The crypto
  helpers it seals with already live in develop's lib/auth.php, loaded by
  global.php, so no duplicate was added.
- lib/snmp.php: snmp_get_method() now routes SNMPv3 get/getnext to the
  procedural snmp3_*() calls when the running PHP supports the configured
  auth/privacy tokens and no context/engine id is set (SHA-224/384 and
  AES-192/256[C] stay on the binary before PHP 8.6); the three single-get
  functions gain the procedural v3 path with \Throwable handling; adds the
  credential-cache subsystem, protocol-option/MD5-DES helpers,
  snmp_native_protocol(), snmp_format_agent() and cacti_snmp_get_multi(); the
  binary v3 auth builder consults the cache when enabled.
- poller.php / script_server.php: prime / load the shared cache.
- poller_maintenance.php: daily out-of-band cache rebuild on every collector
  (per-poller lastrun marker).
- lib/api_device.php / lib/utility.php: bump snmp_cred_version only on v3
  credential add/change (and propagate the token to the affected remote poller).
- include/global.php: resolve and create the private cache/ directory.
- include/global_settings.php: add 'Enable Credential Cache' and 'Enable MD5 and
  DES for SNMPv3' settings (both off by default); default new-device v3
  auth/privacy to SHA/AES instead of legacy MD5/DES.
- host.php / automation_snmp.php: drop MD5/DES from the pickers when disabled and
  default new records to SHA/AES on upgraded installs.
- include/config.php.dist: document $config['cache_dir'].
- tests/Unit/Core/Cache/SharedCacheTest.php: SharedCache behaviour coverage.
- tests/security/baselines: baseline the two new lib/cache.php sinks.

* Incorporate #8171: binary fallback for unsupported SNMPv3 protocols

Layers PR #8171 onto the develop port so an SNMPv3 device whose auth/privacy
protocols the running PHP's ext-snmp cannot service natively (e.g. AES-256
before PHP 8.6) no longer fatals the poller or device-edit screen.

- lib/snmp.php: add CactiSnmpBinarySession, a session stand-in exposing the
  get/getnext/walk/close interface the cacti_snmp_session_*() helpers use and
  delegating each call to cacti_snmp_*() -> the Net-SNMP binary.
  cacti_snmp_session() returns it when php-snmp is absent or the v3 protocol is
  not natively serviceable, so cmd.php/host.php collect these devices via the
  binary on pre-8.6 and switch to the in-process path on 8.6 with no caller
  change. v1/v2 snmpget/snmp2_get now go through snmp_format_agent(). The
  ERRNO_TIMEOUT check tolerates php-snmp being absent. Drop the vendored
  classSNMP.php compatibility shim and its include (and the Yandex attribution).
- cmd.php: open_snmp_session() returns the down sentinel when a host is already
  marked down this run, instead of returning an unset (null) []
  that cacti_snmp_session_get() then dereferenced (TypeError).
- lib/ping.php: ping_snmp() runs the availability check through the procedural
  cacti_snmp_get()/getnext() path so an unsupported protocol falls back to the
  binary instead of raising a ValueError in SNMP::setSecurity().

* Incorporate #8172: retire include/vendor/phpsnmp, relocate into lib

Follow-up to #8171 on the develop port. After classSNMP.php was removed, the
include/vendor/phpsnmp/ directory held only Cacti-owned files; this retires it.

- lib/snmp.php: the ext-snmp subclass that carried Cacti's bulk_walk_size /
  value_output_format (previously vendor/phpsnmp/extension.php) is now declared
  directly as CactiSnmpNativeSession, guarded by CACTI_PHP_SNMP; the include and
  the 'use phpsnmp\SNMP' alias are gone, and new SNMP(...) / SNMP::VERSION_*
  now reference the native \SNMP and the new subclass.
- lib/mib_parser.php: moved from include/vendor/phpsnmp/mib_parser.php;
  lib/mib_cache.php includes it via __DIR__.
- Remove include/vendor/phpsnmp/extension.php and index.php (directory retired).
- tests: SnmpCoverageTest uses \SNMP::ERRNO_TIMEOUT now that phpsnmp\SNMP is
  gone; drop the stale include/vendor/phpsnmp/ entry from the vendor-policy
  allowlist.

develop's sink baseline tracks constant-based includes differently than 1.2.x,
so no baseline refresh was needed here.

* Address PR #8174 review: snmp_get_method params, v3 walk, getnext agent, cache bump, CHANGELOG

- lib/snmp.php: restore $php_snmp as the 6th snmp_get_method() parameter and move
  the new $auth_proto/$priv_proto after it (callers pass them by name), so the
  positional $php_snmp used by SnmpCoverageTest and others keeps working.
- lib/snmp.php: keep every SNMPv3 operation except get/getnext on the Net-SNMP
  binary - the native walk branch implements only v1/v2, so a v3 walk reaching
  the procedural gate would have silently returned empty when path_snmpbulkwalk
  is missing.
- lib/snmp.php: cacti_snmp_getnext() v1/v2 branches now use snmp_format_agent()
  like get/get_raw, so an IPv6 literal / non-default port is bracketed.
- lib/api_device.php: bump snmp_cred_version only when the host's v3 membership
  or one of the cached credential fields actually changed, instead of on every
  save of a v3 device.
- CHANGELOG: move the #8171 entry into the issue block and the #8166 entries into
  the feature block, matching the established section ordering.

* Fix CI: unbracket IPv4/DNS SNMP targets, inline auth-cache SQL columns, apply phpcsfixer standard

* Refresh sink inventory baseline after short-array normalization

* Restore lib/snmp.php 100% coverage after aligning v3 routing to 1.2.x

- update the three SnmpCoverageTest assertions that still encoded develop's
  pre-port behavior: v3 snmp_get_method now returns PHP, an unsupported-
  protocol v3 session returns the binary-delegating session object, and the
  v3 cacti_snmp_get path runs natively
- add a v3 noAuthNoPriv user to the snmp-coverage snmpd fixture so native
  snmp3_get is exercised deterministically
- add tests covering the ported subsystems to 100%: shared auth cache,
  binary-delegating session, protocol pickers, v3 credential args,
  cacti_snmp_get_multi, and the cacti_get_snmpv3_auth cache path
- snmp_auth_cache_load uses a resettable process guard so its enabled and
  disabled branches are both coverable in a single process

* Resolve phpstan errors in the relocated SNMP MIB parser and ported snmp.php

- lib/mib_parser.php: type the MibParser properties, add parameter/return
  types, guard file_get_contents()/preg_split() against false, correct the
  parse_bracket_token delimiter params (string, not integer), and drop the
  unreachable return after trigger_error(E_USER_ERROR) - now phpstan clean
- lib/mib_cache.php: drop the redundant isset($mp->oids) guard (the typed
  property is always initialized; $mp->mib is the real check)
- lib/snmp.php: type the CactiSnmpBinarySession and CactiSnmpNativeSession
  properties/methods and pass bool to snmp_set_quick_print()
- .phpstan.neon: ignore greaterOrEqual.alwaysFalse alongside the existing
  greater.alwaysFalse (the PHP_VERSION_ID >= 80600 forward-compat gate)
- regenerate phpstan-baseline.neon for the irreducible ext-snmp stub
  strictness (snmp3_get literal-union protocols, int<-1,max> timeouts) in
  the ported procedural v3 path, the new lib/cache.php shmop stubs, and the
  $config array-shape offsets in include/global.php

* Make the v3 getter catch coverage net-snmp-build-independent

The DES-rejection trick that drove the procedural snmp3_get()/snmp3_getnext()
try/catch blocks only works on net-snmp builds compiled without DES; CI's
Debian net-snmp accepts DES, so those catches went uncovered (98.3%).

- extend the existing native_get injection seam (already on cacti_snmp_get)
  to cacti_snmp_get_raw, cacti_snmp_getnext, and cacti_snmp_get_multi, and
  drive the catch blocks with a throwing native getter in the test
- mark the seam-less cacti_snmp_session() setSecurity catch with
  @codeCoverageIgnore (it only throws for a protocol the running net-snmp
  rejects, which is not portably reproducible in the fixture)

* Exclude ext-snmp/PHP-8.6-gated defensive branches from snmp coverage

Two branches in lib/snmp.php are unreachable on the PHP 8.3 + ext-snmp
coverage runner and were only "covered" locally via opcache dead-code
elimination:

- snmp_get_method()'s !function_exists('snmp3_get') fallback (ext-snmp
  always provides snmp3_get)
- snmp_php_v3_protocols_supported()'s PHP_VERSION_ID >= 80600 block
  (SHA-224/384 and AES-192/256 tokens are only accepted on PHP 8.6+)

Mark both with @codeCoverageIgnore so the 100% gate is deterministic
across runners regardless of opcache settings.

* Account for the #8166 SNMPv3 credential-cache gate query in the batching test

poller_update_poller_cache_from_buffer() now runs one SELECT per flush to
decide whether the flush touched SNMPv3 poller items before bumping the shared
credential-cache version (matching 1.2.x). UpdateDataQueryCacheBatchingIntegrationTest
counted 4 statements per flush; update it to 5 (and 3 per-row flushes to 15,
1 batched flush to 5). The guard's intent - batching issues fewer statements
than per-row flushes - still holds.

* Port #8175: group SNMP options under an SNMP Behavior section

Mirror the 1.2.x settings reorganization (#8175) on develop. develop already
keeps the SNMP options in a dedicated SNMP tab, so add an "SNMP Behavior"
spacer there, order the behavior options as md5/des, credential cache, max
get size, bulkwalk fetch size, and move "Disable increasing OID Check" out of
the Poller tab to sit last in that group. Display-only; no settings added or
removed and no behavior change. Adds the "SNMP Behavior" heading to cacti.pot.

* fix: complete dependabot htmx 2.0.10 to 2.0.11 bump

Dependabot bumped package.json and package-lock.json to htmx.org 2.0.11
(PR 8179) but left the vendored include/js/htmx.js, its version marker,
and the pinned SRI constant at 2.0.10. The htmx-filters CI workflow runs
npm ci, which regenerates include/js/htmx.js from the 2.0.11 package, so
HtmxTest's runtime sha384 no longer matches the HTMX_2_0_10_SRI constant
and the integrity assertion fails.

Complete the bump: regenerate the vendored include/js/htmx.js to the
2.0.11 build, bump include/js/htmx.js.version to 2.0.11, rename
HTMX_2_0_10_SRI to HTMX_2_0_11_SRI with the recomputed sha384 hash, and
update the version/integrity assertions in tests/Unit/Ui/Html/HtmxTest.php
and tests/HandOff/HtmxLoaderHandOffTest.php. package.json and
package-lock.json match the values dependabot already landed on develop.

* settings: move SNMP Agent Support under the SNMP Behavior spacer

Relocate the enable_snmp_agent setting (SNMP Agent Support Enabled) so it
is the first item under the SNMP Behavior spacer instead of sitting in the
Poller General group, grouping it with the other SNMP behavior options.

* Address PR #8174 review: keep SHA-224/384 on the binary, honor port on transport targets

Resolves the two still-valid Copilot review findings on lib/snmp.php that were
left unresolved (only marked outdated after later commits shifted their lines).

- snmp_php_v3_protocols_supported(): drop SHA224/SHA384 from the native auth
  allowlist. ext-snmp's SNMP::setSecurity()/snmp3_*() only map MD5/SHA/SHA256/
  SHA512 - there is no SHA-224/SHA-384 mapping on any build, including PHP 8.6
  (verified against php-src ext/snmp/snmp.c), so routing those tokens to the
  procedural path raised a ValueError instead of using the binary. They now
  always fall back to the Net-SNMP binary. The AES-192/256 privacy tokens that
  ext-snmp does add on 8.6 stay gated behind PHP_VERSION_ID >= 80600.
- snmp_format_agent(): a udp/tcp transport-qualified target that omits a port
  now has the configured non-default port appended (udp6:[2001:db8::1] + 1161 ->
  udp6:[2001:db8::1]:1161), matching the Net-SNMP binary path. Targets that
  already carry a port, and unix: sockets (no port), are left untouched.
- SnmpCoverageTest: cover the new transport-target branches; lib/snmp.php stays
  at 100%.
This commit is contained in:
TheWitness authored and GitHub committed 2026-10-05 10:18:41 -04:00
1 parent 91fda4f1fe
commit f79dc15c08
34 files changed
+2494 -653

No files matched your search

+1
View File
@@ -43,6 +43,7 @@ parameters:
- identifier: if.alwaysTrue
- identifier: while.alwaysTrue
- identifier: greater.alwaysFalse
- identifier: greaterOrEqual.alwaysFalse
- identifier: identical.alwaysTrue
- identifier: identical.alwaysFalse
- identifier: booleanAnd.leftAlwaysTrue
+4
View File
@@ -41,6 +41,7 @@ Cacti CHANGELOG
-security#8158: Harden - Confine automation sorting and pagination before SQL and HTML rendering
-security#8158: Harden - Replace sibling password-reset links and revoke authentication state after reset
-security#GHSA-3jj2-v5ch-wmq5: Fail closed on a posted LDAP realm that is not a configured domain
-issue#8171: SNMPv3 devices using an auth/privacy protocol the running PHP cannot service natively (e.g. AES-256 before PHP 8.6) now collect through the Net-SNMP binary via a binary-delegating session instead of fataling the poller/device-edit, and the vendored classSNMP.php compatibility shim is removed
-issue#8120: Do not replicate repository and tooling metadata files (.gitignore, .htaccess.dist, .mdl_style.rb, .mdlrc) to remote data collectors during file replication
-issue#8116: Restore legacy unique_keys[] support in db_table_create() and db_update_table() so plugins that declare UNIQUE indexes with that definition style keep them across a schema refresh
-issue#8105: Add a Force Uninstall action to remove an orphaned plugin whose directory is missing
@@ -226,6 +227,9 @@ Cacti CHANGELOG
-issue#8040: Regenerate the vendored DOMPurify asset to match the pinned 3.4.15 release and keep node_modules during CI
-issue#8041: Detect a real TTY instead of a dead github_actions check before calling stty size
-issue#8043: Regenerate the vendored DOMPurify asset to match the pinned 3.4.15 release and keep node_modules during CI
-feature#8166: Add a cross-process shared SNMP authentication cache (disabled by default) that pre-hardens SNMPv3 credential arguments once per credential change and seals them with the per-installation AES-256-GCM key, so poller, cmd and script server processes reuse them instead of rebuilding them on every request
-feature#8166: Route SNMPv3 get/getnext through the in-process php-snmp extension when the running PHP version supports the configured auth/privacy protocols and no context/engine id is set, bypassing a per-request Net-SNMP binary spawn
-feature#8166: Add an "Enable MD5 and DES for SNMPv3" setting (off by default) that removes the legacy MD5/DES algorithms from the Device and Automation SNMP Option pickers when disabled, and default new Devices to SHA/AES
-feature#7884: Manage front-end JavaScript libraries with npm and Dependabot
-feature#7884: Build release artifacts from managed dependencies, including DOMPurify 3.4.14 and phpseclib 4, and a reduced runtime tree
-feature#7835: Add cacti_snmp_session_from_host() to build SNMP sessions from a device row
+18
View File
@@ -641,6 +641,24 @@ function automation_snmp_item_edit() : void {
'value' => '|arg1:sequence|'],
];
// drop the legacy MD5/DES SNMPv3 algorithms from the pickers when disabled
$fields_automation_snmp_item_edit['snmp_auth_protocol']['array'] = snmp_auth_protocol_options(isset($automation_snmp_item['snmp_auth_protocol']) ? $automation_snmp_item['snmp_auth_protocol'] : '');
$fields_automation_snmp_item_edit['snmp_priv_protocol']['array'] = snmp_priv_protocol_options(isset($automation_snmp_item['snmp_priv_protocol']) ? $automation_snmp_item['snmp_priv_protocol'] : '');
/* For a new Automation SNMP item the auth/priv defaults come from the global
* setting, which on an upgraded install may still be a legacy MD5/DES value just
* removed from the picker above; default a new item to the strongest available
* option when the legacy algorithms are disabled so it is not left on [None]. */
if (empty($automation_snmp_item['id']) && !snmp_md5_des_enabled()) {
if (!isset($fields_automation_snmp_item_edit['snmp_auth_protocol']['array'][read_config_option('snmp_auth_protocol')])) {
$fields_automation_snmp_item_edit['snmp_auth_protocol']['value'] = 'SHA';
}
if (!isset($fields_automation_snmp_item_edit['snmp_priv_protocol']['array'][read_config_option('snmp_priv_protocol')])) {
$fields_automation_snmp_item_edit['snmp_priv_protocol']['value'] = 'AES';
}
}
draw_edit_form([
'config' => ['no_form_tag' => true],
'fields' => inject_form_variables($fields_automation_snmp_item_edit, $automation_snmp_item)
+14 -6
View File
@@ -668,8 +668,16 @@ function open_snmp_session(int $host_id, array &$item) : mixed {
$item['max_oids'] = read_config_option('max_get_size');
}
if (!isset($sessions[$host_id . '_' . $item['snmp_version'] . '_' . $item['snmp_port']]) && !isset($downhosts[$host_id . '_' . $item['snmp_version'] . '_' . $item['snmp_port']])) {
$sessions[$host_id . '_' . $item['snmp_version'] . '_' . $item['snmp_port']] = cacti_snmp_session(
$key = $host_id . '_' . $item['snmp_version'] . '_' . $item['snmp_port'];
/* a host already marked down this run has no cached session, so return the
down sentinel instead of falling through to an unset $sessions[$key] (null) */
if (isset($downhosts[$key])) {
return false;
}
if (!isset($sessions[$key])) {
$sessions[$key] = cacti_snmp_session(
$item['hostname'],
$item['snmp_community'],
$item['snmp_version'],
@@ -686,15 +694,15 @@ function open_snmp_session(int $host_id, array &$item) : mixed {
$item['max_oids']
);
if ($sessions[$host_id . '_' . $item['snmp_version'] . '_' . $item['snmp_port']] === false) {
unset($sessions[$host_id . '_' . $item['snmp_version'] . '_' . $item['snmp_port']]);
$downhosts[$host_id . '_' . $item['snmp_version'] . '_' . $item['snmp_port']] = true;
if ($sessions[$key] === false) {
unset($sessions[$key]);
$downhosts[$key] = true;
return false;
}
}
return $sessions[$host_id . '_' . $item['snmp_version'] . '_' . $item['snmp_port']];
return $sessions[$key];
}
function snmp_mark_host_down(int $host_id, array &$item) : void {
+19
View File
@@ -893,6 +893,25 @@ function host_edit() : void {
$fields_host_edit['host_template_id']['value'] = gfrv('host_template_id');
}
// drop the legacy MD5/DES SNMPv3 algorithms from the pickers when disabled
$fields_host_edit['snmp_auth_protocol']['array'] = snmp_auth_protocol_options(isset($host['snmp_auth_protocol']) ? $host['snmp_auth_protocol'] : '');
$fields_host_edit['snmp_priv_protocol']['array'] = snmp_priv_protocol_options(isset($host['snmp_priv_protocol']) ? $host['snmp_priv_protocol'] : '');
/* On a new Device the auth/priv defaults come from the global setting, which on
* an upgraded install may still be a legacy MD5/DES value that was just dropped
* from the picker above - leaving the <select> with no option selected so the
* browser submits [None]. When the legacy algorithms are disabled, default a new
* Device to the strongest available option so the field has a valid selection. */
if (empty($host['id']) && !snmp_md5_des_enabled()) {
if (!isset($fields_host_edit['snmp_auth_protocol']['array'][read_config_option('snmp_auth_protocol')])) {
$fields_host_edit['snmp_auth_protocol']['value'] = 'SHA';
}
if (!isset($fields_host_edit['snmp_priv_protocol']['array'][read_config_option('snmp_priv_protocol')])) {
$fields_host_edit['snmp_priv_protocol']['value'] = 'AES';
}
}
draw_edit_form(
[
'config' => ['no_form_tag' => true],
+10
View File
@@ -111,6 +111,16 @@ $disable_log_rotation = false;
//$rra_path = '/var/www/html/cacti/rra/';
//$package_keys_path = '/etc/cacti/pki';
/*
* Optional parameter to define the directory used by Cacti's shared object
* cache (for example the pre-hardened SNMP credential cache). When unset, Cacti
* uses cache/ below the installation path and creates it when needed. The
* directory must be private and writable by the poller/web server user; if it
* cannot be created or written, the shared cache degrades to per-process storage
* rather than falling back to a world-writable system temporary directory.
*/
//$config['cache_dir'] = '/var/www/html/cacti/cache';
/*
* Optional parameter to define a data input whitelist command string. This
* whitelist file will help protect cacti from unauthorized changes to Cacti
+13
View File
@@ -283,6 +283,19 @@ if (isset($i18n_text_log)) {
$config['i18n_text_log'] = $i18n_text_log;
}
/* Shared object cache directory (see $config['cache_dir'] in config.php).
* Default to a private cache/ under the install. If it cannot be created or is
* not writable the shared cache simply degrades to a process-local tier; never
* fall back to a world-writable shared temp directory, which would let a local
* user plant predictable cache files for the poller to read. */
if (empty($config['cache_dir'])) {
$config['cache_dir'] = $config['base_path'] . '/cache';
}
if (!is_dir($config['cache_dir'])) {
@mkdir($config['cache_dir'], 0770, true);
}
// include base modules
require_once(CACTI_PATH_LIBRARY . '/database.php');
require_once(CACTI_PATH_LIBRARY . '/functions.php');
+38 -21
View File
@@ -1010,7 +1010,7 @@ $settings['snmp'] = [
'method' => 'drop_array',
'friendly_name' => __('Auth Protocol (v3)'),
'description' => __('Default SNMPv3 Authorization Protocol for all new Devices.'),
'default' => 'MD5',
'default' => 'SHA',
'array' => $snmp_auth_protocols,
],
'snmp_username' => [
@@ -1033,7 +1033,7 @@ $settings['snmp'] = [
'method' => 'drop_array',
'friendly_name' => __('Privacy Protocol (v3)'),
'description' => __('Default SNMPv3 Privacy Protocol for all new Devices.'),
'default' => 'DES',
'default' => 'AES',
'array' => $snmp_priv_protocols,
],
'snmp_priv_passphrase' => [
@@ -1094,6 +1094,37 @@ $settings['snmp'] = [
fn () => new Assert\Range(min: 0, max: 100, notInRangeMessage: __('must be between {{ min }} and {{ max }}.')),
],
],
'snmp_behavior_header' => [
'friendly_name' => __('SNMP Behavior'),
'method' => 'spacer',
'collapsible' => 'true'
],
'enable_snmp_agent' => [
'friendly_name' => __('SNMP Agent Support Enabled'),
'description' => __('If this option is checked, Cacti will populate SNMP Agent tables with Cacti device and system information. It does not enable the SNMP Agent itself.'),
'method' => 'checkbox',
'default' => 'on'
],
'snmp_md5_des_enabled' => [
'friendly_name' => __('Enable MD5 and DES for SNMPv3'),
'description' => __('The MD5 authentication and DES privacy algorithms are legacy, weak, and unavailable on hardened (FIPS) PHP and Net-SNMP builds. When disabled, MD5 and DES are removed from the SNMPv3 Authentication and Privacy Protocol dropdowns shown when editing a Device and in the Automation SNMP Options, leaving only the stronger SHA and AES algorithms.'),
'method' => 'checkbox',
'default' => ''
],
'snmp_credential_cache' => [
'friendly_name' => __('Enable Credential Cache'),
'description' => __('Pre-harden and cache SNMPv3 credential arguments once per credential change so each poller process reuses them instead of rebuilding them on every request. This yields a marginal savings when collecting with SNMPv3 credentials through the Net-SNMP binaries. The php-snmp extension handles most SNMPv3 gets in-process and bypasses this cache, but the Net-SNMP binaries (and therefore this cache) are still used for SNMP walks, hex output, requests that set a context or engine id, and protocol combinations that the running PHP version does not support. Enable this if you collect any of those workloads with SNMPv3 credentials.'),
'method' => 'checkbox',
'default' => ''
],
'max_get_size' => [
'friendly_name' => __('Max OID Limit'),
'description' => __('The default maximum number of SNMP Get OIDs to issue per snmpget request. For Devices, this setting is controlled at the Device level. You should only use this setting when using Cacti\'s SNMP API natively in your scripts or plugins.'),
'method' => 'textbox',
'default' => '10',
'max_length' => '10',
'size' => '5'
],
'snmp_bulk_walk_size' => [
'friendly_name' => __('Bulkwalk Fetch Size'),
'description' => __('How many OID\'s should be returned per snmpbulkwalk request? For Devices with large SNMP trees, increasing this size will increase re-index performance over a WAN.'),
@@ -1114,13 +1145,11 @@ $settings['snmp'] = [
'200' => '200'
]
],
'max_get_size' => [
'friendly_name' => __('Max OID Limit'),
'description' => __('The default maximum number of SNMP Get OIDs to issue per snmpget request. For Devices, this setting is controlled at the Device level. You should only use this setting when using Cacti\'s SNMP API natively in your scripts or plugins.'),
'method' => 'textbox',
'default' => '10',
'max_length' => '10',
'size' => '5'
'oid_increasing_check_disable' => [
'friendly_name' => __('Disable increasing OID Check'),
'description' => __('Controls disabling check for increasing OID while walking OID tree.'),
'method' => 'checkbox',
'default' => ''
],
'availability_header' => [
'friendly_name' => __('Availability/Reachability'),
@@ -1600,12 +1629,6 @@ $settings['poller'] = [
'default' => 'on',
'tab' => 'poller'
],
'enable_snmp_agent' => [
'friendly_name' => __('SNMP Agent Support Enabled'),
'description' => __('If this option is checked, Cacti will populate SNMP Agent tables with Cacti device and system information. It does not enable the SNMP Agent itself.'),
'method' => 'checkbox',
'default' => 'on'
],
'poller_type' => [
'friendly_name' => __('Poller Type'),
'description' => __('The poller type to use. This setting will take affect at next polling interval.'),
@@ -1661,12 +1684,6 @@ $settings['poller'] = [
'method' => 'checkbox',
'default' => ''
],
'oid_increasing_check_disable' => [
'friendly_name' => __('Disable increasing OID Check'),
'description' => __('Controls disabling check for increasing OID while walking OID tree.'),
'method' => 'checkbox',
'default' => ''
],
'remote_agent_timeout' => [
'friendly_name' => __('Remote Agent Timeout'),
'description' => __('The amount of time, in seconds, that the Central Cacti web server will wait for a response from the Remote Data Collector to obtain various Device information before abandoning the request. On Devices that are associated with Data Collectors other than the Central Cacti Data Collector, the Remote Agent must be used to gather Device information.'),
+120 -69
View File
@@ -236,7 +236,7 @@ var htmx = (function() {
/**
* If set to true, disables htmx-based requests to non-origin hosts.
* @type boolean
* @default false
* @default true
*/
selfRequestsOnly: true,
/**
@@ -296,7 +296,7 @@ var htmx = (function() {
location,
/** @type {typeof internalEval} */
_: null,
version: '2.0.10'
version: '2.0.11'
}
// Tsc madness part 2
htmx.onLoad = onLoadHelper
@@ -575,6 +575,11 @@ var htmx = (function() {
* @param {DocumentFragment} fragment
*/
function normalizeScriptTags(fragment) {
if (!htmx.config.allowScriptTags) {
// remove all script tags if scripts are disabled
fragment.querySelectorAll('script').forEach((script) => script.remove())
return
}
Array.from(fragment.querySelectorAll('script')).forEach(/** @param {HTMLScriptElement} script */ (script) => {
if (isJavaScriptScriptNode(script)) {
const newScript = duplicateScript(script)
@@ -601,6 +606,8 @@ var htmx = (function() {
* @returns {DocumentFragmentWithTitle}
*/
function makeFragment(response) {
// convert <hx-*> custom tags to <template hx type="*"> so they survive HTML parsing
response = response.replace(/<hx-([a-z]+)((?:\s[^>]*)?)>/gi, '<template hx type="$1"$2>').replace(/<\/hx-[a-z]+>/gi, '</template>')
// strip head tag to determine shape of response we are dealing with
const responseWithNoHead = response.replace(/<head(\s[^>]*)?>[\s\S]*?<\/head>/i, '')
const startTag = getStartTag(responseWithNoHead)
@@ -633,12 +640,7 @@ var htmx = (function() {
}
}
if (fragment) {
if (htmx.config.allowScriptTags) {
normalizeScriptTags(fragment)
} else {
// remove all script tags if scripts are disabled
fragment.querySelectorAll('script').forEach((script) => script.remove())
}
normalizeScriptTags(fragment)
}
return fragment
}
@@ -802,14 +804,7 @@ var htmx = (function() {
* @returns {T1 & T2}
*/
function mergeObjects(obj1, obj2) {
for (const key in obj2) {
if (obj2.hasOwnProperty(key)) {
// @ts-ignore tsc doesn't seem to properly handle types merging
obj1[key] = obj2[key]
}
}
// @ts-ignore tsc doesn't seem to properly handle types merging
return obj1
return Object.assign({}, obj1, obj2)
}
/**
@@ -908,7 +903,7 @@ var htmx = (function() {
*
* @see https://htmx.org/api/#find
*
* @param {ParentNode|string} eltOrSelector the root element to find the matching element in, inclusive | the selector to match
* @param {ParentNode|string} eltOrSelector the root element to search inside of, not including the root itself | the selector to match
* @param {string} [selector] the selector to match
* @returns {Element|null}
*/
@@ -925,7 +920,7 @@ var htmx = (function() {
*
* @see https://htmx.org/api/#findAll
*
* @param {ParentNode|string} eltOrSelector the root element to find the matching elements in, inclusive | the selector to match
* @param {ParentNode|string} eltOrSelector the root element to search inside of, not including the root itself | the selector to match
* @param {string} [selector] the selector to match
* @returns {NodeListOf<Element>}
*/
@@ -1848,6 +1843,55 @@ var htmx = (function() {
}
}
/**
* @param {DocumentFragment|ParentNode} fragment
* @param {HtmxSettleInfo} settleInfo
* @param {Element} sourceElement
* @returns {boolean}
*/
function findAndSwapPartials(fragment, settleInfo, sourceElement) {
var hxTemplates = findAll(fragment, 'template[hx]')
forEach(hxTemplates, function(template) {
var type = getRawAttribute(template, 'type')
if (type === 'partial') {
var targetSelector = getAttributeValue(template, 'hx-target') ||
(template.id ? '#' + CSS.escape(template.id) : null)
if (targetSelector) {
var swapOverride = getAttributeValue(template, 'hx-swap')
var swapSpec = getSwapSpecification(template, swapOverride)
var targets = querySelectorAllExt(sourceElement || getDocument().body, targetSelector, false)
if (targets.length === 0) {
triggerErrorEvent(getDocument().body, 'htmx:partialErrorNoTarget', { template, targetSelector, sourceElement })
}
forEach(targets, function(target) {
target = asElement(target)
if (target) {
var fragment = template.content.cloneNode(true)
normalizeScriptTags(fragment)
var beforeSwapDetails = { shouldSwap: true, target, fragment }
if (!triggerEvent(target, 'htmx:partialBeforeSwap', beforeSwapDetails)) return
target = beforeSwapDetails.target
if (beforeSwapDetails.shouldSwap) {
swap(target, beforeSwapDetails.fragment, swapSpec, {
contextElement: target,
afterSwapCallback: function() {
forEach(settleInfo.elts, function(elt) {
triggerEvent(elt, 'htmx:partialAfterSwap', beforeSwapDetails)
})
}
})
}
}
})
}
} else {
triggerEvent(getDocument().body, 'htmx:processTemplate', { type, template, settleInfo, sourceElement })
}
template.parentNode.removeChild(template)
})
return hxTemplates.length > 0
}
/**
* @param {DocumentFragment} fragment
* @param {HtmxSettleInfo} settleInfo
@@ -1889,7 +1933,12 @@ var htmx = (function() {
maybeCall(swapOptions.beforeSwapCallback)
target = resolveTarget(target)
const rootNode = swapOptions.contextElement ? getRootNode(swapOptions.contextElement, false) : getDocument()
// A detached contextElement's own getRootNode() is its orphaned subtree, not
// the document, so OOB targets that are still live in the document would be
// unreachable through it - fall back to the document in that case.
const rootNode = (swapOptions.contextElement && swapOptions.contextElement.isConnected)
? getRootNode(swapOptions.contextElement, false)
: getDocument()
// preserve focus and selection
const activeElt = document.activeElement
@@ -1908,7 +1957,7 @@ var htmx = (function() {
target.textContent = content
// Otherwise, make the fragment and process it
} else {
let fragment = makeFragment(content)
let fragment = typeof content === 'string' ? makeFragment(content) : content
settleInfo.title = swapOptions.title || fragment.title
if (swapOptions.historyRequest) {
@@ -1940,6 +1989,8 @@ var htmx = (function() {
template.remove()
}
})
// partial swaps — after oob, before main swap
var hasPartials = findAndSwapPartials(fragment, settleInfo, swapOptions.contextElement || asElement(target))
// normal swap
if (swapOptions.select) {
@@ -1950,7 +2001,12 @@ var htmx = (function() {
fragment = newFragment
}
handlePreservedElements(fragment)
swapWithStyle(swapSpec.swapStyle, swapOptions.contextElement, target, fragment, settleInfo)
// if the response contained only <hx-partial> tags and nothing else, skip the main swap
if (hasPartials && !fragment.childElementCount && !fragment.textContent.trim()) {
settleInfo.elts = [asElement(target)]
} else {
swapWithStyle(swapSpec.swapStyle, swapOptions.contextElement, target, fragment, settleInfo)
}
restorePreservedElements()
}
@@ -2066,18 +2122,16 @@ var htmx = (function() {
function handleTriggerHeader(xhr, header, elt) {
const triggerBody = xhr.getResponseHeader(header)
if (triggerBody.indexOf('{') === 0) {
const triggers = parseJSON(triggerBody)
for (const eventName in triggers) {
if (triggers.hasOwnProperty(eventName)) {
let detail = triggers[eventName]
if (isRawObject(detail)) {
// @ts-ignore
elt = detail.target !== undefined ? detail.target : elt
} else {
detail = { value: detail }
}
triggerEvent(elt, eventName, detail)
const triggers = parseJSON(triggerBody) || {}
for (const eventName of Object.keys(triggers)) {
let detail = triggers[eventName]
if (isRawObject(detail)) {
// @ts-ignore
elt = detail.target !== undefined ? detail.target : elt
} else {
detail = { value: detail }
}
triggerEvent(elt, eventName, detail)
}
} else {
const eventNames = triggerBody.split(',')
@@ -2796,7 +2850,7 @@ var htmx = (function() {
const boostedSelector = ', [hx-boost] a, [data-hx-boost] a, a[hx-boost], a[data-hx-boost]'
const extensionSelectors = []
for (const e in extensions) {
for (const e of Object.keys(extensions)) {
const extension = extensions[e]
if (extension.getSelectors) {
var selectors = extension.getSelectors()
@@ -3950,11 +4004,9 @@ var htmx = (function() {
} else {
varsValues = parseJSON(str)
}
for (const key in varsValues) {
if (varsValues.hasOwnProperty(key)) {
if (values[key] == null) {
values[key] = varsValues[key]
}
for (const key of Object.keys(varsValues)) {
if (values[key] == null) {
values[key] = varsValues[key]
}
}
}
@@ -4039,11 +4091,11 @@ var htmx = (function() {
/**
* @param {XMLHttpRequest} xhr
* @param {RegExp} regexp
* @param {string} name
* @return {boolean}
*/
function hasHeader(xhr, regexp) {
return regexp.test(xhr.getAllResponseHeaders())
function hasHeader(xhr, name) {
return xhr.getResponseHeader(name) !== null
}
/**
@@ -4131,15 +4183,13 @@ var htmx = (function() {
function formDataFromObject(obj) {
if (obj instanceof FormData) return obj
const formData = new FormData()
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
if (obj[key] && typeof obj[key].forEach === 'function') {
obj[key].forEach(function(v) { formData.append(key, v) })
} else if (typeof obj[key] === 'object' && !(obj[key] instanceof Blob)) {
formData.append(key, JSON.stringify(obj[key]))
} else {
formData.append(key, obj[key])
}
for (const key of Object.keys(obj)) {
if (obj[key] && typeof obj[key].forEach === 'function') {
obj[key].forEach(function(v) { formData.append(key, v) })
} else if (typeof obj[key] === 'object' && !(obj[key] instanceof Blob)) {
formData.append(key, JSON.stringify(obj[key]))
} else {
formData.append(key, obj[key])
}
}
return formData
@@ -4546,11 +4596,8 @@ var htmx = (function() {
if (requestAttrValues.noHeaders) {
// ignore all headers
} else {
for (const header in headers) {
if (headers.hasOwnProperty(header)) {
const headerValue = headers[header]
safelySetHeaderValue(xhr, header, headerValue)
}
for (const header of Object.keys(headers)) {
safelySetHeaderValue(xhr, header, headers[header])
}
}
@@ -4668,13 +4715,13 @@ var htmx = (function() {
//= ==========================================
let pathFromHeaders = null
let typeFromHeaders = null
if (hasHeader(xhr, /HX-Push:/i)) {
if (hasHeader(xhr, 'HX-Push')) {
pathFromHeaders = xhr.getResponseHeader('HX-Push')
typeFromHeaders = 'push'
} else if (hasHeader(xhr, /HX-Push-Url:/i)) {
} else if (hasHeader(xhr, 'HX-Push-Url')) {
pathFromHeaders = xhr.getResponseHeader('HX-Push-Url')
typeFromHeaders = 'push'
} else if (hasHeader(xhr, /HX-Replace-Url:/i)) {
} else if (hasHeader(xhr, 'HX-Replace-Url')) {
pathFromHeaders = xhr.getResponseHeader('HX-Replace-Url')
typeFromHeaders = 'replace'
}
@@ -4697,9 +4744,8 @@ var htmx = (function() {
const requestPath = responseInfo.pathInfo.finalRequestPath
const responsePath = responseInfo.pathInfo.responsePath
let pushUrl = responseInfo.etc.push || getClosestAttributeValue(elt, 'hx-push-url')
const pushUrl = responseInfo.etc.push || getClosestAttributeValue(elt, 'hx-push-url')
let replaceUrl = responseInfo.etc.replace || getClosestAttributeValue(elt, 'hx-replace-url')
if (pushUrl === 'false') pushUrl = null
if (replaceUrl === 'false') replaceUrl = null
const elementIsBoosted = getInternalData(elt).boosted
@@ -4718,6 +4764,11 @@ var htmx = (function() {
}
if (path) {
// false indicates no push, return empty object
if (path === 'false') {
return {}
}
// true indicates we want to follow wherever the server ended up sending us
if (path === 'true') {
path = responsePath || requestPath // if there is no response path, go with the original request path
@@ -4809,11 +4860,11 @@ var htmx = (function() {
if (!triggerEvent(elt, 'htmx:beforeOnLoad', responseInfo)) return
if (hasHeader(xhr, /HX-Trigger:/i)) {
if (hasHeader(xhr, 'HX-Trigger')) {
handleTriggerHeader(xhr, 'HX-Trigger', elt)
}
if (hasHeader(xhr, /HX-Location:/i)) {
if (hasHeader(xhr, 'HX-Location')) {
let redirectPath = xhr.getResponseHeader('HX-Location')
/** @type {HtmxAjaxHelperContext&{path?:string}} */
var redirectSwapSpec = {}
@@ -4828,9 +4879,9 @@ var htmx = (function() {
return
}
const shouldRefresh = hasHeader(xhr, /HX-Refresh:/i) && xhr.getResponseHeader('HX-Refresh') === 'true'
const shouldRefresh = hasHeader(xhr, 'HX-Refresh') && xhr.getResponseHeader('HX-Refresh') === 'true'
if (hasHeader(xhr, /HX-Redirect:/i)) {
if (hasHeader(xhr, 'HX-Redirect')) {
responseInfo.keepIndicators = true
htmx.location.href = xhr.getResponseHeader('HX-Redirect')
shouldRefresh && htmx.location.reload()
@@ -4859,11 +4910,11 @@ var htmx = (function() {
}
// response headers override response handling config
if (hasHeader(xhr, /HX-Retarget:/i)) {
if (hasHeader(xhr, 'HX-Retarget')) {
responseInfo.target = resolveRetarget(elt, xhr.getResponseHeader('HX-Retarget'))
}
if (hasHeader(xhr, /HX-Reswap:/i)) {
if (hasHeader(xhr, 'HX-Reswap')) {
swapOverride = xhr.getResponseHeader('HX-Reswap')
}
@@ -4919,7 +4970,7 @@ var htmx = (function() {
selectOverride = responseInfoSelect
}
if (hasHeader(xhr, /HX-Reselect:/i)) {
if (hasHeader(xhr, 'HX-Reselect')) {
selectOverride = xhr.getResponseHeader('HX-Reselect')
}
@@ -4933,7 +4984,7 @@ var htmx = (function() {
anchor: responseInfo.pathInfo.anchor,
contextElement: elt,
afterSwapCallback: function() {
if (hasHeader(xhr, /HX-Trigger-After-Swap:/i)) {
if (hasHeader(xhr, 'HX-Trigger-After-Swap')) {
let finalElt = elt
if (!bodyContains(elt)) {
finalElt = getDocument().body
@@ -4942,7 +4993,7 @@ var htmx = (function() {
}
},
afterSettleCallback: function() {
if (hasHeader(xhr, /HX-Trigger-After-Settle:/i)) {
if (hasHeader(xhr, 'HX-Trigger-After-Settle')) {
let finalElt = elt
if (!bodyContains(elt)) {
finalElt = getDocument().body
+1 -1
View File
@@ -1 +1 @@
2.0.10
2.0.11
-310
View File
@@ -1,310 +0,0 @@
<?php
/*
+-------------------------------------------------------------------------+
| Copyright (C) 2010 Boris Lytochkin |
| Sponsored by: Yandex LLC |
| |
| This program is free software; you can redistribute it and/or |
| modify it under the terms of the GNU General Public License |
| as published by the Free Software Foundation; either version 2 |
| of the License, or (at your option) any later version. |
| |
| This program is distributed in the hope that it will be useful, |
| but WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| GNU General Public License for more details. |
+-------------------------------------------------------------------------+
*/
namespace phpsnmp;
const SNMP_OID_OUTPUT_SUFFIX = 1;
const SNMP_OID_OUTPUT_MODULE = 2;
const SNMP_OID_OUTPUT_UCD = 5;
const SNMP_OID_OUTPUT_NONE = 6;
const SNMP_STRING_OUTPUT_GUESS = 1;
const SNMP_STRING_OUTPUT_ASCII = 2;
const SNMP_STRING_OUTPUT_HEX = 3;
class SNMP {
const ERRNO_NOERROR = 0;
const ERRNO_GENERIC = 1;
const ERRNO_TIMEOUT = 2;
const ERRNO_ERROR_IN_REPLY = 3;
const ERRNO_OID_NOT_INCREASING = 4;
const VERSION_1 = 1;
const VERSION_2C = 2;
const VERSION_2c = SNMP::VERSION_2C;
const VERSION_3 = 3;
public $info;
public $max_oids;
public $valueretrieval;
public $oid_output_format;
public $value_output_format;
public $enum_print;
public $quick_print;
public $oid_increasing_check;
public $bulk_walk_size;
private $version;
private $hostname;
private $port;
private $community;
private $timeout;
private $retries;
private $username;
private $sec_level;
private $auth_proto;
private $auth_pass;
private $priv_proto;
private $priv_pass;
private $contextName;
private $contextEngineID;
private $errno;
function __construct($version, $hostname, $community, $timeout = 1000000, $retries = 3) {
$timeout /= 1000;
$this->max_oids = 0;
if (function_exists('snmp_get_valueretrieval')) {
$this->valueretrieval = snmp_get_valueretrieval();
}
$this->oid_output_format = NULL;
$this->enum_print = NULL;
if (function_exists('snmp_get_quick_print')) {
$this->quick_print = snmp_get_quick_print();
}
$this->version = $version;
$delcount = substr_count($hostname, ':');
if ($delcount == 1) {
$hostname = explode(':', $hostname);
$this->hostname = array_shift($hostname);
$this->port = (cacti_sizeof($hostname) ? array_shift($hostname) : 161);
} elseif ($delcount > 1) {
$hostname = explode(':', $hostname);
$this->port = $hostname[sizeof($hostname)-1];
unset($hostname[sizeof($hostname)-1]);
$this->hostname = implode(':', $hostname);
} else {
$this->hostname = $hostname;
$this->port = '161';
}
$this->timeout = $timeout;
$this->retries = $retries;
$this->value_output_format = SNMP_STRING_OUTPUT_GUESS;
if ($version == SNMP::VERSION_3) {
$this->username = $community;
} else {
$this->community = $community;
}
$this->info = array (
'hostname' => $this->hostname,
'port' => $this->port,
'timeout' => $this->timeout,
'retries' => $this->retries
);
}
function __destruct() {
$this->close();
}
function setSecurity($sec_level, $auth_protocol, $auth_passphrase, $priv_protocol,
$priv_passphrase, $contextName, $contextEngineID) {
$this->sec_level = $sec_level;
$this->auth_proto = $auth_protocol;
$this->auth_pass = $auth_passphrase;
$this->priv_proto = $priv_protocol;
$this->priv_pass = $priv_passphrase;
$this->contextName = $contextName;
$this->contextEngineID = $contextEngineID;
return true;
}
function close() {
return true;
}
private function apply_options($backup = array()) {
if (cacti_sizeof($backup) == 0) {
if (function_exists('snmp_get_valueretrieval')) {
$backup['valueretrieval'] = snmp_get_valueretrieval();
snmp_set_valueretrieval($this->valueretrieval);
$backup['quick_print'] = snmp_get_quick_print();
snmp_set_quick_print($this->quick_print);
if ($this->oid_output_format !== NULL) {
snmp_set_oid_output_format($this->oid_output_format);
}
if ($this->enum_print !== NULL) {
if (function_exists('snmp_set_enum_print')) {
snmp_set_enum_print($this->enum_print);
}
}
}
} else {
if (function_exists('snmp_get_valueretrieval')) {
if (isset($backup['valueretrieval'])) {
snmp_set_valueretrieval($backup['valueretrieval']);
}
if (isset($backup['quick_print'])) {
snmp_set_quick_print($backup['quick_print']);
}
}
$backup = true;
}
return $backup;
}
private function uniget($command, $oids) {
$this->errno = SNMP::ERRNO_NOERROR;
$array_output = true;
$output = array();
$function_name = "cacti_snmp_$command";
$options_backup = $this->apply_options();
if (!is_array($oids)) {
$array_output = false;
$oids = array($oids);
}
foreach ($oids as $oid) {
$output[$oid] = $function_name($this->hostname, $this->community, $oid,
$this->version, $this->username, $this->auth_pass, $this->auth_proto,
$this->priv_pass, $this->priv_proto, $this->contextName, $this->port,
$this->timeout, $this->retries, 'SNMP', $this->contextEngineID,
$this->value_output_format);
}
$this->apply_options($options_backup);
if (cacti_sizeof($output) == 0) {
$this->errno = SNMP::TIMEOUT;
}
if ($array_output == false) {
if (cacti_sizeof($output) == 0) {
return false;
}
return array_shift($output);
}
return $output;
}
function get($oid) {
return $this->uniget('get', $oid);
}
function getnext($oid) {
return $this->uniget('getnext', $oid);
}
function walk($oid, $dummy = false, $max_repetitions = 10, $non_repeaters = 0) {
$this->errno = SNMP::ERRNO_NOERROR;
if (is_array($oid)) {
trigger_error('Multi OID walks are not supported!', E_WARNING);
return false;
}
$options_backup = $this->apply_options();
$result = cacti_snmp_walk($this->hostname, $this->community, $oid, $this->version,
$this->username, $this->auth_pass, $this->auth_proto, $this->priv_pass,
$this->priv_proto, $this->contextName, $this->port, $this->timeout,
$this->retries, $max_repetitions, 'SNMP', $this->contextEngineID,
$this->value_output_format);
if ($result === false) {
$this->errno = SNMP::TIMEOUT;
}
$this->apply_options($options_backup);
$output = array();
foreach($result as $item) {
$output[$item['oid']] = $item['value'];
}
return $output;
}
function getErrno() {
return $this->errno;
}
function getError() {
return '';
}
function set($oid, $type, $value) {
trigger_error('set function is not implemented', E_WARNING);
return false;
}
function __set($name, $value) {
switch ($name) {
case 'info':
trigger_error('info property is read-only', E_WARNING);
return false;
case 'valuretrieval':
switch ($value) {
case SNMP_VALUE_LIBRARY:
case SNMP_VALUE_PLAIN:
case SNMP_VALUE_OBJECT:
$this->$name = $value;
return true;
default:
trigger_error("Unknown SNMP value retrieval method '$value'", E_WARNING);
return false;
}
case 'oid_output_format':
switch ($value) {
case SNMP_OID_OUTPUT_SUFFIX:
case SNMP_OID_OUTPUT_MODULE:
case SNMP_OID_OUTPUT_FULL:
case SNMP_OID_OUTPUT_NUMERIC:
case SNMP_OID_OUTPUT_UCD:
case SNMP_OID_OUTPUT_NONE:
$this->$name = $value;
return true;
default:
trigger_error("Unknown SNMP output print format '$value'", E_WARNING);
return false;
}
case 'max_oids':
case 'enum_print':
case 'quick_print':
default:
$this->$name = $value;
break;
}
}
public function getType(): string {
return "SNMP class";
}
}
-36
View File
@@ -1,36 +0,0 @@
<?php
/*
+-------------------------------------------------------------------------+
| Copyright (C) 2004-2026 The Cacti Group |
| |
| This program is free software; you can redistribute it and/or |
| modify it under the terms of the GNU General Public License |
| as published by the Free Software Foundation; either version 2 |
| of the License, or (at your option) any later version. |
| |
| This program is distributed in the hope that it will be useful, |
| but WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| GNU General Public License for more details. |
+-------------------------------------------------------------------------+
| Cacti: The Complete RRDtool-based Graphing Solution |
+-------------------------------------------------------------------------+
| This code is designed, written, and maintained by the Cacti Group. See |
| about.php and/or the AUTHORS file for specific developer information. |
+-------------------------------------------------------------------------+
| http://www.cacti.net/ |
+-------------------------------------------------------------------------+
*/
/*
* Alias the PHP SNMP extension to the phpsnmp namespace so it can be
* referenced as such in lib/snmp.php.
*/
namespace phpsnmp;
class SNMP extends \SNMP {
public $bulk_walk_size;
public $value_output_format;
}
-25
View File
@@ -1,25 +0,0 @@
<?php
/*
+-------------------------------------------------------------------------+
| Copyright (C) 2004-2026 The Cacti Group |
| |
| This program is free software; you can redistribute it and/or |
| modify it under the terms of the GNU General Public License |
| as published by the Free Software Foundation; either version 2 |
| of the License, or (at your option) any later version. |
| |
| This program is distributed in the hope that it will be useful, |
| but WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| GNU General Public License for more details. |
+-------------------------------------------------------------------------+
| Cacti: The Complete RRDtool-based Graphing Solution |
+-------------------------------------------------------------------------+
| This code is designed, written, and maintained by the Cacti Group. See |
| about.php and/or the AUTHORS file for specific developer information. |
+-------------------------------------------------------------------------+
| http://www.cacti.net/ |
+-------------------------------------------------------------------------+
*/
header("Location:../index.php");
+22
View File
@@ -1254,6 +1254,28 @@ function api_device_save(int $id, int $device_template_id, string $description,
}
if ($device_id > 0) {
/* The shared credential cache holds only SNMPv3 tuples, keyed by the exact
* credential fields. Bump the version only when this host's v3 membership or
* one of those credential fields actually changed, so saving an unrelated
* field (notes, availability, ...) does not force a needless cache rebuild. */
$was_v3 = isset($previous['snmp_version']) && $previous['snmp_version'] == 3;
$is_v3 = $save['snmp_version'] == 3;
$cred_changed = ($was_v3 != $is_v3);
if ($is_v3 && $was_v3) {
foreach (['snmp_community', 'snmp_username', 'snmp_password', 'snmp_auth_protocol', 'snmp_priv_passphrase', 'snmp_priv_protocol'] as $field) {
if ((string) ($previous[$field] ?? '') !== (string) ($save[$field] ?? '')) {
$cred_changed = true;
break;
}
}
}
if ($cred_changed) {
set_config_option('snmp_cred_version', uniqid('', true));
}
if (read_config_option('extended_paths') == 'on') {
$pattern = read_config_option('extended_paths_type');
$maxdirs = read_config_option('extended_paths_hashes');
+618
View File
@@ -0,0 +1,618 @@
<?php
/*
+-------------------------------------------------------------------------+
| Copyright (C) 2004-2026 The Cacti Group |
| |
| This program is free software; you can redistribute it and/or |
| modify it under the terms of the GNU General Public License |
| as published by the Free Software Foundation; either version 2 |
| of the License, or (at your option) any later version. |
| |
| This program is distributed in the hope that it will be useful, |
| but WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| GNU General Public License for more details. |
+-------------------------------------------------------------------------+
| Cacti: The Complete RRDtool-based Graphing Solution |
+-------------------------------------------------------------------------+
| This code is designed, written, and maintained by the Cacti Group. See |
| about.php and/or the AUTHORS file for specific developer information. |
+-------------------------------------------------------------------------+
| http://www.cacti.net/ |
+-------------------------------------------------------------------------+
*/
namespace Cacti\Cache;
/**
* A storage tier for SharedCache. Backends persist one opaque wire payload and
* a short plaintext checksum per store name. The checksum lets a producer
* decide whether a rebuild is needed without decoding (or decrypting) the body.
*/
interface CacheBackend {
/** Whether this tier can be used in the current runtime/host. */
public function isAvailable(): bool;
/** Persist $payload (+ $checksum sidecar). Returns success. */
public function write(string $name, string $payload, string $checksum): bool;
/** Return the stored payload, or null when absent. */
public function read(string $name): ?string;
/** Return the stored checksum without decoding the payload, or null. */
public function readChecksum(string $name): ?string;
/** Remove any stored data for $name. */
public function clear(string $name): void;
/** True when this tier is only visible to the current process. */
public function isProcessLocal(): bool;
}
/**
* Process-local tier. Never shared; used as the terminal fallback and as the
* in-process memo so repeated fetches do not re-touch a shared tier.
*/
class StaticBackend implements CacheBackend {
/** @var array<string,array{p:string,c:string}> */
private static array $store = [];
public function isAvailable(): bool {
return true;
}
public function write(string $name, string $payload, string $checksum): bool {
self::$store[$name] = ['p' => $payload, 'c' => $checksum];
return true;
}
public function read(string $name): ?string {
return self::$store[$name]['p'] ?? null;
}
public function readChecksum(string $name): ?string {
return self::$store[$name]['c'] ?? null;
}
public function clear(string $name): void {
unset(self::$store[$name]);
}
public function isProcessLocal(): bool {
return true;
}
}
/**
* Durable file tier. The payload is written as a non-executable JSON data file
* and read back with file_get_contents(); it is never include()d, so a planted
* cache file cannot execute as PHP. Shared across processes because the file
* persists on disk.
*/
class FileBackend implements CacheBackend {
public function __construct(private string $dir) {
}
public function isAvailable(): bool {
if ($this->dir === '') {
return false;
}
if (!is_dir($this->dir)) {
@mkdir($this->dir, 0770, true);
}
return is_dir($this->dir) && is_writable($this->dir);
}
private function file(string $name): string {
return $this->dir . '/' . $name . '.cache';
}
public function write(string $name, string $payload, string $checksum): bool {
$file = $this->file($name);
$tmp = $file . '.' . getmypid() . '.tmp';
$blob = json_encode([
'checksum' => $checksum,
'payload' => base64_encode($payload),
]);
if ($blob === false || @file_put_contents($tmp, $blob, LOCK_EX) === false) {
return false;
}
@chmod($tmp, 0600);
if (!@rename($tmp, $file)) {
@unlink($tmp);
return false;
}
return true;
}
/** @return array{checksum?:string,payload?:string}|null */
private function load(string $name): ?array {
$file = $this->file($name);
if (!is_file($file)) {
return null;
}
$blob = @file_get_contents($file);
if ($blob === false) {
return null;
}
$data = json_decode($blob, true);
return is_array($data) ? $data : null;
}
public function read(string $name): ?string {
$data = $this->load($name);
if ($data === null || !isset($data['payload'])) {
return null;
}
$raw = base64_decode((string) $data['payload'], true);
return $raw === false ? null : $raw;
}
public function readChecksum(string $name): ?string {
$data = $this->load($name);
/* A corrupt cache file could decode to a non-string checksum; treat that
* as absent so it falls through to a rebuild instead of raising a
* TypeError from this ?string return. */
return (isset($data['checksum']) && is_string($data['checksum'])) ? $data['checksum'] : null;
}
public function clear(string $name): void {
$file = $this->file($name);
if (is_file($file)) {
@unlink($file);
}
}
public function isProcessLocal(): bool {
return false;
}
}
/**
* Shared-memory tier (System V) for POSIX hosts. The segment holds a small
* header (payload length + checksum) followed by the wire payload, so a reader
* can validate the checksum without pulling the whole body. Unavailable on
* Windows, where ftok()/shmop semantics differ; callers fall back to the file
* tier there.
*/
class ShmopBackend implements CacheBackend {
private const HEADER_LEN = 68; // 4-byte length + 64-byte checksum
private const CHECKSUM_LEN = 64;
public function __construct(private string $dir, private string $osType) {
}
public function isAvailable(): bool {
if ($this->osType === 'win32' || $this->dir === '') {
return false;
}
if (!function_exists('shmop_open') || !function_exists('ftok')) {
return false;
}
if (!is_dir($this->dir)) {
@mkdir($this->dir, 0770, true);
}
return is_dir($this->dir) && is_writable($this->dir);
}
private function tokenFile(string $name): string {
return $this->dir . '/' . $name . '.shmtoken';
}
private function key(string $name): int {
$token = $this->tokenFile($name);
if (!is_file($token)) {
@touch($token);
@chmod($token, 0600);
}
return @ftok($token, 'C');
}
public function write(string $name, string $payload, string $checksum): bool {
$key = $this->key($name);
if ($key === -1) {
return false;
}
$header = pack('N', strlen($payload)) . str_pad(substr($checksum, 0, self::CHECKSUM_LEN), self::CHECKSUM_LEN, "\0");
$blob = $header . $payload;
$size = strlen($blob);
// A segment is fixed-size at creation, so drop any prior one first.
$existing = @shmop_open($key, 'a', 0, 0);
if ($existing !== false) {
@shmop_delete($existing);
$this->closeSegment($existing);
}
$segment = @shmop_open($key, 'c', 0600, $size);
if ($segment === false) {
return false;
}
$written = @shmop_write($segment, $blob, 0);
$this->closeSegment($segment);
return $written === $size;
}
/** @return \Shmop|resource|false */
private function openForRead(string $name) {
$key = $this->key($name);
if ($key === -1) {
return false;
}
return @shmop_open($key, 'a', 0, 0);
}
public function read(string $name): ?string {
$segment = $this->openForRead($name);
if ($segment === false) {
return null;
}
$size = shmop_size($segment);
if ($size <= self::HEADER_LEN) {
$this->closeSegment($segment);
return null;
}
$blob = shmop_read($segment, 0, $size);
$this->closeSegment($segment);
if ($blob === false || strlen($blob) < self::HEADER_LEN) {
return null;
}
$length = unpack('N', substr($blob, 0, 4))[1];
$payload = substr($blob, self::HEADER_LEN, $length);
return strlen($payload) === $length ? $payload : null;
}
public function readChecksum(string $name): ?string {
$segment = $this->openForRead($name);
if ($segment === false) {
return null;
}
$size = shmop_size($segment);
if ($size < self::HEADER_LEN) {
$this->closeSegment($segment);
return null;
}
$header = shmop_read($segment, 0, self::HEADER_LEN);
$this->closeSegment($segment);
if ($header === false || strlen($header) < self::HEADER_LEN) {
return null;
}
return rtrim(substr($header, 4, self::CHECKSUM_LEN), "\0");
}
public function clear(string $name): void {
$segment = $this->openForRead($name);
if ($segment !== false) {
@shmop_delete($segment);
$this->closeSegment($segment);
}
$token = $this->tokenFile($name);
if (is_file($token)) {
@unlink($token);
}
}
public function isProcessLocal(): bool {
return false;
}
/** @param \Shmop|resource $segment */
private function closeSegment($segment): void {
// shmop_close() was removed in PHP 8.0 (segments close automatically).
if (function_exists('shmop_close') && is_resource($segment)) {
@shmop_close($segment);
}
}
}
/**
* A generalized, cross-process object cache for Cacti utilities.
*
* One SharedCache instance manages one named store (one file / one shared
* memory segment), so different subsystems keep separate cache files. A
* producer process builds the object once and store()s it to the highest
* priority shared tier; every consumer process fetch()es and decodes it a
* single time into process memory.
*
* Tiers are tried in priority order; the default is the durable file tier,
* then POSIX shared memory, then a process-local static fallback. When only
* the process-local tier is available there is no cross-process sharing and
* each consumer must build its own copy.
*
* With 'encrypted' => true the payload is sealed with Cacti's authenticated
* per-installation secret key (cacti_encrypt_secret()/cacti_decrypt_secret())
* before it touches disk or shared memory.
*/
class SharedCache {
private string $name;
private bool $encrypted;
/** @var CacheBackend[] */
private array $backends;
private bool $memoLoaded = false;
/** @var mixed */
private $memo = null;
/**
* @param string $name Store name; also the cache file stem.
* @param array $options encrypted(bool), cache_dir(string), os_type(string),
* backends(string[] priority list).
*/
public function __construct(string $name, array $options = []) {
$this->name = preg_replace('/[^A-Za-z0-9_\-]/', '_', $name);
$this->encrypted = (bool) ($options['encrypted'] ?? false);
$dir = (string) ($options['cache_dir'] ?? self::defaultCacheDir());
$os = (string) ($options['os_type'] ?? self::osType());
$order = $options['backends'] ?? ['file', 'shmop', 'static'];
$this->backends = [];
$hasLocal = false;
foreach ($order as $id) {
$backend = self::makeBackend($id, $dir, $os);
if ($backend !== null && $backend->isAvailable()) {
$this->backends[] = $backend;
if ($backend->isProcessLocal()) {
$hasLocal = true;
}
}
}
if (!$hasLocal) {
$this->backends[] = new StaticBackend();
}
}
/**
* Encode $data and write it to the highest priority shared tier. The
* in-process memo is always updated. Returns false when no shared tier
* accepted the write (callers should then treat the data as unshared).
*
* @param mixed $data
* @param string|null $checksum Optional change token for checksum().
*/
public function store($data, ?string $checksum = null): bool {
$wire = $this->encode($data);
if ($wire === false) {
return false;
}
$sum = $checksum ?? sha1($wire);
$this->memo = $data;
$this->memoLoaded = true;
foreach ($this->backends as $backend) {
if ($backend->isProcessLocal()) {
$backend->write($this->name, $wire, $sum);
continue;
}
if ($backend->write($this->name, $wire, $sum)) {
return true;
}
/* The write failed; drop any stale entry in this higher tier so a
* later fetch()/checksum() cannot read it in preference to the lower
* tier we are about to try. */
$backend->clear($this->name);
}
return false;
}
/**
* Decode and return the cached object, or false when nothing is cached (or
* the payload cannot be decoded/decrypted). Memoized per process.
*
* @return mixed
*/
public function fetch() {
if ($this->memoLoaded) {
return $this->memo;
}
foreach ($this->backends as $backend) {
$wire = $backend->read($this->name);
if ($wire === null) {
continue;
}
$data = $this->decode($wire);
if ($data !== false) {
$this->memo = $data;
$this->memoLoaded = true;
return $data;
}
}
$this->memoLoaded = true;
$this->memo = false;
return false;
}
/**
* Return the stored change token from the highest priority shared tier
* without decoding the body, or null when nothing is stored.
*/
public function checksum(): ?string {
foreach ($this->backends as $backend) {
if ($backend->isProcessLocal()) {
continue;
}
$checksum = $backend->readChecksum($this->name);
if ($checksum !== null) {
return $checksum;
}
}
return null;
}
/** Drop the store from every tier. */
public function invalidate(): void {
foreach ($this->backends as $backend) {
$backend->clear($this->name);
}
$this->memo = null;
$this->memoLoaded = false;
}
/** True when at least one cross-process tier is active. */
public function isShared(): bool {
foreach ($this->backends as $backend) {
if (!$backend->isProcessLocal()) {
return true;
}
}
return false;
}
/**
* @param mixed $data
* @return string|false
*/
private function encode($data) {
$serialized = serialize($data);
if (!$this->encrypted) {
return $serialized;
}
if (!function_exists('cacti_encrypt_secret')) {
return false;
}
try {
$wire = \cacti_encrypt_secret($serialized);
} catch (\Throwable $e) {
return false;
}
return ($wire === '' || $wire === false) ? false : $wire;
}
/**
* @return mixed false on failure
*/
private function decode(string $wire) {
if ($this->encrypted) {
if (!function_exists('cacti_decrypt_secret')) {
return false;
}
$plain = \cacti_decrypt_secret($wire);
if ($plain === false) {
return false;
}
$wire = $plain;
}
$data = @unserialize($wire, ['allowed_classes' => false]);
// Our stored payloads are always arrays; a false result means failure.
return is_array($data) ? $data : false;
}
private static function defaultCacheDir(): string {
global $config;
if (!empty($config['cache_dir'])) {
return $config['cache_dir'];
}
$base = $config['base_path'] ?? getcwd();
return $base . '/cache';
}
private static function osType(): string {
global $config;
if (!empty($config['cacti_server_os'])) {
return $config['cacti_server_os'];
}
return strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' ? 'win32' : 'unix';
}
private static function makeBackend(string $id, string $dir, string $os): ?CacheBackend {
switch ($id) {
case 'opcache':
case 'file':
return new FileBackend($dir);
case 'shmop':
return new ShmopBackend($dir, $os);
case 'static':
return new StaticBackend();
default:
return null;
}
}
}
+7 -7
View File
@@ -89,7 +89,7 @@ function htmx_version(): string {
}
/**
* Subresource Integrity hash pinned to the exact vendored htmx 2.0.10 build
* Subresource Integrity hash pinned to the exact vendored htmx 2.0.11 build
* (include/js/htmx.js). This is a constant, not a value recomputed from the
* served file at runtime: a self-referential hash gives no supply-chain
* protection, since swapping htmx.js would simply re-hash to match it. With
@@ -98,7 +98,7 @@ function htmx_version(): string {
* On an htmx upgrade, replace the vendored file and recompute this value:
* php -r 'echo "sha384-".base64_encode(hash_file("sha384","include/js/htmx.js",true));'
*/
const HTMX_2_0_10_SRI = 'sha384-Q+Dky3iHVJOr6wUjQ4ulh6uQ76an/t+ak1+PjMVaxRjbZamFLAG+u9InkfjbsEQf';
const HTMX_2_0_11_SRI = 'sha384-gmJEF2eAKY4e+FDN+qtKIivWyb6ANwDB7JUdUybKgQspPKyEX/pIRZG/0uaRoW2C';
/**
* Returns a <script> tag that loads the vendored htmx.js with an SRI
@@ -110,7 +110,7 @@ const HTMX_2_0_10_SRI = 'sha384-Q+Dky3iHVJOr6wUjQ4ulh6uQ76an/t+ak1+PjMVaxRjbZamF
* navigation and AJAX submission model. Pages that want htmx behaviour opt in
* per-element with explicit hx-* attributes.
*
* The integrity attribute uses the HTMX_2_0_10_SRI constant pinned to the
* The integrity attribute uses the HTMX_2_0_11_SRI constant pinned to the
* vendored build (see that constant for why the hash is not recomputed here).
*
* The src is root-absolute (prefixed with CACTI_PATH_URL) so the asset
@@ -124,14 +124,14 @@ const HTMX_2_0_10_SRI = 'sha384-Q+Dky3iHVJOr6wUjQ4ulh6uQ76an/t+ak1+PjMVaxRjbZamF
* stale hash after include/js/htmx.js changes.
*
* Two wiring pieces precede the script element:
* - an htmx-config meta that disables allowEval/allowScriptTags. htmx 2.0.10
* - an htmx-config meta that disables allowEval/allowScriptTags. htmx 2.0.11
* defaults both to true, which Cacti's CSP (no unsafe-eval) forbids. The
* meta is read by htmx at load, so it must appear before the script.
* - an htmx:configRequest listener that adds the csrf-magic token to
* body-based (POST/PUT/PATCH) htmx requests. Cacti validates the
* __csrf_magic field on POSTs; layout.js injects it into $.post payloads,
* but htmx has no such hook, so the first hx-post would otherwise fail
* CSRF validation. GET and DELETE are excluded because htmx 2.0.10 encodes
* CSRF validation. GET and DELETE are excluded because htmx 2.0.11 encodes
* their parameters into the URL (methodsThatUseUrlParams), which would
* leak the token into query strings and server logs.
*
@@ -151,7 +151,7 @@ function htmx_script_tag(): string {
// md5 is a cache-buster for the asset URL only, recomputed on every call
// (not cached in a static) so an htmx.js upgrade is visible without a
// process restart. Integrity is the pinned constant, never derived from
// the served file (see HTMX_2_0_10_SRI).
// the served file (see HTMX_2_0_11_SRI).
$md5 = md5_file($js_path);
// CACTI_PATH_URL is defined by include/global_path.php during a normal
@@ -181,7 +181,7 @@ function htmx_script_tag(): string {
. "</script>\n";
$tag = "<script type='text/javascript' $nonce_attr src='" . htmlspecialchars($url, ENT_QUOTES, 'UTF-8') . "'"
. " integrity='" . HTMX_2_0_10_SRI . "'"
. " integrity='" . HTMX_2_0_11_SRI . "'"
. " crossorigin='anonymous'></script>\n";
// Both wiring pieces precede the script element (see the function doc):
+2 -2
View File
@@ -52,13 +52,13 @@ class MibCache {
}
public function install(string $path, bool $replace = false, string $mib_name = 'optional') : mixed {
include_once(CACTI_PATH_INCLUDE . '/vendor/phpsnmp/mib_parser.php');
include_once(__DIR__ . '/mib_parser.php');
$mp = new MibParser();
$mp->add_mib($path, $mib_name);
$mp->generate();
if (isset($mp->mib) && isset($mp->oids) && $mp->mib) {
if (isset($mp->mib) && $mp->mib) {
// check if this mib has already been installed
$existing = db_fetch_cell_prepared('SELECT 1 FROM snmpagent_mibs WHERE `name` = ?', [$mp->mib]);
@@ -49,9 +49,9 @@
*
*/
class MibParser extends MibCache {
protected $parsed = array();
public $oids = array();
public $mib = false;
protected array $parsed = [];
public array $oids = [];
public mixed $mib = false;
/**
* Constructor
@@ -62,39 +62,45 @@ class MibParser extends MibCache {
error_reporting(E_ALL);
}
function add_mib($filename, $mib_name) {
MibParser::parse_mib(file_get_contents($filename), $mib_name, true);
function add_mib(string $filename, string $mib_name): void {
$mibtext = file_get_contents($filename);
if ($mibtext === false) {
return;
}
MibParser::parse_mib($mibtext, $mib_name, true);
}
/**
* Get Tokens
*
* @param string $text
* @param string $text
* @return array
*/
function get_tokens($text) {
$in_quote = false;
$in_quote = false;
$in_comment = false;
$token = '';
$tokens = array();
$length = strlen($text);
$token = '';
$tokens = [];
$length = strlen($text);
for($i = 0; $i < $length; $i++) {
for ($i = 0; $i < $length; $i++) {
if ($in_quote) {
if ($text[$i] == '"') {
$in_quote = false;
if ($token != '') {
/* strip whitespaces from the end of the beginning of every object description row */
$lines = preg_split( '/\r\n|\r|\n/', $token);
// strip whitespaces from the end of the beginning of every object description row
$lines = preg_split('/\r\n|\r|\n/', $token) ?: [];
$token = '';
foreach($lines as $line) {
foreach ($lines as $line) {
$token .= trim($line) . "\r\n";
}
$tokens[] = $token;
$token = '';
$token = '';
}
} else {
$token .= $text[$i];
@@ -106,10 +112,10 @@ class MibParser extends MibCache {
} else {
switch($text[$i]) {
case ':':
if ($text[$i+1] == ':' && $text[$i+2] == '=') {
if ($text[$i + 1] == ':' && $text[$i + 2] == '=') {
if ($token != '') {
$tokens[] = $token;
$token = '';
$token = '';
}
$tokens[] = '::=';
@@ -120,10 +126,10 @@ class MibParser extends MibCache {
break;
case '.':
if ($text[$i+1] == '.') {
if ($text[$i + 1] == '.') {
if ($token != '') {
$tokens[] = $token;
$token = '';
$token = '';
}
$tokens[] = '..';
@@ -142,7 +148,7 @@ class MibParser extends MibCache {
case '|':
if ($token != '') {
$tokens[] = $token;
$token = '';
$token = '';
}
$tokens[] = $text[$i];
@@ -154,13 +160,13 @@ class MibParser extends MibCache {
case "\r":
if ($token != '') {
$tokens[] = $token;
$token = '';
$token = '';
}
break;
case '-':
if ($text[$i+1] == '-') {
$in_comment = true;
if ($text[$i + 1] == '-') {
$in_comment = true;
} else {
$token .= $text[$i];
}
@@ -186,16 +192,16 @@ class MibParser extends MibCache {
/**
* Parse simple token
*
* @param array $tokens
* @param integer $index
* @param array $allowed
* @param array $tokens
* @param integer $index
* @param array $allowed
* @return array
*/
function parse_simple_token($tokens, &$index, $allowed=null) {
function parse_simple_token($tokens, &$index, $allowed = null) {
$index++;
if (is_array($allowed)) {
if (in_array(strtolower($tokens[$index]), $allowed)) {
if (in_array(strtolower($tokens[$index]), $allowed, true)) {
return $tokens[$index];
}
} elseif (is_null($allowed)) {
@@ -207,40 +213,39 @@ class MibParser extends MibCache {
}
trigger_error("unknown token {$tokens[$index]} {$tokens[$index]}", E_USER_ERROR);
return $tokens[$index];
}
/**
* Parse SYNTAX token
*
* @param array $tokens
* @param integer $index
* @param array $tokens
* @param integer $index
* @return array
*/
function parse_SYNTAX_token($tokens, &$index) {
$ret = null;
switch($tokens[$index+1]) {
switch($tokens[$index + 1]) {
case 'SEQUENCE':
if ($tokens[$index+2] == 'OF') {
if ($tokens[$index + 2] == 'OF') {
$index += 3;
if ($tokens[$index] == '{') {
$ret = array('SEQUENCE OF'=>MibParser::parse_bracket_token($tokens, $index, '{', '}'));
$ret = ['SEQUENCE OF'=>MibParser::parse_bracket_token($tokens, $index, '{', '}')];
} else {
$ret = array('SEQUENCE OF'=>$tokens[$index]);
$ret = ['SEQUENCE OF'=>$tokens[$index]];
}
}
break;
case 'OCTET':
if ($tokens[$index+2] == 'STRING') {
if ($tokens[$index + 2] == 'STRING') {
$index += 3;
if ($tokens[$index] == '{') {
$ret = array('OCTET STRING'=>MibParser::parse_bracket_token($tokens, $index, '{', '}'));
$ret = ['OCTET STRING'=>MibParser::parse_bracket_token($tokens, $index, '{', '}')];
} elseif ($tokens[$index] == '(') {
$ret = array('OCTET STRING'=>MibParser::parse_bracket_token($tokens, $index, '(', ')'));
$ret = ['OCTET STRING'=>MibParser::parse_bracket_token($tokens, $index, '(', ')')];
} else {
$ret = 'OCTET STRING';
}
@@ -248,12 +253,12 @@ class MibParser extends MibCache {
break;
case 'OBJECT':
if ($tokens[$index+2] == 'IDENTIFIER') {
if ($tokens[$index + 2] == 'IDENTIFIER') {
$index++;
$ret = $tokens[$index] . ' ' . $tokens[$index+1];
$ret = $tokens[$index] . ' ' . $tokens[$index + 1];
$index++;
} else {
trigger_error("unknown token {$tokens[$index+1]} {$tokens[$index+2]}", E_USER_ERROR);
trigger_error("unknown token {$tokens[$index + 1]} {$tokens[$index + 2]}", E_USER_ERROR);
}
break;
@@ -275,12 +280,12 @@ class MibParser extends MibCache {
$index++;
$ret = $tokens[$index];
if ($tokens[$index+1] == '{') {
if ($tokens[$index + 1] == '{') {
$index++;
$ret = array($ret=>MibParser::parse_bracket_token($tokens, $index, '{', '}'));
} elseif ($tokens[$index+1] == '(') {
$ret = [$ret=>MibParser::parse_bracket_token($tokens, $index, '{', '}')];
} elseif ($tokens[$index + 1] == '(') {
$index++;
$ret = array($ret=>MibParser::parse_bracket_token($tokens, $index, '(', ')'));
$ret = [$ret=>MibParser::parse_bracket_token($tokens, $index, '(', ')')];
}
break;
@@ -288,12 +293,12 @@ class MibParser extends MibCache {
$index++;
$ret = $tokens[$index];
if ($tokens[$index+1] == '{') {
if ($tokens[$index + 1] == '{') {
$index++;
$ret = array($ret=>MibParser::parse_bracket_token($tokens, $index, '{', '}'));
} elseif ($tokens[$index+1] == '(') {
$ret = [$ret=>MibParser::parse_bracket_token($tokens, $index, '{', '}')];
} elseif ($tokens[$index + 1] == '(') {
$index++;
$ret = array($ret=>MibParser::parse_bracket_token($tokens, $index, '(', ')'));
$ret = [$ret=>MibParser::parse_bracket_token($tokens, $index, '(', ')')];
}
break;
@@ -305,16 +310,16 @@ class MibParser extends MibCache {
/**
* Parse bracket token
*
* @param array $tokens
* @param integer $index
* @param integer $start
* @param integer $end
* @param array $tokens
* @param integer $index
* @param string $start
* @param string $end
* @return array
*/
function parse_bracket_token($tokens, &$index, $start, $end) {
$begin = $index + 1;
while($index + 1 < count($tokens) && $tokens[$index] != $end) {
while ($index + 1 < count($tokens) && $tokens[$index] != $end) {
$index++;
if ($tokens[$index] == $start) {
@@ -329,65 +334,66 @@ class MibParser extends MibCache {
/**
* Parse a MIB file
*
* @param string $mibtext
* @param string $mibtext
* @param boolean $full
* @param mixed $mib_name
*/
function parse_mib($mibtext, $mib_name, $full=false) {
function parse_mib($mibtext, $mib_name, $full = false): void {
$tokens = MibParser::get_tokens($mibtext);
$cnt = count($tokens);
$rec = array();
$cnt = count($tokens);
$rec = [];
for($index = 0; $index < $cnt; $index++) {
if ($tokens[$index] == 'DEFINITIONS' && $tokens[$index+1] == "::=" && $tokens[$index+2] == "BEGIN"){
$mib_name = $tokens[$index-1];
for ($index = 0; $index < $cnt; $index++) {
if ($tokens[$index] == 'DEFINITIONS' && $tokens[$index + 1] == '::=' && $tokens[$index + 2] == 'BEGIN') {
$mib_name = $tokens[$index - 1];
$this->mib = $mib_name;
} elseif (in_array($tokens[$index], array('OBJECT-IDENTITY', 'OBJECT-TYPE', 'OBJECT-GROUP', 'NOTIFICATION-GROUP', 'MODULE-IDENTITY', 'NOTIFICATION-TYPE'))) {
if ($tokens[$index-1] != ',' && $tokens[$index+1] != 'FROM' && $tokens[$index+1] != 'MACRO') {
} elseif (in_array($tokens[$index], ['OBJECT-IDENTITY', 'OBJECT-TYPE', 'OBJECT-GROUP', 'NOTIFICATION-GROUP', 'MODULE-IDENTITY', 'NOTIFICATION-TYPE'], true)) {
if ($tokens[$index - 1] != ',' && $tokens[$index + 1] != 'FROM' && $tokens[$index + 1] != 'MACRO') {
if (isset($rec['NAME']) && isset($rec['VALUE'])) {
$this->parsed[] = $rec;
}
$rec = array(
'NAME' => $tokens[$index-1],
$rec = [
'NAME' => $tokens[$index - 1],
'MIB' => $mib_name,
'TYPE' => $tokens[$index]
);
];
}
} elseif ( $tokens[$index] == 'TEXTUAL-CONVENTION') {
if ($tokens[$index-1] == '::=') {
} elseif ($tokens[$index] == 'TEXTUAL-CONVENTION') {
if ($tokens[$index - 1] == '::=') {
if (isset($rec['NAME']) && isset($rec['VALUE'])) {
$this->parsed[] = $rec;
}
$rec = array(
'NAME' => $tokens[$index-2],
$rec = [
'NAME' => $tokens[$index - 2],
'MIB' => $mib_name,
'TYPE' => $tokens[$index],
'VALUE' => 'TEXTUAL-CONVENTION'
);
];
}
} elseif ($tokens[$index] == 'OBJECT') {
if ($tokens[$index+1] == 'IDENTIFIER' && $tokens[$index-1] != '(' && $tokens[$index-1] != '::=' && $tokens[$index-1] != 'SYNTAX' && $tokens[$index-2] != '(') {
if ($tokens[$index + 1] == 'IDENTIFIER' && $tokens[$index - 1] != '(' && $tokens[$index - 1] != '::=' && $tokens[$index - 1] != 'SYNTAX' && $tokens[$index - 2] != '(') {
if (isset($rec['NAME']) && isset($rec['VALUE'])) {
$this->parsed[] = $rec;
}
$rec = array(
'NAME' => $tokens[$index-1],
$rec = [
'NAME' => $tokens[$index - 1],
'MIB' => $mib_name,
'TYPE' => $tokens[$index]
);
];
}
} elseif ($tokens[$index] == '{') {
MibParser::parse_bracket_token($tokens, $index, '{', '}');
} elseif (isset($rec['NAME'])) {
if ($tokens[$index] == '::=' && $tokens[$index+1] != 'TEXTUAL-CONVENTION') {
$rec['VALUE'] = MibParser::parse_simple_token($tokens, $index);
if ($tokens[$index] == '::=' && $tokens[$index + 1] != 'TEXTUAL-CONVENTION') {
$rec['VALUE'] = MibParser::parse_simple_token($tokens, $index);
$this->parsed[] = $rec;
$rec = array();
$rec = [];
} elseif ($full) {
if ($tokens[$index] == 'ACCESS') {
$rec['ACCESS'] = MibParser::parse_simple_token($tokens, $index, array('read-only', 'not-accessible', 'read-write'));
$rec['ACCESS'] = MibParser::parse_simple_token($tokens, $index, ['read-only', 'not-accessible', 'read-write']);
} elseif ($tokens[$index] == 'OBJECTS') {
$rec['OBJECTS'] = MibParser::parse_simple_token($tokens, $index);
} elseif ($tokens[$index] == 'NOTIFICATIONS') {
@@ -399,11 +405,11 @@ class MibParser extends MibCache {
} elseif ($tokens[$index] == 'INDEX') {
$rec['INDEX'] = MibParser::parse_simple_token($tokens, $index);
} elseif ($tokens[$index] == 'MAX-ACCESS') {
$rec['MAX-ACCESS'] = MibParser::parse_simple_token($tokens, $index, array('read-only', 'not-accessible', 'read-write', 'read-create', 'accessible-for-notify'));
$rec['MAX-ACCESS'] = MibParser::parse_simple_token($tokens, $index, ['read-only', 'not-accessible', 'read-write', 'read-create', 'accessible-for-notify']);
} elseif ($tokens[$index] == 'REFERENCE') {
$rec['REFERENCE'] = MibParser::parse_simple_token($tokens, $index);
} elseif ($tokens[$index] == 'STATUS') {
$rec['STATUS'] = MibParser::parse_simple_token($tokens, $index, array('current', 'deprecated', 'obsolete', 'mandatory'));
$rec['STATUS'] = MibParser::parse_simple_token($tokens, $index, ['current', 'deprecated', 'obsolete', 'mandatory']);
} elseif ($tokens[$index] == 'SYNTAX') {
$rec['SYNTAX'] = MibParser::parse_SYNTAX_token($tokens, $index);
} elseif ($tokens[$index] == 'UNITS') {
@@ -418,10 +424,10 @@ class MibParser extends MibCache {
}
}
function generate(){
$this->oids['enterprises'] = array('oid' => '.1.3.6.1.4.1');
function generate(): void {
$this->oids['enterprises'] = ['oid' => '.1.3.6.1.4.1'];
foreach($this->parsed as $object) {
foreach ($this->parsed as $object) {
if (isset($object['VALUE'][0]) && !is_numeric($object['VALUE'][0])) {
if (isset($object['VALUE'][1]) && is_numeric($object['VALUE'][1])) {
if (isset($this->oids[$object['VALUE'][0]]['oid'])) {
@@ -431,57 +437,59 @@ class MibParser extends MibCache {
FROM snmpagent_cache
WHERE name = ?
LIMIT 1',
array($object['VALUE'][0]));
[$object['VALUE'][0]]);
$oid .= '.' . $object['VALUE'][1];
}
$syntax = null;
if (isset($object['SYNTAX'])) {
$syntax = is_array($object['SYNTAX']) ? key($object['SYNTAX']) : $object['SYNTAX'];
}
$parent_otype = strtoupper(substr($object['VALUE'][0], -5));
$otype = $object['TYPE'];
$otype = $object['TYPE'];
if ($otype == 'OBJECT-TYPE' && $syntax !== null && !in_array(strtoupper(substr($object['NAME'], -5)), array('TABLE', 'ENTRY')) && !in_array($parent_otype, array('TABLE', 'ENTRY')) ) {
if ($otype == 'OBJECT-TYPE' && $syntax !== null && !in_array(strtoupper(substr($object['NAME'], -5)), ['TABLE', 'ENTRY'], true) && !in_array($parent_otype, ['TABLE', 'ENTRY'], true)) {
$oid .= '.0';
$otype = 'DATA';
}
$kind ='unknown';
if (in_array($otype, array('MODULE-IDENTITY', 'OBJECT-IDENTITY'))) {
$kind = 'unknown';
if (in_array($otype, ['MODULE-IDENTITY', 'OBJECT-IDENTITY'], true)) {
$kind = 'Node';
} else if (in_array($otype, array('NOTIFICATION-GROUP', 'OBJECT-GROUP'))) {
} elseif (in_array($otype, ['NOTIFICATION-GROUP', 'OBJECT-GROUP'], true)) {
$kind = 'Group';
} else if ($otype == 'OBJECT-TYPE' && strtoupper(substr($object['NAME'], -5)) == 'TABLE' && $syntax == 'SEQUENCE OF') {
} elseif ($otype == 'OBJECT-TYPE' && strtoupper(substr($object['NAME'], -5)) == 'TABLE' && $syntax == 'SEQUENCE OF') {
$kind = 'Table';
} else if ($otype == 'OBJECT-TYPE' && strtoupper(substr($object['NAME'], -5)) == 'ENTRY' && $parent_otype == 'TABLE') {
} elseif ($otype == 'OBJECT-TYPE' && strtoupper(substr($object['NAME'], -5)) == 'ENTRY' && $parent_otype == 'TABLE') {
$kind = 'Row';
} else if ($otype == 'OBJECT-TYPE' && $parent_otype == 'ENTRY') {
} elseif ($otype == 'OBJECT-TYPE' && $parent_otype == 'ENTRY') {
$kind = 'Column';
} else if ($otype == 'DATA') {
} elseif ($otype == 'DATA') {
$kind = 'Scalar';
} else if ($otype == 'NOTIFICATION-TYPE') {
} elseif ($otype == 'NOTIFICATION-TYPE') {
$kind = 'Notification';
}
$this->oids[$object['NAME']] = array(
$this->oids[$object['NAME']] = [
'oid' => $oid,
'max-access' => (isset($object['MAX-ACCESS'])? $object['MAX-ACCESS'] : 'not-accessible'),
'max-access' => (isset($object['MAX-ACCESS']) ? $object['MAX-ACCESS'] : 'not-accessible'),
'syntax' => $syntax,
'otype' => $otype,
'kind' => $kind,
'mib' => $object['MIB'],
'description' => $object['DESCRIPTION']
);
];
if ($otype == 'OBJECT-GROUP' && isset($object['OBJECTS'])) {
$this->oids[$object['NAME']]['objects'] = array_diff($object['OBJECTS'], array(','));
$this->oids[$object['NAME']]['objects'] = array_diff($object['OBJECTS'], [',']);
} elseif ($otype == 'NOTIFICATION-GROUP' && isset($object['NOTIFICATIONS'])) {
$this->oids[$object['NAME']]['notifications'] = array_diff($object['NOTIFICATIONS'], array(','));
$this->oids[$object['NAME']]['notifications'] = array_diff($object['NOTIFICATIONS'], [',']);
} elseif ($otype == 'NOTIFICATION-TYPE' && isset($object['OBJECTS'])) {
$this->oids[$object['NAME']]['objects'] = array_diff($object['OBJECTS'], array(','));
$this->oids[$object['NAME']]['objects'] = array_diff($object['OBJECTS'], [',']);
}
} elseif ($object['VALUE'] == 'TEXTUAL-CONVENTION') {
$syntax = null;
@@ -490,10 +498,10 @@ class MibParser extends MibCache {
$syntax = is_array($object['SYNTAX']) ? key($object['SYNTAX']) : $object['SYNTAX'];
}
$kind = 'Textual-Convention';
$kind = 'Textual-Convention';
$otype = 'TEXTUAL-CONVENTION';
$this->oids[$object['NAME']] = array(
$this->oids[$object['NAME']] = [
'oid' => '',
'max-access' => '',
'syntax' => $syntax,
@@ -501,7 +509,7 @@ class MibParser extends MibCache {
'kind' => $kind,
'mib' => $object['MIB'],
'description' => $object['DESCRIPTION']
);
];
}
}
}
@@ -510,4 +518,3 @@ class MibParser extends MibCache {
unset($this->parsed);
}
}
+20 -22
View File
@@ -338,39 +338,37 @@ class Net_Ping {
$oid = '.1.3.6.1.2.1.1.3.0';
}
$session = cacti_snmp_session($this->host['hostname'], $this->host['snmp_community'],
$this->host['snmp_version'], $this->host['snmp_username'],
$this->host['snmp_password'], $this->host['snmp_auth_protocol'],
$this->host['snmp_priv_passphrase'], $this->host['snmp_priv_protocol'],
$this->host['snmp_context'], $this->host['snmp_engine_id'],
$this->host['snmp_port'], $this->host['snmp_timeout'],
$this->retries, read_config_option('max_get_size'));
if ($session === false) {
$this->snmp_status = 'down';
$this->snmp_response = 'Failed to make SNMP session';
return false;
}
$result = $this->get_snmp_result($session, $oid);
/* Phase 1 (snmp3_get test): run the SNMPv3 availability check through the
procedural cacti_snmp_get()/getnext() path (snmp_get_method -> snmp3_get)
instead of the SNMP class session, so an unsupported privacy protocol is
caught and can fall back to the Net-SNMP binary rather than raising an
uncaught ValueError in SNMP::setSecurity(). */
$result = $this->get_snmp_result($oid);
if (!$result && $oid == '.1.3.6.1.2.1.1.3.0') {
$result = $this->get_snmp_result($session, '.1.3.6.1.6.3.10.2.1.3.0');
$result = $this->get_snmp_result('.1.3.6.1.6.3.10.2.1.3.0');
}
$session->close();
return $result;
}
function get_snmp_result(object $session, string $oid) : bool {
function get_snmp_result(string $oid) : bool {
$h = $this->host;
// getnext does not work in php versions less than 5
if (($this->avail_method == AVAIL_SNMP_GET_NEXT) &&
(version_compare('5', phpversion(), '<'))) {
$output = cacti_snmp_session_getnext($session, $oid);
$output = cacti_snmp_getnext($h['hostname'], $h['snmp_community'], $oid,
$h['snmp_version'], $h['snmp_username'], $h['snmp_password'],
$h['snmp_auth_protocol'], $h['snmp_priv_passphrase'], $h['snmp_priv_protocol'],
$h['snmp_context'], $h['snmp_port'], $h['snmp_timeout'], $this->retries,
'SNMP', $h['snmp_engine_id']);
} else {
$output = cacti_snmp_session_get($session, $oid);
$output = cacti_snmp_get($h['hostname'], $h['snmp_community'], $oid,
$h['snmp_version'], $h['snmp_username'], $h['snmp_password'],
$h['snmp_auth_protocol'], $h['snmp_priv_passphrase'], $h['snmp_priv_protocol'],
$h['snmp_context'], $h['snmp_port'], $h['snmp_timeout'], $this->retries,
'SNMP', $h['snmp_engine_id']);
}
// determine total time +- ~10%
+839 -30
View File
File diff suppressed because it is too large. Load diff
+30
View File
@@ -816,6 +816,36 @@ function poller_update_poller_cache_from_buffer(array $local_data_ids, array &$p
* for Caching.
*/
set_config_option('time_last_change_poller_item', time());
/* Only SNMPv3 credentials live in the shared credential cache. Bump the version
* only when this flush touched v3 poller items, so a non-v3 (or non-SNMP) data
* source change does not force a needless credential cache rebuild. */
if ($ids != '') {
$v3_items = db_fetch_cell_prepared("SELECT COUNT(*) FROM poller_item
WHERE poller_id = ?
AND local_data_id IN ($ids)
AND snmp_version = 3",
[$poller_id]);
} else {
$v3_items = db_fetch_cell('SELECT COUNT(*) FROM poller_item WHERE snmp_version = 3');
}
if ($v3_items > 0) {
$cred_version = uniqid('', true);
set_config_option('snmp_cred_version', $cred_version);
/* A remote collector builds its host-local credential cache from its own
* database copy and reads this token from its own settings, so the main
* database bump alone never invalidates it. Push the same token to the
* affected remote poller so its next poll rebuilds the cache instead of
* serving stale/rotated credentials until the daily out-of-band rebuild. */
if ($poller_id > 1 && remote_poller_up($poller_id)) {
if (($rcnn_id = poller_push_to_remote_db_connect($poller_id, true)) !== false) {
db_execute_prepared('REPLACE INTO settings (name, value) VALUES (\'snmp_cred_version\', ?)',
[$cred_version], true, $rcnn_id);
}
}
}
}
/**
+4
View File
@@ -11981,6 +11981,10 @@ msgstr ""
msgid "By default, upon upgrading the Main Cacti system, it will perform a Full Sync to all Data Collectors. This process may be time consuming. Therefore, to allow upgrades to be completed quicker, we provide this option. Note that if this is disabled, the Cacti administrator must force this process from the Data Collectors interface after upgrade."
msgstr ""
#: include/global_settings.php
msgid "SNMP Behavior"
msgstr ""
#: include/global_settings.php
msgid "Additional Data Collector Settings"
msgstr ""
+117 -3
View File
@@ -1944,6 +1944,18 @@ parameters:
count: 1
path: include/auth.php
-
message: '#^Offset ''base_path'' does not exist on array\{cacti_server_os\: ''unix''\|''win32'', is_web\: bool, proxy_headers\: mixed, trusted_proxies\: mixed, poller_id\: mixed, path_csrf_secret\: mixed, php_snmp_support\: bool, php_path\?\: mixed, \.\.\.\}\.$#'
identifier: offsetAccess.notFound
count: 1
path: include/global.php
-
message: '#^Offset ''cache_dir'' on array\{cacti_server_os\: ''unix''\|''win32'', is_web\: bool, proxy_headers\: mixed, trusted_proxies\: mixed, poller_id\: mixed, path_csrf_secret\: mixed, php_snmp_support\: bool, php_path\?\: mixed, \.\.\.\} in empty\(\) does not exist\.$#'
identifier: empty.offset
count: 1
path: include/global.php
-
message: '#^Argument of an invalid type array\|bool supplied for foreach, only iterables are supported\.$#'
identifier: foreach.nonIterable
@@ -2880,6 +2892,54 @@ parameters:
count: 1
path: lib/boost.php
-
message: '#^Cannot access offset 1 on array\|false\.$#'
identifier: offsetAccess.nonOffsetAccessible
count: 1
path: lib/cache.php
-
message: '#^Method Cacti\\Cache\\ShmopBackend\:\:openForRead\(\) never returns resource so it can be removed from the return type\.$#'
identifier: return.unusedType
count: 1
path: lib/cache.php
-
message: '#^Parameter \#1 \$shmop of function shmop_close expects Shmop, resource given\.$#'
identifier: argument.type
count: 1
path: lib/cache.php
-
message: '#^Parameter \#1 \$shmop of function shmop_delete expects Shmop, resource\|Shmop given\.$#'
identifier: argument.type
count: 1
path: lib/cache.php
-
message: '#^Parameter \#1 \$shmop of function shmop_read expects Shmop, resource\|Shmop given\.$#'
identifier: argument.type
count: 2
path: lib/cache.php
-
message: '#^Parameter \#1 \$shmop of function shmop_size expects Shmop, resource\|Shmop given\.$#'
identifier: argument.type
count: 2
path: lib/cache.php
-
message: '#^Property Cacti\\Cache\\SharedCache\:\:\$name \(string\) does not accept string\|null\.$#'
identifier: assign.propertyType
count: 1
path: lib/cache.php
-
message: '#^Right side of && is always true\.$#'
identifier: booleanAnd.rightAlwaysTrue
count: 1
path: lib/cache.php
-
message: '#^Argument of an invalid type array\|bool supplied for foreach, only iterables are supported\.$#'
identifier: foreach.nonIterable
@@ -4693,7 +4753,25 @@ parameters:
path: lib/snmp.php
-
message: '#^Parameter \#4 \$timeout of class phpsnmp\\SNMP constructor expects int\<\-1, max\>, int given\.$#'
message: '#^Parameter \#3 \$sec_level of function snmp3_get expects ''authNoPriv''\|''authPriv''\|''noAuthNoPriv'', ''''\|''authNoPriv''\|''authPriv''\|''noAuthNoPriv'' given\.$#'
identifier: argument.type
count: 1
path: lib/snmp.php
-
message: '#^Parameter \#4 \$auth_protocol of function snmp3_get expects ''MD5''\|''SHA''\|''SHA256''\|''SHA512'', string given\.$#'
identifier: argument.type
count: 3
path: lib/snmp.php
-
message: '#^Parameter \#4 \$auth_protocol of function snmp3_getnext expects ''MD5''\|''SHA''\|''SHA256''\|''SHA512'', string given\.$#'
identifier: argument.type
count: 1
path: lib/snmp.php
-
message: '#^Parameter \#4 \$timeout of class CactiSnmpNativeSession constructor expects int\<\-1, max\>, int given\.$#'
identifier: argument.type
count: 1
path: lib/snmp.php
@@ -4701,7 +4779,7 @@ parameters:
-
message: '#^Parameter \#4 \$timeout of function snmp2_get expects int\<\-1, max\>, int given\.$#'
identifier: argument.type
count: 2
count: 3
path: lib/snmp.php
-
@@ -4719,7 +4797,7 @@ parameters:
-
message: '#^Parameter \#4 \$timeout of function snmpget expects int\<\-1, max\>, int given\.$#'
identifier: argument.type
count: 2
count: 3
path: lib/snmp.php
-
@@ -4734,6 +4812,42 @@ parameters:
count: 1
path: lib/snmp.php
-
message: '#^Parameter \#6 \$priv_protocol of function snmp3_get expects ''AES''\|''AES128''\|''DES'', string given\.$#'
identifier: argument.type
count: 3
path: lib/snmp.php
-
message: '#^Parameter \#6 \$privacy_protocol of function snmp3_getnext expects ''AES''\|''AES128''\|''DES'', string given\.$#'
identifier: argument.type
count: 1
path: lib/snmp.php
-
message: '#^Parameter \#8 \$object_id of function snmp3_get expects non\-empty\-string, string given\.$#'
identifier: argument.type
count: 2
path: lib/snmp.php
-
message: '#^Parameter \#9 \$timeout of function snmp3_get expects int\<\-1, max\>, int given\.$#'
identifier: argument.type
count: 3
path: lib/snmp.php
-
message: '#^Parameter \#9 \$timeout of function snmp3_getnext expects int\<\-1, max\>, int given\.$#'
identifier: argument.type
count: 1
path: lib/snmp.php
-
message: '#^Trying to invoke non\-falsy\-string but it might not be a callable\.$#'
identifier: callable.nonCallable
count: 1
path: lib/snmp.php
-
message: '#^Argument of an invalid type array\|bool supplied for foreach, only iterables are supported\.$#'
identifier: foreach.nonIterable
+4
View File
@@ -40,6 +40,7 @@ require_once(CACTI_PATH_LIBRARY . '/dsdebug.php');
require_once(CACTI_PATH_LIBRARY . '/boost.php');
require_once(CACTI_PATH_LIBRARY . '/reports.php');
require_once(CACTI_PATH_LIBRARY . '/rrdcheck.php');
require_once(CACTI_PATH_LIBRARY . '/snmp.php');
global $poller_db_cnn_id, $remote_db_cnn_id, $logged, $database_hostname;
@@ -212,6 +213,9 @@ if (CACTI_CONNECTION == 'online') {
update_resource_cache($poller_id);
}
// prime the shared SNMP auth cache (rebuilt only when credentials change)
snmp_auth_cache_refresh();
// get number of polling items from the database
$poller_interval = intval(read_config_option('poller_interval'));
+38
View File
@@ -136,6 +136,10 @@ cpu_cores_check();
// Remove deleted devices
remove_aged_row_cache();
// Sweep this collector's SNMP credential cache (each collector has its own
// host-local cache file / shared-memory segment, so this runs everywhere)
snmp_credential_cache_maintenance();
// Update Object Totals Caches
if (POLLER_ID == 1) {
update_graphs_data_source_templates_totals($force);
@@ -166,6 +170,40 @@ if (!$force) {
exit(0);
/**
* Sweep this collector's shared SNMP credential cache once a day. Each collector
* keeps its own host-local cache file / shared-memory segment, so this runs on
* every collector (not just the main one), using a per-poller lastrun marker so
* one collector's sweep does not suppress another's.
*
* @return void No value is returned.
*/
function snmp_credential_cache_maintenance() : void {
require_once(CACTI_PATH_LIBRARY . '/snmp.php');
if (!function_exists('snmp_auth_cache_rebuild') || !snmp_auth_cache_enabled()) {
return;
}
$setting = 'snmp_cred_cache_lastrun_' . POLLER_ID;
$last_run = read_config_option($setting);
$now = time();
if (empty($last_run)) {
set_config_option($setting, $now);
return;
}
if (date('z', $now) != date('z', $last_run)) {
set_config_option($setting, $now);
maint_debug('Rebuilding SNMP credential cache');
snmp_auth_cache_rebuild();
}
}
function unlock_cacti() : void {
$lockout = read_config_option('cacti_lockout_status', true);
+3
View File
@@ -175,6 +175,9 @@ cacti_log('PHP Script Server has Started - Parent is ' . $environ, false, 'PHPSV
fputs(STDOUT, 'PHP Script Server has Started - Parent is ' . $environ . "\n");
fflush(STDOUT);
require_once(__DIR__ . '/lib/snmp.php');
snmp_auth_cache_load();
// process waits for input and then calls functions as required
while (1) {
$result = '';
+2 -2
View File
@@ -71,10 +71,10 @@ test('htmx.js.version content matches version pinned by the integrity attribute'
* is stale relative to the vendored binary and browsers will refuse to
* execute the script.
*/
expect(htmx_version())->toBe('2.0.10');
expect(htmx_version())->toBe('2.0.11');
expect(htmx_script_tag())->toContain(
"integrity='sha384-Q+Dky3iHVJOr6wUjQ4ulh6uQ76an/t+ak1+PjMVaxRjbZamFLAG+u9InkfjbsEQf'"
"integrity='sha384-gmJEF2eAKY4e+FDN+qtKIivWyb6ANwDB7JUdUybKgQspPKyEX/pIRZG/0uaRoW2C'"
);
});
+162
View File
@@ -0,0 +1,162 @@
<?php
/*
+-------------------------------------------------------------------------+
| Copyright (C) 2004-2026 The Cacti Group |
| |
| This program is free software; you can redistribute it and/or |
| modify it under the terms of the GNU General Public License |
| as published by the Free Software Foundation; either version 2 |
| of the License, or (at your option) any later version. |
+-------------------------------------------------------------------------+
| Cacti: The Complete RRDtool-based Graphing Solution |
+-------------------------------------------------------------------------+
| This code is designed, written, and maintained by the Cacti Group. See |
| about.php and/or the AUTHORS file for specific developer information. |
+-------------------------------------------------------------------------+
| http://www.cacti.net/ |
+-------------------------------------------------------------------------+
*/
/*
* Behavioural coverage for the cross-process SharedCache used by the SNMP
* credential cache. These tests exercise the durable file tier with temporary
* directories and explicit backend orders, including fallback on a failed
* higher-tier write and recovery from malformed/corrupt cache files, without
* touching the database or the encryption key (encrypted is off by default).
*/
require_once dirname(__DIR__, 4) . '/lib/cache.php';
function sharedCacheTmpDir(): string {
$dir = sys_get_temp_dir() . '/cacti_sharedcache_' . uniqid('', true);
mkdir($dir, 0770, true);
return $dir;
}
function sharedCacheRmTree(string $dir): void {
if (!is_dir($dir)) {
return;
}
foreach (glob($dir . '/*') ?: [] as $path) {
if (is_dir($path)) {
sharedCacheRmTree($path);
} else {
@unlink($path);
}
}
@rmdir($dir);
}
test('store and fetch round-trip through the file tier across instances', function () {
$dir = sharedCacheTmpDir();
try {
$data = ['k1' => ['a', 'b'], 'k2' => 42, 'k3' => 'value'];
$writer = new \Cacti\Cache\SharedCache('sc_roundtrip', ['cache_dir' => $dir, 'backends' => ['file']]);
expect($writer->store($data, 'token-1'))->toBeTrue();
expect($writer->isShared())->toBeTrue();
// a fresh instance has no in-process memo, so it must read from disk
$reader = new \Cacti\Cache\SharedCache('sc_roundtrip', ['cache_dir' => $dir, 'backends' => ['file']]);
expect($reader->fetch())->toEqual($data);
expect($reader->checksum())->toBe('token-1');
} finally {
sharedCacheRmTree($dir);
}
});
test('invalidate removes the stored entry from the file tier', function () {
$dir = sharedCacheTmpDir();
try {
$writer = new \Cacti\Cache\SharedCache('sc_invalidate', ['cache_dir' => $dir, 'backends' => ['file']]);
$writer->store(['v' => 1], 'token');
expect(is_file($dir . '/sc_invalidate.cache'))->toBeTrue();
$writer->invalidate();
expect(is_file($dir . '/sc_invalidate.cache'))->toBeFalse();
$reader = new \Cacti\Cache\SharedCache('sc_invalidate', ['cache_dir' => $dir, 'backends' => ['file']]);
expect($reader->fetch())->toBeFalse();
} finally {
sharedCacheRmTree($dir);
}
});
test('a corrupt payload is treated as a miss rather than crashing', function () {
$dir = sharedCacheTmpDir();
try {
// valid JSON envelope, but the payload is not a serialized value
file_put_contents($dir . '/sc_corrupt.cache', json_encode([
'checksum' => 'token',
'payload' => base64_encode('this-is-not-serialized'),
]));
$cache = new \Cacti\Cache\SharedCache('sc_corrupt', ['cache_dir' => $dir, 'backends' => ['file']]);
expect($cache->fetch())->toBeFalse();
} finally {
sharedCacheRmTree($dir);
}
});
test('malformed JSON in the cache file is treated as a miss', function () {
$dir = sharedCacheTmpDir();
try {
file_put_contents($dir . '/sc_badjson.cache', 'not-valid-json{');
$cache = new \Cacti\Cache\SharedCache('sc_badjson', ['cache_dir' => $dir, 'backends' => ['file']]);
expect($cache->fetch())->toBeFalse();
expect($cache->checksum())->toBeNull();
} finally {
sharedCacheRmTree($dir);
}
});
test('a non-string checksum field does not raise a TypeError', function () {
$dir = sharedCacheTmpDir();
try {
/* a corrupt file could decode to an array-valued checksum; readChecksum()
* must treat that as absent instead of returning a non-string */
file_put_contents($dir . '/sc_badsum.cache', json_encode([
'checksum' => ['unexpected', 'array'],
'payload' => base64_encode(serialize(['x' => 1])),
]));
$cache = new \Cacti\Cache\SharedCache('sc_badsum', ['cache_dir' => $dir, 'backends' => ['file']]);
expect($cache->checksum())->toBeNull();
} finally {
sharedCacheRmTree($dir);
}
});
test('a failed higher-tier write falls through without serving stale data', function () {
$dir = sharedCacheTmpDir();
try {
/* occupy the cache path with a directory so the file tier's atomic
* rename() always fails - deterministic even when the suite runs as
* root, where permission bits would be ignored */
mkdir($dir . '/sc_fallback.cache', 0770, true);
$writer = new \Cacti\Cache\SharedCache('sc_fallback', ['cache_dir' => $dir, 'backends' => ['file', 'static']]);
// no cross-process tier accepted the write
expect($writer->store(['fresh' => true], 'new'))->toBeFalse();
/* a fresh consumer still gets the new value from the process-local
* fallback tier and never the unreadable stale directory entry */
$reader = new \Cacti\Cache\SharedCache('sc_fallback', ['cache_dir' => $dir, 'backends' => ['file', 'static']]);
expect($reader->fetch())->toEqual(['fresh' => true]);
} finally {
@rmdir($dir . '/sc_fallback.cache');
sharedCacheRmTree($dir);
}
});
@@ -131,6 +131,38 @@ function cacti_strtolower(string $value) : string {
return strtolower($value);
}
if (!function_exists('set_config_option')) {
function set_config_option(string $name, mixed $value) : void {
$GLOBALS['snmp_coverage_config'][$name] = $value;
}
}
if (!function_exists('db_fetch_assoc')) {
function db_fetch_assoc(string $sql) : array {
if (str_contains($sql, 'FROM host')) {
return $GLOBALS['snmp_coverage_host_rows'] ?? [];
}
if (str_contains($sql, 'FROM poller_item')) {
return $GLOBALS['snmp_coverage_item_rows'] ?? [];
}
return [];
}
}
if (!function_exists('cacti_encrypt_secret')) {
function cacti_encrypt_secret(string $plain) : string {
return 'enc:' . base64_encode($plain);
}
}
if (!function_exists('cacti_decrypt_secret')) {
function cacti_decrypt_secret(string $wire) : string|false {
return str_starts_with($wire, 'enc:') ? (base64_decode(substr($wire, 4), true) ?: false) : false;
}
}
require_once dirname(__DIR__, 4) . '/lib/snmp.php';
test('uptime selection rejects wall-clock engine times and preserves wrap handling', function () : void {
@@ -272,7 +304,7 @@ test('session warning handler delegates non-warning errors and error logging is
expect(cacti_snmp_session_call($session, 'notice', [], $warning, false))->toBeTrue();
$session->errno = phpsnmp\SNMP::ERRNO_TIMEOUT;
$session->errno = \SNMP::ERRNO_TIMEOUT;
cacti_snmp_log_session_error($session, $session->info, ['.1', '.2']);
$session->errno = 8;
$session->error = "native\r\nerror";
@@ -327,7 +359,9 @@ test('OID validation, escaping, method selection, options, and v3 auth cover all
->and(snmp_escape_string('public', 'win32'))->toBe("'public'")
->and(snmp_get_method('get', 1, '', '', SNMP_STRING_OUTPUT_GUESS, false))->toBe(SNMP_METHOD_BINARY)
->and(snmp_get_method('get', 1, '', '', SNMP_STRING_OUTPUT_HEX))->toBe(SNMP_METHOD_BINARY)
->and(snmp_get_method('get', 3))->toBe(SNMP_METHOD_BINARY)
->and(snmp_get_method('get', 3))->toBe(SNMP_METHOD_PHP)
->and(snmp_get_method('get', 3, 'ctx'))->toBe(SNMP_METHOD_BINARY)
->and(snmp_get_method('get', 3, auth_proto: 'INVALID'))->toBe(SNMP_METHOD_BINARY)
->and(snmp_get_method('walk', 1))->toBe(SNMP_METHOD_BINARY)
->and(snmp_get_method('get', 1))->toBe(SNMP_METHOD_PHP)
->and(snmp_get_method('get', 2))->toBe(SNMP_METHOD_PHP);
@@ -363,7 +397,7 @@ test('native sessions cover versions and security levels without network I/O', f
->and(cacti_snmp_session('127.0.0.1', '', '3', 'user', '', '[None]', '', '[None]'))->toBeObject()
->and(cacti_snmp_session('127.0.0.1', '', '3', 'user', 'secretpass', 'SHA', '', '[None]'))->toBeObject()
->and(cacti_snmp_session('127.0.0.1', '', '3', 'user', 'secretpass', 'SHA', 'privatepass', 'AES'))->toBeObject()
->and(cacti_snmp_session('127.0.0.1', '', '3', 'user', 'secretpass', 'INVALID', '', '[None]'))->toBeFalse()
->and(cacti_snmp_session('127.0.0.1', '', '3', 'user', 'secretpass', 'INVALID', '', '[None]'))->toBeObject()
->and(cacti_snmp_session('127.0.0.1', 'public', 'invalid'))->toBeFalse();
// cacti_snmp_session_from_host maps a device row onto the arguments above (#7835).
@@ -406,9 +440,9 @@ test('native and binary get operations cover success and failure results', funct
}))->toBe('U');
$_SESSION = [];
expect(cacti_snmp_get($host, 'public', $oid, 3, 'user', '', '[None]', '', '[None]', port: $port))->toBe('coverage value')
->and(cacti_snmp_get_raw($host, 'public', $oid, 3, 'user', '', '[None]', '', '[None]', port: $port))->toContain('coverage value')
->and(cacti_snmp_getnext($host, 'public', $oid, 3, 'user', '', '[None]', '', '[None]', port: $port))->toBe('coverage value');
expect(cacti_snmp_get($host, 'public', $oid, 3, 'user', '', '[None]', '', '[None]', port: $port))->not->toBe('U')
->and(cacti_snmp_get_raw($host, 'public', $oid, 3, 'user', '', '[None]', '', '[None]', port: $port))->not->toBe('U')
->and(cacti_snmp_getnext($host, 'public', $oid, 3, 'user', '', '[None]', '', '[None]', port: $port))->not->toBe('U');
putenv('CACTI_SNMP_PROBE_MODE=timeout');
expect(cacti_snmp_get($host, 'public', $oid, 1, port: $port, value_output_format: SNMP_STRING_OUTPUT_HEX))->toBe('U')
@@ -478,3 +512,227 @@ test('native and binary walks cover parsing, filtering, and diagnostics', functi
->toContain('Exit Code')
->toContain('Missing credentials');
});
test('protocol pickers, native tokens, agent formatting, and v3 support gating', function () : void {
$GLOBALS['snmp_auth_protocols'] = ['MD5' => 'MD5', 'SHA' => 'SHA'];
$GLOBALS['snmp_priv_protocols'] = ['DES' => 'DES', 'AES' => 'AES'];
$GLOBALS['snmp_coverage_config']['snmp_md5_des_enabled'] = '';
expect(snmp_md5_des_enabled())->toBeFalse()
->and(snmp_auth_protocol_options())->not->toHaveKey('MD5')
->and(snmp_auth_protocol_options('MD5'))->toHaveKey('MD5')
->and(snmp_priv_protocol_options())->not->toHaveKey('DES')
->and(snmp_priv_protocol_options('DES'))->toHaveKey('DES');
$GLOBALS['snmp_coverage_config']['snmp_md5_des_enabled'] = 'on';
expect(snmp_md5_des_enabled())->toBeTrue()
->and(snmp_auth_protocol_options())->toHaveKey('MD5')
->and(snmp_priv_protocol_options())->toHaveKey('DES');
expect(snmp_native_protocol('SHA-256'))->toBe('SHA256')
->and(snmp_native_protocol('AES-256-C'))->toBe('AES256C');
expect(snmp_format_agent('udp:device', 161))->toBe('udp:device')
->and(snmp_format_agent('[2001:db8::1]', 161))->toBe('[2001:db8::1]:161')
->and(snmp_format_agent('[2001:db8::1]:1161', 500))->toBe('[2001:db8::1]:1161')
->and(snmp_format_agent('2001:db8::1', 1161))->toBe('[2001:db8::1]:1161')
->and(snmp_format_agent('127.0.0.1', 161))->toBe('127.0.0.1')
->and(snmp_format_agent('127.0.0.1', 1161))->toBe('127.0.0.1:1161')
->and(snmp_format_agent('unix:/var/agentx/master', 1161))->toBe('unix:/var/agentx/master')
->and(snmp_format_agent('udp6:[2001:db8::1]', 1161))->toBe('udp6:[2001:db8::1]:1161')
->and(snmp_format_agent('udp6:[2001:db8::1]:1161', 500))->toBe('udp6:[2001:db8::1]:1161')
->and(snmp_format_agent('udp:device:1161', 500))->toBe('udp:device:1161')
->and(snmp_format_agent('udp:device', 1161))->toBe('udp:device:1161');
expect(snmp_php_v3_protocols_supported('SHA', 'AES'))->toBeTrue()
->and(snmp_php_v3_protocols_supported('[None]', '[None]'))->toBeTrue()
->and(snmp_php_v3_protocols_supported('BOGUS', '[None]'))->toBeFalse()
->and(snmp_php_v3_protocols_supported('[None]', 'AES'))->toBeFalse();
});
test('v3 credential argument hardening and cache map construction', function () : void {
$GLOBALS['snmp_auth_protocols'] = ['SHA' => 'SHA'];
$GLOBALS['snmp_priv_protocols'] = ['AES' => 'AES'];
expect(snmp_build_v3_cred_args('[None]', 'user', '', '[None]', ''))->toBe(['-u', 'user', '-l', 'noAuthNoPriv'])
->and(snmp_build_v3_cred_args('SHA', 'user', 'secret', '[None]', ''))->toBe(['-u', 'user', '-a', 'SHA', '-A', 'secret', '-l', 'authNoPriv'])
->and(snmp_build_v3_cred_args('BOGUS', 'user', 'secret', '[None]', ''))->toBe([])
->and(snmp_build_v3_cred_args('SHA', 'user', 'secret', 'AES', 'priv'))->toBe(['-u', 'user', '-a', 'SHA', '-A', 'secret', '-x', 'AES', '-X', 'priv', '-l', 'authPriv'])
->and(snmp_build_v3_cred_args('BOGUS', 'user', 'secret', 'AES', 'priv'))->toBe([]);
$key = snmp_auth_cache_key('', 'user', 'secret', 'SHA', '', '[None]');
expect($key)->toBe(snmp_auth_cache_key('', 'user', 'secret', 'SHA', '', '[None]'))
->and(strlen($key))->toBe(40);
$rows = [
['snmp_username' => '', 'snmp_community' => 'public'],
['snmp_username' => 'user', 'snmp_community' => '', 'snmp_password' => 'secret', 'snmp_auth_protocol' => 'SHA', 'snmp_priv_passphrase' => '', 'snmp_priv_protocol' => '[None]'],
['snmp_username' => 'user', 'snmp_community' => '', 'snmp_password' => 'secret', 'snmp_auth_protocol' => 'SHA', 'snmp_priv_passphrase' => '', 'snmp_priv_protocol' => '[None]'],
];
expect(snmp_auth_cache_build_map($rows))->toHaveCount(1);
});
test('shared SNMP auth cache lifecycle', function () : void {
$dir = sys_get_temp_dir() . '/snmpcov_' . uniqid();
mkdir($dir);
$GLOBALS['config']['cache_dir'] = $dir;
$GLOBALS['snmp_auth_protocols'] = ['SHA' => 'SHA'];
$GLOBALS['snmp_priv_protocols'] = ['AES' => 'AES'];
$GLOBALS['snmp_coverage_host_rows'] = [
['snmp_community' => '', 'snmp_username' => 'user', 'snmp_password' => 'secret', 'snmp_auth_protocol' => 'SHA', 'snmp_priv_passphrase' => '', 'snmp_priv_protocol' => '[None]'],
];
$GLOBALS['snmp_coverage_item_rows'] = [];
unset($GLOBALS['snmp_coverage_config']['snmp_cred_version']);
$version = snmp_cred_version();
expect($version)->toBeString()->not->toBe('')
->and(snmp_cred_version())->toBe($version)
->and(snmp_auth_cache_rows())->toHaveCount(1)
->and(snmp_auth_cache_build())->toHaveCount(1);
// disabled: refresh/rebuild short-circuit; load yields an empty map
$GLOBALS['snmp_coverage_config']['snmp_credential_cache'] = '';
expect(snmp_auth_cache_enabled())->toBeFalse();
snmp_auth_cache_refresh();
snmp_auth_cache_rebuild();
unset($GLOBALS['snmp_auth_cache_loaded'], $GLOBALS['snmp_auth_cache_map']);
snmp_auth_cache_load();
expect($GLOBALS['snmp_auth_cache_map'])->toBe([]);
// enabled + empty cache: load() builds from the database (fallback branch)
$GLOBALS['snmp_coverage_config']['snmp_credential_cache'] = 'on';
snmp_auth_cache()->invalidate();
unset($GLOBALS['snmp_auth_cache_loaded'], $GLOBALS['snmp_auth_cache_map']);
snmp_auth_cache_load();
expect($GLOBALS['snmp_auth_cache_map'])->toHaveCount(1);
// refresh seals it (first stores, second short-circuits on checksum); rebuild forces it
snmp_auth_cache_refresh();
snmp_auth_cache_refresh();
snmp_auth_cache_rebuild();
// load() now decodes the sealed cache instead of rebuilding
unset($GLOBALS['snmp_auth_cache_loaded'], $GLOBALS['snmp_auth_cache_map']);
snmp_auth_cache_load();
expect($GLOBALS['snmp_auth_cache_map'])->toHaveCount(1);
// cred lookup: a matching tuple hits, an unknown tuple misses
expect(snmp_auth_cache_cred_lookup('', 'user', 'secret', 'SHA', '', '[None]'))->toBeArray()
->and(snmp_auth_cache_cred_lookup('', 'nobody', '', 'SHA', '', '[None]'))->toBeNull();
// cred lookup also seeds the map itself when it has not been loaded
unset($GLOBALS['snmp_auth_cache_loaded'], $GLOBALS['snmp_auth_cache_map']);
expect(snmp_auth_cache_cred_lookup('', 'user', 'secret', 'SHA', '', '[None]'))->toBeArray();
// a second load() short-circuits on the process guard
snmp_auth_cache_load();
});
test('binary-delegating session routes through the Net-SNMP command path', function () : void {
$host = getenv('CACTI_SNMP_COVERAGE_HOST') ?: '127.0.0.1';
$port = (int) (getenv('CACTI_SNMP_COVERAGE_PORT') ?: 21161);
putenv('CACTI_SNMP_PROBE_MODE=get');
$session = cacti_snmp_session($host, '', '3', 'user', 'secret', 'INVALID', '', '[None]', port: $port);
expect($session)->toBeObject();
expect($session->get('.1.3.6.1.2.1.1.1.0'))->toBeString()
->and($session->get(['.1.3.6.1.2.1.1.1.0']))->toBeArray()
->and($session->getnext('.1.3.6.1.2.1.1.1.0'))->toBeString()
->and($session->walk(['.1']))->toBeFalse()
->and($session->close())->toBeTrue()
->and($session->getErrno())->toBe(0)
->and($session->getError())->toBe('');
putenv('CACTI_SNMP_PROBE_MODE=walk');
expect($session->walk('.1.3.6.1.2.1.1'))->toBeArray();
// A v2 binary session walk returns parsed entries, exercising the result map.
$v2 = new CactiSnmpBinarySession([
'hostname' => $host, 'community' => 'public', 'version' => '2',
'auth_user' => '', 'auth_pass' => '', 'auth_proto' => '', 'priv_pass' => '',
'priv_proto' => '', 'context' => '', 'engineid' => '',
'port' => $port, 'timeout' => 500, 'retries' => 0,
], 10);
expect($v2->walk('.1.3.6.1.2.1.1'))->toBeArray()->not->toBe([]);
});
test('multi-OID get batches, falls back, and maps results', function () : void {
$host = getenv('CACTI_SNMP_COVERAGE_HOST') ?: '127.0.0.1';
$port = (int) (getenv('CACTI_SNMP_COVERAGE_PORT') ?: 21161);
$oids = ['.1.3.6.1.2.1.1.1.0', '.1.3.6.1.2.1.1.3.0'];
putenv('CACTI_SNMP_PROBE_MODE=get');
expect(cacti_snmp_get_multi($host, 'public', $oids, 2, port: $port, max_oids: 1))->toHaveCount(2)
->and(cacti_snmp_get_multi($host, 'public', $oids, 1, port: $port))->toHaveCount(2)
->and(cacti_snmp_get_multi($host, '', $oids, 3, 'user', '', '[None]', '', '[None]', port: $port))->toHaveCount(2)
->and(cacti_snmp_get_multi($host, 'public', '.1.3.6.1.2.1.1.1.0', 1, port: $port, value_output_format: SNMP_STRING_OUTPUT_HEX))->toHaveCount(1)
->and(cacti_snmp_get_multi($host, 'public', [], 1, port: $port))->toBe([]);
$fail = cacti_snmp_get_multi($host, 'wrong', $oids, 2, port: $port, timeout_ms: 1, retries: 0);
expect($fail['.1.3.6.1.2.1.1.1.0'])->toBe('U');
});
test('v3 authNoPriv and authPriv exercise every security-level branch', function () : void {
$host = getenv('CACTI_SNMP_COVERAGE_HOST') ?: '127.0.0.1';
$port = (int) (getenv('CACTI_SNMP_COVERAGE_PORT') ?: 21161);
$oid = '.1.3.6.1.2.1.1.1.0';
$GLOBALS['snmp_auth_protocols'] = ['SHA' => 'SHA'];
$GLOBALS['snmp_priv_protocols'] = ['AES' => 'AES', 'DES' => 'DES'];
$GLOBALS['snmp_coverage_config']['snmp_credential_cache'] = '';
// The fixture only serves a noAuthNoPriv user, so authNoPriv/authPriv requests
// return 'U' but still drive the native sec_level branches. A privacy protocol
// the running net-snmp rejects (DES on AES-only builds) makes snmp3_*() throw,
// which the native try/catch maps to 'U'.
foreach (['cacti_snmp_get', 'cacti_snmp_get_raw', 'cacti_snmp_getnext'] as $fn) {
expect($fn($host, '', $oid, 3, 'user', 'secretpass', 'SHA', '', '[None]', port: $port))->toBe('U')
->and($fn($host, '', $oid, 3, 'user', 'secretpass', 'SHA', 'privpass1', 'AES', port: $port))->toBe('U');
// hex output forces the Net-SNMP command path through cacti_get_snmpv3_auth
putenv('CACTI_SNMP_PROBE_MODE=get');
$fn($host, '', $oid, 3, 'user', 'secretpass', 'SHA', '', '[None]', port: $port, value_output_format: SNMP_STRING_OUTPUT_HEX);
}
// A native getter that throws drives the try/catch of each getter portably,
// independent of whether the running net-snmp rejects a given protocol.
$boom = function () : never { throw new RuntimeException('native failure'); };
expect(cacti_snmp_get_raw($host, 'public', $oid, 1, port: $port, native_get: $boom))->toBe('U')
->and(cacti_snmp_getnext($host, 'public', $oid, 1, port: $port, native_get: $boom))->toBe('U')
->and(cacti_snmp_get_multi($host, 'public', [$oid], 1, port: $port, native_get: $boom))->toBe([$oid => 'U']);
// native multi-get: authPriv success branch + sanitize failure
expect(cacti_snmp_get_multi($host, '', [$oid], 3, 'user', 'secretpass', 'SHA', 'privpass1', 'AES', port: $port))->toHaveCount(1)
->and(cacti_snmp_get_multi($host, '', [$oid], 0, port: $port))->toBe([]);
// result association without depending on MIB availability: numeric output makes
// a leading-dot request key-match verbatim, a dot-less request (net-snmp
// normalizes the returned key to a leading dot) falls through to the positional
// slot, and a duplicate dot-less OID exhausts it for the miss path.
snmp_set_oid_output_format(SNMP_OID_OUTPUT_NUMERIC);
expect(cacti_snmp_get_multi($host, 'public', ['.1.3.6.1.2.1.1.1.0'], 2, port: $port))->toHaveCount(1)
->and(cacti_snmp_get_multi($host, 'public', ['1.3.6.1.2.1.1.1.0'], 2, port: $port))->toHaveCount(1)
->and(cacti_snmp_get_multi($host, 'public', ['1.3.6.1.2.1.1.1.0', '1.3.6.1.2.1.1.1.0'], 2, port: $port))->toHaveCount(1);
});
test('cached v3 auth assembly reuses pre-hardened credential args', function () : void {
$GLOBALS['snmp_auth_protocols'] = ['SHA' => 'SHA'];
$GLOBALS['snmp_priv_protocols'] = ['AES' => 'AES'];
$GLOBALS['snmp_coverage_config']['snmp_credential_cache'] = 'on';
$GLOBALS['snmp_auth_cache_loaded'] = true;
$GLOBALS['snmp_auth_cache_map'] = [];
// not cached -> builds live, then appends context + engine id
expect(cacti_get_snmpv3_auth('SHA', 'user', 'secret', 'AES', 'priv', 'ctx', 'engine'))
->toContain('-n')->toContain('-e');
// a cached tuple is reused verbatim
$key = snmp_auth_cache_key('', 'user', 'secret', 'SHA', '', '[None]');
$GLOBALS['snmp_auth_cache_map'][$key] = ['-u', 'user', '-a', 'SHA', '-A', 'secret', '-l', 'authNoPriv'];
expect(cacti_get_snmpv3_auth('SHA', 'user', 'secret', '[None]', '', '', ''))->toContain('authNoPriv');
// an unknown protocol builds an empty arg list -> ''
expect(cacti_get_snmpv3_auth('BOGUS', 'user', 'secret', '[None]', '', '', ''))->toBe('');
$GLOBALS['snmp_coverage_config']['snmp_credential_cache'] = '';
});
+1 -1
View File
@@ -55,7 +55,7 @@ beforeEach(function () {
});
test('htmx_version reads the version file', function () {
expect(htmx_version())->toBe('2.0.10');
expect(htmx_version())->toBe('2.0.11');
});
test('htmx_version returns empty string when the version file is missing', function () {
+2
View File
@@ -1,4 +1,6 @@
agentAddress udp:161
rocommunity public
createUser user
rouser user noauth
sysLocation Cacti coverage fixture
sysContact cacti@example.invalid
@@ -145,11 +145,12 @@ test('batching 3 changed rows into a single poller_update_poller_cache_from_buff
expect($batchedQueries)->toBeLessThan($perRowQueries);
/* each flush does a present=0 UPDATE, an INSERT, a stale-row DELETE and the
set_config_option() last-changed write, so 3 separate flushes cost 12
statements and 1 batched flush costs 4 */
expect($perRowQueries)->toBe(12)
->and($batchedQueries)->toBe(4);
/* each flush does a present=0 UPDATE, an INSERT, a stale-row DELETE, the
set_config_option() last-changed write, and a SELECT that scans the flushed
rows for SNMPv3 items to gate the shared credential-cache version bump
(#8166), so 3 separate flushes cost 15 statements and 1 batched flush costs 5 */
expect($perRowQueries)->toBe(15)
->and($batchedQueries)->toBe(5);
});
test('the batched flush leaves the same end-state as 3 per-row flushes would', function () {
@@ -111,6 +111,7 @@ cmd_exec ./support.php exec(cacti_escapeshellcmd(read_config_option('path_rrd
cmd_exec ./support.php $cli_json = shell_exec(cacti_escapeshellcmd($php_binary) . ' -q ' . cacti_escapeshellarg(CACTI_PATH_INSTALL . '/cli_check.php') . ' extensions');
cmd_exec ./support.php $snmp_version = (string) shell_exec(cacti_escapeshellcmd($snmpget_path) . ' -V 2>&1');
cmd_exec ./support.php exec(cacti_escapeshellcmd(read_config_option('path_spine')) . ' --version', $out_array);
deserialize ./lib/cache.php $data = @unserialize($wire, ['allowed_classes' => false]);
deserialize ./lib/functions.php $items = unserialize($unstripped, ['allowed_classes' => false]);
deserialize ./lib/functions.php $items = unserialize($unstripped, ['allowed_classes' => false]);
deserialize ./lib/functions.php return unserialize($strobj, ['allowed_classes' => false]);
@@ -172,6 +173,7 @@ fs_write ./lib/CactiFilesystem.php self::default()->writeFile($filename, $cont
fs_write ./lib/api_device.php if (file_put_contents($new_xmlfile, $data) === false) {
fs_write ./lib/boost.php if ($fileptr = fopen($cache_file, 'rb')) {
fs_write ./lib/boost.php $fileptr = fopen($temp_file, 'wb');
fs_write ./lib/cache.php if ($blob === false || @file_put_contents($tmp, $blob, LOCK_EX) === false) {
fs_write ./lib/clog_webapi.php $log_fh = fopen($logfile, 'w');
fs_write ./lib/csp_report_endpoint.php $inputStream = fopen('php://input', 'rb');
fs_write ./lib/database.php file_put_contents(sys_get_temp_dir() . '/cacti-option.log',
Can't render this file because it contains an unexpected character in line 22 and column 251.
-1
View File
@@ -28,7 +28,6 @@ function cacti_vendor_policy_legacy_paths() : array {
'include/vendor/index.php',
'include/vendor/parsedown/',
'include/vendor/phpgettext/',
'include/vendor/phpsnmp/',
];
}