PageRenderTime 33ms CodeModel.GetById 25ms RepoModel.GetById 1ms app.codeStats 0ms

/lib/resolv.rb

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