· 2 years ago · Mar 05, 2023, 01:20 PM
1librenms@svr-digi-librenms:~/includes$ cat functions.php
2<?php
3
4/**
5 * LibreNMS
6 *
7 * This file is part of LibreNMS.
8 *
9 * @copyright (C) 2006 - 2012 Adam Armstrong
10 */
11
12use App\Models\Device;
13use Illuminate\Support\Facades\Http;
14use Illuminate\Support\Str;
15use LibreNMS\Config;
16use LibreNMS\Enum\PortAssociationMode;
17use LibreNMS\Exceptions\HostExistsException;
18use LibreNMS\Exceptions\HostIpExistsException;
19use LibreNMS\Exceptions\HostnameExistsException;
20use LibreNMS\Exceptions\HostSysnameExistsException;
21use LibreNMS\Exceptions\HostUnreachableException;
22use LibreNMS\Exceptions\HostUnreachablePingException;
23use LibreNMS\Exceptions\HostUnreachableSnmpException;
24use LibreNMS\Exceptions\InvalidPortAssocModeException;
25use LibreNMS\Exceptions\SnmpVersionUnsupportedException;
26use LibreNMS\Modules\Core;
27use LibreNMS\Util\Proxy;
28
29function array_sort_by_column($array, $on, $order = SORT_ASC)
30{
31 $new_array = [];
32 $sortable_array = [];
33
34 if (count($array) > 0) {
35 foreach ($array as $k => $v) {
36 if (is_array($v)) {
37 foreach ($v as $k2 => $v2) {
38 if ($k2 == $on) {
39 $sortable_array[$k] = $v2;
40 }
41 }
42 } else {
43 $sortable_array[$k] = $v;
44 }
45 }
46
47 switch ($order) {
48 case SORT_ASC:
49 asort($sortable_array);
50 break;
51 case SORT_DESC:
52 arsort($sortable_array);
53 break;
54 }
55
56 foreach ($sortable_array as $k => $v) {
57 $new_array[$k] = $array[$k];
58 }
59 }
60
61 return $new_array;
62}
63
64function only_alphanumeric($string)
65{
66 return preg_replace('/[^a-zA-Z0-9]/', '', $string);
67}
68
69/**
70 * Parse cli discovery or poller modules and set config for this run
71 *
72 * @param string $type discovery or poller
73 * @param array $options get_opts array (only m key is checked)
74 * @return bool
75 */
76function parse_modules($type, $options)
77{
78 $override = false;
79
80 if (! empty($options['m'])) {
81 Config::set("{$type}_modules", []);
82 foreach (explode(',', $options['m']) as $module) {
83 // parse submodules (only supported by some modules)
84 if (Str::contains($module, '/')) {
85 [$module, $submodule] = explode('/', $module, 2);
86 $existing_submodules = Config::get("{$type}_submodules.$module", []);
87 $existing_submodules[] = $submodule;
88 Config::set("{$type}_submodules.$module", $existing_submodules);
89 }
90
91 $dir = $type == 'poller' ? 'polling' : $type;
92 if (is_file("includes/$dir/$module.inc.php")) {
93 Config::set("{$type}_modules.$module", 1);
94 $override = true;
95 }
96 }
97
98 // display selected modules
99 $modules = array_map(function ($module) use ($type) {
100 $submodules = Config::get("{$type}_submodules.$module");
101
102 return $module . ($submodules ? '(' . implode(',', $submodules) . ')' : '');
103 }, array_keys(Config::get("{$type}_modules", [])));
104
105 d_echo("Override $type modules: " . implode(', ', $modules) . PHP_EOL);
106 }
107
108 return $override;
109}
110
111function logfile($string)
112{
113 $fd = fopen(Config::get('log_file'), 'a');
114 fputs($fd, $string . "\n");
115 fclose($fd);
116}
117
118function percent_colour($perc)
119{
120 $r = min(255, 5 * ($perc - 25));
121 $b = max(0, 255 - (5 * ($perc + 25)));
122
123 return sprintf('#%02x%02x%02x', $r, $b, $b);
124}
125
126/**
127 * @param $device
128 * @return string the path to the icon image for this device. Close to square.
129 */
130function getIcon($device)
131{
132 return 'images/os/' . getImageName($device);
133}
134
135/**
136 * @param $device
137 * @return string an image tag with the icon for this device. Close to square.
138 */
139function getIconTag($device)
140{
141 return '<img src="' . getIcon($device) . '" title="' . getImageTitle($device) . '"/>';
142}
143
144function getImageTitle($device)
145{
146 return $device['icon'] ? str_replace(['.svg', '.png'], '', $device['icon']) : $device['os'];
147}
148
149function getImageName($device, $use_database = true, $dir = 'images/os/')
150{
151 return \LibreNMS\Util\Url::findOsImage($device['os'], $device['features'] ?? '', $use_database ? $device['icon'] : null, $dir);
152}
153
154function renamehost($id, $new, $source = 'console')
155{
156 $host = gethostbyid($id);
157
158 if (! is_dir(Rrd::dirFromHost($new)) && rename(Rrd::dirFromHost($host), Rrd::dirFromHost($new)) === true) {
159 dbUpdate(['hostname' => $new, 'ip' => null], 'devices', 'device_id=?', [$id]);
160 log_event("Hostname changed -> $new ($source)", $id, 'system', 3);
161
162 return '';
163 }
164
165 log_event("Renaming of $host failed", $id, 'system', 5);
166
167 return "Renaming of $host failed\n";
168}
169
170function device_discovery_trigger($id)
171{
172 if (App::runningInConsole() === false) {
173 ignore_user_abort(true);
174 set_time_limit(0);
175 }
176
177 $update = dbUpdate(['last_discovered' => ['NULL']], 'devices', '`device_id` = ?', [$id]);
178 if (! empty($update) || $update == '0') {
179 $message = 'Device will be rediscovered';
180 } else {
181 $message = 'Error rediscovering device';
182 }
183
184 return ['status'=> $update, 'message' => $message];
185}
186
187function delete_device($id)
188{
189 $device = DeviceCache::get($id);
190 if (! $device->exists) {
191 return 'No such device.';
192 }
193
194 if ($device->delete()) {
195 return "Removed device $device->hostname\n";
196 }
197
198 return "Failed to remove device $device->hostname";
199}
200
201/**
202 * Add a device to LibreNMS
203 *
204 * @param string $host dns name or ip address
205 * @param string $snmp_version If this is empty, try v2c,v3,v1. Otherwise, use this specific version.
206 * @param int $port the port to connect to for snmp
207 * @param string $transport udp or tcp
208 * @param string $poller_group the poller group this device will belong to
209 * @param bool $force_add add even if the device isn't reachable
210 * @param string $port_assoc_mode snmp field to use to determine unique ports
211 * @param array $additional an array with additional parameters to take into consideration when adding devices
212 * @return int returns the device_id of the added device
213 *
214 * @throws HostExistsException This hostname already exists
215 * @throws HostIpExistsException We already have a host with this IP
216 * @throws HostUnreachableException We could not reach this device is some way
217 * @throws HostUnreachablePingException We could not ping the device
218 * @throws InvalidPortAssocModeException The given port association mode was invalid
219 * @throws SnmpVersionUnsupportedException The given snmp version was invalid
220 */
221function addHost($host, $snmp_version = '', $port = 161, $transport = 'udp', $poller_group = '0', $force_add = false, $port_assoc_mode = 'ifIndex', $additional = [])
222{
223 // Test Database Exists
224 if (host_exists($host)) {
225 throw new HostnameExistsException($host);
226 }
227
228 // Valid port assoc mode
229 if (! in_array($port_assoc_mode, PortAssociationMode::getModes())) {
230 throw new InvalidPortAssocModeException("Invalid port association_mode '$port_assoc_mode'. Valid modes are: " . join(', ', PortAssociationMode::getModes()));
231 }
232
233 // check if we have the host by IP
234 $overwrite_ip = null;
235 if (! empty($additional['overwrite_ip'])) {
236 $overwrite_ip = $additional['overwrite_ip'];
237 $ip = $overwrite_ip;
238 } elseif (Config::get('addhost_alwayscheckip') === true) {
239 $ip = gethostbyname($host);
240 } else {
241 $ip = $host;
242 }
243 if ($force_add !== true && $existing = device_has_ip($ip)) {
244 throw new HostIpExistsException($host, $existing->hostname, $ip);
245 }
246
247 // Test reachability
248 if (! $force_add) {
249 if (! ((new \LibreNMS\Polling\ConnectivityHelper(new Device(['hostname' => $ip])))->isPingable()->success())) {
250 throw new HostUnreachablePingException($host);
251 }
252 }
253
254 // if $snmpver isn't set, try each version of snmp
255 if (empty($snmp_version)) {
256 $snmpvers = Config::get('snmp.version');
257 } else {
258 $snmpvers = [$snmp_version];
259 }
260
261 if (isset($additional['snmp_disable']) && $additional['snmp_disable'] == 1) {
262 return createHost($host, '', $snmp_version, $port, $transport, [], $poller_group, 1, true, $overwrite_ip, $additional);
263 }
264 $host_unreachable_exception = new HostUnreachableSnmpException($host);
265 // try different snmp variables to add the device
266 foreach ($snmpvers as $snmpver) {
267 if ($snmpver === 'v3') {
268 // Try each set of parameters from config
269 foreach (Config::get('snmp.v3') as $v3) {
270 $device = deviceArray($host, null, $snmpver, $port, $transport, $v3, $port_assoc_mode, $overwrite_ip);
271 if ($force_add === true || isSNMPable($device)) {
272 return createHost($host, null, $snmpver, $port, $transport, $v3, $poller_group, $port_assoc_mode, $force_add, $overwrite_ip);
273 } else {
274 $host_unreachable_exception->addReason($snmpver, $v3['authname'] . '/' . $v3['authlevel']);
275 }
276 }
277 } elseif ($snmpver === 'v2c' || $snmpver === 'v1') {
278 // try each community from config
279 foreach (Config::get('snmp.community') as $community) {
280 $device = deviceArray($host, $community, $snmpver, $port, $transport, null, $port_assoc_mode, $overwrite_ip);
281
282 if ($force_add === true || isSNMPable($device)) {
283 return createHost($host, $community, $snmpver, $port, $transport, [], $poller_group, $port_assoc_mode, $force_add, $overwrite_ip);
284 } else {
285 $host_unreachable_exception->addReason($snmpver, $community);
286 }
287 }
288 } else {
289 throw new SnmpVersionUnsupportedException($snmpver);
290 }
291 }
292 if (isset($additional['ping_fallback']) && $additional['ping_fallback'] == 1) {
293 $additional['snmp_disable'] = 1;
294 $additional['os'] = 'ping';
295
296 return createHost($host, '', $snmp_version, $port, $transport, [], $poller_group, 1, true, $overwrite_ip, $additional);
297 }
298 throw $host_unreachable_exception;
299}
300
301function deviceArray($host, $community, $snmpver, $port = 161, $transport = 'udp', $v3 = [], $port_assoc_mode = 'ifIndex', $overwrite_ip = null)
302{
303 $device = [];
304 $device['hostname'] = $host;
305 $device['overwrite_ip'] = $overwrite_ip;
306 $device['port'] = $port;
307 $device['transport'] = $transport;
308
309 /* Get port_assoc_mode id if neccessary
310 * We can work with names of IDs here */
311 if (! is_int($port_assoc_mode)) {
312 $port_assoc_mode = PortAssociationMode::getId($port_assoc_mode);
313 }
314 $device['port_association_mode'] = $port_assoc_mode;
315
316 $device['snmpver'] = $snmpver;
317 if ($snmpver === 'v2c' or $snmpver === 'v1') {
318 $device['community'] = $community;
319 } elseif ($snmpver === 'v3') {
320 $device['authlevel'] = $v3['authlevel'];
321 $device['authname'] = $v3['authname'];
322 $device['authpass'] = $v3['authpass'];
323 $device['authalgo'] = $v3['authalgo'];
324 $device['cryptopass'] = $v3['cryptopass'];
325 $device['cryptoalgo'] = $v3['cryptoalgo'];
326 }
327
328 return $device;
329}//end deviceArray()
330
331function isSNMPable($device)
332{
333 $pos = snmp_check($device);
334 if ($pos === true) {
335 return true;
336 } else {
337 $pos = snmp_get($device, 'sysObjectID.0', '-Oqv', 'SNMPv2-MIB');
338 if ($pos === '' || $pos === false) {
339 return false;
340 } else {
341 return true;
342 }
343 }
344}
345
346function getpollergroup($poller_group = '0')
347{
348 //Is poller group an integer
349 if (is_int($poller_group) || ctype_digit($poller_group)) {
350 return $poller_group;
351 } else {
352 //Check if it contains a comma
353 if (strpos($poller_group, ',') !== false) {
354 //If it has a comma use the first element as the poller group
355 $poller_group_array = explode(',', $poller_group);
356
357 return getpollergroup($poller_group_array[0]);
358 } else {
359 if (Config::get('distributed_poller_group')) {
360 //If not use the poller's group from the config
361 return getpollergroup(Config::get('distributed_poller_group'));
362 } else {
363 //If all else fails use default
364 return '0';
365 }
366 }
367 }
368}
369
370/**
371 * Add a host to the database
372 *
373 * @param string $host The IP or hostname to add
374 * @param string $community The snmp community
375 * @param string $snmpver snmp version: v1 | v2c | v3
376 * @param int $port SNMP port number
377 * @param string $transport SNMP transport: udp | udp6 | udp | tcp6
378 * @param array $v3 SNMPv3 settings required array keys: authlevel, authname, authpass, authalgo, cryptopass, cryptoalgo
379 * @param int $poller_group distributed poller group to assign this host to
380 * @param string $port_assoc_mode field to use to identify ports: ifIndex, ifName, ifDescr, ifAlias
381 * @param bool $force_add Do not detect the host os
382 * @param array $additional an array with additional parameters to take into consideration when adding devices
383 * @return int the id of the added host
384 *
385 * @throws HostExistsException Throws this exception if the host already exists
386 * @throws Exception Throws this exception if insertion into the database fails
387 */
388function createHost(
389 $host,
390 $community,
391 $snmpver,
392 $port = 161,
393 $transport = 'udp',
394 $v3 = [],
395 $poller_group = 0,
396 $port_assoc_mode = 'ifIndex',
397 $force_add = false,
398 $overwrite_ip = null,
399 $additional = []
400) {
401 $host = trim(strtolower($host));
402
403 $poller_group = getpollergroup($poller_group);
404
405 /* Get port_assoc_mode id if necessary
406 * We can work with names of IDs here */
407 if (! is_int($port_assoc_mode)) {
408 $port_assoc_mode = PortAssociationMode::getId($port_assoc_mode);
409 }
410
411 $device = new Device(array_merge([
412 'hostname' => $host,
413 'overwrite_ip' => $overwrite_ip,
414 'sysName' => $additional['sysName'] ?? $host,
415 'os' => $additional['os'] ?? 'generic',
416 'hardware' => $additional['hardware'] ?? null,
417 'community' => $community,
418 'port' => $port,
419 'transport' => $transport,
420 'status' => '1',
421 'snmpver' => $snmpver,
422 'poller_group' => $poller_group,
423 'status_reason' => '',
424 'port_association_mode' => $port_assoc_mode,
425 'snmp_disable' => $additional['snmp_disable'] ?? 0,
426 ], $v3));
427
428 if ($force_add !== true) {
429 $device->os = Core::detectOS($device);
430
431 $device->sysName = SnmpQuery::device($device)->get('SNMPv2-MIB::sysName.0')->value();
432 if (host_exists($host, $device->sysName)) {
433 throw new HostSysnameExistsException($host, $device->sysName);
434 }
435 }
436 if ($device->save()) {
437 return $device->device_id;
438 }
439
440 throw new \Exception('Failed to add host to the database, please run ./validate.php');
441}
442
443function isDomainResolves($domain)
444{
445 if (gethostbyname($domain) != $domain) {
446 return true;
447 }
448
449 $records = dns_get_record($domain); // returns array or false
450
451 return ! empty($records);
452}
453
454function match_network($nets, $ip, $first = false)
455{
456 $return = false;
457 if (! is_array($nets)) {
458 $nets = [$nets];
459 }
460 foreach ($nets as $net) {
461 $rev = (preg_match("/^\!/", $net)) ? true : false;
462 $net = preg_replace("/^\!/", '', $net);
463 $ip_arr = explode('/', $net);
464 $net_long = ip2long($ip_arr[0]);
465 $x = ip2long($ip_arr[1]);
466 $mask = long2ip($x) == $ip_arr[1] ? $x : 0xFFFFFFFF << (32 - $ip_arr[1]);
467 $ip_long = ip2long($ip);
468 if ($rev) {
469 if (($ip_long & $mask) == ($net_long & $mask)) {
470 return false;
471 }
472 } else {
473 if (($ip_long & $mask) == ($net_long & $mask)) {
474 $return = true;
475 }
476 if ($first && $return) {
477 return true;
478 }
479 }
480 }
481
482 return $return;
483}
484
485// FIXME port to LibreNMS\Util\IPv6 class
486function snmp2ipv6($ipv6_snmp)
487{
488 // Workaround stupid Microsoft bug in Windows 2008 -- this is fixed length!
489 // < fenestro> "because whoever implemented this mib for Microsoft was ignorant of RFC 2578 section 7.7 (2)"
490 $ipv6 = array_slice(explode('.', $ipv6_snmp), -16);
491 $ipv6_2 = [];
492
493 for ($i = 0; $i <= 15; $i++) {
494 $ipv6[$i] = zeropad(dechex($ipv6[$i]));
495 }
496 for ($i = 0; $i <= 15; $i += 2) {
497 $ipv6_2[] = $ipv6[$i] . $ipv6[$i + 1];
498 }
499
500 return implode(':', $ipv6_2);
501}
502
503function get_astext(string|int|null $asn): string
504{
505 return \LibreNMS\Util\AutonomousSystem::get($asn)->name();
506}
507
508/**
509 * Log events to the event table
510 *
511 * @param string $text message describing the event
512 * @param array|int $device device array or device_id
513 * @param string $type brief category for this event. Examples: sensor, state, stp, system, temperature, interface
514 * @param int $severity 1: ok, 2: info, 3: notice, 4: warning, 5: critical, 0: unknown
515 * @param int $reference the id of the referenced entity. Supported types: interface
516 */
517function log_event($text, $device = null, $type = null, $severity = 2, $reference = null)
518{
519 // handle legacy device array
520 if (is_array($device) && isset($device['device_id'])) {
521 $device = $device['device_id'];
522 }
523
524 \App\Models\Eventlog::log($text, $device, $type, $severity, $reference);
525}
526
527// Parse string with emails. Return array with email (as key) and name (as value)
528function parse_email($emails)
529{
530 return \LibreNMS\Util\Mail::parseEmails($emails);
531}
532
533function send_mail($emails, $subject, $message, $html = false)
534{
535 return \LibreNMS\Util\Mail::send($emails, $subject, $message, $html);
536}
537
538function hex2str($hex)
539{
540 $string = '';
541
542 for ($i = 0; $i < strlen($hex) - 1; $i += 2) {
543 $string .= chr(hexdec(substr($hex, $i, 2)));
544 }
545
546 return $string;
547}
548
549// Convert an SNMP hex string to regular string
550function snmp_hexstring($hex)
551{
552 return hex2str(str_replace(' ', '', str_replace(' 00', '', $hex)));
553}
554
555// Check if the supplied string is an SNMP hex string
556function isHexString($str)
557{
558 return (bool) preg_match('/^[a-f0-9][a-f0-9]( [a-f0-9][a-f0-9])*$/is', trim($str));
559}
560
561// Include all .inc.php files in $dir
562function include_dir($dir, $regex = '')
563{
564 global $device, $valid;
565
566 if ($regex == '') {
567 $regex = "/\.inc\.php$/";
568 }
569
570 if ($handle = opendir(Config::get('install_dir') . '/' . $dir)) {
571 while (false !== ($file = readdir($handle))) {
572 if (filetype(Config::get('install_dir') . '/' . $dir . '/' . $file) == 'file' && preg_match($regex, $file)) {
573 d_echo('Including: ' . Config::get('install_dir') . '/' . $dir . '/' . $file . "\n");
574
575 include Config::get('install_dir') . '/' . $dir . '/' . $file;
576 }
577 }
578
579 closedir($handle);
580 }
581}
582
583/**
584 * Check if port is valid to poll.
585 * Settings: empty_ifdescr, good_if, bad_if, bad_if_regexp, bad_ifname_regexp, bad_ifalias_regexp, bad_iftype, bad_ifoperstatus
586 *
587 * @param array $port
588 * @param array $device
589 * @return bool
590 */
591function is_port_valid($port, $device)
592{
593 // check empty values first
594 if (empty($port['ifDescr'])) {
595 // If these are all empty, we are just going to show blank names in the ui
596 if (empty($port['ifAlias']) && empty($port['ifName'])) {
597 d_echo("ignored: empty ifDescr, ifAlias and ifName\n");
598
599 return false;
600 }
601
602 // ifDescr should not be empty unless it is explicitly allowed
603 if (! Config::getOsSetting($device['os'], 'empty_ifdescr', Config::get('empty_ifdescr', false))) {
604 d_echo("ignored: empty ifDescr\n");
605
606 return false;
607 }
608 }
609
610 $ifDescr = $port['ifDescr'];
611 $ifName = $port['ifName'];
612 $ifAlias = $port['ifAlias'] ?? '';
613 $ifType = $port['ifType'];
614 $ifOperStatus = $port['ifOperStatus'] ?? '';
615
616 if (str_i_contains($ifDescr, Config::getOsSetting($device['os'], 'good_if', Config::get('good_if')))) {
617 return true;
618 }
619
620 foreach (Config::getCombined($device['os'], 'bad_if') as $bi) {
621 if (str_i_contains($ifDescr, $bi)) {
622 d_echo("ignored by ifDescr: $ifDescr (matched: $bi)\n");
623
624 return false;
625 }
626 }
627
628 foreach (Config::getCombined($device['os'], 'bad_if_regexp') as $bir) {
629 if (preg_match($bir . 'i', $ifDescr)) {
630 d_echo("ignored by ifDescr: $ifDescr (matched: $bir)\n");
631
632 return false;
633 }
634 }
635
636 foreach (Config::getCombined($device['os'], 'bad_ifname_regexp') as $bnr) {
637 if (preg_match($bnr . 'i', $ifName)) {
638 d_echo("ignored by ifName: $ifName (matched: $bnr)\n");
639
640 return false;
641 }
642 }
643
644 foreach (Config::getCombined($device['os'], 'bad_ifalias_regexp') as $bar) {
645 if (preg_match($bar . 'i', $ifAlias)) {
646 d_echo("ignored by ifName: $ifAlias (matched: $bar)\n");
647
648 return false;
649 }
650 }
651
652 foreach (Config::getCombined($device['os'], 'bad_iftype') as $bt) {
653 if (Str::contains($ifType, $bt)) {
654 d_echo("ignored by ifType: $ifType (matched: $bt )\n");
655
656 return false;
657 }
658 }
659
660 foreach (Config::getCombined($device['os'], 'bad_ifoperstatus') as $bos) {
661 if (Str::contains($ifOperStatus, $bos)) {
662 d_echo("ignored by ifOperStatus: $ifOperStatus (matched: $bos)\n");
663
664 return false;
665 }
666 }
667
668 return true;
669}
670
671/**
672 * Try to fill in data for ifDescr, ifName, and ifAlias if devices do not provide them.
673 * Will not fill ifAlias if the user has overridden it
674 * Also trims the data
675 *
676 * @param array $port
677 * @param array $device
678 */
679function port_fill_missing_and_trim(&$port, $device)
680{
681 if (isset($port['ifDescr'])) {
682 $port['ifDescr'] = trim($port['ifDescr']);
683 }
684 if (isset($port['ifAlias'])) {
685 $port['ifAlias'] = trim($port['ifAlias']);
686 }
687 if (isset($port['ifName'])) {
688 $port['ifName'] = trim($port['ifName']);
689 }
690 // When devices do not provide data, populate with other data if available
691 if (! isset($port['ifDescr']) || $port['ifDescr'] == '') {
692 $port['ifDescr'] = $port['ifName'];
693 d_echo(' Using ifName as ifDescr');
694 }
695 if (! empty($device['attribs']['ifName:' . $port['ifName']])) {
696 // ifAlias overridden by user, don't update it
697 unset($port['ifAlias']);
698 d_echo(' ifAlias overriden by user');
699 } elseif (! isset($port['ifAlias']) || $port['ifAlias'] == '') {
700 $port['ifAlias'] = $port['ifDescr'];
701 d_echo(' Using ifDescr as ifAlias');
702 }
703
704 if (! isset($port['ifName']) || $port['ifName'] == '') {
705 $port['ifName'] = $port['ifDescr'];
706 d_echo(' Using ifDescr as ifName');
707 }
708}
709
710function validate_device_id($id)
711{
712 if (empty($id) || ! is_numeric($id)) {
713 $return = false;
714 } else {
715 $device_id = dbFetchCell('SELECT `device_id` FROM `devices` WHERE `device_id` = ?', [$id]);
716 if ($device_id == $id) {
717 $return = true;
718 } else {
719 $return = false;
720 }
721 }
722
723 return $return;
724}
725
726function convert_delay($delay)
727{
728 if (preg_match('/(\d+)([mhd]?)/', $delay, $matches)) {
729 $multipliers = [
730 'm' => 60,
731 'h' => 3600,
732 'd' => 86400,
733 ];
734
735 $multiplier = $multipliers[$matches[2]] ?? 1;
736
737 return $matches[1] * $multiplier;
738 }
739
740 return $delay === '' ? 0 : 300;
741}
742
743function normalize_snmp_ip_address($data)
744{
745 // $data is received from snmpwalk, can be ipv4 xxx.xxx.xxx.xxx or ipv6 xx:xx:...:xx (16 chunks)
746 // ipv4 is returned unchanged, ipv6 is returned with one ':' removed out of two, like
747 // xxxx:xxxx:...:xxxx (8 chuncks)
748 return preg_replace('/([0-9a-fA-F]{2}):([0-9a-fA-F]{2})/', '\1\2', explode('%', $data, 2)[0]);
749}
750
751function guidv4($data)
752{
753 // http://stackoverflow.com/questions/2040240/php-function-to-generate-v4-uuid#15875555
754 // From: Jack http://stackoverflow.com/users/1338292/ja%CD%A2ck
755 assert(strlen($data) == 16);
756
757 $data[6] = chr(ord($data[6]) & 0x0F | 0x40); // set version to 0100
758 $data[8] = chr(ord($data[8]) & 0x3F | 0x80); // set bits 6-7 to 10
759
760 return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
761}
762
763/**
764 * @param $curl
765 */
766function set_curl_proxy($curl)
767{
768 \LibreNMS\Util\Proxy::applyToCurl($curl);
769}
770
771function target_to_id($target)
772{
773 if ($target[0] . $target[1] == 'g:') {
774 $target = 'g' . dbFetchCell('SELECT id FROM device_groups WHERE name = ?', [substr($target, 2)]);
775 } else {
776 $target = dbFetchCell('SELECT device_id FROM devices WHERE hostname = ?', [$target]);
777 }
778
779 return $target;
780}
781
782function fix_integer_value($value)
783{
784 if ($value < 0) {
785 $return = 4294967296 + $value;
786 } else {
787 $return = $value;
788 }
789
790 return $return;
791}
792
793/**
794 * Find a device that has this IP. Checks ipv4_addresses and ipv6_addresses tables.
795 *
796 * @param string $ip
797 * @return \App\Models\Device|false
798 */
799function device_has_ip($ip)
800{
801 return Device::findByIp($ip);
802}
803
804/**
805 * Checks if the $hostname provided exists in the DB already
806 *
807 * @param string $hostname The hostname to check for
808 * @param string $sysName The sysName to check
809 * @return bool true if hostname already exists
810 * false if hostname doesn't exist
811 */
812function host_exists($hostname, $sysName = null)
813{
814 $query = 'SELECT COUNT(*) FROM `devices` WHERE `hostname`=?';
815 $params = [$hostname];
816
817 if (! empty($sysName) && ! Config::get('allow_duplicate_sysName')) {
818 $query .= ' OR `sysName`=?';
819 $params[] = $sysName;
820
821 if (! empty(Config::get('mydomain'))) {
822 $full_sysname = rtrim($sysName, '.') . '.' . Config::get('mydomain');
823 $query .= ' OR `sysName`=?';
824 $params[] = $full_sysname;
825 }
826 }
827
828 return dbFetchCell($query, $params) > 0;
829}
830
831/**
832 * Perform DNS lookup
833 *
834 * @param array $device Device array from database
835 * @param string $type The type of record to lookup
836 * @return string ip
837 *
838 **/
839function dnslookup($device, $type = false, $return = false)
840{
841 if (filter_var($device['hostname'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) == true || filter_var($device['hostname'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) == true) {
842 return false;
843 }
844 if (empty($type)) {
845 // We are going to use the transport to work out the record type
846 if ($device['transport'] == 'udp6' || $device['transport'] == 'tcp6') {
847 $type = DNS_AAAA;
848 $return = 'ipv6';
849 } else {
850 $type = DNS_A;
851 $return = 'ip';
852 }
853 }
854 if (empty($return)) {
855 return false;
856 }
857 $record = dns_get_record($device['hostname'], $type);
858
859 return $record[0][$return] ?? null;
860}//end dnslookup
861
862/**
863 * Create a new state index. Update translations if $states is given.
864 *
865 * For for backward compatibility:
866 * Returns null if $states is empty, $state_name already exists, and contains state translations
867 *
868 * @param string $state_name the unique name for this state translation
869 * @param array $states array of states, each must contain keys: descr, graph, value, generic
870 * @return int|null
871 */
872function create_state_index($state_name, $states = [])
873{
874 $state_index_id = dbFetchCell('SELECT `state_index_id` FROM state_indexes WHERE state_name = ? LIMIT 1', [$state_name]);
875 if (! is_numeric($state_index_id)) {
876 $state_index_id = dbInsert(['state_name' => $state_name], 'state_indexes');
877
878 // legacy code, return index so states are created
879 if (empty($states)) {
880 return $state_index_id;
881 }
882 }
883
884 // check or synchronize states
885 if (empty($states)) {
886 $translations = dbFetchRows('SELECT * FROM `state_translations` WHERE `state_index_id` = ?', [$state_index_id]);
887 if (count($translations) == 0) {
888 // If we don't have any translations something has gone wrong so return the state_index_id so they get created.
889 return $state_index_id;
890 }
891 } else {
892 sync_sensor_states($state_index_id, $states);
893 }
894
895 return null;
896}
897
898/**
899 * Synchronize the sensor state translations with the database
900 *
901 * @param int $state_index_id index of the state
902 * @param array $states array of states, each must contain keys: descr, graph, value, generic
903 */
904function sync_sensor_states($state_index_id, $states)
905{
906 $new_translations = array_reduce($states, function ($array, $state) use ($state_index_id) {
907 $array[$state['value']] = [
908 'state_index_id' => $state_index_id,
909 'state_descr' => $state['descr'],
910 'state_draw_graph' => $state['graph'],
911 'state_value' => $state['value'],
912 'state_generic_value' => $state['generic'],
913 ];
914
915 return $array;
916 }, []);
917
918 $existing_translations = dbFetchRows(
919 'SELECT `state_index_id`,`state_descr`,`state_draw_graph`,`state_value`,`state_generic_value` FROM `state_translations` WHERE `state_index_id`=?',
920 [$state_index_id]
921 );
922
923 foreach ($existing_translations as $translation) {
924 $value = $translation['state_value'];
925 if (isset($new_translations[$value])) {
926 if ($new_translations[$value] != $translation) {
927 dbUpdate(
928 $new_translations[$value],
929 'state_translations',
930 '`state_index_id`=? AND `state_value`=?',
931 [$state_index_id, $value]
932 );
933 }
934
935 // this translation is synchronized, it doesn't need to be inserted
936 unset($new_translations[$value]);
937 } else {
938 dbDelete('state_translations', '`state_index_id`=? AND `state_value`=?', [$state_index_id, $value]);
939 }
940 }
941
942 // insert any new translations
943 dbBulkInsert($new_translations, 'state_translations');
944}
945
946function create_sensor_to_state_index($device, $state_name, $index)
947{
948 $sensor_entry = dbFetchRow('SELECT sensor_id FROM `sensors` WHERE `sensor_class` = ? AND `device_id` = ? AND `sensor_type` = ? AND `sensor_index` = ?', [
949 'state',
950 $device['device_id'],
951 $state_name,
952 $index,
953 ]);
954 $state_indexes_entry = dbFetchRow('SELECT state_index_id FROM `state_indexes` WHERE `state_name` = ?', [
955 $state_name,
956 ]);
957 if (! empty($sensor_entry['sensor_id']) && ! empty($state_indexes_entry['state_index_id'])) {
958 $insert = [
959 'sensor_id' => $sensor_entry['sensor_id'],
960 'state_index_id' => $state_indexes_entry['state_index_id'],
961 ];
962 foreach ($insert as $key => $val_check) {
963 if (! isset($val_check)) {
964 unset($insert[$key]);
965 }
966 }
967
968 dbInsert($insert, 'sensors_to_state_indexes');
969 }
970}
971
972function delta_to_bits($delta, $period)
973{
974 return round(($delta * 8 / $period), 2);
975}
976
977function report_this($message)
978{
979 return '<h2>' . $message . ' Please <a href="' . Config::get('project_issues') . '">report this</a> to the ' . Config::get('project_name') . ' developers.</h2>';
980}//end report_this()
981
982function hytera_h2f($number, $nd)
983{
984 if (strlen(str_replace(' ', '', $number)) == 4) {
985 $hex = '';
986 for ($i = 0; $i < strlen($number); $i++) {
987 $byte = strtoupper(dechex(ord($number[$i])));
988 $byte = str_repeat('0', 2 - strlen($byte)) . $byte;
989 $hex .= $byte . ' ';
990 }
991 $number = $hex;
992 unset($hex);
993 }
994 $r = '';
995 $y = explode(' ', $number);
996 foreach ($y as $z) {
997 $r = $z . '' . $r;
998 }
999
1000 $hex = [];
1001 $number = substr($r, 0, -1);
1002 //$number = str_replace(" ", "", $number);
1003 for ($i = 0; $i < strlen($number); $i++) {
1004 $hex[] = substr($number, $i, 1);
1005 }
1006
1007 $dec = [];
1008 $hexCount = count($hex);
1009 for ($i = 0; $i < $hexCount; $i++) {
1010 $dec[] = hexdec($hex[$i]);
1011 }
1012
1013 $binfinal = '';
1014 $decCount = count($dec);
1015 for ($i = 0; $i < $decCount; $i++) {
1016 $binfinal .= sprintf('%04d', decbin($dec[$i]));
1017 }
1018
1019 $sign = substr($binfinal, 0, 1);
1020 $exp = substr($binfinal, 1, 8);
1021 $exp = bindec($exp);
1022 $exp -= 127;
1023 $scibin = substr($binfinal, 9);
1024 $binint = substr($scibin, 0, $exp);
1025 $binpoint = substr($scibin, $exp);
1026 $intnumber = bindec('1' . $binint);
1027
1028 $tmppoint = [];
1029 for ($i = 0; $i < strlen($binpoint); $i++) {
1030 $tmppoint[] = substr($binpoint, $i, 1);
1031 }
1032
1033 $tmppoint = array_reverse($tmppoint);
1034 $tpointnumber = min(number_format($tmppoint[0] / 2, strlen($binpoint), '.', ''), 1);
1035
1036 $pointnumber = '';
1037 for ($i = 1; $i < strlen($binpoint); $i++) {
1038 $pointnumber = number_format($tpointnumber / 2, strlen($binpoint), '.', '');
1039 $tpointnumber = $tmppoint[$i + 1] . substr($pointnumber, 1);
1040 }
1041
1042 $floatfinal = $intnumber + $pointnumber;
1043
1044 if ($sign == 1) {
1045 $floatfinal = -$floatfinal;
1046 }
1047
1048 return number_format($floatfinal, $nd, '.', '');
1049}
1050
1051/*
1052 * Cisco CIMC functions
1053 */
1054// Create an entry in the entPhysical table if it doesnt already exist.
1055function setCIMCentPhysical($location, $data, &$entphysical, &$index)
1056{
1057 // Go get the location, this will create it if it doesnt exist.
1058 $entPhysicalIndex = getCIMCentPhysical($location, $entphysical, $index);
1059
1060 // See if we need to update
1061 $update = [];
1062 foreach ($data as $key => $value) {
1063 // Is the Array(DB) value different to the supplied data
1064 if ($entphysical[$location][$key] != $value) {
1065 $update[$key] = $value;
1066 $entphysical[$location][$key] = $value;
1067 } // End if
1068 } // end foreach
1069
1070 // Do we need to update
1071 if (count($update) > 0) {
1072 dbUpdate($update, 'entPhysical', '`entPhysical_id` = ?', [$entphysical[$location]['entPhysical_id']]);
1073 }
1074 $entPhysicalId = $entphysical[$location]['entPhysical_id'];
1075
1076 return [$entPhysicalId, $entPhysicalIndex];
1077}
1078
1079function getCIMCentPhysical($location, &$entphysical, &$index)
1080{
1081 global $device;
1082
1083 // Level 1 - Does the location exist
1084 if (isset($entphysical[$location])) {
1085 // Yes, return the entPhysicalIndex.
1086 return $entphysical[$location]['entPhysicalIndex'];
1087 } else {
1088 /*
1089 * No, the entry doesnt exist.
1090 * Find its parent so we can create it.
1091 */
1092
1093 // Pull apart the location
1094 $parts = explode('/', $location);
1095
1096 // Level 2 - Are we at the root
1097 if (count($parts) == 1) {
1098 // Level 2 - Yes. We are the root, there is no parent
1099 d_echo('ROOT - ' . $location . "\n");
1100 $shortlocation = $location;
1101 $parent = 0;
1102 } else {
1103 // Level 2 - No. Need to go deeper.
1104 d_echo('NON-ROOT - ' . $location . "\n");
1105 $shortlocation = array_pop($parts);
1106 $parentlocation = implode('/', $parts);
1107 d_echo('Decend - parent location: ' . $parentlocation . "\n");
1108 $parent = getCIMCentPhysical($parentlocation, $entphysical, $index);
1109 } // end if - Level 2
1110 d_echo('Parent: ' . $parent . "\n");
1111
1112 // Now we have an ID, create the entry.
1113 $index++;
1114 $insert = [
1115 'device_id' => $device['device_id'],
1116 'entPhysicalIndex' => $index,
1117 'entPhysicalClass' => 'container',
1118 'entPhysicalVendorType' => $location,
1119 'entPhysicalName' => $shortlocation,
1120 'entPhysicalContainedIn' => $parent,
1121 'entPhysicalParentRelPos' => '-1',
1122 ];
1123
1124 // Add to the DB and Array.
1125 $id = dbInsert($insert, 'entPhysical');
1126 $entphysical[$location] = dbFetchRow('SELECT * FROM entPhysical WHERE entPhysical_id=?', [$id]);
1127
1128 return $index;
1129 } // end if - Level 1
1130} // end function
1131
1132/* idea from https://php.net/manual/en/function.hex2bin.php comments */
1133function hex2bin_compat($str)
1134{
1135 if (strlen($str) % 2 !== 0) {
1136 trigger_error(__FUNCTION__ . '(): Hexadecimal input string must have an even length', E_USER_WARNING);
1137 }
1138
1139 return pack('H*', $str);
1140}
1141
1142if (! function_exists('hex2bin')) {
1143 // This is only a hack
1144 function hex2bin($str)
1145 {
1146 return hex2bin_compat($str);
1147 }
1148}
1149
1150function q_bridge_bits2indices($hex_data)
1151{
1152 /* convert hex string to an array of 1-based indices of the nonzero bits
1153 * ie. '9a00' -> '100110100000' -> array(1, 4, 5, 7)
1154 */
1155 $hex_data = str_replace([' ', "\n"], '', $hex_data);
1156
1157 // we need an even number of digits for hex2bin
1158 if (strlen($hex_data) % 2 === 1) {
1159 $hex_data = '0' . $hex_data;
1160 }
1161
1162 $value = hex2bin($hex_data);
1163 $length = strlen($value);
1164 $indices = [];
1165 for ($i = 0; $i < $length; $i++) {
1166 $byte = ord($value[$i]);
1167 for ($j = 7; $j >= 0; $j--) {
1168 if ($byte & (1 << $j)) {
1169 $indices[] = 8 * $i + 8 - $j;
1170 }
1171 }
1172 }
1173
1174 return $indices;
1175}
1176
1177/**
1178 * Function to generate Mac OUI Cache
1179 */
1180function cache_mac_oui()
1181{
1182 // timers:
1183 $mac_oui_refresh_int_min = 86400 * rand(7, 11); // 7 days + a random number between 0 and 4 days
1184 $mac_oui_cache_time = 1296000; // we keep data during 15 days maximum
1185
1186 $lock = Cache::lock('macouidb-refresh', $mac_oui_refresh_int_min); //We want to refresh after at least $mac_oui_refresh_int_min
1187
1188 if (Config::get('mac_oui.enabled') !== true) {
1189 echo 'Mac OUI integration disabled' . PHP_EOL;
1190
1191 return 0;
1192 }
1193
1194 if ($lock->get()) {
1195 echo 'Caching Mac OUI' . PHP_EOL;
1196 try {
1197 $mac_oui_url = 'https://gitlab.com/wireshark/wireshark/-/raw/master/manuf';
1198 //$mac_oui_url_mirror = 'https://raw.githubusercontent.com/wireshark/wireshark/master/manuf';
1199
1200 echo ' -> Downloading ...' . PHP_EOL;
1201 $get = Http::withOptions(['proxy' => Proxy::forGuzzle()])->get($mac_oui_url);
1202 echo ' -> Processing CSV ...' . PHP_EOL;
1203 $csv_data = $get->body();
1204 foreach (explode("\n", $csv_data) as $csv_line) {
1205 unset($oui);
1206 $entry = str_getcsv($csv_line, "\t");
1207
1208 $length = strlen($entry[0]);
1209 $prefix = strtolower(str_replace(':', '', $entry[0]));
1210
1211 if (is_array($entry) && count($entry) >= 3 && $length == 8) {
1212 // We have a standard OUI xx:xx:xx
1213 $oui = $prefix;
1214 } elseif (is_array($entry) && count($entry) >= 3 && $length == 20) {
1215 // We have a smaller range (xx:xx:xx:X or xx:xx:xx:xx:X)
1216 if (substr($prefix, -2) == '28') {
1217 $oui = substr($prefix, 0, 7);
1218 } elseif (substr($prefix, -2) == '36') {
1219 $oui = substr($prefix, 0, 9);
1220 }
1221 }
1222 if (isset($oui)) {
1223 echo "Adding $oui, $entry[2]" . PHP_EOL;
1224 $key = 'OUIDB-' . $oui;
1225 Cache::put($key, $entry[2], $mac_oui_cache_time);
1226 }
1227 }
1228 } catch (Exception $e) {
1229 echo 'Error processing Mac OUI :' . PHP_EOL;
1230 echo 'Exception: ' . get_class($e) . PHP_EOL;
1231 echo $e->getMessage() . PHP_EOL;
1232
1233 $lock->release(); // we did not succeed so we'll try again next time
1234
1235 return 1;
1236 }
1237 }
1238
1239 return 0;
1240}
1241
1242/**
1243 * Function to generate PeeringDB Cache
1244 */
1245function cache_peeringdb()
1246{
1247 if (Config::get('peeringdb.enabled') === true) {
1248 $peeringdb_url = 'https://peeringdb.com/api';
1249 // We cache for 71 hours
1250 $cached = dbFetchCell('SELECT count(*) FROM `pdb_ix` WHERE (UNIX_TIMESTAMP() - timestamp) < 255600');
1251 if ($cached == 0) {
1252 $rand = rand(3, 30);
1253 echo "No cached PeeringDB data found, sleeping for $rand seconds" . PHP_EOL;
1254 sleep($rand);
1255 $peer_keep = [];
1256 $ix_keep = [];
1257 foreach (dbFetchRows('SELECT `bgpLocalAs` FROM `devices` WHERE `disabled` = 0 AND `ignore` = 0 AND `bgpLocalAs` > 0 AND (`bgpLocalAs` < 64512 OR `bgpLocalAs` > 65535) AND `bgpLocalAs` < 4200000000 GROUP BY `bgpLocalAs`') as $as) {
1258 $asn = $as['bgpLocalAs'];
1259 $get = Http::withOptions(['proxy' => Proxy::forGuzzle()])->get($peeringdb_url . '/net?depth=2&asn=' . $asn);
1260 $json_data = $get->body();
1261 $data = json_decode($json_data);
1262 $ixs = $data->{'data'}[0]->{'netixlan_set'};
1263 foreach ($ixs ?? [] as $ix) {
1264 $ixid = $ix->{'ix_id'};
1265 $tmp_ix = dbFetchRow('SELECT * FROM `pdb_ix` WHERE `ix_id` = ? AND asn = ?', [$ixid, $asn]);
1266 if ($tmp_ix) {
1267 $pdb_ix_id = $tmp_ix['pdb_ix_id'];
1268 $update = ['name' => $ix->{'name'}, 'timestamp' => time()];
1269 dbUpdate($update, 'pdb_ix', '`ix_id` = ? AND `asn` = ?', [$ixid, $asn]);
1270 } else {
1271 $insert = [
1272 'ix_id' => $ixid,
1273 'name' => $ix->{'name'},
1274 'asn' => $asn,
1275 'timestamp' => time(),
1276 ];
1277 $pdb_ix_id = dbInsert($insert, 'pdb_ix');
1278 }
1279 $ix_keep[] = $pdb_ix_id;
1280 $get_ix = Http::withOptions(['proxy' => Proxy::forGuzzle()])->get("$peeringdb_url/netixlan?ix_id=$ixid");
1281 $ix_json = $get_ix->body();
1282 $ix_data = json_decode($ix_json);
1283 $peers = $ix_data->{'data'};
1284 foreach ($peers ?? [] as $index => $peer) {
1285 $peer_name = get_astext($peer->{'asn'});
1286 $tmp_peer = dbFetchRow('SELECT * FROM `pdb_ix_peers` WHERE `peer_id` = ? AND `ix_id` = ?', [$peer->{'id'}, $ixid]);
1287 if ($tmp_peer) {
1288 $peer_keep[] = $tmp_peer['pdb_ix_peers_id'];
1289 $update = [
1290 'remote_asn' => $peer->{'asn'},
1291 'remote_ipaddr4' => $peer->{'ipaddr4'},
1292 'remote_ipaddr6' => $peer->{'ipaddr6'},
1293 'name' => $peer_name,
1294 ];
1295 dbUpdate($update, 'pdb_ix_peers', '`pdb_ix_peers_id` = ?', [$tmp_peer['pdb_ix_peers_id']]);
1296 } else {
1297 $peer_insert = [
1298 'ix_id' => $ixid,
1299 'peer_id' => $peer->{'id'},
1300 'remote_asn' => $peer->{'asn'},
1301 'remote_ipaddr4' => $peer->{'ipaddr4'},
1302 'remote_ipaddr6' => $peer->{'ipaddr6'},
1303 'name' => $peer_name,
1304 'timestamp' => time(),
1305 ];
1306 $peer_keep[] = dbInsert($peer_insert, 'pdb_ix_peers');
1307 }
1308 }
1309 }
1310 }
1311
1312 // cleanup
1313 if (empty($peer_keep)) {
1314 dbDelete('pdb_ix_peers');
1315 } else {
1316 dbDelete('pdb_ix_peers', '`pdb_ix_peers_id` NOT IN ' . dbGenPlaceholders(count($peer_keep)), $peer_keep);
1317 }
1318 if (empty($ix_keep)) {
1319 dbDelete('pdb_ix');
1320 } else {
1321 dbDelete('pdb_ix', '`pdb_ix_id` NOT IN ' . dbGenPlaceholders(count($ix_keep)), $ix_keep);
1322 }
1323 } else {
1324 echo 'Cached PeeringDB data found.....' . PHP_EOL;
1325 }
1326 } else {
1327 echo 'Peering DB integration disabled' . PHP_EOL;
1328 }
1329}
1330
1331/**
1332 * Get an array of the schema files.
1333 * schema_version => full_file_name
1334 *
1335 * @return mixed
1336 */
1337function get_schema_list()
1338{
1339 // glob returns an array sorted by filename
1340 $files = glob(Config::get('install_dir') . '/sql-schema/*.sql');
1341
1342 // set the keys to the db schema version
1343 $files = array_reduce($files, function ($array, $file) {
1344 $array[(int) basename($file, '.sql')] = $file;
1345
1346 return $array;
1347 }, []);
1348
1349 ksort($files); // fix dbSchema 1000 order
1350
1351 return $files;
1352}
1353
1354/**
1355 * @param $device
1356 * @return int|null
1357 */
1358function get_device_oid_limit($device)
1359{
1360 // device takes priority
1361 if (! empty($device['attribs']['snmp_max_oid'])) {
1362 return $device['attribs']['snmp_max_oid'];
1363 }
1364
1365 // then os
1366 $os_max = Config::getOsSetting($device['os'], 'snmp_max_oid', 0);
1367 if ($os_max > 0) {
1368 return $os_max;
1369 }
1370
1371 // then global
1372 $global_max = Config::get('snmp.max_oid', 10);
1373
1374 return $global_max > 0 ? $global_max : 10;
1375}
1376
1377/**
1378 * If Distributed, create a lock, then purge the mysql table
1379 *
1380 * @param string $table
1381 * @param string $sql
1382 * @return int exit code
1383 */
1384function lock_and_purge($table, $sql)
1385{
1386 $purge_name = $table . '_purge';
1387 $lock = Cache::lock($purge_name, 86000);
1388 if ($lock->get()) {
1389 $purge_days = Config::get($purge_name);
1390
1391 $name = str_replace('_', ' ', ucfirst($table));
1392 if (is_numeric($purge_days)) {
1393 if (dbDelete($table, $sql, [$purge_days])) {
1394 echo "$name cleared for entries over $purge_days days\n";
1395 }
1396 }
1397 $lock->release();
1398
1399 return 0;
1400 }
1401
1402 return -1;
1403}
1404
1405/**
1406 * If Distributed, create a lock, then purge the mysql table according to the sql query
1407 *
1408 * @param string $table
1409 * @param string $sql
1410 * @param string $msg
1411 * @return int exit code
1412 */
1413function lock_and_purge_query($table, $sql, $msg)
1414{
1415 $purge_name = $table . '_purge';
1416
1417 $purge_duration = Config::get($purge_name);
1418 if (! (is_numeric($purge_duration) && $purge_duration > 0)) {
1419 return -2;
1420 }
1421 $lock = Cache::lock($purge_name, 86000);
1422 if ($lock->get()) {
1423 if (dbQuery($sql, [$purge_duration])) {
1424 printf($msg, $purge_duration);
1425 }
1426 $lock->release();
1427
1428 return 0;
1429 }
1430
1431 return -1;
1432}
1433
1434/**
1435 * Check if disk is valid to poll.
1436 * Settings: bad_disk_regexp
1437 *
1438 * @param array $disk
1439 * @param array $device
1440 * @return bool
1441 */
1442function is_disk_valid($disk, $device)
1443{
1444 foreach (Config::getCombined($device['os'], 'bad_disk_regexp') as $bir) {
1445 if (preg_match($bir . 'i', $disk['diskIODevice'])) {
1446 d_echo("Ignored Disk: {$disk['diskIODevice']} (matched: $bir)\n");
1447
1448 return false;
1449 }
1450 }
1451
1452 return true;
1453}
1454
1455/**
1456 * Take a BGP error code and subcode to return a string representation of it
1457 *
1458 * @params int code
1459 * @params int subcode
1460 *
1461 * @return string
1462 */
1463function describe_bgp_error_code($code, $subcode)
1464{
1465 // https://www.iana.org/assignments/bgp-parameters/bgp-parameters.xhtml#bgp-parameters-3
1466
1467 $message = 'Unknown';
1468
1469 $error_code_key = 'bgp.error_codes.' . $code;
1470 $error_subcode_key = 'bgp.error_subcodes.' . $code . '.' . $subcode;
1471
1472 $error_code_message = __($error_code_key);
1473 $error_subcode_message = __($error_subcode_key);
1474
1475 if ($error_subcode_message != $error_subcode_key) {
1476 $message = $error_code_message . ' - ' . $error_subcode_message;
1477 } elseif ($error_code_message != $error_code_key) {
1478 $message = $error_code_message;
1479 }
1480
1481 return $message;
1482}
1483librenms@svr-digi-librenms:~/includes$
1484