Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
70 changes: 69 additions & 1 deletion lib/mactrack_functions.php
Original file line number Diff line number Diff line change
Expand Up @@ -2987,6 +2987,74 @@ function perform_mactrack_db_maint(): void {
mactrack_debug('Finished deleting old records from the main database.');
}

/**
* Attempts to download the IEEE OUI (vendor MAC prefix) database text
* file, tolerating transient connectivity problems (for example a
* refused connection) instead of surfacing them as a raw PHP warning.
*
* PHP's file() emits an E_WARNING when it cannot open the stream, which
* Cacti's error handler records as an "ERROR PHP WARNING" log entry.
* Those entries fail CI and raise an alert on every transient IEEE
* hiccup, so the warning is captured by a local error handler here
* (rather than relying on the @ operator, which Cacti 1.2.x does not
* honor on PHP 8.0+ because it checks error_reporting() == 0) and
* replaced with a single informational log message. Each supplied URL
* is retried, and callers can pass an alternate IEEE endpoint as a
* fallback.
*
* @param array $urls Ordered list of candidate URLs to try.
* @param int $retries Number of attempts per URL (minimum 1).
* @param int $delay Seconds to wait between attempts on the same URL.
*
* @return array|false Array of file lines on success, or false when
* every attempt failed.
*/
function mactrack_download_oui_database(array $urls, int $retries = 2, int $delay = 3) {
Comment thread
TheWitness marked this conversation as resolved.
Resolved
$urls = array_values(array_filter($urls, static function($url): bool {
return is_string($url) && $url !== '';
}));
$retries = max(1, $retries);

foreach ($urls as $url) {
for ($attempt = 1; $attempt <= $retries; $attempt++) {
$captured_error = '';

// Capture file()'s E_WARNING with a local handler so a refused or
// otherwise transient connection is never recorded as an
// "ERROR PHP WARNING" by Cacti's error handler. A local handler
// works on every supported Cacti branch and PHP version; the @
// operator does not, because Cacti 1.2.x checks for
// error_reporting() == 0, which @ never produces on PHP 8.0+.
set_error_handler(static function($errno, $errstr) use (&$captured_error): bool {
$captured_error = $errstr;

return true;
}, E_WARNING);

try {
$oui_database = file($url);
} finally {
restore_error_handler();
}

if (is_array($oui_database) && cacti_sizeof($oui_database)) {
return $oui_database;
}

$reason = ($captured_error !== '') ? trim($captured_error) : 'no data returned';

cacti_log(sprintf('INFO: MacTrack could not download the OUI database from %s (attempt %d of %d): %s. This is usually a transient IEEE connectivity issue.',
$url, $attempt, $retries, $reason), false, 'MACTRACK', POLLER_VERBOSITY_LOW);

if ($attempt < $retries && $delay > 0) {
sleep($delay);
}
}
}

return false;
}

/**
* Downloads the IEEE OUI (vendor MAC prefix) database text file and
* imports its vendor/MAC-prefix/address records into the
Expand Down Expand Up @@ -3039,7 +3107,7 @@ function import_oui_database($type = 'ui', $oui_file = 'https://standards-oui.ie
$default = stream_context_set_default($default_opts);
}

$oui_database = file($oui_file);
$oui_database = mactrack_download_oui_database([$oui_file, $oui_alternate]);

if ($type != 'ui') {
print '<tr><td>';
Expand Down
241 changes: 241 additions & 0 deletions tests/Unit/MactrackOuiDownloadTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,241 @@
<?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 |
+-------------------------------------------------------------------------+
| http://www.cacti.net/ |
+-------------------------------------------------------------------------+
*/

