PageRenderTime 532ms CodeModel.GetById 111ms app.highlight 337ms RepoModel.GetById 45ms app.codeStats 1ms

/tools/Ruby/lib/ruby/1.8/resolv.rb

http://github.com/agross/netopenspace
Ruby | 2293 lines | 1597 code | 346 blank | 350 comment | 96 complexity | 16b201dfa17619a9038ba5588ae025a7 MD5 | raw file

Large files files are truncated, but you can click here to view the full file

   1require 'socket'
   2require 'fcntl'
   3require 'timeout'
   4require 'thread'
   5
   6begin
   7  require 'securerandom'
   8rescue LoadError
   9end
  10
  11# Resolv is a thread-aware DNS resolver library written in Ruby.  Resolv can
  12# handle multiple DNS requests concurrently without blocking.  The ruby
  13# interpreter.
  14#
  15# See also resolv-replace.rb to replace the libc resolver with # Resolv.
  16# 
  17# Resolv can look up various DNS resources using the DNS module directly.
  18# 
  19# Examples:
  20# 
  21#   p Resolv.getaddress "www.ruby-lang.org"
  22#   p Resolv.getname "210.251.121.214"
  23# 
  24#   Resolv::DNS.open do |dns|
  25#     ress = dns.getresources "www.ruby-lang.org", Resolv::DNS::Resource::IN::A
  26#     p ress.map { |r| r.address }
  27#     ress = dns.getresources "ruby-lang.org", Resolv::DNS::Resource::IN::MX
  28#     p ress.map { |r| [r.exchange.to_s, r.preference] }
  29#   end
  30# 
  31# 
  32# == Bugs
  33# 
  34# * NIS is not supported.
  35# * /etc/nsswitch.conf is not supported.
  36
  37class Resolv
  38
  39  ##
  40  # Looks up the first IP address for +name+.
  41  
  42  def self.getaddress(name)
  43    DefaultResolver.getaddress(name)
  44  end
  45
  46  ##
  47  # Looks up all IP address for +name+.
  48  
  49  def self.getaddresses(name)
  50    DefaultResolver.getaddresses(name)
  51  end
  52
  53  ##
  54  # Iterates over all IP addresses for +name+.
  55
  56  def self.each_address(name, &block)
  57    DefaultResolver.each_address(name, &block)
  58  end
  59
  60  ##
  61  # Looks up the hostname of +address+.
  62
  63  def self.getname(address)
  64    DefaultResolver.getname(address)
  65  end
  66
  67  ##
  68  # Looks up all hostnames for +address+.
  69
  70  def self.getnames(address)
  71    DefaultResolver.getnames(address)
  72  end
  73
  74  ##
  75  # Iterates over all hostnames for +address+.
  76
  77  def self.each_name(address, &proc)
  78    DefaultResolver.each_name(address, &proc)
  79  end
  80
  81  ##
  82  # Creates a new Resolv using +resolvers+.
  83
  84  def initialize(resolvers=[Hosts.new, DNS.new])
  85    @resolvers = resolvers
  86  end
  87
  88  ##
  89  # Looks up the first IP address for +name+.
  90  
  91  def getaddress(name)
  92    each_address(name) {|address| return address}
  93    raise ResolvError.new("no address for #{name}")
  94  end
  95
  96  ##
  97  # Looks up all IP address for +name+.
  98  
  99  def getaddresses(name)
 100    ret = []
 101    each_address(name) {|address| ret << address}
 102    return ret
 103  end
 104
 105  ##
 106  # Iterates over all IP addresses for +name+.
 107
 108  def each_address(name)
 109    if AddressRegex =~ name
 110      yield name
 111      return
 112    end
 113    yielded = false
 114    @resolvers.each {|r|
 115      r.each_address(name) {|address|
 116        yield address.to_s
 117        yielded = true
 118      }
 119      return if yielded
 120    }
 121  end
 122
 123  ##
 124  # Looks up the hostname of +address+.
 125
 126  def getname(address)
 127    each_name(address) {|name| return name}
 128    raise ResolvError.new("no name for #{address}")
 129  end
 130
 131  ##
 132  # Looks up all hostnames for +address+.
 133
 134  def getnames(address)
 135    ret = []
 136    each_name(address) {|name| ret << name}
 137    return ret
 138  end
 139
 140  ##
 141  # Iterates over all hostnames for +address+.
 142
 143  def each_name(address)
 144    yielded = false
 145    @resolvers.each {|r|
 146      r.each_name(address) {|name|
 147        yield name.to_s
 148        yielded = true
 149      }
 150      return if yielded
 151    }
 152  end
 153
 154  ##
 155  # Indicates a failure to resolve a name or address.
 156
 157  class ResolvError < StandardError; end
 158
 159  ##
 160  # Indicates a timeout resolving a name or address.
 161
 162  class ResolvTimeout < TimeoutError; end
 163
 164  ##
 165  # DNS::Hosts is a hostname resolver that uses the system hosts file.
 166
 167  class Hosts
 168    if /mswin32|mingw|bccwin/ =~ RUBY_PLATFORM
 169      require 'win32/resolv'
 170      DefaultFileName = Win32::Resolv.get_hosts_path
 171    else
 172      DefaultFileName = '/etc/hosts'
 173    end
 174
 175    ##
 176    # Creates a new DNS::Hosts, using +filename+ for its data source.
 177
 178    def initialize(filename = DefaultFileName)
 179      @filename = filename
 180      @mutex = Mutex.new
 181      @initialized = nil
 182    end
 183
 184    def lazy_initialize # :nodoc:
 185      @mutex.synchronize {
 186        unless @initialized
 187          @name2addr = {}
 188          @addr2name = {}
 189          open(@filename) {|f|
 190            f.each {|line|
 191              line.sub!(/#.*/, '')
 192              addr, hostname, *aliases = line.split(/\s+/)
 193              next unless addr
 194              addr.untaint
 195              hostname.untaint
 196              @addr2name[addr] = [] unless @addr2name.include? addr
 197              @addr2name[addr] << hostname
 198              @addr2name[addr] += aliases
 199              @name2addr[hostname] = [] unless @name2addr.include? hostname
 200              @name2addr[hostname] << addr
 201              aliases.each {|n|
 202                n.untaint
 203                @name2addr[n] = [] unless @name2addr.include? n
 204                @name2addr[n] << addr
 205              }
 206            }
 207          }
 208          @name2addr.each {|name, arr| arr.reverse!}
 209          @initialized = true
 210        end
 211      }
 212      self
 213    end
 214
 215    ##
 216    # Gets the IP address of +name+ from the hosts file.
 217
 218    def getaddress(name)
 219      each_address(name) {|address| return address}
 220      raise ResolvError.new("#{@filename} has no name: #{name}")
 221    end
 222
 223    ##
 224    # Gets all IP addresses for +name+ from the hosts file.
 225
 226    def getaddresses(name)
 227      ret = []
 228      each_address(name) {|address| ret << address}
 229      return ret
 230    end
 231
 232    ##
 233    # Iterates over all IP addresses for +name+ retrieved from the hosts file.
 234
 235    def each_address(name, &proc)
 236      lazy_initialize
 237      if @name2addr.include?(name)
 238        @name2addr[name].each(&proc)
 239      end
 240    end
 241
 242    ##
 243    # Gets the hostname of +address+ from the hosts file.
 244
 245    def getname(address)
 246      each_name(address) {|name| return name}
 247      raise ResolvError.new("#{@filename} has no address: #{address}")
 248    end
 249
 250    ##
 251    # Gets all hostnames for +address+ from the hosts file.
 252
 253    def getnames(address)
 254      ret = []
 255      each_name(address) {|name| ret << name}
 256      return ret
 257    end
 258
 259    ##
 260    # Iterates over all hostnames for +address+ retrieved from the hosts file.
 261
 262    def each_name(address, &proc)
 263      lazy_initialize
 264      if @addr2name.include?(address)
 265        @addr2name[address].each(&proc)
 266      end
 267    end
 268  end
 269
 270  ##
 271  # Resolv::DNS is a DNS stub resolver.
 272  #
 273  # Information taken from the following places:
 274  #
 275  # * STD0013
 276  # * RFC 1035
 277  # * ftp://ftp.isi.edu/in-notes/iana/assignments/dns-parameters
 278  # * etc.
 279
 280  class DNS
 281
 282    ##
 283    # Default DNS Port
 284
 285    Port = 53
 286
 287    ##
 288    # Default DNS UDP packet size
 289
 290    UDPSize = 512
 291
 292    ##
 293    # Group of DNS resolver threads (obsolete)
 294
 295    DNSThreadGroup = ThreadGroup.new
 296
 297    ##
 298    # Creates a new DNS resolver.  See Resolv::DNS.new for argument details.
 299    #
 300    # Yields the created DNS resolver to the block, if given, otherwise
 301    # returns it.
 302
 303    def self.open(*args)
 304      dns = new(*args)
 305      return dns unless block_given?
 306      begin
 307        yield dns
 308      ensure
 309        dns.close
 310      end
 311    end
 312
 313    ##
 314    # Creates a new DNS resolver.
 315    #
 316    # +config_info+ can be:
 317    # 
 318    # nil:: Uses /etc/resolv.conf.
 319    # String:: Path to a file using /etc/resolv.conf's format.
 320    # Hash:: Must contain :nameserver, :search and :ndots keys.
 321    #
 322    # Example:
 323    #
 324    #   Resolv::DNS.new(:nameserver => ['210.251.121.21'],
 325    #                   :search => ['ruby-lang.org'],
 326    #                   :ndots => 1)
 327
 328    def initialize(config_info=nil)
 329      @mutex = Mutex.new
 330      @config = Config.new(config_info)
 331      @initialized = nil
 332    end
 333
 334    def lazy_initialize # :nodoc:
 335      @mutex.synchronize {
 336        unless @initialized
 337          @config.lazy_initialize
 338          @initialized = true
 339        end
 340      }
 341      self
 342    end
 343
 344    ##
 345    # Closes the DNS resolver.
 346
 347    def close
 348      @mutex.synchronize {
 349        if @initialized
 350          @initialized = false
 351        end
 352      }
 353    end
 354
 355    ##
 356    # Gets the IP address of +name+ from the DNS resolver.
 357    #
 358    # +name+ can be a Resolv::DNS::Name or a String.  Retrieved address will
 359    # be a Resolv::IPv4 or Resolv::IPv6
 360
 361    def getaddress(name)
 362      each_address(name) {|address| return address}
 363      raise ResolvError.new("DNS result has no information for #{name}")
 364    end
 365
 366    ##
 367    # Gets all IP addresses for +name+ from the DNS resolver.
 368    #
 369    # +name+ can be a Resolv::DNS::Name or a String.  Retrieved addresses will
 370    # be a Resolv::IPv4 or Resolv::IPv6
 371
 372    def getaddresses(name)
 373      ret = []
 374      each_address(name) {|address| ret << address}
 375      return ret
 376    end
 377
 378    ##
 379    # Iterates over all IP addresses for +name+ retrieved from the DNS
 380    # resolver.
 381    #
 382    # +name+ can be a Resolv::DNS::Name or a String.  Retrieved addresses will
 383    # be a Resolv::IPv4 or Resolv::IPv6
 384
 385    def each_address(name)
 386      each_resource(name, Resource::IN::A) {|resource| yield resource.address}
 387      each_resource(name, Resource::IN::AAAA) {|resource| yield resource.address}
 388    end
 389
 390    ##
 391    # Gets the hostname for +address+ from the DNS resolver.
 392    #
 393    # +address+ must be a Resolv::IPv4, Resolv::IPv6 or a String.  Retrieved
 394    # name will be a Resolv::DNS::Name.
 395
 396    def getname(address)
 397      each_name(address) {|name| return name}
 398      raise ResolvError.new("DNS result has no information for #{address}")
 399    end
 400
 401    ##
 402    # Gets all hostnames for +address+ from the DNS resolver.
 403    #
 404    # +address+ must be a Resolv::IPv4, Resolv::IPv6 or a String.  Retrieved
 405    # names will be Resolv::DNS::Name instances.
 406
 407    def getnames(address)
 408      ret = []
 409      each_name(address) {|name| ret << name}
 410      return ret
 411    end
 412
 413    ##
 414    # Iterates over all hostnames for +address+ retrieved from the DNS
 415    # resolver.
 416    #
 417    # +address+ must be a Resolv::IPv4, Resolv::IPv6 or a String.  Retrieved
 418    # names will be Resolv::DNS::Name instances.
 419
 420    def each_name(address)
 421      case address
 422      when Name
 423        ptr = address
 424      when IPv4::Regex
 425        ptr = IPv4.create(address).to_name
 426      when IPv6::Regex
 427        ptr = IPv6.create(address).to_name
 428      else
 429        raise ResolvError.new("cannot interpret as address: #{address}")
 430      end
 431      each_resource(ptr, Resource::IN::PTR) {|resource| yield resource.name}
 432    end
 433
 434    ##
 435    # Look up the +typeclass+ DNS resource of +name+.
 436    #
 437    # +name+ must be a Resolv::DNS::Name or a String.
 438    #
 439    # +typeclass+ should be one of the following:
 440    #
 441    # * Resolv::DNS::Resource::IN::A
 442    # * Resolv::DNS::Resource::IN::AAAA
 443    # * Resolv::DNS::Resource::IN::ANY
 444    # * Resolv::DNS::Resource::IN::CNAME
 445    # * Resolv::DNS::Resource::IN::HINFO
 446    # * Resolv::DNS::Resource::IN::MINFO
 447    # * Resolv::DNS::Resource::IN::MX
 448    # * Resolv::DNS::Resource::IN::NS
 449    # * Resolv::DNS::Resource::IN::PTR
 450    # * Resolv::DNS::Resource::IN::SOA
 451    # * Resolv::DNS::Resource::IN::TXT
 452    # * Resolv::DNS::Resource::IN::WKS
 453    #
 454    # Returned resource is represented as a Resolv::DNS::Resource instance,
 455    # i.e. Resolv::DNS::Resource::IN::A.
 456
 457    def getresource(name, typeclass)
 458      each_resource(name, typeclass) {|resource| return resource}
 459      raise ResolvError.new("DNS result has no information for #{name}")
 460    end
 461
 462    ##
 463    # Looks up all +typeclass+ DNS resources for +name+.  See #getresource for
 464    # argument details.
 465  
 466    def getresources(name, typeclass)
 467      ret = []
 468      each_resource(name, typeclass) {|resource| ret << resource}
 469      return ret
 470    end
 471
 472    ##
 473    # Iterates over all +typeclass+ DNS resources for +name+.  See
 474    # #getresource for argument details.
 475  
 476    def each_resource(name, typeclass, &proc)
 477      lazy_initialize
 478      requester = make_requester
 479      senders = {}
 480      begin
 481        @config.resolv(name) {|candidate, tout, nameserver|
 482          msg = Message.new
 483          msg.rd = 1
 484          msg.add_question(candidate, typeclass)
 485          unless sender = senders[[candidate, nameserver]]
 486            sender = senders[[candidate, nameserver]] =
 487              requester.sender(msg, candidate, nameserver)
 488          end
 489          reply, reply_name = requester.request(sender, tout)
 490          case reply.rcode
 491          when RCode::NoError
 492            extract_resources(reply, reply_name, typeclass, &proc)
 493            return
 494          when RCode::NXDomain
 495            raise Config::NXDomain.new(reply_name.to_s)
 496          else
 497            raise Config::OtherResolvError.new(reply_name.to_s)
 498          end
 499        }
 500      ensure
 501        requester.close
 502      end
 503    end
 504
 505    def make_requester # :nodoc:
 506      nameserver_port = @config.nameserver_port
 507      if nameserver_port.length == 1
 508        Requester::ConnectedUDP.new(*nameserver_port[0])
 509      else
 510        Requester::UnconnectedUDP.new(*nameserver_port)
 511      end
 512    end
 513
 514    def extract_resources(msg, name, typeclass) # :nodoc:
 515      if typeclass < Resource::ANY
 516        n0 = Name.create(name)
 517        msg.each_answer {|n, ttl, data|
 518          yield data if n0 == n
 519        }
 520      end
 521      yielded = false
 522      n0 = Name.create(name)
 523      msg.each_answer {|n, ttl, data|
 524        if n0 == n
 525          case data
 526          when typeclass
 527            yield data
 528            yielded = true
 529          when Resource::CNAME
 530            n0 = data.name
 531          end
 532        end
 533      }
 534      return if yielded
 535      msg.each_answer {|n, ttl, data|
 536        if n0 == n
 537          case data
 538          when typeclass
 539            yield data
 540          end
 541        end
 542      }
 543    end
 544
 545    if defined? SecureRandom
 546      def self.random(arg) # :nodoc:
 547        begin
 548          SecureRandom.random_number(arg)
 549        rescue NotImplementedError
 550          rand(arg)
 551        end
 552      end
 553    else
 554      def self.random(arg) # :nodoc:
 555        rand(arg)
 556      end
 557    end
 558
 559
 560    def self.rangerand(range) # :nodoc:
 561      base = range.begin
 562      len = range.end - range.begin
 563      if !range.exclude_end?
 564        len += 1
 565      end
 566      base + random(len)
 567    end
 568
 569    RequestID = {}
 570    RequestIDMutex = Mutex.new
 571
 572    def self.allocate_request_id(host, port) # :nodoc:
 573      id = nil
 574      RequestIDMutex.synchronize {
 575        h = (RequestID[[host, port]] ||= {})
 576        begin
 577          id = rangerand(0x0000..0xffff)
 578        end while h[id] 
 579        h[id] = true
 580      }
 581      id
 582    end
 583
 584    def self.free_request_id(host, port, id) # :nodoc:
 585      RequestIDMutex.synchronize {
 586        key = [host, port]
 587        if h = RequestID[key]
 588          h.delete id
 589          if h.empty?
 590            RequestID.delete key
 591          end
 592        end
 593      }
 594    end
 595
 596    def self.bind_random_port(udpsock, bind_host="0.0.0.0") # :nodoc:
 597      begin
 598        port = rangerand(1024..65535)
 599        udpsock.bind(bind_host, port)
 600      rescue Errno::EADDRINUSE
 601        retry
 602      end
 603    end
 604
 605    class Requester # :nodoc:
 606      def initialize
 607        @senders = {}
 608        @socks = nil
 609      end
 610
 611      def request(sender, tout)
 612        timelimit = Time.now + tout
 613        sender.send
 614        while true
 615          now = Time.now
 616          timeout = timelimit - now
 617          if timeout <= 0
 618            raise ResolvTimeout
 619          end
 620          select_result = IO.select(@socks, nil, nil, timeout)
 621          if !select_result
 622            raise ResolvTimeout
 623          end
 624          reply, from = recv_reply(select_result[0])
 625          begin
 626            msg = Message.decode(reply)
 627          rescue DecodeError
 628            next # broken DNS message ignored
 629          end
 630          if s = @senders[[from,msg.id]]
 631            break
 632          else
 633            # unexpected DNS message ignored
 634          end
 635        end
 636        return msg, s.data
 637      end
 638
 639      def close
 640        socks = @socks
 641        @socks = nil
 642        if socks
 643          socks.each {|sock| sock.close }
 644        end
 645      end
 646
 647      class Sender # :nodoc:
 648        def initialize(msg, data, sock)
 649          @msg = msg
 650          @data = data
 651          @sock = sock
 652        end
 653      end
 654
 655      class UnconnectedUDP < Requester # :nodoc:
 656        def initialize(*nameserver_port)
 657          super()
 658          @nameserver_port = nameserver_port
 659          @socks_hash = {}
 660          @socks = []
 661          nameserver_port.each {|host, port|
 662            if host.index(':')
 663              bind_host = "::"
 664              af = Socket::AF_INET6
 665            else
 666              bind_host = "0.0.0.0"
 667              af = Socket::AF_INET
 668            end
 669            next if @socks_hash[bind_host]
 670            sock = UDPSocket.new(af)
 671            sock.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC) if defined? Fcntl::F_SETFD
 672            DNS.bind_random_port(sock, bind_host)
 673            @socks << sock
 674            @socks_hash[bind_host] = sock
 675          }
 676        end
 677
 678        def recv_reply(readable_socks)
 679          reply, from = readable_socks[0].recvfrom(UDPSize)
 680          return reply, [from[3],from[1]]
 681        end
 682
 683        def sender(msg, data, host, port=Port)
 684          service = [host, port]
 685          id = DNS.allocate_request_id(host, port)
 686          request = msg.encode
 687          request[0,2] = [id].pack('n')
 688          sock = @socks_hash[host.index(':') ? "::" : "0.0.0.0"]
 689          return @senders[[service, id]] =
 690            Sender.new(request, data, sock, host, port)
 691        end
 692
 693        def close
 694          super
 695          @senders.each_key {|service, id|
 696            DNS.free_request_id(service[0], service[1], id)
 697          }
 698        end
 699
 700        class Sender < Requester::Sender # :nodoc:
 701          def initialize(msg, data, sock, host, port)
 702            super(msg, data, sock)
 703            @host = host
 704            @port = port
 705          end
 706          attr_reader :data
 707
 708          def send
 709            @sock.send(@msg, 0, @host, @port)
 710          end
 711        end
 712      end
 713
 714      class ConnectedUDP < Requester # :nodoc:
 715        def initialize(host, port=Port)
 716          super()
 717          @host = host
 718          @port = port
 719          is_ipv6 = host.index(':')
 720          sock = UDPSocket.new(is_ipv6 ? Socket::AF_INET6 : Socket::AF_INET)
 721          @socks = [sock]
 722          sock.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC) if defined? Fcntl::F_SETFD
 723          DNS.bind_random_port(sock, is_ipv6 ? "::" : "0.0.0.0")
 724          sock.connect(host, port)
 725        end
 726
 727        def recv_reply(readable_socks)
 728          reply = readable_socks[0].recv(UDPSize)
 729          return reply, nil
 730        end
 731
 732        def sender(msg, data, host=@host, port=@port)
 733          unless host == @host && port == @port
 734            raise RequestError.new("host/port don't match: #{host}:#{port}")
 735          end
 736          id = DNS.allocate_request_id(@host, @port)
 737          request = msg.encode
 738          request[0,2] = [id].pack('n')
 739          return @senders[[nil,id]] = Sender.new(request, data, @socks[0])
 740        end
 741
 742        def close
 743          super
 744          @senders.each_key {|from, id|
 745            DNS.free_request_id(@host, @port, id)
 746          }
 747        end
 748
 749        class Sender < Requester::Sender # :nodoc:
 750          def send
 751            @sock.send(@msg, 0)
 752          end
 753          attr_reader :data
 754        end
 755      end
 756
 757      class TCP < Requester # :nodoc:
 758        def initialize(host, port=Port)
 759          super()
 760          @host = host
 761          @port = port
 762          sock = TCPSocket.new(@host, @port)
 763          @socks = [sock]
 764          sock.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC) if defined? Fcntl::F_SETFD
 765          @senders = {}
 766        end
 767
 768        def recv_reply(readable_socks)
 769          len = readable_socks[0].read(2).unpack('n')[0]
 770          reply = @socks[0].read(len)
 771          return reply, nil
 772        end
 773
 774        def sender(msg, data, host=@host, port=@port)
 775          unless host == @host && port == @port
 776            raise RequestError.new("host/port don't match: #{host}:#{port}")
 777          end
 778          id = DNS.allocate_request_id(@host, @port)
 779          request = msg.encode
 780          request[0,2] = [request.length, id].pack('nn')
 781          return @senders[[nil,id]] = Sender.new(request, data, @socks[0])
 782        end
 783
 784        class Sender < Requester::Sender # :nodoc:
 785          def send
 786            @sock.print(@msg)
 787            @sock.flush
 788          end
 789          attr_reader :data
 790        end
 791
 792        def close
 793          super
 794          @senders.each_key {|from,id|
 795            DNS.free_request_id(@host, @port, id)
 796          }
 797        end
 798      end
 799
 800      ##
 801      # Indicates a problem with the DNS request.
 802
 803      class RequestError < StandardError
 804      end
 805    end
 806
 807    class Config # :nodoc:
 808      def initialize(config_info=nil)
 809        @mutex = Mutex.new
 810        @config_info = config_info
 811        @initialized = nil
 812      end
 813
 814      def Config.parse_resolv_conf(filename)
 815        nameserver = []
 816        search = nil
 817        ndots = 1
 818        open(filename) {|f|
 819          f.each {|line|
 820            line.sub!(/[#;].*/, '')
 821            keyword, *args = line.split(/\s+/)
 822            args.each { |arg|
 823              arg.untaint
 824            }
 825            next unless keyword
 826            case keyword
 827            when 'nameserver'
 828              nameserver += args
 829            when 'domain'
 830              next if args.empty?
 831              search = [args[0]]
 832            when 'search'
 833              next if args.empty?
 834              search = args
 835            when 'options'
 836              args.each {|arg|
 837                case arg
 838                when /\Andots:(\d+)\z/
 839                  ndots = $1.to_i
 840                end
 841              }
 842            end
 843          }
 844        }
 845        return { :nameserver => nameserver, :search => search, :ndots => ndots }
 846      end
 847
 848      def Config.default_config_hash(filename="/etc/resolv.conf")
 849        if File.exist? filename
 850          config_hash = Config.parse_resolv_conf(filename)
 851        else
 852          if /mswin32|cygwin|mingw|bccwin/ =~ RUBY_PLATFORM
 853            require 'win32/resolv'
 854            search, nameserver = Win32::Resolv.get_resolv_info
 855            config_hash = {}
 856            config_hash[:nameserver] = nameserver if nameserver
 857            config_hash[:search] = [search].flatten if search
 858          end
 859        end
 860        config_hash
 861      end
 862
 863      def lazy_initialize
 864        @mutex.synchronize {
 865          unless @initialized
 866            @nameserver = []
 867            @search = nil
 868            @ndots = 1
 869            case @config_info
 870            when nil
 871              config_hash = Config.default_config_hash
 872            when String
 873              config_hash = Config.parse_resolv_conf(@config_info)
 874            when Hash
 875              config_hash = @config_info.dup
 876              if String === config_hash[:nameserver]
 877                config_hash[:nameserver] = [config_hash[:nameserver]]
 878              end
 879              if String === config_hash[:search]
 880                config_hash[:search] = [config_hash[:search]]
 881              end
 882            else
 883              raise ArgumentError.new("invalid resolv configuration: #{@config_info.inspect}")
 884            end
 885            @nameserver = config_hash[:nameserver] if config_hash.include? :nameserver
 886            @search = config_hash[:search] if config_hash.include? :search
 887            @ndots = config_hash[:ndots] if config_hash.include? :ndots
 888
 889            @nameserver = ['0.0.0.0'] if @nameserver.empty?
 890            if @search
 891              @search = @search.map {|arg| Label.split(arg) }
 892            else
 893              hostname = Socket.gethostname
 894              if /\./ =~ hostname
 895                @search = [Label.split($')]
 896              else
 897                @search = [[]]
 898              end
 899            end
 900
 901            if !@nameserver.kind_of?(Array) ||
 902               !@nameserver.all? {|ns| String === ns }
 903              raise ArgumentError.new("invalid nameserver config: #{@nameserver.inspect}")
 904            end
 905
 906            if !@search.kind_of?(Array) ||
 907               !@search.all? {|ls| ls.all? {|l| Label::Str === l } }
 908              raise ArgumentError.new("invalid search config: #{@search.inspect}")
 909            end
 910
 911            if !@ndots.kind_of?(Integer)
 912              raise ArgumentError.new("invalid ndots config: #{@ndots.inspect}")
 913            end
 914
 915            @initialized = true
 916          end
 917        }
 918        self
 919      end
 920
 921      def single?
 922        lazy_initialize
 923        if @nameserver.length == 1
 924          return @nameserver[0]
 925        else
 926          return nil
 927        end
 928      end
 929
 930      def nameserver_port
 931        lazy_initialize
 932        @nameserver_port ||= @nameserver.map {|i| [i, Port] }
 933        @nameserver_port
 934      end
 935
 936      def generate_candidates(name)
 937        candidates = nil
 938        name = Name.create(name)
 939        if name.absolute?
 940          candidates = [name]
 941        else
 942          if @ndots <= name.length - 1
 943            candidates = [Name.new(name.to_a)]
 944          else
 945            candidates = []
 946          end
 947          candidates.concat(@search.map {|domain| Name.new(name.to_a + domain)})
 948        end
 949        return candidates
 950      end
 951
 952      InitialTimeout = 5
 953
 954      def generate_timeouts
 955        ts = [InitialTimeout]
 956        ts << ts[-1] * 2 / @nameserver.length
 957        ts << ts[-1] * 2
 958        ts << ts[-1] * 2
 959        return ts
 960      end
 961
 962      def resolv(name)
 963        candidates = generate_candidates(name)
 964        timeouts = generate_timeouts
 965        begin
 966          candidates.each {|candidate|
 967            begin
 968              timeouts.each {|tout|
 969                @nameserver.each {|nameserver|
 970                  begin
 971                    yield candidate, tout, nameserver
 972                  rescue ResolvTimeout
 973                  end
 974                }
 975              }
 976              raise ResolvError.new("DNS resolv timeout: #{name}")
 977            rescue NXDomain
 978            end
 979          }
 980        rescue ResolvError
 981        end
 982      end
 983
 984      ##
 985      # Indicates no such domain was found.
 986
 987      class NXDomain < ResolvError
 988      end
 989
 990      ##
 991      # Indicates some other unhandled resolver error was encountered.
 992
 993      class OtherResolvError < ResolvError
 994      end
 995    end
 996
 997    module OpCode # :nodoc:
 998      Query = 0
 999      IQuery = 1
1000      Status = 2
1001      Notify = 4
1002      Update = 5
1003    end
1004
1005    module RCode # :nodoc:
1006      NoError = 0
1007      FormErr = 1
1008      ServFail = 2
1009      NXDomain = 3
1010      NotImp = 4
1011      Refused = 5
1012      YXDomain = 6
1013      YXRRSet = 7
1014      NXRRSet = 8
1015      NotAuth = 9
1016      NotZone = 10
1017      BADVERS = 16
1018      BADSIG = 16
1019      BADKEY = 17
1020      BADTIME = 18
1021      BADMODE = 19
1022      BADNAME = 20
1023      BADALG = 21
1024    end
1025
1026    ##
1027    # Indicates that the DNS response was unable to be decoded.
1028
1029    class DecodeError < StandardError
1030    end
1031
1032    ##
1033    # Indicates that the DNS request was unable to be encoded.
1034
1035    class EncodeError < StandardError
1036    end
1037
1038    module Label # :nodoc:
1039      def self.split(arg)
1040        labels = []
1041        arg.scan(/[^\.]+/) {labels << Str.new($&)}
1042        return labels
1043      end
1044
1045      class Str # :nodoc:
1046        def initialize(string)
1047          @string = string
1048          @downcase = string.downcase
1049        end
1050        attr_reader :string, :downcase
1051
1052        def to_s
1053          return @string
1054        end
1055
1056        def inspect
1057          return "#<#{self.class} #{self.to_s}>"
1058        end
1059
1060        def ==(other)
1061          return @downcase == other.downcase
1062        end
1063
1064        def eql?(other)
1065          return self == other
1066        end
1067
1068        def hash
1069          return @downcase.hash
1070        end
1071      end
1072    end
1073
1074    ##
1075    # A representation of a DNS name.
1076
1077    class Name
1078      
1079      ##
1080      # Creates a new DNS name from +arg+.  +arg+ can be:
1081      #
1082      # Name:: returns +arg+.
1083      # String:: Creates a new Name.
1084
1085      def self.create(arg)
1086        case arg
1087        when Name
1088          return arg
1089        when String
1090          return Name.new(Label.split(arg), /\.\z/ =~ arg ? true : false)
1091        else
1092          raise ArgumentError.new("cannot interpret as DNS name: #{arg.inspect}")
1093        end
1094      end
1095
1096      def initialize(labels, absolute=true) # :nodoc:
1097        @labels = labels
1098        @absolute = absolute
1099      end
1100
1101      def inspect # :nodoc:
1102        "#<#{self.class}: #{self.to_s}#{@absolute ? '.' : ''}>"
1103      end
1104
1105      ##
1106      # True if this name is absolute.
1107
1108      def absolute?
1109        return @absolute
1110      end
1111
1112      def ==(other) # :nodoc:
1113        return false unless Name === other
1114        return @labels.join == other.to_a.join && @absolute == other.absolute?
1115      end
1116
1117      alias eql? == # :nodoc:
1118
1119      ##
1120      # Returns true if +other+ is a subdomain.
1121      #
1122      # Example:
1123      #
1124      #   domain = Resolv::DNS::Name.create("y.z")
1125      #   p Resolv::DNS::Name.create("w.x.y.z").subdomain_of?(domain) #=> true
1126      #   p Resolv::DNS::Name.create("x.y.z").subdomain_of?(domain) #=> true
1127      #   p Resolv::DNS::Name.create("y.z").subdomain_of?(domain) #=> false
1128      #   p Resolv::DNS::Name.create("z").subdomain_of?(domain) #=> false
1129      #   p Resolv::DNS::Name.create("x.y.z.").subdomain_of?(domain) #=> false
1130      #   p Resolv::DNS::Name.create("w.z").subdomain_of?(domain) #=> false
1131      #
1132
1133      def subdomain_of?(other)
1134        raise ArgumentError, "not a domain name: #{other.inspect}" unless Name === other
1135        return false if @absolute != other.absolute?
1136        other_len = other.length
1137        return false if @labels.length <= other_len
1138        return @labels[-other_len, other_len] == other.to_a
1139      end
1140
1141      def hash # :nodoc:
1142        return @labels.hash ^ @absolute.hash
1143      end
1144
1145      def to_a # :nodoc:
1146        return @labels
1147      end
1148
1149      def length # :nodoc:
1150        return @labels.length
1151      end
1152
1153      def [](i) # :nodoc:
1154        return @labels[i]
1155      end
1156
1157      ##
1158      # returns the domain name as a string.
1159      #
1160      # The domain name doesn't have a trailing dot even if the name object is
1161      # absolute.
1162      #
1163      # Example:
1164      #
1165      #   p Resolv::DNS::Name.create("x.y.z.").to_s #=> "x.y.z"
1166      #   p Resolv::DNS::Name.create("x.y.z").to_s #=> "x.y.z"
1167
1168      def to_s
1169        return @labels.join('.')
1170      end
1171    end
1172
1173    class Message # :nodoc:
1174      @@identifier = -1
1175
1176      def initialize(id = (@@identifier += 1) & 0xffff)
1177        @id = id
1178        @qr = 0
1179        @opcode = 0
1180        @aa = 0
1181        @tc = 0
1182        @rd = 0 # recursion desired
1183        @ra = 0 # recursion available
1184        @rcode = 0
1185        @question = []
1186        @answer = []
1187        @authority = []
1188        @additional = []
1189      end
1190
1191      attr_accessor :id, :qr, :opcode, :aa, :tc, :rd, :ra, :rcode
1192      attr_reader :question, :answer, :authority, :additional
1193
1194      def ==(other)
1195        return @id == other.id &&
1196               @qr == other.qr &&
1197               @opcode == other.opcode &&
1198               @aa == other.aa &&
1199               @tc == other.tc &&
1200               @rd == other.rd &&
1201               @ra == other.ra &&
1202               @rcode == other.rcode &&
1203               @question == other.question &&
1204               @answer == other.answer &&
1205               @authority == other.authority &&
1206               @additional == other.additional
1207      end
1208
1209      def add_question(name, typeclass)
1210        @question << [Name.create(name), typeclass]
1211      end
1212
1213      def each_question
1214        @question.each {|name, typeclass|
1215          yield name, typeclass
1216        }
1217      end
1218
1219      def add_answer(name, ttl, data)
1220        @answer << [Name.create(name), ttl, data]
1221      end
1222
1223      def each_answer
1224        @answer.each {|name, ttl, data|
1225          yield name, ttl, data
1226        }
1227      end
1228
1229      def add_authority(name, ttl, data)
1230        @authority << [Name.create(name), ttl, data]
1231      end
1232
1233      def each_authority
1234        @authority.each {|name, ttl, data|
1235          yield name, ttl, data
1236        }
1237      end
1238
1239      def add_additional(name, ttl, data)
1240        @additional << [Name.create(name), ttl, data]
1241      end
1242
1243      def each_additional
1244        @additional.each {|name, ttl, data|
1245          yield name, ttl, data
1246        }
1247      end
1248
1249      def each_resource
1250        each_answer {|name, ttl, data| yield name, ttl, data}
1251        each_authority {|name, ttl, data| yield name, ttl, data}
1252        each_additional {|name, ttl, data| yield name, ttl, data}
1253      end
1254
1255      def encode
1256        return MessageEncoder.new {|msg|
1257          msg.put_pack('nnnnnn',
1258            @id,
1259            (@qr & 1) << 15 |
1260            (@opcode & 15) << 11 |
1261            (@aa & 1) << 10 |
1262            (@tc & 1) << 9 |
1263            (@rd & 1) << 8 |
1264            (@ra & 1) << 7 |
1265            (@rcode & 15),
1266            @question.length,
1267            @answer.length,
1268            @authority.length,
1269            @additional.length)
1270          @question.each {|q|
1271            name, typeclass = q
1272            msg.put_name(name)
1273            msg.put_pack('nn', typeclass::TypeValue, typeclass::ClassValue)
1274          }
1275          [@answer, @authority, @additional].each {|rr|
1276            rr.each {|r|
1277              name, ttl, data = r
1278              msg.put_name(name)
1279              msg.put_pack('nnN', data.class::TypeValue, data.class::ClassValue, ttl)
1280              msg.put_length16 {data.encode_rdata(msg)}
1281            }
1282          }
1283        }.to_s
1284      end
1285
1286      class MessageEncoder # :nodoc:
1287        def initialize
1288          @data = ''
1289          @names = {}
1290          yield self
1291        end
1292
1293        def to_s
1294          return @data
1295        end
1296
1297        def put_bytes(d)
1298          @data << d
1299        end
1300
1301        def put_pack(template, *d)
1302          @data << d.pack(template)
1303        end
1304
1305        def put_length16
1306          length_index = @data.length
1307          @data << "\0\0"
1308          data_start = @data.length
1309          yield
1310          data_end = @data.length
1311          @data[length_index, 2] = [data_end - data_start].pack("n")
1312        end
1313
1314        def put_string(d)
1315          self.put_pack("C", d.length)
1316          @data << d
1317        end
1318
1319        def put_string_list(ds)
1320          ds.each {|d|
1321            self.put_string(d)
1322          }
1323        end
1324
1325        def put_name(d)
1326          put_labels(d.to_a)
1327        end
1328
1329        def put_labels(d)
1330          d.each_index {|i|
1331            domain = d[i..-1]
1332            if idx = @names[domain]
1333              self.put_pack("n", 0xc000 | idx)
1334              return
1335            else
1336              @names[domain] = @data.length
1337              self.put_label(d[i])
1338            end
1339          }
1340          @data << "\0"
1341        end
1342
1343        def put_label(d)
1344          self.put_string(d.to_s)
1345        end
1346      end
1347
1348      def Message.decode(m)
1349        o = Message.new(0)
1350        MessageDecoder.new(m) {|msg|
1351          id, flag, qdcount, ancount, nscount, arcount =
1352            msg.get_unpack('nnnnnn')
1353          o.id = id
1354          o.qr = (flag >> 15) & 1
1355          o.opcode = (flag >> 11) & 15
1356          o.aa = (flag >> 10) & 1
1357          o.tc = (flag >> 9) & 1
1358          o.rd = (flag >> 8) & 1
1359          o.ra = (flag >> 7) & 1
1360          o.rcode = flag & 15
1361          (1..qdcount).each {
1362            name, typeclass = msg.get_question
1363            o.add_question(name, typeclass)
1364          }
1365          (1..ancount).each {
1366            name, ttl, data = msg.get_rr
1367            o.add_answer(name, ttl, data)
1368          }
1369          (1..nscount).each {
1370            name, ttl, data = msg.get_rr
1371            o.add_authority(name, ttl, data)
1372          }
1373          (1..arcount).each {
1374            name, ttl, data = msg.get_rr
1375            o.add_additional(name, ttl, data)
1376          }
1377        }
1378        return o
1379      end
1380
1381      class MessageDecoder # :nodoc:
1382        def initialize(data)
1383          @data = data
1384          @index = 0
1385          @limit = data.length
1386          yield self
1387        end
1388
1389        def get_length16
1390          len, = self.get_unpack('n')
1391          save_limit = @limit
1392          @limit = @index + len
1393          d = yield(len)
1394          if @index < @limit
1395            raise DecodeError.new("junk exists")
1396          elsif @limit < @index
1397            raise DecodeError.new("limit exceeded")
1398          end
1399          @limit = save_limit
1400          return d
1401        end
1402
1403        def get_bytes(len = @limit - @index)
1404          d = @data[@index, len]
1405          @index += len
1406          return d
1407        end
1408
1409        def get_unpack(template)
1410          len = 0
1411          template.each_byte {|byte|
1412            case byte
1413            when ?c, ?C
1414              len += 1
1415            when ?n
1416              len += 2
1417            when ?N
1418              len += 4
1419            else
1420              raise StandardError.new("unsupported template: '#{byte.chr}' in '#{template}'")
1421            end
1422          }
1423          raise DecodeError.new("limit exceeded") if @limit < @index + len
1424          arr = @data.unpack("@#{@index}#{template}")
1425          @index += len
1426          return arr
1427        end
1428
1429        def get_string
1430          len = @data[@index]
1431          raise DecodeError.new("limit exceeded") if @limit < @index + 1 + len
1432          d = @data[@index + 1, len]
1433          @index += 1 + len
1434          return d
1435        end
1436
1437        def get_string_list
1438          strings = []
1439          while @index < @limit
1440            strings << self.get_string
1441          end
1442          strings
1443        end
1444
1445        def get_name
1446          return Name.new(self.get_labels)
1447        end
1448
1449        def get_labels(limit=nil)
1450          limit = @index if !limit || @index < limit
1451          d = []
1452          while true
1453            case @data[@index]
1454            when 0
1455              @index += 1
1456              return d
1457            when 192..255
1458              idx = self.get_unpack('n')[0] & 0x3fff
1459              if limit <= idx
1460                raise DecodeError.new("non-backward name pointer")
1461              end
1462              save_index = @index
1463              @index = idx
1464              d += self.get_labels(limit)
1465              @index = save_index
1466              return d
1467            else
1468              d << self.get_label
1469            end
1470          end
1471          return d
1472        end
1473
1474        def get_label
1475          return Label::Str.new(self.get_string)
1476        end
1477
1478        def get_question
1479          name = self.get_name
1480          type, klass = self.get_unpack("nn")
1481          return name, Resource.get_class(type, klass)
1482        end
1483
1484        def get_rr
1485          name = self.get_name
1486          type, klass, ttl = self.get_unpack('nnN')
1487          typeclass = Resource.get_class(type, klass)
1488          return name, ttl, self.get_length16 {typeclass.decode_rdata(self)}
1489        end
1490      end
1491    end
1492
1493    ##
1494    # A DNS query abstract class.
1495
1496    class Query
1497      def encode_rdata(msg) # :nodoc:
1498        raise EncodeError.new("#{self.class} is query.") 
1499      end
1500
1501      def self.decode_rdata(msg) # :nodoc:
1502        raise DecodeError.new("#{self.class} is query.") 
1503      end
1504    end
1505
1506    ##
1507    # A DNS resource abstract class.
1508
1509    class Resource < Query
1510
1511      ##
1512      # Remaining Time To Live for this Resource.
1513
1514      attr_reader :ttl
1515
1516      ClassHash = {} # :nodoc:
1517
1518      def encode_rdata(msg) # :nodoc:
1519        raise NotImplementedError.new
1520      end
1521
1522      def self.decode_rdata(msg) # :nodoc:
1523        raise NotImplementedError.new
1524      end
1525
1526      def ==(other) # :nodoc:
1527        return self.class == other.class &&
1528          self.instance_variables == other.instance_variables &&
1529          self.instance_variables.collect {|name| self.instance_eval name} ==
1530            other.instance_variables.collect {|name| other.instance_eval name}
1531      end
1532
1533      def eql?(other) # :nodoc:
1534        return self == other
1535      end
1536
1537      def hash # :nodoc:
1538        h = 0
1539        self.instance_variables.each {|name|
1540          h ^= self.instance_eval("#{name}.hash")
1541        }
1542        return h
1543      end
1544
1545      def self.get_class(type_value, class_value) # :nodoc:
1546        return ClassHash[[type_value, class_value]] ||
1547               Generic.create(type_value, class_value)
1548      end
1549
1550      ##
1551      # A generic resource abstract class.
1552
1553      class Generic < Resource
1554
1555        ##
1556        # Creates a new generic resource.
1557
1558        def initialize(data)
1559          @data = data
1560        end
1561
1562        ##
1563        # Data for this generic resource.
1564
1565        attr_reader :data
1566
1567        def encode_rdata(msg) # :nodoc:
1568          msg.put_bytes(data)
1569        end
1570
1571        def self.decode_rdata(msg) # :nodoc:
1572          return self.new(msg.get_bytes)
1573        end
1574
1575        def self.create(type_value, class_value) # :nodoc:
1576          c = Class.new(Generic)
1577          c.const_set(:TypeValue, type_value)
1578          c.const_set(:ClassValue, class_value)
1579          Generic.const_set("Type#{type_value}_Class#{class_value}", c)
1580          ClassHash[[type_value, class_value]] = c
1581          return c
1582        end
1583      end
1584
1585      ##
1586      # Domain Name resource abstract class.
1587
1588      class DomainName < Resource
1589
1590        ##
1591        # Creates a new DomainName from +name+.
1592
1593        def initialize(name)
1594          @name = name
1595        end
1596
1597        ##
1598        # The name of this DomainName.
1599
1600        attr_reader :name
1601
1602        def encode_rdata(msg) # :nodoc:
1603          msg.put_name(@name)
1604        end
1605
1606        def self.decode_rdata(msg) # :nodoc:
1607          return self.new(msg.get_name)
1608        end
1609      end
1610
1611      # Standard (class generic) RRs
1612
1613      ClassValue = nil # :nodoc:
1614
1615      ##
1616      # An authoritative name server.
1617
1618      class NS < DomainName
1619        TypeValue = 2 # :nodoc:
1620      end
1621
1622      ##
1623      # The canonical name for an alias.
1624
1625      class CNAME < DomainName
1626        TypeValue = 5 # :nodoc:
1627      end
1628
1629      ##
1630      # Start Of Authority resource.
1631
1632      class SOA < Resource
1633
1634        TypeValue = 6 # :nodoc:
1635
1636        ##
1637        # Creates a new SOA record.  See the attr documentation for the
1638        # details of each argument.
1639
1640        def initialize(mname, rname, serial, refresh, retry_, expire, minimum)
1641          @mname = mname
1642          @rname = rname
1643          @serial = serial
1644          @refresh = refresh
1645          @retry = retry_
1646          @expire = expire
1647          @minimum = minimum
1648        end
1649
1650        ##
1651        # Name of the host where the master zone file for this zone resides.
1652
1653        attr_reader :mname
1654
1655        ##
1656        # The person responsible for this domain name.
1657
1658        attr_reader :rname
1659
1660        ##
1661        # The version number of the zone file.
1662
1663        attr_reader :serial
1664
1665        ##
1666        # How often, in seconds, a secondary name server is to check for
1667        # updates from the primary name server.
1668
1669        attr_reader :refresh
1670
1671        ##
1672        # How often, in seconds, a secondary name server is to retry after a
1673        # failure to check for a refresh.
1674
1675        attr_reader :retry
1676
1677        ##
1678        # Time in seconds that a secondary name server is to use the data
1679        # before refreshing from the primary name server.
1680
1681        attr_reader :expire
1682
1683        ##
1684        # The minimum number of seconds to be used for TTL values in RRs.
1685
1686        attr_reader :minimum
1687
1688        def encode_rdata(msg) # :nodoc:
1689          msg.put_name(@mname)
1690          msg.put_name(@rname)
1691          msg.put_pack('NNNNN', @serial, @refresh, @retry, @expire, @minimum)
1692        end
1693
1694        def self.decode_rdata(msg) # :nodoc:
1695          mname = msg.get_name
1696          rname = msg.get_name
1697          serial, refresh, retry_, expire, minimum = msg.get_unpack('NNNNN')
1698          return self.new(
1699            mname, rname, serial, refresh, retry_, expire, minimum)
1700        end
1701      end
1702
1703      ##
1704      # A Pointer to another DNS name.
1705
1706      class PTR < DomainName
1707        TypeValue = 12 # :nodoc:
1708      end
1709
1710      ##
1711      # Host Information resource.
1712
1713      class HINFO < Resource
1714
1715        TypeValue = 13 # :nodoc:
1716
1717        ##
1718        # Creates a new HINFO running +os+ on +cpu+.
1719
1720        def initialize(cpu, os)
1721          @cpu = cpu
1722          @os = os
1723        end
1724
1725        ##
1726        # CPU architecture for this resource.
1727
1728        attr_reader :cpu
1729
1730        ##
1731        # Operating system for this resource.
1732
1733        attr_reader :os
1734
1735        def encode_rdata(msg) # :nodoc:
1736          msg.put_string(@cpu)
1737          msg.put_string(@os)
1738        end
1739
1740        def self.decode_rdata(msg) # :nodoc:
1741          cpu = msg.get_string
1742          os = msg.get_string
1743          return self.new(cpu, os)
1744        end
1745      end
1746
1747      ##
1748      # Mailing list or mailbox information.
1749
1750      class MINFO < Resource
1751
1752        TypeValue = 14 # :nodoc:
1753
1754        def initialize(rmailbx, emailbx)
1755          @rmailbx = rmailbx
1756          @emailbx = emailbx
1757        end
1758
1759        ##
1760        # Domain name responsible for this mail list or mailbox.
1761
1762        attr_reader :rmailbx
1763
1764        ##
1765        # Mailbox to use for error messages related to the mail list or mailbox.
1766
1767        attr_reader :emailbx
1768
1769        def encode_rdata(msg) # :nodoc:
1770          msg.put_name(@rmailbx)
1771          msg.put_name(@emailbx)
1772        end
1773
1774        def self.decode_rdata(msg) # :nodoc:
1775          rmailbx = msg.get_string
1776          emailbx = msg.get_string
1777          return self.new(rmailbx, emailbx)
1778        end
1779      end
1780
1781      ##
1782      # Mail Exchanger resource.
1783
1784      class MX < Resource
1785
1786        TypeValue= 15 # :nodoc:
1787
1788        ##
1789        # Creates a new MX record with +preference+, accepting mail at
1790        # +exchange+.
1791
1792        def initialize(preference, exchange)
1793          @preference = preference
1794          @exchange = exchange
1795        end
1796
1797        ##
1798        # The preference for this MX.
1799
1800        attr_reader :preference
1801
1802        ##
1803        # The host of this MX.
1804
1805        attr_reader :exchange
1806
1807        def encode_rdata(msg) # :nodoc:
1808          msg.put_pack('n', @preference)
1809          msg.put_name(@exchange)
1810        end
1811
1812        def self.decode_rdata(msg) # :nodoc:
1813          preference, = msg.get_unpack('n')
1814          exchange = msg.get_name
1815          return self.new(preference, exchange)
1816        end
1817      end
1818
1819      ##
1820      # Unstructured text resource.
1821
1822      class TXT < Resource
1823
1824        TypeValue = 16 # :nodoc:
1825
1826        def initialize(first_string, *rest_strings)
1827          @strings = [first_string, *rest_strings]
1828        end
1829
1830        ##
1831        # Returns an Array of Strings for this TXT record.
1832
1833        attr_reader :strings
1834
1835        ##
1836        # Returns the first string from +strings+.
1837
1838        def data
1839          @strings[0]
1840        end
1841
1842        def encode_rdata(msg) # :nodoc:
1843          msg.put_string_list(@strings)
1844        end
1845
1846        def self.decode_rdata(msg) # :nodoc:
1847          strings = msg.get_string_list
1848          return self.new(*strings)
1849        end
1850      end
1851
1852      ##
1853      # A Query type requesting any RR.
1854
1855      class ANY < Query
1856        TypeValue = 255 # :nodoc:
1857      end
1858
1859      ClassInsensitiveTypes = [ # :nodoc:
1860        NS, CNAME, SOA, PTR, HINFO, MINFO, MX, TXT, ANY
1861      ]
1862
1863      ##
1864      # module IN contains ARPA Internet specific RRs.
1865
1866      module IN
1867
1868        ClassValue = 1 # :nodoc:
1869
1870        ClassInsensitiveTypes.each {|s|
1871          c = Class.new(s)
1872          c.const_set(:TypeValue, s::TypeValue)
1873          c.const_set(:ClassValue, ClassValue)
1874          ClassHash[[s::TypeValue, ClassValue]] = c
1875          self.const_set(s.name.sub(/.*::/, ''), c)
1876        }
1877
1878        ##
1879        # IPv4 Address resource
1880
1881        class A < Resource
1882          TypeValue = 1
1883          ClassValue = IN::ClassValue
1884          ClassHash[[TypeValue, ClassValue]] = self # :nodoc:
1885
1886          ##
1887          # Creates a new A for +address+.
1888
1889          def initialize(address)
1890            @address = IPv4.create(address)
1891          end
1892
1893          ##
1894          # The Resolv::IPv4 address for this A.
1895
1896          attr_reader :address
1897
1898          def encode_rdata(msg) # :nodoc:
1899            msg.put_bytes(@address.address)
1900          end
1901
1902          def self.decode_rdata(msg) # :nodoc:
1903            return self.new(IPv4.new(msg.get_bytes(4)))
1904          end
1905        end
1906
1907        ##
1908        # Well Known Service resource.
1909
1910        class WKS < Resource
1911          TypeValue = 11
1912          ClassValue = IN::ClassValue
1913          ClassHash[[TypeValue, ClassValue]] = self # :nodoc:
1914
1915          def initialize(address, protocol, bitmap)
1916            @address = IPv4.create(address)
1917            @protocol = protocol
1918            @bitmap = bitmap
1919          end
1920
1921          ##
1922          # The host these services run on.
1923
1924          attr_reader :address
1925
1926          ##
1927          # IP protocol number for these services.
1928
1929          attr_reader :protocol
1930
1931          ##
1932          # A bit map of enabled services on this host.
1933          #
1934          # If protocol is 6 (TCP) then the 26th bit corresponds to the SMTP
1935          # service (port 25).  If this bit is set, then an SMTP server should
1936          # be listening on TCP port 25; if zero, SMTP service is not
1937          # supported.
1938
1939          attr_reader :bitmap
1940
1941          def encode_rdata(msg) # :nodoc:
1942            msg.put_bytes(@address.address)
1943            msg.put_pack("n", @protocol)
1944            msg.put_bytes(@bitmap)
1945          end
1946
1947          def self.decode_rdata(msg) # :nodoc:
1948            address = IPv4.new(msg.get_bytes(4))
1949            protocol, = msg.get_unpack("n")
1950            bitmap = msg.get_bytes
1951            return self.new(address, protocol, bitmap)
1952          end
1953        end
1954
1955        ##
1956        # An IPv6 address record.
1957
1958        class AAAA < Resource
1959          TypeValue = 28
1960          ClassValue = IN::ClassValue
1961          ClassHash[[TypeValue, ClassValue]] = self # :nodoc:
1962
1963          ##
1964          # Creates a new AAAA for +address+.
1965
1966          def initialize(address)
1967            @address = IPv6.create(address)
1968          end
1969          
1970          ##
1971          # The Resolv::IPv6 address for this AAAA.
1972
1973          attr_reader :address
1974
1975          def encode_rdata(msg) # :nodoc:
1976            msg.put_bytes(@address.address)
1977          end
1978
1979          def self.decode_rdata(msg) # :nodoc:
1980            return self.new(IPv6.new(msg.get_bytes(16)))
1981          end
1982        end
1983
1984        ##
1985        # SRV resource record defined in RFC 2782
1986        # 
1987        # These records identify the hostname and port that a service is
1988        # available at.
1989
1990        class SRV < Resource
1991          TypeValue = 33
1992          ClassValue = IN::ClassValue
1993          ClassHash[[TypeValue, ClassValue]] = self # :nodoc:
1994
1995          # Create a SRV resource record.
1996          #
1997          # See the documentation for #priority, #weight, #port and #target
1998          # for +…

Large files files are truncated, but you can click here to view the full file