aboutsummaryrefslogtreecommitdiff
path: root/nsdbimport/nsdbimport
blob: 7c72f718a11e4d686e8a582a636dc67b839093aa (plain)
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
#! /usr/bin/perl
# Copyright (C) 2015 Sergey Poznyakoff <gray@gnu.org>
#
# 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 3, 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, see <http://www.gnu.org/licenses/>.

use strict;
use Getopt::Long qw(:config gnu_getopt no_ignore_case);
use File::Basename;
use Pod::Usage;
use Pod::Man;
use String::Regexp;
use DBI;

use constant EX_OK           => 0;
use constant EX_USAGE        => 64;    # command line usage error
use constant EX_DATAERR      => 65;    # data format error
use constant EX_NOINPUT      => 66;    # cannot open input file
use constant EX_UNAVAILABLE  => 69;    # service unavailable 
use constant EX_SOFTWARE     => 70;    # internal software error (not used yet)
use constant EX_OSFILE       => 72;    # critical OS file missing
use constant EX_CANTCREAT    => 73;    # can't create (user) output file
use constant EX_CONFIG       => 78;    # configuration error 

my $progname = basename($0);      # This script name;
my $progdescr = "converts BIND zone files to SQL database";
my $debug;
my $dry_run;
my $verbose;
my $bind_directory;
my $bind_config;
my $dbd;
my $generate_seen;
my $record_count;

sub error {
    my $msg = shift;
    local %_ = @_;
    print STDERR "$progname: " if defined($progname);
    print STDERR "$_{prefix}: " if defined($_{prefix});
    print STDERR "$msg\n"
}

sub debug {
    my $l = shift;
    error(join(' ',@_), prefix => 'DEBUG') if $debug >= $l;
}

sub abend {
    my $code = shift;
    print STDERR "$progname: " if defined($progname);
    print STDERR "@_\n";
    exit $code;
}

END {
    if ($record_count and ($verbose or $?)) {
	print "$progname: $record_count records processed successfully\n";
    }
}

my %config;

sub readconfig {
    my ($file, $kw) = @_;
    open(my $fd, "<", $file)
	or abend(EX_UNAVAILABLE, "can't open configuration file $file: $!");
    my $line;
    my $err;
    while (<$fd>) {
	++$line;
	chomp;
	if (/\\$/) {
	    chop;
	    $_ .= <$fd>;
	    redo;
	}
	
	s/^\s+//;
	s/\s+$//;
	s/#.*//;
	next if ($_ eq "");

	unless (/([\w_-]+)\s*=\s*(.*)/) {
	    error("$file:$line: malformed line");
	    next;
	}
	my ($k,$v) = ($1, $2);

	unless (exists($kw->{$k})) {
	    error("$file:$line: unknown keyword $k");
	    ++$err;
	    next;
	}
	$config{$k} = $v;
    }
    close $fd;
    exit(EX_CONFIG) if $err;
    abend(EX_CONFIG, "rr-query is not defined in $file")
	unless defined($config{'rr-query'});
}

sub istrue {
    my $s = shift;
    return $s =~ /^([1yt])|(yes)|(true)|(enable)$/i;
}

# ###################
sub parse_named_conf {
    my %zone;
    abend(EX_OSFILE, "$bind_config doesn't exist or is unreadable")
	unless -f $bind_config and -r $bind_config;
    open(my $fd, '-|',
	 "cfpeek --parser=bind $bind_config")
	or die "can't run cfpeek: $!";
    while (<$fd>) {
	if (/^\.options\.directory:\s+(.+)/) {
	    $bind_directory = $1;
	} elsif (/^\.zone="([^"]+)"\.((?:type)|(?:file)):\s+(.+)/) {
	    $zone{$1}->{$2} = $3;
	}
    }
    close $fd;
    my %files;
    while (my ($name, $ref) = each %zone) {
	if ($ref->{type} eq 'master' and defined($ref->{file})) {
	    debug(1, "register zone $name, file $ref->{file}");
	    $files{$ref->{file}} = $name;
	}
    }
    return %files;
}
# ###################
my $rx_class = array_to_regexp('IN', 'HS', 'CH');
my @rrtypes = ('A', 'AAAA', 'A6', 'AFSDB',
	       'CNAME', 'DNAME', 'DNSKEY', 'DS',
	       'EUI48', 'EUI64', 'HINFO', 'ISDN',
	       'KEY', 'LOC', 'MX', 'NAPTR',
	       'NS', 'NSEC', 'NXT', 'PTR',
	       'RP', 'RRSIG', 'RT', 'SIG',
	       'SOA', 'SPF', 'SRV', 'TXT',
	       'WKS', 'X25');
