DNS/Nameserver.pm untested

filter: Statementstmt 0.0% 0 / 383 Branchbran 0.0% 0 / 144 Conditioncond 0.0% 0 / 31 MC/DCmcdc 0.0% 0 / 18 Subroutinesub 0.0% 0 / 34 Podpod 0.0% 0 / 18 totaltotal 0.0% 0 / 628 CC 72 SCAR 46.3
CC
72
Cov
0%
_make_reply
380.0
_ReplyHandler
132.0
_read_tcp
90.0
CRAP 102.6
1 package Net::DNS::Nameserver;
2  
3 use strict;
4 use warnings;
5  
6 our $VERSION = (qw$Id: Nameserver.pm 2002 2025-01-07 09:57:46Z willem $)[2];
7  
8  
9 =head1 NAME
10  
11 Net::DNS::Nameserver - DNS server class
12  
13 =head1 SYNOPSIS
14  
15 use Net::DNS::Nameserver;
16  
17 my $nameserver = Net::DNS::Nameserver->new(
18 LocalAddr => ['::1', '127.0.0.1'],
19 LocalPort => 15353,
20 ZoneFile => 'filename'
21 );
22  
23 my $nameserver = Net::DNS::Nameserver->new(
24 LocalAddr => '10.1.2.3',
25 LocalPort => 15353,
26 ReplyHandler => \&reply_handler
27 );
28  
29 $nameserver->start_server($timeout);
30 $nameserver->stop_server;
31  
32  
33 =head1 DESCRIPTION
34  
35 Net::DNS::Nameserver offers a simple mechanism for instantiation of
36 customised DNS server objects intended to provide test responses to
37 queries emanating from a client resolver.
38  
39 It is not, nor will it ever be, a general-purpose DNS nameserver
40 implementation.
41  
42 See L</EXAMPLES> below for further details.
43  
44 =cut
45  
46 use integer;
47 use Carp;
48 use Net::DNS;
49 use Net::DNS::ZoneFile;
50  
51 use IO::Select;
52 use IO::Socket::IP;
53 use IO::Socket;
54 use Socket;
55  
56 use constant SOCKOPT => eval {
57 my @sockopt;
58 push @sockopt, eval '[SOL_SOCKET, SO_REUSEADDR]'; ## no critic
59 push @sockopt, eval '[SOL_SOCKET, SO_REUSEPORT]'; ## no critic
60  
61 my $filter = sub { # check that options safe to use
62 return eval { IO::Socket::IP->new( Proto => "udp", Sockopts => [shift], Type => SOCK_DGRAM ) }
63 };
64 return grep { &$filter($_) } @sockopt; # without any guarantee that they work!
65 };
66  
67 use constant DEFAULT_ADDR => qw(::1 127.0.0.1);
68 use constant DEFAULT_PORT => 15353;
69  
70 use constant POSIX => defined eval 'use POSIX ":sys_wait_h"; 1'; ## no critic
71 use constant MSWin => scalar( $^O =~ /MSWin/i );
72  
73  
74 #------------------------------------------------------------------------------
75 # Constructor.
76 #------------------------------------------------------------------------------
77  
78 sub new {
79 my ( $class, %config ) = @_;
80  
81 my %self = (
82 LocalAddr => [DEFAULT_ADDR],
83 LocalPort => [DEFAULT_PORT],
84 Truncate => 1,
85 %config
86 );
87 my $self = bless \%self, $class;
88  
89 $self->_ReadZoneFile( $self{ZoneFile} ) if exists $self{ZoneFile};
90  
91 croak 'No reply handler!' unless ref( $self{ReplyHandler} ) eq "CODE";
92  
93 # local server addresses need to be accepted by a resolver
94 my $LocalAddr = $self{LocalAddr};
95 my $resolver = Net::DNS::Resolver->new( nameservers => $LocalAddr );
96 $resolver->force_v4( $self{Force_IPv4} );
97 $resolver->force_v6( $self{Force_IPv6} );
98 $self{LocalAddr} = [$resolver->nameservers];
99 return $self;
100 }
101  
102  
103 #------------------------------------------------------------------------------
104 # _ReadZoneFile - Read zone file used by default reply handler
105 #------------------------------------------------------------------------------
106  
107 sub _ReadZoneFile {
108 my ( $self, $file ) = @_;
109 my $zonefile = Net::DNS::ZoneFile->new($file);
110  
111 my $RRhash = $self->{index} = {};
112 my $RRlist = [];
113 my @zonelist;
114 while ( my $rr = $zonefile->read ) {
115 push @{$RRhash->{lc $rr->owner}}, $rr;
116  
117 # Warning: Nasty trick abusing SOA to reference zone RR list
118 if ( $rr->type eq 'SOA' ) {
119 $RRlist = $rr->{RRlist} = [];
120 push @zonelist, lc $rr->owner;
121 } else {
122 push @$RRlist, $rr;
123 }
124 }
125  
126 $self->{namelist} = [sort { length($b) <=> length($a) } keys %$RRhash];
127 $self->{zonelist} = [sort { length($b) <=> length($a) } @zonelist];
128 $self->{ReplyHandler} = sub { $self->_ReplyHandler(@_) };
129 return;
130 }
131  
132  
133 #------------------------------------------------------------------------------
134 # _ReplyHandler - Default reply handler serving RRs from zone file
135 #------------------------------------------------------------------------------
136  
137 sub _ReplyHandler {
138 my ( $self, $qname, $qclass, $qtype, $peerhost, $query, $conn ) = @_;
139 my $RRhash = $self->{index};
140 my $rcode;
141 my %headermask;
142 my @ans;
143 my @auth;
144  
145 if ( $qtype eq 'AXFR' ) {
146 my $RRlist = $RRhash->{lc $qname} || [];
147 my ($soa) = grep { $_->type eq 'SOA' } @$RRlist;
148 if ($soa) {
149 $rcode = 'NOERROR';
150 push @ans, $soa, @{$soa->{RRlist}}, $soa;
151 } else {
152 $rcode = 'NOTAUTH';
153 }
154 return ( $rcode, \@ans, [], [], {}, {} );
155 }
156  
157 my @RRname = @{$self->{namelist}}; # pre-sorted, longest first
158 {
159 my $RRlist = $RRhash->{lc $qname} || []; # hash, then linear search
160 my @match = @$RRlist; # assume $qclass always 'IN'
161 if ( scalar(@match) ) { # exact match
162 $rcode = 'NOERROR';
163 } elsif ( grep {/\.$qname$/i} @RRname ) { # empty non-terminal
164 $rcode = 'NOERROR'; # [NODATA]
165 } else {
166 $rcode = 'NXDOMAIN';
167 foreach ( grep {/^[*][.]/} @RRname ) {
168 my $wildcard = $_; # match wildcard per RFC4592
169 s/^\*//; # delete leading asterisk
170 s/([.?*+])/\\$1/g; # escape dots and regex quantifiers
171 next unless $qname =~ /[.]?([^.]+$_)$/i;
172 my $cover = $1; # check for name covering wildcard
173 next if grep {/[.]?$cover$/i} @RRname;
174  
175 my ($q) = $query->question; # synthesise RR at qname
176 foreach my $rr ( @{$RRhash->{$wildcard}} ) {
177 my $clone = bless( {%$rr}, ref($rr) );
178 $clone->{owner} = $q->{qname};
179 push @match, $clone;
180 }
181 $rcode = 'NOERROR';
182 last;
183 }
184 }
185 push @ans, my @cname = grep { $_->type eq 'CNAME' } @match;
186 $qname = $_->cname for @cname;
187 redo if @cname;
188 push @ans, @match if $qtype eq 'ANY'; # traditional, now out of favour
189 push @ans, grep { $_->type eq $qtype } @match;
190 unless (@ans) {
191 foreach ( @{$self->{zonelist}} ) {
192 my $RRlist = $RRhash->{lc $_};
193 s/([.?*+])/\\$1/g; # escape dots and regex quantifiers
194 next unless $qname =~ /[^.]+[.]$_[.]?$/i;
195 push @auth, grep { $_->type eq 'SOA' } @$RRlist;
196 last;
197 }
198 }
199 $headermask{aa} = 1;
200 }
201 return ( $rcode, \@ans, \@auth, [], \%headermask, {} );
202 }
203  
204  
205 #------------------------------------------------------------------------------
206 # _make_reply - Make a reply packet.
207 #------------------------------------------------------------------------------
208  
209 sub _make_reply {
210 my ( $self, $query, $sock ) = @_;
211 my $verbose = $self->{Verbose};
212  
213 unless ($query) {
214 my $empty = Net::DNS::Packet->new(); # create empty reply packet
215 my $reply = $empty->reply();
216 $reply->header->rcode("FORMERR");
217 return $reply;
218 }
219  
220 if ( $query->header->qr() ) {
221 print "ERROR: invalid packet (qr set), dropping\n" if $verbose;
222 return;
223 }
224  
225 my $reply = $query->reply();
226 my $header = $reply->header;
227 my $headermask;
228 my $optionmask;
229  
230 my $opcode = $query->header->opcode;
231 my $qdcount = $query->header->qdcount;
232  
233 unless ($qdcount) {
234 $header->rcode("NOERROR");
235  
236 } elsif ( $qdcount > 1 ) {
237 $header->rcode("FORMERR");
238  
239 } else {
240 my ($qr) = $query->question;
241 my $qname = $qr->qname;
242 my $qtype = $qr->qtype;
243 my $qclass = $qr->qclass;
244  
245 print $qr->string, "\n" if $verbose;
246  
247 my $conn = {
248 peerhost => my $peer = $sock->peerhost,
249 peerport => $sock->peerport,
250 protocol => $sock->protocol,
251 sockhost => $sock->sockhost,
252 sockport => $sock->sockport
253 };
254  
255 my ( $rcode, $ans, $auth, $add );
256 my @arglist = ( $qname, $qclass, $qtype, $peer, $query, $conn );
257  
258 if ( $opcode eq "QUERY" ) {
259 ( $rcode, $ans, $auth, $add, $headermask, $optionmask ) =
260 &{$self->{ReplyHandler}}(@arglist);
261  
262 } elsif ( $opcode eq "NOTIFY" ) { #RFC1996
263 if ( ref $self->{NotifyHandler} eq "CODE" ) {
264 ( $rcode, $ans, $auth, $add, $headermask, $optionmask ) =
265 &{$self->{NotifyHandler}}(@arglist);
266 } else {
267 $rcode = "NOTIMP";
268 }
269  
270 } elsif ( $opcode eq "UPDATE" ) { #RFC2136
271 if ( ref $self->{UpdateHandler} eq "CODE" ) {
272 ( $rcode, $ans, $auth, $add, $headermask, $optionmask ) =
273 &{$self->{UpdateHandler}}(@arglist);
274 } else {
275 $rcode = "NOTIMP";
276 }
277  
278 } else {
279 print "ERROR: opcode $opcode unsupported\n" if $verbose;
280 $rcode = "FORMERR";
281 }
282  
283 if ( !defined($rcode) ) {
284 print "remaining silent\n" if $verbose;
285 return;
286 }
287  
288 $header->rcode($rcode);
289  
290 push @{$reply->{answer}}, @$ans if $ans;
291 push @{$reply->{authority}}, @$auth if $auth;
292 push @{$reply->{additional}}, @$add if $add;
293 }
294  
295 while ( my ( $key, $value ) = each %{$headermask || {}} ) {
296 $header->$key($value);
297 }
298  
299 while ( my ( $option, $value ) = each %{$optionmask || {}} ) {
300 $reply->edns->option( $option, $value );
301 }
302  
303 $header->print if $verbose && ( $headermask || $optionmask );
304  
305 return $reply;
306 }
307  
308  
309 #------------------------------------------------------------------------------
310 # _TCP_connection - Handle a TCP connection.
311 #------------------------------------------------------------------------------
312  
313 sub _TCP_connection {
314 my ( $self, $socket, $buffer ) = @_;
315 my $verbose = $self->{Verbose};
316  
317 my $query = Net::DNS::Packet->new( \$buffer );
318 if ($@) {
319 print "Error decoding query packet: $@\n" if $verbose;
320 undef $query; ## force FORMERR reply
321 }
322  
323 my $reply = $self->_make_reply( $query, $socket );
324 die 'Failed to create reply' unless defined $reply;
325  
326 my $segment = $reply->data;
327 my $length = length $segment;
328 if ($verbose) {
329 print "TCP response (2 + $length octets) - ";
330 print $socket->send( pack 'na*', $length, $segment ) ? "sent" : "failed: $!", "\n";
331 } else {
332 $socket->send( pack 'na*', $length, $segment );
333 }
334 return;
335 }
336  
337 sub _read_tcp {
338 my ( $socket, $verbose ) = @_;
339  
340 my $header = '';
341 local $! = 0;
342 my $n = sysread( $socket, $header, 2 );
343 unless ( defined $n ) {
344 redo if $!{EINTR}; ## retry if aborted by signal
345 die "sysread: $!";
346 }
347 return '' if $n == 0;
348 return '' if length($header) < 2;
349 my $msglen = unpack 'n', $header;
350  
351 my $buffer = '';
352 while ( $msglen > ( my $len = length $buffer ) ) {
353 local $! = 0;
354 my $n = sysread( $socket, $buffer, ( $msglen - $len ), $len );
355 unless ( defined $n ) {
356 redo if $!{EINTR}; ## retry if aborted by signal
357 die "sysread: $!";
358 }
359 last if $n == 0; ## client closed (or lied) per RT#151240
360 }
361  
362 if ($verbose) {
363 my $peer = $socket->peerhost;
364 my $port = $socket->peerport;
365 my $size = length $buffer;
366 print "Received $size octets from [$peer] port $port\n";
367 }
368 return $buffer;
369 }
370  
371  
372 #------------------------------------------------------------------------------
373 # _UDP_connection - Handle a UDP connection.
374 #------------------------------------------------------------------------------
375  
376 sub _UDP_connection {
377 my ( $self, $socket, $buffer ) = @_;
378 my $verbose = $self->{Verbose};
379  
380 my $query = Net::DNS::Packet->new( \$buffer );
381 if ($@) {
382 print "Error decoding query packet: $@\n" if $verbose;
383 undef $query; ## force FORMERR reply
384 }
385  
386 my $reply = $self->_make_reply( $query, $socket );
387 die 'Failed to create reply' unless defined $reply;
388  
389 my @UDPsize = ( $query && $self->{Truncate} ) ? $query->edns->UDPsize || 512 : ();
390 if ($verbose) {
391 my $response = $reply->data(@UDPsize);
392 print 'UDP response (', length($response), ' octets) - ';
393 print $socket->send($response) ? "sent" : "failed: $!", "\n";
394 } else {
395 $socket->send( $reply->data(@UDPsize) );
396 }
397 return;
398 }
399  
400 sub _read_udp {
401 my ( $socket, $verbose ) = @_;
402 my $buffer = '';
403 $socket->recv( $buffer, 9000 ); ## payload limit for Ethernet "Jumbo" packet
404 if ($verbose) {
405 my $peer = $socket->peerhost;
406 my $port = $socket->peerport;
407 my $size = length $buffer;
408 print "Received $size octets from [$peer] port $port\n";
409 }
410 return $buffer;
411 }
412  
413  
414 #------------------------------------------------------------------------------
415 # Socket mechanics.
416 #------------------------------------------------------------------------------
417  
418 use constant DEBUG => $ENV{DEBUG} ? 1 : 0;
419  
420 sub _logmsg { warn( join '', "$0 $$: @_ at ", scalar localtime(), "\n" ); return }
421  
422 sub _TCP_socket {
423 my ( $ip, $port ) = @_;
424 my $socket = IO::Socket::IP->new(
425 LocalAddr => $ip,
426 LocalPort => $port,
427 Sockopt => [SOCKOPT],
428 Proto => "tcp",
429 Listen => SOMAXCONN,
430 Type => SOCK_STREAM
431 )
432 or die "can't setup TCP socket: $!";
433  
434 _logmsg "TCP server [$ip] port $port" if DEBUG;
435 return $socket;
436 }
437  
438 sub _TCP_server {
439 my ( $self, $ip, $port, $timeout ) = @_;
440 my $listen = _TCP_socket( $ip, $port );
441 my $select = IO::Select->new($listen);
442  
443 my $expired;
444 my $terminate = sub { $expired++ };
445 local $SIG{ALRM} = $terminate;
446 local $SIG{TERM} = $terminate;
447 alarm $timeout;
448 until ($expired) {
449 local $! = 0;
450 scalar( my @ready = $select->can_read(2) ) or do {
451 redo if $!{EINTR}; ## retry if aborted by signal
452 last if $!;
453 };
454  
455 foreach my $socket (@ready) {
456 if ( $socket == $listen ) {
457 $select->add( $listen->accept );
458 next;
459 }
460 if ( my $buffer = _read_tcp( $socket, $self->{Verbose} ) ) {
461 _spawn( sub { $self->_TCP_connection( $socket, $buffer ) } );
462 } else {
463 close($socket);
464 $select->remove($socket);
465 }
466 }
467 sleep(0) if MSWin;
468 }
469 return;
470 }
471  
472  
473 sub _UDP_socket {
474 my ( $ip, $port ) = @_;
475 my $socket = IO::Socket::IP->new(
476 LocalAddr => $ip,
477 LocalPort => $port,
478 Sockopt => [SOCKOPT],
479 Proto => "udp",
480 Type => SOCK_DGRAM
481 )
482 or die "can't setup UDP socket: $!";
483  
484 _logmsg "UDP server [$ip] port $port" if DEBUG;
485 return $socket;
486 }
487  
488 sub _UDP_server {
489 my ( $self, $ip, $port, $timeout ) = @_;
490 my $socket = _UDP_socket( $ip, $port );
491 my $select = IO::Select->new($socket);
492  
493 my $expired;
494 my $terminate = sub { $expired++ };
495 local $SIG{ALRM} = $terminate;
496 local $SIG{TERM} = $terminate;
497 alarm $timeout;
498 until ($expired) {
499 local $! = 0;
500 scalar( my @ready = $select->can_read(2) ) or do {
501 redo if $!{EINTR}; ## retry if aborted by signal
502 last if $!;
503 };
504  
505 foreach my $client (@ready) {
506 my $buffer = _read_udp( $client, $self->{Verbose} );
507 _spawn( sub { $self->_UDP_connection( $client, $buffer ) } );
508 }
509 sleep(0) if MSWin;
510 }
511 return;
512 }
513  
514  
515 #------------------------------------------------------------------------------
516 # Process mechanics.
517 #------------------------------------------------------------------------------
518  
519 my $noop = sub { };
520  
521 sub _spawn {
522 my $coderef = shift;
523 unless ( defined( my $pid = fork() ) ) {
524 die "cannot fork: $!";
525 } elsif ($pid) {
526 _logmsg "begat $pid" if DEBUG;
527 return $pid; ## parent
528 }
529  
530 # else ...
531 local $SIG{TERM} = $noop;
532 local $SIG{CHLD} = \&_reaper;
533 $coderef->(); ## child
534 exit;
535 }
536  
537 sub _reaper {
538 local ( $!, $? ); ## protect error and exit status
539 $SIG{CHLD} = \&_reaper; ## no critic sysV semantics
540 while ( abs( my $pid = waitpid( -1, POSIX ? WNOHANG : 0 ) ) > 1 ) {
541 _logmsg "reaped $pid" if DEBUG;
542 }
543 return;
544 }
545  
546  
547 our @pid;
548 my $pid = $$;
549  
550 sub start_server {
551 my ( $self, $timeout ) = @_;
552 $timeout ||= 600;
553 croak 'Attempt to start ', ref($self), ' in a subprocess' unless $$ == $pid;
554 _logmsg('start server') if DEBUG;
555  
556 foreach my $ip ( @{$self->{LocalAddr}} ) {
557 my $port = $self->{LocalPort};
558 push @pid, _spawn sub { $self->_TCP_server( $ip, $port, $timeout ) };
559 push @pid, _spawn sub { $self->_UDP_server( $ip, $port, $timeout ) };
560 }
561 return;
562 }
563  
564 sub stop_server {
565 _logmsg('stop server') if DEBUG;
566 kill 'TERM', @pid;
567 return;
568 }
569  
570 END {
571 local ( $!, $? ); ## protect error and exit status
572 while ( abs( my $pid = waitpid( -1, 0 ) ) > 1 ) {
573 _logmsg "reaped $pid" if DEBUG;
574 }
575 _logmsg "terminated" if DEBUG;
576 }
577  
578  
579 1;
580 __END__