Class: Net::DNS::Nameserver

Inherits:
Object
  • Object
show all
Defined in:
lib/Net/DNS/Nameserver.rb

Constant Summary collapse

STATE_ACCEPTED =
1
STATE_GOT_LENGTH =
2
STATE_SENDING =
3
DEFAULT_PORT =
53
DEFAULT_ADDR =
Socket::INADDR_ANY

Instance Method Summary collapse

Constructor Details

#initialize(opts = {}) ⇒ Nameserver

def initialize(localaddr=DEFAULT_ADDR, localport=DEFAULT_PORT, verbose=false, &replyhandler)



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
# File 'lib/Net/DNS/Nameserver.rb', line 33

def initialize(opts={})
  #  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).
  opts = {:localaddr => DEFAULT_ADDR, :localport => DEFAULT_PORT, :verbose => false}.merge(opts)
  if (!opts[:replyhandler] || opts[:replyhandler]==nil)
    raise RuntimeError,  "No reply handler!"
  end
  @replyhandler = opts[:replyhandler]
  @verbose = opts[:verbose]
  @sockets = []
  @_tcp = Hash.new
  
  port=opts[:localport]
  
  # make sure we have an array.
  #        localaddr= [DEFAULT_ADDR] unless opts[:localaddr]!=nil
  localaddr= [ opts[:localaddr] ] unless (opts[:localaddr].is_a?(Array))
  
  localaddresses = localaddr
  
  print "Nameserver on #{localaddresses.inspect}:#{port}\n" if @verbose
  
  # while we are here, print incomplete lines as they come along.
  #        local $| = 1 if @verbose
  
  localaddresses.each do |localaddress|
    
    addr = localaddress
    
    # If not, it will do DNS lookups trying to resolve it as a hostname
    # We could also just set it to undef?
    
    #          addr = IPAddr.ntop(addr) unless IPAddr.ipv4?(addr) || IPAddr.ipv6?(addr)
    
    # Pretty IP-addresses, if they are otherwise binary.
    #          addrname = addr
    #          addrname = IPAddr.ntop(addrname) unless addrname =~ /^[\w\.:\-]+$/
    addrname = IPAddr.new(addr, Socket::AF_INET)         
    print "Setting up listening sockets for #{addrname}...\n" if @verbose
    
    print "Creating TCP socket for #{addrname} - " if @verbose
    
    #--------------------------------------------------------------------------
    # Create the TCP socket.
    #--------------------------------------------------------------------------
    
    #            sock_tcp = inet_new(
    #                                    LocalAddr => $addr,
    #                                    LocalPort => $port,
    #                                    Listen	  => 64,
    #                                    Proto	  => "tcp",
    #            Reuse	  => 1,
    #            );
    #          sock_tcp = TCPSocket.new(addr, port)                        
    @tcpserver = TCPServer.new(addr, port)
    if (!@tcpserver)
      raise RuntimError, "Couldn't create TCP socket: #{$!}"
      return
    end
    @tcpserver.listen(64) 
    @sockets.push(@tcpserver)
    print "done.\n" if @verbose
    
    #--------------------------------------------------------------------------
    # Create the UDP Socket.
    #--------------------------------------------------------------------------
    
    print "Creating UDP socket for #{addrname} - " if @verbose
    
    sock_udp = UDPSocket.new()
    sock_udp.bind(addr, port)
    
    if (!sock_udp)
      raise RuntimeError, "Couldn't create UDP socket: #{$!}"
      return
    end
    @sockets.push(sock_udp)
    print "done.\n" if @verbose
  end
  
end

Instance Method Details

#get_open_tcpObject



311
312
313
# File 'lib/Net/DNS/Nameserver.rb', line 311

def get_open_tcp
  return @_tcp.keys
end

#loop_once(timeout = 0) ⇒ Object

NB this method may be subject to change and is therefore left ‘undocumented’



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
# File 'lib/Net/DNS/Nameserver.rb', line 328

