Object
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)
These methods raise an exception or return a response message with rcode==NOERROR
Dnsruby::Resolver#query(name [, type [, klass]])
These methods use a response queue to return the response and the error
Dnsruby::Resolver#send_async(msg, response_queue, query_id)
Dnsruby runs a pure Ruby event loop to handle I/O in a single thread. Support for EventMachine has been deprecated.
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.
Should truncation be ignored? i.e. the TC bit is ignored and thus the resolver will not requery over TCP if TC is set
If no_tcp==true, then ONLY UDP will be used as a transport. This should not generally be used, but is provided as a debugging aid.
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
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.
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.
Should TCP be used as a transport rather than UDP? If use_tcp==true, then ONLY TCP will be used as a transport.
# File lib/Dnsruby/Resolver.rb, line 599 def Resolver.check_port(p, src_port=[]) if (p.class != Fixnum) tmp_src_ports = Array.new(src_port) p.each do |x| if (!Resolver.check_port(x, tmp_src_ports)) return false end tmp_src_ports.push(x) end return true end if (Resolver.port_in_range(p)) if ((p == 0) && (src_port.length > 0)) return false end return true else Dnsruby.log.error("Illegal port (#{p})") raise ArgumentError.new("Illegal port #{p}") end end
# File lib/Dnsruby/Resolver.rb, line 631 def Resolver.get_ports_from(p) a = [] if (p.class == Fixnum) a = [p] else p.each do |x| a.push(x) end end return a end
# File lib/Dnsruby/Resolver.rb, line 665 def Resolver.get_tsig(args) tsig = nil if (args.length == 1) if (args[0]) if (args[0].instance_of?RR::TSIG) tsig = args[0] elsif (args[0].instance_of?Array) if (args[0].length > 2) tsig = RR.new_from_hash({:type => Types.TSIG, :klass => Classes.ANY, :name => args[0][0], :key => args[0][1], :algorithm => args[0][2]}) else tsig = RR.new_from_hash({:type => Types.TSIG, :klass => Classes.ANY, :name => args[0][0], :key => args[0][1]}) end end else # Dnsruby.log.debug{"TSIG signing switched off"} return nil end elsif (args.length ==2) tsig = RR.new_from_hash({:type => Types.TSIG, :klass => Classes.ANY, :name => args[0], :key => args[1]}) elsif (args.length ==3) tsig = RR.new_from_hash({:type => Types.TSIG, :klass => Classes.ANY, :name => args[0], :key => args[1], :algorithm => args[2]}) else raise ArgumentError.new("Wrong number of arguments to tsig=") end Dnsruby.log.info{"TSIG signing now using #{tsig.name}, key=#{tsig.key}"} return tsig 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
:tsig
:recurse
:config_info - see Config
:nameserver - can be either a String or an array of Strings
# File lib/Dnsruby/Resolver.rb, line 377 def initialize(*args) # @TODO@ Should we allow :namesver to be an RRSet of NS records? Would then need to randomly order them? @resolver_ruby = nil @src_address = nil @src_address6 = nil @single_res_mutex = Mutex.new @configured = false @do_caching = true @config = Config.new() reset_attributes # Process args if (args.length==1) if (args[0].class == Hash) args[0].keys.each do |key| begin if (key == :config_info) @config.set_config_info(args[0][:config_info]) elsif (key==:nameserver) set_config_nameserver(args[0][:nameserver]) elsif (key==:nameservers) set_config_nameserver(args[0][:nameservers]) else send(key.to_s+"=", args[0][key]) end rescue Exception => e Dnsruby.log.error{"Argument #{key} not valid : #{e}\n"} end end elsif (args[0].class == String) set_config_nameserver(args[0]) elsif (args[0].class == Config) # also accepts a Config object from Dnsruby::Resolv @config = args[0] end else # Anything to do? end # if (@single_resolvers==[]) # add_config_nameservers # end update # ResolverRegister::register_resolver(self) end
# File lib/Dnsruby/Resolver.rb, line 621 def Resolver.port_in_range(p) if ((p == 0) || ((p >= 50000) && (p <= 65535))) # @TODO@ IANA port bitmap - use 50000 - 65535 for now # ((Iana::IANA_PORTS.index(p)) == nil && # (p > 1024) && (p < 65535))) return true end return false 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. "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)
# File lib/Dnsruby/Resolver.rb, line 586 def add_src_port(p) if (Resolver.check_port(p, @src_port)) a = Resolver.get_ports_from(p) a.each do |x| if ((@src_port.length > 0) && (x == 0)) raise ArgumentError.new("src_port of 0 only allowed as only src_port value (currently #{@src_port.length} values") end @src_port.push(x) end end update end
Close the Resolver. Unfinished queries are terminated with OtherResolvError.
# File lib/Dnsruby/Resolver.rb, line 352 def close @resolver_ruby.close if @resolver_ruby end
# File lib/Dnsruby/Resolver.rb, line 734 def dnssec=(d) @dnssec = d if (d) # Set the UDP size (RFC 4035 section 4.1) if (@udp_size < MinDnssecUdpSize) self.udp_size = MinDnssecUdpSize end end update end
# File lib/Dnsruby/Resolver.rb, line 724 def do_caching=(on) @do_caching=on update end
# File lib/Dnsruby/Resolver.rb, line 694 def ignore_truncation=(on) @ignore_truncation = on update end
# File lib/Dnsruby/Resolver.rb, line 528 def nameserver=(n) @configured = true @single_res_mutex.synchronize { @single_resolvers=[] } set_config_nameserver(n) add_config_nameservers end
# File lib/Dnsruby/Resolver.rb, line 525 def nameservers=(ns) self.nameserver=(ns) end
# File lib/Dnsruby/Resolver.rb, line 648 def no_tcp=(on) @no_tcp=on update end
# File lib/Dnsruby/Resolver.rb, line 542 def packet_timeout=(t) @packet_timeout = t update end
# File lib/Dnsruby/Resolver.rb, line 714 def persistent_tcp=(on) @persistent_tcp = on update end
# File lib/Dnsruby/Resolver.rb, line 719 def persistent_udp=(on) @persistent_udp = on update end
# File lib/Dnsruby/Resolver.rb, line 709 def port=(a) @port = a update 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)
# File lib/Dnsruby/Resolver.rb, line 173 def query(name, type=Types.A, klass=Classes.IN, set_cd=@dnssec) msg = Message.new msg.do_caching = @do_caching msg.header.rd = 1 msg.add_question(name, type, klass) msg.do_validation = @do_validation if (@dnssec) msg.header.cd = set_cd # We do our own validation by default end return send_message(msg) end
# File lib/Dnsruby/Resolver.rb, line 729 def recurse=(a) @recurse = a update end
Asynchronously send a Message to the server. The send can be done using just Dnsruby. Support for EventMachine has been deprecated.
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 only 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
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)
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
# File lib/Dnsruby/Resolver.rb, line 332 def send_async(*args) # msg, client_queue, client_query_id) if (!@configured) add_config_nameservers end # @single_res_mutex.synchronize { if (!@resolver_ruby) # @TODO@ Synchronize this? @resolver_ruby = ResolverRuby.new(self) end # } client_query_id = @resolver_ruby.send_async(*args) if (@single_resolvers.length == 0) Thread.start { sleep(@query_timeout == 0 ? 1 : @query_timeout) args[1].push([client_query_id, nil, ResolvTimeout.new("Query timed out - no nameservers configured")]) } end return client_query_id 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
# File lib/Dnsruby/Resolver.rb, line 214 def send_message(message) Dnsruby.log.debug{"Resolver : sending message"} q = Queue.new send_async(message, q) # # @TODO@ Add new queue tuples, e.g. : # event_type = EventType::RECEIVED # reply = nil # while (event_type == EventType::RECEIVED) # id, event_type, reply, error = q.pop # Dnsruby.log.debug{"Resolver : result received"} # if ((error != nil) && (event_type == EventType::ERROR)) # raise error # end # print "Reply = #{reply}\n" # end # print "Reply = #{reply}\n" # return reply id, result, error = q.pop if (error != nil) raise error else return result end 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
# File lib/Dnsruby/Resolver.rb, line 267 def send_plain_message(message) Dnsruby::TheLog.debug("Resolver : send_plain_message") message.do_caching = false message.do_validation = false message.send_raw = true q = Queue.new send_async(message, q) id, result, error = q.pop return [result, error] end
# File lib/Dnsruby/Resolver.rb, line 440 def set_config_nameserver(n) # @TODO@ Should we allow NS RRSet here? If so, then .sort_by {rand} if (!@configured) @config.get_ready end @configured = true if (n).kind_of?String @config.nameserver=[n] else @config.nameserver=n end add_config_nameservers end
# File lib/Dnsruby/Resolver.rb, line 704 def src_address6=(a) @src_address6 = a update end
# File lib/Dnsruby/Resolver.rb, line 699 def src_address=(a) @src_address = a update 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
# File lib/Dnsruby/Resolver.rb, line 552 def src_port if (@src_port.length == 1) return @src_port[0] end return @src_port 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
# File lib/Dnsruby/Resolver.rb, line 567 def src_port=(p) if (Resolver.check_port(p)) @src_port = Resolver.get_ports_from(p) update end 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) # defaults to hmac-md5
res.tsig=(key_name, key, alg) # e.g. alg = "hmac-sha1"
res.tsig=nil # Stop the resolver from signing
# File lib/Dnsruby/Resolver.rb, line 660 def tsig=(t) @tsig=t update end
# File lib/Dnsruby/Resolver.rb, line 745 def udp_size=(s) @udp_size = s update end
# File lib/Dnsruby/Resolver.rb, line 516 def update_internal_res(res) [:port, :use_tcp, :no_tcp, :tsig, :ignore_truncation, :packet_timeout, :src_address, :src_address6, :src_port, :recurse, :udp_size, :dnssec].each do |param| res.send(param.to_s+"=", instance_variable_get("@"+param.to_s)) end end
Generated with the Darkfish Rdoc Generator 2.