/**
* mactrack_download_oui_database() must tolerate transient IEEE download
* failures (for example a refused connection) without letting PHP's file()
* warning escape to Cacti's error handler, which would log an "ERROR PHP
* WARNING" and fail CI. These tests drive the helper deterministically with
* local file paths (success) and unreachable paths (failure) so no network
* access is required, and they confirm retries, fallback ordering, warning
* capture, and that import_oui_database() routes through the helper.
*/
final class MactrackOuiDownloadTest extends TestCase {
/** @var array<int, string> */
private $tempFiles = [];

/**
* @return void
*/
public static function setUpBeforeClass(): void {
self::loadPluginSource('lib/mactrack_functions.php');
}

/**
* @return void
*/
protected function tearDown(): void {
foreach ($this->tempFiles as $file) {
if (is_file($file)) {
unlink($file);
}
}

$this->tempFiles = [];

parent::tearDown();
}

/**
* Create a readable temp file whose contents file() can return.
*
* @param string $contents
*
* @return string Absolute path to the temp file.
*/
private function writeTempFile($contents) {
$path = tempnam(sys_get_temp_dir(), 'mt_oui_');

file_put_contents($path, $contents);

$this->tempFiles[] = $path;

return $path;
}

/**
* An absolute path that cannot be opened, so file() fails with E_WARNING.
*
* @return string
*/
private function unreachablePath() {
return sys_get_temp_dir() . '/mt_oui_missing_' . uniqid('', true) . '/oui.txt';
}

/**
* Messages passed to the cacti_log() stub during the current test.
*
* @return array<int, string>
*/
private function loggedMessages() {
$messages = [];

foreach ($GLOBALS['__test_db_calls'] as $call) {
if ($call['fn'] === 'cacti_log') {
$messages[] = $call['sql'];
}
}

return $messages;
}

/**
* @return void
*/
public function testReturnsFileContentsOnFirstSuccessfulUrl(): void {
$path = $this->writeTempFile("line one\nline two\n");

$result = mactrack_download_oui_database([$path]);

$this->assertSame(file($path), $result);
$this->assertSame([], $this->loggedMessages(), 'a successful download should not log anything');
}

/**
* @return void
*/
public function testFallsBackToAlternateUrlWhenPrimaryFails(): void {
$bad = $this->unreachablePath();
$good = $this->writeTempFile("aa-bb-cc\n");

$result = mactrack_download_oui_database([$bad, $good], 1, 0);

$this->assertSame(file($good), $result);

$messages = $this->loggedMessages();
$this->assertCount(1, $messages, 'only the failed primary URL should be logged');
$this->assertStringContainsString($bad, $messages[0]);
$this->assertStringContainsString('INFO:', $messages[0]);
}

/**
* @return void
*/
public function testRetriesEachUrlTheRequestedNumberOfTimes(): void {
$result = mactrack_download_oui_database([$this->unreachablePath()], 3, 0);

$this->assertFalse($result);
$this->assertCount(3, $this->loggedMessages());
}

/**
* @return void
*/
public function testReturnsFalseWhenEveryUrlAndAttemptIsExhausted(): void {
$result = mactrack_download_oui_database([$this->unreachablePath(), $this->unreachablePath()], 2, 0);

$this->assertFalse($result);
$this->assertCount(4, $this->loggedMessages(), 'two URLs x two attempts should log four times');
}

/**
* @return void
*/
public function testFiltersOutEmptyUrls(): void {
$good = $this->writeTempFile("vendor\n");

$result = mactrack_download_oui_database(['', $good], 1, 0);

$this->assertSame(file($good), $result);
$this->assertSame([], $this->loggedMessages(), 'empty URLs must not count as a failed attempt');
}

/**
* @return void
*/
public function testCoercesRetriesBelowOneToASingleAttempt(): void {
$result = mactrack_download_oui_database([$this->unreachablePath()], 0, 0);

$this->assertFalse($result);
$this->assertCount(1, $this->loggedMessages(), 'retries below one must still make a single attempt');
}

/**
* @return void
*/
public function testCapturesTheConnectionWarningLocally(): void {
$escaped = false;

set_error_handler(static function() use (&$escaped): bool {
$escaped = true;

return true;
}, E_WARNING);

try {
$result = mactrack_download_oui_database([$this->unreachablePath()], 1, 0);
} finally {
restore_error_handler();
}

$this->assertFalse($result);
$this->assertFalse($escaped, 'file() warning must be captured locally, not propagated');

$messages = $this->loggedMessages();
$this->assertCount(1, $messages);
$this->assertStringContainsStringIgnoringCase('failed to open stream', $messages[0]);
}

/**
* @return void
*/
public function testWaitsBetweenAttemptsWhenDelayIsConfigured(): void {
$start = microtime(true);

$result = mactrack_download_oui_database([$this->unreachablePath()], 2, 1);

$elapsed = microtime(true) - $start;

$this->assertFalse($result);
$this->assertCount(2, $this->loggedMessages());
$this->assertGreaterThanOrEqual(1.0, $elapsed, 'a positive delay should pause between attempts');
}

/**
* import_oui_database() must route its download through the helper and
* still import the returned records. Driving it with a local fixture keeps
* the call site covered without reaching out to IEEE.
*
* @return void
*/
public function testImportOuiDatabaseRoutesThroughDownloader(): void {
$fixture = $this->writeTempFile(
"AA-BB-CC (hex)\t\tExample Vendor Inc.\n" .
"AABBCC (base 16)\t\tExample Vendor Inc.\n" .
"\t\t\t\t123 Example Street\n" .
"\t\t\t\tCity State 12345\n" .
"\n"
);

ob_start();
import_oui_database('ui', $fixture);
$output = ob_get_clean();

$this->assertStringContainsString('OUI Database Download from IEEE Complete', $output);

$replaced = false;

foreach ($GLOBALS['__test_db_calls'] as $call) {
if ($call['fn'] === 'db_execute' && strpos($call['sql'], 'REPLACE INTO mac_track_oui_database') !== false) {
$replaced = true;

break;
}
}

$this->assertTrue($replaced, 'the imported vendor block should be written with a REPLACE');
}
}
6 changes: 6 additions & 0 deletions tests/bootstrap-unit.php
Original file line number Diff line number Diff line change
Expand Up @@ -213,6 +213,12 @@ function db_fetch_cell_prepared($sql, $params = array()) {
}
}

if (!function_exists('db_qstr')) {
function db_qstr($value) {
return "'" . str_replace("'", "''", (string) $value) . "'";
}
}

if (!function_exists('db_index_exists')) {
function db_index_exists($table, $index) {
return mactrack_test_next_return('db_index_exists', false);
Expand Down
Loading