def loop_once(timeout=0)
  #        print ";loop_once called with #{timeout} \n" if @verbose
  @_tcp.keys.each do |sock|
    timeout = 0.1 if @_tcp[sock]["outbuffer"]!=""
  end
  #        ready = @select.can_read(timeout)
  ret = IO::select(@sockets, nil, nil, timeout)
  if (ret!=nil) 
    ready = ret[0]
    print "ready : " + ready.inspect + "\n"
    
    ready.each do |sock|
      if (!(sock.is_a?UDPSocket))
        
        self.readfromtcp(sock) &&
        self.tcp_connection(sock)
      else
        self.udp_connection(sock)
        #          else
        #            print "ERROR: connection with unsupported protocol #{proto}\n" if @verbose
      end
    end
  end
  
  now = Time.now()
  # Lets check if any of our TCP clients has pending actions.
  # (outbuffer, timeout)
  #        @_tcp.keys.each do |s|
  @_tcp.keys.each do |s|
    sock = @_tcp[s]["socket"]
    if (@_tcp[s]["outbuffer"].length>0)
      # If we have buffered output, then send as much as the OS will accept
      # and wait with the rest
      len = @_tcp[s]["outbuffer"].length
      #            charssent = sock.syswrite(@_tcp[s]["outbuffer"]
      charssent = sock.write_nonblock(@_tcp[s]["outbuffer"])
      print "Sent #{charssent} of #{len} octets to " + @_tcp[s]["peer"] + ".\n" if @verbose
      #            substr($self->{"_tcp"}{$s}{"outbuffer"}, 0, charssent) = ""
      @_tcp[s]["outbuffer"] [0, charssent] = ""
      if (@_tcp[s]["outbuffer"].length == 0)
        @_tcp[s]["outbuffer"] = ""
        @_tcp[s]["state"] = STATE_ACCEPTED
        if (@_tcp[s]["inbuffer"].length >= 2)
          # See if the client has send us enough data to process the
          # next query.
          # We do this here, because we only want to process (and buffer!!)
          # a single query at a time, per client. If we allowed a STATE_SENDING
          # client to have new requests processed. We could be easilier
          # victims of DoS (client sending lots of queries and never reading
          # from it's socket).
          # Note that this does not disable serialisation on part of the
          # client. The split second it should take for us to lookip the
          # next query, is likely faster than the time it takes to
          # send the response... well, unless it's a lot of tiny queries,
          # in which case we will be generating an entire TCP packet per
          # reply. --robert
          tcp_connection(@_tcp["socket"])
        end
      end
      @_tcp[s]["timeout"] = Time.now()+120
    else
      # Get rid of idle clients.
      timeout = @_tcp[s]["timeout"]
      if (timeout - now < 0)
        print @_tcp[s]["peer"]," has been idle for too long and will be disconnected.\n" if @verbose
        #              @select.remove(sock)
        @sockets.delete(sock)
        sock.close()
        @_tcp.delete(s)
      end
    end
  end
end

#main_loopObject


main_loop - Main nameserver loop.




406
407
408
409
410
411
412
413
# File 'lib/Net/DNS/Nameserver.rb', line 406

def main_loop
  while (true) do
    print "Waiting for connections...\n" if @verbose
    # You really need an argument otherwise you'll be burning
    # CPU.
    loop_once(10)
  end
end

#make_reply(query, peerhost) ⇒ Object


make_reply - Make a reply packet.




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
# File 'lib/Net/DNS/Nameserver.rb', line 123

def make_reply(query, peerhost)
  reply=""
  headermask=""
  
  if (not query)
    print "ERROR: invalid packet\n" if @verbose
    reply = Net::DNS::Packet.new_from_values("", "ANY", "ANY")
    reply.header.rcode=("FORMERR")
    
    return reply
  end
  
  if (query.header.qr==1)
    print "ERROR: invalid packet (qr was set, dropping)\n" if @verbose
    return
  end
  
  
  qr = (query.question)[0]
  
  qname  = qr ? qr.qname  : ""
  qclass = qr ? qr.qclass : "ANY"
  qtype  = qr ? qr.qtype  : "ANY"
  
  reply = Net::DNS::Packet.new_from_values(qname, qtype, qclass)
  
  if (query.header.opcode == "QUERY")
    if (query.header.qdcount == 1)
      print "query ", query.header.id,
			": (#{qname}, #{qclass}, #{qtype}) - " if @verbose
      
      rcode, ans, auth, add, headermask = @replyhandler.call(qname, qclass, qtype, peerhost, query)
      
      print "#{rcode}\n" if @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 @verbose
      reply.header.rcode=("FORMERR")
    end
  else
    print "ERROR: opcode ", query.header.opcode, " unsupported\n" if @verbose
    reply.header.rcode=("FORMERR")
  end
  
  
  
  if (!headermask)
    reply.header.ra=(1)
    reply.header.ad=(0)
  else
    reply.header.aa=(1) if headermask['aa']
    reply.header.ra=(1) if headermask['ra']
    reply.header.ad=(1) if headermask['ad']
  end
  
  
  reply.header.qr=(1)
  reply.header.cd=(query.header.cd)
  reply.header.rd=(query.header.rd)	
  reply.header.id=(query.header.id)
  
  
  print reply.header.inspect if @verbose && headermask
  
  return reply
end

#readfromtcp(sock) ⇒ Object


readfromtcp - read from a TCP client




199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
# File 'lib/Net/DNS/Nameserver.rb', line 199

