From 2b17cac0c588243cdd3d32839c480d3fc600dfb6 Mon Sep 17 00:00:00 2001 From: twoism Date: Thu, 13 Oct 2011 14:54:42 -0700 Subject: [PATCH] init --- .specification | 112 ++ AUTHORS | 10 + CHANGELOG | 7 + INSTALL | 8 + README | 55 + Rakefile | 83 ++ THANKS | 24 + demo/check_soa.rb | 120 +++ demo/threads.rb | 21 + gemspec | 15 + lib/net/dns/dns.rb | 117 ++ lib/net/dns/header.rb | 761 +++++++++++++ lib/net/dns/names/names.rb | 109 ++ lib/net/dns/packet.rb | 570 ++++++++++ lib/net/dns/question.rb | 195 ++++ lib/net/dns/resolver.rb | 1232 +++++++++++++++++++++ lib/net/dns/resolver/socks.rb | 154 +++ lib/net/dns/resolver/timeouts.rb | 73 ++ lib/net/dns/rr.rb | 406 +++++++ lib/net/dns/rr/a.rb | 121 +++ lib/net/dns/rr/aaaa.rb | 92 ++ lib/net/dns/rr/classes.rb | 148 +++ lib/net/dns/rr/cname.rb | 69 ++ lib/net/dns/rr/hinfo.rb | 74 ++ lib/net/dns/rr/mr.rb | 68 ++ lib/net/dns/rr/mx.rb | 74 ++ lib/net/dns/rr/ns.rb | 70 ++ lib/net/dns/rr/null.rb | 61 ++ lib/net/dns/rr/ptr.rb | 71 ++ lib/net/dns/rr/soa.rb | 85 ++ lib/net/dns/rr/srv.rb | 57 + lib/net/dns/rr/txt.rb | 72 ++ lib/net/dns/rr/types.rb | 200 ++++ setup.rb | 1360 ++++++++++++++++++++++++ test/net/dns/resolver/test_timeouts.rb | 59 + test/net/dns/rr/test_a.rb | 72 ++ test/net/dns/rr/test_classes.rb | 73 ++ test/net/dns/rr/test_ns.rb | 66 ++ test/net/dns/rr/test_types.rb | 127 +++ test/net/dns/test_header.rb | 170 +++ test/net/dns/test_packet.rb | 42 + test/net/dns/test_question.rb | 54 + test/net/dns/test_rr.rb | 133 +++ 43 files changed, 7490 insertions(+) create mode 100644 .specification create mode 100644 AUTHORS create mode 100644 CHANGELOG create mode 100644 INSTALL create mode 100644 README create mode 100644 Rakefile create mode 100644 THANKS create mode 100644 demo/check_soa.rb create mode 100644 demo/threads.rb create mode 100644 gemspec create mode 100644 lib/net/dns/dns.rb create mode 100644 lib/net/dns/header.rb create mode 100644 lib/net/dns/names/names.rb create mode 100644 lib/net/dns/packet.rb create mode 100644 lib/net/dns/question.rb create mode 100644 lib/net/dns/resolver.rb create mode 100644 lib/net/dns/resolver/socks.rb create mode 100644 lib/net/dns/resolver/timeouts.rb create mode 100644 lib/net/dns/rr.rb create mode 100644 lib/net/dns/rr/a.rb create mode 100644 lib/net/dns/rr/aaaa.rb create mode 100644 lib/net/dns/rr/classes.rb create mode 100644 lib/net/dns/rr/cname.rb create mode 100644 lib/net/dns/rr/hinfo.rb create mode 100644 lib/net/dns/rr/mr.rb create mode 100644 lib/net/dns/rr/mx.rb create mode 100644 lib/net/dns/rr/ns.rb create mode 100644 lib/net/dns/rr/null.rb create mode 100644 lib/net/dns/rr/ptr.rb create mode 100644 lib/net/dns/rr/soa.rb create mode 100644 lib/net/dns/rr/srv.rb create mode 100644 lib/net/dns/rr/txt.rb create mode 100644 lib/net/dns/rr/types.rb create mode 100644 setup.rb create mode 100644 test/net/dns/resolver/test_timeouts.rb create mode 100644 test/net/dns/rr/test_a.rb create mode 100644 test/net/dns/rr/test_classes.rb create mode 100644 test/net/dns/rr/test_ns.rb create mode 100644 test/net/dns/rr/test_types.rb create mode 100644 test/net/dns/test_header.rb create mode 100644 test/net/dns/test_packet.rb create mode 100644 test/net/dns/test_question.rb create mode 100644 test/net/dns/test_rr.rb diff --git a/.specification b/.specification new file mode 100644 index 0000000..23ecc83 --- /dev/null +++ b/.specification @@ -0,0 +1,112 @@ +--- !ruby/object:Gem::Specification +name: net-dns +version: !ruby/object:Gem::Version + version: "0.4" +platform: ruby +authors: +- Marco Ceresa +autorequire: +bindir: bin +cert_chain: +date: 2007-05-12 00:00:00 -07:00 +default_executable: +dependencies: [] + +description: A pure Ruby DNS library, similar to the Perl Net::DNS library +email: ceresa@gmail.com +executables: [] + +extensions: [] + +extra_rdoc_files: +- README +- AUTHORS +- INSTALL +- THANKS +files: +- demo +- demo/check_soa.rb +- demo/threads.rb +- README +- setup.rb +- CHANGELOG +- gemspec +- Rakefile +- AUTHORS +- lib +- lib/net +- lib/net/dns +- lib/net/dns/names +- lib/net/dns/names/names.rb +- lib/net/dns/resolver +- lib/net/dns/resolver/timeouts.rb +- lib/net/dns/resolver/socks.rb +- lib/net/dns/resolver.rb +- lib/net/dns/dns.rb +- lib/net/dns/rr.rb +- lib/net/dns/question.rb +- lib/net/dns/header.rb +- lib/net/dns/packet.rb +- lib/net/dns/rr +- lib/net/dns/rr/null.rb +- lib/net/dns/rr/types.rb +- lib/net/dns/rr/hinfo.rb +- lib/net/dns/rr/mr.rb +- lib/net/dns/rr/soa.rb +- lib/net/dns/rr/mx.rb +- lib/net/dns/rr/txt.rb +- lib/net/dns/rr/cname.rb +- lib/net/dns/rr/a.rb +- lib/net/dns/rr/aaaa.rb +- lib/net/dns/rr/ns.rb +- lib/net/dns/rr/classes.rb +- lib/net/dns/rr/ptr.rb +- lib/net/dns/rr/srv.rb +- test +- test/net +- test/net/dns +- test/net/dns/test_packet.rb +- test/net/dns/test_rr.rb +- test/net/dns/resolver +- test/net/dns/resolver/test_timeouts.rb +- test/net/dns/test_header.rb +- test/net/dns/test_question.rb +- test/net/dns/rr +- test/net/dns/rr/test_types.rb +- test/net/dns/rr/test_ns.rb +- test/net/dns/rr/test_a.rb +- test/net/dns/rr/test_classes.rb +- THANKS +- INSTALL +has_rdoc: true +homepage: http://net-dns.rubyforge.org/ +licenses: [] + +post_install_message: +rdoc_options: [] + +require_paths: +- bin +- bin +- lib +required_ruby_version: !ruby/object:Gem::Requirement + requirements: + - - ">" + - !ruby/object:Gem::Version + version: 0.0.0 + version: +required_rubygems_version: !ruby/object:Gem::Requirement + requirements: + - - ">=" + - !ruby/object:Gem::Version + version: "0" + version: +requirements: [] + +rubyforge_project: +rubygems_version: 1.3.5 +signing_key: +specification_version: 1 +summary: Pure Ruby DNS library +test_files: [] + diff --git a/AUTHORS b/AUTHORS new file mode 100644 index 0000000..838cba4 --- /dev/null +++ b/AUTHORS @@ -0,0 +1,10 @@ +# $Id: AUTHORS,v 1.2 2005/06/17 10:09:57 bluemonk Exp $ + + +AUTHORS + +Net::DNS core developement: + Marco Ceresa + +Beta testing: + diff --git a/CHANGELOG b/CHANGELOG new file mode 100644 index 0000000..4c4760e --- /dev/null +++ b/CHANGELOG @@ -0,0 +1,7 @@ +net-dns 0.4 + - many bug fixes (thanks guys!) + - a whole new class Net::DNS::Header::RCode + - new methods in Net::DNS::Resolver class to + do AXFR queries + - a new SRV resource record written by Dan Janowski + - more documentation written and corrected diff --git a/INSTALL b/INSTALL new file mode 100644 index 0000000..0d85fc9 --- /dev/null +++ b/INSTALL @@ -0,0 +1,8 @@ +If you didn't install this from gem, you can do a + +# ruby setup.rb + +or, from normal user (with sudo) + +$ rake install + diff --git a/README b/README new file mode 100644 index 0000000..c3782a5 --- /dev/null +++ b/README @@ -0,0 +1,55 @@ +Net::DNS README +============ + + This is a port of the Perl Net::DNS module, written by Michael Fuhr +and now currently maintained by Olaf Kolkman (www.net-dns.org). It +keeps the same interfaces and function names, although has a bit +improved OO and some other stuff. +It can be used to query DNS servers for various kind of records, perform +zone transfer and dynamic updates. It has even a class for acting as a +nameserver. +This version is quite incomplete. You can use it as a resolver. + + +Requirements +------------ + + * Ruby 1.6 + + +Install +------- + + De-compress archive and enter its top directory. + Then type: + + ($ su) + # ruby setup.rb + + These simple step installs this program under the default + location of Ruby libraries. You can also install files into + your favorite directory by supplying setup.rb some options. + Try "ruby setup.rb --help". + + +Usage +----- + + Have a look on the manual pages. + In doc/ you will find many useful documents too. + + +License +------- + + Net::DNS is distributed under the same license Ruby is. + + +Author +------ + + See AUTHORS + + +# $Id: README,v 1.2 2005/06/17 15:11:18 bluemonk Exp $ + diff --git a/Rakefile b/Rakefile new file mode 100644 index 0000000..d27c6d1 --- /dev/null +++ b/Rakefile @@ -0,0 +1,83 @@ +require 'rake/clean' +require 'rake/testtask' +require 'rake/rdoctask' +require 'rake/contrib/rubyforgepublisher' +require 'rake/gempackagetask' + +require 'rubygems' + +$VERSION = "0.4" + +task :package => [:version, :clean] + +desc "Library version" +task :version do + file = "lib/net/dns/dns.rb" + str = IO.readlines(file).to_s + offset = (str =~ /VERSION = "(.*)"/) + unless $1 == $VERSION + str.gsub!($1,$VERSION) + File.open(file,"w") do |out| + out << str + end + end +end + + +desc "Run the tests" +Rake::TestTask.new do |t| + t.libs << "test" + t.test_files = FileList['test/net/dns/**/test*.rb'] + t.verbose = true +end + +desc "Install the library" +task :install do + sh("sudo ruby setup.rb") +end + +desc "Build documentation" +Rake::RDocTask.new do |rd| + rd.rdoc_files.include("lib/net/dns/**/*.rb") + rd.options << "-S" +end + +# +# Gem specifications +# +SPEC = Gem::Specification.new do |s| + s.name = "net-dns" + s.version = "#$VERSION" + s.author = "Marco Ceresa" + s.email = "ceresa@gmail.com" + s.homepage = "http://net-dns.rubyforge.org/" + s.platform = Gem::Platform::RUBY + s.summary = "Pure Ruby DNS library" + candidates = Dir.glob("**/*") + s.files = candidates.delete_if do |item| + item.include?("CVS") || item.include?("rdoc") || item.include?("pkg") || item.include?(".svn") + end + s.has_rdoc = true + s.extra_rdoc_files = ["README","AUTHORS","INSTALL", "THANKS"] + s.description = < false, :retry => 2) + +#res.defname=false +#res.retry=2 + + +ns_req = res.query(domain, Net::DNS::NS); +raise ArgumentError, "No nameservers found for domain: " + res.errorstring + + "\n" unless ns_req and ns_req.header.anCount > 0 + + +# Send out non-recursive queries +res.recurse=false +# Do not buffer standard out +#| = 1; + + +#------------------------------------------------------------------------------ +# Check the SOA record on each nameserver. +#------------------------------------------------------------------------------ + +ns_req.each_nameserver do |ns| + + #---------------------------------------------------------------------- + # Set the resolver to query this nameserver. + #---------------------------------------------------------------------- + + # In order to lookup the IP(s) of the nameserver, we need a Resolver + # object that is set to our local, recursive nameserver. So we create + # a new object just to do that. + + local_res = Net::DNS::Resolver.new + + a_req = local_res.query(ns, Net::DNS::A) + + + unless a_req + puts "Can not find address for ns: " + res.errorstring + "\n" + next + end + + + a_req.each_address do |ip| + + #---------------------------------------------------------------------- + # Ask this IP. + #---------------------------------------------------------------------- + res.nameservers=ip + + print "#{ns} (#{ip}): " + + #---------------------------------------------------------------------- + # Get the SOA record. + #---------------------------------------------------------------------- + + soa_req = res.send(domain, Net::DNS::SOA, Net::DNS::IN) + + if soa_req == nil + puts res.errorstring, "\n" + next + end + + #---------------------------------------------------------------------- + # Is this nameserver authoritative for the domain? + #---------------------------------------------------------------------- + + unless soa_req.header.auth? + print "isn't authoritative for domain\n" + next + end + + #---------------------------------------------------------------------- + # We should have received exactly one answer. + #---------------------------------------------------------------------- + + unless soa_req.header.anCount == 1 + print "expected 1 answer, got " + soa_req.header.anCount.to_s + "\n" + next + end + + #---------------------------------------------------------------------- + # Did we receive an SOA record? + #---------------------------------------------------------------------- + + unless soa_req.answer[0].class == Net::DNS::RR::SOA + print "expected SOA, got " + Net::DNS::RR::RRTypes.to_str(soa_req.answer[0].type) + "\n" + next + end + + #---------------------------------------------------------------------- + # Print the serial number. + #---------------------------------------------------------------------- + + print "has serial number " + soa_req.answer[0].serial.to_s + "\n" + + end +end + + + diff --git a/demo/threads.rb b/demo/threads.rb new file mode 100644 index 0000000..3c3b7b4 --- /dev/null +++ b/demo/threads.rb @@ -0,0 +1,21 @@ +require 'net/dns/resolver' + +a = ["ibm.com", "sun.com", "redhat.com"] + +threads = [] + +for dom in a + threads << Thread.new(dom) do |domain| + res = Net::DNS::Resolver.new + res.query(domain, Net::DNS::NS).each_nameserver do |ns| + puts "Domain #{domain} has nameserver #{ns}" + end + puts "" + end +end + +threads.each do |t| + t.join +end + + diff --git a/gemspec b/gemspec new file mode 100644 index 0000000..8c8e7c5 --- /dev/null +++ b/gemspec @@ -0,0 +1,15 @@ +require 'rubygems' +SPEC = Gem::Specification.new do |s| + s.name = "net-dns" + s.version = "0.1" + s.author = "Marco Ceresa" + s.email = "ceresa@gmail.com" + s.homepage = "http://net-dns.rubyforge.org/" + s.platform = Gem::Platform::RUBY + s.summary = "Pure Ruby DNS library" + candidates = Dir.glob("{bin,demo,docs,lib,tests}/**/*") + s.files = candidates.delete_if do |item| + item.include?("CVS") || item.include?("rdoc") || item.include?(".svn") + end + s.has_rdoc = true + s.extra_rdoc_files = ["README","AUTHORS","INSTALL", "THANKS"] diff --git a/lib/net/dns/dns.rb b/lib/net/dns/dns.rb new file mode 100644 index 0000000..1214ea5 --- /dev/null +++ b/lib/net/dns/dns.rb @@ -0,0 +1,117 @@ +## +# +# dns.rb +# +# $id$ +# +## + +module Net # :nodoc: + module DNS + + # Version of the library + VERSION = "0.4" + + # Packet size in bytes + PACKETSZ = 512 + + # Size of the header + HFIXEDSZ = 12 + + # Size of the question portion (type and class) + QFIXEDSZ = 4 + + # Size of an RR portion (type,class,lenght and ttl) + RRFIXEDSZ = 10 + + # Size of an int 32 bit + INT32SZ = 4 + + # Size of a short int + INT16SZ = 2 + + module QueryTypes + + SIGZERO = 0 + A = 1 + NS = 2 + MD = 3 + MF = 4 + CNAME = 5 + SOA = 6 + MB = 7 + MG = 8 + MR = 9 + NULL = 10 + WKS = 11 + PTR = 12 + HINFO = 13 + MINFO = 14 + MX = 15 + TXT = 16 + RP = 17 + AFSDB = 18 + X25 = 19 + ISDN = 20 + RT = 21 + NSAP = 22 + NSAPPTR = 23 + SIG = 24 + KEY = 25 + PX = 26 + GPOS = 27 + AAAA = 28 + LOC = 29 + NXT = 30 + EID = 31 + NIMLOC = 32 + SRV = 33 + ATMA = 34 + NAPTR = 35 + KX = 36 + CERT = 37 + DNAME = 39 + OPT = 41 + DS = 43 + SSHFP = 44 + RRSIG = 46 + NSEC = 47 + DNSKEY = 48 + UINFO = 100 + UID = 101 + GID = 102 + UNSPEC = 103 + TKEY = 249 + TSIG = 250 + IXFR = 251 + AXFR = 252 + MAILB = 253 + MAILA = 254 + ANY = 255 + + end + + module QueryClasses + + # Internet class + IN = 1 + + # Chaos class + CH = 3 + + # Hesiod class + HS = 4 + + # None class + NONE = 254 + + # Any class + ANY = 255 + + end + + include QueryTypes + include QueryClasses + + end # module DNS +end # module Net diff --git a/lib/net/dns/header.rb b/lib/net/dns/header.rb new file mode 100644 index 0000000..e5ffcc6 --- /dev/null +++ b/lib/net/dns/header.rb @@ -0,0 +1,761 @@ +#--- +# $Id: Header.rb,v 1.5 2006/07/30 16:54:28 bluemonk Exp $ +#+++ + +require 'net/dns/dns' + +module Net # :nodoc: + module DNS + + # + # =Name + # + # Net::DNS::Header - DNS packet header class + # + # =Synopsis + # + # require 'net/dns/header' + # + # =Description + # + # The Net::DNS::Header class represents the header portion of a + # DNS packet. An Header object is created whenever a new packet + # is parsed or as user request. + # + # header = Net::DNS::Header.new + # # ;; id = 18123 + # # ;; qr = 0 opCode: 0 aa = 0 tc = 0 rd = 1 + # # ;; ra = 0 ad = 0 cd = 0 rcode = 0 + # # ;; qdCount = 1 anCount = 0 nsCount = 0 arCount = 0 + # + # header.format + # # +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + # # | 18123 | + # # +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + # # |0| 0 |0|0|1|0|0| 0 | 0 | + # # +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + # # | 1 | + # # +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + # # | 0 | + # # +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + # # | 0 | + # # +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + # # | 0 | + # # +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + # + # # packet is an instance of Net::DNS::Packet + # header = packet.header + # puts "Answer is #{header.auth? ? '' : 'non'} authoritative" + # + # A lot of methods were written to keep a compatibility layer with + # the Perl version of the library, as long as methods name which are + # more or less the same. + # + # =Error classes + # + # Some error classes has been defined for the Net::DNS::Header class, + # which are listed here to keep a light and browsable main documentation. + # We have: + # + # * HeaderArgumentError: canonical argument error + # * HeaderWrongCount: a wrong +count+ parameter has been passed + # * HeaderWrongRecursive: a wrong +recursive+ parameter has been passed + # * HeaderWrongOpcode: a not valid +opCode+ has been specified + # * HeaderDuplicateID: the requested ID is already in use + # + # =Copyright + # + # Copyright (c) 2006 Marco Ceresa + # + # All rights reserved. This program is free software; you may redistribute + # it and/or modify it under the same terms as Ruby itself. + # + class Header + + # + # =Name + # + # Net::DNS::Header::RCode - DNS Header RCode handling class + # + # =Synopsis + # + # It should be used internally by Net::DNS::Header class. However, it's still + # possible to instantiate it directly. + # + # require 'net/dns/header' + # rcode = Net::DNS::Header::RCode.new 0 + # + # =Description + # + # The RCode class represents the RCode field in the Header portion of a + # DNS packet. This field (called Response Code) is used to get informations + # about the status of a DNS operation, such as a query or an update. These + # are the values in the original Mockapetris's standard (RFC1035): + # + # * 0 No error condition + # * 1 Format error - The name server was unable to interpret + # the query. + # * 2 Server failure - The name server was + # unable to process this query due to a + # problem with the name server. + # * 3 Name Error - Meaningful only for + # responses from an authoritative name + # server, this code signifies that the + # domain name referenced in the query does + # not exist. + # * 4 Not Implemented - The name server does + # not support the requested kind of query. + # * 5 Refused - The name server refuses to + # perform the specified operation for + # policy reasons. For example, a name + # server may not wish to provide the + # information to the particular requester, + # or a name server may not wish to perform + # a particular operation (e.g., zone + # transfer) for particular data. + # * 6-15 Reserved for future use. + # + # In the next DNS RFCs, codes 6-15 has been assigned to the following + # errors: + # + # * 6 YXDomain + # * 7 YXRRSet + # * 8 NXRRSet + # * 9 NotAuth + # * 10 NotZone + # + # More RCodes has to come for TSIGs and other operations. + # + class RCode + + # Constant for +rcode+ Response Code No Error + NOERROR = 0 + # Constant for +rcode+ Response Code Format Error + FORMAT = 1 + # Constant for +rcode+ Response Code Server Format Error + SERVER = 2 + # Constant for +rcode+ Response Code Name Error + NAME = 3 + # Constant for +rcode+ Response Code Not Implemented Error + NOTIMPLEMENTED = 4 + # Constant for +rcode+ Response Code Refused Error + REFUSED = 5 + + + + RCodeType = %w[NoError FormErr ServFail NXDomain NotImp + Refused YXDomain YXRRSet NXRRSet NotAuth NotZone] + + RCodeErrorString = ["No errors", + "The name server was unable to interpret the query", + "The name server was unable to process this query due to problem with the name server", + "Domain name referenced in the query does not exists", + "The name server does not support the requested kind of query", + "The name server refuses to perform the specified operation for policy reasons", + "", + "", + "", + "", + ""] + + attr_reader :code, :type, :explanation + + def initialize(code) + if (0..10).include? code + @code = code + @type = RCodeType[code] + @explanation = RCodeErrorString[code] + else + raise HeaderArgumentError, "RCode #{code} out of range" + end + end + + def to_s + @code.to_s + end + end + + # Constant for +opCode+ query + QUERY = 0 + # Constant for +opCode+ iquery + IQUERY = 1 + # Constant for +opCode+ status + STATUS = 2 + # Array with given strings + OPARR = %w[QUERY IQUERY STATUS] + + @@id_arr = [] + + # Reader for +id+ attribute + attr_reader :id + # Reader for the operational code + attr_reader :opCode + # Reader for the rCode instance + attr_reader :rCode + # Reader for question section entries number + attr_reader :qdCount + # Reader for answer section entries number + attr_reader :anCount + # Reader for authority section entries number + attr_reader :nsCount + # Reader for addictional section entries number + attr_reader :arCount + + # Creates a new Net::DNS::Header object with the desired values, + # which can be specified as an Hash argument. When called without + # arguments, defaults are used. If a data string is passed, values + # are taken from parsing the string. + # + # Examples: + # + # # Create a new Net::DNS::Header object + # header = Net::DNS::Header.new + # + # # Create a new Net::DNS::Header object passing values + # header = Net::DNS::Header.new(:opCode => 1, :rd => 0) + # + # # Create a new Net::DNS::Header object with binary data + # header = Net::DNS::Header.new(data) + # + # Default values are: + # + # :id => auto generated + # :qr => 0 # Query response flag + # :aa => 0 # Authoritative answer flag + # :tc => 0 # Truncated packet flag + # :ra => 0 # Recursiond available flag + # :rCode => 0 # Response code (status of the query) + # :opCode => 0 # Operational code (purpose of the query) + # :cd => 0 # Checking disable flag + # :ad => 0 # Only relevant in DNSSEC context + # :rd => 1 # Recursion desired flag + # :qdCount => 1 # Number of questions in the dns packet + # :anCount => 0 # Number of answer RRs in the dns packet + # :nsCount => 0 # Number of authoritative RRs in the dns packet + # :arCount => 0 # Number of additional RRs in the dns packet + # + # See also each option for a detailed explanation of usage. + # + def initialize(arg = {}) + if arg.kind_of? Hash + new_from_hash(arg) + else + raise HeaderArgumentError, "Wrong argument class: #{arg.class}" + end + end + + # Creates a new Net::DNS::Header object from binary data, which is + # passed as a string object as argument. + # The configurations parameters are taken from parsing the string. + # + # Example: + # + # # Create a new Net::DNS::Header object with binary data + # header = Net::DNS::Header.new(data) + # + # header.auth? + # #=> "true" if it comes from authoritative name server + # + def self.parse(arg) + if arg.kind_of? String + o = allocate + o.send(:new_from_binary, arg) + o + else + raise HeaderArgumentError, "Wrong argument class: #{arg.class}" + end + end + + # Inspect method, prints out all the options and relative values. + # + # p Net::DNS::Header.new + # # ;; id = 18123 + # # ;; qr = 0 opCode: 0 aa = 0 tc = 0 rd = 1 + # # ;; ra = 0 ad = 0 cd = 0 rcode = 0 + # # ;; qdCount = 1 anCount = 0 nsCount = 0 arCount = 0 + # + # This method will maybe be changed in the future to a more pretty + # way of display output. + # + def inspect + ";; id = #@id\n" + + if false # @opCode == "UPDATE" + #do stuff + else + ";; qr = #@qr\t" + + "opCode: #{opCode_str}\t" + + "aa = #@aa\t" + + "tc = #@tc\t" + + "rd = #@rd\n" + + ";; ra = #@ra\t" + + "ad = #@ad\t" + + "cd = #@cd\t" + + "rcode = #{@rCode.type}\n" + + ";; qdCount = #@qdCount\t"+ + "anCount = #@anCount\t"+ + "nsCount = #@nsCount\t"+ + "arCount = #@arCount\n" + end + end + + # The Net::DNS::Header#format method prints out the header + # in a special ascii representation of data, in a way + # similar to those often found on RFCs. + # + # p Net::DNS::Header.new.format + # # +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + # # | 18123 | + # # +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + # # |0| 0 |0|0|1|0|0| 0 | 0 | + # # +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + # # | 1 | + # # +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + # # | 0 | + # # +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + # # | 0 | + # # +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + # # | 0 | + # # +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + # + # This can be very usefull for didactical purpouses :) + # + def format + del = ("+-" * 16) + "+\n" + len = del.length + str = del + "|" + @id.to_s.center(len-3) + "|\n" + str += del + "|" + @qr.to_s + str += "|" + @opCode.to_s.center(7) + str += "|" + @aa.to_s + str += "|" + @tc.to_s + str += "|" + @rd.to_s + str += "|" + @ra.to_s + str += "|" + @ad.to_s + str += "|" + @cd.to_s.center(3) + str += "|" + @rCode.to_s.center(7) + "|\n" + str += del + "|" + @qdCount.to_s.center(len-3) + "|\n" + str += del + "|" + @anCount.to_s.center(len-3) + "|\n" + str += del + "|" + @nsCount.to_s.center(len-3) + "|\n" + str += del + "|" + @arCount.to_s.center(len-3) + "|\n" + del + str + end + + # Returns the header data in binary format, appropriate + # for use in a DNS query packet. + # + # hdata = header.data + # puts "Header is #{hdata.size} bytes" + # + def data + arr = [] + arr.push(@id) + arr.push((@qr<<7)|(@opCode<<3)|(@aa<<2)|(@tc<<1)|@rd) + arr.push((@ra<<7)|(@ad<<5)|(@cd<<4)|@rCode.code) + arr.push(@qdCount) + arr.push(@anCount) + arr.push(@nsCount) + arr.push(@arCount) + arr.pack("n C2 n4") + end + + # Set the ID for the current header. Useful when + # performing security tests. + # + def id=(val) + if @@id_arr.include? val + raise HeaderDuplicateID, "ID #{val} already used" + end + if (1..65535).include? val + @id = val + @@id_arr.push val + else + raise HeaderArgumentError, "ID #{val} out of range" + end + end + + # Checks whether the header is a query (+qr+ bit set to 0) + # + def query? + @qr == 0 + end + + # Set the +qr+ query response flag to be either +true+ or + # +false+. You can also use the values 0 and 1. This flag + # indicates if the DNS packet contains a query or an answer, + # so it should be set to +true+ in DNS answer packets. + # If +qr+ is +true+, the packet is a response. + # + def qr=(val) + case val + when true + @qr = 1 + when false + @qr = 0 + when 0,1 + @qr = val + else + raise HeaderArgumentError, ":qr must be true(or 1) or false(or 0)" + end + end + + # Checks whether the header is a response + # (+qr+ bit set to 1) + # + def response? + @qr == 1 + end + + # Returns a string representation of the +opCode+ + # + # puts "Packet is a #{header.opCode_str}" + # #=> Packet is a QUERY + # + def opCode_str + OPARR[@opCode] + end + + # Set the +opCode+ variable to a new value. This fields indicates + # the type of the question present in the DNS packet; +val+ can be + # one of the values QUERY, IQUERY or STATUS. + # + # * QUERY is the standard DNS query + # * IQUERY is the inverse query + # * STATUS is used to query the nameserver for its status + # + # Example: + # + # include Net::DNS + # header = Header.new + # header.opCode = Header::STATUS + # + def opCode=(val) + if (0..2).include? val + @opCode = val + else + raise HeaderWrongOpcode, "Wrong opCode value (#{val}), must be QUERY, IQUERY or STATUS" + end + end + + # Checks whether the response is authoritative + # + # if header.auth? + # puts "Response is authoritative" + # else + # puts "Answer is NOT authoritative" + # end + # + def auth? + @aa == 1 + end + + # Set the +aa+ flag (authoritative answer) to either +true+ + # or +false+. You can also use 0 or 1. + # + # This flag indicates whether a DNS answer packet contains + # authoritative data, meaning that is was generated by a + # nameserver authoritative for the domain of the question. + # + # Must only be set to +true+ in DNS answer packets. + # + def aa=(val) + case val + when true + @aa = 1 + when false + @aa = 0 + when 0,1 + @aa = val + else + raise HeaderArgumentError, ":aa must be true(or 1) or false(or 0)" + end + end + + # Checks whether the packet was truncated + # + # # Sending packet using UDP + # if header.truncated? + # puts "Warning, packet has been truncated!" + # # Sending packet using TCP + # end + # # Do something with the answer + # + def truncated? + @tc == 1 + end + + # Set the +tc+ flag (truncated packet) to either +true+ + # ot +false+. You can also use 0 or 1. + # + # The truncated flag is used in response packets to indicate + # that the amount of data to be trasmitted exceedes the + # maximum allowed by the protocol in use, tipically UDP, and + # that the data present in the packet has been truncated. + # A different protocol (such has TCP) need to be used to + # retrieve full data. + # + # Must only be set in DNS answer packets. + # + def tc=(val) + case val + when true + @tc = 1 + when false + @tc = 0 + when 0,1 + @tc = val + else + raise HeaderArgumentError, ":tc must be true(or 1) or false(or 0)" + end + end + + # Checks whether the packet has a recursion bit + # set, meaning that recursion is desired + # + def recursive? + @rd == 1 + end + + # Sets the recursion desidered bit. + # Remember that recursion query support is + # optional. + # + # header.recursive = true + # hdata = header.data # suitable for sending + # + # Consult RFC1034 and RFC1035 for a detailed explanation + # of how recursion works. + # + def recursive=(val) + case val + when true + @rd = 1 + when false + @rd = 0 + when 1 + @rd = 1 + when 0 + @rd = 0 + else + raise HeaderWrongRecursive, "Wrong value (#{val}), please specify true (1) or false (0)" + end + end + + # Alias for Header#recursive= to keep compatibility + # with the Perl version. + # + def rd=(val) + self.recursive = val + end + + # Checks whether recursion is available. + # This flag is usually set by nameservers to indicate + # that they support recursive-type queries. + # + def r_available? + @ra == 1 + end + + # Set the +ra+ flag (recursion available) to either +true+ or + # +false+. You can also use 0 and 1. + # + # This flag must only be set in DNS answer packets. + # + def ra=(val) + case val + when true + @ra = 1 + when false + @ra = 0 + when 0,1 + @ra = val + else + raise HeaderArgumentError, ":ra must be true(or 1) or false(or 0)" + end + end + + # Checks whether checking is enabled or disabled. + # + # Checking is enabled by default. + # + def checking? + @cd == 0 + end + + # Set the +cd+ flag (checking disabled) to either +true+ + # ot +false+. You can also use 0 or 1. + # + def cd=(val) + case val + when true + @cd = 1 + when false + @cd = 0 + when 0,1 + @cd = val + else + raise HeaderArgumentError, ":cd must be true(or 1) or false(or 0)" + end + end + + # Checks whether +ad+ flag has been set. + # + # This flag is only relevant in DNSSEC context. + # + def verified? + @ad == 1 + end + + # Set the +ad+ flag to either +true+ + # ot +false+. You can also use 0 or 1. + # + # The AD bit is only set on answers where signatures have + # been cryptographically verified or the server is + # authoritative for the data and is allowed to set the bit by policy. + # + def ad=(val) + case val + when true + @ad = 1 + when false + @ad = 0 + when 0,1 + @ad = val + else + raise HeaderArgumentError, ":ad must be true(or 1) or false(or 0)" + end + end + + # Returns an error array for the header response code, or + # +nil+ if no error is generated. + # + # error, cause = header.rCode_str + # puts "Error #{error} cause by: #{cause}" if error + # #=> Error ForErr caused by: The name server + # #=> was unable to interpret the query + # + def rCode_str + return rCode.type, rCode.explanation + end + + # Checks for errors in the DNS packet + # + # unless header.error? + # puts "No errors in DNS answer packet" + # end + # + def error? + @rCode.code > 0 + end + + # Set the rCode value. This should only be done in DNS + # answer packets. + # + def rCode=(val) + @rCode = RCode.new(val) + end + + # Sets the number of entries in a question section + # + def qdCount=(val) + if (0..65535).include? val + @qdCount = val + else + raise HeaderWrongCount, "Wrong number of count (#{val}), must be 0-65535" + end + end + + # Sets the number of RRs in an answer section + # + def anCount=(val) + if (0..65535).include? val + @anCount = val + else + raise HeaderWrongCount, "Wrong number of count (#{val}), must be 0-65535" + end + end + + # Sets the number of RRs in an authority section + # + def nsCount=(val) + if (0..65535).include? val + @nsCount = val + else + raise HeaderWrongCount, "Wrong number of count (#{val}), must be 0-65535" + end + end + + # Sets the number of RRs in an addictional section + # + def arCount=(val) + if (0..65535).include? val + @arCount = val + else + raise HeaderWrongCount, "Wrong number of count (#{val}), must be 0-65535" + end + end + + private + + def new_from_scratch + @id = genID # generate ad unique id + @qr = @aa = @tc = @ra = @ad = @cd = 0 + @rCode = RCode.new(0) # no error + @anCount = @nsCount = @arCount = 0 + @rd = @qdCount = 1 + @opCode = QUERY # standard query, default message + end + + def new_from_binary(str) + unless str.size == Net::DNS::HFIXEDSZ + raise HeaderArgumentError, "Header binary data has wrong size: #{str.size} bytes" + end + arr = str.unpack("n C2 n4") + @id = arr[0] + @qr = (arr[1] >> 7) & 0x01 + @opCode = (arr[1] >> 3) & 0x0F + @aa = (arr[1] >> 2) & 0x01 + @tc = (arr[1] >> 1) & 0x01 + @rd = arr[1] & 0x1 + @ra = (arr[2] >> 7) & 0x01 + @ad = (arr[2] >> 5) & 0x01 + @cd = (arr[2] >> 4) & 0x01 + @rCode = RCode.new(arr[2] & 0xf) + @qdCount = arr[3] + @anCount = arr[4] + @nsCount = arr[5] + @arCount = arr[6] + end + + def new_from_hash(hash) + new_from_scratch + hash.each do |key,val| + eval "self.#{key.to_s} = val" + end + end + + def genID + while (@@id_arr.include?(q = rand(65535))) + end + @@id_arr.push(q) + q + end + + end # class Header + + end # class DNS +end # module Net + + +class HeaderArgumentError < ArgumentError # :nodoc: all +end + +class HeaderWrongCount < ArgumentError # :nodoc: all +end + +class HeaderWrongRecursive < ArgumentError # :nodoc: all +end + +class HeaderWrongOpcode < ArgumentError # :nodoc: all +end + +class HeaderDuplicateID < ArgumentError # :nodoc: all +end diff --git a/lib/net/dns/names/names.rb b/lib/net/dns/names/names.rb new file mode 100644 index 0000000..01937d0 --- /dev/null +++ b/lib/net/dns/names/names.rb @@ -0,0 +1,109 @@ +module Net # :nodoc: + module DNS + + module Names # :nodoc: all + + INT16SZ = 2 + + # Expand a compressed name in a DNS Packet object. Please + # see RFC1025 for an explanation of how the compression + # in DNS packets works, how may it be useful and how should + # be handled. + # + # This method accept two parameters: a raw packet data and an + # offset, which indicates the point in the packet in which the + # parsing has arrived. + # + def dn_expand(packet,offset) + name = "" + packetlen = packet.size + while true + raise ExpandError, "offset is greater than packet lenght!" if packetlen < (offset+1) + len = packet.unpack("@#{offset} C")[0] + + if len == 0 + offset += 1 + break + elsif (len & 0xC0) == 0xC0 + raise ExpandError, "Packet ended before offset expand" if packetlen < (offset+INT16SZ) + ptr = packet.unpack("@#{offset} n")[0] + ptr &= 0x3FFF + name2 = dn_expand(packet,ptr)[0] + raise ExpandError, "Packet is malformed!" if name2 == nil + name += name2 + offset += INT16SZ + break + else + offset += 1 + raise ExpandError, "No expansion found" if packetlen < (offset+len) + elem = packet[offset..offset+len-1] + name += "#{elem}." + offset += len + end + end + return [name,offset] # name.chomp(".") if trailing dot has to be omitted + end + + def pack_name(name) + if name.size > 63 + raise ArgumentError, "Label data cannot exceed 63 chars" + end + arr = name.split(".") + str = "" + arr.each do |elem| + str += [elem.size,elem].pack("Ca*") + end + str += [0].pack("C") + str + end + + def names_array(name) + arr = name.split(".") + ar = [] + string = "" + arr.size.times do |i| + x = i+1 + elem = arr[-x] + len = elem.size + string = ((string.reverse)+([len,elem].pack("Ca*")).reverse).reverse + ar.unshift(string) + end + return ar + end + + def dn_comp(name,offset,compnames) + names = {} + ptr = 0 + str = "" + arr = names_array(name) + arr.each do |entry| + if compnames.has_key?(entry) + ptr = 0xC000 | compnames[entry] + str += [ptr].pack("n") + offset += INT16SZ + break + else + len = entry.unpack("C")[0] + elem = entry[1..len] + str += [len,elem].pack("Ca*") + names.update({"#{entry}" => offset}) + offset += len + end + end + return str,offset,names + end + + def valid?(name) + if name =~ /^([a-z0-9]([-a-z0-9]*[a-z0-9])?\.)+((a[cdefgilmnoqrstuwxz]|aero|arpa)|(b[abdefghijmnorstvwyz]|biz)|(c[acdfghiklmnorsuvxyz]|cat|com|coop)|d[ejkmoz]|(e[ceghrstu]|edu)|f[ijkmor]|(g[abdefghilmnpqrstuwy]|gov)|h[kmnrtu]|(i[delmnoqrst]|info|int)|(j[emop]|jobs)|k[eghimnprwyz]|l[abcikrstuvy]|(m[acdghklmnopqrstuvwxyz]|mil|mobi|museum)|(n[acefgilopruz]|name|net)|(om|org)|(p[aefghklmnrstwy]|pro)|qa|r[eouw]|s[abcdeghijklmnortvyz]|(t[cdfghjklmnoprtvwz]|travel)|u[agkmsyz]|v[aceginu]|w[fs]|y[etu]|z[amw])$/i + return name + else + raise ArgumentError, "Invalid FQDN: #{name}" + end + end + + end # module Names + end # module DNS +end # module Net + +class ExpandError < StandardError # :nodoc: +end diff --git a/lib/net/dns/packet.rb b/lib/net/dns/packet.rb new file mode 100644 index 0000000..0f4f34b --- /dev/null +++ b/lib/net/dns/packet.rb @@ -0,0 +1,570 @@ +require 'logger' +require 'net/dns/names/names' +require 'net/dns/dns' +require 'net/dns/header' +require 'net/dns/question' +require 'net/dns/rr' + +module Net # :nodoc: + module DNS + + # =Name + # + # Net::DNS::Packet - DNS packet object class + # + # =Synopsis + # + # require 'net/dns/packet' + # + # =Description + # + # The Net::DNS::Packet class represents an entire DNS packet, + # divided in his main section: + # + # * Header (instance of Net::DNS::Header) + # * Question (array of Net::DNS::Question objects) + # * Answer, Authority, Additional (each formed by an array of Net::DNS::RR + # objects) + # + # You can use this class whenever you need to create a DNS packet, whether + # in an user application, in a resolver instance (have a look, for instance, + # at the Net::DNS::Resolver#send method) or for a nameserver. + # + # Some example: + # + # # Create a packet + # packet = Net::DNS::Packet.new("www.example.com") + # mx = Net::DNS::Packet.new("example.com", Net::DNS::MX) + # + # # Getting packet binary data, suitable for network transmission + # data = packet.data + # + # A packet object can be created from binary data too, like an + # answer packet just received from a network stream: + # + # packet = Net::DNS::Packet::parse(data) + # + # Each part of a packet can be gotten by the right accessors: + # + # header = packet.header # Instance of Net::DNS::Header class + # question = packet.question # Instance of Net::DNS::Question class + # + # # Iterate over additional RRs + # packet.additional.each do |rr| + # puts "Got an #{rr.type} record" + # end + # + # Some iterators have been written to easy the access of those RRs, + # which are often the most important. So instead of doing: + # + # packet.answer.each do |rr| + # if rr.type == Net::DNS::RR::Types::A + # # do something with +rr.address+ + # end + # end + # + # we can do: + # + # packet.each_address do |ip| + # # do something with +ip+ + # end + # + # Be sure you don't miss all the iterators in the class documentation. + # + # =Logging facility + # + # As Net::DNS::Resolver class, Net::DNS::Packet class has its own logging + # facility too. It work in the same way the other one do, so you can + # maybe want to override it or change the file descriptor. + # + # packet = Net::DNS::Packet.new("www.example.com") + # packet.logger = $stderr + # + # # or even + # packet.logger = Logger.new("/tmp/packet.log") + # + # If the Net::DNS::Packet class is directly instantiated by the Net::DNS::Resolver + # class, like the great majority of the time, it will use the same logger facility. + # + # Logger level will be set to Logger::Debug if $DEBUG variable is set. + # + # =Error classes + # + # Some error classes has been defined for the Net::DNS::Packet class, + # which are listed here to keep a light and browsable main documentation. + # We have: + # + # * PacketArgumentError: Generic argument error for class Net::DNS::Packet + # * PacketError: Generic Packet error + # + # =Copyright + # + # Copyright (c) 2006 Marco Ceresa + # + # All rights reserved. This program is free software; you may redistribute + # it and/or modify it under the same terms as Ruby itself. + # + class Packet + + include Names + + attr_reader :header, :question, :answer, :authority, :additional + attr_reader :answerfrom, :answersize + + # Create a new instance of Net::DNS::Packet class. Arguments are the + # canonical name of the resourse, an optional type field and an optional + # class field. The record type and class can be omitted; they default + # to +A+ and +IN+. + # + # packet = Net::DNS::Packet.new("www.example.com") + # packet = Net::DNS::Packet.new("example.com", Net::DNS::MX) + # packet = Net::DNS::Packet.new("example.com",Net::DNS::TXT,Net::DNS::CH) + # + # This class no longer instantiate object from binary data coming from + # network streams. Please use Net::DNS::Packet.new_from_data instead. + # + def initialize(name,type=Net::DNS::A,cls=Net::DNS::IN) + @header = Net::DNS::Header.new(:qdCount => 1) + @question = [Net::DNS::Question.new(name,type,cls)] + @answer = [] + @authority = [] + @additional = [] + @logger = Logger.new $stdout + @logger.level = $DEBUG ? Logger::DEBUG : Logger::WARN + end + + # Create a new instance of Net::DNS::Packet class from binary data, taken + # out by a network stream. For example: + # + # # udp_socket is an UDPSocket waiting for a response + # ans = udp_socket.recvfrom(1500) + # packet = Net::DNS::Packet::parse(ans) + # + # An optional +from+ argument can be used to specify the information + # of the sender. If data is passed as is from a Socket#recvfrom call, + # the method will accept it. + # + # Be sure that your network data is clean from any UDP/TCP header, + # expecially when using RAW sockets. + # + def Packet.parse(*args) + o = allocate + o.send(:new_from_data, *args) + o + end + + + # Checks if the packet is a QUERY packet + def query? + @header.opCode == Net::DNS::Header::QUERY + end + + # Return the packet object in binary data, suitable + # for sending across a network stream. + # + # packet_data = packet.data + # puts "Packet is #{packet_data.size} bytes long" + # + def data + qdcount=ancount=nscount=arcount=0 + data = @header.data + headerlength = data.length + + @question.each do |question| + data += question.data + qdcount += 1 + end + @answer.each do |rr| + data += rr.data#(data.length) + ancount += 1 + end + @authority.each do |rr| + data += rr.data#(data.length) + nscount += 1 + end + @additional.each do |rr| + data += rr.data#(data.length) + arcount += 1 + end + + @header.qdCount = qdcount + @header.anCount = ancount + @header.nsCount = nscount + @header.arCount = arcount + + @header.data + data[Net::DNS::HFIXEDSZ..data.size] + end + + # Same as Net::DNS::Packet#data, but implements name compression + # (see RFC1025) for a considerable save of bytes. + # + # packet = Net::DNS::Packet.new("www.example.com") + # puts "Size normal is #{packet.data.size} bytes" + # puts "Size compressed is #{packet.data_comp.size} bytes" + # + def data_comp + offset = 0 + compnames = {} + qdcount=ancount=nscount=arcount=0 + data = @header.data + headerlength = data.length + + @question.each do |question| + str,offset,names = question.data + data += str + compnames.update(names) + qdcount += 1 + end + + @answer.each do |rr| + str,offset,names = rr.data(offset,compnames) + data += str + compnames.update(names) + ancount += 1 + end + + @authority.each do |rr| + str,offset,names = rr.data(offset,compnames) + data += str + compnames.update(names) + nscount += 1 + end + + @additional.each do |rr| + str,offset,names = rr.data(offset,compnames) + data += str + compnames.update(names) + arcount += 1 + end + + @header.qdCount = qdcount + @header.anCount = ancount + @header.nsCount = nscount + @header.arCount = arcount + + @header.data + data[Net::DNS::HFIXEDSZ..data.size] + end + + # Inspect method + def inspect + retval = "" + if @answerfrom != "0.0.0.0:0" and @answerfrom + retval += ";; Answer received from #@answerfrom (#{@answersize} bytes)\n;;\n" + end + + retval += ";; HEADER SECTION\n" + retval += @header.inspect + + retval += "\n" + section = (@header.opCode == "UPDATE") ? "ZONE" : "QUESTION" + retval += ";; #{section} SECTION (#{@header.qdCount} record#{@header.qdCount == 1 ? '' : 's'}):\n" + @question.each do |qr| + retval += ";; " + qr.inspect + "\n" + end + + unless @answer.size == 0 + retval += "\n" + section = (@header.opCode == "UPDATE") ? "PREREQUISITE" : "ANSWER" + retval += ";; #{section} SECTION (#{@header.anCount} record#{@header.anCount == 1 ? '' : 's'}):\n" + @answer.each do |rr| + retval += rr.inspect + "\n" + end + end + + unless @authority.size == 0 + retval += "\n" + section = (@header.opCode == "UPDATE") ? "UPDATE" : "AUTHORITY" + retval += ";; #{section} SECTION (#{@header.nsCount} record#{@header.nsCount == 1 ? '' : 's'}):\n" + @authority.each do |rr| + retval += rr.inspect + "\n" + end + end + + unless @additional.size == 0 + retval += "\n" + retval += ";; ADDITIONAL SECTION (#{@header.arCount} record#{@header.arCount == 1 ? '' : 's'}):\n" + @additional.each do |rr| + retval += rr.inspect + "\n" + end + end + + retval + end + + + # Wrapper to Header#truncated? + # + def truncated? + @header.truncated? + end + + # Assing a Net::DNS::Header object to a Net::DNS::Packet + # instance. + # + def header=(object) + if object.kind_of? Net::DNS::Header + @header = object + else + raise PacketArgumentError, "Argument must be a Net::DNS::Header object" + end + end + + # Assign a Net::DNS::Question object, or an array of + # Questions objects, to a Net::DNS::Packet instance. + # + def question=(object) + case object + when Array + if object.all? {|x| x.kind_of? Net::DNS::Question} + @question = object + else + raise PacketArgumentError, "Some of the elements is not an Net::DNS::Question object" + end + when Net::DNS::Question + @question = [object] + else + raise PacketArgumentError, "Invalid argument, not a Question object nor an array of objects" + end + end + + # Assign a Net::DNS::RR object, or an array of + # RR objects, to a Net::DNS::Packet instance answer + # section. + # + def answer=(object) + case object + when Array + if object.all? {|x| x.kind_of? Net::DNS::RR} + @answer = object + else + raise PacketArgumentError, "Some of the elements is not an Net::DNS::RR object" + end + when Net::DNS::RR + @answer = [object] + else + raise PacketArgumentError, "Invalid argument, not a RR object nor an array of objects" + end + end + + # Assign a Net::DNS::RR object, or an array of + # RR objects, to a Net::DNS::Packet instance additional + # section. + # + def additional=(object) + case object + when Array + if object.all? {|x| x.kind_of? Net::DNS::RR} + @additional = object + else + raise PacketArgumentError, "Some of the elements is not an Net::DNS::RR object" + end + when Net::DNS::RR + @additional = [object] + else + raise PacketArgumentError, "Invalid argument, not a RR object nor an array of objects" + end + end + + # Assign a Net::DNS::RR object, or an array of + # RR objects, to a Net::DNS::Packet instance authority + # section. + # + def authority=(object) + case object + when Array + if object.all? {|x| x.kind_of? Net::DNS::RR} + @authority = object + else + raise PacketArgumentError, "Some of the elements is not an Net::DNS::RR object" + end + when Net::DNS::RR + @authority = [object] + else + raise PacketArgumentError, "Invalid argument, not a RR object nor an array of objects" + end + end + + # Iterate for every address in the +answer+ section of a + # Net::DNS::Packet object. + # + # packet.each_address do |ip| + # ping ip.to_s + # end + # + # As you can see in the documentation for Net::DNS::RR::A class, + # the address returned is an instance of IPAddr class. + # + def each_address + @answer.each do |elem| + next unless elem.class == Net::DNS::RR::A + yield elem.address + end + end + + # Iterate for every nameserver in the +answer+ section of a + # Net::DNS::Packet object. + # + # packet.each_nameserver do |ns| + # puts "Nameserver found: #{ns}" + # end + # + def each_nameserver + @answer.each do |elem| + next unless elem.class == Net::DNS::RR::NS + yield elem.nsdname + end + end + + # Iterate for every exchange record in the +answer+ section + # of a Net::DNS::Packet object. + # + # packet.each_mx do |pref,name| + # puts "Mail exchange #{name} has preference #{pref}" + # end + # + def each_mx + @answer.each do |elem| + next unless elem.class == Net::DNS::RR::MX + yield elem.preference,elem.exchange + end + end + + # Iterate for every canonical name in the +answer+ section + # of a Net::DNS::Packet object. + # + # packet.each_cname do |cname| + # puts "Canonical name: #{cname}" + # end + # + def each_cname + @answer.each do |elem| + next unless elem.class == Net::DNS::RR::CNAME + yield elem.cname + end + end + + # Iterate for every pointer in the +answer+ section of a + # Net::DNS::Packet object. + # + # packet.each_ptr do |ptr| + # puts "Pointer for resource: #{ptr}" + # end + # + def each_ptr + @answer.each do |elem| + next unless elem.class == Net::DNS::RR::PTR + yield elem.ptrdname + end + end + + # Chacks whether a query has returned a NXDOMAIN error, + # meaning the domain name queried doesn't exists. + # + # %w[a.com google.com ibm.com d.com].each do |domain| + # response = Net::DNS::Resolver.new.send(domain) + # puts "#{domain} doesn't exist" if response.nxdomain? + # end + # #=> a.com doesn't exist + # #=> d.com doesn't exist + # + def nxdomain? + header.rCode == Net::DNS::Header::NAME + end + + private + + # New packet from binary data + def new_from_data(data, from = nil) + unless from + if data.kind_of? Array + data,from = data + else + from = [0,0,"0.0.0.0","unknown"] + end + end + + @answerfrom = from[2] + ":" + from[1].to_s + @answersize = data.size + @logger = Logger.new $stdout + @logger.level = $DEBUG ? Logger::DEBUG : Logger::WARN + + #------------------------------------------------------------ + # Header section + #------------------------------------------------------------ + offset = Net::DNS::HFIXEDSZ + @header = Net::DNS::Header.parse(data[0..offset-1]) + + @logger.debug ";; HEADER SECTION" + @logger.debug @header.inspect + + #------------------------------------------------------------ + # Question section + #------------------------------------------------------------ + section = @header.opCode == "UPDATE" ? "ZONE" : "QUESTION" + @logger.debug ";; #{section} SECTION (#{@header.qdCount} record#{@header.qdCount == 1 ? '': 's'})" + + @question = [] + @header.qdCount.times do + qobj,offset = parse_question(data,offset) + @question << qobj + @logger.debug ";; #{qobj.inspect}" + end + + #------------------------------------------------------------ + # Answer/prerequisite section + #------------------------------------------------------------ + section = @header.opCode == "UPDATE" ? "PREREQUISITE" : "ANSWER" + @logger.debug ";; #{section} SECTION (#{@header.qdCount} record#{@header.qdCount == 1 ? '': 's'})" + + @answer = [] + @header.anCount.times do + rrobj,offset = Net::DNS::RR.parse_packet(data,offset) + @answer << rrobj + @logger.debug rrobj.inspect + end + + #------------------------------------------------------------ + # Authority/update section + #------------------------------------------------------------ + section = @header.opCode == "UPDATE" ? "UPDATE" : "AUTHORITY" + @logger.debug ";; #{section} SECTION (#{@header.nsCount} record#{@header.nsCount == 1 ? '': 's'})" + + @authority = [] + @header.nsCount.times do + rrobj,offset = Net::DNS::RR.parse_packet(data,offset) + @authority << rrobj + @logger.debug rrobj.inspect + end + + #------------------------------------------------------------ + # Additional section + #------------------------------------------------------------ + @logger.debug ";; ADDITIONAL SECTION (#{@header.arCount} record#{@header.arCount == 1 ? '': 's'})" + + @additional = [] + @header.arCount.times do + rrobj,offset = Net::DNS::RR.parse_packet(data,offset) + @additional << rrobj + @logger.debug rrobj.inspect + end + + end # new_from_data + + + # Parse question section + def parse_question(data,offset) + size = (dn_expand(data,offset)[1]-offset) + 2*Net::DNS::INT16SZ + return [Net::DNS::Question.parse(data[offset,size]), offset+size] + rescue StandardError => err + raise PacketError, "Caught exception, maybe packet malformed => #{err}" + end + + end # class Packet + + end # module DNS +end # module Net + +class PacketError < StandardError # :nodoc: +end +class PacketArgumentError < ArgumentError # :nodoc: +end diff --git a/lib/net/dns/question.rb b/lib/net/dns/question.rb new file mode 100644 index 0000000..9eb6158 --- /dev/null +++ b/lib/net/dns/question.rb @@ -0,0 +1,195 @@ +#--- +# $Id: Question.rb,v 1.8 2006/07/28 19:00:03 bluemonk Exp $ +#+++ + +require 'net/dns/dns' +require 'net/dns/names/names' +require 'net/dns/rr/types' +require 'net/dns/rr/classes' + +module Net # :nodoc: + module DNS + + # + # =Name + # + # Net::DNS::Question - DNS packet question class + # + # =Synopsis + # + # require 'net/dns/question' + # + # =Description + # + # This class represent the Question portion of a DNS packet. The number + # of question entries is stored in the +qdCount+ variable of an Header + # object. + # + # A new object can be created passing the name of the query and the type + # of answer desired, plus an optional argument containing the class: + # + # question = Net::DNS::Question.new("google.com.", Net::DNS::A) + # #=> "google.com. A IN" + # + # Alternatevly, a new object is created when processing a binary + # packet, as when an answer is received. + # To obtain the binary data from a question object you can use + # the method Question#data: + # + # question.data + # #=> "\006google\003com\000\000\001\000\001" + # + # A lot of methods were written to keep a compatibility layer with + # the Perl version of the library, as long as methods name which are + # more or less the same. + # + # =Error classes + # + # Some error classes has been defined for the Net::DNS::Header class, + # which are listed here to keep a light and browsable main documentation. + # We have: + # + # * QuestionArgumentError: generic argument error + # * QuestionNameError: an error in the +name+ part of a Question entry + # + # =Copyright + # + # Copyright (c) 2006 Marco Ceresa + # + # All rights reserved. This program is free software; you may redistribute + # it and/or modify it under the same terms as Ruby itself. + # + class Question + + include Net::DNS::Names + + # +name+ part of a Question entry + attr_reader :qName + # +type+ part of a Question entry + attr_reader :qType + # +class+ part of a Question entry + attr_reader :qClass + + # Creates a new Net::DNS::Question object: + # + # question = Net::DNS::Question.new("example.com") + # #=> "example.com A IN" + # question = Net::DNS::Question.new("example.com", Net::DNS::MX) + # #=> "example.com MX IN" + # question = Net::DNS::Question.new("example.com", Net::DNS::TXT, Net::DNS::HS) + # #=> "example.com TXT HS" + + # If not specified, +type+ and +cls+ arguments defaults + # to Net::DNS::A and Net::DNS::IN respectively. + # + def initialize(name,type=Net::DNS::A,cls=Net::DNS::IN) + @qName = check_name name + @qType = Net::DNS::RR::Types.new type + @qClass = Net::DNS::RR::Classes.new cls + end + + # Return a new Net::DNS::Question object created by + # parsing binary data, such as an answer from the + # nameserver. + # + # question = Net::DNS::Question.parse(data) + # puts "Queried for #{question.qName} type #{question.qType.to_s}" + # #=> Queried for example.com type A + # + def self.parse(arg) + if arg.kind_of? String + o = allocate + o.send(:new_from_binary,arg) + o + else + raise QuestionArgumentError, "Wrong argument format, must be a String" + end + end + + # Known inspect method with nice formatting + def inspect + if @qName.size > 29 then + len = @qName.size + 1 + else + len = 29 + end + [@qName,@qClass.to_s,@qType.to_s].pack("A#{len} A8 A8") + end + + # Outputs binary data from a Question object + # + # question.data + # #=> "\006google\003com\000\000\001\000\001" + # + def data + [pack_name(@qName),@qType.to_i,@qClass.to_i].pack("a*nn") + end + + # Return the binary data of the objects, plus an offset + # and an Hash with references to compressed names. For use in + # Net::DNS::Packet compressed packet creation. + # + def comp_data + arr = @qName.split(".") + str = pack_name(@qName) + string = "" + names = {} + offset = Net::DNS::HFIXEDSZ + arr.size.times do |i| + x = i+1 + elem = arr[-x] + len = elem.size + string = ((string.reverse)+([len,elem].pack("Ca*")).reverse).reverse + names[string] = offset + offset += len + end + offset += 2 * Net::DNS::INT16SZ + str += "\000" + [[str,@qType.to_i,@qClass.to_i].pack("a*nn"),offset,names] + end + + private + + def build_qName(str) + result = "" + offset = 0 + loop do + len = str.unpack("@#{offset} C")[0] + break if len == 0 + offset += 1 + result += str[offset..offset+len-1] + result += "." + offset += len + end + result + end + + def check_name(name) + name.strip! + if name =~ /[^\w\.\-_]/ + raise QuestionNameError, "Question name #{name.inspect} not valid" + else + name + end + rescue + raise QuestionNameError, "Question name #{name.inspect} not valid" + end + + def new_from_binary(data) + str,type,cls = data.unpack("a#{data.size-4}nn") + @qName = build_qName(str) + @qType = Net::DNS::RR::Types.new type + @qClass = Net::DNS::RR::Classes.new cls + rescue StandardError => e + raise QuestionArgumentError, "Invalid data: #{data.inspect}\n{e.backtrace}" + end + + end # class Question + + end # class DNS +end # module Net + +class QuestionArgumentError < ArgumentError # :nodoc: +end +class QuestionNameError < StandardError # :nodoc: +end diff --git a/lib/net/dns/resolver.rb b/lib/net/dns/resolver.rb new file mode 100644 index 0000000..d15d59a --- /dev/null +++ b/lib/net/dns/resolver.rb @@ -0,0 +1,1232 @@ +# +# $Id: Resolver.rb,v 1.11 2006/07/30 16:55:35 bluemonk Exp $ +# + + + +require 'socket' +require 'timeout' +require 'ipaddr' +require 'logger' +require 'net/dns/packet' +require 'net/dns/resolver/timeouts' + +alias old_send send + +module Net # :nodoc: + module DNS + + include Logger::Severity + + # =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" + # + class Resolver + + # 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. + Defaults = { + :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)} + + # 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. + # + 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 + + # Get the resolver searchlist, returned as an array of entries + # + # res.searchlist + # #=> ["example.com","a.example.com","b.example.com"] + # + def searchlist + @config[:searchlist].inspect + end + + # 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 + # + 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 + + # Get the list of resolver nameservers, in a dotted decimal format + # + # res.nameservers + # #=> ["192.168.0.1","192.168.0.2"] + # + def nameservers + arr = [] + @config[:nameservers].each do |x| + arr << x.to_s + end + arr + end + alias_method :nameserver, :nameservers + + # 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) + # + 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 + alias_method("nameserver=","nameservers=") + + # Return a string with the default domain + # + def domain + @config[:domain].inspect + end + + # Set the domain for the query + # + def domain=(name) + @config[:domain] = name if valid? name + end + + # Return the defined size of the packet + # + def packet_size + @config[:packet_size] + end + + # Get the port number to which the resolver sends queries. + # + # puts "Sending queries to port #{res.port}" + # + def port + @config[:port] + end + + # 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. + # + 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 + + # Get the value of the source port number + # + # puts "Sending queries using port #{res.source_port}" + # + def source_port + @config[:source_port] + end + alias srcport source_port + + # 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. + # + 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 + alias srcport= source_port= + + # Get the local address from which the resolver sends queries + # + # puts "Sending queries using source address #{res.source_address}" + # + def source_address + @config[:source_address].to_s + end + alias srcaddr source_address + + # 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 http://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). + # + 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 + alias srcaddr= source_address= + + # Return the retrasmission interval (in seconds) the resolvers has + # been set on + # + def retry_interval + @config[:retry_interval] + end + alias retrans retry_interval + + # Set the retrasmission interval in seconds. Default 5 seconds + # + 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 + alias retrans= retry_interval= + + # The number of times the resolver will try a query + # + # puts "Will try a max of #{res.retry_number} queries" + # + def retry_number + @config[:retry_number] + end + + # Set the number of times the resolver will try a query. + # Default 4 times + # + 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 + alias_method('retry=', 'retry_number=') + + # 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" + # + def recursive? + @config[:recursive] + end + alias_method :recurse, :recursive? + alias_method :recursive, :recursive? + + # Sets whether or not the resolver should perform recursive + # queries. Default is true. + # + # res.recursive = false # perform non-recursive query + # + 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 + alias_method :recurse=, :recursive= + + # Return a string rapresenting the resolver state, suitable + # for printing on the screen. + # + # puts "Resolver state:" + # puts res.state + # + 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 + alias print state + alias inspect state + + # Checks whether the +defname+ flag has been activate. + def defname? + @config[:defname] + end + alias defname defname? + + # 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. + # + 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 + + # Get the state of the dns_search flag + def dns_search + @config[:dns_search] + end + alias_method :dnsrch, :dns_search + + # 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. + # + 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 + alias_method("dnsrch=","dns_search=") + + # Get the state of the use_tcp flag. + # + def use_tcp? + @config[:use_tcp] + end + alias_method :usevc, :use_tcp? + alias_method :use_tcp, :use_tcp? + + # 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. + # + 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 + alias usevc= use_tcp= + + def ignore_truncated? + @config[:ignore_truncated] + end + alias_method :ignore_truncated, :ignore_truncated? + + 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 + + # 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. + # + def tcp_timeout + @config[:tcp_timeout].to_s + end + + # 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 + def tcp_timeout=(secs) + @config[:tcp_timeout] = TcpTimeout.new(secs) + @logger.info("New TCP timeout value: #{@config[:tcp_timeout]} seconds") + end + + # 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. + # + def udp_timeout + @config[:udp_timeout].to_s + end + + # 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 + # + def udp_timeout=(secs) + @config[:udp_timeout] = UdpTimeout.new(secs) + @logger.info("New UDP timeout value: #{@config[:udp_timeout]} seconds") + end + + # 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. + # + def log_file=(log) + @logger.close + @config[:log_file] = log + @logger = Logger.new(@config[:log_file]) + @logger.level = $DEBUG ? Logger::DEBUG : Logger::WARN + end + + # 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. + # + 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 + + # 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. + # + def log_level=(level) + @logger.level = level + end + + # Performs a DNS query for the given name, applying the searchlist if + # appropriate. The search algorithm is as follows: + # + # 1. If the name contains at least one dot, try it as is. + # 2. 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. + # 3. 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. + # + 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 + + # 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. + # + 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 + + # 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. + # + 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 + + # + # 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. + # + def axfr(name,cls=Net::DNS::IN) + @logger.info "Requested AXFR transfer, zone #{name} class #{cls}" + send(name,Net::DNS::AXFR,cls) + end + + # + # Performs an MX query for the domain name passed as parameter. + # + # It actually uses the same methods a normal Resolver query would + # use, but automatically sort the results based on preferences + # and returns an ordered array. + # + # Example: + # + # res = Net::DNS::Resolver.new + # res.mx("google.com") + # + 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 + + private + + # Parse a configuration file specified as the argument. + # + def parse_config_file + if RUBY_PLATFORM =~ /win32/ + require 'win32/resolv' + arr = Win32::Resolv.get_resolv_info + self.domain = arr[0] + self.nameservers = arr[1] + else + IO.foreach(@config[:config_file]) do |line| + line.gsub!(/\s*[;#].*/,"") + next unless line =~ /\S/ + case line + when /^\s*domain\s+(\S+)/ + self.domain = $1 + when /^\s*search\s+(.*)/ + self.searchlist = $1.split(" ") + when /^\s*nameserver\s+(.*)/ + self.nameservers = $1.split(" ") + end + end + end + end + + # Parse environment variables + def parse_environment_variables + if ENV['RES_NAMESERVERS'] + self.nameservers = ENV['RES_NAMESERVERS'].split(" ") + end + if ENV['RES_SEARCHLIST'] + self.searchlist = ENV['RES_SEARCHLIST'].split(" ") + end + if ENV['LOCALDOMAIN'] + self.domain = ENV['LOCALDOMAIN'] + end + if ENV['RES_OPTIONS'] + ENV['RES_OPTIONS'].split(" ").each do |opt| + name,val = opt.split(":") + begin + eval("self.#{name} = #{val}") + rescue NoMethodError + raise ResolverArgumentError, "Invalid ENV option #{name}" + end + end + end + end + + def nameservers_from_name(arg) + arr = [] + arg.split(" ").each do |name| + Resolver.new.search(name).each_address do |ip| + arr << ip + end + end + @config[:nameservers] << arr + end + + def make_query_packet(string,type,cls) + case string + when IPAddr + name = string.reverse + type = Net::DNS::PTR + @logger.warn "PTR query required for address #{string}, changing type to PTR" + when /\d/ # Contains a number, try to see if it's an IP or IPv6 address + begin + name = IPAddr.new(string).reverse + type = Net::DNS::PTR + rescue ArgumentError + name = string if valid? string + end + else + name = string if valid? string + end + + # Create the packet + packet = Net::DNS::Packet.new(name,type,cls) + + if packet.query? + packet.header.recursive = @config[:recursive] ? 1 : 0 + end + + # DNSSEC and TSIG stuff to be inserted here + + packet + + end + + def send_tcp(packet,packet_data) + + ans = nil + length = [packet_data.size].pack("n") + + @config[:nameservers].each do |ns| + begin + buffer = "" + socket = Socket.new(Socket::AF_INET,Socket::SOCK_STREAM,0) + socket.bind(Socket.pack_sockaddr_in(@config[:source_port],@config[:source_address].to_s)) + + sockaddr = Socket.pack_sockaddr_in(@config[:port],ns.to_s) + + @config[:tcp_timeout].timeout do + socket.connect(sockaddr) + @logger.info "Contacting nameserver #{ns} port #{@config[:port]}" + socket.write(length+packet_data) + ans = socket.recv(Net::DNS::INT16SZ) + len = ans.unpack("n")[0] + + @logger.info "Receiving #{len} bytes..." + + if len == 0 + @logger.warn "Receiving 0 lenght packet from nameserver #{ns}, trying next." + next + end + + while (buffer.size < len) + left = len - buffer.size + temp,from = socket.recvfrom(left) + buffer += temp + end + + unless buffer.size == len + @logger.warn "Malformed packet from nameserver #{ns}, trying next." + next + end + end + return [buffer,["",@config[:port],ns.to_s,ns.to_s]] + rescue TimeoutError + @logger.warn "Nameserver #{ns} not responding within TCP timeout, trying next one" + next + ensure + socket.close + end + end + end + + def send_udp(packet,packet_data) + socket = UDPSocket.new + socket.bind(@config[:source_address].to_s,@config[:source_port]) + + ans = nil + response = "" + @config[:nameservers].each do |ns| + begin + @config[:udp_timeout].timeout do + @logger.info "Contacting nameserver #{ns} port #{@config[:port]}" + socket.send(packet_data,0,ns.to_s,@config[:port]) + ans = socket.recvfrom(@config[:packet_size]) + end + break if ans + rescue TimeoutError + @logger.warn "Nameserver #{ns} not responding within UDP timeout, trying next one" + next + end + end + ans + end + + def valid?(name) + if name =~ /[^-\w\.]/ + raise ResolverArgumentError, "Invalid domain name #{name}" + else + true + end + end + + end # class Resolver + end # module DNS +end # module Net + +class ResolverArgumentError < ArgumentError # :nodoc: +end +class NoResponseError < StandardError # :nodoc: +end + +module ExtendHash # :nodoc: + # Returns an hash with all the + # keys turned into downcase + # + # hsh = {"Test" => 1, "FooBar" => 2} + # hsh.key_downcase! + # #=> {"test"=>1,"foobar"=>2} + # + def key_downcase! + hsh = Hash.new + self.each do |key,val| + hsh[key.downcase] = val + end + self.replace(hsh) + end +end + +class Hash # :nodoc: + include ExtendHash +end + + + + + + + + + + + + diff --git a/lib/net/dns/resolver/socks.rb b/lib/net/dns/resolver/socks.rb new file mode 100644 index 0000000..45f5dea --- /dev/null +++ b/lib/net/dns/resolver/socks.rb @@ -0,0 +1,154 @@ +require 'socket' +require 'ipaddr' + +class RawSocket # :nodoc: + + @@id_arr = [] + + def initialize(src_addr,dest_addr) + + # Define socket + begin + @socket = Socket.new PF_INET, SOCK_RAW, IPPROTO_RAW + rescue SystemCallError => e + raise SystemCallError, "You must be root to use raw sockets! #{e}" + end + + @socket.setsockopt IPPROTO_IP, IP_HDRINCL, 1 + + # Checks addresses + @src_addr = check_addr src_addr + @dest_addr = check_addr dest_addr + + # Source and destination port are zero + @src_port = 0 + @dest_port = 0 + + # Set correct protocol version in the header + @version = @dest_addr.ipv4? ? "0100" : "0110" + + # Total lenght: must be overridden by subclasses + @tot_lenght = 20 + + # Protocol: must be overridden by subclasses + @protocol = 1 # ICMP by default + + # Generate a new id + # @id = genID + @id = 1234 + + # Generate peer sockaddr + @to = Socket.pack_sockaddr_in @dest_port, @dest_addr.to_s + end + + def send(payload = '') + packet = make_ip_header([[ @version+'0101', 'B8' ], # version, hlen + [ 0, 'C' ], # tos + [ @tot_lenght + payload.size, 'n' ], # total len + [ @id, 'n' ], # id + [ 0, 'n' ], # flags, offset + [ 64, 'C' ], # ttl + [ @protocol, 'C' ], # protocol + [ 0, 'n' ], # checksum + [ @src_addr.to_i, 'N' ], # source + [ @dest_addr.to_i, 'N' ], # destination + ]) + packet << make_transport_header(payload.size) + packet << [payload].pack("a*") + @socket.send(packet,0,@to) + end + + private + + def check_addr addr + case addr + when String + IPAddr.new addr + when IPAddr + addr + else + raise ArgumentError, "Wrong address format: #{addr}" + end + end + + def check_port port + if (1..65535).include? port and port.kind_of? Integer + port + else + raise ArgumentError, "Port #{port} not valid" + end + end + + def genID + while (@@id_arr.include?(q = rand(65535))) + end + @@id_arr.push(q) + q + end + + def ipchecksum(data) + checksum = data.unpack("n*").inject(0) { |s, x| s + x } + ((checksum >> 16) + (checksum & 0xffff)) ^ 0xffff + end + + def make_ip_header(parts) + template = '' + data = [] + parts.each do |part| + data += part[0..-2] + template << part[-1] + end + data_str = data.pack(template) + checksum = ipchecksum(data_str) + data[-3] = checksum + data.pack(template) + end + + def make_transport_header + "" + end + +end + +class UdpRawSocket < RawSocket # :nodoc: + + def initialize(src_addr,src_port,dest_addr,dest_port) + + super(src_addr,dest_addr) + + # Check ports + @src_port = check_port src_port + @dest_port = check_port dest_port + + # Total lenght: must be overridden by subclasses + @tot_lenght = 20 + 8 # 8 bytes => UDP Header + + # Protocol: must be overridden by subclasses + @protocol = 17 # UDP protocol + + @to = Socket.pack_sockaddr_in @dest_port, @dest_addr.to_s + end + + private + + def make_udp_header(parts) + template = '' + data = [] + parts.each do |part| + data += part[0..-2] + template << part[-1] + end + data.pack(template) + end + + def make_transport_header(pay_size) + make_udp_header([ + [ @src_port, 'n'], # source port + [ @dest_port, 'n' ], # destination port + [ 8 + pay_size, 'n' ], # len + [ 0, 'n' ] # checksum (mandatory) + ]) + end + +end + diff --git a/lib/net/dns/resolver/timeouts.rb b/lib/net/dns/resolver/timeouts.rb new file mode 100644 index 0000000..e0b4f19 --- /dev/null +++ b/lib/net/dns/resolver/timeouts.rb @@ -0,0 +1,73 @@ +require 'timeout' + +module SecondsHandle #:nodoc: all + def transform(secs) + case secs + when 0 + to_s + when 1..59 + "#{secs} seconds" + when 60..3559 + "#{secs/60} minutes and #{secs%60} seconds" + else + hours = secs/3600 + secs -= (hours*3600) + "#{hours} hours, #{secs/60} minutes and #{secs%60} seconds" + end + end +end + +class DnsTimeout # :nodoc: all + + include SecondsHandle + + def initialize(seconds) + if seconds.is_a? Numeric and seconds >= 0 + @timeout = seconds + else + raise DnsTimeoutArgumentError, "Invalid value for tcp timeout" + end + end + + def to_s + if @timeout == 0 + @output + else + @timeout.to_s + end + end + + def pretty_to_s + transform(@timeout) + end + + def timeout + unless block_given? + raise DnsTimeoutArgumentError, "Block required but missing" + end + if @timeout == 0 + yield + else + return Timeout.timeout(@timeout) do + yield + end + end + end +end + +class TcpTimeout < DnsTimeout # :nodoc: all + def initialize(seconds) + @output = "infinite" + super(seconds) + end +end + +class UdpTimeout < DnsTimeout # :nodoc: all + def initialize(seconds) + @output = "not defined" + super(seconds) + end +end + +class DnsTimeoutArgumentError < ArgumentError # :nodoc: all +end diff --git a/lib/net/dns/rr.rb b/lib/net/dns/rr.rb new file mode 100644 index 0000000..bf91dde --- /dev/null +++ b/lib/net/dns/rr.rb @@ -0,0 +1,406 @@ +# +# $Id: RR.rb,v 1.19 2006/07/28 07:33:36 bluemonk Exp $ +# + +require 'net/dns/names/names' +require 'net/dns/rr/types' +require 'net/dns/rr/classes' + + +%w[a ns mx cname txt soa ptr aaaa mr].each do |file| + require "net/dns/rr/#{file}" +end + +module Net # :nodoc: + module DNS + + # =Name + # + # Net::DNS::RR - DNS Resource Record class + # + # =Synopsis + # + # require 'net/dns/rr' + # + # =Description + # + # The Net::DNS::RR is the base class for DNS Resource + # Record (RR) objects. A RR is a pack of data that represents + # resources for a DNS zone. The form in which this data is + # shows can be drawed as follow: + # + # "name ttl class type data" + # + # The +name+ is the name of the resource, like an canonical + # name for an +A+ record (internet ip address). The +ttl+ is the + # time to live, expressed in seconds. +type+ and +class+ are + # respectively the type of resource (+A+ for ip addresses, +NS+ + # for nameservers, and so on) and the class, which is almost + # always +IN+, the Internet class. At the end, +data+ is the + # value associated to the name for that particular type of + # resource record. An example: + # + # # A record for IP address + # "www.example.com 86400 IN A 172.16.100.1" + # + # # NS record for name server + # "www.example.com 86400 IN NS ns.example.com" + # + # A new RR object can be created in 2 ways: passing a string + # such the ones above, or specifying each field as the pair + # of an hash. See the Net::DNS::RR.new method for details. + # + # =Error classes + # + # Some error classes has been defined for the Net::DNS::RR class, + # which are listed here to keep a light and browsable main documentation. + # We have: + # + # * RRArgumentError: Generic argument error for class Net::DNS::RR + # * RRDataError: Error in parsing binary data, maybe from a malformed packet + # + # =Copyright + # + # Copyright (c) 2006 Marco Ceresa + # + # All rights reserved. This program is free software; you may redistribute + # it and/or modify it under the same terms as Ruby itself. + # + class RR + include Net::DNS::Names + + # Regexp matching an RR string + RR_REGEXP = Regexp.new("^\\s*(\\S+)\\s*(\\d+)?\\s+(" + + Net::DNS::RR::Classes.regexp + + "|CLASS\\d+)?\\s*(" + + Net::DNS::RR::Types.regexp + + "|TYPE\\d+)?\\s*(.*)$", Regexp::IGNORECASE) + + # Dimension of the sum of class, type, TTL and rdlength fields in a + # RR portion of the packet, in bytes + RRFIXEDSZ = 10 + + # Name of the RR + attr_reader :name + # TTL time (in seconds) of the RR + attr_reader :ttl + # Data belonging to that appropriate class, + # not to be used (use real accessors instead) + attr_reader :rdata + + # Create a new instance of Net::DNS::RR class, or an instance of + # any of the subclass of the appropriate type. + # + # Argument can be a string or an hash. With a sting, we can pass + # a RR resource record in the canonical format: + # + # a = Net::DNS::RR.new("foo.example.com. 86400 A 10.1.2.3") + # mx = Net::DNS::RR.new("example.com. 7200 MX 10 mailhost.example.com.") + # cname = Net::DNS::RR.new("www.example.com 300 IN CNAME www1.example.com") + # txt = Net::DNS::RR.new('baz.example.com 3600 HS TXT "text record"') + # + # Incidentally, +a+, +mx+, +cname+ and +txt+ objects will be instances of + # respectively Net::DNS::RR::A, Net::DNS::RR::MX, Net::DNS::RR::CNAME and + # Net::DNS::RR::TXT classes. + # + # The name and RR data are required; all other informations are optional. + # If omitted, the +TTL+ defaults to 10800, +type+ default to +A+ and the RR class + # defaults to +IN+. Omitting the optional fields is useful for creating the + # empty RDATA sections required for certain dynamic update operations. + # All names must be fully qualified. The trailing dot (.) is optional. + # + # The preferred method is however passing an hash with keys and values: + # + # rr = Net::DNS::RR.new( + # :name => "foo.example.com", + # :ttl => 86400, + # :cls => "IN", + # :type => "A", + # :address => "10.1.2.3" + # ) + # + # rr = Net::DNS::RR.new( + # :name => "foo.example.com", + # :rdata => "10.1.2.3" + # ) + # + # Name and data are required; all the others fields are optionals like + # we've seen before. The data field can be specified either with the + # right name of the resource (+:address+ in the example above) or with + # the generic key +:rdata+. Consult documentation to find the exact name + # for the resource in each subclass. + # + def initialize(arg) + case arg + when String + instance = new_from_string(arg) + when Hash + instance = new_from_hash(arg) + else + raise RRArgumentError, "Invalid argument, must be a RR string or an hash of values" + end + + if @type.to_s == "ANY" + @cls = Net::DNS::RR::Classes.new("IN") + end + + build_pack + set_type + + instance + end + + # Return a new RR object of the correct type (like Net::DNS::RR::A + # if the type is A) from a binary string, usually obtained from + # network stream. + # + # This method is used when parsing a binary packet by the Packet + # class. + # + def RR.parse(data) + o = allocate + obj,offset = o.send(:new_from_binary, data, 0) + return obj + end + + # Same as RR.parse, but takes an entire packet binary data to + # perform name expansion. Default when analizing a packet + # just received from a network stream. + # + # Return an instance of appropriate class and the offset + # pointing at the end of the data parsed. + # + def RR.parse_packet(data,offset) + o = allocate + o.send(:new_from_binary,data,offset) + end + + # Return the RR object in binary data format, suitable + # for using in network streams, with names compressed. + # Must pass as arguments the offset inside the packet + # and an hash of compressed names. + # + # This method is to be used in other classes and is + # not intended for user space programs. + # + # TO FIX in one of the future releases + # + def comp_data(offset,compnames) + type,cls = @type.to_i, @cls.to_i + str,offset,names = dn_comp(@name,offset,compnames) + str += [type,cls,@ttl,@rdlength].pack("n2 N n") + offset += Net::DNS::RRFIXEDSZ + return str,offset,names + end + + # Return the RR object in binary data format, suitable + # for using in network streams. + # + # raw_data = rr.data + # puts "RR is #{raw_data.size} bytes long" + # + def data + type,cls = @type.to_i, @cls.to_i + str = pack_name(@name) + return str + [type,cls,@ttl,@rdlength].pack("n2 N n") + get_data + end + + # Canonical inspect method + # + # mx = Net::DNS::RR.new("example.com. 7200 MX 10 mailhost.example.com.") + # #=> example.com. 7200 IN MX 10 mailhost.example.com. + # + def inspect + data = get_inspect + # Returns the preformatted string + if @name.size < 24 + [@name, @ttl.to_s, @cls.to_s, @type.to_s, + data].pack("A24 A8 A8 A8 A*") + else + to_a.join(" ") + end + end + + # Returns the RR in a string format. + # + # mx = Net::DNS::RR.new("example.com. 7200 MX 10 mailhost.example.com.") + # mx.to_s + # #=> "example.com. 7200 IN MX 10 mailhost.example.com." + # + def to_s + "#{self.inspect}" + end + + # Returns an array with all the fields for the RR record. + # + # mx = Net::DNS::RR.new("example.com. 7200 MX 10 mailhost.example.com.") + # mx.to_a + # #=> ["example.com.",7200,"IN","MX","10 mailhost.example.com."] + # + def to_a + [@name,@ttl,@cls.to_s,@type.to_s,get_inspect] + end + + # Type accessor + def type + @type.to_s + end + + # Class accessor + def cls + @cls.to_s + end + + private + + #--- + # New RR with argument in string form + #--- + def new_from_string(rrstring) + + unless rrstring =~ RR_REGEXP + raise RRArgumentError, + "Format error for RR string (maybe CLASS and TYPE not valid?)" + end + + # Name of RR - mandatory + begin + @name = $1.downcase + rescue NoMethodError + raise RRArgumentError, "Missing name field in RR string #{rrstring}" + end + + # Time to live for RR, default 3 hours + @ttl = $2 ? $2.to_i : 10800 + + # RR class, default to IN + @cls = Net::DNS::RR::Classes.new $3 + + # RR type, default to A + @type = Net::DNS::RR::Types.new $4 + + # All the rest is data + @rdata = $5 ? $5.strip : "" + + if self.class == Net::DNS::RR + (eval "Net::DNS::RR::#@type").new(rrstring) + else + subclass_new_from_string(@rdata) + self.class + end + end + + def new_from_hash(args) + + # Name field is mandatory + unless args.has_key? :name + raise RRArgumentError, "RR argument error: need at least RR name" + end + + @name = args[:name].downcase + @ttl = args[:ttl] ? args[:ttl].to_i : 10800 # Default 3 hours + @type = Net::DNS::RR::Types.new args[:type] + @cls = Net::DNS::RR::Classes.new args[:cls] + + @rdata = args[:rdata] ? args[:rdata].strip : "" + @rdlength = args[:rdlength] || @rdata.size + + if self.class == Net::DNS::RR + (eval "Net::DNS::RR::#@type").new(args) + else + hash = args - [:name,:ttl,:type,:cls] + if hash.has_key? :rdata + subclass_new_from_string(hash[:rdata]) + else + subclass_new_from_hash(hash) + end + self.class + end + end # new_from_hash + + def new_from_binary(data,offset) + if self.class == Net::DNS::RR + temp = dn_expand(data,offset)[1] + type = Net::DNS::RR::Types.new data.unpack("@#{temp} n")[0] + (eval "Net::DNS::RR::#{type}").parse_packet(data,offset) + else + @name,offset = dn_expand(data,offset) + rrtype,cls,@ttl,@rdlength = data.unpack("@#{offset} n2 N n") + @type = Net::DNS::RR::Types.new rrtype + @cls = Net::DNS::RR::Classes.new cls + offset += RRFIXEDSZ + offset = subclass_new_from_binary(data,offset) + build_pack + set_type + return [self,offset] + end +# rescue StandardError => err +# raise RRDataError, "Caught exception, maybe packet malformed: #{err}" + end + + # Methods to be overridden by subclasses + def subclass_new_from_array(arr) + end + def subclass_new_from_string(str) + end + def subclass_new_from_hash(hash) + end + def subclass_new_from_binary(data,offset) + end + def build_pack + end + def set_type + end + def get_inspect + @rdata + end + def get_data + @rdata + end + + # NEW new method :) + def self.new(*args) + o = allocate + obj = o.send(:initialize,*args) + if self == Net::DNS::RR + return obj + else + return o + end + end + + end # class RR + + end # module DNS +end # module Net + +class RRArgumentError < ArgumentError # :nodoc: +end +class RRDataError < StandardError # :nodoc: +end + +module ExtendHash # :nodoc: + + # Performs a sort of group difference + # operation on hashes or arrays + # + # a = {:a=>1,:b=>2,:c=>3} + # b = {:a=>1,:b=>2} + # c = [:a,:c] + # a-b #=> {:c=>3} + # a-c #=> {:b=>2} + # + def -(oth) + case oth + when Hash + delete_if {|k,v| oth.has_key? k} + when Array + delete_if {|k,v| oth.include? k} + end + end +end + +class Hash # :nodoc: + include ExtendHash +end + diff --git a/lib/net/dns/rr/a.rb b/lib/net/dns/rr/a.rb new file mode 100644 index 0000000..99e360f --- /dev/null +++ b/lib/net/dns/rr/a.rb @@ -0,0 +1,121 @@ +## +# +# Net::DNS::RR::A +# +# $id$ +# +## + +require 'ipaddr' + +module Net # :nodoc: + module DNS + + class RR + + # =Name + # + # Net::DNS::RR::A DNS A resource record + # + # =Synopsis + # + # require "net/dns/rr" + # + # =Description + # + # Net::DNS::RR::A is the class to handle resource records of type A, the + # most common in a DNS query. Its resource data is an IPv4 (i.e. 32 bit + # long) address, hold in the instance variable +address+. + # a = Net::DNS::RR::A.new("localhost.movie.edu. 360 IN A 127.0.0.1") + # + # a = Net::DNS::RR::A.new(:name => "localhost.movie.edu.", + # :ttl => 360, + # :cls => Net::DNS::IN, + # :type => Net::DNS::A, + # :address => "127.0.0.1") + # + # When computing binary data to trasmit the RR, the RDATA section is an + # Internet address expressed as four decimal numbers separated by dots + # without any imbedded spaces (e.g.,"10.2.0.52" or "192.0.5.6"). + # + class A < RR + attr_reader :address + + # Assign to the RR::A object a new IPv4 address, which can be in the + # form of a string or an IPAddr object + # + # a.address = "192.168.0.1" + # a.address = IPAddr.new("10.0.0.1") + # + def address=(addr) + @address = check_address addr + build_pack + end # address= + + private + + def check_address(addr) + address = "" + case addr + when String + address = IPAddr.new addr + when Integer # Address in numeric form + tempAddr = [(addr>>24),(addr>>16)&0xFF,(addr>>8)&0xFF,addr&0xFF] + tempAddr = tempAddr.collect {|x| x.to_s}.join(".") + address = IPAddr.new tempAddr + when IPAddr + address = addr + else + raise RRArgumentError, "Unknown address type: #{addr}" + end + raise RRArgumentError, "Must specify an IPv4 address" unless address.ipv4? + address + rescue ArgumentError + raise RRArgumentError, "Invalid address #{addr}" + end + + def build_pack + @address_pack = @address.hton + @rdlength = @address_pack.size + end + + def set_type + @type = Net::DNS::RR::Types.new("A") + end + + def get_data + @address_pack + end + + def get_inspect + "#@address" + end + + def subclass_new_from_hash(args) + if args.has_key? :address + @address = check_address args[:address] + elsif args.has_key? :rdata + @address = check_address args[:rdata] + else + # Address field is mandatory + raise RRArgumentError, ":address field is mandatory but missing" + end + end + + def subclass_new_from_string(str) + @address = check_address(str) + end + + def subclass_new_from_binary(data,offset) + a,b,c,d = data.unpack("@#{offset} CCCC") + @address = IPAddr.new "#{a}.#{b}.#{c}.#{d}" + return offset + 4 + end + + end # class A + + end # class RR + end # module DNS +end # module Net + + diff --git a/lib/net/dns/rr/aaaa.rb b/lib/net/dns/rr/aaaa.rb new file mode 100644 index 0000000..72dabcb --- /dev/null +++ b/lib/net/dns/rr/aaaa.rb @@ -0,0 +1,92 @@ +## +# +# Net::DNS::RR::AAAA +# +# $id$ +# +## + +require 'ipaddr' + +module Net + module DNS + + class RR + + # + # RR type AAAA + # + class AAAA < RR + attr_reader :address + + # Assign to the RR::AAAA object a new IPv6 address, which can be in the + # form of a string or an IPAddr object + # + # a.address = "::1" + # a.address = IPAddr.new("::1") + # + def address=(addr) + @address = check_address addr + build_pack + end # address= + + private + + def check_address(addr) + address = "" + case addr + when String + address = IPAddr.new addr + when IPAddr + address = addr + else + raise RRArgumentError, "Unknown address type: #{addr.inspect}" + end + raise RRArgumentError, "Must specify an IPv6 address" unless address.ipv6? + address + rescue ArgumentError + raise RRArgumentError, "Invalid address #{addr.inspect}" + end + + def build_pack + @address_pack = @address.hton + @rdlength = @address_pack.size + end + + def set_type + @type = Net::DNS::RR::Types.new("AAAA") + end + + def get_data + @address_pack + end + + def get_inspect + "#@address" + end + + def subclass_new_from_hash(args) + if args.has_key? :address + @address = check_address args[:address] + else + raise RRArgumentError, ":address field is mandatory but missing" + end + end + + def subclass_new_from_string(str) + @address = check_address(str) + end + + def subclass_new_from_binary(data,offset) + arr = data.unpack("@#{offset} n8") + @address = IPAddr.new sprintf("%x:%x:%x:%x:%x:%x:%x:%x",*arr) + return offset + 16 + end + + end # class AAAA + + end # class RR + end # module DNS +end # module Net + + diff --git a/lib/net/dns/rr/classes.rb b/lib/net/dns/rr/classes.rb new file mode 100644 index 0000000..25fd0c0 --- /dev/null +++ b/lib/net/dns/rr/classes.rb @@ -0,0 +1,148 @@ +module Net # :nodoc: + module DNS + + class RR + + # + # This is an auxiliary class to hadle RR class field in a DNS packet. + # + class Classes + + # An hash with the values of each RR class stored with the + # respective id number + Classes = { + 'IN' => 1, # RFC 1035 + 'CH' => 3, # RFC 1035 + 'HS' => 4, # RFC 1035 + 'NONE' => 254, # RFC 2136 + 'ANY' => 255, # RFC 1035 + } + + # The default value when class is nil in Resource Records + @@default = Classes["IN"] + + # Be able to control the default class to assign when + # cls argument is +nil+. Default to +IN+ + def self.default=(str) + if Classes.has_key? str + @@default = Classes[str] + else + raise ClassArgumentError, "Unknown class #{str}" + end + end + + # Checks whether +cls+ is a valid RR class. + def self.valid?(cls) + case cls + when String + return Classes.has_key?(cls) + when Fixnum + return Classes.invert.has_key?(cls) + else + raise ClassArgumentError, "Wrong cls class: #{cls.class}" + end + end + + # Returns the class in string format, as "IN" or "CH", + # given the numeric value + def self.to_str(cls) + case cls + when Fixnum + if Classes.invert.has_key? cls + return Classes.invert[cls] + else + raise ClassArgumentError, "Unknown class number #{cls}" + end + else + raise ClassArgumentError, "Wrong cls class: #{cls.class}" + end + end + + # Gives in output the keys from the +Classes+ hash + # in a format suited for regexps + def self.regexp + Classes.keys.join("|") + end + + # Creates a new object representing an RR class. Performs some + # checks on the argument validity too. Il +cls+ is +nil+, the + # default value is +ANY+ or the one set with Classes.default= + def initialize(cls) + case cls + when String + # type in the form "A" or "NS" + new_from_string(cls.upcase) + when Fixnum + # type in numeric form + new_from_num(cls) + when nil + # default type, control with Classes.default= + @str = Classes.invert[@@default] + @num = @@default + else + raise ClassArgumentError, "Wrong cls class: #{cls.class}" + end + end + + # Constructor for string data class, + # *PRIVATE* method + def new_from_string(cls) + case cls + when /^CLASS\\d+/ + # TODO!!! + else + # String with name of class + if Classes.has_key? cls + @str = cls + @num = Classes[cls] + else + raise ClassesArgumentError, "Unknown cls #{cls}" + end + end + end + + # Contructor for numeric data class + # *PRIVATE* method + def new_from_num(cls) + if Classes.invert.has_key? cls + @num = cls + @str = Classes.invert[cls] + else + raise ClassesArgumentError, "Unkown cls number #{cls}" + end + end + + # Returns the class in number format + # (default for normal use) + def inspect + @num + end + + # Returns the class in string format, + # i.d. "IN" or "CH" or such a string. + def to_s + @str + end + + # Returns the class in numeric format, + # usable by the pack methods for data transfers + def to_i + @num.to_i + end + + + # Should be used only for testing purpouses + def to_str + @num.to_s + end + + private :new_from_num, :new_from_string + + end # class Classes + + end # class RR + end # module DNS +end # module Net + +class ClassArgumentError < ArgumentError # :nodoc: +end diff --git a/lib/net/dns/rr/cname.rb b/lib/net/dns/rr/cname.rb new file mode 100644 index 0000000..1a2bf94 --- /dev/null +++ b/lib/net/dns/rr/cname.rb @@ -0,0 +1,69 @@ +## +# +# Net::DNS::RR::CNAME +# +# $Id: CNAME.rb,v 1.7 2006/07/28 07:33:36 bluemonk Exp $ +# +## + +module Net + module DNS + + class RR + + #------------------------------------------------------------ + # RR type CNAME + #------------------------------------------------------------ + class CNAME < RR + attr_reader :cname + + private + + def check_name(name) + unless name =~ /(\w\.?)+\s*$/ and name =~ /[a-zA-Z]/ + raise RRArgumentError, "Canonical Name not valid: #{name}" + end + name + end + + def build_pack + @cname_pack = pack_name(@cname) + @rdlength = @cname_pack.size + end + + def set_type + @type = Net::DNS::RR::Types.new("CNAME") + end + + def get_data + @cname_pack + end + + def get_inspect + "#@cname" + end + + def subclass_new_from_hash(args) + if args.has_key? :cname + @cname = check_name args[:cname] + else + raise RRArgumentError, ":cname field is mandatory but missing" + end + end + + def subclass_new_from_string(str) + @cname = check_name(str) + end + + def subclass_new_from_binary(data,offset) + @cname,offset = dn_expand(data,offset) + return offset + end + + end # class CNAME + + end # class RR + end # module DNS +end # module Net + + diff --git a/lib/net/dns/rr/hinfo.rb b/lib/net/dns/rr/hinfo.rb new file mode 100644 index 0000000..688a10f --- /dev/null +++ b/lib/net/dns/rr/hinfo.rb @@ -0,0 +1,74 @@ +## +# +# Net::DNS::RR::HINFO +# +# $Id: HINFO.rb,v 1.4 2006/07/28 07:33:36 bluemonk Exp $ +# +## + +module Net + module DNS + class RR + + #------------------------------------------------------------ + # RR type HINFO + #------------------------------------------------------------ + class HINFO < RR + attr_reader :cpu, :os + + private + + def check_hinfo(str) + if str.strip =~ /^["'](.*?)["']\s+["'](.*?)["']$/ + return $1,$2 + else + raise RRArgumentError, "HINFO section not valid: #{str.inspect}" + end + end + + def build_pack + @hinfo_pack = [@cpu.size].pack("C") + @cpu + @hinfo_pack += [@os.size].pack("C") + @os + @rdlength = @hinfo_pack.size + end + + def set_type + @type = Net::DNS::RR::Types.new("HINFO") + end + + def get_data + @hinfo_pack + end + + def get_inspect + "#@cpu #@os" + end + + def subclass_new_from_hash(args) + if args.has_key? :cpu and args.has_key? :os + @cpu = args[:cpu] + @os = args[:os] + else + raise RRArgumentError, ":cpu and :os fields are mandatory but missing" + end + end + + def subclass_new_from_string(str) + @cpu,@os = check_hinfo(str) + end + + def subclass_new_from_binary(data,offset) + len = data.unpack("@#{offset} C")[0] + @cpu = data[offset+1..offset+1+len] + offset += len+1 + len = @data.unpack("@#{offset} C")[0] + @os = data[offset+1..offset+1+len] + return offset += len+1 + end + + end # class HINFO + + end # class RR + end # module DNS +end # module Net + diff --git a/lib/net/dns/rr/mr.rb b/lib/net/dns/rr/mr.rb new file mode 100644 index 0000000..57e81fc --- /dev/null +++ b/lib/net/dns/rr/mr.rb @@ -0,0 +1,68 @@ +## +# +# Net::DNS::RR::MR +# +# $Id: MR.rb,v 1.4 2006/07/28 07:33:36 bluemonk Exp $ +# +## + +module Net + module DNS + + class RR + + #------------------------------------------------------------ + # RR type MR + #------------------------------------------------------------ + class MR < RR + attr_reader :newname + + private + + def check_name(name) + unless name =~ /(\w\.?)+\s*$/ + raise RRArgumentError, "Name not valid: #{name.inspect}" + end + name + end + + def build_pack + @newname_pack = pack_name(@newname) + @rdlength = @newname_pack.size + end + + def set_type + @type = Net::DNS::RR::Types.new("MR") + end + + def get_data + @newname_pack + end + + def get_inspect + "#@newname" + end + + def subclass_new_from_hash(args) + if args.has_key? :newname + @newname = check_name args[:newname] + else + raise RRArgumentError, ":newname field is mandatory but missing" + end + end + + def subclass_new_from_string(str) + @newname = check_name(str) + end + + def subclass_new_from_array(data,offset) + @newname = dn_expand(data,offset) + return offset + end + + end # class MR + + end # class RR + end # module DNS +end # module Net + diff --git a/lib/net/dns/rr/mx.rb b/lib/net/dns/rr/mx.rb new file mode 100644 index 0000000..3da050b --- /dev/null +++ b/lib/net/dns/rr/mx.rb @@ -0,0 +1,74 @@ +## +# +# Net::DNS::RR::MX +# +# $Id: MX.rb,v 1.8 2006/07/28 07:33:36 bluemonk Exp $ +# +## + + +module Net + module DNS + class RR + + #------------------------------------------------------------ + # RR type MX + #------------------------------------------------------------ + class MX < RR + attr_reader :preference, :exchange + + private + + def check_mx(str) + if str.strip =~ /^(\d+)\s+(\S+)$/ + return $1.to_i,$2 + else + raise RRArgumentError, "MX section not valid" + end + end + + def build_pack + @mx_pack = [@preference].pack("n") + pack_name(@exchange) + @rdlength = @mx_pack.size + end + + def set_type + @type = Net::DNS::RR::Types.new("MX") + end + + def get_data + @mx_pack + end + + def get_inspect + "#@preference #@exchange" + end + + def subclass_new_from_hash(args) + if args.has_key? :preference and args.has_key? :exchange + @preference = args[0][:preference].to_i + @exchange = args[0][:exchange] + else + raise RRArgumentError, ":preference and :exchange fields are mandatory but missing" + end + end + + def subclass_new_from_string(str) + @preference,@exchange = check_mx(str) + end + + def subclass_new_from_binary(data,offset) + @preference = data.unpack("@#{offset} n")[0] + offset += 2 + @exchange,offset = dn_expand(data,offset) + return offset + end + + end # class MX + + end # class RR + end # module DNS +end # module Net + + + diff --git a/lib/net/dns/rr/ns.rb b/lib/net/dns/rr/ns.rb new file mode 100644 index 0000000..1999f9e --- /dev/null +++ b/lib/net/dns/rr/ns.rb @@ -0,0 +1,70 @@ +## +# +# Net::DNS::RR::NS +# +# $Id: NS.rb,v 1.8 2006/07/28 07:33:36 bluemonk Exp $ +# +## + +module Net + module DNS + + class RR + + #------------------------------------------------------------ + # RR type NS + #------------------------------------------------------------ + class NS < RR + attr_reader :nsdname + + private + + def check_name(name) + unless name =~ /(\w\.?)+\s*$/ and name =~ /[a-zA-Z]/ + raise RRArgumentError, "NS Domain Name not valid: #{name}" + end + name + end + + def build_pack + @nsdname_pack = pack_name(@nsdname) + @rdlength = @nsdname_pack.size + end + + def set_type + @type = Net::DNS::RR::Types.new("NS") + end + + def get_data + @nsdname_pack + end + + def get_inspect + "#@nsdname" + end + + def subclass_new_from_hash(args) + if args.has_key? :nsdname + @nsdname = check_name args[:nsdname] + else + raise RRArgumentError, ":nsdname field is mandatory but missing" + end + end + + def subclass_new_from_string(str) + @nsdname = check_name(str) + end + + def subclass_new_from_binary(data,offset) + @nsdname,offset = dn_expand(data,offset) + return offset + end + + end # class NS + + end # class RR + end # module DNS +end # module Net + + + diff --git a/lib/net/dns/rr/null.rb b/lib/net/dns/rr/null.rb new file mode 100644 index 0000000..2eeaab8 --- /dev/null +++ b/lib/net/dns/rr/null.rb @@ -0,0 +1,61 @@ +## +# +# Net::DNS::RR::NULL +# +# $Id: NULL.rb,v 1.5 2006/07/28 07:33:36 bluemonk Exp $ +# +## + + +module Net + module DNS + class RR + + #------------------------------------------------------------ + # RR type NULL + #------------------------------------------------------------ + class NULL < RR + attr_reader :null + + private + + def build_pack + @null_pack = @null + @rdlength = @null_pack.size + end + + def set_type + @type = Net::DNS::RR::RRTypes.new("NULL") + end + + def get_data + @null_pack + end + + def get_inspect + "#@null" + end + + def subclass_new_from_hash(args) + if args.has_key? :null + @null = args[:null] + else + raise RRArgumentError, ":null field is mandatory but missing" + end + end + + def subclass_new_from_string(str) + @null = str.strip + end + + def subclass_new_from_binary(data,offset) + @null = data[offset..offset+@rdlength] + return offset + @rdlength + end + + end # class NULL + + end # class RR + end # module DNS +end # module Net + diff --git a/lib/net/dns/rr/ptr.rb b/lib/net/dns/rr/ptr.rb new file mode 100644 index 0000000..cf6c2b4 --- /dev/null +++ b/lib/net/dns/rr/ptr.rb @@ -0,0 +1,71 @@ +## +# +# Net::DNS::RR::PTR +# +# $Id: PTR.rb,v 1.5 2006/07/28 07:33:36 bluemonk Exp $ +# +## + +module Net + module DNS + class RR + + #------------------------------------------------------------ + # RR type PTR + #------------------------------------------------------------ + class PTR < RR + + # Getter for PTR resource + def ptr + @ptrdname.to_s + end + alias_method :ptrdname, :ptr + + private + + def check_ptr(str) + IPAddr.new str + rescue + raise RRArgumentError, "PTR section not valid" + end + + def build_pack + @ptrdname_pack = pack_name(@ptrdname) + @rdlength = @ptrdname_pack.size + end + + def set_type + @type = Net::DNS::RR::Types.new("PTR") + end + + def get_data + @ptrdname_pack + end + + def get_inspect + "#@ptrdname" + end + + def subclass_new_from_hash(args) + if args.has_key? :ptrdname or args.has_key? :ptr + @ptrdname = args[0][:ptrdname] + else + raise RRArgumentError, ":ptrdname or :ptr field is mandatory but missing" + end + end + + def subclass_new_from_string(str) + @ptrdname = check_ptr(str) + end + + def subclass_new_from_binary(data,offset) + @ptrdname,offset = dn_expand(data,offset) + return offset + end + + end # class PTR + + end # class RR + end # module DNS +end # module Net + diff --git a/lib/net/dns/rr/soa.rb b/lib/net/dns/rr/soa.rb new file mode 100644 index 0000000..05c7ae3 --- /dev/null +++ b/lib/net/dns/rr/soa.rb @@ -0,0 +1,85 @@ +## +# +# Net::DNS::RR::SOA +# +# $Id: SOA.rb,v 1.4 2006/07/28 07:33:36 bluemonk Exp $ +# +## + +module Net + module DNS + class RR + + #------------------------------------------------------------ + # RR type SOA + #------------------------------------------------------------ + class SOA < RR + attr_reader :mname, :rname, :serial, :refresh, :retry, :expire, :minimum + + private + + def build_pack + @soa_pack = pack_name(@mname) + @soa_pack += pack_name(@rname) + @soa_pack += [@serial,@refresh,@retry,@expire,@minimum].pack("N5") + end + + def set_type + @type = Net::DNS::RR::Types.new("SOA") + end + + def get_data + @soa_pack + end + + def get_inspect + "#@mname #@rname #@serial #@refresh #@retry #@expire #@minimum" + end + + def subclass_new_from_hash(args) + if args.has_key? :rdata + subclass_new_from_string(args[:rdata]) + else + [:mname,:rname,:serial,:refresh,:retry,:expire,:minimum].each do |key| + raise RRArgumentError, "Missing field :#{key}" unless args.has_key? key + end + @mname = args[:mname] if valid? args[:mname] + @rname = args[:rname] if valid? args[:rname] + @serial = args[:serial] if number? args[:serial] + @refresh = args[:refresh] if number? args[:refresh] + @retry = args[:retry] if number? args[:retry] + @expire = args[:expire] if number? args[:expire] + @minimum = args[:minimum] if number? args[:minimum] + end + end + + def number?(num) + if num.kind_of? Integer and num > 0 + true + else + raise RRArgumentError, "Wrong format field: #{num} not a number or less than zero" + end + end + + def subclass_new_from_string(str) + mname,rname,serial,refresh,ret,expire,minimum = str.strip.split(" ") + @mname = mname if valid? mname + @rname = rname if valid? rname + @serial,@refresh,@retry,@expire,@minimum = [serial,refresh,ret,expire,minimum].collect do |i| + i.to_i if valid? i.to_i + end + end + + def subclass_new_from_binary(data,offset) + @mname,offset = dn_expand(data,offset) + @rname,offset = dn_expand(data,offset) + @serial,@refresh,@retry,@expire,@minimum = data.unpack("@#{offset} N5") + return offset + 5*Net::DNS::INT32SZ + end + + end # class SOA + + end # class RR + end # module DNS +end # module Net + diff --git a/lib/net/dns/rr/srv.rb b/lib/net/dns/rr/srv.rb new file mode 100644 index 0000000..eaa52a9 --- /dev/null +++ b/lib/net/dns/rr/srv.rb @@ -0,0 +1,57 @@ +## +# +# Net::DNS::RR::SRV +# +# $Id$ +# +## + + +module Net + module DNS + class RR + + #------------------------------------------------------------ + # RR type SRV + #------------------------------------------------------------ + class SRV < RR + + attr_reader :priority, :weight, :port, :host + + private + + def build_pack + str = "" + end + + def set_type + @type = Net::DNS::RR::Types.new("SRV") + end + + def subclass_new_from_binary(data,offset) + off_end = offset + @rdlength + @priority, @weight, @port = data.unpack("@#{offset} n n n") + offset+=6 + + @host=[] + while offset < off_end + len = data.unpack("@#{offset} C")[0] + offset += 1 + str = data[offset..offset+len-1] + offset += len + @host << str + end + @host=@host.join(".") + offset + end + + + end # class SRV + end # class RR + + + end # module DNS +end # module Net + + + diff --git a/lib/net/dns/rr/txt.rb b/lib/net/dns/rr/txt.rb new file mode 100644 index 0000000..c182f5f --- /dev/null +++ b/lib/net/dns/rr/txt.rb @@ -0,0 +1,72 @@ +## +# +# Net::DNS::RR::TXT +# +# $Id: TXT.rb,v 1.4 2006/07/28 07:33:36 bluemonk Exp $ +# +## + + +module Net + module DNS + class RR + + #------------------------------------------------------------ + # RR type TXT + #------------------------------------------------------------ + class TXT < RR + attr_reader :txt + + private + + def build_pack + str = "" + @txt.split(" ").each do |txt| + str += [txt.length,txt].pack("C a*") + end + @txt_pack = str + @rdlength = @txt_pack.size + end + + def set_type + @type = Net::DNS::RR::Types.new("TXT") + end + + def get_data + @txt_pack + end + + def subclass_new_from_hash(args) + if args.has_key? :txt + @txt = args[:txt].strip + else + raise RRArgumentError, ":txt field is mandatory but missing" + end + end + + def subclass_new_from_string(str) + @txt = str.strip + end + + def subclass_new_from_binary(data,offset) + off_end = offset + @rdlength + @txt = "" + while offset < off_end + len = data.unpack("@#{offset} C")[0] + offset += 1 + str = data[offset..offset+len-1] + offset += len + @txt << str << " " + end + return offset + end + + end # class TXT + + end # class RR + end # module DNS +end # module Net + + + + diff --git a/lib/net/dns/rr/types.rb b/lib/net/dns/rr/types.rb new file mode 100644 index 0000000..57f19a8 --- /dev/null +++ b/lib/net/dns/rr/types.rb @@ -0,0 +1,200 @@ +module Net # :nodoc: + module DNS + + class RR + + # + # This is an auxiliary class to hadle RR type field in a DNS packet. + # + class Types + + # :nodoc: + Types = { # :nodoc: + 'SIGZERO' => 0, # RFC2931 consider this a pseudo type + 'A' => 1, # RFC 1035, Section 3.4.1 + 'NS' => 2, # RFC 1035, Section 3.3.11 + 'MD' => 3, # RFC 1035, Section 3.3.4 (obsolete) + 'MF' => 4, # RFC 1035, Section 3.3.5 (obsolete) + 'CNAME' => 5, # RFC 1035, Section 3.3.1 + 'SOA' => 6, # RFC 1035, Section 3.3.13 + 'MB' => 7, # RFC 1035, Section 3.3.3 + 'MG' => 8, # RFC 1035, Section 3.3.6 + 'MR' => 9, # RFC 1035, Section 3.3.8 + 'NULL' => 10, # RFC 1035, Section 3.3.10 + 'WKS' => 11, # RFC 1035, Section 3.4.2 (deprecated) + 'PTR' => 12, # RFC 1035, Section 3.3.12 + 'HINFO' => 13, # RFC 1035, Section 3.3.2 + 'MINFO' => 14, # RFC 1035, Section 3.3.7 + 'MX' => 15, # RFC 1035, Section 3.3.9 + 'TXT' => 16, # RFC 1035, Section 3.3.14 + 'RP' => 17, # RFC 1183, Section 2.2 + 'AFSDB' => 18, # RFC 1183, Section 1 + 'X25' => 19, # RFC 1183, Section 3.1 + 'ISDN' => 20, # RFC 1183, Section 3.2 + 'RT' => 21, # RFC 1183, Section 3.3 + 'NSAP' => 22, # RFC 1706, Section 5 + 'NSAP_PTR' => 23, # RFC 1348 (obsolete) + # The following 2 RRs are impemented in Net::DNS::SEC, TODO + 'SIG' => 24, # RFC 2535, Section 4.1 + 'KEY' => 25, # RFC 2535, Section 3.1 + 'PX' => 26, # RFC 2163, + 'GPOS' => 27, # RFC 1712 (obsolete) + 'AAAA' => 28, # RFC 1886, Section 2.1 + 'LOC' => 29, # RFC 1876 + # The following RR is impemented in Net::DNS::SEC, TODO + 'NXT' => 30, # RFC 2535, Section 5.2 + 'EID' => 31, # draft-ietf-nimrod-dns-xx.txt + 'NIMLOC' => 32, # draft-ietf-nimrod-dns-xx.txt + 'SRV' => 33, # RFC 2052 + 'ATMA' => 34, # ??? + 'NAPTR' => 35, # RFC 2168 + 'KX' => 36, # RFC 2230 + 'CERT' => 37, # RFC 2538 + 'DNAME' => 39, # RFC 2672 + 'OPT' => 41, # RFC 2671 + # The following 4 RRs are impemented in Net::DNS::SEC TODO + 'DS' => 43, # draft-ietf-dnsext-delegation-signer + 'SSHFP' => 44, # draft-ietf-secsh-dns (No RFC # yet at time of coding) + 'RRSIG' => 46, # draft-ietf-dnsext-dnssec-2535typecode-change + 'NSEC' => 47, # draft-ietf-dnsext-dnssec-2535typecode-change + 'DNSKEY' => 48, # draft-ietf-dnsext-dnssec-2535typecode-change + 'UINFO' => 100, # non-standard + 'UID' => 101, # non-standard + 'GID' => 102, # non-standard + 'UNSPEC' => 103, # non-standard + 'TKEY' => 249, # RFC 2930 + 'TSIG' => 250, # RFC 2931 + 'IXFR' => 251, # RFC 1995 + 'AXFR' => 252, # RFC 1035 + 'MAILB' => 253, # RFC 1035 (MB, MG, MR) + 'MAILA' => 254, # RFC 1035 (obsolete - see MX) + 'ANY' => 255, # RFC 1035 + } + + # The default value when type is nil in Resource Records + @@default = Types["A"] + + # Be able to control the default type to assign when + # type is +nil+. Default to +A+ + def self.default=(str) + if Types.has_key? str + @@default = Types[str] + else + raise TypeArgumentError, "Unknown type #{str}" + end + end + + # Checks whether +type+ is a valid RR type. + def self.valid?(type) + case type + when String + return Types.has_key?(type) + when Fixnum + return Types.invert.has_key?(type) + else + raise TypeArgumentError, "Wrong type class: #{type.class}" + end + end + + # Returns the type in string format, as "A" or "NS", + # given the numeric value + def self.to_str(type) + case type + when Fixnum + if Types.invert.has_key? type + return Types.invert[type] + else + raise TypeArgumentError, "Unknown type number #{type}" + end + else + raise TypeArgumentError, "Wrong type class: #{type.class}" + end + end + + # Gives in output the keys from the +Types+ hash + # in a format suited for regexps + def self.regexp + Types.keys.join("|") + end + + # Creates a new object representing an RR type. Performs some + # checks on the argument validity too. Il +type+ is +nil+, the + # default value is +ANY+ or the one set with Types.default= + def initialize(type) + case type + when String + # type in the form "A" or "NS" + new_from_string(type.upcase) + when Fixnum + # type in numeric form + new_from_num(type) + when nil + # default type, control with Types.default= + @str = Types.invert[@@default] + @num = @@default + else + raise TypeArgumentError, "Wrong type class: #{type.class}" + end + end + + # Returns the type in number format + # (default for normal use) + def inspect + @num + end + + # Returns the type in string format, + # i.d. "A" or "NS" or such a string. + def to_s + @str + end + + # Returns the type in numeric format, + # usable by the pack methods for data transfers + def to_i + @num.to_i + end + + # Should be used only for testing purpouses + def to_str + @num.to_s + end + + private + + # Constructor for string data type, + # *PRIVATE* method + def new_from_string(type) + case type + when /^TYPE\\d+/ + # TODO!!! + else + # String with name of type + if Types.has_key? type + @str = type + @num = Types[type] + else + raise TypeArgumentError, "Unknown type #{type}" + end + end + end + + # Contructor for numeric data type + # *PRIVATE* method + def new_from_num(type) + if Types.invert.has_key? type + @num = type + @str = Types.invert[type] + else + raise TypeArgumentError, "Unkown type number #{type}" + end + end + + end # class Types + + end # class RR + end # module DNS +end # module Net + +class TypeArgumentError < ArgumentError # :nodoc: +end diff --git a/setup.rb b/setup.rb new file mode 100644 index 0000000..0807023 --- /dev/null +++ b/setup.rb @@ -0,0 +1,1360 @@ +# +# setup.rb +# +# Copyright (c) 2000-2004 Minero Aoki +# +# This program is free software. +# You can distribute/modify this program under the terms of +# the GNU LGPL, Lesser General Public License version 2.1. +# + +unless Enumerable.method_defined?(:map) # Ruby 1.4.6 + module Enumerable + alias map collect + end +end + +unless File.respond_to?(:read) # Ruby 1.6 + def File.read(fname) + open(fname) {|f| + return f.read + } + end +end + +def File.binread(fname) + open(fname, 'rb') {|f| + return f.read + } +end + +# for corrupted windows stat(2) +def File.dir?(path) + File.directory?((path[-1,1] == '/') ? path : path + '/') +end + + +class SetupError < StandardError; end + +def setup_rb_error(msg) + raise SetupError, msg +end + +# +# Config +# + +if arg = ARGV.detect {|arg| /\A--rbconfig=/ =~ arg } + ARGV.delete(arg) + require arg.split(/=/, 2)[1] + $".push 'rbconfig.rb' +else + require 'rbconfig' +end + +def multipackage_install? + FileTest.directory?(File.dirname($0) + '/packages') +end + + +class ConfigItem + def initialize(name, template, default, desc) + @name = name.freeze + @template = template + @value = default + @default = default.dup.freeze + @description = desc + end + + attr_reader :name + attr_reader :description + + attr_accessor :default + alias help_default default + + def help_opt + "--#{@name}=#{@template}" + end + + def value + @value + end + + def eval(table) + @value.gsub(%r<\$([^/]+)>) { table[$1] } + end + + def set(val) + @value = check(val) + end + + private + + def check(val) + setup_rb_error "config: --#{name} requires argument" unless val + val + end +end + +class BoolItem < ConfigItem + def config_type + 'bool' + end + + def help_opt + "--#{@name}" + end + + private + + def check(val) + return 'yes' unless val + unless /\A(y(es)?|n(o)?|t(rue)?|f(alse))\z/i =~ val + setup_rb_error "config: --#{@name} accepts only yes/no for argument" + end + (/\Ay(es)?|\At(rue)/i =~ value) ? 'yes' : 'no' + end +end + +class PathItem < ConfigItem + def config_type + 'path' + end + + private + + def check(path) + setup_rb_error "config: --#{@name} requires argument" unless path + path[0,1] == '$' ? path : File.expand_path(path) + end +end + +class ProgramItem < ConfigItem + def config_type + 'program' + end +end + +class SelectItem < ConfigItem + def initialize(name, template, default, desc) + super + @ok = template.split('/') + end + + def config_type + 'select' + end + + private + + def check(val) + unless @ok.include?(val.strip) + setup_rb_error "config: use --#{@name}=#{@template} (#{val})" + end + val.strip + end +end + +class PackageSelectionItem < ConfigItem + def initialize(name, template, default, help_default, desc) + super name, template, default, desc + @help_default = help_default + end + + attr_reader :help_default + + def config_type + 'package' + end + + private + + def check(val) + unless File.dir?("packages/#{val}") + setup_rb_error "config: no such package: #{val}" + end + val + end +end + +class ConfigTable_class + + def initialize(items) + @items = items + @table = {} + items.each do |i| + @table[i.name] = i + end + ALIASES.each do |ali, name| + @table[ali] = @table[name] + end + end + + include Enumerable + + def each(&block) + @items.each(&block) + end + + def key?(name) + @table.key?(name) + end + + def lookup(name) + @table[name] or raise ArgumentError, "no such config item: #{name}" + end + + def add(item) + @items.push item + @table[item.name] = item + end + + def remove(name) + item = lookup(name) + @items.delete_if {|i| i.name == name } + @table.delete_if {|name, i| i.name == name } + item + end + + def new + dup() + end + + def savefile + '.config' + end + + def load + begin + t = dup() + File.foreach(savefile()) do |line| + k, v = *line.split(/=/, 2) + t[k] = v.strip + end + t + rescue Errno::ENOENT + setup_rb_error $!.message + "#{File.basename($0)} config first" + end + end + + def save + @items.each {|i| i.value } + File.open(savefile(), 'w') {|f| + @items.each do |i| + f.printf "%s=%s\n", i.name, i.value if i.value + end + } + end + + def [](key) + lookup(key).eval(self) + end + + def []=(key, val) + lookup(key).set val + end + +end + +c = ::Config::CONFIG + +rubypath = c['bindir'] + '/' + c['ruby_install_name'] + +major = c['MAJOR'].to_i +minor = c['MINOR'].to_i +teeny = c['TEENY'].to_i +version = "#{major}.#{minor}" + +# ruby ver. >= 1.4.4? +newpath_p = ((major >= 2) or + ((major == 1) and + ((minor >= 5) or + ((minor == 4) and (teeny >= 4))))) + +if c['rubylibdir'] + # V < 1.6.3 + _stdruby = c['rubylibdir'] + _siteruby = c['sitedir'] + _siterubyver = c['sitelibdir'] + _siterubyverarch = c['sitearchdir'] +elsif newpath_p + # 1.4.4 <= V <= 1.6.3 + _stdruby = "$prefix/lib/ruby/#{version}" + _siteruby = c['sitedir'] + _siterubyver = "$siteruby/#{version}" + _siterubyverarch = "$siterubyver/#{c['arch']}" +else + # V < 1.4.4 + _stdruby = "$prefix/lib/ruby/#{version}" + _siteruby = "$prefix/lib/ruby/#{version}/site_ruby" + _siterubyver = _siteruby + _siterubyverarch = "$siterubyver/#{c['arch']}" +end +libdir = '-* dummy libdir *-' +stdruby = '-* dummy rubylibdir *-' +siteruby = '-* dummy site_ruby *-' +siterubyver = '-* dummy site_ruby version *-' +parameterize = lambda {|path| + path.sub(/\A#{Regexp.quote(c['prefix'])}/, '$prefix')\ + .sub(/\A#{Regexp.quote(libdir)}/, '$libdir')\ + .sub(/\A#{Regexp.quote(stdruby)}/, '$stdruby')\ + .sub(/\A#{Regexp.quote(siteruby)}/, '$siteruby')\ + .sub(/\A#{Regexp.quote(siterubyver)}/, '$siterubyver') +} +libdir = parameterize.call(c['libdir']) +stdruby = parameterize.call(_stdruby) +siteruby = parameterize.call(_siteruby) +siterubyver = parameterize.call(_siterubyver) +siterubyverarch = parameterize.call(_siterubyverarch) + +if arg = c['configure_args'].split.detect {|arg| /--with-make-prog=/ =~ arg } + makeprog = arg.sub(/'/, '').split(/=/, 2)[1] +else + makeprog = 'make' +end + +common_conf = [ + PathItem.new('prefix', 'path', c['prefix'], + 'path prefix of target environment'), + PathItem.new('bindir', 'path', parameterize.call(c['bindir']), + 'the directory for commands'), + PathItem.new('libdir', 'path', libdir, + 'the directory for libraries'), + PathItem.new('datadir', 'path', parameterize.call(c['datadir']), + 'the directory for shared data'), + PathItem.new('mandir', 'path', parameterize.call(c['mandir']), + 'the directory for man pages'), + PathItem.new('sysconfdir', 'path', parameterize.call(c['sysconfdir']), + 'the directory for man pages'), + PathItem.new('stdruby', 'path', stdruby, + 'the directory for standard ruby libraries'), + PathItem.new('siteruby', 'path', siteruby, + 'the directory for version-independent aux ruby libraries'), + PathItem.new('siterubyver', 'path', siterubyver, + 'the directory for aux ruby libraries'), + PathItem.new('siterubyverarch', 'path', siterubyverarch, + 'the directory for aux ruby binaries'), + PathItem.new('rbdir', 'path', '$siterubyver', + 'the directory for ruby scripts'), + PathItem.new('sodir', 'path', '$siterubyverarch', + 'the directory for ruby extentions'), + PathItem.new('rubypath', 'path', rubypath, + 'the path to set to #! line'), + ProgramItem.new('rubyprog', 'name', rubypath, + 'the ruby program using for installation'), + ProgramItem.new('makeprog', 'name', makeprog, + 'the make program to compile ruby extentions'), + SelectItem.new('shebang', 'all/ruby/never', 'ruby', + 'shebang line (#!) editing mode'), + BoolItem.new('without-ext', 'yes/no', 'no', + 'does not compile/install ruby extentions') +] +class ConfigTable_class # open again + ALIASES = { + 'std-ruby' => 'stdruby', + 'site-ruby-common' => 'siteruby', # For backward compatibility + 'site-ruby' => 'siterubyver', # For backward compatibility + 'bin-dir' => 'bindir', + 'bin-dir' => 'bindir', + 'rb-dir' => 'rbdir', + 'so-dir' => 'sodir', + 'data-dir' => 'datadir', + 'ruby-path' => 'rubypath', + 'ruby-prog' => 'rubyprog', + 'ruby' => 'rubyprog', + 'make-prog' => 'makeprog', + 'make' => 'makeprog' + } +end +multipackage_conf = [ + PackageSelectionItem.new('with', 'name,name...', '', 'ALL', + 'package names that you want to install'), + PackageSelectionItem.new('without', 'name,name...', '', 'NONE', + 'package names that you do not want to install') +] +if multipackage_install? + ConfigTable = ConfigTable_class.new(common_conf + multipackage_conf) +else + ConfigTable = ConfigTable_class.new(common_conf) +end + + +module MetaConfigAPI + + def eval_file_ifexist(fname) + instance_eval File.read(fname), fname, 1 if File.file?(fname) + end + + def config_names + ConfigTable.map {|i| i.name } + end + + def config?(name) + ConfigTable.key?(name) + end + + def bool_config?(name) + ConfigTable.lookup(name).config_type == 'bool' + end + + def path_config?(name) + ConfigTable.lookup(name).config_type == 'path' + end + + def value_config?(name) + case ConfigTable.lookup(name).config_type + when 'bool', 'path' + true + else + false + end + end + + def add_config(item) + ConfigTable.add item + end + + def add_bool_config(name, default, desc) + ConfigTable.add BoolItem.new(name, 'yes/no', default ? 'yes' : 'no', desc) + end + + def add_path_config(name, default, desc) + ConfigTable.add PathItem.new(name, 'path', default, desc) + end + + def set_config_default(name, default) + ConfigTable.lookup(name).default = default + end + + def remove_config(name) + ConfigTable.remove(name) + end + +end + + +# +# File Operations +# + +module FileOperations + + def mkdir_p(dirname, prefix = nil) + dirname = prefix + File.expand_path(dirname) if prefix + $stderr.puts "mkdir -p #{dirname}" if verbose? + return if no_harm? + + # does not check '/'... it's too abnormal case + dirs = File.expand_path(dirname).split(%r<(?=/)>) + if /\A[a-z]:\z/i =~ dirs[0] + disk = dirs.shift + dirs[0] = disk + dirs[0] + end + dirs.each_index do |idx| + path = dirs[0..idx].join('') + Dir.mkdir path unless File.dir?(path) + end + end + + def rm_f(fname) + $stderr.puts "rm -f #{fname}" if verbose? + return if no_harm? + + if File.exist?(fname) or File.symlink?(fname) + File.chmod 0777, fname + File.unlink fname + end + end + + def rm_rf(dn) + $stderr.puts "rm -rf #{dn}" if verbose? + return if no_harm? + + Dir.chdir dn + Dir.foreach('.') do |fn| + next if fn == '.' + next if fn == '..' + if File.dir?(fn) + verbose_off { + rm_rf fn + } + else + verbose_off { + rm_f fn + } + end + end + Dir.chdir '..' + Dir.rmdir dn + end + + def move_file(src, dest) + File.unlink dest if File.exist?(dest) + begin + File.rename src, dest + rescue + File.open(dest, 'wb') {|f| f.write File.binread(src) } + File.chmod File.stat(src).mode, dest + File.unlink src + end + end + + def install(from, dest, mode, prefix = nil) + $stderr.puts "install #{from} #{dest}" if verbose? + return if no_harm? + + realdest = prefix ? prefix + File.expand_path(dest) : dest + realdest = File.join(realdest, File.basename(from)) if File.dir?(realdest) + str = File.binread(from) + if diff?(str, realdest) + verbose_off { + rm_f realdest if File.exist?(realdest) + } + File.open(realdest, 'wb') {|f| + f.write str + } + File.chmod mode, realdest + + File.open("#{objdir_root()}/InstalledFiles", 'a') {|f| + if prefix + f.puts realdest.sub(prefix, '') + else + f.puts realdest + end + } + end + end + + def diff?(new_content, path) + return true unless File.exist?(path) + new_content != File.binread(path) + end + + def command(str) + $stderr.puts str if verbose? + system str or raise RuntimeError, "'system #{str}' failed" + end + + def ruby(str) + command config('rubyprog') + ' ' + str + end + + def make(task = '') + command config('makeprog') + ' ' + task + end + + def extdir?(dir) + File.exist?(dir + '/MANIFEST') + end + + def all_files_in(dirname) + Dir.open(dirname) {|d| + return d.select {|ent| File.file?("#{dirname}/#{ent}") } + } + end + + REJECT_DIRS = %w( + CVS SCCS RCS CVS.adm .svn + ) + + def all_dirs_in(dirname) + Dir.open(dirname) {|d| + return d.select {|n| File.dir?("#{dirname}/#{n}") } - %w(. ..) - REJECT_DIRS + } + end + +end + + +# +# Main Installer +# + +module HookUtils + + def run_hook(name) + try_run_hook "#{curr_srcdir()}/#{name}" or + try_run_hook "#{curr_srcdir()}/#{name}.rb" + end + + def try_run_hook(fname) + return false unless File.file?(fname) + begin + instance_eval File.read(fname), fname, 1 + rescue + setup_rb_error "hook #{fname} failed:\n" + $!.message + end + true + end + +end + + +module HookScriptAPI + + def get_config(key) + @config[key] + end + + alias config get_config + + def set_config(key, val) + @config[key] = val + end + + # + # srcdir/objdir (works only in the package directory) + # + + #abstract srcdir_root + #abstract objdir_root + #abstract relpath + + def curr_srcdir + "#{srcdir_root()}/#{relpath()}" + end + + def curr_objdir + "#{objdir_root()}/#{relpath()}" + end + + def srcfile(path) + "#{curr_srcdir()}/#{path}" + end + + def srcexist?(path) + File.exist?(srcfile(path)) + end + + def srcdirectory?(path) + File.dir?(srcfile(path)) + end + + def srcfile?(path) + File.file? srcfile(path) + end + + def srcentries(path = '.') + Dir.open("#{curr_srcdir()}/#{path}") {|d| + return d.to_a - %w(. ..) + } + end + + def srcfiles(path = '.') + srcentries(path).select {|fname| + File.file?(File.join(curr_srcdir(), path, fname)) + } + end + + def srcdirectories(path = '.') + srcentries(path).select {|fname| + File.dir?(File.join(curr_srcdir(), path, fname)) + } + end + +end + + +class ToplevelInstaller + + Version = '3.3.1' + Copyright = 'Copyright (c) 2000-2004 Minero Aoki' + + TASKS = [ + [ 'all', 'do config, setup, then install' ], + [ 'config', 'saves your configurations' ], + [ 'show', 'shows current configuration' ], + [ 'setup', 'compiles ruby extentions and others' ], + [ 'install', 'installs files' ], + [ 'clean', "does `make clean' for each extention" ], + [ 'distclean',"does `make distclean' for each extention" ] + ] + + def ToplevelInstaller.invoke + instance().invoke + end + + @singleton = nil + + def ToplevelInstaller.instance + @singleton ||= new(File.dirname($0)) + @singleton + end + + include MetaConfigAPI + + def initialize(ardir_root) + @config = nil + @options = { 'verbose' => true } + @ardir = File.expand_path(ardir_root) + end + + def inspect + "#<#{self.class} #{__id__()}>" + end + + def invoke + run_metaconfigs + case task = parsearg_global() + when nil, 'all' + @config = load_config('config') + parsearg_config + init_installers + exec_config + exec_setup + exec_install + else + @config = load_config(task) + __send__ "parsearg_#{task}" + init_installers + __send__ "exec_#{task}" + end + end + + def run_metaconfigs + eval_file_ifexist "#{@ardir}/metaconfig" + end + + def load_config(task) + case task + when 'config' + ConfigTable.new + when 'clean', 'distclean' + if File.exist?(ConfigTable.savefile) + then ConfigTable.load + else ConfigTable.new + end + else + ConfigTable.load + end + end + + def init_installers + @installer = Installer.new(@config, @options, @ardir, File.expand_path('.')) + end + + # + # Hook Script API bases + # + + def srcdir_root + @ardir + end + + def objdir_root + '.' + end + + def relpath + '.' + end + + # + # Option Parsing + # + + def parsearg_global + valid_task = /\A(?:#{TASKS.map {|task,desc| task }.join '|'})\z/ + + while arg = ARGV.shift + case arg + when /\A\w+\z/ + setup_rb_error "invalid task: #{arg}" unless valid_task =~ arg + return arg + + when '-q', '--quiet' + @options['verbose'] = false + + when '--verbose' + @options['verbose'] = true + + when '-h', '--help' + print_usage $stdout + exit 0 + + when '-v', '--version' + puts "#{File.basename($0)} version #{Version}" + exit 0 + + when '--copyright' + puts Copyright + exit 0 + + else + setup_rb_error "unknown global option '#{arg}'" + end + end + + nil + end + + + def parsearg_no_options + unless ARGV.empty? + setup_rb_error "#{task}: unknown options: #{ARGV.join ' '}" + end + end + + alias parsearg_show parsearg_no_options + alias parsearg_setup parsearg_no_options + alias parsearg_clean parsearg_no_options + alias parsearg_distclean parsearg_no_options + + def parsearg_config + re = /\A--(#{ConfigTable.map {|i| i.name }.join('|')})(?:=(.*))?\z/ + @options['config-opt'] = [] + + while i = ARGV.shift + if /\A--?\z/ =~ i + @options['config-opt'] = ARGV.dup + break + end + m = re.match(i) or setup_rb_error "config: unknown option #{i}" + name, value = *m.to_a[1,2] + @config[name] = value + end + end + + def parsearg_install + @options['no-harm'] = false + @options['install-prefix'] = '' + while a = ARGV.shift + case a + when /\A--no-harm\z/ + @options['no-harm'] = true + when /\A--prefix=(.*)\z/ + path = $1 + path = File.expand_path(path) unless path[0,1] == '/' + @options['install-prefix'] = path + else + setup_rb_error "install: unknown option #{a}" + end + end + end + + def print_usage(out) + out.puts 'Typical Installation Procedure:' + out.puts " $ ruby #{File.basename $0} config" + out.puts " $ ruby #{File.basename $0} setup" + out.puts " # ruby #{File.basename $0} install (may require root privilege)" + out.puts + out.puts 'Detailed Usage:' + out.puts " ruby #{File.basename $0} " + out.puts " ruby #{File.basename $0} [] []" + + fmt = " %-24s %s\n" + out.puts + out.puts 'Global options:' + out.printf fmt, '-q,--quiet', 'suppress message outputs' + out.printf fmt, ' --verbose', 'output messages verbosely' + out.printf fmt, '-h,--help', 'print this message' + out.printf fmt, '-v,--version', 'print version and quit' + out.printf fmt, ' --copyright', 'print copyright and quit' + out.puts + out.puts 'Tasks:' + TASKS.each do |name, desc| + out.printf fmt, name, desc + end + + fmt = " %-24s %s [%s]\n" + out.puts + out.puts 'Options for CONFIG or ALL:' + ConfigTable.each do |item| + out.printf fmt, item.help_opt, item.description, item.help_default + end + out.printf fmt, '--rbconfig=path', 'rbconfig.rb to load',"running ruby's" + out.puts + out.puts 'Options for INSTALL:' + out.printf fmt, '--no-harm', 'only display what to do if given', 'off' + out.printf fmt, '--prefix=path', 'install path prefix', '$prefix' + out.puts + end + + # + # Task Handlers + # + + def exec_config + @installer.exec_config + @config.save # must be final + end + + def exec_setup + @installer.exec_setup + end + + def exec_install + @installer.exec_install + end + + def exec_show + ConfigTable.each do |i| + printf "%-20s %s\n", i.name, i.value + end + end + + def exec_clean + @installer.exec_clean + end + + def exec_distclean + @installer.exec_distclean + end + +end + + +class ToplevelInstallerMulti < ToplevelInstaller + + include HookUtils + include HookScriptAPI + include FileOperations + + def initialize(ardir) + super + @packages = all_dirs_in("#{@ardir}/packages") + raise 'no package exists' if @packages.empty? + end + + def run_metaconfigs + eval_file_ifexist "#{@ardir}/metaconfig" + @packages.each do |name| + eval_file_ifexist "#{@ardir}/packages/#{name}/metaconfig" + end + end + + def init_installers + @installers = {} + @packages.each do |pack| + @installers[pack] = Installer.new(@config, @options, + "#{@ardir}/packages/#{pack}", + "packages/#{pack}") + end + + with = extract_selection(config('with')) + without = extract_selection(config('without')) + @selected = @installers.keys.select {|name| + (with.empty? or with.include?(name)) \ + and not without.include?(name) + } + end + + def extract_selection(list) + a = list.split(/,/) + a.each do |name| + setup_rb_error "no such package: #{name}" unless @installers.key?(name) + end + a + end + + def print_usage(f) + super + f.puts 'Inluded packages:' + f.puts ' ' + @packages.sort.join(' ') + f.puts + end + + # + # multi-package metaconfig API + # + + attr_reader :packages + + def declare_packages(list) + raise 'package list is empty' if list.empty? + list.each do |name| + raise "directory packages/#{name} does not exist"\ + unless File.dir?("#{@ardir}/packages/#{name}") + end + @packages = list + end + + # + # Task Handlers + # + + def exec_config + run_hook 'pre-config' + each_selected_installers {|inst| inst.exec_config } + run_hook 'post-config' + @config.save # must be final + end + + def exec_setup + run_hook 'pre-setup' + each_selected_installers {|inst| inst.exec_setup } + run_hook 'post-setup' + end + + def exec_install + run_hook 'pre-install' + each_selected_installers {|inst| inst.exec_install } + run_hook 'post-install' + end + + def exec_clean + rm_f ConfigTable.savefile + run_hook 'pre-clean' + each_selected_installers {|inst| inst.exec_clean } + run_hook 'post-clean' + end + + def exec_distclean + rm_f ConfigTable.savefile + run_hook 'pre-distclean' + each_selected_installers {|inst| inst.exec_distclean } + run_hook 'post-distclean' + end + + # + # lib + # + + def each_selected_installers + Dir.mkdir 'packages' unless File.dir?('packages') + @selected.each do |pack| + $stderr.puts "Processing the package `#{pack}' ..." if @options['verbose'] + Dir.mkdir "packages/#{pack}" unless File.dir?("packages/#{pack}") + Dir.chdir "packages/#{pack}" + yield @installers[pack] + Dir.chdir '../..' + end + end + + def verbose? + @options['verbose'] + end + + def no_harm? + @options['no-harm'] + end + +end + + +class Installer + + FILETYPES = %w( bin lib ext data ) + + include HookScriptAPI + include HookUtils + include FileOperations + + def initialize(config, opt, srcroot, objroot) + @config = config + @options = opt + @srcdir = File.expand_path(srcroot) + @objdir = File.expand_path(objroot) + @currdir = '.' + end + + def inspect + "#<#{self.class} #{File.basename(@srcdir)}>" + end + + # + # Hook Script API base methods + # + + def srcdir_root + @srcdir + end + + def objdir_root + @objdir + end + + def relpath + @currdir + end + + # + # configs/options + # + + def no_harm? + @options['no-harm'] + end + + def verbose? + @options['verbose'] + end + + def verbose_off + begin + save, @options['verbose'] = @options['verbose'], false + yield + ensure + @options['verbose'] = save + end + end + + # + # TASK config + # + + def exec_config + exec_task_traverse 'config' + end + + def config_dir_bin(rel) + end + + def config_dir_lib(rel) + end + + def config_dir_ext(rel) + extconf if extdir?(curr_srcdir()) + end + + def extconf + opt = @options['config-opt'].join(' ') + command "#{config('rubyprog')} #{curr_srcdir()}/extconf.rb #{opt}" + end + + def config_dir_data(rel) + end + + # + # TASK setup + # + + def exec_setup + exec_task_traverse 'setup' + end + + def setup_dir_bin(rel) + all_files_in(curr_srcdir()).each do |fname| + adjust_shebang "#{curr_srcdir()}/#{fname}" + end + end + + def adjust_shebang(path) + return if no_harm? + tmpfile = File.basename(path) + '.tmp' + begin + File.open(path, 'rb') {|r| + first = r.gets + return unless File.basename(config('rubypath')) == 'ruby' + return unless File.basename(first.sub(/\A\#!/, '').split[0]) == 'ruby' + $stderr.puts "adjusting shebang: #{File.basename(path)}" if verbose? + File.open(tmpfile, 'wb') {|w| + w.print first.sub(/\A\#!\s*\S+/, '#! ' + config('rubypath')) + w.write r.read + } + move_file tmpfile, File.basename(path) + } + ensure + File.unlink tmpfile if File.exist?(tmpfile) + end + end + + def setup_dir_lib(rel) + end + + def setup_dir_ext(rel) + make if extdir?(curr_srcdir()) + end + + def setup_dir_data(rel) + end + + # + # TASK install + # + + def exec_install + rm_f 'InstalledFiles' + exec_task_traverse 'install' + end + + def install_dir_bin(rel) + install_files collect_filenames_auto(), "#{config('bindir')}/#{rel}", 0755 + end + + def install_dir_lib(rel) + install_files ruby_scripts(), "#{config('rbdir')}/#{rel}", 0644 + end + + def install_dir_ext(rel) + return unless extdir?(curr_srcdir()) + install_files ruby_extentions('.'), + "#{config('sodir')}/#{File.dirname(rel)}", + 0555 + end + + def install_dir_data(rel) + install_files collect_filenames_auto(), "#{config('datadir')}/#{rel}", 0644 + end + + def install_files(list, dest, mode) + mkdir_p dest, @options['install-prefix'] + list.each do |fname| + install fname, dest, mode, @options['install-prefix'] + end + end + + def ruby_scripts + collect_filenames_auto().select {|n| /\.rb\z/ =~ n } + end + + # picked up many entries from cvs-1.11.1/src/ignore.c + reject_patterns = %w( + core RCSLOG tags TAGS .make.state + .nse_depinfo #* .#* cvslog.* ,* .del-* *.olb + *~ *.old *.bak *.BAK *.orig *.rej _$* *$ + + *.org *.in .* + ) + mapping = { + '.' => '\.', + '$' => '\$', + '#' => '\#', + '*' => '.*' + } + REJECT_PATTERNS = Regexp.new('\A(?:' + + reject_patterns.map {|pat| + pat.gsub(/[\.\$\#\*]/) {|ch| mapping[ch] } + }.join('|') + + ')\z') + + def collect_filenames_auto + mapdir((existfiles() - hookfiles()).reject {|fname| + REJECT_PATTERNS =~ fname + }) + end + + def existfiles + all_files_in(curr_srcdir()) | all_files_in('.') + end + + def hookfiles + %w( pre-%s post-%s pre-%s.rb post-%s.rb ).map {|fmt| + %w( config setup install clean ).map {|t| sprintf(fmt, t) } + }.flatten + end + + def mapdir(filelist) + filelist.map {|fname| + if File.exist?(fname) # objdir + fname + else # srcdir + File.join(curr_srcdir(), fname) + end + } + end + + def ruby_extentions(dir) + Dir.open(dir) {|d| + ents = d.select {|fname| /\.#{::Config::CONFIG['DLEXT']}\z/ =~ fname } + if ents.empty? + setup_rb_error "no ruby extention exists: 'ruby #{$0} setup' first" + end + return ents + } + end + + # + # TASK clean + # + + def exec_clean + exec_task_traverse 'clean' + rm_f ConfigTable.savefile + rm_f 'InstalledFiles' + end + + def clean_dir_bin(rel) + end + + def clean_dir_lib(rel) + end + + def clean_dir_ext(rel) + return unless extdir?(curr_srcdir()) + make 'clean' if File.file?('Makefile') + end + + def clean_dir_data(rel) + end + + # + # TASK distclean + # + + def exec_distclean + exec_task_traverse 'distclean' + rm_f ConfigTable.savefile + rm_f 'InstalledFiles' + end + + def distclean_dir_bin(rel) + end + + def distclean_dir_lib(rel) + end + + def distclean_dir_ext(rel) + return unless extdir?(curr_srcdir()) + make 'distclean' if File.file?('Makefile') + end + + # + # lib + # + + def exec_task_traverse(task) + run_hook "pre-#{task}" + FILETYPES.each do |type| + if config('without-ext') == 'yes' and type == 'ext' + $stderr.puts 'skipping ext/* by user option' if verbose? + next + end + traverse task, type, "#{task}_dir_#{type}" + end + run_hook "post-#{task}" + end + + def traverse(task, rel, mid) + dive_into(rel) { + run_hook "pre-#{task}" + __send__ mid, rel.sub(%r[\A.*?(?:/|\z)], '') + all_dirs_in(curr_srcdir()).each do |d| + traverse task, "#{rel}/#{d}", mid + end + run_hook "post-#{task}" + } + end + + def dive_into(rel) + return unless File.dir?("#{@srcdir}/#{rel}") + + dir = File.basename(rel) + Dir.mkdir dir unless File.dir?(dir) + prevdir = Dir.pwd + Dir.chdir dir + $stderr.puts '---> ' + rel if verbose? + @currdir = rel + yield + Dir.chdir prevdir + $stderr.puts '<--- ' + rel if verbose? + @currdir = File.dirname(rel) + end + +end + + +if $0 == __FILE__ + begin + if multipackage_install? + ToplevelInstallerMulti.invoke + else + ToplevelInstaller.invoke + end + rescue SetupError + raise if $DEBUG + $stderr.puts $!.message + $stderr.puts "Try 'ruby #{$0} --help' for detailed usage." + exit 1 + end +end diff --git a/test/net/dns/resolver/test_timeouts.rb b/test/net/dns/resolver/test_timeouts.rb new file mode 100644 index 0000000..6c54629 --- /dev/null +++ b/test/net/dns/resolver/test_timeouts.rb @@ -0,0 +1,59 @@ +require 'test/unit' +require 'net/dns/resolver/timeouts.rb' + +class Test_DnsTimeout < Test::Unit::TestCase + + def test_tcp + assert_equal(TcpTimeout.new(0).to_s,"infinite") + assert_equal(TcpTimeout.new(30).to_s, "30") + assert_equal(TcpTimeout.new(30).pretty_to_s, "30 seconds") + assert_equal(TcpTimeout.new(90).pretty_to_s, + "1 minutes and 30 seconds") + assert_equal(TcpTimeout.new(3690).pretty_to_s, + "1 hours, 1 minutes and 30 seconds") + assert_equal(TcpTimeout.new(1).timeout {1+1}, 2) + end + + def test_udp + assert_equal(UdpTimeout.new(0).to_s,"not defined") + assert_equal(UdpTimeout.new(30).to_s, "30") + assert_equal(UdpTimeout.new(30).pretty_to_s, "30 seconds") + assert_equal(UdpTimeout.new(90).pretty_to_s, + "1 minutes and 30 seconds") + assert_equal(UdpTimeout.new(3690).pretty_to_s, + "1 hours, 1 minutes and 30 seconds") + assert_equal(UdpTimeout.new(1).timeout {1+1}, 2) + end + + def test_range_tcp + assert_raise(DnsTimeoutArgumentError) do + TcpTimeout.new("a") + end + assert_raise(DnsTimeoutArgumentError) do + TcpTimeout.new(-1) + end + assert_raise(DnsTimeoutArgumentError) do + TcpTimeout.new(1).timeout + end + assert_raise(TimeoutError) do + TcpTimeout.new(0.1).timeout {sleep 2} + end + end + + def test_range_udp + assert_raise(DnsTimeoutArgumentError) do + UdpTimeout.new("a") + end + assert_raise(DnsTimeoutArgumentError) do + UdpTimeout.new(-1) + end + assert_raise(DnsTimeoutArgumentError) do + UdpTimeout.new(1).timeout + end + assert_raise(TimeoutError) do + UdpTimeout.new(0.1).timeout {sleep 2} + end + end + +end + diff --git a/test/net/dns/rr/test_a.rb b/test/net/dns/rr/test_a.rb new file mode 100644 index 0000000..9557f46 --- /dev/null +++ b/test/net/dns/rr/test_a.rb @@ -0,0 +1,72 @@ +require 'test/unit' +require 'net/dns/rr' + +class Test_A < Test::Unit::TestCase + def setup + + @name = "google.com." + @type = "A" + @cls = "IN" + @ttl = 10800 + @address = "64.233.187.99" + + + @hash = Net::DNS::RR::A.new(:name => @name, + :address => @address) + + @string = Net::DNS::RR::A.new("google.com. 10800 IN A 64.233.187.99") + + @arr = Net::DNS::RR.parse(@string.data) + + @str = "google.com. 10800 IN A 64.233.187.99" + end + + def test_simple + assert_equal(@str,@hash.inspect) + assert_equal(@name, @hash.name) + assert_equal(@type, @hash.type) + assert_equal(@cls, @hash.cls) + assert_equal(@ttl, @hash.ttl) + assert_equal(@address, @hash.address.to_s) + + assert_equal(@str, @string.inspect) + assert_equal(@name, @string.name) + assert_equal(@type, @string.type) + assert_equal(@cls, @string.cls) + assert_equal(@ttl, @string.ttl) + assert_equal(@address, @string.address.to_s) + + assert_equal(@str, @arr.inspect) + assert_equal(@name, @arr.name) + assert_equal(@type, @arr.type) + assert_equal(@cls, @arr.cls) + assert_equal(@ttl, @arr.ttl) + assert_equal(@address, @arr.address.to_s) + end + + def test_range + assert_raise(RRArgumentError) do + Net::DNS::RR::A.new(:name => "google.com", + :address => "255.256") + end + assert_raise(RRArgumentError) do + Net::DNS::RR::A.new(:name => "google.com") + end + assert_raise(RRArgumentError) do + Net::DNS::RR::A.new(Object.new) + end + assert_raise(RRArgumentError) do + Net::DNS::RR::A.new(Array.new(7)) + end + assert_raise(RRArgumentError) do + Net::DNS::RR::A.new("10800 IN A") + end + assert_raise(RRArgumentError) do + Net::DNS::RR::A.new("google.com. 10800 IN B") + end + assert_raise(RRArgumentError) do + Net::DNS::RR::A.new("google.com. 10800 IM A") + end + end +end + diff --git a/test/net/dns/rr/test_classes.rb b/test/net/dns/rr/test_classes.rb new file mode 100644 index 0000000..f339f19 --- /dev/null +++ b/test/net/dns/rr/test_classes.rb @@ -0,0 +1,73 @@ +require 'test/unit' +require 'net/dns/rr/classes' + +class Test_Classes < Test::Unit::TestCase + def setup + @classes = { + 'IN' => 1, # RFC 1035 + 'CH' => 3, # RFC 1035 + 'HS' => 4, # RFC 1035 + 'NONE' => 254, # RFC 2136 + 'ANY' => 255, # RFC 1035 + } + @regexp_string = "HS|ANY|NONE|CH|IN" + end + + def test_default + # Default type should be ANY => 255 + instance = Net::DNS::RR::Classes.new(nil) + assert_equal("1", instance.to_str) + assert_equal("IN", instance.to_s) + + # Let's change default behaviour + Net::DNS::RR::Classes.default = "CH" + instance = Net::DNS::RR::Classes.new(nil) + assert_equal("3", instance.to_str) + assert_equal("CH", instance.to_s) + + Net::DNS::RR::Classes.default = "IN" + instance = Net::DNS::RR::Classes.new(nil) + assert_equal("1", instance.to_str) + assert_equal("IN", instance.to_s) + + end + + def test_classes + @classes.each do |key,num| + instance_from_string = Net::DNS::RR::Classes.new(key) + instance_from_num = Net::DNS::RR::Classes.new(num) + assert_equal(key, instance_from_string.to_s) + assert_equal(num.to_s, instance_from_string.to_str) + assert_equal(key, instance_from_num.to_s) + assert_equal(num.to_s, instance_from_num.to_str) + end + assert_raise(ClassArgumentError) do + Net::DNS::RR::Classes.new(Hash.new) + end + end + + def test_regexp + assert_equal(@regexp_string, Net::DNS::RR::Classes.regexp) + end + + def test_valid + assert_equal(true, Net::DNS::RR::Classes.valid?("IN")) + assert_equal(true, Net::DNS::RR::Classes.valid?(1)) + assert_equal(false, Net::DNS::RR::Classes.valid?("Q")) + assert_equal(false, Net::DNS::RR::Classes.valid?(256)) + assert_raise(ClassArgumentError) do + Net::DNS::RR::Classes.valid? Hash.new + end + end + + def test_to_str + assert_equal("IN", Net::DNS::RR::Classes.to_str(1)) + assert_raise(ClassArgumentError) do + Net::DNS::RR::Classes.to_str(256) + end + assert_raise(ClassArgumentError) do + Net::DNS::RR::Classes.to_str("string") + end + end + +end diff --git a/test/net/dns/rr/test_ns.rb b/test/net/dns/rr/test_ns.rb new file mode 100644 index 0000000..d9ba25e --- /dev/null +++ b/test/net/dns/rr/test_ns.rb @@ -0,0 +1,66 @@ +require 'test/unit' +require 'net/dns/rr' + +class Test_NS < Test::Unit::TestCase + def setup + + @name = "google.com." + @type = "NS" + @cls = "IN" + @ttl = 10800 + @nsdname = "ns1.google.com." + + + @hash = Net::DNS::RR::NS.new(:name => @name, + :nsdname => @nsdname) + + @string = Net::DNS::RR::NS.new("google.com. 10800 IN NS ns1.google.com.") + + @arr = Net::DNS::RR.parse(@string.data) + + @str = "google.com. 10800 IN NS ns1.google.com." + end + + def test_simple + assert_equal(@str,@hash.inspect) + assert_equal(@name, @hash.name) + assert_equal(@type, @hash.type) + assert_equal(@cls, @hash.cls) + assert_equal(@ttl, @hash.ttl) + assert_equal(@nsdname, @hash.nsdname) + + assert_equal(@str, @string.inspect) + assert_equal(@name, @string.name) + assert_equal(@type, @string.type) + assert_equal(@cls, @string.cls) + assert_equal(@ttl, @string.ttl) + assert_equal(@nsdname, @string.nsdname) + + assert_equal(@str, @arr.inspect) + assert_equal(@name, @arr.name) + assert_equal(@type, @arr.type) + assert_equal(@cls, @arr.cls) + assert_equal(@ttl, @arr.ttl) + assert_equal(@nsdname, @arr.nsdname) + end + + def test_range + assert_raise(RRArgumentError) do + Net::DNS::RR::NS.new(:name => "google.com", + :nsdname => "255.256") + end + assert_raise(RRArgumentError) do + Net::DNS::RR::NS.new(:name => "google.com") + end + assert_raise(ArgumentError) do + Net::DNS::RR::NS.new(Range.new) + end + assert_raise(RRArgumentError) do + Net::DNS::RR::NS.new(Array.new(7)) + end + assert_raise(RRArgumentError) do + Net::DNS::RR::NS.new("10800 IN A") + end + end +end + diff --git a/test/net/dns/rr/test_types.rb b/test/net/dns/rr/test_types.rb new file mode 100644 index 0000000..5d40263 --- /dev/null +++ b/test/net/dns/rr/test_types.rb @@ -0,0 +1,127 @@ +require 'test/unit' +require 'net/dns/rr/types' + +class Test_Types < Test::Unit::TestCase + def setup + @types = { + 'SIGZERO' => 0, + 'A' => 1, + 'NS' => 2, + 'MD' => 3, + 'MF' => 4, + 'CNAME' => 5, + 'SOA' => 6, + 'MB' => 7, + 'MG' => 8, + 'MR' => 9, + 'NULL' => 10, + 'WKS' => 11, + 'PTR' => 12, + 'HINFO' => 13, + 'MINFO' => 14, + 'MX' => 15, + 'TXT' => 16, + 'RP' => 17, + 'AFSDB' => 18, + 'X25' => 19, + 'ISDN' => 20, + 'RT' => 21, + 'NSAP' => 22, + 'NSAP_PTR' => 23, + 'SIG' => 24, + 'KEY' => 25, + 'PX' => 26, + 'GPOS' => 27, + 'AAAA' => 28, + 'LOC' => 29, + 'NXT' => 30, + 'EID' => 31, + 'NIMLOC' => 32, + 'SRV' => 33, + 'ATMA' => 34, + 'NAPTR' => 35, + 'KX' => 36, + 'CERT' => 37, + 'DNAME' => 39, + 'OPT' => 41, + 'DS' => 43, + 'SSHFP' => 44, + 'RRSIG' => 46, + 'NSEC' => 47, + 'DNSKEY' => 48, + 'UINFO' => 100, + 'UID' => 101, + 'GID' => 102, + 'UNSPEC' => 103, + 'TKEY' => 249, + 'TSIG' => 250, + 'IXFR' => 251, + 'AXFR' => 252, + 'MAILB' => 253, + 'MAILA' => 254, + 'ANY' => 255, + } + + @regexp_string = "MAILB|TKEY|ATMA|EID|LOC|MX|ANY|SRV|AFSDB|MD|A|GID|KX|" + + "GPOS|RT|NSEC|NIMLOC|NSAP_PTR|PTR|CNAME|MF|SIGZERO|DNSKEY|DS|DNAME|" + + "CERT|AAAA|HINFO|MG|IXFR|UID|X25|TXT|MR|SOA|NS|SIG|AXFR|TSIG|UINFO|" + + "SSHFP|NULL|OPT|PX|RP|UNSPEC|NAPTR|KEY|NSAP|ISDN|MINFO|WKS|MAILA|RRSIG|NXT|MB" + end + + def test_default + # Default type should be ANY => 255 + instance = Net::DNS::RR::Types.new(nil) + assert_equal("1", instance.to_str) + assert_equal("A", instance.to_s) + + # Let's change default behaviour + Net::DNS::RR::Types.default = "A" + instance = Net::DNS::RR::Types.new(nil) + assert_equal("1", instance.to_str) + assert_equal("A", instance.to_s) + + Net::DNS::RR::Types.default = "ANY" + instance = Net::DNS::RR::Types.new(nil) + assert_equal("255", instance.to_str) + assert_equal("ANY", instance.to_s) + end + + def test_types + @types.each do |key,num| + instance_from_string = Net::DNS::RR::Types.new(key) + instance_from_num = Net::DNS::RR::Types.new(num) + assert_equal(key, instance_from_string.to_s) + assert_equal(num.to_s, instance_from_string.to_str) + assert_equal(key, instance_from_num.to_s) + assert_equal(num.to_s, instance_from_num.to_str) + end + assert_raise(TypeArgumentError) do + Net::DNS::RR::Types.new(Hash.new) + end + end + + def test_regexp + assert_equal(@regexp_string, Net::DNS::RR::Types.regexp) + end + + def test_valid + assert_equal(true, Net::DNS::RR::Types.valid?("A")) + assert_equal(true, Net::DNS::RR::Types.valid?(1)) + assert_equal(false, Net::DNS::RR::Types.valid?("Q")) + assert_equal(false, Net::DNS::RR::Types.valid?(256)) + assert_raise(TypeArgumentError) do + Net::DNS::RR::Types.valid? Hash.new + end + end + + def test_to_str + assert_equal("A", Net::DNS::RR::Types.to_str(1)) + assert_raise(TypeArgumentError) do + Net::DNS::RR::Types.to_str(256) + end + assert_raise(TypeArgumentError) do + Net::DNS::RR::Types.to_str("string") + end + end + +end diff --git a/test/net/dns/test_header.rb b/test/net/dns/test_header.rb new file mode 100644 index 0000000..b0abadb --- /dev/null +++ b/test/net/dns/test_header.rb @@ -0,0 +1,170 @@ +require 'test/unit' +require 'net/dns/header' + +class Test_Header < Test::Unit::TestCase + include Net::DNS + + def setup + + @default = Header.new + @hash = Header.new(:id => 441, + :qr => 1, + :opCode => Header::IQUERY, + :aa => 1, + :tc => 1, + :rd => 0, + :cd => 0, + :ad => 0, + :ra => 1, + :rCode => Header::RCode::FORMAT, + :qdCount => 1, + :anCount => 2, + :nsCount => 3, + :arCount => 3) + + @modified = Header.new + @modified.id = 442 + @modified.qr = true + @modified.opCode = Header::IQUERY + @modified.aa = true + @modified.tc = true + @modified.rd = false + @modified.cd = false + @modified.ra = true + @modified.rCode = Header::RCode::FORMAT + @modified.qdCount = 1 + @modified.anCount = 2 + @modified.nsCount = 3 + @modified.arCount = 3 + + @data = @modified.data + num = [(@data.unpack("n")[0]+1)].pack("n") + @data[0],@data[1] = num[0], num[1] + @binary = Header.parse(@data) + + end + + def test_simple + assert_equal(@default.query?, true) + assert_equal(@default.response?, false) + assert_equal(@default.opCode, Header::QUERY) + assert_equal(@default.auth?, false) + assert_equal(@default.truncated?, false) + assert_equal(@default.recursive?, true) + assert_equal(@default.checking?, true) + assert_equal(@default.verified?, false) + assert_equal(@default.r_available?, false) + assert_equal(@default.rCode.code, Header::RCode::NOERROR) + assert_equal(@default.qdCount, 1) + assert_equal(@default.anCount, 0) + assert_equal(@default.nsCount, 0) + assert_equal(@default.arCount, 0) + + assert_equal(@hash.id, 441) + assert_equal(@hash.query?, false) + assert_equal(@hash.response?, true) + assert_equal(@hash.opCode, Header::IQUERY) + assert_equal(@hash.auth?, true) + assert_equal(@hash.truncated?, true) + assert_equal(@hash.recursive?, false) + assert_equal(@hash.checking?, true) + assert_equal(@hash.verified?, false) + assert_equal(@hash.r_available?, true) + assert_equal(@hash.rCode.code, Header::RCode::FORMAT) + assert_equal(@hash.qdCount, 1) + assert_equal(@hash.anCount, 2) + assert_equal(@hash.nsCount, 3) + assert_equal(@hash.arCount, 3) + + assert_equal(@modified.id, 442) + assert_equal(@modified.query?, false) + assert_equal(@modified.response?, true) + assert_equal(@modified.opCode, Header::IQUERY) + assert_equal(@modified.auth?, true) + assert_equal(@modified.truncated?, true) + assert_equal(@modified.recursive?, false) + assert_equal(@modified.checking?, true) + assert_equal(@modified.verified?, false) + assert_equal(@modified.r_available?, true) + assert_equal(@modified.rCode.code, Header::RCode::FORMAT) + assert_equal(@modified.qdCount, 1) + assert_equal(@modified.anCount, 2) + assert_equal(@modified.nsCount, 3) + assert_equal(@modified.arCount, 3) + + assert_equal(@binary.data, @data) + + assert_equal(@binary.id, 443) + assert_equal(@binary.query?, false) + assert_equal(@binary.response?, true) + assert_equal(@binary.opCode, Header::IQUERY) + assert_equal(@binary.auth?, true) + assert_equal(@binary.truncated?, true) + assert_equal(@binary.recursive?, false) + assert_equal(@binary.checking?, true) + assert_equal(@binary.verified?, false) + assert_equal(@binary.r_available?, true) + assert_equal(@binary.rCode.code, Header::RCode::FORMAT) + assert_equal(@binary.qdCount, 1) + assert_equal(@binary.anCount, 2) + assert_equal(@binary.nsCount, 3) + assert_equal(@binary.arCount, 3) + + assert_raise(HeaderArgumentError) do + Header.new(Array.new) + end + assert_raise(HeaderArgumentError) do + Header.parse(Array.new) + end + assert_raise(HeaderArgumentError) do + Header.parse("aa") + end + assert_raise(HeaderDuplicateID) do + @default.id = 441 + end + assert_raise(HeaderArgumentError) do + @default.id = 1000000 + end + assert_raise(HeaderArgumentError) do + @default.qr=2 + end + assert_raise(HeaderWrongOpcode) do + @default.opCode=4 + end + assert_raise(HeaderArgumentError) do + @default.aa=2 + end + assert_raise(HeaderArgumentError) do + @default.tc=2 + end + assert_raise(HeaderWrongRecursive) do + @default.recursive=2 + end + assert_raise(HeaderArgumentError) do + @default.ra=2 + end + assert_raise(HeaderArgumentError) do + @default.cd=2 + end + assert_raise(HeaderArgumentError) do + @default.ad=2 + end + assert_raise(HeaderArgumentError) do + @default.rCode=46 + end + assert_raise(HeaderWrongCount) do + @default.qdCount=100000 + end + assert_raise(HeaderWrongCount) do + @default.anCount=100000 + end + assert_raise(HeaderWrongCount) do + @default.nsCount=100000 + end + assert_raise(HeaderWrongCount) do + @default.arCount=100000 + end + end + +end + diff --git a/test/net/dns/test_packet.rb b/test/net/dns/test_packet.rb new file mode 100644 index 0000000..bf7b3f7 --- /dev/null +++ b/test/net/dns/test_packet.rb @@ -0,0 +1,42 @@ +require 'test/unit' +require 'net/dns/packet' + +class Test_Packet < Test::Unit::TestCase + include Net::DNS + + def setup + @domain = 'example.com' + @type = 'MX' + @cls = 'HS' + + @default = Packet.new(@domain) + @string = Packet.new(@domain, MX, HS) + + packet = "\337M\201\200\000\001\000\003\000\004\000\004\006google\003com\000\000\001\000\001\300\f\000\001\000\001\000\000\001,\000\004@\351\273c\300\f\000\001\000\001\000\000\001,\000\004H\016\317c\300\f\000\001\000\001\000\000\001,\000\004@\351\247c\300\f\000\002\000\001\000\003\364\200\000\006\003ns1\300\f\300\f\000\002\000\001\000\003\364\200\000\006\003ns2\300\f\300\f\000\002\000\001\000\003\364\200\000\006\003ns3\300\f\300\f\000\002\000\001\000\003\364\200\000\006\003ns4\300\f\300X\000\001\000\001\000\003\307\273\000\004\330\357 \n\300j\000\001\000\001\000\003\307\273\000\004\330\357\"\n\300|\000\001\000\001\000\003\307\273\000\004\330\357$\n\300\216\000\001\000\001\000\003\307\273\000\004\330\357&\n" + + @binary = Packet.parse(packet) + + end + + def test_instances + assert_instance_of(Net::DNS::Packet, @string) + assert_instance_of(Net::DNS::Header, @string.header) + assert_instance_of(Array, @string.question) + assert_instance_of(Net::DNS::Question, @string.question[0]) + assert_instance_of(Array, @string.answer) + assert_instance_of(Array, @string.authority) + assert_instance_of(Array, @string.additional) + + assert_instance_of(Net::DNS::Packet, @binary) + assert_instance_of(Net::DNS::Header, @binary.header) + assert_instance_of(Array, @binary.question) + assert_instance_of(Net::DNS::Question, @binary.question[0]) + assert_instance_of(Array, @binary.answer) + assert_instance_of(Net::DNS::RR::A, @binary.answer[0]) + assert_instance_of(Array, @binary.authority) + assert_instance_of(Net::DNS::RR::NS, @binary.authority[0]) + assert_instance_of(Array, @binary.additional) + assert_instance_of(Net::DNS::RR::A, @binary.additional[0]) + end + +end diff --git a/test/net/dns/test_question.rb b/test/net/dns/test_question.rb new file mode 100644 index 0000000..36c6973 --- /dev/null +++ b/test/net/dns/test_question.rb @@ -0,0 +1,54 @@ +require 'test/unit' +require 'net/dns/question' + +class Test_Question < Test::Unit::TestCase + include Net::DNS + + def setup + @domain = 'example.com.' + @type = 'MX' + @cls = 'HS' + @data = "\006google\003com\000\000\001\000\001" + + @default = Question.new(@domain) + @string = Question.new(@domain,@type,@cls) + @binary = Question.parse(@data) + @binary2 = Question.parse(@string.data) + end + + def test_simple + assert_equal(@default.qName, @domain) + assert_equal(@default.qType.to_s, "A") + assert_equal(@default.qClass.to_s, "IN") + + assert_equal(@string.qName, @domain) + assert_equal(@string.qType.to_s, "MX") + assert_equal(@string.qClass.to_s, "HS") + + assert_equal(@binary.qName, "google.com.") + assert_equal(@binary.qType.to_s, "A") + assert_equal(@binary.qClass.to_s, "IN") + + assert_equal(@binary2.qName, @domain) + assert_equal(@binary2.qType.to_s, "MX") + assert_equal(@binary2.qClass.to_s, "HS") + end + + def test_raise + assert_raise(QuestionNameError) do + Question.new(1) + end + assert_raise(QuestionNameError) do + Question.new("test{") + end + assert_raise(QuestionArgumentError) do + Question.parse(Array.new) + end + assert_raise(QuestionArgumentError) do + Question.parse("test") + end + + end + + +end diff --git a/test/net/dns/test_rr.rb b/test/net/dns/test_rr.rb new file mode 100644 index 0000000..0027204 --- /dev/null +++ b/test/net/dns/test_rr.rb @@ -0,0 +1,133 @@ +require 'test/unit' +require 'net/dns/rr' + +class Test_RR < Test::Unit::TestCase + + def setup + @name = "example.com." + @type = "A" + @cls = "IN" + @ttl = 10800 + @rdata = "64.233.187.99" + + @defaults = Net::DNS::RR.new(:name => @name, + :rdata => @rdata) + + + @a_hash = Net::DNS::RR.new(:name => @name, + :ttl => @ttl, + :cls => @cls, + :type => @type, + :address => @rdata) + + @a_string = Net::DNS::RR::A.new("example.com. 10800 IN A 64.233.187.99") + + @str = "example.com. 10800 IN A 64.233.187.99" + + @a = Net::DNS::RR.new("foo.example.com. 86400 A 10.1.2.3") + @mx = Net::DNS::RR.new("example.com. 7200 MX 10 mailhost.example.com.") + @cname = Net::DNS::RR.new("www.example.com IN CNAME www1.example.com") + @txt = Net::DNS::RR.new('baz.example.com 3600 HS TXT "text record"') + + @a_data = @a.data + @a_binary = Net::DNS::RR.parse(@a_data) + @mx_data = @mx.data + @mx_binary = Net::DNS::RR.parse(@mx_data) + + @array = [@name,@ttl,@cls,@type,@rdata] + + end + + def test_classes + assert_instance_of Net::DNS::RR::A, @a + assert_instance_of Net::DNS::RR::MX, @mx + assert_instance_of Net::DNS::RR::CNAME, @cname + assert_instance_of Net::DNS::RR::TXT, @txt + assert_instance_of Net::DNS::RR::A, @a_binary + assert_instance_of Net::DNS::RR::MX, @mx_binary + end + + def test_ttl + assert_equal @a.ttl, 86400 + assert_equal @mx.ttl, 7200 + assert_equal @cname.ttl, 10800 + assert_equal @txt.ttl, 3600 + assert_equal @a_binary.ttl, 86400 + assert_equal @mx_binary.ttl, 7200 + end + + def test_types + assert_equal @a.type, "A" + assert_equal @mx.type, "MX" + assert_equal @cname.type, "CNAME" + assert_equal @txt.type, "TXT" + assert_equal @a_binary.type, "A" + assert_equal @mx_binary.type, "MX" + end + + def test_cls + assert_equal @a.cls, "IN" + assert_equal @mx.cls, "IN" + assert_equal @cname.cls, "IN" + assert_equal @txt.cls, "HS" + assert_equal @a_binary.cls, "IN" + assert_equal @mx_binary.cls, "IN" + end + + def test_name + assert_equal @a.name, "foo.example.com." + assert_equal @mx.name, "example.com." + assert_equal @cname.name, "www.example.com" + assert_equal @txt.name, "baz.example.com" + assert_equal @a_binary.name, "foo.example.com." + assert_equal @mx_binary.name, "example.com." + end + + def test_rdata + assert_equal @a.address.to_s, "10.1.2.3" + assert_equal @mx.preference, 10 + assert_equal @mx.exchange, "mailhost.example.com." + assert_equal @cname.cname, "www1.example.com" + assert_equal @txt.txt, '"text record"' + assert_equal @a_binary.address.to_s, "10.1.2.3" + assert_equal @mx_binary.preference, 10 + assert_equal @mx_binary.exchange, "mailhost.example.com." + end + + def test_simple + + assert_equal @name, @defaults.name + assert_equal @type, @defaults.type + assert_equal @cls, @defaults.cls + assert_equal @ttl, @defaults.ttl + assert_equal @rdata, @defaults.rdata.to_s + + assert_equal(@str,@a_hash.inspect) + assert_equal(@name, @a_hash.name) + assert_equal(@type, @a_hash.type) + assert_equal(@cls, @a_hash.cls) + assert_equal(@ttl, @a_hash.ttl) + assert_equal(@rdata, @a_hash.address.to_s) + + assert_equal(@str, @a_string.inspect) + assert_equal(@name, @a_string.name) + assert_equal(@type, @a_string.type) + assert_equal(@cls, @a_string.cls) + assert_equal(@ttl, @a_string.ttl) + assert_equal(@rdata, @a_string.address.to_s) + + assert_equal(@a_data, @a_binary.data) + assert_equal(@mx_data, @mx_binary.data) + + assert_equal(@str, @a_hash.to_s) + assert_equal(@array, @a_hash.to_a) + end + + def test_range + assert_raise(RRArgumentError) do + Net::DNS::RR.new("google.com. 10800 IM A") + end + end + +end +