Class Dnsruby::Resolver
In: lib/Dnsruby/Resolver.rb
Parent: Object
ResolvError EncodeError OtherResolvError ServFail FormErr DecodeError NXRRSet YXDomain NotImp NXDomain VerifyError NotAuth YXRRSet NotZone Refused TsigError Message Update CodeMapper Types MetaTypes QTypes Nsec3HashAlgorithms Algorithms OpCode Classes ExtendedRCode RCode Modes Comparable Name RRSet Resolver SingleResolver StandardError TimeoutError ResolvTimeout DNS Dnssec Hosts SelectThread\n[lib/Dnsruby/select_thread.rb\nlib/Dnsruby/select_thread.rb.michael.rb] Recursor IPv6 IPv4 ZoneTransfer MessageDecoder MessageEncoder Question Header TheLog RR\n[lib/Dnsruby/resource/A.rb\nlib/Dnsruby/resource/AAAA.rb\nlib/Dnsruby/resource/AFSDB.rb\nlib/Dnsruby/resource/CERT.rb\nlib/Dnsruby/resource/DLV.rb\nlib/Dnsruby/resource/DNSKEY.rb\nlib/Dnsruby/resource/DS.rb\nlib/Dnsruby/resource/HINFO.rb\nlib/Dnsruby/resource/IN.rb\nlib/Dnsruby/resource/ISDN.rb\nlib/Dnsruby/resource/LOC.rb\nlib/Dnsruby/resource/MINFO.rb\nlib/Dnsruby/resource/MX.rb\nlib/Dnsruby/resource/NAPTR.rb\nlib/Dnsruby/resource/NSAP.rb\nlib/Dnsruby/resource/NSEC.rb\nlib/Dnsruby/resource/NSEC3.rb\nlib/Dnsruby/resource/NSEC3PARAM.rb\nlib/Dnsruby/resource/OPT.rb\nlib/Dnsruby/resource/PX.rb\nlib/Dnsruby/resource/RP.rb\nlib/Dnsruby/resource/RRSIG.rb\nlib/Dnsruby/resource/RT.rb\nlib/Dnsruby/resource/SOA.rb\nlib/Dnsruby/resource/SPF.rb\nlib/Dnsruby/resource/SRV.rb\nlib/Dnsruby/resource/TKEY.rb\nlib/Dnsruby/resource/TSIG.rb\nlib/Dnsruby/resource/TXT.rb\nlib/Dnsruby/resource/X25.rb\nlib/Dnsruby/resource/domain_name.rb\nlib/Dnsruby/resource/generic.rb\nlib/Dnsruby/resource/resource.rb] ValidatorThread PacketSender ResolverRuby Config KeyCache Cache SingleVerifier Resolv Iana lib/Dnsruby/DNS.rb lib/Dnsruby/dnssec.rb lib/Dnsruby/Hosts.rb lib/Dnsruby/select_thread.rb.michael.rb lib/Dnsruby/Recursor.rb lib/Dnsruby/update.rb lib/Dnsruby/ipv6.rb lib/Dnsruby/ipv4.rb lib/Dnsruby/code_mapper.rb lib/Dnsruby/zone_transfer.rb lib/Dnsruby/message.rb lib/Dnsruby/TheLog.rb lib/Dnsruby/resource/resource.rb lib/Dnsruby/validator_thread.rb lib/Dnsruby/PacketSender.rb lib/Dnsruby/Resolver.rb lib/Dnsruby/Config.rb lib/Dnsruby/key_cache.rb lib/Dnsruby/Cache.rb lib/Dnsruby/single_verifier.rb lib/Dnsruby/SingleResolver.rb lib/Dnsruby/name.rb lib/dnsruby.rb lib/Dnsruby/resource/TKEY.rb lib/Dnsruby/iana_ports.rb Dnsruby dot/m_56_0.png

Description

