'; } function getImageTitle($device) { return $device['icon'] ? str_replace(['.svg', '.png'], '', $device['icon']) : $device['os']; } function getImageName($device, $use_database = true, $dir = 'images/os/') { return \LibreNMS\Util\Url::findOsImage($device['os'], $device['features'] ?? '', $use_database ? $device['icon'] : null, $dir); } function renamehost($id, $new, $source = 'console') { $host = gethostbyid($id); $new_rrd_dir = Rrd::dirFromHost($new); if (is_dir($new_rrd_dir)) { log_event("Renaming of $host failed due to existing RRD folder for $new", $id, 'system', 5); return "Renaming of $host failed due to existing RRD folder for $new\n"; } if (! is_dir($new_rrd_dir) && rename(Rrd::dirFromHost($host), $new_rrd_dir) === true) { dbUpdate(['hostname' => $new, 'ip' => null], 'devices', 'device_id=?', [$id]); log_event("Hostname changed -> $new ($source)", $id, 'system', 3); return ''; } log_event("Renaming of $host failed", $id, 'system', 5); return "Renaming of $host failed\n"; } function device_discovery_trigger($id) { if (App::runningInConsole() === false) { ignore_user_abort(true); set_time_limit(0); } $update = dbUpdate(['last_discovered' => null], 'devices', '`device_id` = ?', [$id]); if (! empty($update) || $update == '0') { $message = 'Device will be rediscovered'; } else { $message = 'Error rediscovering device'; } return ['status' => $update, 'message' => $message]; } function delete_device($id) { $device = DeviceCache::get($id); if (! $device->exists) { return 'No such device.'; } if ($device->delete()) { return "Removed device $device->hostname\n"; } return "Failed to remove device $device->hostname"; } function isDomainResolves($domain) { if (gethostbyname($domain) != $domain) { return true; } $records = dns_get_record($domain); // returns array or false return ! empty($records); } function match_network($nets, $ip, $first = false) { $return = false; if (! is_array($nets)) { $nets = [$nets]; } foreach ($nets as $net) { $rev = (preg_match("/^\!/", $net)) ? true : false; $net = preg_replace("/^\!/", '', $net); $ip_arr = explode('/', $net); $net_long = ip2long($ip_arr[0]); $x = ip2long($ip_arr[1]); $mask = long2ip($x) == $ip_arr[1] ? $x : 0xFFFFFFFF << (32 - $ip_arr[1]); $ip_long = ip2long($ip); if ($rev) { if (($ip_long & $mask) == ($net_long & $mask)) { return false; } } else { if (($ip_long & $mask) == ($net_long & $mask)) { $return = true; } if ($first && $return) { return true; } } } return $return; } // FIXME port to LibreNMS\Util\IPv6 class function snmp2ipv6($ipv6_snmp) { // Workaround stupid Microsoft bug in Windows 2008 -- this is fixed length! // < fenestro> "because whoever implemented this mib for Microsoft was ignorant of RFC 2578 section 7.7 (2)" $ipv6 = array_slice(explode('.', $ipv6_snmp), -16); $ipv6_2 = []; for ($i = 0; $i <= 15; $i++) { $ipv6[$i] = zeropad(dechex($ipv6[$i])); } for ($i = 0; $i <= 15; $i += 2) { $ipv6_2[] = $ipv6[$i] . $ipv6[$i + 1]; } return implode(':', $ipv6_2); } /** * Log events to the event table * * @param string $text message describing the event * @param array|int $device device array or device_id * @param string $type brief category for this event. Examples: sensor, state, stp, system, temperature, interface * @param int $severity 1: ok, 2: info, 3: notice, 4: warning, 5: critical, 0: unknown * @param int $reference the id of the referenced entity. Supported types: interface */ function log_event($text, $device = null, $type = null, $severity = 2, $reference = null) { // handle legacy device array if (is_array($device) && isset($device['device_id'])) { $device = $device['device_id']; } \App\Models\Eventlog::log($text, $device, $type, Severity::tryFrom((int) $severity) ?? Severity::Info, $reference); } function hex2str($hex) { $string = ''; for ($i = 0; $i < strlen($hex) - 1; $i += 2) { $string .= chr(hexdec(substr($hex, $i, 2))); } return $string; } // Convert an SNMP hex string to regular string function snmp_hexstring($hex) { return hex2str(str_replace(' ', '', str_replace(' 00', '', $hex))); } /** * Check if port is valid to poll. * Settings: empty_ifdescr, good_if, bad_if, bad_if_regexp, bad_ifname_regexp, bad_ifalias_regexp, bad_iftype, bad_ifoperstatus * * @param array $port * @param array $device * @return bool */ function is_port_valid($port, $device) { // check empty values first if (empty($port['ifDescr'])) { // If these are all empty, we are just going to show blank names in the ui if (empty($port['ifAlias']) && empty($port['ifName'])) { d_echo("ignored: empty ifDescr, ifAlias and ifName\n"); return false; } // ifDescr should not be empty unless it is explicitly allowed if (! Config::getOsSetting($device['os'], 'empty_ifdescr', Config::get('empty_ifdescr', false))) { d_echo("ignored: empty ifDescr\n"); return false; } } $ifDescr = $port['ifDescr']; $ifName = $port['ifName'] ?? ''; $ifAlias = $port['ifAlias'] ?? ''; $ifType = $port['ifType']; $ifOperStatus = $port['ifOperStatus'] ?? ''; if (str_i_contains($ifDescr, Config::getOsSetting($device['os'], 'good_if', Config::get('good_if')))) { return true; } foreach (Config::getCombined($device['os'], 'bad_if') as $bi) { if (str_i_contains($ifDescr, $bi)) { d_echo("ignored by ifDescr: $ifDescr (matched: $bi)\n"); return false; } } foreach (Config::getCombined($device['os'], 'bad_if_regexp') as $bir) { if (preg_match($bir . 'i', $ifDescr)) { d_echo("ignored by ifDescr: $ifDescr (matched: $bir)\n"); return false; } } foreach (Config::getCombined($device['os'], 'bad_ifname_regexp') as $bnr) { if (preg_match($bnr . 'i', $ifName)) { d_echo("ignored by ifName: $ifName (matched: $bnr)\n"); return false; } } foreach (Config::getCombined($device['os'], 'bad_ifalias_regexp') as $bar) { if (preg_match($bar . 'i', $ifAlias)) { d_echo("ignored by ifName: $ifAlias (matched: $bar)\n"); return false; } } foreach (Config::getCombined($device['os'], 'bad_iftype') as $bt) { if (Str::contains($ifType, $bt)) { d_echo("ignored by ifType: $ifType (matched: $bt )\n"); return false; } } foreach (Config::getCombined($device['os'], 'bad_ifoperstatus') as $bos) { if (Str::contains($ifOperStatus, $bos)) { d_echo("ignored by ifOperStatus: $ifOperStatus (matched: $bos)\n"); return false; } } return true; } /** * Try to fill in data for ifDescr, ifName, and ifAlias if devices do not provide them. * Will not fill ifAlias if the user has overridden it * Also trims the data * * @param array $port * @param array $device */ function port_fill_missing_and_trim(&$port, $device) { $port['ifDescr'] = isset($port['ifDescr']) ? trim($port['ifDescr']) : null; $port['ifAlias'] = isset($port['ifAlias']) ? trim($port['ifAlias']) : null; $port['ifName'] = isset($port['ifName']) ? trim($port['ifName']) : null; // When devices do not provide data, populate with other data if available if (! isset($port['ifDescr']) || $port['ifDescr'] == '') { $port['ifDescr'] = $port['ifName']; d_echo(' Using ifName as ifDescr'); } $attrib = DeviceCache::get($device['device_id'] ?? null)->getAttrib('ifName:' . $port['ifName']); if (! empty($attrib)) { // ifAlias overridden by user, don't update it unset($port['ifAlias']); d_echo(' ifAlias overriden by user'); } elseif (! isset($port['ifAlias']) || $port['ifAlias'] == '') { $port['ifAlias'] = $port['ifDescr']; d_echo(' Using ifDescr as ifAlias'); } if (! isset($port['ifName']) || $port['ifName'] == '') { $port['ifName'] = $port['ifDescr']; d_echo(' Using ifDescr as ifName'); } } function validate_device_id($id) { if (empty($id) || ! is_numeric($id)) { $return = false; } else { $device_id = dbFetchCell('SELECT `device_id` FROM `devices` WHERE `device_id` = ?', [$id]); if ($device_id == $id) { $return = true; } else { $return = false; } } return $return; } function convert_delay($delay) { if (preg_match('/(\d+)([mhd]?)/', $delay, $matches)) { $multipliers = [ 'm' => 60, 'h' => 3600, 'd' => 86400, ]; $multiplier = $multipliers[$matches[2]] ?? 1; return $matches[1] * $multiplier; } return $delay === '' ? 0 : 300; } function normalize_snmp_ip_address($data) { // $data is received from snmpwalk, can be ipv4 xxx.xxx.xxx.xxx or ipv6 xx:xx:...:xx (16 chunks) // ipv4 is returned unchanged, ipv6 is returned with one ':' removed out of two, like // xxxx:xxxx:...:xxxx (8 chuncks) return preg_replace('/([0-9a-fA-F]{2}):([0-9a-fA-F]{2})/', '\1\2', explode('%', $data, 2)[0]); } function fix_integer_value($value) { if ($value < 0) { $return = 4294967296 + $value; } else { $return = $value; } return $return; } /** * Checks if the $hostname provided exists in the DB already * * @param string $hostname The hostname to check for * @param string $sysName The sysName to check * @return bool true if hostname already exists * false if hostname doesn't exist */ function host_exists($hostname, $sysName = null) { $query = 'SELECT COUNT(*) FROM `devices` WHERE `hostname`=?'; $params = [$hostname]; if (! empty($sysName) && ! Config::get('allow_duplicate_sysName')) { $query .= ' OR `sysName`=?'; $params[] = $sysName; if (! empty(Config::get('mydomain'))) { $full_sysname = rtrim($sysName, '.') . '.' . Config::get('mydomain'); $query .= ' OR `sysName`=?'; $params[] = $full_sysname; } } return dbFetchCell($query, $params) > 0; } /** * Perform DNS lookup * * @param array $device Device array from database * @param string $type The type of record to lookup * @return string ip * **/ function dnslookup($device, $type = false, $return = false) { if (filter_var($device['hostname'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) == true || filter_var($device['hostname'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) == true) { return false; } if (empty($type)) { // We are going to use the transport to work out the record type if ($device['transport'] == 'udp6' || $device['transport'] == 'tcp6') { $type = DNS_AAAA; $return = 'ipv6'; } else { $type = DNS_A; $return = 'ip'; } } if (empty($return)) { return false; } $record = dns_get_record($device['hostname'], $type); return $record[0][$return] ?? null; }//end dnslookup /** * Create a new state index. Update translations if $states is given. * * For for backward compatibility: * Returns null if $states is empty, $state_name already exists, and contains state translations * * @param string $state_name the unique name for this state translation * @param array $states array of states, each must contain keys: descr, graph, value, generic * @return int|null */ function create_state_index($state_name, $states = []) { $state_index_id = dbFetchCell('SELECT `state_index_id` FROM state_indexes WHERE state_name = ? LIMIT 1', [$state_name]); if (! is_numeric($state_index_id)) { $state_index_id = dbInsert(['state_name' => $state_name], 'state_indexes'); // legacy code, return index so states are created if (empty($states)) { return $state_index_id; } } // check or synchronize states if (empty($states)) { $translations = dbFetchRows('SELECT * FROM `state_translations` WHERE `state_index_id` = ?', [$state_index_id]); if (count($translations) == 0) { // If we don't have any translations something has gone wrong so return the state_index_id so they get created. return $state_index_id; } } else { sync_sensor_states($state_index_id, $states); } return null; } /** * Synchronize the sensor state translations with the database * * @param int $state_index_id index of the state * @param array $states array of states, each must contain keys: descr, graph, value, generic */ function sync_sensor_states($state_index_id, $states) { $new_translations = array_reduce($states, function ($array, $state) use ($state_index_id) { $array[$state['value']] = [ 'state_index_id' => $state_index_id, 'state_descr' => $state['descr'], 'state_draw_graph' => $state['graph'], 'state_value' => $state['value'], 'state_generic_value' => $state['generic'], ]; return $array; }, []); $existing_translations = dbFetchRows( 'SELECT `state_index_id`,`state_descr`,`state_draw_graph`,`state_value`,`state_generic_value` FROM `state_translations` WHERE `state_index_id`=?', [$state_index_id] ); foreach ($existing_translations as $translation) { $value = $translation['state_value']; if (isset($new_translations[$value])) { if ($new_translations[$value] != $translation) { dbUpdate( $new_translations[$value], 'state_translations', '`state_index_id`=? AND `state_value`=?', [$state_index_id, $value] ); } // this translation is synchronized, it doesn't need to be inserted unset($new_translations[$value]); } else { dbDelete('state_translations', '`state_index_id`=? AND `state_value`=?', [$state_index_id, $value]); } } // insert any new translations dbBulkInsert($new_translations, 'state_translations'); } function create_sensor_to_state_index($device, $state_name, $index) { $sensor_entry = dbFetchRow('SELECT sensor_id FROM `sensors` WHERE `sensor_class` = ? AND `device_id` = ? AND `sensor_type` = ? AND `sensor_index` = ?', [ 'state', $device['device_id'], $state_name, $index, ]); $state_indexes_entry = dbFetchRow('SELECT state_index_id FROM `state_indexes` WHERE `state_name` = ?', [ $state_name, ]); if (! empty($sensor_entry['sensor_id']) && ! empty($state_indexes_entry['state_index_id'])) { $insert = [ 'sensor_id' => $sensor_entry['sensor_id'], 'state_index_id' => $state_indexes_entry['state_index_id'], ]; foreach ($insert as $key => $val_check) { if (! isset($val_check)) { unset($insert[$key]); } } dbInsert($insert, 'sensors_to_state_indexes'); } } function delta_to_bits($delta, $period) { return round($delta * 8 / $period, 2); } function report_this($message) { return '