my $rx_rr = array_to_regexp(@rrtypes);

# ###################
sub replvar {
    my ($rec, $var, $opt) = @_;
    my %option;
    if (defined($opt)) {
	foreach my $x (split /,/, $opt) {
	    if ($x =~ /([?+\.@-])(.*)/) {
		$option{$1} = $2;
	    }
	}
    }

    my $val = $rec->{$var} || '';
    
    if ($val eq '') {
	if (defined($option{'-'})) {
	    $val = $option{'-'};
	} elsif (defined($option{'?'})) {
	    my $text = $option{'?'} || "$var not defined";
	    error($text, prefix => $rec->{locus});
	}
    } elsif (defined($option{'+'})) {
	$val = $option{'+'};
    }

    if ($val ne '') {
	if ($val eq '@' and defined($option{'@'})) {
	    $val = $option{'@'} || $rec->{origin};
	    $val .= '.' unless $val =~ /\.$/;
	} elsif (defined($option{'.'}) and $val !~ /\.$/) {
	    $val .= '.' . ($option{'.'} || $rec->{origin});
	    $val .= '.' unless $val =~ /\.$/;
	}
    }
    return $val;
}
	
sub query_expand {
    my ($q, $rec) = @_;
    $q =~ s/\$\{([\w_-]+)(?::(.+?))?\}/replvar($rec, $1, $2)/gex;
    debug(2, "$rec->{locus}: $q");
    return $q;
}

sub sql_query {
    my ($tmpl, $rec) = @_;
    my $q = query_expand($tmpl, $rec);
    unless ($dry_run) {
	$dbd->do($q)
	    or abend(EX_UNAVAILABLE, $dbd->errstr."\nFailed query: $q");
    }
    ++$record_count;
}

# generate($expr, $origin, $file, $line);
# $GENERATE start-stop[/step] lhs[{offset[,width[,type]]}] rr-type rhs[{offset[,width[,type]]}]
# http://www.zytrax.com/books/dns/ch8/generate.html