Dnsruby::Resolver is a DNS stub resolver. This class performs queries with retries across multiple nameservers. The system configured resolvers are used by default.

The retry policy is a combination of the Net::DNS and dnsjava approach, and has the option of :

  • A total timeout for the query (defaults to 0, meaning "no total timeout")
  • A retransmission system that targets the namervers concurrently once the first query round is complete, but in which the total time per query round is split between the number of nameservers targetted for the first round. and total time for query round is doubled for each query round
 Note that, if a total timeout is specified, then that will apply regardless of the retry policy

(i.e. it may cut retries short).

 Note also that these timeouts are distinct from the SingleResolver's packet_timeout

 Timeouts apply to the initial query and response. If DNSSEC validation is to
 be performed, then additional queries may be required (these are performed automatically
 by Dnsruby). Each additional query will be performed with its own timeouts.
 So, even with a query_timeout of 5 seconds, a response which required extensive
 validation may take several times that long.
 (Future versions of Dnsruby may expose finer-grained events for client tracking of
 responses and validation)

Methods

Synchronous

These methods raise an exception or return a response message with rcode==NOERROR

Asynchronous

These methods use a response queue to return the response and the error

Event Loop

Dnsruby runs a pure Ruby event loop to handle I/O in a single thread. Support for EventMachine has been deprecated.

Methods

Classes and Modules

Class Dnsruby::Resolver::EventType

Constants

DefaultQueryTimeout = 0
DefaultPacketTimeout = 10
DefaultRetryTimes = 4
DefaultRetryDelay = 5
DefaultPort = 53
DefaultDnssec = true
AbsoluteMinDnssecUdpSize = 1220
MinDnssecUdpSize = 4096
DefaultUDPSize = MinDnssecUdpSize

Attributes

config  [R]  The current Config
dnssec  [R]  Use DNSSEC for this Resolver
do_validation  [RW]  Defines whether validation is performed by default on this Resolver when the query method is called. Note that send_message and send_async expect a Message object to be passed in, which is already configured to the callers requirements.
ignore_truncation  [R]  Should truncation be ignored? i.e. the TC bit is ignored and thus the resolver will not requery over TCP if TC is set
packet_timeout  [R]  The timeout for any individual packet. This is the timeout used by SingleResolver
port  [R]  The port to send queries to on the resolver
query_timeout  [RW]  Note that this timeout represents the total time a query may run for - multiple packets can be sent to multiple nameservers in this time. This is distinct from the SingleResolver per-packet timeout The query_timeout is not required - it will default to 0, which means "do not use query_timeout". If this is the case then the timeout will be dictated by the retry_times and retry_delay attributes
recurse  [R]  Should the Recursion Desired bit be set?
retry_delay  [RW]  The query will be tried across nameservers retry_times times, with a delay of retry_delay seconds between each retry. The first time round, retry_delay will be divided by the number of nameservers being targetted, and a new nameserver will be queried with the resultant delay.
retry_times  [RW]  The query will be tried across nameservers retry_times times, with a delay of retry_delay seconds between each retry. The first time round, retry_delay will be divided by the number of nameservers being targetted, and a new nameserver will be queried with the resultant delay.
src_address  [R]  The source address to send queries from
tsig  [R] 
udp_size  [R]  The maximum UDP size to be used
use_tcp  [R]  Should TCP be used as a transport rather than UDP?

Public Class methods

[Source]

     # File lib/Dnsruby/Resolver.rb, line 559
559:     def Resolver.check_port(p, src_port=[])
560:       if (p.class != Fixnum)
561:         tmp_src_ports = Array.new(src_port)
562:         p.each do |x|
563:           if (!Resolver.check_port(x, tmp_src_ports))
564:             return false
565:           end
566:           tmp_src_ports.push(x)
567:         end
568:         return true
569:       end
570:       if (Resolver.port_in_range(p))
571:         if ((p == 0) && (src_port.length > 0))
572:           return false
573:         end
574:         return true
575:       else
576:         Dnsruby.log.error("Illegal port (#{p})")
577:         raise ArgumentError.new("Illegal port #{p}")
578:       end
579:     end

