| Class | Dnsruby::Resolver |
| In: |
lib/Dnsruby/Resolver.rb
|
| Parent: | 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 :
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
These methods use a response queue to return the response and the error
Dnsruby runs a pure Ruby event loop to handle I/O in a single thread. Support for EventMachine has been deprecated.
| DefaultQueryTimeout | = | 0 |
| DefaultPacketTimeout | = | 10 |
| DefaultRetryTimes | = | 4 |
| DefaultRetryDelay | = | 5 |
| DefaultPort | = | 53 |
| DefaultDnssec | = | true |
| AbsoluteMinDnssecUdpSize | = | 1220 |
| MinDnssecUdpSize | = | 4096 |
| DefaultUDPSize | = | MinDnssecUdpSize |
| config | [R] | The current Config |
| dnssec | [R] | Use DNSSEC for this Resolver |
| do_caching | [R] | Does this Resolver cache answers, and attempt to retrieve answer from the cache? |
| do_caching | [RW] | Defines whether we will cache responses, or pass every request to the upstream resolver. This is only really useful when querying authoritative servers (as the upstream recursive resolver is likely to cache) |
| 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 |
| no_tcp | [R] | 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. |
| 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? If use_tcp==true, then ONLY TCP will be used as a transport. |
# File lib/Dnsruby/Resolver.rb, line 593
593: def Resolver.check_port(p, src_port=[])
594: if (p.class != Fixnum)
595: tmp_src_ports = Array.new(src_port)
596: p.each do |x|
597: if (!Resolver.check_port(x, tmp_src_ports))
598: return false
599: end
600: tmp_src_ports.push(x)
601: end
602: return true
603: end
604: if (Resolver.port_in_range(p))
605: if ((p == 0) && (src_port.length > 0))
606: return false
607: end
608: return true
609: else
610: Dnsruby.log.error("Illegal port (#{p})")
611: raise ArgumentError.new("Illegal port #{p}")
612: end
613: end
# File lib/Dnsruby/Resolver.rb, line 625
625: def Resolver.get_ports_from(p)
626: a = []
627: if (p.class == Fixnum)
628: a = [p]
629: else
630: p.each do |x|
631: a.push(x)
632: end
633: end
634: return a
635: end
# File lib/Dnsruby/Resolver.rb, line 659
659: def Resolver.get_tsig(args)
660: tsig = nil
661: if (args.length == 1)
662: if (args[0])
663: if (args[0].instance_of?RR::TSIG)
664: tsig = args[0]
665: elsif (args[0].instance_of?Array)
666: if (args[0].length > 2)
667: tsig = RR.new_from_hash({:type => Types.TSIG, :klass => Classes.ANY, :name => args[0][0], :key => args[0][1], :algorithm => args[0][2]})
668: else
669: tsig = RR.new_from_hash({:type => Types.TSIG, :klass => Classes.ANY, :name => args[0][0], :key => args[0][1]})
670: end
671: end
672: else
673: # Dnsruby.log.debug{"TSIG signing switched off"}
674: return nil
675: end
676: elsif (args.length ==2)
677: tsig = RR.new_from_hash({:type => Types.TSIG, :klass => Classes.ANY, :name => args[0], :key => args[1]})
678: elsif (args.length ==3)
679: tsig = RR.new_from_hash({:type => Types.TSIG, :klass => Classes.ANY, :name => args[0], :key => args[1], :algorithm => args[2]})
680: else
681: raise ArgumentError.new("Wrong number of arguments to tsig=")
682: end
683: Dnsruby.log.info{"TSIG signing now using #{tsig.name}, key=#{tsig.key}"}
684: return tsig
685: 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 :
# File lib/Dnsruby/Resolver.rb, line 373
373: def initialize(*args)
374: # @TODO@ Should we allow :namesver to be an RRSet of NS records? Would then need to randomly order them?
375: @resolver_ruby = nil
376: @src_address = nil
377: @single_res_mutex = Mutex.new
378: @configured = false
379: @do_caching = true
380: @config = Config.new()
381: reset_attributes
382:
383: # Process args
384: if (args.length==1)
385: if (args[0].class == Hash)
386: args[0].keys.each do |key|
387: begin
388: if (key == :config_info)
389: @config.set_config_info(args[0][:config_info])
390: elsif (key==:nameserver)
391: set_config_nameserver(args[0][:nameserver])
392: elsif (key==:nameservers)
393: set_config_nameserver(args[0][:nameservers])
394: else
395: send(key.to_s+"=", args[0][key])
396: end
397: rescue Exception
398: Dnsruby.log.error{"Argument #{key} not valid\n"}
399: end
400: end
401: elsif (args[0].class == String)
402: set_config_nameserver(args[0])
403: elsif (args[0].class == Config)
404: # also accepts a Config object from Dnsruby::Resolv
405: @config = args[0]
406: end
407: else
408: # Anything to do?
409: end
410: # if (@single_resolvers==[])
411: # add_config_nameservers
412: # end
413: update
414: # ResolverRegister::register_resolver(self)
415: end
# File lib/Dnsruby/Resolver.rb, line 615
615: def Resolver.port_in_range(p)
616: if ((p == 0) || ((p >= 50000) && (p <= 65535)))
617: # @TODO@ IANA port bitmap - use 50000 - 65535 for now
618: # ((Iana::IANA_PORTS.index(p)) == nil &&
619: # (p > 1024) && (p < 65535)))
620: return true
621: end
622: return false
623: 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 580
580: def add_src_port(p)
581: if (Resolver.check_port(p, @src_port))
582: a = Resolver.get_ports_from(p)
583: a.each do |x|
584: if ((@src_port.length > 0) && (x == 0))
585: raise ArgumentError.new("src_port of 0 only allowed as only src_port value (currently #{@src_port.length} values")
586: end
587: @src_port.push(x)
588: end
589: end
590: update
591: end
Close the Resolver. Unfinished queries are terminated with OtherResolvError.
# File lib/Dnsruby/Resolver.rb, line 349
349: def close
350: @resolver_ruby.close if @resolver_ruby
351: end
# File lib/Dnsruby/Resolver.rb, line 723
723: def dnssec=(d)
724: @dnssec = d
725: if (d)
726: # Set the UDP size (RFC 4035 section 4.1)
727: if (@udp_size < MinDnssecUdpSize)
728: self.udp_size = MinDnssecUdpSize
729: end
730: end
731: update
732: end
# File lib/Dnsruby/Resolver.rb, line 713
713: def do_caching=(on)
714: @do_caching=on
715: update
716: end
# File lib/Dnsruby/Resolver.rb, line 688
688: def ignore_truncation=(on)
689: @ignore_truncation = on
690: update
691: end
# File lib/Dnsruby/Resolver.rb, line 522
522: def nameserver=(n)
523: @configured = true
524: @single_res_mutex.synchronize {
525: @single_resolvers=[]
526: }
527: set_config_nameserver(n)
528: add_config_nameservers
529: end
# File lib/Dnsruby/Resolver.rb, line 519
519: def nameservers=(ns)
520: self.nameserver=(n)
521: end
# File lib/Dnsruby/Resolver.rb, line 536
536: def packet_timeout=(t)
537: @packet_timeout = t
538: update
539: end
# File lib/Dnsruby/Resolver.rb, line 703
703: def persistent_tcp=(on)
704: @persistent_tcp = on
705: update
706: end
# File lib/Dnsruby/Resolver.rb, line 708
708: def persistent_udp=(on)
709: @persistent_udp = on
710: update
711: 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 170
170: def query(name, type=Types.A, klass=Classes.IN, set_cd=@dnssec)
171: msg = Message.new
172: msg.do_caching = @do_caching
173: msg.header.rd = 1
174: msg.add_question(name, type, klass)
175: msg.do_validation = @do_validation
176: if (@dnssec)
177: msg.header.cd = set_cd # We do our own validation by default
178: end
179: return send_message(msg)
180: end
# File lib/Dnsruby/Resolver.rb, line 718
718: def recurse=(a)
719: @recurse = a
720: update
721: 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 :
Returns :
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 329
329: def send_async(*args) # msg, client_queue, client_query_id)
330: if (!@configured)
331: add_config_nameservers
332: end
333: # @single_res_mutex.synchronize {
334: if (!@resolver_ruby) # @TODO@ Synchronize this?
335: @resolver_ruby = ResolverRuby.new(self)
336: end
337: # }
338: client_query_id = @resolver_ruby.send_async(*args)
339: if (@single_resolvers.length == 0)
340: Thread.start {
341: sleep(@query_timeout == 0 ? 1 : @query_timeout)
342: args[1].push([client_query_id, nil, ResolvTimeout.new("Query timed out - no nameservers configured")])
343: }
344: end
345: return client_query_id
346: 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 211
211: def send_message(message)
212: Dnsruby.log.debug{"Resolver : sending message"}
213: q = Queue.new
214: send_async(message, q)
215: # # @TODO@ Add new queue tuples, e.g. :
216: # event_type = EventType::RECEIVED
217: # reply = nil
218: # while (event_type == EventType::RECEIVED)
219: # id, event_type, reply, error = q.pop
220: # Dnsruby.log.debug{"Resolver : result received"}
221: # if ((error != nil) && (event_type == EventType::ERROR))
222: # raise error
223: # end
224: # print "Reply = #{reply}\n"
225: # end
226: # print "Reply = #{reply}\n"
227: # return reply
228:
229: id, result, error = q.pop
230:
231: if (error != nil)
232: raise error
233: else
234: return result
235: end
236: 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 264
264: def send_plain_message(message)
265: Dnsruby::TheLog.debug("Resolver : send_plain_message")
266: message.do_caching = false
267: message.do_validation = false
268: message.send_raw = true
269: q = Queue.new
270: send_async(message, q)
271: id, result, error = q.pop
272: return [result, error]
273: end
# File lib/Dnsruby/Resolver.rb, line 435
435: def set_config_nameserver(n)
436: # @TODO@ Should we allow NS RRSet here? If so, then .sort_by {rand}
437: if (!@configured)
438: @config.get_ready
439: end
440: @configured = true
441: if (n).kind_of?String
442: @config.nameserver=[n]
443: else
444: @config.nameserver=n
445: end
446: add_config_nameservers
447: end
# File lib/Dnsruby/Resolver.rb, line 693
693: def src_address=(a)
694: @src_address = a
695: update
696: 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 546
546: def src_port
547: if (@src_port.length == 1)
548: return @src_port[0]
549: end
550: return @src_port
551: 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 561
561: def src_port=(p)
562: if (Resolver.check_port(p))
563: @src_port = Resolver.get_ports_from(p)
564: update
565: end
566: 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.
# File lib/Dnsruby/Resolver.rb, line 654
654: def tsig=(t)
655: @tsig=t
656: update
657: end
# File lib/Dnsruby/Resolver.rb, line 734
734: def udp_size=(s)
735: @udp_size = s
736: update
737: end
# File lib/Dnsruby/Resolver.rb, line 510
510: def update_internal_res(res)
511: [:port, :use_tcp, :no_tcp, :tsig, :ignore_truncation, :packet_timeout,
512: :src_address, :src_port, :recurse,
513: :udp_size, :dnssec].each do |param|
514:
515: res.send(param.to_s+"=", instance_variable_get("@"+param.to_s))
516: end
517: end