sub format_part {
    my ($i, $xhs, $xwid, $xtyp, $loc) = @_;
    my $ctr;

    if ($xtyp =~ /^[doxX]$/) {
	$ctr = sprintf($xwid > 0 ? "%0${xwid}$xtyp" : "%$xtyp", $i);
    } elsif ($xtyp =~ /[nN]/) {
	my $f = $xtyp eq 'n' ? '%x' : '%X';
	my @a = reverse(split(//, sprintf("%x", $i)));
	unshift @a, '0' while (($#a+1) < $xwid);
	$ctr = join('.', @a);
    } else {
	error("invalid type $xtyp in \$GENERATE", prefix => $loc);
    }
    $xhs =~ s/\$/$ctr/;
    return $xhs;
}

sub generate {
    my ($expr, $origin, $ttl, $file, $line) = @_;
    my $p = '([^\s\{]+)(?:\{(\d+)(?:(?:,(\d+))(?:,([doxXnN])))\})?';
    if ($expr =~ /(\d+)-(\d+)(?:\/(\d+))?\s+$p\s+($rx_rr)\s+$p/) {
	my ($start,$stop,$step,
	    $lhs,$loff,$lwid,$ltyp,
	    $rr,
	    $rhs,$roff,$rwid,$rtyp) = ($1, $2, $3 || 1,
				       $4, $5 || 0, $6 || 0, $7 || 'd',
				       $8,
				       $9, $10 || 0, $11 || 0, $12 || 'd');
	for (my $i = $start; $i <= $stop; $i += $step) {
	    import_record({origin => $origin,
			   locus => "$file:$line",
			   ttl => $ttl,
			   rr => $rr,
			   label => format_part($i + $loff,$lhs,$lwid,$ltyp),
			   data => format_part($i + $roff,$rhs,$rwid,$rtyp)});
	}
    }
}

# ###################
my $rxt = '[\dshdwmy]+';
sub insert_soa {
    my ($rec, $tmpl) = @_;
    if ($rec->{data} =~ /^([^\s]+)\s+([^\s]+)\s+\(\s*($rxt)\s+($rxt)\s+($rxt)\s+($rxt)\s+($rxt)\s*\)$/i) {
	$rec->{ns} = $1;
	$rec->{resp_person} = $2;
	$rec->{serial} = $3;
	$rec->{refresh} = parsetime($4, $rec->{origin});
	$rec->{retry} = parsetime($5, $rec->{origin});
	$rec->{expire} = parsetime($6, $rec->{origin});
	$rec->{minimum} = parsetime($7, $rec->{origin});
	sql_query($tmpl, $rec);
    } else {
	error("malformed SOA: '$rec->{data}'",
	      prefix => "warning: $rec->{locus}");
    }
}
    
sub insert_mx {
    my ($rec, $tmpl) = @_;
    if ($rec->{data} =~ /^(\d+)\s+(.+)$/) {
	$rec->{mx_priority} = $1;
	$rec->{mx} = $2;
	sql_query($tmpl, $rec);
    } else {
	error("malformed MX: '$rec->{data}'",
	      prefix => "warning: $rec->{locus}");
    }
}

my %rrfun = (SOA => \&insert_soa,
	     MX => \&insert_mx);

sub insert_rr {
    my ($rec, $tmpl) = @_;
    sql_query($tmpl || $config{'rr-query'}, $rec);
}

# ###################
sub parsetime {
    my ($s, $loc) = @_;
    my $t = 0;
    if ($s =~ /^\d+$/) {
	$t = $s;
    } else {
	my @keyord = ('s', 1,
		      'm', 60,
		      'h', 3600,
		      'd', 86400,
		      'w', 7*86400,
		      'm', 31*86400,
		      'y', 365*86400);
	if ($s =~ s/(\d+)$//) {
	    $t = $1;
	    shift @keyord;
	    shift @keyord;
	}	    
      OUTER:
	while (1) {
	    my $i = 0;
	    my $set = join('', map { ++$i % 2 ? $_ : () }  @keyord);
	    last if $set eq '';
	    last unless $s =~ s/(\d+)([$set])$//i;
	    my $k = lc $2;
	    while (shift(@keyord) ne $k) {
		shift(@keyord);
		last OUTER if $#keyord == -1;
	    }
	    $t += $1 * shift(@keyord);
	}
	unless ($s eq '')  {
	    my $p = "warning: $loc" if $loc;
	    error("time specification error near $s", prefix => $p);
	    return undef;
	}
    }
    return $t;
}

sub import_record {
    my $rec = shift;
    my $kw = lc($rec->{rr}).'-query';

    if (defined($rrfun{$rec->{rr}}) and defined($config{$kw})) {
	&{$rrfun{$rec->{rr}}}($rec, $config{$kw});
    } else {
	insert_rr($rec, $config{$kw});
    }
}

sub zimport {
    my ($file, $origin) = @_;

    $file = "$bind_directory/$file"
	if $file !~ m#^/# and defined($bind_directory);
    debug(1, "processing file $file, origin $origin");
    open(my $fd, "<", $file)
	or abend(EX_NOINPUT, "can't open input file $file: $!");
    my $line;
    my $ttl = 86400; # FIXME
    while (<$fd>) {
	++$line;
	chomp;
	s/^\s+//;
	s/\s+$//;
	s/;.*//;
	next if ($_ eq "");
	if (/^\$TTL\s+(.+?)\s*$/) {
	    $ttl = parsetime($1);
	} elsif (/^\$ORIGIN\s+(.+)/) {
	    $origin = $1;
	} elsif (/^\$INCLUDE\s+([^\s]+)\s+(.+)$/) {
	    zimport($1, $2);
	} elsif (/^\$INCLUDE\s+(.+)/) {
	    zimport($1, $origin);
	} elsif (/^\$GENERATE\s+(.+)/) {
	    if (istrue($config{generate})) {
		generate($1, $origin, $ttl, $file, $line);
	    } else {
		error('$GENERATE ignored',
		      prefix => "$file:$line: warning");
		$generate_seen = 1;
	    }
	} elsif (/^\$/) {
	    error("ignoring unrecognized directive",
		  prefix => "$file:$line: warning");
    	         # LABEL TTL CLASS RR DATA
	} elsif (/(?:(@|[^\s]+)\s+)?(?:([\dwdhms]+)\s+)?(?:$rx_class\s+)?($rx_rr)\s+(.*)/i) {
	    my $rr = uc $3;
	    if ($rr eq 'SOA') {
		unless (/\)$/) {
		    my $s = <$fd>;
		    $s =~ s/;.*//;
		    $_ .= $s;
		    redo;
		}
	    }

	    import_record({origin => $origin,
			   label => $1,
			   ttl => parsetime($2, "$file:$line") || $ttl,
			   rr => $rr,
			   data => $4,
			   locus => "$file:$line"});
	    
	    if ($rr eq 'SOA') {
		$origin = $1 unless $1 eq '@';
	    }
	}
    }
    close $fd;
}

# ###################
my $conffile;
my $origin = '.';

GetOptions("h" => sub {
		    pod2usage(-message => "$progname: $progdescr",
			      -exitstatus => 0);
	   },
	   "help" => sub {
		    pod2usage(-exitstatus => EX_OK, -verbose => 2);
	   },
	   "usage" => sub {
		    pod2usage(-exitstatus => EX_OK, -verbose => 0);
	   },
	   "directory|C=s" => \$bind_directory,
	   "bind-config|from-config=s" => \$bind_config,
	   "origin=s" => \$origin,
	   "debug|d+" => \$debug,
	   "verbose|v+" => \$verbose,
	   "dry-run|n" => \$dry_run,
	   "config|c=s" => \$conffile) or exit(EX_USAGE);

++$debug if $dry_run;

unless (defined($conffile)) {
    ($conffile) = grep { -e $_ } (
	'.nsdbimport.conf',
	"$ENV{HOME}/.nsdbimport.conf",
	'/etc/nsdbimport.conf');
}

abend(EX_OSFILE, "no configuration file; please use the --config option")
    unless defined $conffile;

my %kw = ('database' => 1,
	  'host' => 1,
	  'port' => 1,
	  'db-params' => 1,
	  'user' => 1,
	  'password' => 1,
	  'db-default-file' => 1,
	  'generate' => 1,
	  'rr-query' => 1);

foreach my $rr (@rrtypes) {
    $kw{lc($rr).'-query'} = 1;
}

readconfig($conffile, \%kw);

debug(1, "connecting to the database");

my $arg = "";
$arg .= ":database=$config{database}" if defined $config{database};
$arg .= ":host=$config{host}" if defined $config{host};
$arg .= ":port=$config{port}" if defined $config{port};
$arg .= ":$config{'db-params'}" if defined $config{'db-params'};
$arg .= ":;mysql_read_default_file=$config{'db-default-file'}"
    if defined $config{'db-default-file'};

if (!$arg
    or (!defined($config{user}) and !defined($config{'db-default-file'}))) {
    my $my_cnf = "$ENV{HOME}/.my.cnf";
    if (-r $my_cnf) {
        debug(1, "using mysql option file $my_cnf");
        $arg .= ";mysql_read_default_file=$my_cnf";
    }
}
$arg = 'DBI:mysql'.$arg;

$dbd = DBI->connect($arg, $config{user}, $config{password},
		    { PrintError => 0, AutoCommit => 1})
    or abend(EX_UNAVAILABLE, "can't connect to the database: ".$DBI::errstr);

if (defined($bind_config)) {
    abend(EX_USAGE, "extra input files") if $#ARGV >= 0;
    my %files = parse_named_conf;
    while (my ($file, $origin) = each %files) {
	zimport($file, $origin);
    }
} else {
    abend(EX_USAGE, "no input files") unless $#ARGV >= 0;
    foreach my $arg (@ARGV) {
	zimport($arg, $origin);
    }	  
}

error('set generate=yes to enable processing of $GENERATE directives')
    if ($generate_seen);

$dbd->disconnect;
__END__
=head1 NAME

nsdbimport - import data from BIND-compatible zone files to SQL database

=head1 SYNOPSIS

B<nsdbimport>
[B<-dhnv>]
[B<-C> I<DIR>]
[B<-c> I<FILE>]    
[B<--bind-config=>I<FILE>]
[B<--config=>I<FILE>
[B<--debug>]
[B<--directory=>I<DIR>]
[B<--dry-run>]
[B<--from-config=>I<FILE>]
[B<--help>]    
[B<--origin=>I<ZONE>]
[B<--usage>]
[B<--verbose>]    
[I<ZONEFILE>...]
    
=head1 DESCRIPTION

Imports DNS records from zone files in BIND-compatible format into a SQL
database.  The format of the database (or, more precisely, SQL statements
used to populate the database) is determined by configuration file.

Source files can either be listed as command line arguments, or read directly
from BIND configuration file, supplied by the B<--bind-config> option.  In
former case, it is recommended to define explicit origin using the
B<--origin> option.

When using B<--bind-config> option, no files can be given in the command line.
Instead, B<nsdbimport> parses B<named> configuration file and selects B<zone>
statements that have type B<master>.  Then it imports files listed in these
statements.  In this case, origin is determined automatically for each file.
    
=head1 OPTIONS

=over 4

=item B<-d>, B<--debug>

Increase debug level.

=item B<-C> I<DIR>

Set current working directory.  All zone files specified with relative
file names will be searched in that directory.    
    
=item B<-c>, B<--config=>I<FILE>

Read configuration from I<FILE>.  If this option is not given, B<nsdbimport>
tries the following files: F<.nsdbimport.conf>, F<~/.nsdbimport.conf> and
F</etc/nsdbimport.conf>.  First of them which exists is read.  See the
section B<CONFIGURATION> below for a discussion of configuration file format.

=item B<--bind-config>, B<--from-config=>I<FILE>

Parse BIND configuration file I<FILE> and process all files corresponding
to master zones.  Note, that this option relies on B<cfpeek>(1) being
installed on your system.
    
=item B<-n>, B<--dry-run>

Don't actually import data, print what would have been done instead.    
    
=item B<--origin=>I<ZONE>

Set initial origin.  Useful when processing individual files.

=item B<-v>, B<--verbose>

Verbose mode.  Report count of successfully processed records at the
end of the run.    
    
=back

The following options cause the program to display informative text and
exit:

=over 4
    
=item B<-h>

Show a short usage summary.

=item B<--help>

Show man page.

=item B<--usage>

Show a concise command line syntax reminder.

=back

=head1 CONFIGURATION

Configuration file supplies credentials for accessing the database and
templates for the SQL queries (normally, B<INSERT> statements) to be
used in order to import records of particular B<RR> types.

If the command line option B<--config> (B<-c>) is given, B<nsdbimport>
takes its value as the name of configuration file to read.  Otherwies,
it tries to read file F<.nsdbimport.conf> from the current working
directory.  If it does not exist, the program looks it up in the home
directory of the user.  If that file doesn't exist either,
F</etc/nsdbimport.conf> is read.  If none of these files exists,
B<nsdbimport> terminates with error code .

The configuration file consists of statements -- pairs I<keyword>=I<value>,
occupying a single logical line.  Within a statement, any amount of white
space is allowed before I<keyword>, after I<value> and on either side of
the equals sign.  To split very long lines, the usual backslash
escaping is used: any line ending with a backslash immediately followed
by a newline indicates continuation on the next line.  The newline character
is stripped off and the contents of the next line is appended in its place.

Comments begin with B<#> character and extend to the end of physical line.

Empty lines are ignored.

The following statements configure database credentials:

=over 4

=item B<database=>I<STRING>

Database name.

=item B<host=>I<NAME>

Hostname or IP address of the host running the database server.    

=item B<port=>I<NUM>

Port number, if it differs from the default.

=item B<db-params=>I<STRING>

Additional database-specific options.  E.g. path to the UNIX socket file, or
the like.    
    
=item B<user=>I<STRING>

Database user name.

=item B<password=>I<STRING>

Password to connect to the database.

=item B<db-default-file=>I<FILE>

Pathname of the mysql defaults (a.k.a. options) file to use.  The utility
will look for the section B<[client]> and use options defined in it.  The
use of mysql defaults file is advised, instead of specifying database
credentials in B<nsdbimport> configuration file.

=back

The following two options control how the import is performed, in general.

=over 4    
    
=item B<generate=>I<no>|I<yes>

Enable or disable processing of B<$GENERATE> directives.  Such directives
usually insert enormous amount of data into the database and therefore
are disabled by default.  Set B<generate = yes> to enable them.

=back

=head2 Query templates

SQL statements used to actually import DNS data into the database are
formed using I<templates>.  Configuration statements that define templates
have the following form:

=over 4

B<I<rrtype>-query = >I<TEMPLATE>

=back

where I<rrtype> is the B<RR> of the record converted to lower case.  At the
time of this writing, B<nsdbimport> supports the following B<RR> types: B<A>,
B<AAAA>, B<A6>, B<AFSDB>, B<CNAME>, B<DNAME>, B<DNSKEY>, B<DS>, B<EUI48>,
B<EUI64>, B<HINFO>, B<ISDN>, B<KEY>, B<LOC>, B<MX>, B<NAPTR>, B<NS>, B<NSEC>,
B<NXT>, B<PTR>, B<RP>, B<RRSIG>, B<RT>, B<SIG>, B<SOA>, B<SPF>, B<SRV>,
B<TXT>, B<WKS>, B<X25B>.  Thus, for example, the statement B<soa-query> defines
the query used to import B<SOA> records.

However, you don't need to define a template for each possible B<RR> type.
Instead you can use the I<generic query>, which is defined using the following
statement:

=over 4

B<rr-query = >I<TEMPLATE>      

=back

This query will be used whenever no particular query is defined for the
B<RR> type of a record being imported.
    
The I<TEMPLATE> used in B<*-query> statements must be a valid SQL statement
(normally, an B<INSERT>), with I<macro references> used in place of the
actual data.  In its simplest form, a macro reference is B<${I<macro>}>,
where I<macro> is the name of a macro variable.  Upon executing the statement,
macro references are replaced with the actual values of the corresponding
variables.  The following variables are defined for all B<RR> types:

=over 4

=item B<rr>

The B<RR> type.
    
=item B<origin>

Origin of the record.
    
=item B<label>

Label (or I<owner-user>) of the record.

=item B<ttl>

TTL value (seconds).
    
=item B<data>

Data (or I<right-hand side>) of the record.
    
=item B<locus>

Location of the source record in the input file (B<I<file-name>:I<line-number>>).

=back

For example, given the following input file F<example.zone>:

    $ORIGIN example.com.
    www   1H  A  192.0.2.1

the second line will produce the following macro variables:

    rr     = A
    origin = example.com.
    ttl    = 3600
    data   = 192.0.2.1
    locus  = example.zone:2

For B<MX> records, the following two macro variables are defined:

=over 4
    
=item B<mx>

Host name of the MX server.

=item B<mx_priority>

Server priority

=back

For B<SOA> records, the following additional variables are defined:

=over 4
    
=item B<ns>

Hostname of the principal NS server.
    
=item B<resp_person>

Email address of the responsible person (in standard NS notation: B<@> being
substituted by a dot).    
    
=item B<serial>

Serial number.    
    
=item B<refresh>

Zone refresh interval (seconds).
    
=item B<retry>

Retry interval (seconds).
    
=item B<expire>

Expire interval (seconds).    
    
=item B<minimum>

Minimum initerval (seconds).    
    
=back    

More complex form of macro references allows for I<flags>, which control how
the value of the variable is represented after expansion.  Flags are specified
as a comma-separated list following a colon after the variable name, e.g.:

=over 4

B<${label:-@}>

=back

The construct above expands to the actual value of label, unless it is empty,
in which case it expands to B<@>.

The following flags are recognized (brackets denoting optional part:

=over 4

=item B<?>[I<text>]

If the variable is not defined or empty, displays a warning message.  Default
I<text> is B<I<var> not defined>, where I<var> is replaced with the name
of the variable in question.    
    
=item B<->I<text>

If the variable is not defined or empty, replace it with I<text>.
    
=item B<+>I<text>

If the variable is defined, expand to I<text>, instead of its value.
    
=item B<.>[I<text>]

If the expansion of the variable does not end with a dot, append to it a dot
and the current origin.  If I<text> is supplied, use it as the origin.  For
example, if B<origin=example.com> and B<data=www>, then B<${data:.}> will
produce B<www.example.com>.    
    
=item B<@>[I<text>]

If variable expands to the apex symbol (B<@>), replace it with the actual
origin.  If I<text> is supplied, use it instead.    

=back    

=head1 FILES

Configuration files:
    
=over 4

=item F<.nsdbimport.conf>

=item F<~/.nsdbimport.conf>

=item F</etc/nsdbimport.conf>

=back    

=head1 EXIT CODES

=over 4

=item 0

Successful termination.    
    
=item 64

Invalid command line usage.
    
=item 66

Failed to open a zone file.

=item 69

Can't open B<nsdbimport> configuration file or failed to execute SQL query.

=item 72

Configuration file does not exist or is not readable.  This can refer to both
the B<nsdbimport> configuration file and to BIND configuration file, supplied
with the B<--bind-config> option.

=item 78

Exited due to errors in configuration file.    

=back    
    
=head1 BUGS

Only MySQL is supported and tested.

Need to ensure proper quoting of SQL query arguments.
    
=head1 SEE ALSO

B<cfpeek>(1), B<named>(8), B<named.conf>(5).    
    
=head1 AUTHOR

Sergey Poznyakoff <gray@gnu.org>

=cut    

Return to:

Send suggestions and report system problems to the System administrator.