[Source]

     # File lib/Dnsruby/Resolver.rb, line 589
589:     def Resolver.get_ports_from(p)
590:       a = []
591:       if (p.class == Fixnum)
592:         a = [p]
593:       else
594:         p.each do |x|
595:           a.push(x)
596:         end
597:       end
598:       return a
599:     end

[Source]

     # File lib/Dnsruby/Resolver.rb, line 617
617:     def Resolver.get_tsig(args)
618:       tsig = nil
619:       if (args.length == 1)
620:         if (args[0])
621:           if (args[0].instance_of?RR::TSIG)
622:             tsig = args[0]
623:           elsif (args[0].instance_of?Array)
624:             tsig = RR.new_from_hash({:type => Types.TSIG, :klass => Classes.ANY, :name => args[0][0], :key => args[0][1]})
625:           end
626:         else
627:           #          Dnsruby.log.debug{"TSIG signing switched off"}

628:           return nil
629:         end
630:       elsif (args.length ==2)
631:         tsig = RR.new_from_hash({:type => Types.TSIG, :klass => Classes.ANY, :name => args[0], :key => args[1]})
632:       else
633:         raise ArgumentError.new("Wrong number of arguments to tsig=")
634:       end
635:       Dnsruby.log.info{"TSIG signing now using #{tsig.name}, key=#{tsig.key}"}
636:       return tsig
637:     end

Create a new Resolver object. If no parameters are passed in, then the default system configuration will be used. Otherwise, a Hash may be passed in with the following optional elements :

  • :port
  • :use_tcp
  • :tsig
  • :ignore_truncation
  • :src_address
  • :src_port
  • :recurse
  • :udp_size
  • :config_info - see Config
  • :nameserver - can be either a String or an array of Strings
  • :packet_timeout
  • :query_timeout
  • :retry_times
  • :retry_delay

[Source]

     # File lib/Dnsruby/Resolver.rb, line 350
350:     def initialize(*args)
351:       # @TODO@ Should we allow :namesver to be an RRSet of NS records? Would then need to randomly order them?

352:       @resolver_ruby = nil
353:       @src_address = nil
354:       @single_res_mutex = Mutex.new
355:       @configured = false
356:       @config = Config.new()
357:       reset_attributes
358:       
359:       # Process args

360:       if (args.length==1)
361:         if (args[0].class == Hash)
362:           args[0].keys.each do |key|
363:             begin
364:               if (key == :config_info)
365:                 @config.set_config_info(args[0][:config_info])
366:               elsif (key==:nameserver)
367:                 set_config_nameserver(args[0][:nameserver])
368:               elsif (key==:nameservers)
369:                 set_config_nameserver(args[0][:nameservers])
370:               else
371:                 send(key.to_s+"=", args[0][key])
372:               end
373:             rescue Exception
374:               Dnsruby.log.error{"Argument #{key} not valid\n"}
375:             end
376:           end
377:         elsif (args[0].class == String)
378:           set_config_nameserver(args[0])          
379:         elsif (args[0].class == Config)
380:           # also accepts a Config object from Dnsruby::Resolv

381:           @config = args[0]
382:         end
383:       else
384:         # Anything to do?

385:       end
386:       #      if (@single_resolvers==[])

387:       #        add_config_nameservers

388:       #      end

389:       update
390:       #      ResolverRegister::register_resolver(self)

391:     end

[Source]

     # File lib/Dnsruby/Resolver.rb, line 581
581:     def Resolver.port_in_range(p)
582:       if ((p == 0) || ((Iana::IANA_PORTS.index(p)) == nil &&
583:               (p > 1024) && (p < 65535)))
584:         return true
585:       end
586:       return false
587:     end

Public Instance methods

