1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/** |
4
|
|
|
* LibreNMS |
5
|
|
|
* |
6
|
|
|
* This file is part of LibreNMS. |
7
|
|
|
* |
8
|
|
|
* @copyright (C) 2006 - 2012 Adam Armstrong |
9
|
|
|
*/ |
10
|
|
|
|
11
|
|
|
use App\Models\Device; |
12
|
|
|
use Illuminate\Support\Str; |
13
|
|
|
use LibreNMS\Config; |
14
|
|
|
use LibreNMS\Exceptions\HostExistsException; |
15
|
|
|
use LibreNMS\Exceptions\HostIpExistsException; |
16
|
|
|
use LibreNMS\Exceptions\HostUnreachableException; |
17
|
|
|
use LibreNMS\Exceptions\HostUnreachablePingException; |
18
|
|
|
use LibreNMS\Exceptions\InvalidPortAssocModeException; |
19
|
|
|
use LibreNMS\Exceptions\SnmpVersionUnsupportedException; |
20
|
|
|
use LibreNMS\Fping; |
21
|
|
|
use LibreNMS\Modules\Core; |
22
|
|
|
use LibreNMS\Util\Debug; |
23
|
|
|
use LibreNMS\Util\IPv4; |
24
|
|
|
use LibreNMS\Util\IPv6; |
25
|
|
|
use PHPMailer\PHPMailer\PHPMailer; |
26
|
|
|
use Symfony\Component\Process\Process; |
27
|
|
|
|
28
|
|
|
function array_sort_by_column($array, $on, $order = SORT_ASC) |
29
|
|
|
{ |
30
|
|
|
$new_array = []; |
31
|
|
|
$sortable_array = []; |
32
|
|
|
|
33
|
|
|
if (count($array) > 0) { |
34
|
|
|
foreach ($array as $k => $v) { |
35
|
|
|
if (is_array($v)) { |
36
|
|
|
foreach ($v as $k2 => $v2) { |
37
|
|
|
if ($k2 == $on) { |
38
|
|
|
$sortable_array[$k] = $v2; |
39
|
|
|
} |
40
|
|
|
} |
41
|
|
|
} else { |
42
|
|
|
$sortable_array[$k] = $v; |
43
|
|
|
} |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
switch ($order) { |
47
|
|
|
case SORT_ASC: |
48
|
|
|
asort($sortable_array); |
49
|
|
|
break; |
50
|
|
|
case SORT_DESC: |
51
|
|
|
arsort($sortable_array); |
52
|
|
|
break; |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
foreach ($sortable_array as $k => $v) { |
56
|
|
|
$new_array[$k] = $array[$k]; |
57
|
|
|
} |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
return $new_array; |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
function only_alphanumeric($string) |
64
|
|
|
{ |
65
|
|
|
return preg_replace('/[^a-zA-Z0-9]/', '', $string); |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
/** |
69
|
|
|
* Parse cli discovery or poller modules and set config for this run |
70
|
|
|
* |
71
|
|
|
* @param string $type discovery or poller |
72
|
|
|
* @param array $options get_opts array (only m key is checked) |
73
|
|
|
* @return bool |
74
|
|
|
*/ |
75
|
|
|
function parse_modules($type, $options) |
76
|
|
|
{ |
77
|
|
|
$override = false; |
78
|
|
|
|
79
|
|
|
if ($options['m']) { |
80
|
|
|
Config::set("{$type}_modules", []); |
81
|
|
|
foreach (explode(',', $options['m']) as $module) { |
82
|
|
|
// parse submodules (only supported by some modules) |
83
|
|
|
if (Str::contains($module, '/')) { |
84
|
|
|
[$module, $submodule] = explode('/', $module, 2); |
85
|
|
|
$existing_submodules = Config::get("{$type}_submodules.$module", []); |
86
|
|
|
$existing_submodules[] = $submodule; |
87
|
|
|
Config::set("{$type}_submodules.$module", $existing_submodules); |
88
|
|
|
} |
89
|
|
|
|
90
|
|
|
$dir = $type == 'poller' ? 'polling' : $type; |
91
|
|
|
if (is_file("includes/$dir/$module.inc.php")) { |
92
|
|
|
Config::set("{$type}_modules.$module", 1); |
93
|
|
|
$override = true; |
94
|
|
|
} |
95
|
|
|
} |
96
|
|
|
|
97
|
|
|
// display selected modules |
98
|
|
|
$modules = array_map(function ($module) use ($type) { |
99
|
|
|
$submodules = Config::get("{$type}_submodules.$module"); |
100
|
|
|
|
101
|
|
|
return $module . ($submodules ? '(' . implode(',', $submodules) . ')' : ''); |
102
|
|
|
}, array_keys(Config::get("{$type}_modules", []))); |
103
|
|
|
|
104
|
|
|
d_echo("Override $type modules: " . implode(', ', $modules) . PHP_EOL); |
105
|
|
|
} |
106
|
|
|
|
107
|
|
|
return $override; |
108
|
|
|
} |
109
|
|
|
|
110
|
|
|
function logfile($string) |
111
|
|
|
{ |
112
|
|
|
$fd = fopen(Config::get('log_file'), 'a'); |
113
|
|
|
fputs($fd, $string . "\n"); |
114
|
|
|
fclose($fd); |
115
|
|
|
} |
116
|
|
|
|
117
|
|
|
/** |
118
|
|
|
* Check an array of regexes against a subject if any match, return true |
119
|
|
|
* |
120
|
|
|
* @param string $subject the string to match against |
121
|
|
|
* @param array|string $regexes an array of regexes or single regex to check |
122
|
|
|
* @return bool if any of the regexes matched, return true |
123
|
|
|
*/ |
124
|
|
|
function preg_match_any($subject, $regexes) |
125
|
|
|
{ |
126
|
|
|
foreach ((array) $regexes as $regex) { |
127
|
|
|
if (preg_match($regex, $subject)) { |
128
|
|
|
return true; |
129
|
|
|
} |
130
|
|
|
} |
131
|
|
|
|
132
|
|
|
return false; |
133
|
|
|
} |
134
|
|
|
|
135
|
|
|
/** |
136
|
|
|
* Perform comparison of two items based on give comparison method |
137
|
|
|
* Valid comparisons: =, !=, ==, !==, >=, <=, >, <, contains, starts, ends, regex |
138
|
|
|
* contains, starts, ends: $a haystack, $b needle(s) |
139
|
|
|
* regex: $a subject, $b regex |
140
|
|
|
* |
141
|
|
|
* @param mixed $a |
142
|
|
|
* @param mixed $b |
143
|
|
|
* @param string $comparison =, !=, ==, !== >=, <=, >, <, contains, starts, ends, regex |
144
|
|
|
* @return bool |
145
|
|
|
*/ |
146
|
|
|
function compare_var($a, $b, $comparison = '=') |
147
|
|
|
{ |
148
|
|
|
// handle PHP8 change to implicit casting |
149
|
|
|
if (is_numeric($a) || is_numeric($b)) { |
150
|
|
|
$a = cast_number($a); |
151
|
|
|
$b = is_array($b) ? $b : cast_number($b); |
152
|
|
|
} |
153
|
|
|
|
154
|
|
|
switch ($comparison) { |
155
|
|
|
case '=': |
156
|
|
|
return $a == $b; |
157
|
|
|
case '!=': |
158
|
|
|
return $a != $b; |
159
|
|
|
case '==': |
160
|
|
|
return $a === $b; |
161
|
|
|
case '!==': |
162
|
|
|
return $a !== $b; |
163
|
|
|
case '>=': |
164
|
|
|
return $a >= $b; |
165
|
|
|
case '<=': |
166
|
|
|
return $a <= $b; |
167
|
|
|
case '>': |
168
|
|
|
return $a > $b; |
169
|
|
|
case '<': |
170
|
|
|
return $a < $b; |
171
|
|
|
case 'contains': |
172
|
|
|
return Str::contains($a, $b); |
173
|
|
|
case 'not_contains': |
174
|
|
|
return ! Str::contains($a, $b); |
175
|
|
|
case 'starts': |
176
|
|
|
return Str::startsWith($a, $b); |
177
|
|
|
case 'not_starts': |
178
|
|
|
return ! Str::startsWith($a, $b); |
179
|
|
|
case 'ends': |
180
|
|
|
return Str::endsWith($a, $b); |
181
|
|
|
case 'not_ends': |
182
|
|
|
return ! Str::endsWith($a, $b); |
183
|
|
|
case 'regex': |
184
|
|
|
return (bool) preg_match($b, $a); |
185
|
|
|
case 'not regex': |
186
|
|
|
return ! ((bool) preg_match($b, $a)); |
187
|
|
|
case 'in_array': |
188
|
|
|
return in_array($a, $b); |
|
|
|
|
189
|
|
|
case 'not_in_array': |
190
|
|
|
return ! in_array($a, $b); |
191
|
|
|
case 'exists': |
192
|
|
|
return isset($a) == $b; |
193
|
|
|
default: |
194
|
|
|
return false; |
195
|
|
|
} |
196
|
|
|
} |
197
|
|
|
|
198
|
|
|
function percent_colour($perc) |
199
|
|
|
{ |
200
|
|
|
$r = min(255, 5 * ($perc - 25)); |
201
|
|
|
$b = max(0, 255 - (5 * ($perc + 25))); |
202
|
|
|
|
203
|
|
|
return sprintf('#%02x%02x%02x', $r, $b, $b); |
204
|
|
|
} |
205
|
|
|
|
206
|
|
|
/** |
207
|
|
|
* @param $device |
208
|
|
|
* @return string the logo image path for this device. Images are often wide, not square. |
209
|
|
|
*/ |
210
|
|
|
function getLogo($device) |
211
|
|
|
{ |
212
|
|
|
$img = getImageName($device, true, 'images/logos/'); |
213
|
|
|
if (! Str::startsWith($img, 'generic')) { |
214
|
|
|
return 'images/logos/' . $img; |
215
|
|
|
} |
216
|
|
|
|
217
|
|
|
return getIcon($device); |
218
|
|
|
} |
219
|
|
|
|
220
|
|
|
/** |
221
|
|
|
* @param array $device |
222
|
|
|
* @param string $class to apply to the image tag |
223
|
|
|
* @return string an image tag with the logo for this device. Images are often wide, not square. |
224
|
|
|
*/ |
225
|
|
|
function getLogoTag($device, $class = null) |
226
|
|
|
{ |
227
|
|
|
$tag = '<img src="' . url(getLogo($device)) . '" title="' . getImageTitle($device) . '"'; |
228
|
|
|
if (isset($class)) { |
229
|
|
|
$tag .= " class=\"$class\" "; |
230
|
|
|
} |
231
|
|
|
$tag .= ' />'; |
232
|
|
|
|
233
|
|
|
return $tag; |
234
|
|
|
} |
235
|
|
|
|
236
|
|
|
/** |
237
|
|
|
* @param $device |
238
|
|
|
* @return string the path to the icon image for this device. Close to square. |
239
|
|
|
*/ |
240
|
|
|
function getIcon($device) |
241
|
|
|
{ |
242
|
|
|
return 'images/os/' . getImageName($device); |
243
|
|
|
} |
244
|
|
|
|
245
|
|
|
/** |
246
|
|
|
* @param $device |
247
|
|
|
* @return string an image tag with the icon for this device. Close to square. |
248
|
|
|
*/ |
249
|
|
|
function getIconTag($device) |
250
|
|
|
{ |
251
|
|
|
return '<img src="' . getIcon($device) . '" title="' . getImageTitle($device) . '"/>'; |
252
|
|
|
} |
253
|
|
|
|
254
|
|
|
function getImageTitle($device) |
255
|
|
|
{ |
256
|
|
|
return $device['icon'] ? str_replace(['.svg', '.png'], '', $device['icon']) : $device['os']; |
257
|
|
|
} |
258
|
|
|
|
259
|
|
|
function getImageName($device, $use_database = true, $dir = 'images/os/') |
260
|
|
|
{ |
261
|
|
|
return \LibreNMS\Util\Url::findOsImage($device['os'], $device['features'], $use_database ? $device['icon'] : null, $dir); |
262
|
|
|
} |
263
|
|
|
|
264
|
|
|
function renamehost($id, $new, $source = 'console') |
265
|
|
|
{ |
266
|
|
|
$host = gethostbyid($id); |
267
|
|
|
|
268
|
|
|
if (! is_dir(Rrd::dirFromHost($new)) && rename(Rrd::dirFromHost($host), Rrd::dirFromHost($new)) === true) { |
269
|
|
|
dbUpdate(['hostname' => $new, 'ip' => null], 'devices', 'device_id=?', [$id]); |
270
|
|
|
log_event("Hostname changed -> $new ($source)", $id, 'system', 3); |
271
|
|
|
|
272
|
|
|
return ''; |
273
|
|
|
} |
274
|
|
|
|
275
|
|
|
log_event("Renaming of $host failed", $id, 'system', 5); |
276
|
|
|
|
277
|
|
|
return "Renaming of $host failed\n"; |
278
|
|
|
} |
279
|
|
|
|
280
|
|
|
function device_discovery_trigger($id) |
281
|
|
|
{ |
282
|
|
|
if (App::runningInConsole() === false) { |
283
|
|
|
ignore_user_abort(true); |
284
|
|
|
set_time_limit(0); |
285
|
|
|
} |
286
|
|
|
|
287
|
|
|
$update = dbUpdate(['last_discovered' => ['NULL']], 'devices', '`device_id` = ?', [$id]); |
288
|
|
|
if (! empty($update) || $update == '0') { |
289
|
|
|
$message = 'Device will be rediscovered'; |
290
|
|
|
} else { |
291
|
|
|
$message = 'Error rediscovering device'; |
292
|
|
|
} |
293
|
|
|
|
294
|
|
|
return ['status'=> $update, 'message' => $message]; |
295
|
|
|
} |
296
|
|
|
|
297
|
|
|
function delete_device($id) |
298
|
|
|
{ |
299
|
|
|
if (App::runningInConsole() === false) { |
300
|
|
|
ignore_user_abort(true); |
301
|
|
|
set_time_limit(0); |
302
|
|
|
} |
303
|
|
|
|
304
|
|
|
$ret = ''; |
305
|
|
|
|
306
|
|
|
$host = dbFetchCell('SELECT hostname FROM devices WHERE device_id = ?', [$id]); |
307
|
|
|
if (empty($host)) { |
308
|
|
|
return 'No such host.'; |
309
|
|
|
} |
310
|
|
|
|
311
|
|
|
// Remove IPv4/IPv6 addresses before removing ports as they depend on port_id |
312
|
|
|
dbQuery('DELETE `ipv4_addresses` FROM `ipv4_addresses` INNER JOIN `ports` ON `ports`.`port_id`=`ipv4_addresses`.`port_id` WHERE `device_id`=?', [$id]); |
313
|
|
|
dbQuery('DELETE `ipv6_addresses` FROM `ipv6_addresses` INNER JOIN `ports` ON `ports`.`port_id`=`ipv6_addresses`.`port_id` WHERE `device_id`=?', [$id]); |
314
|
|
|
|
315
|
|
|
//Remove IsisAdjacencies |
316
|
|
|
\App\Models\IsisAdjacency::where('device_id', $id)->delete(); |
317
|
|
|
|
318
|
|
|
//Remove Outages |
319
|
|
|
\App\Models\Availability::where('device_id', $id)->delete(); |
320
|
|
|
\App\Models\DeviceOutage::where('device_id', $id)->delete(); |
321
|
|
|
|
322
|
|
|
\App\Models\Port::where('device_id', $id) |
323
|
|
|
->with('device') |
324
|
|
|
->select(['port_id', 'device_id', 'ifIndex', 'ifName', 'ifAlias', 'ifDescr']) |
325
|
|
|
->chunk(100, function ($ports) use (&$ret) { |
326
|
|
|
foreach ($ports as $port) { |
327
|
|
|
$port->delete(); |
328
|
|
|
$ret .= "Removed interface $port->port_id (" . $port->getLabel() . ")\n"; |
329
|
|
|
} |
330
|
|
|
}); |
331
|
|
|
|
332
|
|
|
// Remove sensors manually due to constraints |
333
|
|
|
foreach (dbFetchRows('SELECT * FROM `sensors` WHERE `device_id` = ?', [$id]) as $sensor) { |
334
|
|
|
$sensor_id = $sensor['sensor_id']; |
335
|
|
|
dbDelete('sensors_to_state_indexes', '`sensor_id` = ?', [$sensor_id]); |
336
|
|
|
} |
337
|
|
|
$fields = ['device_id', 'host']; |
338
|
|
|
|
339
|
|
|
$db_name = dbFetchCell('SELECT DATABASE()'); |
340
|
|
|
foreach ($fields as $field) { |
341
|
|
|
foreach (dbFetch('SELECT TABLE_NAME FROM information_schema.columns WHERE table_schema = ? AND column_name = ?', [$db_name, $field]) as $table) { |
342
|
|
|
$table = $table['TABLE_NAME']; |
343
|
|
|
$entries = (int) dbDelete($table, "`$field` = ?", [$id]); |
344
|
|
|
if ($entries > 0 && Debug::isEnabled()) { |
345
|
|
|
$ret .= "$field@$table = #$entries\n"; |
346
|
|
|
} |
347
|
|
|
} |
348
|
|
|
} |
349
|
|
|
|
350
|
|
|
$ex = shell_exec("bash -c '( [ ! -d " . trim(Rrd::dirFromHost($host)) . ' ] || rm -vrf ' . trim(Rrd::dirFromHost($host)) . " 2>&1 ) && echo -n OK'"); |
351
|
|
|
$tmp = explode("\n", $ex); |
352
|
|
|
if ($tmp[sizeof($tmp) - 1] != 'OK') { |
353
|
|
|
$ret .= "Could not remove files:\n$ex\n"; |
354
|
|
|
} |
355
|
|
|
|
356
|
|
|
$ret .= "Removed device $host\n"; |
357
|
|
|
log_event("Device $host has been removed", 0, 'system', 3); |
358
|
|
|
oxidized_reload_nodes(); |
359
|
|
|
|
360
|
|
|
return $ret; |
361
|
|
|
} |
362
|
|
|
|
363
|
|
|
/** |
364
|
|
|
* Add a device to LibreNMS |
365
|
|
|
* |
366
|
|
|
* @param string $host dns name or ip address |
367
|
|
|
* @param string $snmp_version If this is empty, try v2c,v3,v1. Otherwise, use this specific version. |
368
|
|
|
* @param int $port the port to connect to for snmp |
369
|
|
|
* @param string $transport udp or tcp |
370
|
|
|
* @param string $poller_group the poller group this device will belong to |
371
|
|
|
* @param bool $force_add add even if the device isn't reachable |
372
|
|
|
* @param string $port_assoc_mode snmp field to use to determine unique ports |
373
|
|
|
* @param array $additional an array with additional parameters to take into consideration when adding devices |
374
|
|
|
* @return int returns the device_id of the added device |
375
|
|
|
* |
376
|
|
|
* @throws HostExistsException This hostname already exists |
377
|
|
|
* @throws HostIpExistsException We already have a host with this IP |
378
|
|
|
* @throws HostUnreachableException We could not reach this device is some way |
379
|
|
|
* @throws HostUnreachablePingException We could not ping the device |
380
|
|
|
* @throws InvalidPortAssocModeException The given port association mode was invalid |
381
|
|
|
* @throws SnmpVersionUnsupportedException The given snmp version was invalid |
382
|
|
|
*/ |
383
|
|
|
function addHost($host, $snmp_version = '', $port = 161, $transport = 'udp', $poller_group = '0', $force_add = false, $port_assoc_mode = 'ifIndex', $additional = []) |
384
|
|
|
{ |
385
|
|
|
// Test Database Exists |
386
|
|
|
if (host_exists($host)) { |
387
|
|
|
throw new HostExistsException("Already have host $host"); |
388
|
|
|
} |
389
|
|
|
|
390
|
|
|
// Valid port assoc mode |
391
|
|
|
if (! in_array($port_assoc_mode, get_port_assoc_modes())) { |
392
|
|
|
throw new InvalidPortAssocModeException("Invalid port association_mode '$port_assoc_mode'. Valid modes are: " . join(', ', get_port_assoc_modes())); |
393
|
|
|
} |
394
|
|
|
|
395
|
|
|
// check if we have the host by IP |
396
|
|
|
$overwrite_ip = null; |
397
|
|
|
if (! empty($additional['overwrite_ip'])) { |
398
|
|
|
$overwrite_ip = $additional['overwrite_ip']; |
399
|
|
|
$ip = $overwrite_ip; |
400
|
|
|
} elseif (Config::get('addhost_alwayscheckip') === true) { |
401
|
|
|
$ip = gethostbyname($host); |
402
|
|
|
} else { |
403
|
|
|
$ip = $host; |
404
|
|
|
} |
405
|
|
|
if ($force_add !== true && $device = device_has_ip($ip)) { |
406
|
|
|
$message = "Cannot add $host, already have device with this IP $ip"; |
407
|
|
|
if ($ip != $device->hostname) { |
408
|
|
|
$message .= " ($device->hostname)"; |
409
|
|
|
} |
410
|
|
|
$message .= '. You may force add to ignore this.'; |
411
|
|
|
throw new HostIpExistsException($message); |
412
|
|
|
} |
413
|
|
|
|
414
|
|
|
// Test reachability |
415
|
|
|
if (! $force_add) { |
416
|
|
|
$address_family = snmpTransportToAddressFamily($transport); |
417
|
|
|
$ping_result = isPingable($ip, $address_family); |
418
|
|
|
if (! $ping_result['result']) { |
419
|
|
|
throw new HostUnreachablePingException("Could not ping $host"); |
420
|
|
|
} |
421
|
|
|
} |
422
|
|
|
|
423
|
|
|
// if $snmpver isn't set, try each version of snmp |
424
|
|
|
if (empty($snmp_version)) { |
425
|
|
|
$snmpvers = Config::get('snmp.version'); |
426
|
|
|
} else { |
427
|
|
|
$snmpvers = [$snmp_version]; |
428
|
|
|
} |
429
|
|
|
|
430
|
|
|
if (isset($additional['snmp_disable']) && $additional['snmp_disable'] == 1) { |
431
|
|
|
return createHost($host, '', $snmp_version, $port, $transport, [], $poller_group, 1, true, $overwrite_ip, $additional); |
432
|
|
|
} |
433
|
|
|
$host_unreachable_exception = new HostUnreachableException("Could not connect to $host, please check the snmp details and snmp reachability"); |
434
|
|
|
// try different snmp variables to add the device |
435
|
|
|
foreach ($snmpvers as $snmpver) { |
436
|
|
|
if ($snmpver === 'v3') { |
437
|
|
|
// Try each set of parameters from config |
438
|
|
|
foreach (Config::get('snmp.v3') as $v3) { |
439
|
|
|
$device = deviceArray($host, null, $snmpver, $port, $transport, $v3, $port_assoc_mode, $overwrite_ip); |
440
|
|
|
if ($force_add === true || isSNMPable($device)) { |
441
|
|
|
return createHost($host, null, $snmpver, $port, $transport, $v3, $poller_group, $port_assoc_mode, $force_add, $overwrite_ip); |
442
|
|
|
} else { |
443
|
|
|
$host_unreachable_exception->addReason("SNMP $snmpver: No reply with credentials " . $v3['authname'] . '/' . $v3['authlevel']); |
444
|
|
|
} |
445
|
|
|
} |
446
|
|
|
} elseif ($snmpver === 'v2c' || $snmpver === 'v1') { |
447
|
|
|
// try each community from config |
448
|
|
|
foreach (Config::get('snmp.community') as $community) { |
449
|
|
|
$device = deviceArray($host, $community, $snmpver, $port, $transport, null, $port_assoc_mode, $overwrite_ip); |
450
|
|
|
|
451
|
|
|
if ($force_add === true || isSNMPable($device)) { |
452
|
|
|
return createHost($host, $community, $snmpver, $port, $transport, [], $poller_group, $port_assoc_mode, $force_add, $overwrite_ip); |
453
|
|
|
} else { |
454
|
|
|
$host_unreachable_exception->addReason("SNMP $snmpver: No reply with community $community"); |
455
|
|
|
} |
456
|
|
|
} |
457
|
|
|
} else { |
458
|
|
|
throw new SnmpVersionUnsupportedException("Unsupported SNMP Version \"$snmpver\", must be v1, v2c, or v3"); |
459
|
|
|
} |
460
|
|
|
} |
461
|
|
|
if (isset($additional['ping_fallback']) && $additional['ping_fallback'] == 1) { |
462
|
|
|
$additional['snmp_disable'] = 1; |
463
|
|
|
$additional['os'] = 'ping'; |
464
|
|
|
|
465
|
|
|
return createHost($host, '', $snmp_version, $port, $transport, [], $poller_group, 1, true, $overwrite_ip, $additional); |
466
|
|
|
} |
467
|
|
|
throw $host_unreachable_exception; |
468
|
|
|
} |
469
|
|
|
|
470
|
|
|
function deviceArray($host, $community, $snmpver, $port = 161, $transport = 'udp', $v3 = [], $port_assoc_mode = 'ifIndex', $overwrite_ip = null) |
471
|
|
|
{ |
472
|
|
|
$device = []; |
473
|
|
|
$device['hostname'] = $host; |
474
|
|
|
$device['overwrite_ip'] = $overwrite_ip; |
475
|
|
|
$device['port'] = $port; |
476
|
|
|
$device['transport'] = $transport; |
477
|
|
|
|
478
|
|
|
/* Get port_assoc_mode id if neccessary |
479
|
|
|
* We can work with names of IDs here */ |
480
|
|
|
if (! is_int($port_assoc_mode)) { |
481
|
|
|
$port_assoc_mode = get_port_assoc_mode_id($port_assoc_mode); |
482
|
|
|
} |
483
|
|
|
$device['port_association_mode'] = $port_assoc_mode; |
484
|
|
|
|
485
|
|
|
$device['snmpver'] = $snmpver; |
486
|
|
|
if ($snmpver === 'v2c' or $snmpver === 'v1') { |
487
|
|
|
$device['community'] = $community; |
488
|
|
|
} elseif ($snmpver === 'v3') { |
489
|
|
|
$device['authlevel'] = $v3['authlevel']; |
490
|
|
|
$device['authname'] = $v3['authname']; |
491
|
|
|
$device['authpass'] = $v3['authpass']; |
492
|
|
|
$device['authalgo'] = $v3['authalgo']; |
493
|
|
|
$device['cryptopass'] = $v3['cryptopass']; |
494
|
|
|
$device['cryptoalgo'] = $v3['cryptoalgo']; |
495
|
|
|
} |
496
|
|
|
|
497
|
|
|
return $device; |
498
|
|
|
}//end deviceArray() |
499
|
|
|
|
500
|
|
|
function isSNMPable($device) |
501
|
|
|
{ |
502
|
|
|
$pos = snmp_check($device); |
503
|
|
|
if ($pos === true) { |
504
|
|
|
return true; |
505
|
|
|
} else { |
506
|
|
|
$pos = snmp_get($device, 'sysObjectID.0', '-Oqv', 'SNMPv2-MIB'); |
507
|
|
|
if ($pos === '' || $pos === false) { |
508
|
|
|
return false; |
509
|
|
|
} else { |
510
|
|
|
return true; |
511
|
|
|
} |
512
|
|
|
} |
513
|
|
|
} |
514
|
|
|
|
515
|
|
|
/** |
516
|
|
|
* Check if the given host responds to ICMP echo requests ("pings"). |
517
|
|
|
* |
518
|
|
|
* @param string $hostname The hostname or IP address to send ping requests to. |
519
|
|
|
* @param string $address_family The address family ('ipv4' or 'ipv6') to use. Defaults to IPv4. |
520
|
|
|
* Will *not* be autodetected for IP addresses, so it has to be set to 'ipv6' when pinging an IPv6 address or an IPv6-only host. |
521
|
|
|
* @param array $attribs The device attributes |
522
|
|
|
* @return array 'result' => bool pingable, 'last_ping_timetaken' => int time for last ping, 'db' => fping results |
523
|
|
|
*/ |
524
|
|
|
function isPingable($hostname, $address_family = 'ipv4', $attribs = []) |
525
|
|
|
{ |
526
|
|
|
if (can_ping_device($attribs) !== true) { |
527
|
|
|
return [ |
528
|
|
|
'result' => true, |
529
|
|
|
'last_ping_timetaken' => 0, |
530
|
|
|
]; |
531
|
|
|
} |
532
|
|
|
|
533
|
|
|
$status = app()->make(Fping::class)->ping( |
534
|
|
|
$hostname, |
535
|
|
|
Config::get('fping_options.count', 3), |
536
|
|
|
Config::get('fping_options.interval', 500), |
537
|
|
|
Config::get('fping_options.timeout', 500), |
538
|
|
|
$address_family |
539
|
|
|
); |
540
|
|
|
|
541
|
|
|
if ($status['dup'] > 0) { |
542
|
|
|
Log::event('Duplicate ICMP response detected! This could indicate a network issue.', getidbyname($hostname), 'icmp', 4); |
543
|
|
|
$status['exitcode'] = 0; // when duplicate is detected fping returns 1. The device is up, but there is another issue. Clue admins in with above event. |
544
|
|
|
} |
545
|
|
|
|
546
|
|
|
return [ |
547
|
|
|
'result' => ($status['exitcode'] == 0 && $status['loss'] < 100), |
548
|
|
|
'last_ping_timetaken' => $status['avg'], |
549
|
|
|
'db' => array_intersect_key($status, array_flip(['xmt', 'rcv', 'loss', 'min', 'max', 'avg'])), |
550
|
|
|
]; |
551
|
|
|
} |
552
|
|
|
|
553
|
|
|
function getpollergroup($poller_group = '0') |
554
|
|
|
{ |
555
|
|
|
//Is poller group an integer |
556
|
|
|
if (is_int($poller_group) || ctype_digit($poller_group)) { |
557
|
|
|
return $poller_group; |
558
|
|
|
} else { |
559
|
|
|
//Check if it contains a comma |
560
|
|
|
if (strpos($poller_group, ',') !== false) { |
561
|
|
|
//If it has a comma use the first element as the poller group |
562
|
|
|
$poller_group_array = explode(',', $poller_group); |
563
|
|
|
|
564
|
|
|
return getpollergroup($poller_group_array[0]); |
565
|
|
|
} else { |
566
|
|
|
if (Config::get('distributed_poller_group')) { |
567
|
|
|
//If not use the poller's group from the config |
568
|
|
|
return getpollergroup(Config::get('distributed_poller_group')); |
569
|
|
|
} else { |
570
|
|
|
//If all else fails use default |
571
|
|
|
return '0'; |
572
|
|
|
} |
573
|
|
|
} |
574
|
|
|
} |
575
|
|
|
} |
576
|
|
|
|
577
|
|
|
/** |
578
|
|
|
* Add a host to the database |
579
|
|
|
* |
580
|
|
|
* @param string $host The IP or hostname to add |
581
|
|
|
* @param string $community The snmp community |
582
|
|
|
* @param string $snmpver snmp version: v1 | v2c | v3 |
583
|
|
|
* @param int $port SNMP port number |
584
|
|
|
* @param string $transport SNMP transport: udp | udp6 | udp | tcp6 |
585
|
|
|
* @param array $v3 SNMPv3 settings required array keys: authlevel, authname, authpass, authalgo, cryptopass, cryptoalgo |
586
|
|
|
* @param int $poller_group distributed poller group to assign this host to |
587
|
|
|
* @param string $port_assoc_mode field to use to identify ports: ifIndex, ifName, ifDescr, ifAlias |
588
|
|
|
* @param bool $force_add Do not detect the host os |
589
|
|
|
* @param array $additional an array with additional parameters to take into consideration when adding devices |
590
|
|
|
* @return int the id of the added host |
591
|
|
|
* |
592
|
|
|
* @throws HostExistsException Throws this exception if the host already exists |
593
|
|
|
* @throws Exception Throws this exception if insertion into the database fails |
594
|
|
|
*/ |
595
|
|
|
function createHost( |
596
|
|
|
$host, |
597
|
|
|
$community, |
598
|
|
|
$snmpver, |
599
|
|
|
$port = 161, |
600
|
|
|
$transport = 'udp', |
601
|
|
|
$v3 = [], |
602
|
|
|
$poller_group = 0, |
603
|
|
|
$port_assoc_mode = 'ifIndex', |
604
|
|
|
$force_add = false, |
605
|
|
|
$overwrite_ip = null, |
606
|
|
|
$additional = [] |
607
|
|
|
) { |
608
|
|
|
$host = trim(strtolower($host)); |
609
|
|
|
|
610
|
|
|
$poller_group = getpollergroup($poller_group); |
611
|
|
|
|
612
|
|
|
/* Get port_assoc_mode id if necessary |
613
|
|
|
* We can work with names of IDs here */ |
614
|
|
|
if (! is_int($port_assoc_mode)) { |
615
|
|
|
$port_assoc_mode = get_port_assoc_mode_id($port_assoc_mode); |
616
|
|
|
} |
617
|
|
|
|
618
|
|
|
$device = [ |
619
|
|
|
'hostname' => $host, |
620
|
|
|
'overwrite_ip' => $overwrite_ip, |
621
|
|
|
'sysName' => $additional['sysName'] ?? $host, |
622
|
|
|
'os' => $additional['os'] ?? 'generic', |
623
|
|
|
'hardware' => $additional['hardware'] ?? null, |
624
|
|
|
'community' => $community, |
625
|
|
|
'port' => $port, |
626
|
|
|
'transport' => $transport, |
627
|
|
|
'status' => '1', |
628
|
|
|
'snmpver' => $snmpver, |
629
|
|
|
'poller_group' => $poller_group, |
630
|
|
|
'status_reason' => '', |
631
|
|
|
'port_association_mode' => $port_assoc_mode, |
632
|
|
|
'snmp_disable' => $additional['snmp_disable'] ?? 0, |
633
|
|
|
]; |
634
|
|
|
|
635
|
|
|
$device = array_merge($device, $v3); // merge v3 settings |
636
|
|
|
|
637
|
|
|
if ($force_add !== true) { |
638
|
|
|
$device['os'] = Core::detectOS($device); |
639
|
|
|
|
640
|
|
|
$snmphost = snmp_get($device, 'sysName.0', '-Oqv', 'SNMPv2-MIB'); |
641
|
|
|
if (host_exists($host, $snmphost)) { |
642
|
|
|
throw new HostExistsException("Already have host $host ($snmphost) due to duplicate sysName"); |
643
|
|
|
} |
644
|
|
|
} |
645
|
|
|
|
646
|
|
|
$device_id = dbInsert($device, 'devices'); |
647
|
|
|
if ($device_id) { |
648
|
|
|
return $device_id; |
649
|
|
|
} |
650
|
|
|
|
651
|
|
|
throw new \Exception('Failed to add host to the database, please run ./validate.php'); |
652
|
|
|
} |
653
|
|
|
|
654
|
|
|
function isDomainResolves($domain) |
655
|
|
|
{ |
656
|
|
|
if (gethostbyname($domain) != $domain) { |
657
|
|
|
return true; |
658
|
|
|
} |
659
|
|
|
|
660
|
|
|
$records = dns_get_record($domain); // returns array or false |
661
|
|
|
|
662
|
|
|
return ! empty($records); |
663
|
|
|
} |
664
|
|
|
|
665
|
|
|
function match_network($nets, $ip, $first = false) |
666
|
|
|
{ |
667
|
|
|
$return = false; |
668
|
|
|
if (! is_array($nets)) { |
669
|
|
|
$nets = [$nets]; |
670
|
|
|
} |
671
|
|
|
foreach ($nets as $net) { |
672
|
|
|
$rev = (preg_match("/^\!/", $net)) ? true : false; |
673
|
|
|
$net = preg_replace("/^\!/", '', $net); |
674
|
|
|
$ip_arr = explode('/', $net); |
675
|
|
|
$net_long = ip2long($ip_arr[0]); |
676
|
|
|
$x = ip2long($ip_arr[1]); |
677
|
|
|
$mask = long2ip($x) == $ip_arr[1] ? $x : 0xFFFFFFFF << (32 - $ip_arr[1]); |
678
|
|
|
$ip_long = ip2long($ip); |
679
|
|
|
if ($rev) { |
680
|
|
|
if (($ip_long & $mask) == ($net_long & $mask)) { |
681
|
|
|
return false; |
682
|
|
|
} |
683
|
|
|
} else { |
684
|
|
|
if (($ip_long & $mask) == ($net_long & $mask)) { |
685
|
|
|
$return = true; |
686
|
|
|
} |
687
|
|
|
if ($first && $return) { |
688
|
|
|
return true; |
689
|
|
|
} |
690
|
|
|
} |
691
|
|
|
} |
692
|
|
|
|
693
|
|
|
return $return; |
694
|
|
|
} |
695
|
|
|
|
696
|
|
|
// FIXME port to LibreNMS\Util\IPv6 class |
697
|
|
|
function snmp2ipv6($ipv6_snmp) |
698
|
|
|
{ |
699
|
|
|
// Workaround stupid Microsoft bug in Windows 2008 -- this is fixed length! |
700
|
|
|
// < fenestro> "because whoever implemented this mib for Microsoft was ignorant of RFC 2578 section 7.7 (2)" |
701
|
|
|
$ipv6 = array_slice(explode('.', $ipv6_snmp), -16); |
702
|
|
|
$ipv6_2 = []; |
703
|
|
|
|
704
|
|
|
for ($i = 0; $i <= 15; $i++) { |
705
|
|
|
$ipv6[$i] = zeropad(dechex($ipv6[$i])); |
706
|
|
|
} |
707
|
|
|
for ($i = 0; $i <= 15; $i += 2) { |
708
|
|
|
$ipv6_2[] = $ipv6[$i] . $ipv6[$i + 1]; |
709
|
|
|
} |
710
|
|
|
|
711
|
|
|
return implode(':', $ipv6_2); |
712
|
|
|
} |
713
|
|
|
|
714
|
|
|
function get_astext($asn) |
715
|
|
|
{ |
716
|
|
|
global $cache; |
717
|
|
|
|
718
|
|
|
if (Config::has("astext.$asn")) { |
719
|
|
|
return Config::get("astext.$asn"); |
720
|
|
|
} |
721
|
|
|
|
722
|
|
|
if (isset($cache['astext'][$asn])) { |
723
|
|
|
return $cache['astext'][$asn]; |
724
|
|
|
} |
725
|
|
|
|
726
|
|
|
$result = @dns_get_record("AS$asn.asn.cymru.com", DNS_TXT); |
727
|
|
|
if (! empty($result[0]['txt'])) { |
728
|
|
|
$txt = explode('|', $result[0]['txt']); |
729
|
|
|
$result = trim($txt[4], ' "'); |
730
|
|
|
$cache['astext'][$asn] = $result; |
731
|
|
|
|
732
|
|
|
return $result; |
733
|
|
|
} |
734
|
|
|
|
735
|
|
|
return ''; |
736
|
|
|
} |
737
|
|
|
|
738
|
|
|
/** |
739
|
|
|
* Log events to the event table |
740
|
|
|
* |
741
|
|
|
* @param string $text message describing the event |
742
|
|
|
* @param array|int $device device array or device_id |
743
|
|
|
* @param string $type brief category for this event. Examples: sensor, state, stp, system, temperature, interface |
744
|
|
|
* @param int $severity 1: ok, 2: info, 3: notice, 4: warning, 5: critical, 0: unknown |
745
|
|
|
* @param int $reference the id of the referenced entity. Supported types: interface |
746
|
|
|
*/ |
747
|
|
|
function log_event($text, $device = null, $type = null, $severity = 2, $reference = null) |
748
|
|
|
{ |
749
|
|
|
// handle legacy device array |
750
|
|
|
if (is_array($device) && isset($device['device_id'])) { |
751
|
|
|
$device = $device['device_id']; |
752
|
|
|
} |
753
|
|
|
|
754
|
|
|
Log::event($text, $device, $type, $severity, $reference); |
755
|
|
|
} |
756
|
|
|
|
757
|
|
|
// Parse string with emails. Return array with email (as key) and name (as value) |
758
|
|
|
function parse_email($emails) |
759
|
|
|
{ |
760
|
|
|
$result = []; |
761
|
|
|
$regex = '/^[\"\']?([^\"\']+)[\"\']?\s{0,}<([^@]+@[^>]+)>$/'; |
762
|
|
|
if (is_string($emails)) { |
763
|
|
|
$emails = preg_split('/[,;]\s{0,}/', $emails); |
764
|
|
|
foreach ($emails as $email) { |
765
|
|
|
if (preg_match($regex, $email, $out, PREG_OFFSET_CAPTURE)) { |
766
|
|
|
$result[$out[2][0]] = $out[1][0]; |
767
|
|
|
} else { |
768
|
|
|
if (strpos($email, '@')) { |
769
|
|
|
$from_name = Config::get('email_user'); |
770
|
|
|
$result[$email] = $from_name; |
771
|
|
|
} |
772
|
|
|
} |
773
|
|
|
} |
774
|
|
|
} else { |
775
|
|
|
// Return FALSE if input not string |
776
|
|
|
return false; |
777
|
|
|
} |
778
|
|
|
|
779
|
|
|
return $result; |
780
|
|
|
} |
781
|
|
|
|
782
|
|
|
function send_mail($emails, $subject, $message, $html = false) |
783
|
|
|
{ |
784
|
|
|
if (is_array($emails) || ($emails = parse_email($emails))) { |
785
|
|
|
d_echo("Attempting to email $subject to: " . implode('; ', array_keys($emails)) . PHP_EOL); |
786
|
|
|
$mail = new PHPMailer(true); |
787
|
|
|
try { |
788
|
|
|
$mail->Hostname = php_uname('n'); |
789
|
|
|
|
790
|
|
|
foreach (parse_email(Config::get('email_from')) as $from => $from_name) { |
791
|
|
|
$mail->setFrom($from, $from_name); |
792
|
|
|
} |
793
|
|
|
foreach ($emails as $email => $email_name) { |
794
|
|
|
$mail->addAddress($email, $email_name); |
795
|
|
|
} |
796
|
|
|
$mail->Subject = $subject; |
797
|
|
|
$mail->XMailer = Config::get('project_name'); |
798
|
|
|
$mail->CharSet = 'utf-8'; |
799
|
|
|
$mail->WordWrap = 76; |
800
|
|
|
$mail->Body = $message; |
801
|
|
|
if ($html) { |
802
|
|
|
$mail->isHTML(true); |
803
|
|
|
} |
804
|
|
|
switch (strtolower(trim(Config::get('email_backend')))) { |
805
|
|
|
case 'sendmail': |
806
|
|
|
$mail->Mailer = 'sendmail'; |
807
|
|
|
$mail->Sendmail = Config::get('email_sendmail_path'); |
808
|
|
|
break; |
809
|
|
|
case 'smtp': |
810
|
|
|
$mail->isSMTP(); |
811
|
|
|
$mail->Host = Config::get('email_smtp_host'); |
812
|
|
|
$mail->Timeout = Config::get('email_smtp_timeout'); |
813
|
|
|
$mail->SMTPAuth = Config::get('email_smtp_auth'); |
814
|
|
|
$mail->SMTPSecure = Config::get('email_smtp_secure'); |
815
|
|
|
$mail->Port = Config::get('email_smtp_port'); |
816
|
|
|
$mail->Username = Config::get('email_smtp_username'); |
817
|
|
|
$mail->Password = Config::get('email_smtp_password'); |
818
|
|
|
$mail->SMTPAutoTLS = Config::get('email_auto_tls'); |
819
|
|
|
$mail->SMTPDebug = false; |
820
|
|
|
break; |
821
|
|
|
default: |
822
|
|
|
$mail->Mailer = 'mail'; |
823
|
|
|
break; |
824
|
|
|
} |
825
|
|
|
$mail->send(); |
826
|
|
|
|
827
|
|
|
return true; |
828
|
|
|
} catch (\PHPMailer\PHPMailer\Exception $e) { |
829
|
|
|
return $e->errorMessage(); |
830
|
|
|
} catch (Exception $e) { |
831
|
|
|
return $e->getMessage(); |
832
|
|
|
} |
833
|
|
|
} |
834
|
|
|
|
835
|
|
|
return 'No contacts found'; |
836
|
|
|
} |
837
|
|
|
|
838
|
|
|
function hex2str($hex) |
839
|
|
|
{ |
840
|
|
|
$string = ''; |
841
|
|
|
|
842
|
|
|
for ($i = 0; $i < strlen($hex) - 1; $i += 2) { |
843
|
|
|
$string .= chr(hexdec(substr($hex, $i, 2))); |
844
|
|
|
} |
845
|
|
|
|
846
|
|
|
return $string; |
847
|
|
|
} |
848
|
|
|
|
849
|
|
|
// Convert an SNMP hex string to regular string |
850
|
|
|
function snmp_hexstring($hex) |
851
|
|
|
{ |
852
|
|
|
return hex2str(str_replace(' ', '', str_replace(' 00', '', $hex))); |
853
|
|
|
} |
854
|
|
|
|
855
|
|
|
// Check if the supplied string is an SNMP hex string |
856
|
|
|
function isHexString($str) |
857
|
|
|
{ |
858
|
|
|
return (bool) preg_match('/^[a-f0-9][a-f0-9]( [a-f0-9][a-f0-9])*$/is', trim($str)); |
859
|
|
|
} |
860
|
|
|
|
861
|
|
|
// Include all .inc.php files in $dir |
862
|
|
|
function include_dir($dir, $regex = '') |
863
|
|
|
{ |
864
|
|
|
global $device, $valid; |
865
|
|
|
|
866
|
|
|
if ($regex == '') { |
867
|
|
|
$regex = "/\.inc\.php$/"; |
868
|
|
|
} |
869
|
|
|
|
870
|
|
|
if ($handle = opendir(Config::get('install_dir') . '/' . $dir)) { |
871
|
|
|
while (false !== ($file = readdir($handle))) { |
872
|
|
|
if (filetype(Config::get('install_dir') . '/' . $dir . '/' . $file) == 'file' && preg_match($regex, $file)) { |
873
|
|
|
d_echo('Including: ' . Config::get('install_dir') . '/' . $dir . '/' . $file . "\n"); |
874
|
|
|
|
875
|
|
|
include Config::get('install_dir') . '/' . $dir . '/' . $file; |
876
|
|
|
} |
877
|
|
|
} |
878
|
|
|
|
879
|
|
|
closedir($handle); |
880
|
|
|
} |
881
|
|
|
} |
882
|
|
|
|
883
|
|
|
/** |
884
|
|
|
* Check if port is valid to poll. |
885
|
|
|
* Settings: empty_ifdescr, good_if, bad_if, bad_if_regexp, bad_ifname_regexp, bad_ifalias_regexp, bad_iftype, bad_ifoperstatus |
886
|
|
|
* |
887
|
|
|
* @param array $port |
888
|
|
|
* @param array $device |
889
|
|
|
* @return bool |
890
|
|
|
*/ |
891
|
|
|
function is_port_valid($port, $device) |
892
|
|
|
{ |
893
|
|
|
// check empty values first |
894
|
|
|
if (empty($port['ifDescr'])) { |
895
|
|
|
// If these are all empty, we are just going to show blank names in the ui |
896
|
|
|
if (empty($port['ifAlias']) && empty($port['ifName'])) { |
897
|
|
|
d_echo("ignored: empty ifDescr, ifAlias and ifName\n"); |
898
|
|
|
|
899
|
|
|
return false; |
900
|
|
|
} |
901
|
|
|
|
902
|
|
|
// ifDescr should not be empty unless it is explicitly allowed |
903
|
|
|
if (! Config::getOsSetting($device['os'], 'empty_ifdescr', Config::get('empty_ifdescr', false))) { |
904
|
|
|
d_echo("ignored: empty ifDescr\n"); |
905
|
|
|
|
906
|
|
|
return false; |
907
|
|
|
} |
908
|
|
|
} |
909
|
|
|
|
910
|
|
|
$ifDescr = $port['ifDescr']; |
911
|
|
|
$ifName = $port['ifName']; |
912
|
|
|
$ifAlias = $port['ifAlias']; |
913
|
|
|
$ifType = $port['ifType']; |
914
|
|
|
$ifOperStatus = $port['ifOperStatus']; |
915
|
|
|
|
916
|
|
|
if (str_i_contains($ifDescr, Config::getOsSetting($device['os'], 'good_if', Config::get('good_if')))) { |
917
|
|
|
return true; |
918
|
|
|
} |
919
|
|
|
|
920
|
|
|
foreach (Config::getCombined($device['os'], 'bad_if') as $bi) { |
921
|
|
|
if (str_i_contains($ifDescr, $bi)) { |
922
|
|
|
d_echo("ignored by ifDescr: $ifDescr (matched: $bi)\n"); |
923
|
|
|
|
924
|
|
|
return false; |
925
|
|
|
} |
926
|
|
|
} |
927
|
|
|
|
928
|
|
|
foreach (Config::getCombined($device['os'], 'bad_if_regexp') as $bir) { |
929
|
|
|
if (preg_match($bir . 'i', $ifDescr)) { |
930
|
|
|
d_echo("ignored by ifDescr: $ifDescr (matched: $bir)\n"); |
931
|
|
|
|
932
|
|
|
return false; |
933
|
|
|
} |
934
|
|
|
} |
935
|
|
|
|
936
|
|
|
foreach (Config::getCombined($device['os'], 'bad_ifname_regexp') as $bnr) { |
937
|
|
|
if (preg_match($bnr . 'i', $ifName)) { |
938
|
|
|
d_echo("ignored by ifName: $ifName (matched: $bnr)\n"); |
939
|
|
|
|
940
|
|
|
return false; |
941
|
|
|
} |
942
|
|
|
} |
943
|
|
|
|
944
|
|
|
foreach (Config::getCombined($device['os'], 'bad_ifalias_regexp') as $bar) { |
945
|
|
|
if (preg_match($bar . 'i', $ifAlias)) { |
946
|
|
|
d_echo("ignored by ifName: $ifAlias (matched: $bar)\n"); |
947
|
|
|
|
948
|
|
|
return false; |
949
|
|
|
} |
950
|
|
|
} |
951
|
|
|
|
952
|
|
|
foreach (Config::getCombined($device['os'], 'bad_iftype') as $bt) { |
953
|
|
|
if (Str::contains($ifType, $bt)) { |
954
|
|
|
d_echo("ignored by ifType: $ifType (matched: $bt )\n"); |
955
|
|
|
|
956
|
|
|
return false; |
957
|
|
|
} |
958
|
|
|
} |
959
|
|
|
|
960
|
|
|
foreach (Config::getCombined($device['os'], 'bad_ifoperstatus') as $bos) { |
961
|
|
|
if (Str::contains($ifOperStatus, $bos)) { |
962
|
|
|
d_echo("ignored by ifOperStatus: $ifOperStatus (matched: $bos)\n"); |
963
|
|
|
|
964
|
|
|
return false; |
965
|
|
|
} |
966
|
|
|
} |
967
|
|
|
|
968
|
|
|
return true; |
969
|
|
|
} |
970
|
|
|
|
971
|
|
|
/** |
972
|
|
|
* Try to fill in data for ifDescr, ifName, and ifAlias if devices do not provide them. |
973
|
|
|
* Will not fill ifAlias if the user has overridden it |
974
|
|
|
* |
975
|
|
|
* @param array $port |
976
|
|
|
* @param array $device |
977
|
|
|
*/ |
978
|
|
|
function port_fill_missing(&$port, $device) |
979
|
|
|
{ |
980
|
|
|
// When devices do not provide data, populate with other data if available |
981
|
|
|
if ($port['ifDescr'] == '' || $port['ifDescr'] == null) { |
982
|
|
|
$port['ifDescr'] = $port['ifName']; |
983
|
|
|
d_echo(' Using ifName as ifDescr'); |
984
|
|
|
} |
985
|
|
|
if (! empty($device['attribs']['ifName:' . $port['ifName']])) { |
986
|
|
|
// ifAlias overridden by user, don't update it |
987
|
|
|
unset($port['ifAlias']); |
988
|
|
|
d_echo(' ifAlias overriden by user'); |
989
|
|
|
} elseif ($port['ifAlias'] == '' || $port['ifAlias'] == null) { |
990
|
|
|
$port['ifAlias'] = $port['ifDescr']; |
991
|
|
|
d_echo(' Using ifDescr as ifAlias'); |
992
|
|
|
} |
993
|
|
|
|
994
|
|
|
if ($port['ifName'] == '' || $port['ifName'] == null) { |
995
|
|
|
$port['ifName'] = $port['ifDescr']; |
996
|
|
|
d_echo(' Using ifDescr as ifName'); |
997
|
|
|
} |
998
|
|
|
} |
999
|
|
|
|
1000
|
|
|
function scan_new_plugins() |
1001
|
|
|
{ |
1002
|
|
|
$installed = 0; // Track how many plugins we install. |
1003
|
|
|
|
1004
|
|
|
if (file_exists(Config::get('plugin_dir'))) { |
1005
|
|
|
$plugin_files = scandir(Config::get('plugin_dir')); |
1006
|
|
|
foreach ($plugin_files as $name) { |
1007
|
|
|
if (is_dir(Config::get('plugin_dir') . '/' . $name)) { |
1008
|
|
|
if ($name != '.' && $name != '..') { |
1009
|
|
|
if (is_file(Config::get('plugin_dir') . '/' . $name . '/' . $name . '.php') && is_file(Config::get('plugin_dir') . '/' . $name . '/' . $name . '.inc.php')) { |
1010
|
|
|
$plugin_id = dbFetchRow('SELECT `plugin_id` FROM `plugins` WHERE `plugin_name` = ?', [$name]); |
1011
|
|
|
if (empty($plugin_id)) { |
1012
|
|
|
if (dbInsert(['plugin_name' => $name, 'plugin_active' => '0'], 'plugins')) { |
1013
|
|
|
$installed++; |
1014
|
|
|
} |
1015
|
|
|
} |
1016
|
|
|
} |
1017
|
|
|
} |
1018
|
|
|
} |
1019
|
|
|
} |
1020
|
|
|
} |
1021
|
|
|
|
1022
|
|
|
return $installed; |
1023
|
|
|
} |
1024
|
|
|
|
1025
|
|
|
function scan_removed_plugins() |
1026
|
|
|
{ |
1027
|
|
|
$removed = 0; // Track how many plugins will be removed from database |
1028
|
|
|
|
1029
|
|
|
if (file_exists(Config::get('plugin_dir'))) { |
1030
|
|
|
$plugin_files = scandir(Config::get('plugin_dir')); |
1031
|
|
|
$installed_plugins = dbFetchColumn('SELECT `plugin_name` FROM `plugins`'); |
1032
|
|
|
foreach ($installed_plugins as $name) { |
1033
|
|
|
if (in_array($name, $plugin_files)) { |
1034
|
|
|
continue; |
1035
|
|
|
} |
1036
|
|
|
if (dbDelete('plugins', '`plugin_name` = ?', $name)) { |
1037
|
|
|
$removed++; |
1038
|
|
|
} |
1039
|
|
|
} |
1040
|
|
|
} |
1041
|
|
|
|
1042
|
|
|
return $removed; |
1043
|
|
|
} |
1044
|
|
|
|
1045
|
|
|
function validate_device_id($id) |
1046
|
|
|
{ |
1047
|
|
|
if (empty($id) || ! is_numeric($id)) { |
1048
|
|
|
$return = false; |
1049
|
|
|
} else { |
1050
|
|
|
$device_id = dbFetchCell('SELECT `device_id` FROM `devices` WHERE `device_id` = ?', [$id]); |
1051
|
|
|
if ($device_id == $id) { |
1052
|
|
|
$return = true; |
1053
|
|
|
} else { |
1054
|
|
|
$return = false; |
1055
|
|
|
} |
1056
|
|
|
} |
1057
|
|
|
|
1058
|
|
|
return $return; |
1059
|
|
|
} |
1060
|
|
|
|
1061
|
|
|
function convert_delay($delay) |
1062
|
|
|
{ |
1063
|
|
|
if (preg_match('/(\d+)([mhd]?)/', $delay, $matches)) { |
1064
|
|
|
$multipliers = [ |
1065
|
|
|
'm' => 60, |
1066
|
|
|
'h' => 3600, |
1067
|
|
|
'd' => 86400, |
1068
|
|
|
]; |
1069
|
|
|
|
1070
|
|
|
$multiplier = $multipliers[$matches[2]] ?? 1; |
1071
|
|
|
|
1072
|
|
|
return $matches[1] * $multiplier; |
1073
|
|
|
} |
1074
|
|
|
|
1075
|
|
|
return $delay === '' ? 0 : 300; |
1076
|
|
|
} |
1077
|
|
|
|
1078
|
|
|
function normalize_snmp_ip_address($data) |
1079
|
|
|
{ |
1080
|
|
|
// $data is received from snmpwalk, can be ipv4 xxx.xxx.xxx.xxx or ipv6 xx:xx:...:xx (16 chunks) |
1081
|
|
|
// ipv4 is returned unchanged, ipv6 is returned with one ':' removed out of two, like |
1082
|
|
|
// xxxx:xxxx:...:xxxx (8 chuncks) |
1083
|
|
|
return preg_replace('/([0-9a-fA-F]{2}):([0-9a-fA-F]{2})/', '\1\2', explode('%', $data, 2)[0]); |
1084
|
|
|
} |
1085
|
|
|
|
1086
|
|
|
function guidv4($data) |
1087
|
|
|
{ |
1088
|
|
|
// http://stackoverflow.com/questions/2040240/php-function-to-generate-v4-uuid#15875555 |
1089
|
|
|
// From: Jack http://stackoverflow.com/users/1338292/ja%CD%A2ck |
1090
|
|
|
assert(strlen($data) == 16); |
1091
|
|
|
|
1092
|
|
|
$data[6] = chr(ord($data[6]) & 0x0F | 0x40); // set version to 0100 |
1093
|
|
|
$data[8] = chr(ord($data[8]) & 0x3F | 0x80); // set bits 6-7 to 10 |
1094
|
|
|
|
1095
|
|
|
return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4)); |
1096
|
|
|
} |
1097
|
|
|
|
1098
|
|
|
/** |
1099
|
|
|
* @param $curl |
1100
|
|
|
*/ |
1101
|
|
|
function set_curl_proxy($curl) |
1102
|
|
|
{ |
1103
|
|
|
$proxy = get_proxy(); |
1104
|
|
|
|
1105
|
|
|
$tmp = rtrim($proxy, '/'); |
1106
|
|
|
$proxy = str_replace(['http://', 'https://'], '', $tmp); |
1107
|
|
|
if (! empty($proxy)) { |
1108
|
|
|
curl_setopt($curl, CURLOPT_PROXY, $proxy); |
1109
|
|
|
} |
1110
|
|
|
} |
1111
|
|
|
|
1112
|
|
|
/** |
1113
|
|
|
* Return the proxy url in guzzle format |
1114
|
|
|
* |
1115
|
|
|
* @return 'tcp://' + $proxy |
1116
|
|
|
*/ |
1117
|
|
|
function get_guzzle_proxy() |
1118
|
|
|
{ |
1119
|
|
|
$proxy = get_proxy(); |
1120
|
|
|
|
1121
|
|
|
$tmp = rtrim($proxy, '/'); |
1122
|
|
|
$proxy = str_replace(['http://', 'https://'], '', $tmp); |
1123
|
|
|
|
1124
|
|
|
return empty($proxy) ? '' : ('tcp://' . $proxy); |
1125
|
|
|
} |
1126
|
|
|
|
1127
|
|
|
/** |
1128
|
|
|
* Return the proxy url |
1129
|
|
|
* |
1130
|
|
|
* @return array|bool|false|string |
1131
|
|
|
*/ |
1132
|
|
|
function get_proxy() |
1133
|
|
|
{ |
1134
|
|
|
if (getenv('http_proxy')) { |
1135
|
|
|
return getenv('http_proxy'); |
1136
|
|
|
} elseif (getenv('https_proxy')) { |
1137
|
|
|
return getenv('https_proxy'); |
1138
|
|
|
} elseif ($callback_proxy = Config::get('callback_proxy')) { |
1139
|
|
|
return $callback_proxy; |
1140
|
|
|
} elseif ($http_proxy = Config::get('http_proxy')) { |
1141
|
|
|
return $http_proxy; |
1142
|
|
|
} |
1143
|
|
|
|
1144
|
|
|
return false; |
1145
|
|
|
} |
1146
|
|
|
|
1147
|
|
|
function target_to_id($target) |
1148
|
|
|
{ |
1149
|
|
|
if ($target[0] . $target[1] == 'g:') { |
1150
|
|
|
$target = 'g' . dbFetchCell('SELECT id FROM device_groups WHERE name = ?', [substr($target, 2)]); |
1151
|
|
|
} else { |
1152
|
|
|
$target = dbFetchCell('SELECT device_id FROM devices WHERE hostname = ?', [$target]); |
1153
|
|
|
} |
1154
|
|
|
|
1155
|
|
|
return $target; |
1156
|
|
|
} |
1157
|
|
|
|
1158
|
|
|
function fix_integer_value($value) |
1159
|
|
|
{ |
1160
|
|
|
if ($value < 0) { |
1161
|
|
|
$return = 4294967296 + $value; |
1162
|
|
|
} else { |
1163
|
|
|
$return = $value; |
1164
|
|
|
} |
1165
|
|
|
|
1166
|
|
|
return $return; |
1167
|
|
|
} |
1168
|
|
|
|
1169
|
|
|
/** |
1170
|
|
|
* Find a device that has this IP. Checks ipv4_addresses and ipv6_addresses tables. |
1171
|
|
|
* |
1172
|
|
|
* @param string $ip |
1173
|
|
|
* @return \App\Models\Device|false |
1174
|
|
|
*/ |
1175
|
|
|
function device_has_ip($ip) |
1176
|
|
|
{ |
1177
|
|
|
if (IPv6::isValid($ip)) { |
1178
|
|
|
$ip_address = \App\Models\Ipv6Address::query() |
1179
|
|
|
->where('ipv6_address', IPv6::parse($ip, true)->uncompressed()) |
1180
|
|
|
->with('port.device') |
1181
|
|
|
->first(); |
1182
|
|
|
} elseif (IPv4::isValid($ip)) { |
1183
|
|
|
$ip_address = \App\Models\Ipv4Address::query() |
1184
|
|
|
->where('ipv4_address', $ip) |
1185
|
|
|
->with('port.device') |
1186
|
|
|
->first(); |
1187
|
|
|
} |
1188
|
|
|
|
1189
|
|
|
if (isset($ip_address) && $ip_address->port) { |
1190
|
|
|
return $ip_address->port->device; |
1191
|
|
|
} |
1192
|
|
|
|
1193
|
|
|
return false; // not an ipv4 or ipv6 address... |
1194
|
|
|
} |
1195
|
|
|
|
1196
|
|
|
/** |
1197
|
|
|
* Try to determine the address family (IPv4 or IPv6) associated with an SNMP |
1198
|
|
|
* transport specifier (like "udp", "udp6", etc.). |
1199
|
|
|
* |
1200
|
|
|
* @param string $transport The SNMP transport specifier, for example "udp", |
1201
|
|
|
* "udp6", "tcp", or "tcp6". See `man snmpcmd`, |
1202
|
|
|
* section "Agent Specification" for a full list. |
1203
|
|
|
* @return string The address family associated with the given transport |
1204
|
|
|
* specifier: 'ipv4' (or local connections not associated |
1205
|
|
|
* with an IP stack) or 'ipv6'. |
1206
|
|
|
*/ |
1207
|
|
|
function snmpTransportToAddressFamily($transport) |
1208
|
|
|
{ |
1209
|
|
|
$ipv6_snmp_transport_specifiers = ['udp6', 'udpv6', 'udpipv6', 'tcp6', 'tcpv6', 'tcpipv6']; |
1210
|
|
|
|
1211
|
|
|
if (in_array($transport, $ipv6_snmp_transport_specifiers)) { |
1212
|
|
|
return 'ipv6'; |
1213
|
|
|
} |
1214
|
|
|
|
1215
|
|
|
return 'ipv4'; |
1216
|
|
|
} |
1217
|
|
|
|
1218
|
|
|
/** |
1219
|
|
|
* Checks if the $hostname provided exists in the DB already |
1220
|
|
|
* |
1221
|
|
|
* @param string $hostname The hostname to check for |
1222
|
|
|
* @param string $sysName The sysName to check |
1223
|
|
|
* @return bool true if hostname already exists |
1224
|
|
|
* false if hostname doesn't exist |
1225
|
|
|
*/ |
1226
|
|
|
function host_exists($hostname, $sysName = null) |
1227
|
|
|
{ |
1228
|
|
|
$query = 'SELECT COUNT(*) FROM `devices` WHERE `hostname`=?'; |
1229
|
|
|
$params = [$hostname]; |
1230
|
|
|
|
1231
|
|
|
if (! empty($sysName) && ! Config::get('allow_duplicate_sysName')) { |
1232
|
|
|
$query .= ' OR `sysName`=?'; |
1233
|
|
|
$params[] = $sysName; |
1234
|
|
|
|
1235
|
|
|
if (! empty(Config::get('mydomain'))) { |
1236
|
|
|
$full_sysname = rtrim($sysName, '.') . '.' . Config::get('mydomain'); |
1237
|
|
|
$query .= ' OR `sysName`=?'; |
1238
|
|
|
$params[] = $full_sysname; |
1239
|
|
|
} |
1240
|
|
|
} |
1241
|
|
|
|
1242
|
|
|
return dbFetchCell($query, $params) > 0; |
1243
|
|
|
} |
1244
|
|
|
|
1245
|
|
|
function oxidized_reload_nodes() |
1246
|
|
|
{ |
1247
|
|
|
if (Config::get('oxidized.enabled') === true && Config::get('oxidized.reload_nodes') === true && Config::has('oxidized.url')) { |
1248
|
|
|
$oxidized_reload_url = Config::get('oxidized.url') . '/reload.json'; |
1249
|
|
|
$ch = curl_init($oxidized_reload_url); |
1250
|
|
|
|
1251
|
|
|
curl_setopt($ch, CURLOPT_TIMEOUT, 5); |
1252
|
|
|
curl_setopt($ch, CURLOPT_TIMEOUT_MS, 5000); |
1253
|
|
|
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5); |
1254
|
|
|
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); |
1255
|
|
|
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); |
1256
|
|
|
curl_setopt($ch, CURLOPT_HEADER, 1); |
1257
|
|
|
curl_exec($ch); |
1258
|
|
|
curl_close($ch); |
1259
|
|
|
} |
1260
|
|
|
} |
1261
|
|
|
|
1262
|
|
|
/** |
1263
|
|
|
* Perform DNS lookup |
1264
|
|
|
* |
1265
|
|
|
* @param array $device Device array from database |
1266
|
|
|
* @param string $type The type of record to lookup |
1267
|
|
|
* @return string ip |
1268
|
|
|
* |
1269
|
|
|
**/ |
1270
|
|
|
function dnslookup($device, $type = false, $return = false) |
1271
|
|
|
{ |
1272
|
|
|
if (filter_var($device['hostname'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) == true || filter_var($device['hostname'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) == true) { |
1273
|
|
|
return false; |
1274
|
|
|
} |
1275
|
|
|
if (empty($type)) { |
1276
|
|
|
// We are going to use the transport to work out the record type |
1277
|
|
|
if ($device['transport'] == 'udp6' || $device['transport'] == 'tcp6') { |
1278
|
|
|
$type = DNS_AAAA; |
1279
|
|
|
$return = 'ipv6'; |
1280
|
|
|
} else { |
1281
|
|
|
$type = DNS_A; |
1282
|
|
|
$return = 'ip'; |
1283
|
|
|
} |
1284
|
|
|
} |
1285
|
|
|
if (empty($return)) { |
1286
|
|
|
return false; |
1287
|
|
|
} |
1288
|
|
|
$record = dns_get_record($device['hostname'], $type); |
1289
|
|
|
|
1290
|
|
|
return $record[0][$return]; |
1291
|
|
|
}//end dnslookup |
1292
|
|
|
|
1293
|
|
|
/** |
1294
|
|
|
* Create a new state index. Update translations if $states is given. |
1295
|
|
|
* |
1296
|
|
|
* For for backward compatibility: |
1297
|
|
|
* Returns null if $states is empty, $state_name already exists, and contains state translations |
1298
|
|
|
* |
1299
|
|
|
* @param string $state_name the unique name for this state translation |
1300
|
|
|
* @param array $states array of states, each must contain keys: descr, graph, value, generic |
1301
|
|
|
* @return int|null |
1302
|
|
|
*/ |
1303
|
|
|
function create_state_index($state_name, $states = []) |
1304
|
|
|
{ |
1305
|
|
|
$state_index_id = dbFetchCell('SELECT `state_index_id` FROM state_indexes WHERE state_name = ? LIMIT 1', [$state_name]); |
1306
|
|
|
if (! is_numeric($state_index_id)) { |
1307
|
|
|
$state_index_id = dbInsert(['state_name' => $state_name], 'state_indexes'); |
1308
|
|
|
|
1309
|
|
|
// legacy code, return index so states are created |
1310
|
|
|
if (empty($states)) { |
1311
|
|
|
return $state_index_id; |
1312
|
|
|
} |
1313
|
|
|
} |
1314
|
|
|
|
1315
|
|
|
// check or synchronize states |
1316
|
|
|
if (empty($states)) { |
1317
|
|
|
$translations = dbFetchRows('SELECT * FROM `state_translations` WHERE `state_index_id` = ?', [$state_index_id]); |
1318
|
|
|
if (count($translations) == 0) { |
1319
|
|
|
// If we don't have any translations something has gone wrong so return the state_index_id so they get created. |
1320
|
|
|
return $state_index_id; |
1321
|
|
|
} |
1322
|
|
|
} else { |
1323
|
|
|
sync_sensor_states($state_index_id, $states); |
1324
|
|
|
} |
1325
|
|
|
|
1326
|
|
|
return null; |
1327
|
|
|
} |
1328
|
|
|
|
1329
|
|
|
/** |
1330
|
|
|
* Synchronize the sensor state translations with the database |
1331
|
|
|
* |
1332
|
|
|
* @param int $state_index_id index of the state |
1333
|
|
|
* @param array $states array of states, each must contain keys: descr, graph, value, generic |
1334
|
|
|
*/ |
1335
|
|
|
function sync_sensor_states($state_index_id, $states) |
1336
|
|
|
{ |
1337
|
|
|
$new_translations = array_reduce($states, function ($array, $state) use ($state_index_id) { |
1338
|
|
|
$array[$state['value']] = [ |
1339
|
|
|
'state_index_id' => $state_index_id, |
1340
|
|
|
'state_descr' => $state['descr'], |
1341
|
|
|
'state_draw_graph' => $state['graph'], |
1342
|
|
|
'state_value' => $state['value'], |
1343
|
|
|
'state_generic_value' => $state['generic'], |
1344
|
|
|
]; |
1345
|
|
|
|
1346
|
|
|
return $array; |
1347
|
|
|
}, []); |
1348
|
|
|
|
1349
|
|
|
$existing_translations = dbFetchRows( |
1350
|
|
|
'SELECT `state_index_id`,`state_descr`,`state_draw_graph`,`state_value`,`state_generic_value` FROM `state_translations` WHERE `state_index_id`=?', |
1351
|
|
|
[$state_index_id] |
1352
|
|
|
); |
1353
|
|
|
|
1354
|
|
|
foreach ($existing_translations as $translation) { |
1355
|
|
|
$value = $translation['state_value']; |
1356
|
|
|
if (isset($new_translations[$value])) { |
1357
|
|
|
if ($new_translations[$value] != $translation) { |
1358
|
|
|
dbUpdate( |
1359
|
|
|
$new_translations[$value], |
1360
|
|
|
'state_translations', |
1361
|
|
|
'`state_index_id`=? AND `state_value`=?', |
1362
|
|
|
[$state_index_id, $value] |
1363
|
|
|
); |
1364
|
|
|
} |
1365
|
|
|
|
1366
|
|
|
// this translation is synchronized, it doesn't need to be inserted |
1367
|
|
|
unset($new_translations[$value]); |
1368
|
|
|
} else { |
1369
|
|
|
dbDelete('state_translations', '`state_index_id`=? AND `state_value`=?', [$state_index_id, $value]); |
1370
|
|
|
} |
1371
|
|
|
} |
1372
|
|
|
|
1373
|
|
|
// insert any new translations |
1374
|
|
|
dbBulkInsert($new_translations, 'state_translations'); |
1375
|
|
|
} |
1376
|
|
|
|
1377
|
|
|
function create_sensor_to_state_index($device, $state_name, $index) |
1378
|
|
|
{ |
1379
|
|
|
$sensor_entry = dbFetchRow('SELECT sensor_id FROM `sensors` WHERE `sensor_class` = ? AND `device_id` = ? AND `sensor_type` = ? AND `sensor_index` = ?', [ |
1380
|
|
|
'state', |
1381
|
|
|
$device['device_id'], |
1382
|
|
|
$state_name, |
1383
|
|
|
$index, |
1384
|
|
|
]); |
1385
|
|
|
$state_indexes_entry = dbFetchRow('SELECT state_index_id FROM `state_indexes` WHERE `state_name` = ?', [ |
1386
|
|
|
$state_name, |
1387
|
|
|
]); |
1388
|
|
|
if (! empty($sensor_entry['sensor_id']) && ! empty($state_indexes_entry['state_index_id'])) { |
1389
|
|
|
$insert = [ |
1390
|
|
|
'sensor_id' => $sensor_entry['sensor_id'], |
1391
|
|
|
'state_index_id' => $state_indexes_entry['state_index_id'], |
1392
|
|
|
]; |
1393
|
|
|
foreach ($insert as $key => $val_check) { |
1394
|
|
|
if (! isset($val_check)) { |
1395
|
|
|
unset($insert[$key]); |
1396
|
|
|
} |
1397
|
|
|
} |
1398
|
|
|
|
1399
|
|
|
dbInsert($insert, 'sensors_to_state_indexes'); |
1400
|
|
|
} |
1401
|
|
|
} |
1402
|
|
|
|
1403
|
|
|
function delta_to_bits($delta, $period) |
1404
|
|
|
{ |
1405
|
|
|
return round(($delta * 8 / $period), 2); |
1406
|
|
|
} |
1407
|
|
|
|
1408
|
|
|
function report_this($message) |
1409
|
|
|
{ |
1410
|
|
|
return '<h2>' . $message . ' Please <a href="' . Config::get('project_issues') . '">report this</a> to the ' . Config::get('project_name') . ' developers.</h2>'; |
1411
|
|
|
}//end report_this() |
1412
|
|
|
|
1413
|
|
|
function hytera_h2f($number, $nd) |
1414
|
|
|
{ |
1415
|
|
|
if (strlen(str_replace(' ', '', $number)) == 4) { |
1416
|
|
|
$hex = ''; |
1417
|
|
|
for ($i = 0; $i < strlen($number); $i++) { |
1418
|
|
|
$byte = strtoupper(dechex(ord($number[$i]))); |
1419
|
|
|
$byte = str_repeat('0', 2 - strlen($byte)) . $byte; |
1420
|
|
|
$hex .= $byte . ' '; |
1421
|
|
|
} |
1422
|
|
|
$number = $hex; |
1423
|
|
|
unset($hex); |
1424
|
|
|
} |
1425
|
|
|
$r = ''; |
1426
|
|
|
$y = explode(' ', $number); |
1427
|
|
|
foreach ($y as $z) { |
1428
|
|
|
$r = $z . '' . $r; |
1429
|
|
|
} |
1430
|
|
|
|
1431
|
|
|
$hex = []; |
1432
|
|
|
$number = substr($r, 0, -1); |
1433
|
|
|
//$number = str_replace(" ", "", $number); |
1434
|
|
|
for ($i = 0; $i < strlen($number); $i++) { |
1435
|
|
|
$hex[] = substr($number, $i, 1); |
1436
|
|
|
} |
1437
|
|
|
|
1438
|
|
|
$dec = []; |
1439
|
|
|
$hexCount = count($hex); |
1440
|
|
|
for ($i = 0; $i < $hexCount; $i++) { |
1441
|
|
|
$dec[] = hexdec($hex[$i]); |
1442
|
|
|
} |
1443
|
|
|
|
1444
|
|
|
$binfinal = ''; |
1445
|
|
|
$decCount = count($dec); |
1446
|
|
|
for ($i = 0; $i < $decCount; $i++) { |
1447
|
|
|
$binfinal .= sprintf('%04d', decbin($dec[$i])); |
1448
|
|
|
} |
1449
|
|
|
|
1450
|
|
|
$sign = substr($binfinal, 0, 1); |
1451
|
|
|
$exp = substr($binfinal, 1, 8); |
1452
|
|
|
$exp = bindec($exp); |
1453
|
|
|
$exp -= 127; |
1454
|
|
|
$scibin = substr($binfinal, 9); |
1455
|
|
|
$binint = substr($scibin, 0, $exp); |
1456
|
|
|
$binpoint = substr($scibin, $exp); |
1457
|
|
|
$intnumber = bindec('1' . $binint); |
1458
|
|
|
|
1459
|
|
|
$tmppoint = []; |
1460
|
|
|
for ($i = 0; $i < strlen($binpoint); $i++) { |
1461
|
|
|
$tmppoint[] = substr($binpoint, $i, 1); |
1462
|
|
|
} |
1463
|
|
|
|
1464
|
|
|
$tmppoint = array_reverse($tmppoint); |
1465
|
|
|
$tpointnumber = number_format($tmppoint[0] / 2, strlen($binpoint), '.', ''); |
1466
|
|
|
|
1467
|
|
|
$pointnumber = ''; |
1468
|
|
|
for ($i = 1; $i < strlen($binpoint); $i++) { |
1469
|
|
|
$pointnumber = number_format($tpointnumber / 2, strlen($binpoint), '.', ''); |
1470
|
|
|
$tpointnumber = $tmppoint[$i + 1] . substr($pointnumber, 1); |
1471
|
|
|
} |
1472
|
|
|
|
1473
|
|
|
$floatfinal = $intnumber + $pointnumber; |
1474
|
|
|
|
1475
|
|
|
if ($sign == 1) { |
1476
|
|
|
$floatfinal = -$floatfinal; |
1477
|
|
|
} |
1478
|
|
|
|
1479
|
|
|
return number_format($floatfinal, $nd, '.', ''); |
1480
|
|
|
} |
1481
|
|
|
|
1482
|
|
|
/* |
1483
|
|
|
* Cisco CIMC functions |
1484
|
|
|
*/ |
1485
|
|
|
// Create an entry in the entPhysical table if it doesnt already exist. |
1486
|
|
|
function setCIMCentPhysical($location, $data, &$entphysical, &$index) |
1487
|
|
|
{ |
1488
|
|
|
// Go get the location, this will create it if it doesnt exist. |
1489
|
|
|
$entPhysicalIndex = getCIMCentPhysical($location, $entphysical, $index); |
1490
|
|
|
|
1491
|
|
|
// See if we need to update |
1492
|
|
|
$update = []; |
1493
|
|
|
foreach ($data as $key => $value) { |
1494
|
|
|
// Is the Array(DB) value different to the supplied data |
1495
|
|
|
if ($entphysical[$location][$key] != $value) { |
1496
|
|
|
$update[$key] = $value; |
1497
|
|
|
$entphysical[$location][$key] = $value; |
1498
|
|
|
} // End if |
1499
|
|
|
} // end foreach |
1500
|
|
|
|
1501
|
|
|
// Do we need to update |
1502
|
|
|
if (count($update) > 0) { |
1503
|
|
|
dbUpdate($update, 'entPhysical', '`entPhysical_id` = ?', [$entphysical[$location]['entPhysical_id']]); |
1504
|
|
|
} |
1505
|
|
|
$entPhysicalId = $entphysical[$location]['entPhysical_id']; |
1506
|
|
|
|
1507
|
|
|
return [$entPhysicalId, $entPhysicalIndex]; |
1508
|
|
|
} |
1509
|
|
|
|
1510
|
|
|
function getCIMCentPhysical($location, &$entphysical, &$index) |
1511
|
|
|
{ |
1512
|
|
|
global $device; |
1513
|
|
|
|
1514
|
|
|
// Level 1 - Does the location exist |
1515
|
|
|
if (isset($entphysical[$location])) { |
1516
|
|
|
// Yes, return the entPhysicalIndex. |
1517
|
|
|
return $entphysical[$location]['entPhysicalIndex']; |
1518
|
|
|
} else { |
1519
|
|
|
/* |
1520
|
|
|
* No, the entry doesnt exist. |
1521
|
|
|
* Find its parent so we can create it. |
1522
|
|
|
*/ |
1523
|
|
|
|
1524
|
|
|
// Pull apart the location |
1525
|
|
|
$parts = explode('/', $location); |
1526
|
|
|
|
1527
|
|
|
// Level 2 - Are we at the root |
1528
|
|
|
if (count($parts) == 1) { |
1529
|
|
|
// Level 2 - Yes. We are the root, there is no parent |
1530
|
|
|
d_echo('ROOT - ' . $location . "\n"); |
1531
|
|
|
$shortlocation = $location; |
1532
|
|
|
$parent = 0; |
1533
|
|
|
} else { |
1534
|
|
|
// Level 2 - No. Need to go deeper. |
1535
|
|
|
d_echo('NON-ROOT - ' . $location . "\n"); |
1536
|
|
|
$shortlocation = array_pop($parts); |
1537
|
|
|
$parentlocation = implode('/', $parts); |
1538
|
|
|
d_echo('Decend - parent location: ' . $parentlocation . "\n"); |
1539
|
|
|
$parent = getCIMCentPhysical($parentlocation, $entphysical, $index); |
1540
|
|
|
} // end if - Level 2 |
1541
|
|
|
d_echo('Parent: ' . $parent . "\n"); |
1542
|
|
|
|
1543
|
|
|
// Now we have an ID, create the entry. |
1544
|
|
|
$index++; |
1545
|
|
|
$insert = [ |
1546
|
|
|
'device_id' => $device['device_id'], |
1547
|
|
|
'entPhysicalIndex' => $index, |
1548
|
|
|
'entPhysicalClass' => 'container', |
1549
|
|
|
'entPhysicalVendorType' => $location, |
1550
|
|
|
'entPhysicalName' => $shortlocation, |
1551
|
|
|
'entPhysicalContainedIn' => $parent, |
1552
|
|
|
'entPhysicalParentRelPos' => '-1', |
1553
|
|
|
]; |
1554
|
|
|
|
1555
|
|
|
// Add to the DB and Array. |
1556
|
|
|
$id = dbInsert($insert, 'entPhysical'); |
1557
|
|
|
$entphysical[$location] = dbFetchRow('SELECT * FROM entPhysical WHERE entPhysical_id=?', [$id]); |
1558
|
|
|
|
1559
|
|
|
return $index; |
1560
|
|
|
} // end if - Level 1 |
1561
|
|
|
} // end function |
1562
|
|
|
|
1563
|
|
|
/* idea from https://php.net/manual/en/function.hex2bin.php comments */ |
1564
|
|
|
function hex2bin_compat($str) |
1565
|
|
|
{ |
1566
|
|
|
if (strlen($str) % 2 !== 0) { |
1567
|
|
|
trigger_error(__FUNCTION__ . '(): Hexadecimal input string must have an even length', E_USER_WARNING); |
1568
|
|
|
} |
1569
|
|
|
|
1570
|
|
|
return pack('H*', $str); |
1571
|
|
|
} |
1572
|
|
|
|
1573
|
|
|
if (! function_exists('hex2bin')) { |
1574
|
|
|
// This is only a hack |
1575
|
|
|
function hex2bin($str) |
1576
|
|
|
{ |
1577
|
|
|
return hex2bin_compat($str); |
1578
|
|
|
} |
1579
|
|
|
} |
1580
|
|
|
|
1581
|
|
|
function q_bridge_bits2indices($hex_data) |
1582
|
|
|
{ |
1583
|
|
|
/* convert hex string to an array of 1-based indices of the nonzero bits |
1584
|
|
|
* ie. '9a00' -> '100110100000' -> array(1, 4, 5, 7) |
1585
|
|
|
*/ |
1586
|
|
|
$hex_data = str_replace(' ', '', $hex_data); |
1587
|
|
|
|
1588
|
|
|
// we need an even number of digits for hex2bin |
1589
|
|
|
if (strlen($hex_data) % 2 === 1) { |
1590
|
|
|
$hex_data = '0' . $hex_data; |
1591
|
|
|
} |
1592
|
|
|
|
1593
|
|
|
$value = hex2bin($hex_data); |
1594
|
|
|
$length = strlen($value); |
1595
|
|
|
$indices = []; |
1596
|
|
|
for ($i = 0; $i < $length; $i++) { |
1597
|
|
|
$byte = ord($value[$i]); |
1598
|
|
|
for ($j = 7; $j >= 0; $j--) { |
1599
|
|
|
if ($byte & (1 << $j)) { |
1600
|
|
|
$indices[] = 8 * $i + 8 - $j; |
1601
|
|
|
} |
1602
|
|
|
} |
1603
|
|
|
} |
1604
|
|
|
|
1605
|
|
|
return $indices; |
1606
|
|
|
} |
1607
|
|
|
|
1608
|
|
|
/** |
1609
|
|
|
* Intialize global stat arrays |
1610
|
|
|
*/ |
1611
|
|
|
function initStats() |
1612
|
|
|
{ |
1613
|
|
|
global $snmp_stats, $snmp_stats_last; |
1614
|
|
|
|
1615
|
|
|
if (! isset($snmp_stats)) { |
1616
|
|
|
$snmp_stats = [ |
1617
|
|
|
'ops' => [ |
1618
|
|
|
'snmpget' => 0, |
1619
|
|
|
'snmpgetnext' => 0, |
1620
|
|
|
'snmpwalk' => 0, |
1621
|
|
|
], |
1622
|
|
|
'time' => [ |
1623
|
|
|
'snmpget' => 0.0, |
1624
|
|
|
'snmpgetnext' => 0.0, |
1625
|
|
|
'snmpwalk' => 0.0, |
1626
|
|
|
], |
1627
|
|
|
]; |
1628
|
|
|
$snmp_stats_last = $snmp_stats; |
1629
|
|
|
} |
1630
|
|
|
} |
1631
|
|
|
|
1632
|
|
|
/** |
1633
|
|
|
* Print out the stats totals since the last time this function was called |
1634
|
|
|
* |
1635
|
|
|
* @param bool $update_only Only update the stats checkpoint, don't print them |
1636
|
|
|
*/ |
1637
|
|
|
function printChangedStats($update_only = false) |
1638
|
|
|
{ |
1639
|
|
|
global $snmp_stats, $db_stats; |
1640
|
|
|
global $snmp_stats_last, $db_stats_last; |
1641
|
|
|
$output = sprintf( |
1642
|
|
|
'>> SNMP: [%d/%.2fs] MySQL: [%d/%.2fs]', |
1643
|
|
|
array_sum($snmp_stats['ops'] ?? []) - array_sum($snmp_stats_last['ops'] ?? []), |
1644
|
|
|
array_sum($snmp_stats['time'] ?? []) - array_sum($snmp_stats_last['time'] ?? []), |
1645
|
|
|
array_sum($db_stats['ops'] ?? []) - array_sum($db_stats_last['ops'] ?? []), |
1646
|
|
|
array_sum($db_stats['time'] ?? []) - array_sum($db_stats_last['time'] ?? []) |
1647
|
|
|
); |
1648
|
|
|
|
1649
|
|
|
foreach (app('Datastore')->getStats() as $datastore => $stats) { |
1650
|
|
|
/** @var \LibreNMS\Data\Measure\MeasurementCollection $stats */ |
1651
|
|
|
$output .= sprintf(' %s: [%d/%.2fs]', $datastore, $stats->getCountDiff(), $stats->getDurationDiff()); |
1652
|
|
|
$stats->checkpoint(); |
1653
|
|
|
} |
1654
|
|
|
|
1655
|
|
|
if (! $update_only) { |
1656
|
|
|
echo $output . PHP_EOL; |
1657
|
|
|
} |
1658
|
|
|
|
1659
|
|
|
// make a new checkpoint |
1660
|
|
|
$snmp_stats_last = $snmp_stats; |
1661
|
|
|
$db_stats_last = $db_stats; |
1662
|
|
|
} |
1663
|
|
|
|
1664
|
|
|
/** |
1665
|
|
|
* Print global stat arrays |
1666
|
|
|
*/ |
1667
|
|
|
function printStats() |
1668
|
|
|
{ |
1669
|
|
|
global $snmp_stats, $db_stats; |
1670
|
|
|
|
1671
|
|
|
if ($snmp_stats) { |
1672
|
|
|
printf( |
1673
|
|
|
"SNMP [%d/%.2fs]: Get[%d/%.2fs] Getnext[%d/%.2fs] Walk[%d/%.2fs]\n", |
1674
|
|
|
array_sum($snmp_stats['ops']), |
1675
|
|
|
array_sum($snmp_stats['time']), |
1676
|
|
|
$snmp_stats['ops']['snmpget'], |
1677
|
|
|
$snmp_stats['time']['snmpget'], |
1678
|
|
|
$snmp_stats['ops']['snmpgetnext'], |
1679
|
|
|
$snmp_stats['time']['snmpgetnext'], |
1680
|
|
|
$snmp_stats['ops']['snmpwalk'], |
1681
|
|
|
$snmp_stats['time']['snmpwalk'] |
1682
|
|
|
); |
1683
|
|
|
} |
1684
|
|
|
|
1685
|
|
|
if ($db_stats) { |
1686
|
|
|
printf( |
1687
|
|
|
"MySQL [%d/%.2fs]: Cell[%d/%.2fs] Row[%d/%.2fs] Rows[%d/%.2fs] Column[%d/%.2fs] Update[%d/%.2fs] Insert[%d/%.2fs] Delete[%d/%.2fs]\n", |
1688
|
|
|
array_sum($db_stats['ops']), |
1689
|
|
|
array_sum($db_stats['time']), |
1690
|
|
|
$db_stats['ops']['fetchcell'], |
1691
|
|
|
$db_stats['time']['fetchcell'], |
1692
|
|
|
$db_stats['ops']['fetchrow'], |
1693
|
|
|
$db_stats['time']['fetchrow'], |
1694
|
|
|
$db_stats['ops']['fetchrows'], |
1695
|
|
|
$db_stats['time']['fetchrows'], |
1696
|
|
|
$db_stats['ops']['fetchcolumn'], |
1697
|
|
|
$db_stats['time']['fetchcolumn'], |
1698
|
|
|
$db_stats['ops']['update'], |
1699
|
|
|
$db_stats['time']['update'], |
1700
|
|
|
$db_stats['ops']['insert'], |
1701
|
|
|
$db_stats['time']['insert'], |
1702
|
|
|
$db_stats['ops']['delete'], |
1703
|
|
|
$db_stats['time']['delete'] |
1704
|
|
|
); |
1705
|
|
|
} |
1706
|
|
|
|
1707
|
|
|
foreach (app('Datastore')->getStats() as $datastore => $stats) { |
1708
|
|
|
/** @var \LibreNMS\Data\Measure\MeasurementCollection $stats */ |
1709
|
|
|
printf('%s [%d/%.2fs]:', $datastore, $stats->getTotalCount(), $stats->getTotalDuration()); |
1710
|
|
|
|
1711
|
|
|
foreach ($stats as $stat) { |
1712
|
|
|
/** @var \LibreNMS\Data\Measure\MeasurementSummary $stat */ |
1713
|
|
|
printf(' %s[%d/%.2fs]', ucfirst($stat->getType()), $stat->getCount(), $stat->getDuration()); |
1714
|
|
|
} |
1715
|
|
|
echo PHP_EOL; |
1716
|
|
|
} |
1717
|
|
|
} |
1718
|
|
|
|
1719
|
|
|
/** |
1720
|
|
|
* @param string $stat snmpget, snmpwalk |
1721
|
|
|
* @param float $start_time The time the operation started with 'microtime(true)' |
1722
|
|
|
* @return float The calculated run time |
1723
|
|
|
*/ |
1724
|
|
|
function recordSnmpStatistic($stat, $start_time) |
1725
|
|
|
{ |
1726
|
|
|
global $snmp_stats; |
1727
|
|
|
initStats(); |
1728
|
|
|
|
1729
|
|
|
$runtime = microtime(true) - $start_time; |
1730
|
|
|
$snmp_stats['ops'][$stat]++; |
1731
|
|
|
$snmp_stats['time'][$stat] += $runtime; |
1732
|
|
|
|
1733
|
|
|
return $runtime; |
1734
|
|
|
} |
1735
|
|
|
|
1736
|
|
|
function runTraceroute($device) |
1737
|
|
|
{ |
1738
|
|
|
$address_family = snmpTransportToAddressFamily($device['transport']); |
1739
|
|
|
$trace_name = $address_family == 'ipv6' ? 'traceroute6' : 'traceroute'; |
1740
|
|
|
$trace_path = Config::get($trace_name, $trace_name); |
1741
|
|
|
$process = new Process([$trace_path, '-q', '1', '-w', '1', $device['hostname']]); |
1742
|
|
|
$process->run(); |
1743
|
|
|
if ($process->isSuccessful()) { |
1744
|
|
|
return ['traceroute' => $process->getOutput()]; |
1745
|
|
|
} |
1746
|
|
|
|
1747
|
|
|
return ['output' => $process->getErrorOutput()]; |
1748
|
|
|
} |
1749
|
|
|
|
1750
|
|
|
/** |
1751
|
|
|
* @param $device |
1752
|
|
|
* @param bool $record_perf |
1753
|
|
|
* @return array |
1754
|
|
|
*/ |
1755
|
|
|
function device_is_up($device, $record_perf = false) |
1756
|
|
|
{ |
1757
|
|
|
$address_family = snmpTransportToAddressFamily($device['transport']); |
1758
|
|
|
$poller_target = Device::pollerTarget($device['hostname']); |
1759
|
|
|
$ping_response = isPingable($poller_target, $address_family, $device['attribs']); |
1760
|
|
|
$device_perf = $ping_response['db']; |
1761
|
|
|
$device_perf['device_id'] = $device['device_id']; |
1762
|
|
|
$device_perf['timestamp'] = ['NOW()']; |
1763
|
|
|
$maintenance = DeviceCache::get($device['device_id'])->isUnderMaintenance(); |
1764
|
|
|
$consider_maintenance = Config::get('graphing.availability_consider_maintenance'); |
1765
|
|
|
$state_update_again = false; |
1766
|
|
|
|
1767
|
|
|
if ($record_perf === true && can_ping_device($device['attribs'])) { |
1768
|
|
|
$trace_debug = []; |
1769
|
|
|
if ($ping_response['result'] === false && Config::get('debug.run_trace', false)) { |
1770
|
|
|
$trace_debug = runTraceroute($device); |
1771
|
|
|
} |
1772
|
|
|
$device_perf['debug'] = json_encode($trace_debug); |
1773
|
|
|
dbInsert($device_perf, 'device_perf'); |
1774
|
|
|
|
1775
|
|
|
// if device_perf is inserted and the ping was successful then update device last_ping timestamp |
1776
|
|
|
if (! empty($ping_response['last_ping_timetaken']) && $ping_response['last_ping_timetaken'] != '0') { |
1777
|
|
|
dbUpdate( |
1778
|
|
|
['last_ping' => NOW(), 'last_ping_timetaken' => $ping_response['last_ping_timetaken']], |
1779
|
|
|
'devices', |
1780
|
|
|
'device_id=?', |
1781
|
|
|
[$device['device_id']] |
1782
|
|
|
); |
1783
|
|
|
} |
1784
|
|
|
} |
1785
|
|
|
$response = []; |
1786
|
|
|
$response['ping_time'] = $ping_response['last_ping_timetaken']; |
1787
|
|
|
if ($ping_response['result']) { |
1788
|
|
|
if ($device['snmp_disable'] || isSNMPable($device)) { |
1789
|
|
|
$response['status'] = '1'; |
1790
|
|
|
$response['status_reason'] = ''; |
1791
|
|
|
} else { |
1792
|
|
|
echo 'SNMP Unreachable'; |
1793
|
|
|
$response['status'] = '0'; |
1794
|
|
|
$response['status_reason'] = 'snmp'; |
1795
|
|
|
} |
1796
|
|
|
} else { |
1797
|
|
|
echo 'Unpingable'; |
1798
|
|
|
$response['status'] = '0'; |
1799
|
|
|
$response['status_reason'] = 'icmp'; |
1800
|
|
|
} |
1801
|
|
|
|
1802
|
|
|
// Special case where the device is still down, optional mode is on, device not in maintenance mode and has no ongoing outages |
1803
|
|
|
if (($consider_maintenance && ! $maintenance) && ($device['status'] == '0' && $response['status'] == '0')) { |
1804
|
|
|
$state_update_again = empty(dbFetchCell('SELECT going_down FROM device_outages WHERE device_id=? AND up_again IS NULL ORDER BY going_down DESC', [$device['device_id']])); |
1805
|
|
|
} |
1806
|
|
|
|
1807
|
|
|
if ($device['status'] != $response['status'] || $device['status_reason'] != $response['status_reason'] || $state_update_again) { |
1808
|
|
|
if (! $state_update_again) { |
1809
|
|
|
dbUpdate( |
1810
|
|
|
['status' => $response['status'], 'status_reason' => $response['status_reason']], |
1811
|
|
|
'devices', |
1812
|
|
|
'device_id=?', |
1813
|
|
|
[$device['device_id']] |
1814
|
|
|
); |
1815
|
|
|
} |
1816
|
|
|
|
1817
|
|
|
if ($response['status']) { |
1818
|
|
|
$type = 'up'; |
1819
|
|
|
$reason = $device['status_reason']; |
1820
|
|
|
|
1821
|
|
|
$going_down = dbFetchCell('SELECT going_down FROM device_outages WHERE device_id=? AND up_again IS NULL ORDER BY going_down DESC', [$device['device_id']]); |
1822
|
|
|
if (! empty($going_down)) { |
1823
|
|
|
$up_again = time(); |
1824
|
|
|
dbUpdate( |
1825
|
|
|
['device_id' => $device['device_id'], 'up_again' => $up_again], |
1826
|
|
|
'device_outages', |
1827
|
|
|
'device_id=? and going_down=? and up_again is NULL', |
1828
|
|
|
[$device['device_id'], $going_down] |
1829
|
|
|
); |
1830
|
|
|
} |
1831
|
|
|
} else { |
1832
|
|
|
$type = 'down'; |
1833
|
|
|
$reason = $response['status_reason']; |
1834
|
|
|
|
1835
|
|
|
if ($device['status'] != $response['status']) { |
1836
|
|
|
if (! $consider_maintenance || (! $maintenance && $consider_maintenance)) { |
1837
|
|
|
// use current time as a starting point when an outage starts |
1838
|
|
|
$data = ['device_id' => $device['device_id'], |
1839
|
|
|
'going_down' => time(), ]; |
1840
|
|
|
dbInsert($data, 'device_outages'); |
1841
|
|
|
} |
1842
|
|
|
} |
1843
|
|
|
} |
1844
|
|
|
|
1845
|
|
|
log_event('Device status changed to ' . ucfirst($type) . " from $reason check.", $device, $type); |
1846
|
|
|
} |
1847
|
|
|
|
1848
|
|
|
return $response; |
1849
|
|
|
} |
1850
|
|
|
|
1851
|
|
|
function update_device_logo(&$device) |
1852
|
|
|
{ |
1853
|
|
|
$icon = getImageName($device, false); |
1854
|
|
|
if ($icon != $device['icon']) { |
1855
|
|
|
log_event('Device Icon changed ' . $device['icon'] . " => $icon", $device, 'system', 3); |
1856
|
|
|
$device['icon'] = $icon; |
1857
|
|
|
dbUpdate(['icon' => $icon], 'devices', 'device_id=?', [$device['device_id']]); |
1858
|
|
|
echo "Changed Icon! : $icon\n"; |
1859
|
|
|
} |
1860
|
|
|
} |
1861
|
|
|
|
1862
|
|
|
/** |
1863
|
|
|
* Function to generate Mac OUI Cache |
1864
|
|
|
*/ |
1865
|
|
|
function cache_mac_oui() |
1866
|
|
|
{ |
1867
|
|
|
// timers: |
1868
|
|
|
$mac_oui_refresh_int_min = 86400 * rand(7, 11); // 7 days + a random number between 0 and 4 days |
1869
|
|
|
$mac_oui_cache_time = 1296000; // we keep data during 15 days maximum |
1870
|
|
|
|
1871
|
|
|
$lock = Cache::lock('macouidb-refresh', $mac_oui_refresh_int_min); //We want to refresh after at least $mac_oui_refresh_int_min |
1872
|
|
|
|
1873
|
|
|
if (Config::get('mac_oui.enabled') !== true) { |
1874
|
|
|
echo 'Mac OUI integration disabled' . PHP_EOL; |
1875
|
|
|
|
1876
|
|
|
return 0; |
1877
|
|
|
} |
1878
|
|
|
|
1879
|
|
|
if ($lock->get()) { |
1880
|
|
|
echo 'Caching Mac OUI' . PHP_EOL; |
1881
|
|
|
try { |
1882
|
|
|
$mac_oui_url = 'https://macaddress.io/database/macaddress.io-db.json'; |
1883
|
|
|
echo ' -> Downloading ...' . PHP_EOL; |
1884
|
|
|
$get = Requests::get($mac_oui_url, [], ['proxy' => get_proxy()]); |
1885
|
|
|
echo ' -> Processing ...' . PHP_EOL; |
1886
|
|
|
$json_data = $get->body; |
1887
|
|
|
foreach (explode("\n", $json_data) as $json_line) { |
1888
|
|
|
$entry = json_decode($json_line); |
1889
|
|
|
if ($entry && $entry->{'assignmentBlockSize'} == 'MA-L') { |
1890
|
|
|
$oui = strtolower(str_replace(':', '', $entry->{'oui'})); |
1891
|
|
|
$key = 'OUIDB-' . $oui; |
1892
|
|
|
Cache::put($key, $entry->{'companyName'}, $mac_oui_cache_time); |
1893
|
|
|
} |
1894
|
|
|
} |
1895
|
|
|
} catch (Exception $e) { |
1896
|
|
|
echo 'Error processing Mac OUI :' . PHP_EOL; |
1897
|
|
|
echo 'Exception: ' . get_class($e) . PHP_EOL; |
1898
|
|
|
echo $e->getMessage() . PHP_EOL; |
1899
|
|
|
|
1900
|
|
|
$lock->release(); // we did not succeed so we'll try again next time |
1901
|
|
|
|
1902
|
|
|
return 1; |
1903
|
|
|
} |
1904
|
|
|
} |
1905
|
|
|
|
1906
|
|
|
return 0; |
1907
|
|
|
} |
1908
|
|
|
|
1909
|
|
|
/** |
1910
|
|
|
* Function to generate PeeringDB Cache |
1911
|
|
|
*/ |
1912
|
|
|
function cache_peeringdb() |
1913
|
|
|
{ |
1914
|
|
|
if (Config::get('peeringdb.enabled') === true) { |
1915
|
|
|
$peeringdb_url = 'https://peeringdb.com/api'; |
1916
|
|
|
// We cache for 71 hours |
1917
|
|
|
$cached = dbFetchCell('SELECT count(*) FROM `pdb_ix` WHERE (UNIX_TIMESTAMP() - timestamp) < 255600'); |
1918
|
|
|
if ($cached == 0) { |
1919
|
|
|
$rand = rand(3, 30); |
1920
|
|
|
echo "No cached PeeringDB data found, sleeping for $rand seconds" . PHP_EOL; |
1921
|
|
|
sleep($rand); |
1922
|
|
|
$peer_keep = []; |
1923
|
|
|
$ix_keep = []; |
1924
|
|
|
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) { |
1925
|
|
|
$asn = $as['bgpLocalAs']; |
1926
|
|
|
$get = Requests::get($peeringdb_url . '/net?depth=2&asn=' . $asn, [], ['proxy' => get_proxy()]); |
1927
|
|
|
$json_data = $get->body; |
1928
|
|
|
$data = json_decode($json_data); |
1929
|
|
|
$ixs = $data->{'data'}[0]->{'netixlan_set'}; |
1930
|
|
|
foreach ($ixs as $ix) { |
1931
|
|
|
$ixid = $ix->{'ix_id'}; |
1932
|
|
|
$tmp_ix = dbFetchRow('SELECT * FROM `pdb_ix` WHERE `ix_id` = ? AND asn = ?', [$ixid, $asn]); |
1933
|
|
|
if ($tmp_ix) { |
1934
|
|
|
$pdb_ix_id = $tmp_ix['pdb_ix_id']; |
1935
|
|
|
$update = ['name' => $ix->{'name'}, 'timestamp' => time()]; |
1936
|
|
|
dbUpdate($update, 'pdb_ix', '`ix_id` = ? AND `asn` = ?', [$ixid, $asn]); |
1937
|
|
|
} else { |
1938
|
|
|
$insert = [ |
1939
|
|
|
'ix_id' => $ixid, |
1940
|
|
|
'name' => $ix->{'name'}, |
1941
|
|
|
'asn' => $asn, |
1942
|
|
|
'timestamp' => time(), |
1943
|
|
|
]; |
1944
|
|
|
$pdb_ix_id = dbInsert($insert, 'pdb_ix'); |
1945
|
|
|
} |
1946
|
|
|
$ix_keep[] = $pdb_ix_id; |
1947
|
|
|
$get_ix = Requests::get("$peeringdb_url/netixlan?ix_id=$ixid", [], ['proxy' => get_proxy()]); |
1948
|
|
|
$ix_json = $get_ix->body; |
1949
|
|
|
$ix_data = json_decode($ix_json); |
1950
|
|
|
$peers = $ix_data->{'data'}; |
1951
|
|
|
foreach ($peers as $index => $peer) { |
1952
|
|
|
$peer_name = get_astext($peer->{'asn'}); |
1953
|
|
|
$tmp_peer = dbFetchRow('SELECT * FROM `pdb_ix_peers` WHERE `peer_id` = ? AND `ix_id` = ?', [$peer->{'id'}, $ixid]); |
1954
|
|
|
if ($tmp_peer) { |
1955
|
|
|
$peer_keep[] = $tmp_peer['pdb_ix_peers_id']; |
1956
|
|
|
$update = [ |
1957
|
|
|
'remote_asn' => $peer->{'asn'}, |
1958
|
|
|
'remote_ipaddr4' => $peer->{'ipaddr4'}, |
1959
|
|
|
'remote_ipaddr6' => $peer->{'ipaddr6'}, |
1960
|
|
|
'name' => $peer_name, |
1961
|
|
|
]; |
1962
|
|
|
dbUpdate($update, 'pdb_ix_peers', '`pdb_ix_peers_id` = ?', [$tmp_peer['pdb_ix_peers_id']]); |
1963
|
|
|
} else { |
1964
|
|
|
$peer_insert = [ |
1965
|
|
|
'ix_id' => $ixid, |
1966
|
|
|
'peer_id' => $peer->{'id'}, |
1967
|
|
|
'remote_asn' => $peer->{'asn'}, |
1968
|
|
|
'remote_ipaddr4' => $peer->{'ipaddr4'}, |
1969
|
|
|
'remote_ipaddr6' => $peer->{'ipaddr6'}, |
1970
|
|
|
'name' => $peer_name, |
1971
|
|
|
'timestamp' => time(), |
1972
|
|
|
]; |
1973
|
|
|
$peer_keep[] = dbInsert($peer_insert, 'pdb_ix_peers'); |
1974
|
|
|
} |
1975
|
|
|
} |
1976
|
|
|
} |
1977
|
|
|
} |
1978
|
|
|
|
1979
|
|
|
// cleanup |
1980
|
|
|
if (empty($peer_keep)) { |
1981
|
|
|
dbDelete('pdb_ix_peers'); |
1982
|
|
|
} else { |
1983
|
|
|
dbDelete('pdb_ix_peers', '`pdb_ix_peers_id` NOT IN ' . dbGenPlaceholders(count($peer_keep)), $peer_keep); |
1984
|
|
|
} |
1985
|
|
|
if (empty($ix_keep)) { |
1986
|
|
|
dbDelete('pdb_ix'); |
1987
|
|
|
} else { |
1988
|
|
|
dbDelete('pdb_ix', '`pdb_ix_id` NOT IN ' . dbGenPlaceholders(count($ix_keep)), $ix_keep); |
1989
|
|
|
} |
1990
|
|
|
} else { |
1991
|
|
|
echo 'Cached PeeringDB data found.....' . PHP_EOL; |
1992
|
|
|
} |
1993
|
|
|
} else { |
1994
|
|
|
echo 'Peering DB integration disabled' . PHP_EOL; |
1995
|
|
|
} |
1996
|
|
|
} |
1997
|
|
|
|
1998
|
|
|
/** |
1999
|
|
|
* Get an array of the schema files. |
2000
|
|
|
* schema_version => full_file_name |
2001
|
|
|
* |
2002
|
|
|
* @return mixed |
2003
|
|
|
*/ |
2004
|
|
|
function get_schema_list() |
2005
|
|
|
{ |
2006
|
|
|
// glob returns an array sorted by filename |
2007
|
|
|
$files = glob(Config::get('install_dir') . '/sql-schema/*.sql'); |
2008
|
|
|
|
2009
|
|
|
// set the keys to the db schema version |
2010
|
|
|
$files = array_reduce($files, function ($array, $file) { |
2011
|
|
|
$array[(int) basename($file, '.sql')] = $file; |
2012
|
|
|
|
2013
|
|
|
return $array; |
2014
|
|
|
}, []); |
2015
|
|
|
|
2016
|
|
|
ksort($files); // fix dbSchema 1000 order |
2017
|
|
|
|
2018
|
|
|
return $files; |
2019
|
|
|
} |
2020
|
|
|
|
2021
|
|
|
/** |
2022
|
|
|
* @param $device |
2023
|
|
|
* @return int|null |
2024
|
|
|
*/ |
2025
|
|
|
function get_device_oid_limit($device) |
2026
|
|
|
{ |
2027
|
|
|
// device takes priority |
2028
|
|
|
if (! empty($device['attribs']['snmp_max_oid'])) { |
2029
|
|
|
return $device['attribs']['snmp_max_oid']; |
2030
|
|
|
} |
2031
|
|
|
|
2032
|
|
|
// then os |
2033
|
|
|
$os_max = Config::getOsSetting($device['os'], 'snmp_max_oid', 0); |
2034
|
|
|
if ($os_max > 0) { |
2035
|
|
|
return $os_max; |
2036
|
|
|
} |
2037
|
|
|
|
2038
|
|
|
// then global |
2039
|
|
|
$global_max = Config::get('snmp.max_oid', 10); |
2040
|
|
|
|
2041
|
|
|
return $global_max > 0 ? $global_max : 10; |
2042
|
|
|
} |
2043
|
|
|
|
2044
|
|
|
/** |
2045
|
|
|
* If Distributed, create a lock, then purge the mysql table |
2046
|
|
|
* |
2047
|
|
|
* @param string $table |
2048
|
|
|
* @param string $sql |
2049
|
|
|
* @return int exit code |
2050
|
|
|
*/ |
2051
|
|
|
function lock_and_purge($table, $sql) |
2052
|
|
|
{ |
2053
|
|
|
$purge_name = $table . '_purge'; |
2054
|
|
|
$lock = Cache::lock($purge_name, 86000); |
2055
|
|
|
if ($lock->get()) { |
2056
|
|
|
$purge_days = Config::get($purge_name); |
2057
|
|
|
|
2058
|
|
|
$name = str_replace('_', ' ', ucfirst($table)); |
2059
|
|
|
if (is_numeric($purge_days)) { |
2060
|
|
|
if (dbDelete($table, $sql, [$purge_days])) { |
2061
|
|
|
echo "$name cleared for entries over $purge_days days\n"; |
2062
|
|
|
} |
2063
|
|
|
} |
2064
|
|
|
$lock->release(); |
2065
|
|
|
|
2066
|
|
|
return 0; |
2067
|
|
|
} |
2068
|
|
|
|
2069
|
|
|
return -1; |
2070
|
|
|
} |
2071
|
|
|
|
2072
|
|
|
/** |
2073
|
|
|
* If Distributed, create a lock, then purge the mysql table according to the sql query |
2074
|
|
|
* |
2075
|
|
|
* @param string $table |
2076
|
|
|
* @param string $sql |
2077
|
|
|
* @param string $msg |
2078
|
|
|
* @return int exit code |
2079
|
|
|
*/ |
2080
|
|
|
function lock_and_purge_query($table, $sql, $msg) |
2081
|
|
|
{ |
2082
|
|
|
$purge_name = $table . '_purge'; |
2083
|
|
|
|
2084
|
|
|
$purge_duration = Config::get($purge_name); |
2085
|
|
|
if (! (is_numeric($purge_duration) && $purge_duration > 0)) { |
2086
|
|
|
return -2; |
2087
|
|
|
} |
2088
|
|
|
$lock = Cache::lock($purge_name, 86000); |
2089
|
|
|
if ($lock->get()) { |
2090
|
|
|
if (dbQuery($sql, [$purge_duration])) { |
2091
|
|
|
printf($msg, $purge_duration); |
2092
|
|
|
} |
2093
|
|
|
$lock->release(); |
2094
|
|
|
|
2095
|
|
|
return 0; |
2096
|
|
|
} |
2097
|
|
|
|
2098
|
|
|
return -1; |
2099
|
|
|
} |
2100
|
|
|
|
2101
|
|
|
/** |
2102
|
|
|
* Check if disk is valid to poll. |
2103
|
|
|
* Settings: bad_disk_regexp |
2104
|
|
|
* |
2105
|
|
|
* @param array $disk |
2106
|
|
|
* @param array $device |
2107
|
|
|
* @return bool |
2108
|
|
|
*/ |
2109
|
|
|
function is_disk_valid($disk, $device) |
2110
|
|
|
{ |
2111
|
|
|
foreach (Config::getCombined($device['os'], 'bad_disk_regexp') as $bir) { |
2112
|
|
|
if (preg_match($bir . 'i', $disk['diskIODevice'])) { |
2113
|
|
|
d_echo("Ignored Disk: {$disk['diskIODevice']} (matched: $bir)\n"); |
2114
|
|
|
|
2115
|
|
|
return false; |
2116
|
|
|
} |
2117
|
|
|
} |
2118
|
|
|
|
2119
|
|
|
return true; |
2120
|
|
|
} |
2121
|
|
|
|
2122
|
|
|
/** |
2123
|
|
|
* Queues a hostname to be refreshed by Oxidized |
2124
|
|
|
* Settings: oxidized.url |
2125
|
|
|
* |
2126
|
|
|
* @param string $hostname |
2127
|
|
|
* @param string $msg |
2128
|
|
|
* @param string $username |
2129
|
|
|
* @return bool |
2130
|
|
|
*/ |
2131
|
|
|
function oxidized_node_update($hostname, $msg, $username = 'not_provided') |
2132
|
|
|
{ |
2133
|
|
|
// Work around https://github.com/rack/rack/issues/337 |
2134
|
|
|
$msg = str_replace('%', '', $msg); |
2135
|
|
|
$postdata = ['user' => $username, 'msg' => $msg]; |
2136
|
|
|
$oxidized_url = Config::get('oxidized.url'); |
2137
|
|
|
if (! empty($oxidized_url)) { |
2138
|
|
|
Requests::put("$oxidized_url/node/next/$hostname", [], json_encode($postdata), ['proxy' => get_proxy()]); |
2139
|
|
|
|
2140
|
|
|
return true; |
2141
|
|
|
} |
2142
|
|
|
|
2143
|
|
|
return false; |
2144
|
|
|
}//end oxidized_node_update() |
2145
|
|
|
|
2146
|
|
|
/** |
2147
|
|
|
* @params int code |
2148
|
|
|
* @params int subcode |
2149
|
|
|
* |
2150
|
|
|
* @return string |
2151
|
|
|
* Take a BGP error code and subcode to return a string representation of it |
2152
|
|
|
*/ |
2153
|
|
|
function describe_bgp_error_code($code, $subcode) |
2154
|
|
|
{ |
2155
|
|
|
// https://www.iana.org/assignments/bgp-parameters/bgp-parameters.xhtml#bgp-parameters-3 |
2156
|
|
|
|
2157
|
|
|
$message = 'Unknown'; |
2158
|
|
|
|
2159
|
|
|
$error_code_key = 'bgp.error_codes.' . $code; |
2160
|
|
|
$error_subcode_key = 'bgp.error_subcodes.' . $code . '.' . $subcode; |
2161
|
|
|
|
2162
|
|
|
$error_code_message = __($error_code_key); |
2163
|
|
|
$error_subcode_message = __($error_subcode_key); |
2164
|
|
|
|
2165
|
|
|
if ($error_subcode_message != $error_subcode_key) { |
2166
|
|
|
$message = $error_code_message . ' - ' . $error_subcode_message; |
2167
|
|
|
} elseif ($error_code_message != $error_code_key) { |
2168
|
|
|
$message = $error_code_message; |
2169
|
|
|
} |
2170
|
|
|
|
2171
|
|
|
return $message; |
2172
|
|
|
} |
2173
|
|
|
|