Repository navigation
Expand file tree
/
Copy pathpoller_mactrack.php
More file actions
1570 lines (1296 loc) · 50.5 KB
/
Copy pathpoller_mactrack.php
File metadata and controls
1570 lines (1296 loc) · 50.5 KB
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
#!/usr/bin/php -q
<?php
/*
+-------------------------------------------------------------------------+
| Copyright (C) 2004-2026 The Cacti Group |
| |
| This program is free software; you can redistribute it and/or |
| modify it under the terms of the GNU General Public License |
| as published by the Free Software Foundation; either version 2 |
| of the License, or (at your option) any later version. |
| |
| This program is distributed in the hope that it will be useful, |
| but WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| GNU General Public License for more details. |
+-------------------------------------------------------------------------+
| Cacti: The Complete RRDTool-based Graphing Solution |
+-------------------------------------------------------------------------+
| This code is designed, written, and maintained by the Cacti Group. See |
| about.php and/or the AUTHORS file for specific developer information. |
+-------------------------------------------------------------------------+
| http://www.cacti.net/ |
+-------------------------------------------------------------------------+
*/
if (function_exists('pcntl_async_signals')) {
pcntl_async_signals(true);
} else {
declare(ticks = 100);
}
ini_set('output_buffering', 'Off');
ini_set('max_runtime', '-1');
ini_set('memory_limit', '-1');
ini_set('max_execution_time', '-1');
set_time_limit(0);
ob_implicit_flush();
$dir = __DIR__;
chdir($dir);
if (substr_count(strtolower($dir), 'mactrack')) {
chdir('../../');
}
require('./include/cli_check.php');
global $config;
require_once($config['base_path'] . '/lib/poller.php');
require_once($config['base_path'] . '/plugins/mactrack/includes/database.php');
require_once($config['base_path'] . '/plugins/mactrack/lib/mactrack_functions.php');
require_once($config['base_path'] . '/plugins/mactrack/lib/mactrack_activity.php');
mactrack_retry_default_site();
// install signal handlers for UNIX only
if (function_exists('pcntl_signal')) {
pcntl_signal(SIGTERM, 'sig_handler');
pcntl_signal(SIGINT, 'sig_handler');
}
// get the mactrack polling cycle
$collect_frequency = read_config_option('mt_collection_timing');
$poller_interval = read_config_option('poller_interval');
if (is_numeric($collect_frequency)) {
// Leave a poller interval before the next run, but at least 80% of the
// frequency: at 5 minutes on a 5-minute poller the difference is zero.
$max_run_duration = max(($collect_frequency * 60) - $poller_interval, (int) ($collect_frequency * 48));
} else {
// default for force
$max_run_duration = 1800;
}
// Disable Mib File Loading
putenv('MIBS=:');
global $config, $debug, $web, $track_errors;
// initialize variables
$site_id = 0;
$debug = false;
$force = false;
$web = false;
$track_errors = 0;
// process calling arguments
$parms = $_SERVER['argv'];
array_shift($parms);
if (cacti_sizeof($parms)) {
foreach ($parms as $parameter) {
if (strpos($parameter, '=') !== false) {
[$arg, $value] = explode('=', $parameter);
} else {
$arg = $parameter;
$value = '';
}
switch ($arg) {
case '-sid':
$site_id = (int) $value;
break;
case '-d':
case '--debug':
$debug = true;
break;
case '-f':
case '--force':
$force = true;
break;
case '-w':
case '--web':
$web = true;
break;
case '--version':
case '-V':
case '-v':
display_version();
exit;
case '--help':
case '-H':
case '-h':
display_help();
exit;
default:
print 'ERROR: Invalid Parameter ' . $parameter . PHP_EOL . PHP_EOL;
display_help();
exit;
}
}
}
// silently end if the registered process is still running, or process table missing
if (function_exists('register_process_start')) {
if (!register_process_start('mactrack', 'master', $config['poller_id'], $max_run_duration)) {
mactrack_debug('Another Mactrack Process Still Running');
exit(0);
}
}
// Defer while a background database upgrade is in progress, or while the
// aggregated-ports rebuild has left its work table (mac_track_aggregated_ports_upgrade)
// in place after an interrupted run. The rebuild renames the live table aside
// and repopulates it per scan date, so the poller's aggregate writes and
// scan-buffer truncation would otherwise race with it and lose or restore
// rows. The upgrade runs once per version change and resumes on its own, so a
// few skipped cycles are harmless.
if (function_exists('mactrack_background_upgrade_running')) {
$upgrade_active = mactrack_background_upgrade_running();
$defer_reason = 'upgrade';
if (!$upgrade_active && function_exists('mactrack_db_table_exists')) {
$upgrade_active = mactrack_db_table_exists('mac_track_aggregated_ports_upgrade');
$defer_reason = 'rebuild_table';
}
if ($upgrade_active) {
mactrack_debug('Deferring the Mactrack poller run while a database upgrade is in progress');
// the Process Status page shows why no scan ran
mactrack_poller_deferred($defer_reason);
if (function_exists('unregister_process')) {
unregister_process('mactrack', 'master', $config['poller_id'], getmypid());
}
exit(0);
}
}
// A partitioning rebuild renames mac_track_ports and mac_track_ips aside and
// copies them back (cli/upgrade_partitioning.php). Until it finishes the live
// tables are incomplete, so a scan would store its results in a partial table.
if (function_exists('mactrack_partition_rebuild_pending') && mactrack_partition_rebuild_pending() !== []) {
mactrack_debug('Deferring the Mactrack poller run while the port and IP tables are repartitioned');
mactrack_poller_deferred('partition_rebuild');
// A maintenance window that passes meanwhile is run after the rebuild.
mactrack_partition_rebuild_note_maintenance();
if (function_exists('unregister_process')) {
unregister_process('mactrack', 'master', $config['poller_id'], getmypid());
}
exit(0);
}
// not deferring: drop the note the Process Status page shows
mactrack_poller_deferred_clear();
// Get rid of old/hung processes
clear_old_processes($site_id);
if ($collect_frequency == 'disabled') {
print 'WARNING: Mactrack scanning frequency is disabled, exiting. You have to enable it in settings.' . PHP_EOL;
if (function_exists('unregister_process')) {
unregister_process('mactrack', 'master', $config['poller_id'], getmypid());
}
exit(1);
} else {
// for manual scans, verify if we should run or not
$running_processes = db_fetch_cell('SELECT COUNT(*) FROM mac_track_processes');
if ($running_processes) {
$start_date = db_fetch_cell('SELECT MIN(start_date) FROM mac_track_processes');
if (time() < (strtotime($start_date) + $max_run_duration) && !$force) {
print 'NOTE: Mactrack currently running and max run duration not eclipsed.' . PHP_EOL;
if (function_exists('unregister_process')) {
unregister_process('mactrack', 'master', $config['poller_id'], getmypid());
}
exit(0);
}
if ($force) {
mactrack_debug('WARNING: Forcing Collection although Collection Appears in Process');
db_execute('TRUNCATE mac_track_processes');
} else {
mactrack_debug('WARNING: Stale data found in Matrack process table');
db_execute('TRUNCATE mac_track_processes');
}
}
// A port table conversion holds this lock for hours; scans are skipped until it ends.
if (!mactrack_partition_scan_begin()) {
print 'NOTE: A port table conversion or another scan is running, exiting.' . PHP_EOL;
if (function_exists('unregister_process')) {
unregister_process('mactrack', 'master', $config['poller_id'], getmypid());
}
exit(0);
}
// we don't want to see errors in the cacti log
errors_disable();
if ($site_id > 0) {
mactrack_debug('About to enter Mactrack Site Scan Processing');
// take time and log performance data
$start = microtime(true);
collect_mactrack_data($start, $site_id);
log_mactrack_statistics('collect');
} else {
mactrack_debug('About to enter Mactrack poller processing');
if ($force || $collect_frequency > 0) {
mactrack_debug('Into Processing. Checking to determine if it\'s time to run.');
$collect_frequency = $collect_frequency * 60;
// find out if it's time to collect device information
$base_start_time = read_config_option('mt_base_time');
$database_maint_time = read_config_option('mt_maint_time');
$last_run_time = read_config_option('mt_last_run_time');
$last_db_maint_time = read_config_option('mt_last_db_maint_time');
$previous_base_start_time = read_config_option('mt_prev_base_time');
$previous_db_maint_time = read_config_option('mt_prev_db_maint_time');
// see if the user desires a new start time
mactrack_debug('Checking if user changed the start time');
if (!empty($previous_base_start_time)) {
if ($base_start_time != $previous_base_start_time) {
mactrack_debug('Detected that user changed the start time');
unset($last_run_time);
db_execute("DELETE FROM settings WHERE name='mt_last_run_time'");
}
}
// see if the user desires a new db maintenance time
/*
mactrack_debug('Checking if user changed the maintenance time');
if (!empty($previous_db_maint_time)) {
if ($database_maint_time <> $previous_db_maint_time) {
mactrack_debug('Detected that user changed the db maintenance time');
unset($last_db_maint_time);
db_execute("DELETE FROM settings WHERE name='mt_last_db_maint_time'");
}
}
*/
// set to detect if the user cleared the time between polling cycles
set_config_option('mt_prev_base_time', $base_start_time);
set_config_option('mt_prev_db_maint_time', $database_maint_time);
// determine the next start time
$current_time = strtotime('now');
if (empty($last_run_time)) {
if ($current_time > strtotime($base_start_time)) {
// if timer expired within a polling interval, then poll
if (($current_time - $poller_interval) < strtotime($base_start_time)) {
$next_run_time = strtotime(date('Y-m-d') . ' ' . $base_start_time);
} else {
// not + 86400, which is an hour off across a DST change
$next_run_time = strtotime('tomorrow ' . $base_start_time);
}
} else {
$next_run_time = strtotime(date('Y-m-d') . ' ' . $base_start_time);
}
} else {
$next_run_time = $last_run_time + $collect_frequency;
}
$time_till_next_run = $next_run_time - $current_time;
// The poller fires a second or two either side of its interval;
// a strict < 0 test let a run due now wait a whole interval.
$run_due = $time_till_next_run <= $poller_interval / 2;
if ($run_due) {
mactrack_debug('The next run time has been determined to be NOW');
} else {
mactrack_debug("The next run time has been determined to be at '" . date('Y-m-d H:i:s', (int) $next_run_time) . "'");
}
/*
if (empty($last_db_maint_time)) {
$next_db_maint_time = strtotime(date('Y-m-d') . ' ' . $database_maint_time);
} else {
$next_db_maint_time = $last_db_maint_time + 24*3600;
}
*/
$db_maint_time = strtotime($database_maint_time);
// An unreadable time is false, which is less than any last run
// and would run maintenance every cycle; use the default.
if ($db_maint_time === false) {
cacti_log("WARNING: MacTrack maintenance time '" . $database_maint_time . "' is not a time; using 12:00am", false, 'MACTRACK');
$database_maint_time = '12:00am';
$db_maint_time = strtotime($database_maint_time);
}
if ($last_db_maint_time < $db_maint_time) {
$next_db_maint_time = $db_maint_time;
} else {
$next_db_maint_time = strtotime('Tomorrow ' . $database_maint_time);
}
$time_till_next_db_maint = $next_db_maint_time - $current_time;
if ($time_till_next_db_maint < 0) {
mactrack_debug('The next database maintenance run time has been determined to be NOW');
} else {
mactrack_debug("The next database maintenance run time has been determined to be at '" . date('Y-m-d H:i:s', (int) $next_db_maint_time) . "'");
}
if ($run_due || $force == true) {
mactrack_debug('Either a scan has been forced, or it\'s time to check for macs');
// take time and log performance data
$start = microtime(true);
// Store the slot this run belongs to, not when it started, so
// the schedule stays on the base time's grid; after a gap, step
// to the latest slot that has passed.
if ($run_due && $collect_frequency > 0) {
$run_slot = mactrack_run_slot((int) $next_run_time, (int) $current_time, (int) $collect_frequency);
} else {
$run_slot = $current_time;
}
set_config_option('mt_last_run_time', $run_slot);
collect_mactrack_data($start, $site_id);
log_mactrack_statistics('collect');
}
// A window that passed during a partitioning rebuild runs now.
$maint_missed = (string) read_config_option('mt_db_maint_missed', true) === 'on';
if ($time_till_next_db_maint < 0 || $maint_missed) {
// take time and log performance data
$start = microtime(true);
set_config_option('mt_last_db_maint_time', $current_time);
perform_mactrack_db_maint();
log_mactrack_statistics('maint');
}
}
}
// show errors now
errors_restore();
}
if (function_exists('unregister_process')) {
unregister_process('mactrack', 'master', $config['poller_id'], getmypid());
}
exit(0);
/**
* Disables PHP's track_errors ini setting and installs
* mactrack_error_handler() as the active error handler, so that
* subsequent errors are routed through MacTrack's own logging instead
* of the default handler.
*
* @return void
*
* @global bool|string &$track_errors Receives the previous
* track_errors ini value, for later
* restoration by errors_restore().
*/
function errors_disable(): void {
global $track_errors;
$track_errors = ini_get('track_errors');
ini_set('track_errors', 0);
set_error_handler('mactrack_error_handler');
}
/**
* Restores the track_errors ini setting saved by errors_disable() and
* reinstates PHP's previous error handler.
*
* @return void
*
* @global bool|string $track_errors The previous track_errors ini
* value saved by errors_disable().
*/
function errors_restore(): void {
global $track_errors;
ini_set('track_errors', $track_errors);
restore_error_handler();
}
/**
* Custom PHP error handler installed by errors_disable(): logs the
* error (with the originating plugin name extracted from the file
* path when applicable) to the Cacti log, and for fatal-class errors
* originating in a plugin, disables that plugin to prevent repeated
* crashes.
*
* @param int $level The PHP error level constant (e.g. E_ERROR).
* @param string $message The error message.
* @param string $file The file the error occurred in.
* @param int $line The line number the error occurred on.
* @param array $context Unused; retained for error handler signature
* compatibility.
*
* @return bool False to allow PHP's normal error handling to continue
* (except when IgnoreErrorHandler() suppresses the error
* entirely, in which case true is returned).
*
* @global array $phperrors Map of PHP error level constants to
* human-readable labels.
*/
function mactrack_error_handler($level, $message, $file, $line, $context = []) {
global $phperrors;
if (IgnoreErrorHandler($message)) {
return true;
}
preg_match("/.*\/plugins\/([\w-]*)\/.*/", $file, $output_array);
$plugin = ($output_array[1] ?? '');
$error = 'PHP ' . $phperrors[$level] . ($plugin != '' ? " in Plugin '$plugin'" : '') . ": $message in file: $file on line: $line";
switch ($level) {
case E_COMPILE_ERROR:
case E_CORE_ERROR:
case E_ERROR:
case E_PARSE:
if ($plugin != '') {
api_plugin_disable_all($plugin);
cacti_log("ERRORS DETECTED - DISABLING PLUGIN '$plugin'");
}
cacti_log($error, false, 'ERROR');
cacti_debug_backtrace('PHP ERROR PARSE');
break;
case E_RECOVERABLE_ERROR:
case E_USER_ERROR:
cacti_log($error, false, 'ERROR');
cacti_debug_backtrace('PHP ERROR');
break;
case E_COMPILE_WARNING:
case E_CORE_WARNING:
case E_USER_WARNING:
case E_WARNING:
cacti_log($error, false, 'ERROR');
cacti_debug_backtrace('PHP ERROR WARNING');
break;
case E_NOTICE:
case E_USER_NOTICE:
break;
case E_STRICT:
cacti_log($error, false, 'ERROR');
cacti_debug_backtrace('PHP ERROR STRICT');
break;
default:
cacti_log($error, false, 'ERROR');
cacti_debug_backtrace('PHP ERROR');
}
return false;
}
/**
* Parses one arp.dat line: MAC, IP address, timestamp and, when known,
* the host name, separated by tabs.
*
* @param string $line The line as read, with its newline.
* @param string $delim The separator to put between MAC octets.
*
* @return array{mac: string, ip: string, dns: string}|null The entry, or
* null for a blank or malformed line.
*/
function mactrack_parse_arpwatch_line(string $line, string $delim): ?array {
$fields = explode("\t", trim($line));
if (count($fields) < 2) {
return null;
}
$octets = explode(':', $fields[0]);
if (count($octets) !== 6) {
return null;
}
foreach ($octets as $k => $octet) {
if (!ctype_xdigit($octet) || strlen($octet) > 2) {
return null;
}
$octets[$k] = str_pad(strtoupper($octet), 2, '0', STR_PAD_LEFT);
}
return [
'mac' => implode($delim, $octets),
'ip' => $fields[1],
'dns' => trim($fields[3] ?? ''),
];
}
/**
* Returns the schedule slot a due collection run belongs to: the slot it
* was due at, or after missed runs the latest slot that has passed.
*
* @param int $next_run_time The slot the run was due at.
* @param int $current_time The time the run starts.
* @param int $frequency Seconds between runs, more than 0.
*
* @return int The slot to store as the last run time.
*/
function mactrack_run_slot(int $next_run_time, int $current_time, int $frequency): int {
if ($current_time <= $next_run_time) {
return $next_run_time;
}
return $next_run_time + intdiv($current_time - $next_run_time, $frequency) * $frequency;
}
/**
* Stops the scanners still registered when a run reaches its time limit
* and removes their process rows.
*
* @return void
*/
function mactrack_stop_scanners(): void {
$scanners = db_fetch_assoc('SELECT device_id, process_id
FROM mac_track_processes
WHERE device_id > 0');
foreach ($scanners as $scanner) {
mactrack_kill_process((int) $scanner['process_id']);
cacti_log("WARNING: Stopping Mactrack Scanner for Device '" . $scanner['device_id'] . "' at the run time limit", false, 'MACTRACK');
}
db_execute('DELETE FROM mac_track_processes WHERE device_id > 0');
}
/**
* Terminates a MacTrack worker by process id; 0 means it has not
* registered a PID yet. On Linux a process whose command line does not
* name MacTrack is left alone.
*
* @param int $process_id The worker's process id.
*
* @return void
*/
function mactrack_kill_process(int $process_id): void {
if ($process_id <= 0) {
return;
}
// A stored PID may have been reused, after a reboot for instance. Where
// the command line is readable, signal only a MacTrack worker.
$cmdline = @file_get_contents('/proc/' . $process_id . '/cmdline');
if ($cmdline !== false && preg_match('~(?:^|\x00)(?:[^\x00]*/)?(?:poller_mactrack|mactrack_scanner|mactrack_resolver)\.php(?:\x00|$)~', $cmdline) !== 1) {
return;
}
if (strstr(PHP_OS, 'WIN')) {
exec('taskkill /pid ' . $process_id);
} else {
exec('kill ' . $process_id);
}
}
/**
* Deletes stale mac_track_processes rows (and cleans up their scan
* locks) for scans that have exceeded the configured maximum script
* runtime, for the given site (or all sites when $site_id is 0).
*
* @param int $site_id The MacTrack site id to limit cleanup to, or 0
* for all sites.
*
* @return void
*/
function clear_old_processes($site_id): void {
// get the max script runtime and kill old scripts
$max_script_runtime = read_config_option('mt_script_runtime');
$delete_time = date('Y-m-d H:i:s', (int) strtotime('-' . $max_script_runtime . ' Minutes'));
$site_id = intval($site_id);
// LEFT JOIN: the poller (-1) and resolver (0) rows have no device, and
// a run for all sites must clear them too
$sql = 'SELECT mtp.*
FROM mac_track_processes AS mtp
LEFT JOIN mac_track_devices AS mtd
ON mtp.device_id=mtd.device_id
WHERE start_date < ?';
$params = [$delete_time];
if ($site_id > 0) {
$sql .= ' AND mtd.site_id = ?';
$params[] = $site_id;
}
// remove old processes from the system if they exist
$old_procs = db_fetch_assoc_prepared($sql, $params);
if (cacti_sizeof($old_procs)) {
$device_ids = [];
foreach ($old_procs as $p) {
$process_id = intval($p['process_id']);
$device_ids[] = intval($p['device_id']);
if ($process_id > 0) {
mactrack_kill_process($process_id);
cacti_log("WARNING: Removing Hung Mactrack Process for Device '" . $p['device_id'] . "' With Status '" . $p['status'] . "'");
} else {
cacti_log("WARNING: Removing Hung Mactrack Process Entry for Device '" . $p['device_id'] . "' With Status '" . $p['status'] . "'");
}
}
// device_id is the key; a PID of 0 would also match every entry still
// waiting for one, and the age check spares an entry re-queued meanwhile
db_execute_prepared('DELETE FROM mac_track_processes
WHERE device_id IN (' . implode(',', array_fill(0, count($device_ids), '?')) . ')
AND start_date < ?',
array_merge($device_ids, [$delete_time]));
}
}
/**
* Main MacTrack data collection routine: launches parallel scanning
* worker processes for each enabled device (or the devices of a
* specific site) to collect port/MAC/VLAN/ARP/802.1x data, waiting for
* all workers to finish or the maximum run duration to elapse.
*
* @param float $start The collection run's start time
* (microtime(true)), used to enforce
* $max_run_duration.
* @param int $site_id The MacTrack site id to scan, or 0 to scan all
* sites (default 0).
*
* @return void
*
* @global int $max_run_duration Maximum allowed collection run
* duration in seconds.
* @global array $config Cacti global configuration array.
* @global bool $debug Whether debug output is enabled.
* @global string $scan_date The current scan timestamp.
*/
function collect_mactrack_data($start, $site_id = 0): void {
global $max_run_duration, $config, $debug, $scan_date;
if (defined('CACTI_BASE_PATH')) {
$config['base_path'] = CACTI_BASE_PATH;
}
// dns resolver binary
$resolver_launched = false;
if (read_config_option('mt_reverse_dns') == 'on') {
$dns_resolver_required = true;
} else {
$dns_resolver_required = false;
}
// get php binary path
$command_string = read_config_option('path_php_binary');
// save the scan date information
$scan_date = date('Y-m-d H:i:s');
set_config_option('mt_scan_date', $scan_date);
// create this scan's partition before any of its rows are written
$partition_plan = mactrack_partition_prepare_scan($scan_date);
// just in case we've run too long
$exit_mactrack = false;
// start mainline processing, order by site_id to keep routers grouped with switches
if ($site_id > 0) {
$device_ids = db_fetch_assoc_prepared('SELECT device_id
FROM mac_track_devices
WHERE site_id = ?
AND disabled = ""
ORDER BY last_runduration DESC',
[$site_id]);
} else {
$device_ids = db_fetch_assoc('SELECT device_id
FROM mac_track_devices
WHERE disabled = ""
ORDER BY last_runduration DESC');
}
$total_devices = cacti_sizeof($device_ids);
$concurrent_processes = read_config_option('mt_processes');
if ($debug == true) {
$e_debug = ' -d';
} else {
$e_debug = '';
}
if ($site_id > 0) {
$e_site = " -sid=$site_id";
} else {
$e_site = '';
}
// add the parent process to the process list
db_process_add('-1');
if ($total_devices) {
$mac_ip_dns = [];
// grab arpwatch data
if (read_config_option('mt_arpwatch') == 'on') {
$arp_db = read_config_option('mt_arpwatch_path');
$delim = read_config_option('mt_mac_delim');
$mac_ip_dns = [];
if (file_exists($arp_db)) {
$arp_dat = fopen($arp_db, 'r');
if ($arp_dat) {
while (!feof($arp_dat)) {
$line = fgets($arp_dat, 4096);
$entry = $line === false ? null : mactrack_parse_arpwatch_line($line, (string) $delim);
if ($entry !== null) {
$mac_ip_dns[$entry['mac']]['ip'] = $entry['ip'];
$mac_ip_dns[$entry['mac']]['dns'] = $entry['dns'];
}
}
fclose($arp_dat);
mactrack_debug('ARPWATCH: IP, DNS & MAC collection complete with ArpWatch');
} else {
cacti_log("ERROR: cannot open file ArpWatch database '$arp_db'");
}
}
}
// scan through all devices
mactrack_activity_begin('scanning', ['devices' => $total_devices]);
$j = 0;
$i = 0;
$last_time = strtotime('now') - 7200;
$processes_available = $concurrent_processes;
while ($j < $total_devices) {
// check for pending signals
if (function_exists('pcntl_signal_dispatch')) {
pcntl_signal_dispatch();
}
/**
* retrieve the number of concurrent mac_track processes to run
* default to 10 for now
*/
$concurrent_processes = db_fetch_cell("SELECT value FROM settings WHERE name='mt_processes'");
for ($i = 0; $i < $processes_available; $i++) {
if (($j + $i) >= $total_devices) {
break;
}
// Register the device before launching it, so the counts below
// include scanners that have not started yet; the scanner adds
// its PID to this row.
db_process_add($device_ids[$i + $j]['device_id']);
$extra_args = ' -q ' . $config['base_path'] . '/plugins/mactrack/mactrack_scanner.php -id=' . $device_ids[$i + $j]['device_id'] . $e_debug;
mactrack_debug('CMD: ' . $command_string . $extra_args);
exec_background($command_string, $extra_args);
}
$j = $j + $i;
// launch the dns resolver if it hasn't been yet
if (($dns_resolver_required) && (!$resolver_launched)) {
sleep(2);
exec_background($command_string, ' -q ' . $config['base_path'] . '/plugins/mactrack/mactrack_resolver.php' . $e_debug . $e_site);
$resolver_launched = true;
mactrack_debug('DNS Resolver process launched');
}
mactrack_debug('A process cycle launch just completed.');
/**
* wait the correct number of seconds for processes prior to
* attempting to update records
*/
sleep(2);
$current_time = strtotime('now');
if (($current_time - $last_time) > read_config_option('mt_dns_prime_interval')) {
// resolve some ip's to mac addresses to let the resolver knock them out
db_execute_prepared('UPDATE mac_track_temp_ports
INNER JOIN mac_track_ips
ON mac_track_temp_ports.mac_address=mac_track_ips.mac_address
AND mac_track_temp_ports.site_id=mac_track_ips.site_id
SET mac_track_temp_ports.ip_address=mac_track_ips.ip_address,
mac_track_temp_ports.updated=1
WHERE mac_track_temp_ports.updated=0
AND mac_track_ips.scan_date = ?',
[$scan_date]);
mactrack_debug('Interum IP addresses to MAC addresses association pass complete.');
$last_time = $current_time;
}
mactrack_reap_unstarted_scanners();
// scanners only; the parent (-1) and resolver (0) rows do not count
$processes_running = db_fetch_cell('SELECT COUNT(*)
FROM mac_track_processes
WHERE device_id > 0');
$processes_available = $concurrent_processes - $processes_running;
// take time to check for an exit condition
$current = microtime(true);
// exit if we've run too long
if (($current - $start) > $max_run_duration) {
$exit_mactrack = true;
cacti_log('ERROR: Mactrack timed out during main script processing.');
db_execute("DELETE FROM settings WHERE name='mactrack_process_status'");
db_process_remove('-1');
break;
} else {
set_config_option('mactrack_process_status', "Total:$total_devices Completed:$j");
}
}
// wait for last process to exit
$processes_running = db_fetch_cell('SELECT COUNT(*)
FROM mac_track_processes
WHERE device_id > 0');
while ($processes_running > 0 && !$exit_mactrack) {
mactrack_reap_unstarted_scanners();
$processes_running = db_fetch_cell('SELECT COUNT(*)
FROM mac_track_processes
WHERE device_id > 0');
$devices_running = db_fetch_cell("SELECT GROUP_CONCAT(CAST(`device_id` as CHAR) SEPARATOR ', ')
FROM mac_track_processes");
/**
* wait the correct number of seconds for processes prior to
* attempting to update records
*/
sleep(2);
$current_time = strtotime('now');
if (($current_time - $last_time) > read_config_option('mt_dns_prime_interval')) {
// resolve some ip's to mac addresses to let the resolver knock them out
db_execute_prepared('UPDATE mac_track_temp_ports
INNER JOIN mac_track_ips
ON mac_track_temp_ports.mac_address=mac_track_ips.mac_address
AND mac_track_temp_ports.site_id=mac_track_ips.site_id
SET mac_track_temp_ports.ip_address=mac_track_ips.ip_address,
mac_track_temp_ports.updated=1
WHERE mac_track_temp_ports.updated=0
AND mac_track_ips.scan_date = ?',
[$scan_date]);
mactrack_debug('Interum IP addresses to MAC addresses association pass complete.');
}
// take time to check for an exit condition
$current = microtime(true);
// exit if we've run too long
if (($current - $start) > $max_run_duration) {
$exit_mactrack = true;
cacti_log('ERROR: Mactrack timed out during main script processing.');
break;
}
mactrack_debug('Waiting on ' . $processes_running . ' with id = [' . $devices_running . '] to complete prior to exiting.');
}
// Scanners still running would write after the load and the TRUNCATE
// below, so their rows would land in the next run under this run's
// scan date. Stop them first.
if ($exit_mactrack) {
mactrack_stop_scanners();
}
// if arpwatch is enabled, let's let it pick up the stragglers, based upon IP address first
if ((read_config_option('mt_arpwatch') == 'on') && (cacti_sizeof($mac_ip_dns))) {
$ports = db_fetch_assoc('SELECT site_id, device_id, mac_address
FROM mac_track_temp_ports
WHERE updated = 0');
if (cacti_sizeof($ports)) {
foreach ($ports as $port) {
if (isset($mac_ip_dns[$port['mac_address']])) {
if ($mac_ip_dns[$port['mac_address']]['dns'] != '') {
db_execute_prepared('UPDATE mac_track_temp_ports
SET updated = 1, ip_address = ?, dns_hostname = ?
WHERE site_id = ?
AND device_id = ?
AND mac_address = ?',
[
$mac_ip_dns[$port['mac_address']]['ip'],
$mac_ip_dns[$port['mac_address']]['dns'],
$port['site_id'],
$port['device_id'],
$port['mac_address']
]
);
} else {
db_execute_prepared('UPDATE mac_track_temp_ports
SET updated = 1, ip_address = ?
WHERE site_id = ?
AND device_id = ?
AND mac_address = ?',
[
$mac_ip_dns[$port['mac_address']]['ip'],
$port['site_id'],
$port['device_id'],
$port['mac_address']
]
);
}
}
}
}
}