Can be a single Fixnum or a Range or an Array If an invalid port is selected (one reserved by IANA), then an ArgumentError will be raised. "0" means "any valid port" - this is only a viable option if it is the only port in the list. An ArgumentError will be raised if "0" is added to an existing set of source ports.

       res.add_src_port(60000)
       res.add_src_port([60001,60005,60010])
       res.add_src_port(60015..60115)

[Source]

     # File lib/Dnsruby/Resolver.rb, line 546
546:     def add_src_port(p)
547:       if (Resolver.check_port(p, @src_port))
548:         a = Resolver.get_ports_from(p)
549:         a.each do |x|
550:           if ((@src_port.length > 0) && (x == 0))
551:             raise ArgumentError.new("src_port of 0 only allowed as only src_port value (currently #{@src_port.length} values")
552:           end
553:           @src_port.push(x)
554:         end
555:       end
556:       update
557:     end

Close the Resolver. Unfinished queries are terminated with OtherResolvError.

[Source]

     # File lib/Dnsruby/Resolver.rb, line 327
327:     def close
328:       @resolver_ruby.close if @resolver_ruby
329:     end

[Source]

     # File lib/Dnsruby/Resolver.rb, line 670
670:     def dnssec=(d)
671:       @dnssec = d
672:       if (d)
673:         # Set the UDP size (RFC 4035 section 4.1)

674:         if (@udp_size < MinDnssecUdpSize)
675:           self.udp_size = MinDnssecUdpSize
676:         end
677:       end
678:       update
679:     end

[Source]

     # File lib/Dnsruby/Resolver.rb, line 640
640:     def ignore_truncation=(on)
641:       @ignore_truncation = on
642:       update
643:     end

[Source]

     # File lib/Dnsruby/Resolver.rb, line 488
488:     def nameserver=(n)
489:       @configured = true
490:             @single_res_mutex.synchronize {
491:       @single_resolvers=[]
492:             }
493:       set_config_nameserver(n)
494:       add_config_nameservers
495:     end

[Source]

     # File lib/Dnsruby/Resolver.rb, line 485
485:     def nameservers=(ns)
486:       self.nameserver=(n)
487:     end

[Source]

     # File lib/Dnsruby/Resolver.rb, line 502
502:     def packet_timeout=(t)
503:       @packet_timeout = t
504:       update
505:     end

[Source]

     # File lib/Dnsruby/Resolver.rb, line 655
655:     def persistent_tcp=(on)
656:       @persistent_tcp = on
657:       update
658:     end

[Source]

     # File lib/Dnsruby/Resolver.rb, line 660
660:     def persistent_udp=(on)
661:       @persistent_udp = on
662:       update
663:     end

[Source]

     # File lib/Dnsruby/Resolver.rb, line 650
650:     def port=(a)
651:       @port = a
652:       update
653:     end

Query for a name. If a valid Message is received, then it is returned to the caller. Otherwise an exception (a Dnsruby::ResolvError or Dnsruby::ResolvTimeout) is raised.

  require 'Dnsruby'
  res = Dnsruby::Resolver.new
  response = res.query("example.com") # defaults to Types.A, Classes.IN
  response = res.query("example.com", Types.MX)
  response = res.query("208.77.188.166") # IPv4 address so PTR query will be made
  response = res.query("208.77.188.166", Types.PTR)

[Source]

     # File lib/Dnsruby/Resolver.rb, line 157
157:     def query(name, type=Types.A, klass=Classes.IN, set_cd=@dnssec)
158:       msg = Message.new
159:       msg.header.rd = 1
160:       msg.add_question(name, type, klass)
161:       msg.do_validation = @do_validation
162:       if (@dnssec)
163:         msg.header.cd = set_cd # We do our own validation by default

164:       end
165:       return send_message(msg)
166:     end

[Source]

     # File lib/Dnsruby/Resolver.rb, line 665
665:     def recurse=(a)
666:       @recurse = a
667:       update
668:     end

