File: Nameserver.pm

package info (click to toggle)
libnet-dns-perl 0.19-0.1
  • links: PTS
  • area: main
  • in suites: woody
  • size: 544 kB
  • ctags: 323
  • sloc: perl: 5,191; makefile: 54
file content (371 lines) | stat: -rw-r--r-- 10,406 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
package Net::DNS::Nameserver;
# $Id: Nameserver.pm,v 1.1 2000/12/12 17:18:00 mfuhr Exp mfuhr $

use Net::DNS;
use IO::Socket;
use IO::Select;
use Carp qw(cluck);
use strict;
use vars qw($VERSION);

$VERSION = $Net::DNS::Version;

use constant DEFAULT_ADDR => INADDR_ANY;
use constant DEFAULT_PORT => 53;

#------------------------------------------------------------------------------
# Constructor.
#------------------------------------------------------------------------------

sub new {
    my ($class, %self) = @_;

    my $addr = $self{"LocalAddr"} || inet_ntoa(DEFAULT_ADDR);
    my $port = $self{"LocalPort"} || DEFAULT_PORT;

    if (!$self{"ReplyHandler"} || !ref($self{"ReplyHandler"})) {
	cluck "No reply handler!";
	return;
    }

    #--------------------------------------------------------------------------
    # Create the TCP socket.
    #--------------------------------------------------------------------------

    print "creating TCP socket..." if $self{"Verbose"};

    my $sock_tcp = IO::Socket::INET->new(
	LocalAddr => $addr,
	LocalPort => $port,
	Listen    => 5,
	Proto     => "tcp",
	Reuse     => 1,
    );

    if (!$sock_tcp) {
	cluck "couldn't create TCP socket: $!";
	return;
    }

    print "done.\n" if $self{"Verbose"};

    #--------------------------------------------------------------------------
    # Create the UDP Socket.
    #--------------------------------------------------------------------------

    print "creating UDP socket..." if $self{"Verbose"};

    my $sock_udp = IO::Socket::INET->new(
	Proto => "udp",
    );

    if (!$sock_udp) {
        cluck "couldn't create UDP socket: $!";
	return;
    }

    print "done.\n" if $self{"Verbose"};

    print "binding UDP socket..." if $self{"Verbose"};
    my $sockaddr = sockaddr_in($port, inet_aton($addr));
    if (!$sock_udp->bind($sockaddr)) {
	cluck "couldn't bind UDP socket: $!";
	return;
    }
    print "done.\n";

    #--------------------------------------------------------------------------
    # Create the Select object.
    #--------------------------------------------------------------------------

    $self{"select"} = IO::Select->new;
    $self{"select"}->add($sock_tcp);
    $self{"select"}->add($sock_udp);

    #--------------------------------------------------------------------------
    # Return the object.
    #--------------------------------------------------------------------------

    my $self = bless \%self, $class;
    return $self;
}

#------------------------------------------------------------------------------
# make_reply - Make a reply packet.
#------------------------------------------------------------------------------

sub make_reply {
    my ($self, $query) = @_;

    my $reply;

    if ($query) {
        my $qr = ($query->question)[0];

        my $qname  = $qr ? $qr->qname  : "";
        my $qclass = $qr ? $qr->qclass : "ANY";
        my $qtype  = $qr ? $qr->qtype  : "ANY";

        $reply = Net::DNS::Packet->new($qname, $qclass, $qtype);

        if ($query->header->opcode eq "QUERY") {
            if ($query->header->qdcount == 1) {
                print "query ", $query->header->id,
		      ": ($qname, $qclass, $qtype)..." if $self->{"Verbose"};

		my ($rcode, $ans, $auth, $add) =
		    &{$self->{"ReplyHandler"}}($qname, $qclass, $qtype);

		print "$rcode\n" if $self->{"Verbose"};

		$reply->header->rcode($rcode);

		$reply->push("answer",     @$ans)  if $ans;
		$reply->push("authority",  @$auth) if $auth;
		$reply->push("additional", @$add)  if $add;
	    }
	    else {
	        print "ERROR: qdcount ", $query->header->qdcount,
		      "unsupported\n" if $self->{"Verbose"};
		$reply->header->rcode("FORMERR");
	    }
        }
        else {
            print "ERROR: opcode ", $query->header->opcode, " unsupported\n"
	      if $self->{"Verbose"};
            $reply->header->rcode("FORMERR");
        }
    }
    else {
        print "ERROR: invalid packet\n" if $self->{"Verbose"};
        $reply = Net::DNS::Packet->new("", "ANY", "ANY");
        $reply->header->rcode("FORMERR");
    }

    $reply->header->qr(1);
    $reply->header->ra(1);
    $reply->header->rd($query->header->rd);
    $reply->header->id($query->header->id);

    return $reply;
}

#------------------------------------------------------------------------------
# tcp_connection - Handle a TCP connection.
#------------------------------------------------------------------------------

sub tcp_connection {
    my ($self, $sock) = @_;

    print "TCP connection from ", $sock->peerhost, ":", $sock->peerport, "\n"
      if $self->{"Verbose"};
	    
    while (1) {
        my $buf;
        print "reading message length..." if $self->{"Verbose"};
        $sock->read($buf, 2) or last;
        print "done\n" if $self->{"Verbose"};

        my ($msglen) = unpack("n", $buf);
        print "expecting $msglen bytes..." if $self->{"Verbose"};
        $sock->read($buf, $msglen);
        print "got ", length($buf), " bytes\n" if $self->{"Verbose"};

        my $query = Net::DNS::Packet->new(\$buf);
	my $reply = $self->make_reply($query);
        my $reply_data = $reply->data;

        print "writing response..." if $self->{"Verbose"};
        $sock->write(pack("n", length($reply_data)) . $reply_data);
        print "done\n" if $self->{"Verbose"};
    }

    print "closing connection..." if $self->{"Verbose"};
    $sock->close;
    print "done\n" if $self->{"Verbose"};
}

