File: mkrdns

package info (click to toggle)
dnscvsutil 0.5
  • links: PTS
  • area: main
  • in suites: potato
  • size: 80 kB
  • ctags: 35
  • sloc: perl: 557; makefile: 71; sh: 64
file content (763 lines) | stat: -rwxr-xr-x 24,702 bytes parent folder | download
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
#!/usr/bin/perl
#
# mkrdns - Make Reverse DNS - Version 1.4
#
# By: Theo Van Dinter (tvd@chrysalis.com, felicity@kluge.net) (c) 1998-1999
# Revision Info: $Id: mkrdns,v 1.15 1999/06/03 19:30:58 tvd Stab $
#
# The goal of this script is to automatically generate new reverse IP
# mapping zone files for DNS/BIND.  It's been done before, but there
# always seems to be something which makes it not workable in my
# environment.  This script should hopefully fix that.
#
#
# 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.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
#

use strict;
use Getopt::Long;
use MD5;
use POSIX qw(strftime);

# User Specified variables (commandline)
my($debug) = 0; # display debugging information (user)
my($help) = 0; # help screen (user)
my($bootfile) = ""; # configuration file to use (user)
my($ext) = ""; # extension for output files (user)
my($quiet) = 0; # show errors only, or warnings too?
my($version) = 0; # show version information

# Program needed variables
my($i,@domains,%networks,%maps,%serial,%mips,%hash,%ptrs,%netmap,@toskip);
my($nameddir);

# Get commandline parameters
$i=&GetOptions("debug" => \$debug,
					"help" => \$help,
					"extension=s" => \$ext,
					"quiet" => \$quiet,
					"version" => \$version,
					"<>" => sub{$bootfile = $_[0]},	# any "non-option" is
																# config (boot) file
					);

if ( $version ) {
	print "
mkrdns v1.4 (c) 1998-1999
By: Theo Van Dinter (tvd\@chrysalis.com, felicity\@kluge.net)

";
	exit 0;
}

if ( !$i || $help ) { # print help screen if requested or error on params.
	print "
Usage: $0 [options] [configuration file]

Options:
-debug\t\tTurn on debugging (warning, this prints a *LOT* of info)
-extension\tAppend given extension to output files
-help\t\tShow this help screen
-quiet\t\tTurn off warning messages (multiple A records -> IP, etc.)

Configuration file is the full path to either named.boot or named.conf.

";
	exit 0;
}

print "Debugging turned on.
Help       = $help
Extension  = $ext
Quiet Mode = $quiet
" if ( $debug );

# If bootfile wasn't specified, try to find one in /etc...
unless ( $bootfile ) {
	my($stdloc) = "/etc";
	warn "(warn) No configuration file specified.  Checking in standard",
		" location ($stdloc) ...\n";

	opendir(ETC,$stdloc) || die "(fatal) Can't open directory $stdloc:$!";
	my(@files) = grep( /^named\.(boot|conf)$/, readdir(ETC) );
	closedir(ETC);

	print "(debug) Config files found in $stdloc: ",join(",",@files),"\n" if ( $debug );

	if ( $#files == -1 ) { # named.boot and named.conf weren't found, exit.
		die "(fatal) Neither named.boot nor named.conf were found.  Exiting.\n";
	}
	elsif ( $#files == 0 ) { # one file was found, use it.
		$bootfile = "$stdloc/$files[0]";
		warn "(warn) $bootfile was found.\n";
	}
	else { # more than one file was found, use the "best" one.
		$bootfile = "$stdloc/named.conf";
		warn "(warn) Multiple configuration files were found, using $bootfile.\n";
	}
}