Asynchronously send a Message to the server. The send can be done using just Dnsruby. Support for EventMachine has been deprecated.

Dnsruby pure Ruby event loop :

A client_queue is supplied by the client, along with an optional client_query_id to identify the response. The client_query_id is generated, if not supplied, and returned to the client. When the response is known, a tuple of (query_id, response_message, exception) will be added to the client_queue.

The query is sent synchronously in the caller‘s thread. The select thread is then used to listen for and process the response (up to pushing it to the client_queue). The client thread is then used to retrieve the response and deal with it.

Takes :

  • msg - the message to send
  • client_queue - a Queue to push the response to, when it arrives
  • client_query_id - an optional ID to identify the query to the client
  • use_tcp - whether to use TCP (defaults to SingleResolver.use_tcp)

Returns :

  • client_query_id - to identify the query response to the client. This ID is

generated if it is not passed in by the client

Example invocations :

    id = res.send_async(msg, queue)
    NOT SUPPORTED : id = res.send_async(msg, queue, use_tcp)
    id = res.send_async(msg, queue, id)
    id = res.send_async(msg, queue, id, use_tcp)

Example code :

   require 'Dnsruby'
   res = Dnsruby::Resolver.newsend
   query_id = 10 # can be any object you like
   query_queue = Queue.new
   res.send_async(Message.new("example.com", Types.MX),  query_queue, query_id)
   query_id_2 = res.send_async(Message.new("example.com", Types.A), query_queue)
   # ...do a load of other stuff here...
   2.times do
     response_id, response, exception = query_queue.pop
     # You can check the ID to see which query has been answered
     if (exception == nil)
         # deal with good response
     else
         # deal with problem
     end
   end

[Source]

     # File lib/Dnsruby/Resolver.rb, line 314
314:     def send_async(*args) # msg, client_queue, client_query_id)

315:       if (!@configured)
316:         add_config_nameservers
317:       end
318: #      @single_res_mutex.synchronize {

319:       if (!@resolver_ruby) # @TODO@ Synchronize this?

320:         @resolver_ruby = ResolverRuby.new(self)
321:       end
322: #      }

323:       return @resolver_ruby.send_async(*args)
324:     end

Send a message, and wait for the response. If a valid Message is received, then it is returned to the caller. Otherwise an exception (a Dnsruby::ResolvError or Dnsruby::ResolvTimeout) is raised.

send_async is called internally.

example :

  require 'dnsruby'
  include Dnsruby
  res = Dnsruby::Resolver.new
  begin
  response = res.send_message(Message.new("example.com", Types.MX))
  rescue ResolvError
    # ...
  rescue ResolvTimeout
    # ...
  end

[Source]

     # File lib/Dnsruby/Resolver.rb, line 196
196:     def send_message(message)
197:       Dnsruby.log.debug{"Resolver : sending message"}
198:       q = Queue.new
199:       send_async(message, q)
200:       #      # @TODO@ Add new queue tuples, e.g. :

201:       #      event_type = EventType::RECEIVED

202:       #      reply = nil

203:       #      while (event_type == EventType::RECEIVED)

204:       #        id, event_type, reply, error = q.pop

205:       #        Dnsruby.log.debug{"Resolver : result received"}

206:       #        if ((error != nil) && (event_type == EventType::ERROR))

207:       #          raise error

208:       #        end

209:       #        print "Reply = #{reply}\n"

210:       #      end

211:       #      print "Reply = #{reply}\n"

212:       #      return reply

213: 
214:       id, result, error = q.pop
215: 
216:       if (error != nil)
217:         raise error
218:       else
219:         return result
220:       end
221:     end

