-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnsadmin
More file actions
executable file
·3489 lines (3173 loc) · 82.8 KB
/
nsadmin
File metadata and controls
executable file
·3489 lines (3173 loc) · 82.8 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
#!/bin/sh
#-
# Copyright (c) 2006-2013 Parker Lee Ranney TTEE
# Copyright (c) 2017-2025 Devin Teske <dteske@FreeBSD.org>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.
#
############################################################ IDENT(1)
#
# $Title: Distributed bind9 administration and management tool $
# $Id: nsadmin,v 1.1 2012/05/09 21:39:43 root Exp $
# $Copyright: 2017-2025 Devin Teske. All rights reserved. $
# $FrauBSD: nsadmin/nsadmin 2025-09-26 02:02:39 -0700 freebsdfrau $
#
############################################################ INFORMATION
#
# nsadmin -- Update Bind's installation on the master NS server. RCS
# is used for file history. All updates will be sent out as an
# email to the appropriate admin address. A lock is kept during
# the run of this program to prevent conflicting updates.
#
# --------------------------------------------------------------------
# Notes:
# - Requires bind server and nsadmin.conf on the master.
# - Users must be placed in the DNSOPS group in sudoers as a
# result of the commands that require root access.
# Commands used via sudo: awk chmod chown cp find mv rm service su
# (and possibly [depending on your system]: systemctl)
# - Users must also belong to the "bind" group in /etc/group to
# edit the files.
#
# Requirements to use AXFR transfer method ($transfer in nsadmin.conf):
# - nsaxfr on the secondary Bind servers.
# - User 'cm' and the authorized_keys2 file for that user must be
# installed on all secondary Bind servers. The 'cm' user account
# and ID file must be on the server with this script.
# - User 'cm' must be able to remotely execute via SSH the
# following command:
# sudo /usr/local/bin/nsaxfr
# Without password on the secondary Bind servers.
# --------------------------------------------------------------------
# Version History:
# Sep 2025: Release 6.1.5
# - Fix EXIT: line processing in batch error suppression awk
# - Add missing 'next' to prevent EXIT: lines from appearing
# Sep 2025: Release 6.1.4
# - CRITICAL FIX: Fix PTR record initialization bug in genrev()
# - Only use -i (initialize) flag on first file, not all files
# - Prevent subsequent files from wiping out previous PTR records
# - Fixes catastrophic PTR loss introduced in 6.0 optimization
# - PERFORMANCE: Replace f_filter_errors with f_suppress_errors
# - Eliminate overhead from error suppression (O(n) -> O(1))
# - Use single awk process instead of multiple grep calls
# - Add streaming error suppression with immediate fflush()
# - Dramatic performance improvement for error-heavy operations
# - Zero overhead when suppress_errors is empty (common case)
# - Whitespace fixes
# - Add version to more places in logged output
# Sep 2025: Release 6.1.3
# - CRITICAL FIX: Fix PTR record generation regression
# - Replace regex matching with literal string prefix matching
# - Use substr() and length() instead of regex ~ operator
# - Fixes false matches by dots in zone names (regex wildcards)
# - Change zone2rev awk script to use fname instead of file path
# - Bug introduced during 6.0 refactoring when zone2rev was
# changed to accept multiple files
# Sep 2025: Release 6.1.2
# - Fix -a (sync-all) 6.1 regression causing interactive mode
# - Reset skip variable in -a loop to prevent sticky exclusions
# - Ensures -a processes all valid zones as intended
# - Whitespace
# Sep 2025: Release 6.1.1
# - Replace hard-coded error filter with configurable suppression
# - Add suppress_errors variable to nsadmin.conf
# - Default: no error suppression (empty suppress_errors var)
# - Example:
# suppress_errors="Operation not permitted|Permission denied"
# - Add f_filter_errors() function for centralized error handling
# - PERFORMANCE: Avoid subshells when suppress_errors is empty
# - PERFORMANCE: Use variable-by-reference to eliminate subshells
# - Maintain backward compatibility while allowing customization
# Sep 2025: Release 6.1
# - Add zone name validation, prevent invalid files
# - Remove pattern matching in exclude conf variable (#*, ~*, *~)
# - Add zone_exclude_patterns conf variable for patterns
# - Default exclusions: "*.backup* *.bak*" (can customize)
# - Can customize: allows valid domains like "test.backup"
# - Core validation: *[!0-9a-zA-Z.-]*|..|.|[.-]*|*[.-]
# - Fix BIND failures from files like "3.2.1.backup-working"
# - Prevents invalid files from causing BIND deployment failures
# - Silently filter "Operation not permitted" errors
# - Silently filter "Permission denied" errors
# - Filter errors during rollback, local, and remote push
# - Suppress "unknown format" warnings for empty files
# - Preserve other error messages for actionable issues
# - Fixup code whitespace and line lengths
# Sep 2025: Release 6.0.5
# - CRITICAL FIX: Fix PTR record format in zone2rev function
# - Extract basename from file path for correct domain format
# - Add missing options (-h, -u, -v) to usage documentation
# - Whitespace fixes
# - Reverts broken 6.0.4 release
# Sep 2025: Release 6.0.4 (REVERTED)
# - Attempted fix for sync-all PTR generation (BIND failures)
# - Added duplicate zone2rev calls leading to file conflicts
# Sep 2025: Release 6.0.3
# - Fix infinite loop in zone2rev_awk process_file function
# - Simplify while loop to use getline directly in condition
# - Add single version log statement at start of operations
# Sep 2025: Release 6.0.2
# - Fix awk variable conflicts in zone2rev_awk script
# - Rename array variables to avoid scalar/array name conflicts
# - Change files[] array to output_files[] array
# - Change subnets[] array to found_subnets[] array
# - Fix NR parameter conflict by using lineno local variable
# - Resolve "use of non-array as array" awk errors
# Sep 2025: Release 6.0.1
# - Fix syntax error in case statement (remove # from pattern)
# Sep 2025: Release 6.0
# - Add f_count_ifs() and f_replaceall() from FreeBSD bsdconfig
# - Add f_getword() function for shell-native word extraction
# - Add f_indent() function to abstract line indentation patterns
# - Optimize zone2rev to accept multiple file arguments
# - Enhance zone2rev to accept multiple subnets
# (-s subnet1 -s subnet2 or -s "subnet1 subnet2")
# - Replace echo|sed patterns with shell parameter expansion
# - Replace echo|awk indentation with printf loops
# - Replace tr|sort|tr pipeline with f_replaceall + NL
# - Replace echo|wc -l with f_count_ifs
# - Move file existence checking into zone2rev()
# - Fix exclude pattern matching to use literal strings (prevents
# unintended matches with patterns like #*, ~*, *~)
# - Optimize space-separated list building (unconditional space +
# trim vs conditional space)
# - Eliminate .updzones temporary file (direct genzone call)
# - Fix genrev() to use f_count_ifs instead of destructive set --
# - Transform genrev() from O(N×M×V) to O(N×V) complexity
# - Use POSIX-compliant arithmetic expressions
# - Maintain single-file architecture and all existing behavior
# Sep 2025: Release 5.7.1
# - Fix subnet collection in edit mode to prevent PTR record loss
# - Optimize reverse DNS regeneration
# Sep 2025: Release 5.7
# - Add overlapping subnet dependency detection
# Jan 2022: Release 5.6.6
# - Allow yes/no (instead of just y/n) for chance-acceptance
# Jan 2021: Release 5.6.5
# - Fix permissions even after no changes detected in edit
# Jan 2021: Release 5.6.4
# - Ignore emacs/vim recovery files in $nsadmindir
# Nov 2020: Release 5.6.3.1
# - Update sudo requirement comments
# Nov 2020: Release 5.6.3
# - Fix a typo
# Nov 2020: Release 5.6.2
# - Prevent editing zone if journal exists
# Nov 2020: Release 5.6.1
# - Prevent configuring non-text journal files in genconf()
# Nov 2020: Release 5.6
# - Allow config of extra options in named.conf(5) includes
# Nov 2020: Release 5.5
# - Transfer generated includes to secondaries
# Nov 2020: Release 5.4
# - Fix permission issues with transfer method
# Nov 2020: Release 5.3
# - Allow multiple admin/critical mail recipients
# (space-separated)
# Nov 2020: Release 5.2.1
# - Set default view in config and clarify separator
# Nov 2019: Release 5.2
# - Add a warn function
# - Warn when a jnl (journal) file exists for master zone
# - Fixup warnings about jnl (journal) files
# Oct 2019: Release 5.1.1
# - Prevent management of more invalid domain names
# - Comments
# Oct 2019: Release 5.1
# - Rename AXFR software and use modern terminology
# - Fix bug with some shells that fail on $( case ... )
# - Update comments for accuracy
# Oct 2019: Release 5.0
# - Fix bug on detecting revert of all changes after edit
# - Make backup of previous versions silent
# Oct 2019: Release 4.9.9
# - Show all pending diffs with `/diff' in edit mode
# - Improve pause() and change ENTER to return
# - Use pause() in place of peppered recipes to wait
# - Make a read that is ignored more visibly-so
# - Revert changed state if edit undoes a change
# Oct 2019: Release 4.9.8
# - Do not use sudo in sigquit()
# - Revert some previous changes around locking
# Oct 2019: Release 4.9.7
# - Add /diff command
# - Centralize definition of view/edit commands
# Oct 2019: Release 4.9.6
# - Whitespace
# - Trim leading blank lines from /log output
# Oct 2019: Release 4.9.5
# - Hide zone history unless in edit mode
# - Add /log command
# - Enable commands in view mode (/log only)
# Oct 2019: Release 4.9.4
# - Improve handling of commit message
# - Add user-provided commit message to checkin()
# - Optimize genconf() for performance
# Oct 2019: Release 4.9.3
# - Add /mv command
# - Make globals all-caps
# - Remove signal management variable (ransig)
# - Remove unused variable (vfail)
# - Improve security around /-command execution
# - Display deleted zones in menu, greyed-out
# - Add details on edit how to resurrect removed zones
# Oct 2019: Release 4.9.2
# - Revert reset of traps before generation tasks
# - Whitespace
# - Remove stray semi-colon
# Oct 2019: Release 4.9.1
# - Fix editmaster() read-only issue on re-edits
# - Fix unnecessary compound string in sigquit()
# - Re-checkout /rm'd zones on unclean exit
# - Remove /new'd zones on unclean exit
# - Make /rm require config regeneration and edit desc
# - Add `-u' and `-v' command-line options to checkout()
# - Use checkout() in newzone() instead of one-off `co'
# - Ensure /rm'd zones/revs are not resolvable after rm
# - Prevent `/' commands in view mode
# - Improve vimcat handling
# - Warn user when journal file exists
# - Move `local' definitions in rmzone() to top of function
# - Always forcefully lock files before ci in checkin()
# - Highlight rm'd zones as-such (red) during backups
# - Print config file paths during genconf()
# - Reset traps before entering generation stage
# Oct 2019: Release 4.9
# - Move vim filetype hint to top of new zone template
# - Move command-line option global definitions
# - Fix `-n host[,...]' config override
# - Show diff when importing changes detected during sync
# Oct 2019: Release 4.8.9
# - If running as root, require new `-u user' option
# - Check user after sourcing config so we can write to log
# - Fail immediately if log variable not set in config
# - Use green banner in edit mode, red when unsaved changes
# Oct 2019: Release 4.8.8
# - Ignore jnl files created by nsupdate in conf generation
# Oct 2019: Release 4.8.7
# - Add support for @ in zone2rev()
# Oct 2019: Release 4.8.6
# - Final fixup for /new RCS checkout
# - Improve backup efficiency
# - Skip checkin if no differences
# - Create new files with template contents
# Oct 2019: Release 4.8.5
# - Show files being backed up
# - Fixup /new RCS checkout
# Oct 2019: Release 4.8.4
# - User interface/log enhancement
# Oct 2019: Release 4.8.3
# - Fixup user interface and log nits
# Oct 2019: Release 4.8.2
# - Fixup creation of new/existing zone via /new
# Oct 2019: Release 4.8.1
# - Fixup RCS checkout by /new
# Oct 2019: Release 4.8
# - Make /new check for RCS files
# Oct 2019: Release 4.7.7
# - Add support for sender domain override
# Oct 2019: Release 4.7.6
# - Fix ANSI clear codes
# Oct 2019: Release 4.7.5
# - Fix ANSI escape sequences for BSD
# Oct 2019: Release 4.7.4
# - Remove log of sudo failure
# Oct 2019: Release 4.7.3
# - Fix detection of sudo failure in predit()
# Oct 2019: Release 4.7.2
# - Wordsmithing
# Oct 2019: Release 4.7.1
# - Fix version
# - Change header color when changes made
# Oct 2019: Release 4.7
# - Add /new and /rm commands to edit prompt
# Oct 2019: Release 4.6.5
# - Fix TLD record generation
# Oct 2019: Release 4.6.4
# - Fix error in genconf() when no rev maps exist
# Oct 2019: Release 4.6.3
# - Fix copy/pasta
# Oct 2019: Release 4.6.2
# - Minor edit
# Oct 2019: Release 4.6.1
# - Use sudo to create view directories
# Oct 2019: Release 4.6
# - Add support for TLD A/AAAA records
# - Create $nsadmindir on initial launch
# Oct 2019: Release 4.5.9
# - Use full paths in genconf()
# Oct 2019: Release 4.5.8
# - Fix configuration defaults
# Oct 2019: Release 4.5.7
# - Make mail optional with disabled defaults
# Oct 2019: Release 4.5.6
# - Make default $transfer empty in config
# Oct 2019: Release 4.5.5
# - Use BSD compatible ANSI escape sequences for printf
# Oct 2019: Release 4.5.4
# - Fix config
# Oct 2019: Release 4.5.3
# - Add OS Glue to config for FreeBSD
# Oct 2019: Release 4.5.2
# - Defer loading of config until after processing options
# - Defer check for root until after options processing
# - Comments
# - Look for config in proper directory based on OS
# Oct 2019: Release 4.5.1
# - Remove confusing line numbers from named-checkzone output
# - Comments and other Minor edits
# - Fix version
# Oct 2019: Release 4.5
# - Make include files for generated zones and rev maps
# Oct 2019: Release 4.4.1
# - Remove log if exiting due to running as root
# Oct 2019: Release 4.4
# - Show lock file location when locked
# - Do not use sudo in sigquit() if first use fails
# - Release lock if exiting due to sudo failure
# Oct 2019: Release 4.3
# - Fix sync (-s) based checkin from automated edits
# Oct 2019: Release 4.2.2
# - Add support for vimcat in read-only view mode
# - Improve vimcat support with PAGER in all modes
# Oct 2019: Release 4.2.1
# - Show progress as we generate rev maps
# - Only checkin sync'd files on exit if they pass syntax check
# - Fix memory leak in genrev()
# - Minimally improve and document sudo support
# Oct 2019: Release 4.2
# - checkin files after sync (-s)
# Oct 2019: Release 4.1.1
# - Lower sync verbosity
# Oct 2019: Release 4.1
# - Add support for inline custom TTL preceding protocol family
# Oct 2019: Release 4.0.4
# - Do not show contextual diff before review
# - Add whitespace after main menu prompt
# Oct 2019: Release 4.0.3
# - Fix rev map synchronization with `-s'
# - Trim trailing whitespace on code lines
# - Fix spurious error from `cd -' in sigquit()
# Oct 2019: Release 4.0.2
# - Fix permission issues for members of $bindgroup
# Oct 2019: Release 4.0.1
# - Fix hang on stdin from RCS co when file is writable
# Oct 2019: Release 4.0
# - Replace bash arrays with POSIX /bin/sh syntax
# - Do not overwrite config files if they exist on install
# - Change umask to 0022
# - Remove obsolete code
# - Improve check for duplicate running instances
# - Create required directories if they do not exist
# - Optimize usage of "cd" to fix errors
# - Improved debugging
# - Renamed *-var.inc to *.conf and cleanup
# - Merge *.inc files and zone2rev.awk into nsadmin
# - Set default view [required] to program basename (nsadmin)
# - Add support for `IN' protocol family in master zones
# - Fix `-l' to work with `-s'
# - Prevent Outlook from eating blank lines in diffs
# - Merge nsaxfr-centos7 into nsaxfr
# - Add support for vimcat
# - Add limited ANSI coloring to console output
# - Add support for `less -F' when viewing diffs
# - Add `-v' to get version
# Aug 2019: Release 3.2
# - Add Makefile
# Jul 2019: Release 3.1
# - Initial Public release.
# - Enable restriction to prevent anonymous root access.
# - Add secondary variable to `nsadmin-var.inc'.
# - Fix hard-coded primary/secondary in `GEN FUNCTIONS'.
# Jul 2018: Release 3.0
# - Major rewrite and code cleanup.
# - Improved error checking of zone files.
# - Support IPv6 AAAA records.
# Jul 2018: Release 2.6
# - Fix bug preventing some reverse entries from being created
# Jul 2018: Release 2.5
# - Fix bug preventing reverse lookup of A records ending in
# .0 or .255
# Jul 2017: Release 2.4
# - Ask the user for a message to describe changes.
# - Only allow one instance of nsadmin at a time.
# Jun 2017: Release 2.3
# - Add `-n hosts' syntax for selecting a subset of secondaries.
# - Ported to FreeBSD.
# Mar 2010: Release 2.2
# - Fixed comments.
# Jul 2006: Release 2.1
# - Modified to migrate zones manually as IXFR and AXFR
# are not reliable.
# Jun 2006: Release 2.0
# - Major rewrite and creation of includes.
# - Syntax checking.
# - Update only the rev maps with a changed IP.
# - Added read-only interface.
# - Added ability to generate zone files and rev maps
# from the master files without performing updates,
# known as sync.
# Apr 2006: Release 1.0
# - Basic interface and zone generation.
#
############################################################ INCLUDES
NSADMIN_CONF=nsadmin.conf # See OS Glue
############################################################ GLOBALS
VERSION='$Version: 6.1.5 $'
_VERSION="${VERSION#*: }" # Extract clean version string
_VERSION="${_VERSION% *}" # Remove trailing RCS marker
pgm="${0##*/}" # Program basename
progdir="${0%/*}" # Program directory
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin
#
# Global exit status
#
SUCCESS=0
FAILURE=1
#
# Command-line options
#
USER= # -u user
EDITMODE= # -e
SYNC= # -s
SYNCALL= # -a
UPDZONES= # -l file[,...] (also used to track edited zones)
TRANSFER= # -n host[,...] (taken from $NSADMIN_CONF if unused or NULL)
#
# Commands
#
EDITCMDS="/diff /log /mv /new /rm"
VIEWCMDS="/diff /log"
#
# OS Glue
#
: ${UNAME_s:=$( uname -s )}
#
# Miscellaneous
#
NL="
" # END-QUOTE
COMMITMSG= # User-provided commit message
CHANGES= # Have changes been made?
FAILFILE= # File that failed zonetest()
FAILTYPE= # Type of file that failed
MVJNL= # Move journal for commit
MVJNLREV= # Reverse move journal for interrupt
NEWZONES= # Newly created zones
RMDREVS= # Rev maps of removed zones
RMDZONES= # Removed zones
ROOTFAIL= # Exited due to running as root
SEP="-----------------------------------------------------------------------"
# Separator
SEPDBL="====================" # Double separator
SUBNETS= # Subnets changed for rev maps
SYNCCNT=0 # Number of files sync'd
UPDATE=0 # Stage of master file updates
############################################################ FUNCTIONS
have(){ type "$@" > /dev/null 2>&1; }
# setvar $var_to_set [$value]
#
# Implement setvar for shells unlike FreeBSD sh(1).
#
if ! have setvar; then
setvar()
{
[ $# -gt 0 ] || return $SUCCESS
local __setvar_var_to_set="$1" __setvar_right="$2" __setvar_left=
case $# in
1) unset "$__setvar_var_to_set"
return $? ;;
2) : fall through ;;
*) echo "setvar: too many arguments" >&2
return $FAILURE
esac
case "$__setvar_var_to_set" in *[!0-9A-Za-z_]*)
echo "setvar: $__setvar_var_to_set: bad variable name" >&2
return 2
esac
while case "$__setvar_right" in *\'*) : ;; *) false ; esac
do
__setvar_left="$__setvar_left${__setvar_right%%\'*}'\\''"
__setvar_right="${__setvar_right#*\'}"
done
__setvar_left="$__setvar_left${__setvar_right#*\'}"
eval "$__setvar_var_to_set='$__setvar_left'"
}
fi
# f_replaceall $string $find $replace [$var_to_set]
#
# Replace all occurrences of $find in $string with $replace. If $var_to_set is
# either missing or NULL, the variable name is produced on standard out for
# capturing in a sub-shell (which is less recommended due to performance
# degradation).
#
# To replace newlines or a sequence containing the newline character, use $NL
# as `\n' is not supported.
#
f_replaceall()
{
local __left="" __right="$1"
local __find="$2" __replace="$3" __var_to_set="$4"
while :; do
case "$__right" in *$__find*)
__left="$__left${__right%%$__find*}$__replace"
__right="${__right#*$__find}"
continue
esac
break
done
__left="$__left${__right#*$__find}"
if [ "$__var_to_set" ]; then
setvar "$__var_to_set" "$__left"
else
echo "$__left"
fi
}
# f_count_ifs $var_to_set string ...
#
# Sets $var_to_set to the number of words (split by the internal field
# separator, IFS) following $var_to_set.
#
f_count_ifs()
{
local __var_to_set="$1"
shift 1
set -- $*
setvar "$__var_to_set" $#
}
# f_getword [-v var_to_set] $n $word1 $word2 ...
#
# Get the nth word from the provided arguments.
# Words are split by IFS at caller's stack before function invocation.
#
f_getword()
{
local __var_to_set= __n
local OPTIND=1 OPTARG __flag
while getopts v: __flag; do
case "$__flag" in
v) __var_to_set="$OPTARG" ;;
esac
done
shift $(( $OPTIND - 1 ))
__n="$1"
shift 1 # __n
# Validate that n is numerical and not null
case "$__n" in
""|*[!0-9]*) return $FAILURE ;;
esac
# Get the nth word
eval "local __word=\${${__n}}"
if [ "$__var_to_set" ]; then
eval "$__var_to_set=\"\$__word\""
else
echo "$__word"
fi
}
# f_indent [-p prefix] [input]
#
# Read lines from input (or stdin) and print each line with indentation prefix.
# Default prefix is a tab character. Use -p to specify custom prefix.
#
f_indent()
{
local prefix="\t"
local OPTIND=1 OPTARG flag
while getopts p: flag; do
case "$flag" in
p) prefix="$OPTARG" ;;
esac
done
shift $(( $OPTIND - 1 ))
if [ $# -gt 0 ]; then
# Input provided as argument
printf '%s\n' "$*" | while IFS= read -r line; do
printf "$prefix%s\n" "$line"
done
else
# Read from stdin
while IFS= read -r line; do
printf "$prefix%s\n" "$line"
done
fi
}
# f_validate_zone_name zone_name
#
# Validate a zone name for RFC compliance.
# Logs warning if invalid. Returns SUCCESS if valid, FAILURE if invalid.
#
f_validate_zone_name()
{
local zone="$1"
case "$zone" in
*[!0-9a-zA-Z.-]*|..|.|[.-]*|*[.-])
warn "Skipping invalid zone name: $zone"
return $FAILURE ;;
*)
return $SUCCESS ;;
esac
}
# f_check_zone_exclusions zone_name
#
# Check if a zone name matches any exclusion patterns.
# Logs warning if excluded. Returns SUCCESS if excluded, FAILURE if allowed.
#
f_check_zone_exclusions()
{
local zone="$1" pattern
for pattern in $zone_exclude_patterns; do
case "$zone" in
$pattern)
warn "Excluded zone name: $zone (matches $pattern)"
return $SUCCESS ;;
esac
done
return $FAILURE
}
# f_suppress_errors [-c] [command [args ...]]
#
# High-performance error suppression using awk for real-time filtering.
# Filters stderr/stdout based on suppress_errors configuration patterns.
#
# USAGE:
# f_suppress_errors < input_stream # Filter stdin
# command 2>&1 | f_suppress_errors # Filter command output
# f_suppress_errors -c command [args ...] # Execute command w/ filtering
#
# The -c flag executes the command and filters its combined stdout/stderr,
# while preserving the original command's exit status.
#
# PERFORMANCE: Uses single awk process instead of multiple grep subprocesses
# for dramatic performance improvement with large error volumes.
#
exec 9<<'EOF'
BEGIN { exit_status = 0 }
/^EXIT:[0-9]+$/ { exit_status = substr($0, 6); next }
{ # Check if line matches any suppression pattern
if ($0 ~ suppress_errors) { # Suppress this line (don't print)
next
} else { # Print line and immediately flush for responsiveness
print
fflush()
}
}
END { exit exit_status }
EOF
f_suppress_errors_awk=$( cat <&9 )
f_suppress_errors()
{
if [ "$1" = "-c" ]; then
shift 1 # -c
if [ ! "$suppress_errors" ]; then
"$@"
return
fi
{ "$@" 2>&1; echo EXIT:$?; } |
awk -v suppress_errors="$suppress_errors" \
"$f_suppress_errors_awk"
elif [ ! "$suppress_errors" ]; then
cat
else
awk -v suppress_errors="$suppress_errors" \
"$f_suppress_errors_awk"
fi
}
# usage
#
# Print the help menu and exit.
#
usage()
{
exec >&2
echo
echo " Usage: $pgm ..."
echo
echo " Edit Mode:"
echo " Used to edit the master $pgm files:"
echo
echo " $pgm [-n hosts] -e"
echo
echo " Review Mode: (Default)"
echo " Used to view the master $pgm files:"
echo
echo " $pgm"
echo
echo " Sync Mode:"
echo " Used to update the Bind zone files with the data from"
echo " the master $pgm files. This does not allow"
echo " editing of the master files:"
echo
echo " $pgm -s [-ah?] [-n hosts] -l <file>[,<file>, ..."
echo
echo " -a Sync all master files."
echo " -l <file>[,<file>] Sync list of files."
echo " -n <host>[,<host>] Override transfer hosts."
echo
echo " Other Options:"
echo " -h Show this help message."
echo " -u <user> Specify user for audit logging."
echo " -v Show version information."
echo
exit $FAILURE
}
############################################################ REV FUNCTIONS
# Functions for generating rev maps from master zones
# zone2rev [-cdilv] file ...
#
# Read nsadmin zone files and produce rev maps.
#
# Options:
# -c Enable ANSI color. Implies `-d'
# -d Enable debug messages printed to stderr
# -i Initialize files to zero length
# -l List subnets on stdout and exit
# -r List reverse arpa subnets on stdout and exit
# -S Use sudo
# -s subnets Process only subnet(s) from $file
# -V Verify contents and exit. Implies `-d'
# -v view Process only view from $file
#
exec 9<<'EOF'
function err(str)
{
if (verify) vstatus = 1
if (!debug) return
if (console)
printf "\033[35m%s\033[36m:\033[32m%d\033[36m:\033[m %s\n",
file, NR, str > "/dev/stderr"
else
printf "%s:%d: %s\n", file, NR, str > "/dev/stderr"
fflush()
}
# _asorti(src, dest)
#
# Like GNU awk's asorti() but works with any awk(1)
# NB: Named _asorti() to prevent conflict with GNU awk
#
function _asorti(src, dest, k, nitems, i, idx)
{
k = nitems = 0
for (i in src) dest[++nitems] = i
for (i = 1; i <= nitems; k = i++) {
idx = dest[i]
while ((k > 0) && (dest[k] > idx)) {
dest[k+1] = dest[k]; k--
}
dest[k+1] = idx
}
return nitems
}
# validate_ipaddr4(ip)
#
# Returns zero if the given argument (an IP address) is of the proper format.
#
# The return value for invalid IP address is one of:
# 1 One or more individual octets within the IP address (separated
# by dots) contains one or more invalid characters.
# 2 One or more individual octets within the IP address are null
# and/or missing.
# 3 One or more individual octets within the IP address exceeds the
# maximum of 255 (or 2^8-1, being an octet comprised of 8 bits).
# 4 The IP address has either too few or too many octets.
#
function validate_ipaddr4(ip, octets, noctets, n, octet)
{
# Split on `dot'
noctets = split(ip, octets, /\./)
if (noctets != 4) return 4
for (n = 1; n <= noctets; n++) {
octet = octets[n]
# Return error if the octet is null
if (octet == "") return 2
# Return error if not a whole/positive integer
if (octet ~ /[^0-9]/) return 1
# Return error if the octet exceeds 255
if (octet > 255) return 3
}
return 0
}
# validate_ipaddr6(ip)
#
# Returns zero if the given argument (an IPv6 address) is of the proper format.
#
# The return value for invalid IP address is one of:
# 1 One or more individual segments with the IP address
# (separated by colons) contains one or more invalid characters.
# Segments must contain only combinations of the characters 0-9,
# A-F, or a-f.
# 2 Too many/incorrent null segments. A single null segment is
# allowed within the IP address (separated by colons) but not
# allowed at the beginning or end (unless a double-null segment;
# i.e., "::*" or "*::").
# 3 One or more individual segments within the IP address
# (separated by colons) exceeds the length of 4 hex-digits.
# 4 The IP address entered has either too few (less than 3), too
# many (more than 8), or not enough segments, separated by
# colons.
# 5 The IPv4 address at the end of the IPv6 address is invalid.
#
function validate_ipaddr6(ip,
segments, nsegments, n, segment, h, short, nulls,
contains_ipv4_segment, maxsegments)
{
sub(/%.*$/, "", ip) # remove interface spec if-present
# Split on `colon'
nsegments = split(ip, segments, /:/)
# Return error if too many or too few segments
# Using 9 as max in case of leading or trailing null spanner
if (nsegments > 9 || nsegments < 3) return 4
h = "[0-9A-Fa-f]"
short = sprintf("^(%s|%s|%s|%s)$", h, h h, h h h, h h h h)
nulls = contains_ipv4_segment = 0
for (n = 1; n <= nsegments; n++) {
segment = segments[n]
#
# Return error if this segment makes one null too-many. A
# single null segment is allowed anywhere in the middle as well
# as double null segments are allowed at the beginning or end
# (but not both).
#
if (segment == "") {
nulls++
if (nulls == 3) {
# Only valid syntax for 3 nulls is `::'
if (ip != "::") return 2
} else if (nulls == 2) {
# Only valid if begins/ends with `::'
if (ip !~ /(^::|::$)/) return 2
}
continue
}
#
# Return error if not a valid hexadecimal short
#
if (segment ~ short) continue # Valid segment of 1-4 hex digits
if (segment ~ /[^0-9A-Fa-f]/) {
# Segment contains at least one invalid char
# Return error immediately if not last segment
if (n < nsegments) return 1
# Otherwise, check for legacy IPv4 notation
if (segment ~ /[^0-9.]/) {
# Segment contains at least one invalid
# character even for an IPv4 address
return 1
}
# Return error if not enough segments
if (nulls == 0) {
if (nsegments != 7) return 4
}
contains_ipv4_segment=1
# Validate ipv4_segment
if (validate_ipaddr4(segment)) return 5
} else {
# Segment characters are all valid but too many
return 3
}
}
if (nulls == 1) {
# Single null segment cannot be at beginning/end
if (ip ~ /(^:|:$)/) return 2
}
#
# A legacy IPv4 address can span the last two 16-bit segments,
# reducing the amount of maximum allowable segments by-one.
#
maxsegments = contains_ipv4_segment ? 7 : 8
if (nulls == 0) {
# Return error if missing segments with no null spanner
if (nsegments != maxsegments) return 4
} else if (nulls == 1) {
# Return error if null spanner with too many segments
if (nsegments > maxsegments) return 4
} else if (nulls == 2) {
# Return error if leading/trailing `::' with too many segments
if (nsegments > (maxsegments + 1)) return 4
}
return 0
}
# split6(ip, array)
#
# Split the elements of IPv6 ip into 32 hex-nibbles stored in array.
#
function split6(ip, nibbles, n, ip4, octs, s, i, nibs, nib, k)
{
for (n = 1; n <= 32; n++) nibbles[n] = 0
if (match(ip, /:[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$/)) {
ip4 = substr(ip, RSTART + 1)
ip = substr(ip, 1, RSTART - 1)
split(ip4, octs, /\./)
ip = sprintf("%s:%02x%02x:%02x%02x",
ip, octs[1], octs[2], octs[3], octs[4])
}
if (sub(/^::/, "", ip)) {
n = 32
ip = sprintf("%04s", ip)
for (k = 4; k > 0; k--) nibbles[n--] = substr(ip, k, 1)
} else if (sub(/::$/, "", ip)) {
n = 1
ip = sprintf("%04s", ip)
for (k = 1; k <= 4; k++) nibbles[n++] = substr(ip, k, 1)
} else if (ip ~ /::/) {
left = right = ip
sub(/::.*$/, "", left)
sub(/^.*::/, "", right)
s = split(left, nibs, /:/)
for (i = 1; i <= s; i++) {
n = (i - 1) * 4 + 1
nib = sprintf("%04s", nibs[i])
for (k = 1; k <= 4; k++)
nibbles[n++] = substr(nib, k, 1)
}
s = split(right, nibs, /:/)