Class: Net::DNS::Resolver
- Inherits:
-
Object
- Object
- Net::DNS::Resolver
- Defined in:
- lib/net/dns/resolver.rb
Overview
Name
Net::DNS::Resolver - DNS resolver class
Synopsis
require 'net/dns/resolver'
Description
The Net::DNS::Resolver class implements a complete DNS resolver written in pure Ruby, without a single C line of code. It has all of the tipical properties of an evoluted resolver, and a bit of OO which comes from having used Ruby.
This project started as a porting of the Net::DNS Perl module, written by Martin Fuhr, but turned out (in the last months) to be an almost complete rewriting. Well, maybe some of the features of the Perl version are still missing, but guys, at least this is readable code!
FIXME
Environment
The Following Environment variables can also be used to configure the resolver:
-
RES_NAMESERVERS
: A space-separated list of nameservers to query.# Bourne Shell $ RES_NAMESERVERS="192.168.1.1 192.168.2.2 192.168.3.3" $ export RES_NAMESERVERS # C Shell % setenv RES_NAMESERVERS "192.168.1.1 192.168.2.2 192.168.3.3"
-
RES_SEARCHLIST
: A space-separated list of domains to put in the search list.# Bourne Shell $ RES_SEARCHLIST="example.com sub1.example.com sub2.example.com" $ export RES_SEARCHLIST # C Shell % setenv RES_SEARCHLIST "example.com sub1.example.com sub2.example.com"
-
LOCALDOMAIN
: The default domain.# Bourne Shell $ LOCALDOMAIN=example.com $ export LOCALDOMAIN # C Shell % setenv LOCALDOMAIN example.com
-
RES_OPTIONS
: A space-separated list of resolver options to set.Options that take values are specified as option:value.
# Bourne Shell $ RES_OPTIONS="retrans:3 retry:2 debug" $ export RES_OPTIONS # C Shell % setenv RES_OPTIONS "retrans:3 retry:2 debug"
Constant Summary collapse
- Defaults =
An hash with the defaults values of almost all the configuration parameters of a resolver object. See the description for each parameter to have an explanation of its usage.
{ :config_file => "/etc/resolv.conf", :log_file => $stdout, :port => 53, :searchlist => [], :nameservers => [IPAddr.new("127.0.0.1")], :domain => "", :source_port => 0, :source_address => IPAddr.new("0.0.0.0"), :retry_interval => 5, :retry_number => 4, :recursive => true, :defname => true, :dns_search => true, :use_tcp => false, :ignore_truncated => false, :packet_size => 512, :tcp_timeout => TcpTimeout.new(120), :udp_timeout => UdpTimeout.new(0)}
Class Method Summary collapse
-
.platform_windows? ⇒ Boolean
Returns true if running on a Windows platform.
-
.start(*params) ⇒ Object
Quick resolver method.
Instance Method Summary collapse
-
#axfr(name, cls = Net::DNS::IN) ⇒ Object
Performs a zone transfer for the zone passed as a parameter.
-
#defname=(bool) ⇒ Object
Set the flag
defname
in a boolean state. -
#defname? ⇒ Boolean
(also: #defname)
Checks whether the
defname
flag has been activate. -
#dns_search ⇒ Object
(also: #dnsrch)
Get the state of the dns_search flag.
-
#dns_search=(bool) ⇒ Object
(also: #dnsrch=)
Set the flag
dns_search
in a boolean state. -
#domain ⇒ Object
Return a string with the default domain.
-
#domain=(name) ⇒ Object
Set the domain for the query.
- #ignore_truncated=(bool) ⇒ Object
- #ignore_truncated? ⇒ Boolean (also: #ignore_truncated)
-
#initialize(config = {}) ⇒ Resolver
constructor
Create a new resolver object.
-
#log_file=(log) ⇒ Object
Set a new log file for the logger facility of the resolver class.
-
#log_level=(level) ⇒ Object
Set the log level for the built-in logging facility.
-
#logger=(logger) ⇒ Object
This one permits to have a personal logger facility to handle resolver messages, instead of new built-in one, which is set up for a $stdout (or $stderr) use.
-
#mx(name, cls = Net::DNS::IN) ⇒ Object
Performs an MX query for the domain name passed as parameter.
-
#nameservers ⇒ Object
(also: #nameserver)
Get the list of resolver nameservers, in a dotted decimal format.
-
#nameservers=(arg) ⇒ Object
(also: #nameserver=)
Set the list of resolver nameservers
arg
can be a single ip address or an array of addresses. -
#packet_size ⇒ Object
Return the defined size of the packet.
-
#port ⇒ Object
Get the port number to which the resolver sends queries.
-
#port=(num) ⇒ Object
Set the port number to which the resolver sends queries.
-
#query(name, type = Net::DNS::A, cls = Net::DNS::IN) ⇒ Object
Performs a DNS query for the given name; the search list is not applied.
-
#recursive=(bool) ⇒ Object
(also: #recurse=)
Sets whether or not the resolver should perform recursive queries.
-
#recursive? ⇒ Boolean
(also: #recurse, #recursive)
This method will return true if the resolver is configured to perform recursive queries.
-
#retry_interval ⇒ Object
(also: #retrans)
Return the retrasmission interval (in seconds) the resolvers has been set on.
-
#retry_interval=(num) ⇒ Object
(also: #retrans=)
Set the retrasmission interval in seconds.
-
#retry_number ⇒ Object
The number of times the resolver will try a query.
-
#retry_number=(num) ⇒ Object
(also: #retry=)
Set the number of times the resolver will try a query.
-
#search(name, type = Net::DNS::A, cls = Net::DNS::IN) ⇒ Object
Performs a DNS query for the given name, applying the searchlist if appropriate.
-
#searchlist ⇒ Object
Get the resolver searchlist, returned as an array of entries.
-
#searchlist=(arg) ⇒ Object
Set the resolver searchlist.
-
#send(argument, type = Net::DNS::A, cls = Net::DNS::IN) ⇒ Object
Performs a DNS query for the given name.
-
#source_address ⇒ Object
(also: #srcaddr)
Get the local address from which the resolver sends queries.
-
#source_address=(addr) ⇒ Object
(also: #srcaddr=)
Set the local source address from which the resolver sends its queries.
-
#source_port ⇒ Object
(also: #srcport)
Get the value of the source port number.
-
#source_port=(num) ⇒ Object
(also: #srcport=)
Set the local source port from which the resolver sends its queries.
-
#state ⇒ Object
(also: #print, #inspect)
Return a string rapresenting the resolver state, suitable for printing on the screen.
-
#tcp_timeout ⇒ Object
Return an object representing the value of the stored TCP timeout the resolver will use in is queries.
-
#tcp_timeout=(secs) ⇒ Object
Set the value of TCP timeout for resolver queries that will be performed using TCP.
-
#udp_timeout ⇒ Object
Return an object representing the value of the stored UDP timeout the resolver will use in is queries.
-
#udp_timeout=(secs) ⇒ Object
Set the value of UDP timeout for resolver queries that will be performed using UDP.
-
#use_tcp=(bool) ⇒ Object
(also: #usevc=)
If
use_tcp
is true, the resolver will perform all queries using TCP virtual circuits instead of UDP datagrams, which is the default for the DNS protocol. -
#use_tcp? ⇒ Boolean
(also: #usevc, #use_tcp)
Get the state of the use_tcp flag.
Constructor Details
#initialize(config = {}) ⇒ Resolver
Create a new resolver object.
Argument config
can either be empty or be an hash with some configuration parameters. To know what each parameter do, look at the description of each. Some example:
# Use the sistem defaults
res = Net::DNS::Resolver.new
# Specify a configuration file
res = Net::DNS::Resolver.new(:config_file => '/my/dns.conf')
# Set some option
res = Net::DNS::Resolver.new(:nameservers => "172.16.1.1",
:recursive => false,
:retry => 10)
Config file
Net::DNS::Resolver uses a config file to read the usual values a resolver needs, such as nameserver list and domain names. On UNIX systems the defaults are read from the following files, in the order indicated:
-
/etc/resolv.conf
-
$HOME/.resolv.conf
-
./.resolv.conf
The following keywords are recognized in resolver configuration files:
-
domain: the default domain.
-
search: a space-separated list of domains to put in the search list.
-
nameserver: a space-separated list of nameservers to query.
Files except for /etc/resolv.conf must be owned by the effective userid running the program or they won’t be read. In addition, several environment variables can also contain configuration information; see Environment in the main description for Resolver class.
On Windows Systems, an attempt is made to determine the system defaults using the registry. This is still a work in progress; systems with many dynamically configured network interfaces may confuse Net::DNS.
You can include a configuration file of your own when creating a resolver object:
# Use my own configuration file
my $res = Net::DNS::Resolver->new(config_file => '/my/dns.conf');
This is supported on both UNIX and Windows. Values pulled from a custom configuration file override the the system’s defaults, but can still be overridden by the other arguments to Resolver::new.
Explicit arguments to Resolver::new override both the system’s defaults and the values of the custom configuration file, if any.
Parameters
The following arguments to Resolver::new are supported:
-
nameservers: an array reference of nameservers to query.
-
searchlist: an array reference of domains.
-
recurse
-
debug
-
domain
-
port
-
srcaddr
-
srcport
-
tcp_timeout
-
udp_timeout
-
retrans
-
retry
-
usevc
-
stayopen
-
igntc
-
defnames
-
dnsrch
-
persistent_tcp
-
persistent_udp
-
dnssec
For more information on any of these options, please consult the method of the same name.
Disclaimer
Part of the above documentation is taken from the one in the Net::DNS::Resolver Perl module.
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 |
# File 'lib/net/dns/resolver.rb', line 227 def initialize(config = {}) raise ResolverArgumentError, "Argument has to be Hash" unless config.kind_of? Hash # config.key_downcase! @config = Defaults.merge config @raw = false # New logger facility @logger = Logger.new(@config[:log_file]) @logger.level = $DEBUG ? Logger::DEBUG : Logger::WARN #------------------------------------------------------------ # Resolver configuration will be set in order from: # 1) initialize arguments # 2) ENV variables # 3) config file # 4) defaults (and /etc/resolv.conf for config) #------------------------------------------------------------ #------------------------------------------------------------ # Parsing config file #------------------------------------------------------------ parse_config_file #------------------------------------------------------------ # Parsing ENV variables #------------------------------------------------------------ parse_environment_variables #------------------------------------------------------------ # Parsing arguments #------------------------------------------------------------ config.each do |key,val| next if key == :log_file or key == :config_file begin eval "self.#{key.to_s} = val" rescue NoMethodError raise ResolverArgumentError, "Option #{key} not valid" end end end |
Class Method Details
.platform_windows? ⇒ Boolean
Returns true if running on a Windows platform.
Note. This method doesn’t rely on the RUBY_PLATFORM constant because the comparison will fail when running on JRuby. On JRuby RUBY_PLATFORM == ‘java’.
1236 1237 1238 |
# File 'lib/net/dns/resolver.rb', line 1236 def platform_windows? !!(Config::CONFIG["host_os"] =~ /msdos|mswin|djgpp|mingw/i) end |
Instance Method Details
#axfr(name, cls = Net::DNS::IN) ⇒ Object
Performs a zone transfer for the zone passed as a parameter.
It is actually only a wrapper to a send with type set as Net::DNS::AXFR, since it is using the same infrastucture.
1024 1025 1026 1027 |
# File 'lib/net/dns/resolver.rb', line 1024 def axfr(name,cls=Net::DNS::IN) @logger.info "Requested AXFR transfer, zone #{name} class #{cls}" send(name,Net::DNS::AXFR,cls) end |
#defname=(bool) ⇒ Object
Set the flag defname
in a boolean state. if defname
is true, calls to Resolver#query will append the default domain to names that contain no dots. Example:
# Domain example.com
res.defname = true
res.query("machine1")
#=> This will perform a query for machine1.example.com
Default is true.
626 627 628 629 630 631 632 633 634 |
# File 'lib/net/dns/resolver.rb', line 626 def defname=(bool) case bool when TrueClass,FalseClass @config[:defname] = bool @logger.info("Defname state changed to #{bool}") else raise ResolverArgumentError, "Argument must be boolean" end end |
#defname? ⇒ Boolean Also known as: defname
Checks whether the defname
flag has been activate.
609 610 611 |
# File 'lib/net/dns/resolver.rb', line 609 def defname? @config[:defname] end |
#dns_search ⇒ Object Also known as: dnsrch
Get the state of the dns_search flag
637 638 639 |
# File 'lib/net/dns/resolver.rb', line 637 def dns_search @config[:dns_search] end |
#dns_search=(bool) ⇒ Object Also known as: dnsrch=
Set the flag dns_search
in a boolean state. If dns_search
is true, when using the Resolver#search method will be applied the search list. Default is true.
646 647 648 649 650 651 652 653 654 |
# File 'lib/net/dns/resolver.rb', line 646 def dns_search=(bool) case bool when TrueClass,FalseClass @config[:dns_search] = bool @logger.info("DNS search state changed to #{bool}") else raise ResolverArgumentError, "Argument must be boolean" end end |
#domain ⇒ Object
Return a string with the default domain
372 373 374 |
# File 'lib/net/dns/resolver.rb', line 372 def domain @config[:domain].inspect end |
#domain=(name) ⇒ Object
Set the domain for the query
378 379 380 |
# File 'lib/net/dns/resolver.rb', line 378 def domain=(name) @config[:domain] = name if valid? name end |
#ignore_truncated=(bool) ⇒ Object
691 692 693 694 695 696 697 698 699 |
# File 'lib/net/dns/resolver.rb', line 691 def ignore_truncated=(bool) case bool when TrueClass,FalseClass @config[:ignore_truncated] = bool @logger.info("Ignore truncated flag changed to #{bool}") else raise ResolverArgumentError, "Argument must be boolean" end end |
#ignore_truncated? ⇒ Boolean Also known as: ignore_truncated
686 687 688 |
# File 'lib/net/dns/resolver.rb', line 686 def ignore_truncated? @config[:ignore_truncated] end |
#log_file=(log) ⇒ Object
Set a new log file for the logger facility of the resolver class. Could be a file descriptor too:
res.log_file = $stderr
Note that a new logging facility will be create, destroing the old one, which will then be impossibile to recover.
777 778 779 780 781 782 |
# File 'lib/net/dns/resolver.rb', line 777 def log_file=(log) @logger.close @config[:log_file] = log @logger = Logger.new(@config[:log_file]) @logger.level = $DEBUG ? Logger::DEBUG : Logger::WARN end |
#log_level=(level) ⇒ Object
Set the log level for the built-in logging facility.
The log level can be one of the following:
-
Net::DNS::DEBUG
-
Net::DNS::INFO
-
Net::DNS::WARN
-
Net::DNS::ERROR
-
Net::DNS::FATAL
Note that if the global variable $DEBUG is set (like when the -d switch is used at the command line) the logger level is automatically set at DEGUB.
For further informations, see Logger documentation in the Ruby standard library.
827 828 829 |
# File 'lib/net/dns/resolver.rb', line 827 def log_level=(level) @logger.level = level end |
#logger=(logger) ⇒ Object
This one permits to have a personal logger facility to handle resolver messages, instead of new built-in one, which is set up for a $stdout (or $stderr) use.
If you want your own logging facility you can create a new instance of the Logger
class:
log = Logger.new("/tmp/resolver.log","weekly",2*1024*1024)
log.level = Logger::DEBUG
log.progname = "ruby_resolver"
and then pass it to the resolver:
res.logger = log
Note that this will destroy the precedent logger.
801 802 803 804 805 806 807 808 |
# File 'lib/net/dns/resolver.rb', line 801 def logger=(logger) if logger.kind_of? Logger @logger.close @logger = logger else raise ResolverArgumentError, "Argument must be an instance of Logger class" end end |
#mx(name, cls = Net::DNS::IN) ⇒ Object
1041 1042 1043 1044 1045 1046 1047 |
# File 'lib/net/dns/resolver.rb', line 1041 def mx(name,cls=Net::DNS::IN) arr = [] send(name, Net::DNS::MX, cls).answer.each do |entry| arr << entry if entry.type == 'MX' end return arr.sort_by {|a| a.preference} end |
#nameservers ⇒ Object Also known as: nameserver
Get the list of resolver nameservers, in a dotted decimal format
res.nameservers
#=> ["192.168.0.1","192.168.0.2"]
311 312 313 314 315 316 317 |
# File 'lib/net/dns/resolver.rb', line 311 def nameservers arr = [] @config[:nameservers].each do |x| arr << x.to_s end arr end |
#nameservers=(arg) ⇒ Object Also known as: nameserver=
Set the list of resolver nameservers arg
can be a single ip address or an array of addresses
res.nameservers = "192.168.0.1"
res.nameservers = ["192.168.0.1","192.168.0.2"]
If you want you can specify the addresses as IPAddr instances
ip = IPAddr.new("192.168.0.3")
res.nameservers << ip
#=> ["192.168.0.1","192.168.0.2","192.168.0.3"]
The default is 127.0.0.1 (localhost)
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 |
# File 'lib/net/dns/resolver.rb', line 334 def nameservers=(arg) case arg when String begin @config[:nameservers] = [IPAddr.new(arg)] @logger.info "Nameservers list changed to value #{@config[:nameservers].inspect}" rescue ArgumentError # arg is in the name form, not IP nameservers_from_name(arg) end when IPAddr @config[:nameservers] = [arg] @logger.info "Nameservers list changed to value #{@config[:nameservers].inspect}" when Array @config[:nameservers] = [] arg.each do |x| @config[:nameservers] << case x when String begin IPAddr.new(x) rescue ArgumentError nameservers_from_name(arg) return end when IPAddr x else raise ResolverArgumentError, "Wrong argument format" end end @logger.info "Nameservers list changed to value #{@config[:nameservers].inspect}" else raise ResolverArgumentError, "Wrong argument format, neither String, Array nor IPAddr" end end |
#packet_size ⇒ Object
Return the defined size of the packet
384 385 386 |
# File 'lib/net/dns/resolver.rb', line 384 def packet_size @config[:packet_size] end |
#port ⇒ Object
Get the port number to which the resolver sends queries.
puts "Sending queries to port #{res.port}"
392 393 394 |
# File 'lib/net/dns/resolver.rb', line 392 def port @config[:port] end |
#port=(num) ⇒ Object
Set the port number to which the resolver sends queries. This can be useful for testing a nameserver running on a non-standard port.
res.port = 10053
The default is port 53.
403 404 405 406 407 408 409 410 |
# File 'lib/net/dns/resolver.rb', line 403 def port=(num) if (0..65535).include? num @config[:port] = num @logger.info "Port number changed to #{num}" else raise ResolverArgumentError, "Wrong port number #{num}" end end |
#query(name, type = Net::DNS::A, cls = Net::DNS::IN) ⇒ Object
Performs a DNS query for the given name; the search list is not applied. If the name doesn’t contain any dots and defname
is true then the default domain will be appended.
The record type and class can be omitted; they default to A
and IN
. If the name looks like an IP address (IPv4 or IPv6), then an appropriate PTR query will be performed.
packet = res.query('mailhost')
packet = res.query('mailhost.example.com')
packet = res.query('example.com', Net::DNS::MX)
packet = res.query('user.passwd.example.com', Net::DNS::TXT, Net::DNS::HS)
If the name is an IP address (Ipv4 or IPv6), in the form of a string or a IPAddr
object, then an appropriate PTR query will be performed:
ip = IPAddr.new("172.16.100.2")
packet = res.query(ip)
packet = res.query("192.168.10.254")
Returns a Net::DNS::Packet object. If you need to examine the response packet whether it contains any answers or not, use the Resolver#send method instead.
905 906 907 908 909 910 911 912 913 914 915 916 |
# File 'lib/net/dns/resolver.rb', line 905 def query(name,type=Net::DNS::A,cls=Net::DNS::IN) # If the name doesn't contain any dots then append the default domain. if name !~ /\./ and name !~ /:/ and @config[:defnames] name += "." + @config[:domain] end @logger.debug "Query(#{name},#{Net::DNS::RR::Types.new(type)},#{Net::DNS::RR::Classes.new(cls)})" send(name,type,cls) end |
#recursive=(bool) ⇒ Object Also known as: recurse=
Sets whether or not the resolver should perform recursive queries. Default is true.
res.recursive = false # perform non-recursive query
574 575 576 577 578 579 580 581 582 |
# File 'lib/net/dns/resolver.rb', line 574 def recursive=(bool) case bool when TrueClass,FalseClass @config[:recursive] = bool @logger.info("Recursive state changed to #{bool}") else raise ResolverArgumentError, "Argument must be boolean" end end |
#recursive? ⇒ Boolean Also known as: recurse, recursive
This method will return true if the resolver is configured to perform recursive queries.
print "The resolver will perform a "
print res.recursive? ? "" : "not "
puts "recursive query"
563 564 565 |
# File 'lib/net/dns/resolver.rb', line 563 def recursive? @config[:recursive] end |
#retry_interval ⇒ Object Also known as: retrans
Return the retrasmission interval (in seconds) the resolvers has been set on
518 519 520 |
# File 'lib/net/dns/resolver.rb', line 518 def retry_interval @config[:retry_interval] end |
#retry_interval=(num) ⇒ Object Also known as: retrans=
Set the retrasmission interval in seconds. Default 5 seconds
525 526 527 528 529 530 531 532 |
# File 'lib/net/dns/resolver.rb', line 525 def retry_interval=(num) if num > 0 @config[:retry_interval] = num @logger.info "Retransmission interval changed to #{num} seconds" else raise ResolverArgumentError, "Interval must be positive" end end |
#retry_number ⇒ Object
The number of times the resolver will try a query
puts "Will try a max of #{res.retry_number} queries"
539 540 541 |
# File 'lib/net/dns/resolver.rb', line 539 def retry_number @config[:retry_number] end |
#retry_number=(num) ⇒ Object Also known as: retry=
Set the number of times the resolver will try a query. Default 4 times
546 547 548 549 550 551 552 553 |
# File 'lib/net/dns/resolver.rb', line 546 def retry_number=(num) if num.kind_of? Integer and num > 0 @config[:retry_number] = num @logger.info "Retrasmissions number changed to #{num}" else raise ResolverArgumentError, "Retry value must be a positive integer" end end |
#search(name, type = Net::DNS::A, cls = Net::DNS::IN) ⇒ Object
Performs a DNS query for the given name, applying the searchlist if appropriate. The search algorithm is as follows:
-
If the name contains at least one dot, try it as is.
-
If the name doesn’t end in a dot then append each item in the search list to the name. This is only done if
dns_search
is true. -
If the name doesn’t contain any dots, try it as is.
The record type and class can be omitted; they default to A
and IN
.
packet = res.search('mailhost')
packet = res.search('mailhost.example.com')
packet = res.search('example.com', Net::DNS::MX)
packet = res.search('user.passwd.example.com', Net::DNS::TXT, Net::DNS::HS)
If the name is an IP address (Ipv4 or IPv6), in the form of a string or a IPAddr
object, then an appropriate PTR query will be performed:
ip = IPAddr.new("172.16.100.2")
packet = res.search(ip)
packet = res.search("192.168.10.254")
Returns a Net::DNS::Packet object. If you need to examine the response packet whether it contains any answers or not, use the send() method instead.
856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 |
# File 'lib/net/dns/resolver.rb', line 856 def search(name,type=Net::DNS::A,cls=Net::DNS::IN) # If the name contains at least one dot then try it as is first. if name.include? "." @logger.debug "Search(#{name},#{Net::DNS::RR::Types.new(type)},#{Net::DNS::RR::Classes.new(cls)})" ans = query(name,type,cls) return ans if ans.header.anCount > 0 end # If the name doesn't end in a dot then apply the search list. if name !~ /\.$/ and @config[:dns_search] @config[:searchlist].each do |domain| newname = name + "." + domain @logger.debug "Search(#{newname},#{Net::DNS::RR::Types.new(type)},#{Net::DNS::RR::Classes.new(cls)})" ans = query(newname,type,cls) return ans if ans.header.anCount > 0 end end # Finally, if the name has no dots then try it as is. @logger.debug "Search(#{name},#{Net::DNS::RR::Types.new(type)},#{Net::DNS::RR::Classes.new(cls)})" query(name+".",type,cls) end |
#searchlist ⇒ Object
Get the resolver searchlist, returned as an array of entries
res.searchlist
#=> ["example.com","a.example.com","b.example.com"]
275 276 277 |
# File 'lib/net/dns/resolver.rb', line 275 def searchlist @config[:searchlist].inspect end |
#searchlist=(arg) ⇒ Object
Set the resolver searchlist. arg
can be a single string or an array of strings
res.searchstring = "example.com"
res.searchstring = ["example.com","a.example.com","b.example.com"]
Note that you can also append a new name to the searchlist
res.searchlist << "c.example.com"
res.searchlist
#=> ["example.com","a.example.com","b.example.com","c.example.com"]
The default is an empty array
293 294 295 296 297 298 299 300 301 302 303 304 |
# File 'lib/net/dns/resolver.rb', line 293 def searchlist=(arg) case arg when String @config[:searchlist] = [arg] if valid? arg @logger.info "Searchlist changed to value #{@config[:searchlist].inspect}" when Array @config[:searchlist] = arg if arg.all? {|x| valid? x} @logger.info "Searchlist changed to value #{@config[:searchlist].inspect}" else raise ResolverArgumentError, "Wrong argument format, neither String nor Array" end end |
#send(argument, type = Net::DNS::A, cls = Net::DNS::IN) ⇒ Object
Performs a DNS query for the given name. Neither the searchlist nor the default domain will be appended.
The argument list can be either a Net::DNS::Packet object or a name string plus optional type and class, which if omitted default to A
and IN
.
Returns a Net::DNS::Packet object.
# Sending a +Packet+ object
send_packet = Net::DNS::Packet.new("host.example.com",Net::DNS::NS,Net::DNS::HS)
packet = res.send(send_packet)
# Performing a query
packet = res.send("host.example.com")
packet = res.send("host.example.com",Net::DNS::NS)
packet = res.send("host.example.com",Net::DNS::NS,Net::DNS::HS)
If the name is an IP address (Ipv4 or IPv6), in the form of a string or a IPAddr object, then an appropriate PTR query will be performed:
ip = IPAddr.new("172.16.100.2")
packet = res.send(ip)
packet = res.send("192.168.10.254")
Use packet.header.ancount
or packet.answer
to find out if there were any records in the answer section.
946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 |
# File 'lib/net/dns/resolver.rb', line 946 def send(argument,type=Net::DNS::A,cls=Net::DNS::IN) if @config[:nameservers].size == 0 raise ResolverError, "No nameservers specified!" end method = :send_udp if argument.kind_of? Net::DNS::Packet packet = argument else packet = make_query_packet(argument,type,cls) end # Store packet_data for performance improvements, # so methods don't keep on calling Packet#data packet_data = packet.data packet_size = packet_data.size # Choose whether use TCP, UDP or RAW if packet_size > @config[:packet_size] # Must use TCP, either plain or raw if @raw # Use raw sockets? @logger.info "Sending #{packet_size} bytes using TCP over RAW socket" method = :send_raw_tcp else @logger.info "Sending #{packet_size} bytes using TCP" method = :send_tcp end else # Packet size is inside the boundaries if @raw # Use raw sockets? @logger.info "Sending #{packet_size} bytes using UDP over RAW socket" method = :send_raw_udp elsif use_tcp? # User requested TCP @logger.info "Sending #{packet_size} bytes using TCP" method = :send_tcp else # Finally use UDP @logger.info "Sending #{packet_size} bytes using UDP" end end if type == Net::DNS::AXFR if @raw @logger.warn "AXFR query, switching to TCP over RAW socket" method = :send_raw_tcp else @logger.warn "AXFR query, switching to TCP" method = :send_tcp end end ans = self.old_send(method,packet,packet_data) unless ans @logger.fatal "No response from nameservers list: aborting" raise NoResponseError end @logger.info "Received #{ans[0].size} bytes from #{ans[1][2]+":"+ans[1][1].to_s}" response = Net::DNS::Packet.parse(ans[0],ans[1]) if response.header.truncated? and not ignore_truncated? @logger.warn "Packet truncated, retrying using TCP" self.use_tcp = true begin return send(argument,type,cls) ensure self.use_tcp = false end end return response end |
#source_address ⇒ Object Also known as: srcaddr
Get the local address from which the resolver sends queries
puts "Sending queries using source address #{res.source_address}"
448 449 450 |
# File 'lib/net/dns/resolver.rb', line 448 def source_address @config[:source_address].to_s end |
#source_address=(addr) ⇒ Object Also known as: srcaddr=
Set the local source address from which the resolver sends its queries.
res.source_address = "172.16.100.1"
res.source_address = IPAddr.new("172.16.100.1")
You can specify arg
as either a string containing the ip address or an instance of IPAddr class.
Normally this can be used to force queries out a specific interface on a multi-homed host. In this case, you should of course need to know the addresses of the interfaces.
Another way to use this option is for some kind of spoofing attacks towards weak nameservers, to probe the security of your network. This includes specifing ranged attacks such as DoS and others. For a paper on DNS security, checks www.marcoceresa.com/security/
Note that if you want to set a non-binded source address you need root priviledges, as raw sockets will be used to generate packets. The class will then generate an exception if you’re not root.
The default is 0.0.0.0, meaning any local address (chosen on routing needs).
478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 |
# File 'lib/net/dns/resolver.rb', line 478 def source_address=(addr) unless addr.respond_to? :to_s raise ResolverArgumentError, "Wrong address argument #{addr}" end begin port = rand(64000)+1024 @logger.warn "Try to determine state of source address #{addr} with port #{port}" a = TCPServer.new(addr.to_s,port) rescue SystemCallError => e case e.errno when 98 # Port already in use! @logger.warn "Port already in use" retry when 99 # Address is not valid: raw socket @raw = true @logger.warn "Using raw sockets" else raise SystemCallError, e end ensure a.close end case addr when String @config[:source_address] = IPAddr.new(string) @logger.info "Using new source address: #{@config[:source_address]}" when IPAddr @config[:source_address] = addr @logger.info "Using new source address: #{@config[:source_address]}" else raise ArgumentError, "Unknown dest_address format" end end |
#source_port ⇒ Object Also known as: srcport
Get the value of the source port number
puts "Sending queries using port #{res.source_port}"
416 417 418 |
# File 'lib/net/dns/resolver.rb', line 416 def source_port @config[:source_port] end |
#source_port=(num) ⇒ Object Also known as: srcport=
Set the local source port from which the resolver sends its queries.
res.source_port = 40000
Note that if you want to set a port you need root priviledges, as raw sockets will be used to generate packets. The class will then generate the exception ResolverPermissionError if you’re not root.
The default is 0, which means that the port will be chosen by the underlaying layers.
432 433 434 435 436 437 438 439 440 441 |
# File 'lib/net/dns/resolver.rb', line 432 def source_port=(num) unless root? raise ResolverPermissionError, "Are you root?" end if (0..65535).include?(num) @config[:source_port] = num else raise ResolverArgumentError, "Wrong port number #{num}" end end |
#state ⇒ Object Also known as: print, inspect
Return a string rapresenting the resolver state, suitable for printing on the screen.
puts "Resolver state:"
puts res.state
591 592 593 594 595 596 597 598 599 600 601 602 603 604 |
# File 'lib/net/dns/resolver.rb', line 591 def state str = ";; RESOLVER state:\n;; " i = 1 @config.each do |key,val| if key == :log_file or key == :config_file str << "#{key}: #{val} \t" else str << "#{key}: #{eval(key.to_s)} \t" end str << "\n;; " if i % 2 == 0 i += 1 end str end |
#tcp_timeout ⇒ Object
Return an object representing the value of the stored TCP timeout the resolver will use in is queries. This object is an instance of the class TcpTimeout
, and two methods are available for printing informations: TcpTimeout#to_s and TcpTimeout#pretty_to_s.
Here’s some example:
puts "Timeout of #{res.tcp_timeout} seconds" # implicit to_s
#=> Timeout of 150 seconds
puts "You set a timeout of " + res.tcp_timeout.pretty_to_s
#=> You set a timeout of 2 minutes and 30 seconds
If the timeout is infinite, a string “infinite” will be returned.
718 719 720 |
# File 'lib/net/dns/resolver.rb', line 718 def tcp_timeout @config[:tcp_timeout].to_s end |
#tcp_timeout=(secs) ⇒ Object
Set the value of TCP timeout for resolver queries that will be performed using TCP. A value of 0 means that the timeout will be infinite. The value is stored internally as a TcpTimeout
object, see the description for Resolver#tcp_timeout
Default is 120 seconds
729 730 731 732 |
# File 'lib/net/dns/resolver.rb', line 729 def tcp_timeout=(secs) @config[:tcp_timeout] = TcpTimeout.new(secs) @logger.info("New TCP timeout value: #{@config[:tcp_timeout]} seconds") end |
#udp_timeout ⇒ Object
Return an object representing the value of the stored UDP timeout the resolver will use in is queries. This object is an instance of the class UdpTimeout
, and two methods are available for printing informations: UdpTimeout#to_s and UdpTimeout#pretty_to_s.
Here’s some example:
puts "Timeout of #{res.udp_timeout} seconds" # implicit to_s
#=> Timeout of 150 seconds
puts "You set a timeout of " + res.udp_timeout.pretty_to_s
#=> You set a timeout of 2 minutes and 30 seconds
If the timeout is zero, a string “not defined” will be returned.
751 752 753 |
# File 'lib/net/dns/resolver.rb', line 751 def udp_timeout @config[:udp_timeout].to_s end |
#udp_timeout=(secs) ⇒ Object
Set the value of UDP timeout for resolver queries that will be performed using UDP. A value of 0 means that the timeout will not be used, and the resolver will use only retry_number
and retry_interval
parameters. That is the default.
The value is stored internally as a UdpTimeout
object, see the description for Resolver#udp_timeout
764 765 766 767 |
# File 'lib/net/dns/resolver.rb', line 764 def udp_timeout=(secs) @config[:udp_timeout] = UdpTimeout.new(secs) @logger.info("New UDP timeout value: #{@config[:udp_timeout]} seconds") end |
#use_tcp=(bool) ⇒ Object Also known as: usevc=
If use_tcp
is true, the resolver will perform all queries using TCP virtual circuits instead of UDP datagrams, which is the default for the DNS protocol.
res.use_tcp = true
res.query "host.example.com"
#=> Sending TCP segments...
Default is false.
675 676 677 678 679 680 681 682 683 |
# File 'lib/net/dns/resolver.rb', line 675 def use_tcp=(bool) case bool when TrueClass,FalseClass @config[:use_tcp] = bool @logger.info("Use tcp flag changed to #{bool}") else raise ResolverArgumentError, "Argument must be boolean" end end |
#use_tcp? ⇒ Boolean Also known as: usevc, use_tcp
Get the state of the use_tcp flag.
659 660 661 |
# File 'lib/net/dns/resolver.rb', line 659 def use_tcp? @config[:use_tcp] end |