forked from librenms/librenms
/
functions.php
2646 lines (2335 loc) · 82.2 KB
/
functions.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* LibreNMS
*
* This file is part of LibreNMS.
*
* @package LibreNMS
* @subpackage functions
* @copyright (C) 2006 - 2012 Adam Armstrong
*
*/
use Illuminate\Database\Events\QueryExecuted;
use LibreNMS\Authentication\LegacyAuth;
use LibreNMS\Config;
use LibreNMS\Exceptions\HostExistsException;
use LibreNMS\Exceptions\HostIpExistsException;
use LibreNMS\Exceptions\HostUnreachableException;
use LibreNMS\Exceptions\HostUnreachablePingException;
use LibreNMS\Exceptions\InvalidPortAssocModeException;
use LibreNMS\Exceptions\LockException;
use LibreNMS\Exceptions\SnmpVersionUnsupportedException;
use LibreNMS\Util\IPv4;
use LibreNMS\Util\IPv6;
use LibreNMS\Util\MemcacheLock;
use Symfony\Component\Process\Process;
use PHPMailer\PHPMailer\PHPMailer;
if (!function_exists('set_debug')) {
/**
* Set debugging output
*
* @param bool $state If debug is enabled or not
* @param bool $silence When not debugging, silence every php error
* @return bool
*/
function set_debug($state = true, $silence = false)
{
global $debug;
$debug = $state; // set to global
restore_error_handler(); // disable Laravel error handler
if (isset($debug) && $debug) {
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
ini_set('log_errors', 0);
error_reporting(E_ALL & ~E_NOTICE);
\LibreNMS\Util\Laravel::enableCliDebugOutput();
\LibreNMS\Util\Laravel::enableQueryDebug();
} else {
ini_set('display_errors', 0);
ini_set('display_startup_errors', 0);
ini_set('log_errors', 1);
error_reporting($silence ? 0 : E_ERROR);
\LibreNMS\Util\Laravel::disableCliDebugOutput();
\LibreNMS\Util\Laravel::disableQueryDebug();
}
return $debug;
}
}//end set_debug()
function array_sort_by_column($array, $on, $order = SORT_ASC)
{
$new_array = array();
$sortable_array = array();
if (count($array) > 0) {
foreach ($array as $k => $v) {
if (is_array($v)) {
foreach ($v as $k2 => $v2) {
if ($k2 == $on) {
$sortable_array[$k] = $v2;
}
}
} else {
$sortable_array[$k] = $v;
}
}
switch ($order) {
case SORT_ASC:
asort($sortable_array);
break;
case SORT_DESC:
arsort($sortable_array);
break;
}
foreach ($sortable_array as $k => $v) {
$new_array[$k] = $array[$k];
}
}
return $new_array;
}
function mac_clean_to_readable($mac)
{
return \LibreNMS\Util\Rewrite::readableMac($mac);
}
function only_alphanumeric($string)
{
return preg_replace('/[^a-zA-Z0-9]/', '', $string);
}
/**
* Parse cli discovery or poller modules and set config for this run
*
* @param string $type discovery or poller
* @param array $options get_opts array (only m key is checked)
* @return bool
*/
function parse_modules($type, $options)
{
$override = false;
if ($options['m']) {
Config::set("{$type}_modules", []);
foreach (explode(',', $options['m']) as $module) {
// parse submodules (only supported by some modules)
if (str_contains($module, '/')) {
list($module, $submodule) = explode('/', $module, 2);
$existing_submodules = Config::get("{$type}_submodules.$module", []);
$existing_submodules[] = $submodule;
Config::set("{$type}_submodules.$module", $existing_submodules);
}
$dir = $type == 'poller' ? 'polling' : $type;
if (is_file("includes/$dir/$module.inc.php")) {
Config::set("{$type}_modules.$module", 1);
$override = true;
}
}
// display selected modules
$modules = array_map(function ($module) use ($type) {
$submodules = Config::get("{$type}_submodules.$module");
return $module . ($submodules ? '(' . implode(',', $submodules) . ')' : '');
}, array_keys(Config::get("{$type}_modules", [])));
d_echo("Override $type modules: " . implode(', ', $modules) . PHP_EOL);
}
return $override;
}
function logfile($string)
{
global $config;
$fd = fopen($config['log_file'], 'a');
fputs($fd, $string . "\n");
fclose($fd);
}
/**
* Detect the os of the given device.
*
* @param array $device device to check
* @return string the name of the os
*/
function getHostOS($device)
{
$device['sysDescr'] = snmp_get($device, "SNMPv2-MIB::sysDescr.0", "-Ovq");
$device['sysObjectID'] = snmp_get($device, "SNMPv2-MIB::sysObjectID.0", "-Ovqn");
d_echo("| {$device['sysDescr']} | {$device['sysObjectID']} | \n");
$deferred_os = array(
'freebsd',
'linux',
);
// check yaml files
$os_defs = Config::get('os');
foreach ($os_defs as $os => $def) {
if (isset($def['discovery']) && !in_array($os, $deferred_os)) {
foreach ($def['discovery'] as $item) {
if (checkDiscovery($device, $item)) {
return $os;
}
}
}
}
// check include files
$os = null;
$pattern = Config::get('install_dir') . '/includes/discovery/os/*.inc.php';
foreach (glob($pattern) as $file) {
include $file;
if (isset($os)) {
return $os;
}
}
// check deferred os
foreach ($deferred_os as $os) {
if (isset($os_defs[$os]['discovery'])) {
foreach ($os_defs[$os]['discovery'] as $item) {
if (checkDiscovery($device, $item)) {
return $os;
}
}
}
}
return 'generic';
}
/**
* Check an array of conditions if all match, return true
* sysObjectID if sysObjectID starts with any of the values under this item
* sysDescr if sysDescr contains any of the values under this item
* sysDescr_regex if sysDescr matches any of the regexes under this item
* snmpget perform an snmpget on `oid` and check if the result contains `value`. Other subkeys: options, mib, mibdir
*
* Appending _except to any condition will invert the match.
*
* @param array $device
* @param array $array Array of items, keys should be sysObjectID, sysDescr, or sysDescr_regex
* @return bool the result (all items passed return true)
*/
function checkDiscovery($device, $array)
{
// all items must be true
foreach ($array as $key => $value) {
if ($check = ends_with($key, '_except')) {
$key = substr($key, 0, -7);
}
if ($key == 'sysObjectID') {
if (starts_with($device['sysObjectID'], $value) == $check) {
return false;
}
} elseif ($key == 'sysDescr') {
if (str_contains($device['sysDescr'], $value) == $check) {
return false;
}
} elseif ($key == 'sysDescr_regex') {
if (preg_match_any($device['sysDescr'], $value) == $check) {
return false;
}
} elseif ($key == 'sysObjectID_regex') {
if (preg_match_any($device['sysObjectID'], $value) == $check) {
return false;
}
} elseif ($key == 'snmpget') {
$options = isset($value['options']) ? $value['options'] : '-Oqv';
$mib = isset($value['mib']) ? $value['mib'] : null;
$mib_dir = isset($value['mib_dir']) ? $value['mib_dir'] : null;
$op = isset($value['op']) ? $value['op'] : 'contains';
$get_value = snmp_get($device, $value['oid'], $options, $mib, $mib_dir);
if (compare_var($get_value, $value['value'], $op) == $check) {
return false;
}
}
}
return true;
}
/**
* Check an array of regexes against a subject if any match, return true
*
* @param string $subject the string to match against
* @param array|string $regexes an array of regexes or single regex to check
* @return bool if any of the regexes matched, return true
*/
function preg_match_any($subject, $regexes)
{
foreach ((array)$regexes as $regex) {
if (preg_match($regex, $subject)) {
return true;
}
}
return false;
}
/**
* Perform comparison of two items based on give comparison method
* Valid comparisons: =, !=, ==, !==, >=, <=, >, <, contains, starts, ends, regex
* contains, starts, ends: $a haystack, $b needle(s)
* regex: $a subject, $b regex
*
* @param mixed $a
* @param mixed $b
* @param string $comparison =, !=, ==, !== >=, <=, >, <, contains, starts, ends, regex
* @return bool
*/
function compare_var($a, $b, $comparison = '=')
{
switch ($comparison) {
case "=":
return $a == $b;
case "!=":
return $a != $b;
case "==":
return $a === $b;
case "!==":
return $a !== $b;
case ">=":
return $a >= $b;
case "<=":
return $a <= $b;
case ">":
return $a > $b;
case "<":
return $a < $b;
case "contains":
return str_contains($a, $b);
case "starts":
return starts_with($a, $b);
case "ends":
return ends_with($a, $b);
case "regex":
return (bool)preg_match($b, $a);
default:
return false;
}
}
function percent_colour($perc)
{
$r = min(255, 5 * ($perc - 25));
$b = max(0, 255 - (5 * ($perc + 25)));
return sprintf('#%02x%02x%02x', $r, $b, $b);
}
// Returns the last in/out errors value in RRD
function interface_errors($rrd_file, $period = '-1d')
{
global $config;
$errors = array();
$cmd = $config['rrdtool']." fetch -s $period -e -300s $rrd_file AVERAGE | grep : | cut -d\" \" -f 4,5";
$data = trim(shell_exec($cmd));
$in_errors = 0;
$out_errors = 0;
foreach (explode("\n", $data) as $entry) {
list($in, $out) = explode(" ", $entry);
$in_errors += ($in * 300);
$out_errors += ($out * 300);
}
$errors['in'] = round($in_errors);
$errors['out'] = round($out_errors);
return $errors;
}
/**
* @param $device
* @return string the logo image path for this device. Images are often wide, not square.
*/
function getLogo($device)
{
$img = getImageName($device, true, 'images/logos/');
if (!starts_with($img, 'generic')) {
return 'images/logos/' . $img;
}
return getIcon($device);
}
/**
* @param array $device
* @param string $class to apply to the image tag
* @return string an image tag with the logo for this device. Images are often wide, not square.
*/
function getLogoTag($device, $class = null)
{
$tag = '<img src="' . getLogo($device) . '" title="' . getImageTitle($device) . '"';
if (isset($class)) {
$tag .= " class=\"$class\" ";
}
$tag .= ' />';
return $tag;
}
/**
* @param $device
* @return string the path to the icon image for this device. Close to square.
*/
function getIcon($device)
{
return 'images/os/' . getImageName($device);
}
/**
* @param $device
* @return string an image tag with the icon for this device. Close to square.
*/
function getIconTag($device)
{
return '<img src="' . getIcon($device) . '" title="' . getImageTitle($device) . '"/>';
}
function getImageTitle($device)
{
return $device['icon'] ? str_replace(array('.svg', '.png'), '', $device['icon']) : $device['os'];
}
function getImageName($device, $use_database = true, $dir = 'images/os/')
{
global $config;
$os = strtolower($device['os']);
// fetch from the database
if ($use_database && is_file($config['html_dir'] . "/$dir" . $device['icon'])) {
return $device['icon'];
}
// linux specific handling, distro icons
$distro = null;
if ($os == "linux") {
$features = strtolower(trim($device['features']));
list($distro) = explode(" ", $features);
}
$possibilities = array(
$distro,
$config['os'][$os]['icon'],
$os,
);
foreach ($possibilities as $basename) {
foreach (array('.svg', '.png') as $ext) {
$name = $basename . $ext;
if (is_file($config['html_dir'] . "/$dir" . $name)) {
return $name;
}
}
}
// fallback to the generic icon
return 'generic.svg';
}
function renamehost($id, $new, $source = 'console')
{
$host = gethostbyid($id);
if (!is_dir(get_rrd_dir($new)) && rename(get_rrd_dir($host), get_rrd_dir($new)) === 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 delete_device($id)
{
global $config, $debug;
if (isCli() === false) {
ignore_user_abort(true);
set_time_limit(0);
}
$ret = '';
$host = dbFetchCell("SELECT hostname FROM devices WHERE device_id = ?", array($id));
if (empty($host)) {
return "No such host.";
}
// Remove IPv4/IPv6 addresses before removing ports as they depend on port_id
dbQuery("DELETE `ipv4_addresses` FROM `ipv4_addresses` INNER JOIN `ports` ON `ports`.`port_id`=`ipv4_addresses`.`port_id` WHERE `device_id`=?", array($id));
dbQuery("DELETE `ipv6_addresses` FROM `ipv6_addresses` INNER JOIN `ports` ON `ports`.`port_id`=`ipv6_addresses`.`port_id` WHERE `device_id`=?", array($id));
foreach (dbFetch("SELECT * FROM `ports` WHERE `device_id` = ?", array($id)) as $int_data) {
$int_if = $int_data['ifDescr'];
$int_id = $int_data['port_id'];
delete_port($int_id);
$ret .= "Removed interface $int_id ($int_if)\n";
}
// Remove sensors manually due to constraints
foreach (dbFetchRows("SELECT * FROM `sensors` WHERE `device_id` = ?", array($id)) as $sensor) {
$sensor_id = $sensor['sensor_id'];
dbDelete('sensors_to_state_indexes', "`sensor_id` = ?", array($sensor_id));
}
$fields = array('device_id','host');
$db_name = dbFetchCell('SELECT DATABASE()');
foreach ($fields as $field) {
foreach (dbFetch("SELECT table_name FROM information_schema.columns WHERE table_schema = ? AND column_name = ?", [$db_name, $field]) as $table) {
$table = $table['table_name'];
$entries = (int) dbDelete($table, "`$field` = ?", array($id));
if ($entries > 0 && $debug === true) {
$ret .= "$field@$table = #$entries\n";
}
}
}
$ex = shell_exec("bash -c '( [ ! -d ".trim(get_rrd_dir($host))." ] || rm -vrf ".trim(get_rrd_dir($host))." 2>&1 ) && echo -n OK'");
$tmp = explode("\n", $ex);
if ($tmp[sizeof($tmp)-1] != "OK") {
$ret .= "Could not remove files:\n$ex\n";
}
$ret .= "Removed device $host\n";
log_event("Device $host has been removed", 0, 'system', 3);
oxidized_reload_nodes();
return $ret;
}
/**
* Add a device to LibreNMS
*
* @param string $host dns name or ip address
* @param string $snmp_version If this is empty, try v2c,v3,v1. Otherwise, use this specific version.
* @param string $port the port to connect to for snmp
* @param string $transport udp or tcp
* @param string $poller_group the poller group this device will belong to
* @param boolean $force_add add even if the device isn't reachable
* @param string $port_assoc_mode snmp field to use to determine unique ports
* @param array $additional an array with additional parameters to take into consideration when adding devices
*
* @return int returns the device_id of the added device
*
* @throws HostExistsException This hostname already exists
* @throws HostIpExistsException We already have a host with this IP
* @throws HostUnreachableException We could not reach this device is some way
* @throws HostUnreachablePingException We could not ping the device
* @throws InvalidPortAssocModeException The given port association mode was invalid
* @throws SnmpVersionUnsupportedException The given snmp version was invalid
*/
function addHost($host, $snmp_version = '', $port = '161', $transport = 'udp', $poller_group = '0', $force_add = false, $port_assoc_mode = 'ifIndex', $additional = array())
{
global $config;
// Test Database Exists
if (host_exists($host)) {
throw new HostExistsException("Already have host $host");
}
// Valid port assoc mode
if (!in_array($port_assoc_mode, get_port_assoc_modes())) {
throw new InvalidPortAssocModeException("Invalid port association_mode '$port_assoc_mode'. Valid modes are: " . join(', ', get_port_assoc_modes()));
}
// check if we have the host by IP
if ($config['addhost_alwayscheckip'] === true) {
$ip = gethostbyname($host);
} else {
$ip = $host;
}
if ($force_add !== true && $device = device_has_ip($ip)) {
$message = "Cannot add $host, already have device with this IP $ip";
if ($ip != $device->hostname) {
$message .= " ($device->hostname)";
}
$message .= '. You may force add to ignore this.';
throw new HostIpExistsException($message);
}
// Test reachability
if (!$force_add) {
$address_family = snmpTransportToAddressFamily($transport);
$ping_result = isPingable($host, $address_family);
if (!$ping_result['result']) {
throw new HostUnreachablePingException("Could not ping $host");
}
}
// if $snmpver isn't set, try each version of snmp
if (empty($snmp_version)) {
$snmpvers = Config::get('snmp.version');
} else {
$snmpvers = array($snmp_version);
}
if (isset($additional['snmp_disable']) && $additional['snmp_disable'] == 1) {
return createHost($host, '', $snmp_version, $port, $transport, array(), $poller_group, 1, true, $additional);
}
$host_unreachable_exception = new HostUnreachableException("Could not connect to $host, please check the snmp details and snmp reachability");
// try different snmp variables to add the device
foreach ($snmpvers as $snmpver) {
if ($snmpver === "v3") {
// Try each set of parameters from config
foreach ($config['snmp']['v3'] as $v3) {
$device = deviceArray($host, null, $snmpver, $port, $transport, $v3, $port_assoc_mode);
if ($force_add === true || isSNMPable($device)) {
return createHost($host, null, $snmpver, $port, $transport, $v3, $poller_group, $port_assoc_mode, $force_add);
} else {
$host_unreachable_exception->addReason("SNMP $snmpver: No reply with credentials " . $v3['authname'] . "/" . $v3['authlevel']);
}
}
} elseif ($snmpver === "v2c" || $snmpver === "v1") {
// try each community from config
foreach ($config['snmp']['community'] as $community) {
$device = deviceArray($host, $community, $snmpver, $port, $transport, null, $port_assoc_mode);
if ($force_add === true || isSNMPable($device)) {
return createHost($host, $community, $snmpver, $port, $transport, array(), $poller_group, $port_assoc_mode, $force_add);
} else {
$host_unreachable_exception->addReason("SNMP $snmpver: No reply with community $community");
}
}
} else {
throw new SnmpVersionUnsupportedException("Unsupported SNMP Version \"$snmpver\", must be v1, v2c, or v3");
}
}
if (isset($additional['ping_fallback']) && $additional['ping_fallback'] == 1) {
$additional['snmp_disable'] = 1;
$additional['os'] = "ping";
return createHost($host, '', $snmp_version, $port, $transport, array(), $poller_group, 1, true, $additional);
}
throw $host_unreachable_exception;
}
function deviceArray($host, $community, $snmpver, $port = 161, $transport = 'udp', $v3 = array(), $port_assoc_mode = 'ifIndex')
{
$device = array();
$device['hostname'] = $host;
$device['port'] = $port;
$device['transport'] = $transport;
/* Get port_assoc_mode id if neccessary
* We can work with names of IDs here */
if (! is_int($port_assoc_mode)) {
$port_assoc_mode = get_port_assoc_mode_id($port_assoc_mode);
}
$device['port_association_mode'] = $port_assoc_mode;
$device['snmpver'] = $snmpver;
if ($snmpver === "v2c" or $snmpver === "v1") {
$device['community'] = $community;
} elseif ($snmpver === "v3") {
$device['authlevel'] = $v3['authlevel'];
$device['authname'] = $v3['authname'];
$device['authpass'] = $v3['authpass'];
$device['authalgo'] = $v3['authalgo'];
$device['cryptopass'] = $v3['cryptopass'];
$device['cryptoalgo'] = $v3['cryptoalgo'];
}
return $device;
}
function formatUptime($diff, $format = "long")
{
$yearsDiff = floor($diff/31536000);
$diff -= $yearsDiff*31536000;
$daysDiff = floor($diff/86400);
$diff -= $daysDiff*86400;
$hrsDiff = floor($diff/60/60);
$diff -= $hrsDiff*60*60;
$minsDiff = floor($diff/60);
$diff -= $minsDiff*60;
$secsDiff = $diff;
$uptime = "";
if ($format == "short") {
if ($yearsDiff > '0') {
$uptime .= $yearsDiff . "y ";
}
if ($daysDiff > '0') {
$uptime .= $daysDiff . "d ";
}
if ($hrsDiff > '0') {
$uptime .= $hrsDiff . "h ";
}
if ($minsDiff > '0') {
$uptime .= $minsDiff . "m ";
}
if ($secsDiff > '0') {
$uptime .= $secsDiff . "s ";
}
} else {
if ($yearsDiff > '0') {
$uptime .= $yearsDiff . " years, ";
}
if ($daysDiff > '0') {
$uptime .= $daysDiff . " day" . ($daysDiff != 1 ? 's' : '') . ", ";
}
if ($hrsDiff > '0') {
$uptime .= $hrsDiff . "h ";
}
if ($minsDiff > '0') {
$uptime .= $minsDiff . "m ";
}
if ($secsDiff > '0') {
$uptime .= $secsDiff . "s ";
}
}
return trim($uptime);
}
function isSNMPable($device)
{
global $config;
$pos = snmp_check($device);
if ($pos === true) {
return true;
} else {
$pos = snmp_get($device, "sysObjectID.0", "-Oqv", "SNMPv2-MIB");
if ($pos === '' || $pos === false) {
return false;
} else {
return true;
}
}
}
/**
* Check if the given host responds to ICMP echo requests ("pings").
*
* @param string $hostname The hostname or IP address to send ping requests to.
* @param string $address_family The address family ('ipv4' or 'ipv6') to use. Defaults to IPv4.
* 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.
* @param array $attribs The device attributes
*
* @return array 'result' => bool pingable, 'last_ping_timetaken' => int time for last ping, 'db' => fping results
*/
function isPingable($hostname, $address_family = 'ipv4', $attribs = [])
{
if (can_ping_device($attribs) !== true) {
return [
'result' => true,
'last_ping_timetaken' => 0
];
}
$status = fping(
$hostname,
Config::get('fping_options.count', 3),
Config::get('fping_options.interval', 500),
Config::get('fping_options.timeout', 500),
$address_family
);
return [
'result' => ($status['exitcode'] == 0 && $status['loss'] < 100),
'last_ping_timetaken' => $status['avg'],
'db' => array_intersect_key($status, array_flip(['xmt','rcv','loss','min','max','avg']))
];
}
function getpollergroup($poller_group = '0')
{
//Is poller group an integer
if (is_int($poller_group) || ctype_digit($poller_group)) {
return $poller_group;
} else {
//Check if it contains a comma
if (strpos($poller_group, ',')!== false) {
//If it has a comma use the first element as the poller group
$poller_group_array=explode(',', $poller_group);
return getpollergroup($poller_group_array[0]);
} else {
if ($config['distributed_poller_group']) {
//If not use the poller's group from the config
return getpollergroup($config['distributed_poller_group']);
} else {
//If all else fails use default
return '0';
}
}
}
}
/**
* Add a host to the database
*
* @param string $host The IP or hostname to add
* @param string $community The snmp community
* @param string $snmpver snmp version: v1 | v2c | v3
* @param int $port SNMP port number
* @param string $transport SNMP transport: udp | udp6 | udp | tcp6
* @param array $v3 SNMPv3 settings required array keys: authlevel, authname, authpass, authalgo, cryptopass, cryptoalgo
* @param int $poller_group distributed poller group to assign this host to
* @param string $port_assoc_mode field to use to identify ports: ifIndex, ifName, ifDescr, ifAlias
* @param bool $force_add Do not detect the host os
* @param array $additional an array with additional parameters to take into consideration when adding devices
* @return int the id of the added host
* @throws HostExistsException Throws this exception if the host already exists
* @throws Exception Throws this exception if insertion into the database fails
*/
function createHost(
$host,
$community,
$snmpver,
$port = 161,
$transport = 'udp',
$v3 = array(),
$poller_group = 0,
$port_assoc_mode = 'ifIndex',
$force_add = false,
$additional = array()
) {
$host = trim(strtolower($host));
$poller_group=getpollergroup($poller_group);
/* Get port_assoc_mode id if necessary
* We can work with names of IDs here */
if (! is_int($port_assoc_mode)) {
$port_assoc_mode = get_port_assoc_mode_id($port_assoc_mode);
}
$device = array(
'hostname' => $host,
'sysName' => $additional['sysName'] ? $additional['sysName'] : $host,
'os' => $additional['os'] ? $additional['os'] : 'generic',
'hardware' => $additional['hardware'] ? $additional['hardware'] : null,
'community' => $community,
'port' => $port,
'transport' => $transport,
'status' => '1',
'snmpver' => $snmpver,
'poller_group' => $poller_group,
'status_reason' => '',
'port_association_mode' => $port_assoc_mode,
'snmp_disable' => $additional['snmp_disable'] ? $additional['snmp_disable'] : 0,
);
$device = array_merge($device, $v3); // merge v3 settings
if ($force_add !== true) {
$device['os'] = getHostOS($device);
$snmphost = snmp_get($device, "sysName.0", "-Oqv", "SNMPv2-MIB");
if (host_exists($host, $snmphost)) {
throw new HostExistsException("Already have host $host ($snmphost) due to duplicate sysName");
}
}
$device_id = dbInsert($device, 'devices');
if ($device_id) {
return $device_id;
}
throw new \Exception("Failed to add host to the database, please run ./validate.php");
}
function isDomainResolves($domain)
{
if (gethostbyname($domain) != $domain) {
return true;
}
$records = dns_get_record($domain); // returns array or false
return !empty($records);
}
function hoststatus($id)
{
return dbFetchCell("SELECT `status` FROM `devices` WHERE `device_id` = ?", array($id));
}
function match_network($nets, $ip, $first = false)
{
$return = false;
if (!is_array($nets)) {
$nets = array ($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 = array();
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);
}
function get_astext($asn)
{
global $cache;
if (Config::has("astext.$asn")) {
return Config::get("astext.$asn");
}
if (isset($cache['astext'][$asn])) {
return $cache['astext'][$asn];
}
$result = @dns_get_record("AS$asn.asn.cymru.com", DNS_TXT);
if (!empty($result[0]['txt'])) {
$txt = explode('|', $result[0]['txt']);
$result = trim($txt[4], ' "');
$cache['astext'][$asn] = $result;
return $result;
}
return '';
}
/**
* 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)
{
if (!is_array($device)) {
$device = device_by_id_cache($device);
}
dbInsert([
'device_id' => ($device['device_id'] ?: 0),
'reference' => $reference,
'type' => $type,
'datetime' => \Carbon\Carbon::now(),
'severity' => $severity,
'message' => $text,
'username' => isset(LegacyAuth::user()->username) ? LegacyAuth::user()->username : '',
], 'eventlog');
}
// Parse string with emails. Return array with email (as key) and name (as value)
function parse_email($emails)
{
$result = array();
$regex = '/^[\"\']?([^\"\']+)[\"\']?\s{0,}<([^@]+@[^>]+)>$/';
if (is_string($emails)) {
$emails = preg_split('/[,;]\s{0,}/', $emails);
foreach ($emails as $email) {
if (preg_match($regex, $email, $out, PREG_OFFSET_CAPTURE)) {
$result[$out[2][0]] = $out[1][0];
} else {
if (strpos($email, "@")) {
$from_name = Config::get('email_user');
$result[$email] = $from_name;
}
}
}
} else {
// Return FALSE if input not string
return false;
}
return $result;
}
function send_mail($emails, $subject, $message, $html = false)
{
global $config;
if (is_array($emails) || ($emails = parse_email($emails))) {
d_echo("Attempting to email $subject to: " . implode('; ', array_keys($emails)) . PHP_EOL);
$mail = new PHPMailer(true);
try {
$mail->Hostname = php_uname('n');
foreach (parse_email($config['email_from']) as $from => $from_name) {
$mail->setFrom($from, $from_name);
}
foreach ($emails as $email => $email_name) {
$mail->addAddress($email, $email_name);