#------------------------------------------------------------------------------
# udp_connection - Handle a UDP connection.
#------------------------------------------------------------------------------

sub udp_connection {
    my ($self, $sock) = @_;

    my $buf = "";
    my $peer_sockaddr = $sock->recv($buf, &Net::DNS::PACKETSZ);
    my ($peerport, $peeraddr) = sockaddr_in($peer_sockaddr);
    my $peerhost = inet_ntoa($peeraddr);

    print "UDP connection from $peerhost:$peerport\n" if $self->{"Verbose"};

    my $query = Net::DNS::Packet->new(\$buf);
    my $reply = $self->make_reply($query);
    my $reply_data = $reply->data;

    print "writing response..." if $self->{"Verbose"};
    $sock->send($reply_data) or die "send: $!";
    print "done\n" if $self->{"Verbose"};
}

#------------------------------------------------------------------------------
# main_loop - Main nameserver loop.
#------------------------------------------------------------------------------

sub main_loop {
    my $self = shift;

    local $| = 1;

    while (1) {
	print "waiting for connections..." if $self->{"Verbose"};
	my @ready = $self->{"select"}->can_read;

	foreach my $sock (@ready) {
            my $proto = getprotobynumber($sock->protocol);

            if (!$proto) {
                print "ERROR: connection with unknown protocol\n"
                    if $self->{"Verbose"};
            }
            elsif (lc($proto) eq "tcp") {
                my $client = $sock->accept;
                $self->tcp_connection($client);
            }
            elsif (lc($proto) eq "udp") {
                $self->udp_connection($sock);
            }
            else {
                print "ERROR: connection with unsupported protocol $proto\n"
                    if $self->{"Verbose"};
            }
        }
    }
}

1;

__END__

=head1 NAME

Net::DNS::Nameserver - DNS server class

=head1 SYNOPSIS

C<use Net::DNS::Nameserver;>

=head1 DESCRIPTION

Instances of the C<Net::DNS::Nameserver> class represent simple DNS server
objects.  See L</EXAMPLE> for an example.

=head1 METHODS

=head2 new

    my $ns = Net::DNS::Nameserver->new(
	LocalAddr    => "10.1.2.3",
	LocalPort    => "5353",
	ReplyHandler => \&reply_handler,
	Verbose      => 1
    );

Creates a nameserver object.  Attributes are:

  LocalAddr     IP address on which to listen.  Defaults to INADDR_ANY.
  LocalPort     Port on which to listen.  Defaults to 53.
  ReplyHandler  Reference to reply-handling subroutine.  Required.
  Verbose       Print info about received queries.  Defaults to 0 (off).

The ReplyHandler subroutine is passed the query name, query class,
and query type.  It must return the response code and references
to the answer, authority, and additional sections of the response.
Common response codes are:

  NOERROR   No error
  FORMERR   Format error
  SERVFAIL  Server failure
  NXDOMAIN  Non-existent domain (name doesn't exist)
  NOTIMP    Not implemented
  REFUSED   Query refused

See RFC 1035 and the IANA dns-parameters file for more information:

  ftp://ftp.rfc-editor.org/in-notes/rfc1035.txt
  http://www.isi.edu/in-notes/iana/assignments/dns-parameters

The nameserver will listen for both UDP and TCP connections.  On
Unix-like systems, the program will probably have to run as root
to listen on the default port, 53.  A non-privileged user should
be able to listen on ports 1024 and higher.

Returns a Net::DNS::Nameserver object, or undef if the object
couldn't be created.

See L</EXAMPLE> for an example.  

=head2 main_loop

    $ns->main_loop;

Start accepting queries.

=head1 EXAMPLE

The following example will listen on port 5353 and respond to all queries
for A records with the IP address 10.1.2.3.  All other queries will be
answered with NXDOMAIN.  Authority and additional sections are left empty.

  #!/usr/bin/perl -Tw
  
  use Net::DNS;
  use strict;
  
  sub reply_handler {
      my ($qname, $qclass, $qtype) = @_;
      my ($rcode, @ans, @auth, @add);
  
      if ($qtype eq "A") {
        my ($ttl, $rdata) = (3600, "10.1.2.3");
        push @ans, Net::DNS::RR->new("$qname $ttl $qclass $qtype $rdata");
        $rcode = "NOERROR";
      }
      else {
        $rcode = "NXDOMAIN";
      }
        
      return ($rcode, \@ans, \@auth, \@add);
  }

  my $ns = Net::DNS::Nameserver->new(
      LocalPort    => 5353,
      ReplyHandler => \&reply_handler,
      Verbose      => 1
  );
  
  if ($ns) {
      $ns->main_loop;
  }
  else {
      die "couldn't create nameserver object\n";
  }

=head1 BUGS

Net::DNS::Nameserver objects can handle only one query at a time.

=head1 COPYRIGHT

Copyright (c) 2000 Michael Fuhr.  All rights reserved.  This program
is free software; you can redistribute it and/or modify it under
the same terms as Perl itself.

=head1 SEE ALSO

L<perl(1)>, L<Net::DNS>, L<Net::DNS::Resolver>, L<Net::DNS::Packet>,
L<Net::DNS::Update>, L<Net::DNS::Header>, L<Net::DNS::Question>,
L<Net::DNS::RR>, RFC 1035

=cut