READCONF: {
	my($type) = ($bootfile=~/\.(\w+)$/);	# what kind of config file
														# (boot, conf, etc.)?

	# neither boot nor conf -- start crying and exit.
	if ( $type !~ /^(boot|conf)$/ ) {
		die "(fatal) $bootfile is not a boot or conf file.\n";
	}

	# Read configuration file into memory.
	my($config);
	open(CONF,$bootfile) || die "(fatal) Can't open $bootfile:$!";
	while ( $_ = <CONF> ) { # deal with the includes!
		if ( /\bdirectory\s+/i ) { # directory statement!
			($nameddir) = ( /\bdirectory\s+\"?([^\"\s]+)\"?/i );
			print "(debug) Named Directory = $nameddir\n" if ( $debug );
		}

		if ( (/^\s*include\s/i && $type eq "boot") ||
				(/\binclude\s+\"/i && $type eq "conf") ) { # include statement!
			my(@conf) = ($_);

			# (boot) ^include <file>
			# (conf) ^include "<file>";
			for(my($i)=0; $i<=$#conf; $i++) {
				next unless ( $conf[$i] =~ /\binclude\s/i ); # skip non includes ...
				chomp($conf[$i]);
				print "(debug) Include statement ($conf[$i]) found.\n"
					if ( $debug );

				my($file) = ( $conf[$i] =~ /\binclude\s+\"?([^\"\s]+)\"?/i );
				$file =~ s/\s+//; # files shouldn't have whitespace ...
				unless ( $file =~ m!^/! ) { # relative
					unless ( $nameddir ) { # include before directory?  boo!
						$nameddir = ".";
						warn "(warn) Include found before named directory was ",
							"specified!  Using \".\".\n";
					}
					$file = "$nameddir/$file";
				}

				print "(debug) Reading file $file.\n" if ( $debug );
				open(IN,$file) || die "(fatal) Can't open $file:$!";
				splice @conf, $i--, 1, <IN>;	# replace include with data then
														# recheck index
				close(IN);
			}
			
			$config .= join("",@conf); # tack in included stuff ...
			next;
		}

		$config .= $_; # append single line!
	}
	close(CONF);
	print "(debug) Read in $bootfile.\n" if ( $debug );

	# no directory statement anywhere?
	die "(fatal) No named directory specified!\n" unless ( $nameddir );

	my(%files);

	if ( $type eq "boot" ) { # parse named.boot
		foreach $i ( split(/\n/,$config) ) {
			$i=~s/\#.+$//; # remove comments
			$i=~s/^\s+//; # remove whitespace
			$i=~s/\s+$//;

			if ( $i=~/^;\s*mkrdns/i ) { # mkrdns directive
				$i=~s/^;\s*mrkdns\s+//; # strip header

				my($type,$vals) = split(/\s+/, $i, 2);

				print "(debug) mkrdns directive, type \"$type\", ",
					"vals \"$vals\"\n" if ( $debug );

				if ( $type =~ /^map$/i ) {
					my($nm,$nn) = split(/\s+/, $vals);
					@{$netmap{$nm}}= ($nn,&GenMask(split(/\//,$nm)));
				}
				elsif ( $type =~ /^skip$/i ) {
					push(@toskip,$vals);
				}
				else {
					die "(fatal) mkrdns directive type \"$type\" is unknown.";
				}
			}
			elsif ( $i=~/^(primary|secondary)/i ) { # primary/secondary domain ...
				my($type,$domain,$tmp,$file) =
					($i=~/^(\S+)\s+(\S+)\s+(\S+\s+)?(\S+)\s*$/);

				# Skip IP domains we don't control.
				next if ( $type=~/^secondary$/i && $domain=~/\.arpa$/i );

				unless ( $domain && $file ) {
					warn "(warn) Error with line \"$i\" in \"$bootfile\".\n";
					next;
				}

				# The file is already being used!
				die "(fatal) The zone file \"$file\" is being used by two zones!",
					"  Error in config file!\n($files{$file} and $domain ...)\n"
					if ( $files{$file} );

				$files{$file} = $domain;
				$file = "$nameddir/$file" if ( $file !~ m!^/! );	# full path
																					# or relative?

				if ( $domain =~ m!\.arpa$!i ) { # network
					$domain =~ s/\.in-addr\.arpa$//; # just the net ...
					if ( $domain =~ /127$/ ) { # silently skip 127.*
						print "(debug) Skipping $file for the 127.* network.\n"
							if ( $debug );
						next;
					}
					$domain = join( ".", reverse(split(/\./,$domain)) );
					$networks{$domain} = $file;
					print "(debug) Network \"$domain\", File \"$file\", ",
						"Type \"$type\".\n" if ( $debug );
				}
				else { # "normal" domain
					# read in domains in order presented.
					push(@domains,"$domain:$file");
					print "(debug) Domain \"$domain\", File \"$file\", ",
						"Type \"$type\".\n" if ( $debug );
				}
			}
		}
	}
	elsif ( $type eq "conf" ) { # parse named.conf
		my($directives) = ($config=~m!^/\*\s*mkrdns(.+?)\*/!msi);
		if ( $directives ) { # mkrdns directive
			foreach $i ( split(/\n/, $directives) ) {
				$i=~s/\#.+$//;
				$i=~s/^\s+//;
				$i=~s/\s+$//;

				next unless $i=~/\S/;

				my($type,$vals) = split(/\s+/, $i, 2);
				print "(debug) mkrdns directive, type \"$type\", ",
					"vals \"$vals\"\n" if ( $debug );
				if ( $type =~ /^map$/i ) {
					my($nm,$nn) = split(/\s+/, $vals);
					@{$netmap{$nm}}= ($nn,&GenMask(split(/\//,$nm)));
				}
				elsif ( $type =~ /^skip$/i ) {
					push(@toskip,$vals);
				}
				else {
					die "(fatal) mkrdns directive type \"$type\" is unknown.";
				}
			}
		}
    
		# Remove comments from config!
		$config =~ s!/\*.*?\*/!!gs;
		$config =~ s!//.*?\n!\n!gs;
		$config =~ s!#.*?\n!\n!gs;

		# determine which domains and networks we are master for.
		# this first regexp is *REALLY* a pain.
		foreach $i ( $config =~ m!\b(zone\s+\"[^\"]+?\"\s+\w*\s*\{\s*type\s+(?:master|slave)\s*\;\s*file\s+\"[^\"]+?\")!isg ) {
			my($domain,$file) = ( $i=~/\"([^\"]+)\"/g );
			my($type) = ( $i=~/type\s+(master|slave)/i );

			# Skip IP domains we don't control.
			next if ( $type=~/^slave$/i && $domain=~/\.arpa$/i );

			# The file is already being used!
			die "(fatal) The zone file \"$file\" is being used by two zones!  ",
				"Error in config file!\n($files{$file} and $domain ...)\n"
				if ( $files{$file} );
      
			$files{$file} = $domain;
			# full path or relative?
			$file = "$nameddir/$file" if ( $file !~ m!^/! );

			if ( $domain =~ m!\.arpa$!i ) { # network
				$domain =~ s/\.in-addr\.arpa$//; # just the net ...
				if ( $domain =~ /127$/ ) { # silently skip 127.*
					print "(debug) Skipping $file for the 127.* network.\n"
						if ( $debug );
					next;
				}
				$domain = join( ".", reverse(split(/\./,$domain)) );
				$networks{$domain} = $file;
				print "(debug) Network \"$domain\", File \"$file\", Type \"$type\".\n" if ( $debug );
			}
			else { # "normal" domain
				# read in domains in order presented.
				push(@domains,"$domain:$file");
				print "(debug) Domain \"$domain\", File \"$file\", ",
					"Type \"$type\".\n" if ( $debug );
			}
		}
	}
}

my($md5) = new MD5; # get ready for MD5 checks ...

# Read in current reverse maps, report errors.  Remember non-PTR lines
# for creation later on.
REVERSE: {
	while ( my($net,$file) = each %networks ) {
		open(IN,$file) || die "(fatal) Can't open \"$file\" for reading:$!";
		$md5->reset();
		seek(IN,0,0);
		$md5->add(<IN>);
		$hash{$net} = $md5->hexdigest; # get the MD5 value for the original file
		print "(debug) Generated MD5 value for $file: $hash{$net}.\n" if ( $debug );

		print "(debug) Scanning $file for non-PTR lines:\n" if ( $debug );
		seek(IN,0,0);

		# strip out IN PTR, $ORIGIN, and $INCLUDE ...
		$maps{$net} = join("", grep(!/(IN\s+PTR|\$(ORIGIN|INCLUDE))/i, <IN>));
		close(IN);

		# Pick out the serial number ( should be YYYYMMDDVV )
		($i = $maps{$net}) =~ s/;.+?\n//g; # remove comments
		($serial{$file}) = ( $i =~ m!\(\s*(\d+)!s );

		if ( $debug ) { # print out non-PTR records (long...?)
			foreach $i ( split(/\n/, $maps{$net}),
							"Parsed serial number: $serial{$file}" ) {
				print "(debug) $i\n";
			}
		}
	}
}

# Read in current forward maps, convert A records into PTR records,
# add to map.  If there are multiple A records for a given IP, report
# duplicate, and keep first.
READIN: {
	foreach ( @domains ) {
		my($domain,$map) = split(/:/,$_); # $domain = domain, $map = map file
		my($last) = "$domain.";	# what to use in case of blank hostname
										# hostname, $ORIGIN, domain in that order
		my($ext) = $last;			# what to use in case of relative hostname
										# $ORIGIN then domain, in that order	

		print "(debug) Reading in entries from $map for domain $domain.\n"
			if ( $debug );

		open(IN,$map) || die "(fatal) Can't open $map:$!";
		my(@data) = grep(chomp,<IN>); # slurp in map file w/out ending \n's
		close(IN);

		# deal with $INCLUDE statements ...
		print "(debug) Scanning for \$INCLUDE statements...\n" if ( $debug );

		for($i=0; $i<=$#data; $i++) {
			next unless ( $data[$i] =~ /^\$INCLUDE/ ); # skip non-include lines

			# $INCLUDE <file> <origin>
			my($inc,$file,$origin) = split(/\s+/,$data[$i]);

			print "(debug) \"$data[$i]\" specified.\n" if ( $debug );

			$file = "$nameddir/$file" unless ( $file =~ m!^/! );

			open(IN,$file) || die "(fatal) Can't read \$INCLUDE file \"$file\":$!";
			my(@inc) = grep(chomp, <IN>);
			close(IN);

			if ( $origin ) {	# specified origin applies only to specified
									# include file.  put appropriate sections at end
									# of zone file.  see BIND 3rd ed. p.146

				# put $ORIGIN and included file at the end in memory
				splice @data, $#data+1, 0, "\$ORIGIN $origin", @inc;
				splice @data, $i, 1; # remove $INCLUDE
			}
			else { # just replace the $INCLUDE line with the contents of file
				splice @data, $i, 1, @inc;
			}
			$i--; # no matter what, there's a new line where $INCLUDE was now ...
		}

		# the file should be fully expanded in memory now.
		# go through all 'host IN ? ?' and $ORIGIN lines ...
		foreach $i ( grep(/^(\S*(\s+\d+)?\s+IN\s+\S+\s+|\$ORIGIN)/i,@data) ) {
			$i =~ s/;.+$//; # strip comments ...
			next unless ( $i =~ /\S/ ); # skip blanks

			if ( $i =~ /^\$ORIGIN/i ) { # $ORIGIN!
				($ext) = ( $i =~ /^\$ORIGIN\s+(\S+)/i );
				$ext .= ".$domain." if ( $ext !~ /\.$/ ); # not FQDN

				print "(debug) \"$i\" specified.  Final = \"$ext\".\n"
					if ( $debug );

				$last = $ext;
				next;
			}
				
			# parse the line
			my($host,$undef,$type,$ip) = ($i=~m!^(\S*)(\s+\d+)?\s+IN\s+(\w+)\s+(\S+)!i);
			$host = lc $host; # lowercase the host
			$type = uc $type; # make sure the type (A,MX,etc) is uppercase

			next if ( $host eq "\@" );	# @ IN SOA is useless to us since @
												# origin = domain!

			# what to do with host?  interact with last if necessary ...
			if ( $host eq "" ) { # it's a blank, use the last entry ...
				$host = $last;
			}
			elsif ( $host !~ /\.$/ ) { # relative hostname
				$last = $host = "$host.$ext";
			}
			else { # FQDN!
				$last = $host;
			}

			next unless ( $type eq "A" ); # skip non-IN A records

			# should we skip?
			foreach $i ( @toskip ) {
				if ( $host=~/$i/ || $ip=~/$i/ ) {
					print "(debug) Skipping $host/$ip, matched toskip regexp ($i).\n"
						if ($debug);
					$host = "";
					last;
				}
			}

			next unless ( $host );

			# do network mapping
			my($ipm) = &GenMask($ip);
			foreach $i ( keys %netmap ) {
				my($newnet,$netm,$mask) = @{$netmap{$i}};
	
				unless ( ($ipm^$netm) & $mask ) { # 0 if in match made
					my($ptr) = ( $ip =~ /\.(\d+)$/ );
					print "(debug) $ip mapping to $newnet.$ptr ...\n" if ( $debug );
					$ip = "$newnet.$ptr";
					last; # IPs should only match once ...
				}
			}

			# skip hosts in networks we don't run!
			my($network) = &IPinNetwork($ip,%networks);
			unless ( $network ) {
				print "(debug) Not keeping $host = $ip, not in any network.\n"
					if ($debug);
				next;
			}

			print "(debug) Keeping $host = $ip, in network $network.\n"
				if ( $debug );

			if ( $mips{$ip} ) { # IP already has mapping!
				print "The entry in \"$map\" for \"$host\" duplicated ",
					"\"$mips{$ip}\".\nKeeping the \"$mips{$ip} IN A $ip\" entry.\n"
						unless ( $quiet );
				next;
			}

			$mips{$ip} = $host; # Map IP to host ...

			# IP without network prepended (48.7 not 199.172.48.7)
			my($ptr) = ( $ip =~ /^$network\.(.+)$/ );
			push(@{$ptrs{$network}},$ptr);
		}
		close(IN);
	}
}

# Check each output zone file to see if it needs changing
MD5: {
	while ( my($net,$file) = each %networks ) {
		my($nlorigin,$lorigin,$ptr);
		my($map) = $maps{$net};

		@{$ptrs{$net}} = () unless ( defined $ptrs{$net} ); # no IPs in net!
		foreach $ptr ( sort IPSort @{$ptrs{$net}} ) { # ptr = non-net IP #
			my($a) = "$net.$ptr"; # $a = full IP address

			if ( $ptr =~ /\./ ) {	# we should use $ORIGIN statements! (easier
											# reading)
				my($orig);
				($orig,$ptr) = ( $ptr =~ /^([0-9\.]+)\.(\d+)$/ );
				if ( $orig ne $nlorigin ) { # if new origin (between net & host ptr)
					$nlorigin = $orig; # prepare for fast new origin check

					# prepare the new full origin
					$lorigin = join(".", reverse(split(/\./,$orig)),
						reverse(split(/\./,$net)),"in-addr","arpa","");

					$map.= "\$ORIGIN $lorigin\n"; # append $ORIGIN to map
				}
			}

			# Add PTR line to map
			$map.= sprintf "%-3s IN\tPTR\t%s\n", $ptr, $mips{$a};
		}

		$md5->reset();
		my($hv) = $md5->hexhash($map); # generate MD5 for new map

		if ( $hv ne $hash{$net} ) { # maps are different!
			print "(debug) File $file needs to be updated.\n" if ( $debug );
			my($fserial) = &strftime("%Y%m%d00",localtime(time));

			# if fserial > serial, then use fserial directly ...
			if ( $fserial <= $serial{$file} ) {	# serial is >= fserial, add 1 to
															# serial and use it if possible

				if ( $serial{$file} =~ /99$/ ) { # version 99! can't roll.
					die "(fatal) Serial number $serial{$file} (file \"$file\")",
						" ends in 99 -- can't add 1!  Freaky!\n";
				}

				$fserial = $serial{$file} + 1;
			}

			print "(debug) Changing serial number for $file from",
				"$serial{$file} to $fserial\n" if ( $debug );

			$map =~ s/(\(.+?)$serial{$file}/$1$fserial/s;

			$file .= ".$ext" if ( $ext ); # file or file.ext?

			print "Updating file \"$file\"\n" unless ( $quiet );
			open(OUT,">$file") || die "(fatal) Can't open $file for writing:$!";
			print OUT $map;
			close(OUT);
		}
		else {
			print "File $file needs no modification.\n" unless ( $quiet );
		}
	}
}

exit 0;

# Is the given IP address in any of the specified networks?
# note: this routine only checks on byte boundaries
# Return 0 if not, network number if yes.
#
sub IPinNetwork {
	my($ip,%networks)=@_; # IP to check, hash of networks to check

	do { # matches most specific network first (10.0.49 before 10 ...)
		$ip =~ s/\.[^\.]+$//; # remove last octet (host #)
		return $ip if ( $networks{$ip} );
	} while ( $ip =~ /\./ ); # while there's a period in the IP

	return 0;
}

# Sorts IP Addresses numerically!
sub IPSort {
	my(@f) = split(/\./,$a);
	my(@s) = split(/\./,$b);
	my($i) = 0;

	# $#f and $#s should be equal ... don't confuse it.
	$i++ while( $i<$#f && $f[$i]==$s[$i] );
	return ( $f[$i] <=> $s[$i] );
}

# Generate a bitmask from an IP/Network/bit count.
# Returns array of bitmasks from array of input values.
#
sub GenMask {
	my(@marray,$val);

	foreach $val ( @_ ) {
		if ( $val =~ /^\d+$/ ) { # /27 ...
			push(@marray, ~(2**(32-$val)-1));
		}
		else { # 255.255.255.224 ...
			my($mask);
			foreach (split(/\./,$val)) {
				$mask = ($mask<<8) + $_;
			}
			push(@marray,$mask);
		}
	}

	return @marray;
}

__END__

=head1 NAME

mkrdns - MaKe Reverse DNS (auto generate PTR maps)

=head1 SYNOPSIS

mkrdns [options] [configuration file]

=head1 DESCRIPTION

mkrdns is a program designed to auto-generate reverse DNS maps (IN PTR
records).  Some programs already accompany the BIND source package
that will do this kind of thing on a single domain or network basis.
mkrdns will read either a named.boot or named.conf file, figure out
which domains and networks to deal with, and then generate the reverse
maps.

You are deemed "in charge" of a network/domain if you are the primary
DNS for a reverse zone, or if you are either the primary or secondary
for a forward zone.  The exception to this rule is that the 127.*
network is not auto-generated due to the "1 IN PTR localhost." issue.

=head1 OPTIONS

-debug           Print debugging information.  (this will
                 print a B<LOT> of information, be warned.)

-extension <ext> Append the given extension to the output
                 files.  This is useful if you want to
                 have the reverse maps generated, but want
                 to check their contents before use.

-help            The help screen.

-quiet           Turn off warning messages (multiple A
                 records -> IP, etc.)  Good for scripts,
                 but you probably want to check on what
                 the warnings report. 

=head1 CONFIGURATION FILE

mkrdns reads the standard BIND configuration files I<named.boot> and
I<named.conf>.  If you don't specify the full path to the file on the
command line, mkrdns assumes that one (or both) will exist in /etc and
will search for them.  If none are found, the program exits.  If one
is found, it is used.  If both are found, named.conf is used.

=head1 DIRECTIVES

Directives are new in mkrdns since version 1.2.  Think of directives
as configuration options for mkrdns which are simply comments to BIND.
The current directives are B<map> and B<skip>.

Map allows you to map IN A hosts to another network.  This was
designed in for the purpose of handling DNS for a subnet of a class C
network which you do not control.  (See the DNS & BIND O'Reilly and
Associates book, 3rd Ed., pg. 215-218) Assume that you have
10.4.4.32/27 (ie: you have the 32 IPs from 10.4.4.32 to 10.4.4.63 ...)
You want to do reverse mappings for those IPs.  How do you do it?
You've subnetted on a non-octet boundary.  The solution is to become
the master for another network (such as 32.4.4.10.in-addr.arpa. or
32-63.4.4.10.in-addr.arpa.), and CNAME the correct reverse pointers to
the ones you're in charge of.  It's pretty funky.  The format for the
directive is:
   map <network/mask> <new network>

Ex: map 10.4.4.32/27 10.4.4.32-63

This maps all hosts between 10.4.4.32 and 10.4.4.63 to 10.4.4.32-63.32
to 10.4.4.32-63.63.

Skip forces mkrdns to ignore certain hosts/IPs via regular
expression. The concept is that there are some IN A records that you
would like to skip and not create a reverse entry.  Skip allows
this. (for instance, "foo IN A 10.4.4.32" and "mail IN A 10.4.4.32"
both exist, but you want to force foo as the reverse lookup and ignore
mail.  The following example can do this for you.)
Format:
   skip <regular expression>

Ex: skip ^mail

This will skip any host (or IP) that matches the "^mail" regular
expression.  The host is the FQDN, and the IP is before mapping (see
above).

The format of a directive differs (sorry) between named.conf and
named.boot.  UNIX-style comments (the hash mark then the comment) are
allowed.

=head2 named.boot directives

Directives look like a comment, so the format is simply:

 ; mkrdns <directive type> <parameters>

=head2 named.conf directives

To make directives more efficient with BIND 8, the format is slightly
different: 

 /* mkrdns
    <directive type> <parameters>
    ...
 */

=head1 EXAMPLES

B<mkrdns -e new /etc/named.boot>

This will run mkrdns over the file /etc/named.boot.  Output files will
be generated as <name>.new (i.e.: if the PTR zone file is called
160.zone, the output will be 160.zone.new.)

=head1 NOTES

I tend to use this script like a lint check.  i.e.: Edit the proper
zone files, then run mkrdns.

As with most documentation, there are probably things that aren't mentioned
in the docs that the script does/assumes/etc.  I apologize for any
inaccuracies/omissions.  Let me know if there are any parts that have an
"issue", and I'll see if I can't straighten it out.

=head1 ASSUMPTIONS

- the <network>.zone reverse map files must already be created, and
have the appropriate information (SOA/NS records, etc.) in there.
This script will strip out any PTR records, and then add them back in.
(This means anything like blank lines and comments will be moved to the
top of the file.)  $ORIGIN and $INCLUDE are striped as of mkrdns 1.3.

- you must be at least a secondary for all domains which reference IP
networks for which you're responsible.  There is no means (currently
at least) to specify a PTR record for a non-existent A record, so this
script must have access to all A records that need to be "reversed".

- if you have more than 1 A record pointing to a specific IP, you can't
have both be the PTR record.  This script takes the first A record it
sees as the one used for the PTR record.  A warning is printed for any
additional entries.  (While the RFCs don't prohibit multiple PTR records
for the same IP, I have yet to find anyone who can give me a good reason
to do it.)

- requires the MD5 library to be installed (see your local favorite CPAN
mirror) to handle if reverse maps have changed.

- map serial numbers should be in YYYYMMDDVV format.  (YYYY = year,
MM = month, DD = day, VV = version (00-99).  This script will convert
your serial number to this format if it's not already.  I don't have too
many daily DNS changes, so the action for not being able to update the
serial number (ie: VV is at 99 and can't be increased) is to simply exit.
If someone really wants a way around this, I can add in a flag to use the
above format or not (ie: is the serial number representative of the date,
or is it just a number?)  Either way, a problem will come up when the
serial number reaches 4294967295 (max value), but that's another story.

=head1 AUTHOR

Theo Van Dinter <tvd@chrysalis.com> <tvd@kluge.net>

=cut