Repository navigation
Expand file tree
/
Copy pathsetup.php
More file actions
962 lines (807 loc) · 35 KB
/
Copy pathsetup.php
File metadata and controls
962 lines (807 loc) · 35 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
<?php
declare(strict_types = 1);
/*
+-------------------------------------------------------------------------+
| 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/ |
+-------------------------------------------------------------------------+
*/
/**
* Return the CSP nonce attribute for inline <script> tags, safely across
* Cacti versions. Newer Cacti releases enforce a Content-Security-Policy that
* requires a per-request nonce on parser-inserted scripts; older releases lack
* the CactiSecureHeaders class, so this returns an empty string there.
*
* @return string The nonce attribute when supported, otherwise empty string.
*/
function plugin_routerconfigs_csp_nonce(): string {
if (class_exists('CactiSecureHeaders')) {
return CactiSecureHeaders::getNonceAttribute();
}
return '';
}
require_once(__DIR__ . '/includes/arrays.php');
/**
* Reads this plugin's version/author metadata from its INFO file.
* Invoked by the Cacti plugin framework to display plugin information,
* and called from routerconfigs_check_upgrade() to detect a pending
* schema upgrade.
*
* @return array The plugin's INFO file 'info' section (name, version,
* author, etc.).
*
* @global array $config Cacti global configuration array; used to
* locate the plugin's INFO file.
*/
function plugin_routerconfigs_version() {
global $config;
$info = parse_ini_file($config['base_path'] . '/plugins/routerconfigs/INFO', true);
return isset($info['info']) && is_array($info['info']) ? $info['info'] : [];
}
/**
* Registers this plugin's Cacti hooks (tab display, config arrays,
* navigation breadcrumbs, settings, poller_bottom, page_head) and its
* router-*.php realm, then creates the plugin's database tables.
* Invoked by the Cacti plugin framework when the plugin is
* installed/enabled.
*
* @return void
*/
function plugin_routerconfigs_install() {
global $config;
api_plugin_register_hook('routerconfigs', 'top_header_tabs', 'routerconfigs_show_tab', 'setup.php');
api_plugin_register_hook('routerconfigs', 'top_graph_header_tabs', 'routerconfigs_show_tab', 'setup.php');
api_plugin_register_hook('routerconfigs', 'config_arrays', 'routerconfigs_config_arrays', 'setup.php');
api_plugin_register_hook('routerconfigs', 'draw_navigation_text', 'routerconfigs_draw_navigation_text', 'setup.php');
api_plugin_register_hook('routerconfigs', 'config_settings', 'routerconfigs_config_settings', 'setup.php');
api_plugin_register_hook('routerconfigs', 'poller_bottom', 'routerconfigs_poller_bottom', 'setup.php');
api_plugin_register_hook('routerconfigs', 'page_head', 'routerconfigs_page_head', 'setup.php');
api_plugin_register_hook('routerconfigs', 'device_action_array', 'routerconfigs_device_action_array', 'includes/devices.php');
api_plugin_register_hook('routerconfigs', 'device_action_prepare', 'routerconfigs_device_action_prepare', 'includes/devices.php');
api_plugin_register_hook('routerconfigs', 'device_action_execute', 'routerconfigs_device_action_execute', 'includes/devices.php');
api_plugin_register_realm('routerconfigs', 'router-devices.php,router-accounts.php,router-backups.php,router-compare.php,router-devtypes.php', __('Router Configs', 'routerconfigs'), 1);
require_once($config['base_path'] . '/plugins/routerconfigs/includes/database.php');
routerconfigs_setup_table_new();
}
/**
* No-op uninstall hook; this plugin does not remove its database tables
* on uninstall. Invoked by the Cacti plugin framework when the plugin is
* uninstalled.
*
* @return void
*/
function plugin_routerconfigs_uninstall() {
// Do any extra Uninstall stuff here
}
/**
* Here we will upgrade to the newest version
*
* Runs any pending database schema upgrade for this plugin. Invoked by
* the Cacti plugin framework when the plugin's installed version
* differs from its current version.
*
* @return bool Always false.
*/
function plugin_routerconfigs_upgrade() {
// Here we will upgrade to the newest version
routerconfigs_check_upgrade();
return false;
}
/**
* Applies version-gated schema migrations for this plugin (realm
* updates, column renames/adds/drops across several historical
* versions, SSH host-key storage columns, seeding built-in device
* types) based on comparing the installed version recorded in
* plugin_config against the current INFO file version, then updates the
* recorded version. Only runs on plugins.php, router-devices.php, or
* settings.php to avoid the version lookup on every page. Called from
* plugin_routerconfigs_upgrade() and routerconfigs_config_arrays().
*
* @return void
*
* @global array $config Cacti global configuration array;
* used to locate database/functions
* libraries.
* @global object $database_default Reserved/declared for parity with
* the included library files; not used
* directly here.
*/
function routerconfigs_check_upgrade() {
global $config, $database_default;
require_once($config['library_path'] . '/database.php');
require_once($config['library_path'] . '/functions.php');
require_once($config['base_path'] . '/plugins/routerconfigs/includes/database.php');
// Let's only run this check if we are on a page that actually needs the data
$files = ['plugins.php', 'router-devices.php', 'settings.php'];
if (!in_array(get_current_page(), $files, true)) {
return;
}
$info = plugin_routerconfigs_version();
$current = $info['version'];
$old = db_fetch_cell_prepared('SELECT version FROM plugin_config WHERE directory = ?', ['routerconfigs']);
if ($current != $old) {
// Create any missing tables up front, before the guarded historical
// migrations, the SSH host-key column check, and AddDeviceTypes() below,
// so a missing devices/device-types table can no longer make those
// pre-steps error or seed device types into a not-yet-created table.
routerconfigs_create_missing_tables();
$hostkey_schema_ready = routerconfigs_ensure_hostkey_schema();
api_plugin_register_hook('routerconfigs', 'top_header_tabs', 'routerconfigs_show_tab', 'setup.php', 1);
api_plugin_register_hook('routerconfigs', 'top_graph_header_tabs', 'routerconfigs_show_tab', 'setup.php', 1);
// Ensure existing installs pick up the Devices-page import action hooks.
api_plugin_register_hook('routerconfigs', 'device_action_array', 'routerconfigs_device_action_array', 'includes/devices.php', 1);
api_plugin_register_hook('routerconfigs', 'device_action_prepare', 'routerconfigs_device_action_prepare', 'includes/devices.php', 1);
api_plugin_register_hook('routerconfigs', 'device_action_execute', 'routerconfigs_device_action_execute', 'includes/devices.php', 1);
// update realms for old versions
if (cacti_version_compare($old,'0.2','<')) {
api_plugin_register_realm('routerconfigs', 'router-devices.php,router-accounts.php,router-backups.php,router-compare.php', 'Plugin -> Router Configs', 1);
// get the realm id's and change from old to new
$user = db_fetch_cell_prepared('SELECT id FROM plugin_realms WHERE file=?', ['router-devices.php']);
if ($user > 0) {
$users = db_fetch_assoc_prepared('SELECT user_id FROM user_auth_realm WHERE realm_id = ?', [86]);
if (cacti_sizeof($users)) {
foreach ($users as $u) {
db_execute_prepared('INSERT INTO user_auth_realm
(realm_id, user_id) VALUES (?, ?)
ON DUPLICATE KEY UPDATE realm_id=VALUES(realm_id)',
[(int) $user, (int) $u['user_id']]);
db_execute_prepared('DELETE FROM user_auth_realm
WHERE user_id = ?
AND realm_id = ?',
[(int) $u['user_id'], 86]);
}
}
}
}
if (cacti_version_compare($old, '1.4.0', '<')) {
plugin_routerconfigs_fix_backups_pre14();
}
if (cacti_version_compare($old, '1.5.1', '<')) {
// Remove old columns of backups
if (db_column_exists('plugin_routerconfigs_backups', 'config')) {
db_execute('ALTER TABLE plugin_routerconfigs_backups
DROP COLUMN `config`');
}
if (db_column_exists('plugin_routerconfigs_backups','username')) {
db_execute('ALTER TABLE plugin_routerconfigs_backups
CHANGE COLUMN `username` `lastuser` varchar(64)');
}
if (db_column_exists('plugin_routerconfigs_devices','password')) {
db_execute('ALTER TABLE plugin_routerconfigs_devices
DROP COLUMN `password`');
}
if (db_column_exists('plugin_routerconfigs_devices', 'anykey')) {
db_execute('ALTER TABLE plugin_routerconfigs_devices
DROP COLUMN `anykey`');
}
// Rename existing columns of devices
if (db_column_exists('plugin_routerconfigs_devices','connect_type')) {
db_execute('ALTER TABLE plugin_routerconfigs_devices
CHANGE COLUMN `connect_type` `connecttype` varchar(10) DEFAULT \'\'');
}
if (db_column_exists('plugin_routerconfigs_devices','username')) {
db_execute('ALTER TABLE plugin_routerconfigs_devices
CHANGE COLUMN `username` `lastuser` varchar(64)');
}
// Add new/missing columns of devices
if (!db_column_exists('plugin_routerconfigs_devices','connecttype')) {
db_execute('ALTER TABLE plugin_routerconfigs_devices
ADD COLUMN `connecttype` varchar(10) DEFAULT \'\'');
}
if (!db_column_exists('plugin_routerconfigs_devices','nextbackup')) {
db_execute('ALTER TABLE plugin_routerconfigs_devices
ADD COLUMN `nextbackup` int(18)');
}
if (!db_column_exists('plugin_routerconfigs_devices','nextattempt')) {
db_execute('ALTER TABLE plugin_routerconfigs_devices
ADD COLUMN `nextattempt` int(18)');
}
if (!db_column_exists('plugin_routerconfigs_devices', 'timeout')) {
db_execute('ALTER TABLE plugin_routerconfigs_devices
ADD COLUMN `timeout` int(18)');
}
if (!db_column_exists('plugin_routerconfigs_devices', 'sleep')) {
db_execute('ALTER TABLE plugin_routerconfigs_devices
ADD COLUMN `sleep` int(18)');
}
if (!db_column_exists('plugin_routerconfigs_devices', 'elevated')) {
db_execute('ALTER TABLE plugin_routerconfigs_devices
ADD COLUMN `elevated` char(3)');
}
// Perform tidy up of devices
db_execute_prepared('UPDATE plugin_routerconfigs_devices SET
nextbackup = IFNULL(nextbackup,0),
nextattempt = IFNULL(nextattempt,0)', []);
// Rename existing columns of device types
if (db_column_exists('plugin_routerconfigs_devicetypes','connect_type')) {
db_execute('ALTER TABLE plugin_routerconfigs_devicetypes
CHANGE COLUMN `connect_type` `connecttype` varchar(10) DEFAULT \'\'');
}
if (db_column_exists('plugin_routerconfigs_devicetypes','username')) {
db_execute('ALTER TABLE plugin_routerconfigs_devicetypes
CHANGE COLUMN `username` `promptuser` varchar(64)');
}
if (db_column_exists('plugin_routerconfigs_devicetypes','password')) {
db_execute('ALTER TABLE plugin_routerconfigs_devicetypes
CHANGE COLUMN `password` `promptpass` varchar(256)');
}
// Add new/missing columns of device types
if (!db_column_exists('plugin_routerconfigs_devicetypes', 'anykey')) {
db_execute('ALTER TABLE plugin_routerconfigs_devicetypes
ADD COLUMN `anykey` varchar(50) DEFAULT \'\'');
}
if (!db_column_exists('plugin_routerconfigs_devicetypes', 'configfile')) {
db_execute('ALTER TABLE plugin_routerconfigs_devicetypes
ADD COLUMN `configfile` varchar(256) DEFAULT \'\'');
}
if (!db_column_exists('plugin_routerconfigs_devicetypes','connecttype')) {
db_execute('ALTER TABLE plugin_routerconfigs_devicetypes
ADD COLUMN `connecttype` varchar(10) DEFAULT \'both\'');
}
if (!db_column_exists('plugin_routerconfigs_devicetypes', 'sleep')) {
db_execute('ALTER TABLE plugin_routerconfigs_devicetypes
ADD COLUMN `sleep` int(18)');
}
if (!db_column_exists('plugin_routerconfigs_devicetypes', 'timeout')) {
db_execute('ALTER TABLE plugin_routerconfigs_devicetypes
ADD COLUMN `timeout` int(18)');
}
if (!db_column_exists('plugin_routerconfigs_devicetypes', 'elevated')) {
db_execute('ALTER TABLE plugin_routerconfigs_devicetypes
ADD COLUMN `elevated` char(3)');
}
}
if (cacti_version_compare($old, '1.5.2', '<')) {
if (!db_column_exists('plugin_routerconfigs_devicetypes','promptconfirm')) {
db_execute('ALTER TABLE plugin_routerconfigs_devicetypes
ADD COLUMN `promptconfirm` varchar(64) DEFAULT \'confirm|to tftp:\'');
}
}
if (cacti_version_compare($old, '1.5.3', '<')) {
if (!db_column_exists('plugin_routerconfigs_devicetypes','promptconfirm')) {
db_execute('ALTER TABLE plugin_routerconfigs_devicetypes
MODIFY COLUMN `promptconfirm` varchar(64) DEFAULT \'confirm|to tftp:\'');
}
}
AddDeviceTypes();
if (!$hostkey_schema_ready) {
cacti_log('ERROR: Routerconfigs upgrade incomplete: unable to create SSH host-key storage columns', false, 'RCONFIG');
}
// Refresh each table to the current definition; the historical column
// renames/drops above run first so db_update_table() sees current names.
$tables_ready = routerconfigs_upgrade_tables();
// Only record the new version (and prune retired files) once every
// required schema step succeeded; otherwise leave the stored version
// behind so the upgrade is retried on the next request.
if (!$hostkey_schema_ready || !$tables_ready) {
cacti_log('WARNING: Routerconfigs upgrade did not complete cleanly; leaving the stored version unchanged to retry on the next request', false, 'RCONFIG');
return;
}
db_execute_prepared('UPDATE plugin_config
SET version = ?, name = ?, author = ?, webpage = ?
WHERE directory = ?',
[$info['version'], $info['longname'], $info['author'], $info['homepage'], 'routerconfigs']);
routerconfigs_prune_files();
}
}
/**
* Adds the SSH host-key fingerprint/type storage columns to
* plugin_routerconfigs_devices if they don't already exist. Called from
* routerconfigs_check_upgrade() during upgrade.
*
* @return bool True if both columns exist after this call (whether they
* already existed or were just added), false if adding them
* failed.
*/
function routerconfigs_ensure_hostkey_schema() {
if (!db_column_exists('plugin_routerconfigs_devices', 'ssh_fingerprint')) {
db_execute('ALTER TABLE plugin_routerconfigs_devices
ADD COLUMN `ssh_fingerprint` varchar(255) DEFAULT NULL');
}
if (!db_column_exists('plugin_routerconfigs_devices', 'ssh_hostkey_type')) {
db_execute('ALTER TABLE plugin_routerconfigs_devices
ADD COLUMN `ssh_hostkey_type` varchar(64) DEFAULT NULL');
}
return db_column_exists('plugin_routerconfigs_devices', 'ssh_fingerprint') &&
db_column_exists('plugin_routerconfigs_devices', 'ssh_hostkey_type');
}
/**
* No-op dependency check. Invoked by the Cacti plugin framework to
* verify this plugin's dependencies are satisfied before
* installation/upgrade.
*
* @return bool Always true.
*
* @global array $plugins Reserved/declared for parity with other hook
* implementations; not used directly here.
* @global array $config Cacti global configuration array (declared but
* not directly used here).
*/
function routerconfigs_check_dependencies() {
global $plugins, $config;
return true;
}
/**
* Seeds the built-in device type definitions (Cisco IOS/CatOS/Nexus, HP
* Comware, Dell Switch) via AddDeviceType(). Called from
* routerconfigs_setup_table_new() during install, and from
* routerconfigs_check_upgrade() during upgrade to add any newly
* introduced built-in device types.
*
* @return void
*/
function AddDeviceTypes() {
AddDeviceType('Cisco IOS', 'username:', 'password:', 'copy run tftp', 'show version', 'y', '', 'on','');
AddDeviceType('Cisco CatOS', 'username:', 'password:', 'copy config tftp', '', 'y', 'on', '', '');
AddDeviceType('Cisco Nexus', 'Username:', 'Password:', 'copy running-config tftp://%SERVER%/%FILE% vrf management', 'show version', '', '', '', '');
AddDeviceType('HP Comware', 'usernmae:', 'password:', 'copy startup.cfg tftp://%SERVER%/%FILE%', '', '', '', '', 'on');
AddDeviceType('Dell Switch', 'User', 'Password', 'copy running-config tftp://%SERVER%/%FILE% vrf management', 'show version', 'y', '', '', '', 'Are you sure you want to start');
}
/**
* Inserts a single built-in device type definition if a device type with
* the same name doesn't already exist (so re-running this on upgrade
* doesn't duplicate or overwrite a user-customized entry). Called from
* AddDeviceTypes() for each built-in device type.
*
* @param string $name The device type's display name.
* @param string $promptuser The username prompt pattern to expect.
* @param string $promptpass The password prompt pattern to expect.
* @param string $copytftp The command used to copy the running
* config to a TFTP server.
* @param string $version The command used to query the device's
* version/model.
* @param string $confirm The confirmation response text
* expected during backup.
* @param string $forceconfirm Whether to force the confirmation
* prompt.
* @param string $checkendinconfig Whether to check for a recognizable
* end-of-config marker.
* @param string $elevated Whether this device type requires an
* elevated/enable password.
* @param string $promptconfirm The confirmation prompt pattern to
* expect; defaults to
* 'confirm|to tftp:'.
*
* @return void
*/
function AddDeviceType($name, $promptuser, $promptpass, $copytftp, $version, $confirm, $forceconfirm, $checkendinconfig, $elevated, $promptconfirm = 'confirm|to tftp:') {
$params = [ $name, $promptuser, $promptpass, $copytftp, $version, $confirm, $forceconfirm, $checkendinconfig, $elevated, $promptconfirm, $name ];
db_execute_prepared('INSERT INTO plugin_routerconfigs_devicetypes
(name, promptuser, promptpass, copytftp, version,
confirm, forceconfirm, checkendinconfig, elevated,
promptconfirm)
SELECT
? AS name, ? AS promptuser, ? AS promptpass, ? AS copytftp, ? AS version,
? AS confirm, ? AS forceconfirm, ? AS checkendinconfig, ? AS elevated,
? AS promptconfirm FROM DUAL
WHERE NOT EXISTS(SELECT * FROM plugin_routerconfigs_devicetypes
WHERE name = ? LIMIT 1)', $params);
}
/**
* Injects this plugin's diff.css stylesheet into the page head when
* viewing router-compare.php. Invoked by the Cacti plugin framework via
* the 'page_head' hook.
*
* @return void
*
* @global array $config Cacti global configuration array; used to build
* the stylesheet URL.
*/
function routerconfigs_page_head() {
global $config;
if (strpos(get_current_page(), 'router-compare.php') !== false) {
print get_md5_include_css('plugins/routerconfigs/css/diff.css');
}
}
/**
* Launches a background router-download.php process to run scheduled
* device backups, once per poller interval near the top of each hour's
* cycle, adding '--retry' outside the configured daily retry hour so
* failed backups are retried more aggressively at other times. Invoked
* by the Cacti plugin framework via the 'poller_bottom' hook at the end
* of each poller cycle.
*
* @return void
*
* @global array $config Cacti global configuration array; used to
* resolve the PHP binary and
* router-download.php path.
*/
function routerconfigs_poller_bottom() {
global $config;
$h = date('G', time());
$s = date('i', time()) * 60;
// Check for the polling interval, only valid with the Multipoller patch
$poller_interval = read_config_option('poller_interval');
$poller_interval ??= 300;
if ($s < $poller_interval) {
$command_string = trim(read_config_option('path_php_binary'));
if (trim($command_string) == '') {
$command_string = 'php';
}
$extra_args = ' -q ' . $config['base_path'] . '/plugins/routerconfigs/router-download.php';
$daily = read_config_option('routerconfigs_hour');
if ($daily === false || $daily < 0 || $daily > 23) {
$daily = 0;
}
$daily = (int)$daily;
if ($h != $daily) {
$extra_args .= ' --retry';
}
cacti_log(__("DEBUG: Executing '%s' with arguments '%s'", $command_string, $extra_args, 'routerconfigs'), true, 'RCONFIG', POLLER_VERBOSITY_DEBUG);
exec_background($command_string, $extra_args);
}
}
/**
* Triggers a schema-upgrade check, then registers this plugin's
* 'Router Configs' Settings tab and its configuration fields. Invoked by
* the Cacti plugin framework via the 'config_settings' hook when
* rendering the Settings page.
*
* @return void
*
* @global array $tabs Cacti's registered settings tabs; a
* 'routerconfigs' entry is added.
* @global array $settings Cacti's registered settings fields; a
* 'routerconfigs' entry is added/merged with
* $rc_settings.
* @global array $config Cacti global configuration array (declared
* but not directly used here).
* @global array $rc_settings This plugin's settings field definitions,
* merged into $settings.
*/
function routerconfigs_config_settings() {
global $tabs, $settings, $config, $rc_settings;
routerconfigs_check_upgrade();
$tabs['routerconfigs'] = __('Router Configs', 'routerconfigs');
if (isset($settings['routerconfigs'])) {
$settings['routerconfigs'] = array_merge($settings['routerconfigs'], $rc_settings);
} else {
$settings['routerconfigs'] = $rc_settings;
}
}
/**
* Triggers a schema-upgrade check, and adds this plugin's 'Router
* Configs' entry to the Utilities menu when using the 'console'
* presentation style. Invoked by the Cacti plugin framework via the
* 'config_arrays' hook.
*
* @return void
*
* @global array $menu Cacti's registered admin menu; a 'Router Configs'
* entry is added under 'Utilities' when applicable.
*/
function routerconfigs_config_arrays() {
global $menu;
plugin_routerconfigs_upgrade();
if (read_config_option('routerconfigs_presentation') == 'console') {
$menu[__('Utilities', 'routerconfigs')]['plugins/routerconfigs/router-devices.php'] = __('Router Configs', 'routerconfigs');
}
}
/**
* Adds this plugin's page breadcrumb/navigation entries (device list/
* edit/actions/view-config/view-debug, backup list/edit/actions/view-
* config, account list/edit/actions, and compare). Invoked by the Cacti
* plugin framework via the 'draw_navigation_text' hook.
*
* @param array $nav Cacti's registered navigation text entries.
*
* @return array The $nav array with this plugin's entries added.
*/
function routerconfigs_draw_navigation_text($nav) {
$nav['router-devices.php:'] = [
'title' => __('Router Devices', 'routerconfigs'),
'mapping' => 'index.php:',
'url' => 'router-devices.php',
'level' => '1'
];
$nav['router-devices.php:edit'] = [
'title' => __('(edit)', 'routerconfigs'),
'mapping' => 'index.php:,router-devices.php:',
'url' => 'router-devices.php',
'level' => '2'
];
$nav['router-devices.php:actions'] = [
'title' => __('(actions)', 'routerconfigs'),
'mapping' => 'index.php:,router-devices.php:',
'url' => 'router-devices.php',
'level' => '2'
];
$nav['router-devices.php:viewconfig'] = [
'title' => __('View Config', 'routerconfigs'),
'mapping' => 'index.php:,router-devices.php:',
'url' => 'router-devices.php',
'level' => '2'
];
$nav['router-devices.php:viewdebug'] = [
'title' => __('View Debug', 'routerconfigs'),
'mapping' => 'index.php:,router-devices.php:',
'url' => 'router-devices.php',
'level' => '2'
];
$nav['router-backups.php:'] = [
'title' => __('Router Backups', 'routerconfigs'),
'mapping' => 'index.php:',
'url' => 'router-backups.php',
'level' => '1'
];
$nav['router-backups.php:edit'] = [
'title' => __('(edit)', 'routerconfigs'),
'mapping' => 'index.php:,router-backups.php:',
'url' => 'router-backups.php',
'level' => '2'
];
$nav['router-backups.php:actions'] = [
'title' => __('(actions)', 'routerconfigs'),
'mapping' => 'index.php:,router-backups.php:',
'url' => 'router-backups.php',
'level' => '2'
];
$nav['router-backups.php:viewconfig'] = [
'title' => __('View Config', 'routerconfigs'),
'mapping' => 'index.php:,router-backups.php:',
'url' => 'router-backups.php',
'level' => '2'
];
$nav['router-accounts.php:'] = [
'title' => __('Router Accounts', 'routerconfigs'),
'mapping' => 'index.php:',
'url' => 'router-accounts.php',
'level' => '1'
];
$nav['router-accounts.php:edit'] = [
'title' => __('(edit)', 'routerconfigs'),
'mapping' => 'index.php:,router-accounts.php:',
'url' => 'router-accounts.php',
'level' => '2'
];
$nav['router-accounts.php:actions'] = [
'title' => __('(actions)', 'routerconfigs'),
'mapping' => 'index.php:,router-accounts.php:',
'url' => 'router-accounts.php',
'level' => '2'
];
$nav['router-compare.php:'] = [
'title' => __('Router Compare', 'routerconfigs'),
'mapping' => 'index.php:',
'url' => 'router-compare.php',
'level' => '1'
];
return $nav;
}
/**
* Joins two filesystem path fragments with a single separating slash;
* treats $path2 as absolute (discarding $path1) if it starts with '/'.
* Called from plugin_routerconfigs_fix_backups_pre14() to rebuild
* historical backup file paths.
*
* @param string $path1 The base path fragment.
* @param string $path2 The path fragment to append (or, if absolute,
* to use in place of $path1).
*
* @return string The combined path, with exactly one slash between the
* two fragments.
*/
function plugin_routerconfigs_combinepaths($path1, $path2) {
if (strlen($path2) < 1 || $path2[0] != '/') {
if (strlen($path1) && $path1[strlen($path1) - 1] != '/') {
$path1 = $path1 . '/';
}
} else {
$path1 = '';
}
if (strlen($path2) && $path2[strlen($path2) - 1] != '/') {
$path2 = $path2 . '/';
}
return $path1 . $path2;
}
/**
* Normalizes pre-1.4.0 plugin_routerconfigs_backups rows whose 'filename'
* column may have included a relative directory path, splitting it back
* into separate 'directory'/'filename' values rooted at the configured
* backup path. Called from routerconfigs_check_upgrade() when upgrading
* from a version older than 1.4.0.
*
* @return void
*/
function plugin_routerconfigs_fix_backups_pre14() {
$backups = db_fetch_assoc_prepared('SELECT id, directory, filename FROM plugin_routerconfigs_backups', []);
foreach ($backups as $backup) {
$filename = trim($backup['filename']);
$path = $backup['directory'];
if (strlen($path) && $path[strlen($path) - 1] != '/') {
$path = $path . '/';
}
if (strlen($path) < 1 || $path[0] != '/') {
$path = plugin_routerconfigs_combinepaths(read_config_option('routerconfigs_backup_path'), $path);
}
if (basename($filename) != $filename || $path != $backup['directory']) {
$dir = trim(dirname($filename));
if ($dir == '.') {
$dir = '';
}
$dir = plugin_routerconfigs_combinepaths($path, $dir);
db_execute_prepared('UPDATE plugin_routerconfigs_backups
SET directory = ?, filename = ?
WHERE id = ?',
[$dir, basename($filename), $backup['id']]);
}
}
}
/**
* Renders this plugin's tab icon/link on device and graph header pages,
* when using the 'toptab' presentation style and the current user is
* authorized for router-devices.php. Invoked by the Cacti plugin
* framework via the 'top_header_tabs' and 'top_graph_header_tabs' hooks.
*
* @return void Outputs the tab link HTML directly (nothing if the tab
* style isn't 'toptab' or the user lacks the
* router-devices.php realm).
*
* @global array $config Cacti global configuration array; used to build
* the tab link/image URLs.
*/
function routerconfigs_show_tab() {
global $config;
$tabstyle = read_config_option('routerconfigs_presentation');
$selected_theme = get_selected_theme();
if (api_plugin_user_realm_auth('router-devices.php') && $tabstyle == 'toptab') {
if (preg_match('/router-devices.php/', $_SERVER['REQUEST_URI'], $matches)) {
$down = true;
} else {
$down = false;
}
print '<a id="routerconfigs"
href="' . $config['url_path'] . 'plugins/routerconfigs/router-devices.php">
<img src="' . ($selected_theme == 'classic' ? get_classic_tabimage(__('Routers', 'routerconfig'), $down) : '#') . '" alt="' . __esc('RouterConfigs', 'routerconfigs') . '"></a>';
}
}
/**
* Removes files and directories that a previous version of this plugin
* shipped but that have since moved or been deleted, using the tombstone
* and whitelist lists in manifest.json. Whitelisted (user-data) paths and
* any VCS metadata (.git*) are never touched; the dev-only tests/ tree is
* removed. Any path that resolves outside the plugin directory (a tampered
* manifest.json) is refused, and any file/directory that cannot be removed
* (e.g. read-only) is reported to the Cacti log. Any top-level entry that is
* neither expected nor a tombstone nor whitelisted is logged to the Cacti
* log and left in place. Called on a plugin version change.
*
* @return void
*
* @global array $config Cacti global configuration array; used to resolve
* the plugin directory.
*/
function routerconfigs_prune_files(): void {
global $config;
$plugin_dir = $config['base_path'] . '/plugins/routerconfigs';
$manifest_path = $plugin_dir . '/manifest.json';
if (!is_readable($manifest_path)) {
return;
}
$manifest = json_decode((string) file_get_contents($manifest_path), true);
if (!is_array($manifest)) {
cacti_log('WARNING: routerconfigs manifest.json could not be parsed; skipping file prune', false, 'ROUTERCONFIGS');
return;
}
$tombstones = isset($manifest['tombstones']) && is_array($manifest['tombstones']) ? $manifest['tombstones'] : [];
$expected = isset($manifest['expected']) && is_array($manifest['expected']) ? $manifest['expected'] : [];
$whitelist = isset($manifest['whitelist']) && is_array($manifest['whitelist']) ? $manifest['whitelist'] : [];
$protected = function (string $rel) use ($whitelist): bool {
if (strncmp($rel, '.git', 4) === 0 || strncmp($rel, '.md', 3) === 0) {
return true;
}
foreach ($whitelist as $entry) {
$entry = trim((string) $entry, '/');
if ($entry !== '' && ($rel === $entry
|| strncmp($rel, $entry . '/', strlen($entry) + 1) === 0
|| strncmp($entry, $rel . '/', strlen($rel) + 1) === 0)) {
return true;
}
}
return false;
};
// Security: resolve the plugin directory so a tampered manifest.json
// cannot steer the prune outside of it.
$plugin_real = realpath($plugin_dir);
// Remove tombstoned (moved/deleted) paths plus the dev-only tests/
// tree and the phpunit.xml test configuration.
$remove = $tombstones;
$remove[] = 'tests/';
$remove[] = 'phpunit.xml';
foreach ($remove as $rel) {
$rel = trim((string) $rel, '/');
if ($rel === '' || $protected($rel)) {
continue;
}
// A tombstone must never contain '.'/'..' segments; a tampered manifest
// could use them to escape the plugin directory or target its root.
$segments = explode('/', $rel);
if (in_array('.', $segments, true) || in_array('..', $segments, true)) {
cacti_log(sprintf('WARNING: routerconfigs prune refused to remove %s: path contains a traversal segment (tampered manifest.json?)', $rel), false, 'ROUTERCONFIGS');
continue;
}
$path = $plugin_dir . '/' . $rel;
if (!is_link($path) && !file_exists($path)) {
continue;
}
// Refuse any path that, after resolving symlinks and ../ segments,
// escapes the plugin directory (protects user data from a tampered
// manifest.json).
$anchor = is_link($path) ? dirname($path) : $path;
$real = realpath($anchor);
if ($real === false || ($real !== $plugin_real && strncmp($real, $plugin_real . DIRECTORY_SEPARATOR, strlen((string) $plugin_real) + 1) !== 0)) {
cacti_log(sprintf('WARNING: routerconfigs prune refused to remove %s: path resolves outside the plugin directory (tampered manifest.json?)', $rel), false, 'ROUTERCONFIGS');
continue;
}
if (is_dir($path) && !is_link($path)) {
$removed = routerconfigs_rmtree($path);
} else {
$removed = @unlink($path);
}
if (!$removed) {
cacti_log(sprintf('WARNING: routerconfigs upgrade could not remove %s (check file/directory permissions)', $rel), false, 'ROUTERCONFIGS');
}
}
// Surface any top-level entry the manifest does not account for.
$known = [];
foreach (array_merge($expected, $tombstones) as $entry) {
$top = explode('/', trim((string) $entry, '/'))[0];
if ($top !== '') {
$known[$top] = true;
}
}
$entries = scandir($plugin_dir);
foreach (($entries !== false ? $entries : []) as $entry) {
if ($entry === '.' || $entry === '..' || $entry === 'tests' || $entry === 'phpunit.xml' || $protected($entry) || isset($known[$entry])) {
continue;
}
cacti_log(sprintf('WARNING: routerconfigs upgrade found a file/directory not described in manifest.json: %s (left in place)', $entry), false, 'ROUTERCONFIGS');
}
}
/**
* Recursively deletes a directory and its contents. Symlinks are removed
* without being followed. Helper for routerconfigs_prune_files().
*
* @param string $dir Absolute path to the directory to remove.
*
* @return bool True if the directory and everything under it was removed;
* false if any entry could not be deleted.
*/
function routerconfigs_rmtree(string $dir): bool {
$entries = scandir($dir);
$ok = true;
foreach (($entries !== false ? $entries : []) as $entry) {
if ($entry === '.' || $entry === '..') {
continue;
}
$path = $dir . '/' . $entry;
if (is_dir($path) && !is_link($path)) {
if (!routerconfigs_rmtree($path)) {
$ok = false;
}
} elseif (!@unlink($path)) {
$ok = false;
}
}
if (!@rmdir($dir)) {
$ok = false;
}
return $ok;
}