This method takes a Message (supplied by the client), and sends it to the configured nameservers. No changes are made to the Message before it is sent (TSIG signatures will be applied if configured on the Resolver). Retries are handled as the Resolver is configured to do. Incoming responses to the query are not cached or validated (although TCP fallback will be performed if the TC bit is set and the (Single)Resolver has ignore_truncation set to false). Note that the Message is left untouched - this means that no OPT records are added, even if the UDP transport for the server is specified at more than 512 bytes. If it is desired to use EDNS for this packet, then you should call the Dnsruby::PacketSender#prepare_for_dnssec(msg), or Dnsruby::PacketSender#add_opt_rr(msg) The return value from this method is the [response, error] tuple. Either of these values may be nil - it is up to the client to check.

example :

  require 'dnsruby'
  include Dnsruby
  res = Dnsruby::Resolver.new
  response, error = res.send_plain_message(Message.new("example.com", Types.MX))
  if (error)
    print "Error returned : #{error}\n"
  else
    process_response(response)
  end

[Source]

     # File lib/Dnsruby/Resolver.rb, line 249
249:     def send_plain_message(message)
250:       Dnsruby::TheLog.debug("Resolver : send_plain_message")
251:       message.do_caching = false
252:       message.do_validation = false
253:       message.send_raw = true
254:       q = Queue.new
255:       send_async(message, q)
256:       id, result, error = q.pop
257:       return [result, error]
258:     end

[Source]

     # File lib/Dnsruby/Resolver.rb, line 410
410:     def set_config_nameserver(n)
411:       # @TODO@ Should we allow NS RRSet here? If so, then .sort_by {rand}

412:       if (!@configured)
413:         @config.get_ready
414:       end
415:       @configured = true
416:       if (n).kind_of?String
417:         @config.nameserver=[n]
418:       else
419:         @config.nameserver=n
420:       end
421:       add_config_nameservers
422:     end

[Source]

     # File lib/Dnsruby/Resolver.rb, line 645
645:     def src_address=(a)
646:       @src_address = a
647:       update
648:     end

The source port to send queries from Returns either a single Fixnum or an Array e.g. "0", or "[60001, 60002, 60007]"

Defaults to 0 - random port

[Source]

     # File lib/Dnsruby/Resolver.rb, line 512
512:     def src_port
513:       if (@src_port.length == 1) 
514:         return @src_port[0]
515:       end
516:       return @src_port
517:     end

Can be a single Fixnum or a Range or an Array If an invalid port is selected (one reserved by IANA), then an ArgumentError will be raised.

       res.src_port=0
       res.src_port=[60001,60005,60010]
       res.src_port=60015..60115

[Source]

     # File lib/Dnsruby/Resolver.rb, line 527
527:     def src_port=(p)
528:       if (Resolver.check_port(p))
529:         @src_port = Resolver.get_ports_from(p)
530:         update
531:       end
532:     end

Sets the TSIG to sign outgoing messages with. Pass in either a Dnsruby::RR::TSIG, or a key_name and key (or just a key) Pass in nil to stop tsig signing.

  • res.tsig=(tsig_rr)
  • res.tsig=(key_name, key)
  • res.tsig=nil # Stop the resolver from signing

[Source]

     # File lib/Dnsruby/Resolver.rb, line 612
612:     def tsig=(t)
613:       @tsig=t
614:       update
615:     end

[Source]

     # File lib/Dnsruby/Resolver.rb, line 681
681:     def udp_size=(s)
682:       @udp_size = s
683:       update
684:     end

[Source]

     # File lib/Dnsruby/Resolver.rb, line 476
476:     def update_internal_res(res)
477:       [:port, :use_tcp, :tsig, :ignore_truncation, :packet_timeout,
478:         :src_address, :src_port, :recurse,
479:         :udp_size, :dnssec].each do |param|
480: 
481:         res.send(param.to_s+"=", instance_variable_get("@"+param.to_s))
482:       end
483:     end

[Source]

     # File lib/Dnsruby/Resolver.rb, line 601
601:     def use_tcp=(on)
602:       @use_tcp = on
603:       update
604:     end

[Validate]