Files
TheWitness f79dc15c08 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%.
2026-10-05 10:18:41 -04:00

619 lines
15 KiB
PHP

<?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;
}
}
}