def readfromtcp(sock)
  return -1 unless @_tcp[sock]
  peer = @_tcp[sock]["peer"]
  #        charsread = sock.sysread(@_tcp[sock]["inbuffer"], 16384)
  @_tcp[sock]["inbuffer"] = sock.recv_nonblock(16384)
  charsread = @_tcp[sock]["inbuffer"].length
  @_tcp[sock]["timeout"] = Time.now()+120; # Reset idle timer
  print "Received #{charsread} octets from #{peer}\n" if @verbose
  if (charsread == 0) # 0 octets means socket has closed
    print "Connection to #{peer} closed or lost.\n" if @verbose
    @sockets.delete(sock)
    sock.close()
    @_tcp.delete(sock)
    return charsread
  end
  return charsread
end

#tcp_connection(sock) ⇒ Object


tcp_connection - Handle a TCP connection.




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
# File 'lib/Net/DNS/Nameserver.rb', line 221

def tcp_connection(sock)
  #        if (not @_tcp[sock])
  if ((sock == @tcpserver)) # || (not @_tcp[sock]))
    # We go here if we are called with a listener socket.
    client = sock.accept_nonblock
    if (!client)
      print "TCP connection closed by peer before we could accept it.\n" if @verbose
      return 0
    end
    peerport= client.addr[1]
    peerhost = client.addr[3]
    
    print "TCP connection from #{peerhost}:#{peerport}\n" if @verbose
    #          client.blocking=(0)
    @_tcp[client]=Hash.new
    @_tcp[client]["peer"] = "tcp:"+peerhost.inspect+":"+peerport.inspect
    @_tcp[client]["state"] = STATE_ACCEPTED
    @_tcp[client]["socket"] = client
    @_tcp[client]["timeout"] = Time.now()+120
    @_tcp[client]["outbuffer"] = ""
    @sockets.push(client)
    # After we accepted we will look at the socket again 
    # to see if there is any data there. ---Olaf
    loop_once(0)
  elsif @_tcp[sock]
    # We go here if we are called with a client socket
    peer = @_tcp[sock]["peer"]
    
    if (@_tcp[sock]["state"] == STATE_ACCEPTED)
      if (not @_tcp[sock]["inbuffer"].sub!(/^(..)/, ""))
        return; # Still not 2 octets ready
      end
      msglen = $1.unpack("n")[0]
      print "Removed 2 octets from the input buffer from #{peer}.\n" +
		  	"#{peer} said his query contains #{msglen} octets.\n" if @verbose
      @_tcp[sock]["state"] = STATE_GOT_LENGTH
      @_tcp[sock]["querylength"] = msglen
    end
    # Not elsif, because we might already have all the data
    if (@_tcp[sock]["state"] == STATE_GOT_LENGTH)
      # return if not all data has been received yet.
      return if @_tcp[sock]["querylength"] > @_tcp[sock]["inbuffer"].length
      
      qbuf = @_tcp[sock]["inbuffer"][0, @_tcp[sock]["querylength"]]
      #            substr($self->{"_tcp"}{$sock}{"inbuffer"}, 0, $self->{"_tcp"}{$sock}{"querylength"}) = "";
      @_tcp[sock]["inbuffer"][0, @_tcp[sock]["querylength"]]=""
      query = Net::DNS::Packet.new_from_binary(qbuf)
      reply = make_reply(query, sock.addr[3])
      if (!reply) 
        print "I couldn't create a reply for #{peer}. Closing socket.\n" if @verbose
        #              @select.remove(sock)
        @sockets.delete(sock)
        sock.close()
        @_tcp.delete(sock)
        return
      end
      reply_data = reply.data
      len = reply_data.length
      @_tcp[sock]["outbuffer"] = [len].pack("n") + reply_data
      print "Queued #{@_tcp[sock]['outbuffer'].length} octets to #{peer}.\n" if @verbose
      # We are done.
      @_tcp[sock]["state"] = STATE_SENDING
    end
  end
end

#udp_connection(sock) ⇒ Object


udp_connection - Handle a UDP connection.




291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
# File 'lib/Net/DNS/Nameserver.rb', line 291

def udp_connection(sock)
  buf, sender = sock.recvfrom(Net::DNS::PACKETSZ)
  peerhost = sender[2]
  peerport= sender[1]
  
  print "UDP connection from #{peerhost}:#{peerport}\n" if @verbose
  
  query = Net::DNS::Packet.new_from_binary(buf)
  
  reply = make_reply(query, peerhost) || return
  reply_data = reply.data
  
  #        local $| = 1 if @verbose
  print "Writing response - " if @verbose
  # die() ?!??  I think we need something better. --robert
  sock.send(reply_data, 0, peerhost, peerport) or raise RuntimError, "send: #{$!}"
  print "done\n" if @verbose
end