Class: Dnsruby::Recursor

Inherits:
Object
  • Object
show all
Defined in:
lib/dnsruby/recursor.rb

Overview

Dnsruby::Recursor - Perform recursive dns lookups

require 'Dnsruby'
rec = Dnsruby::Recursor.new()
answer = rec.query("rob.com.au")

This module uses a Dnsruby::Resolver to perform recursive queries.

AUTHOR

Rob Brown, [email protected] Alex Dalitz, [email protected]

SEE ALSO

Dnsruby::Resolver,

Copyright (c) 2002, Rob Brown. All rights reserved. Portions Copyright (c) 2005, Olaf M Kolkman. Ruby version with caching and validation Copyright (c) 2008, AlexD (Nominet UK)

Example lookup process:

[root@box root]# dig +trace www.rob.com.au.

; <<>> DiG 9.2.0 <<>> +trace www.rob.com.au. ;; global options: printcmd . 507343 IN NS C.ROOT-SERVERS.NET. . 507343 IN NS D.ROOT-SERVERS.NET. . 507343 IN NS E.ROOT-SERVERS.NET. . 507343 IN NS F.ROOT-SERVERS.NET. . 507343 IN NS G.ROOT-SERVERS.NET. . 507343 IN NS H.ROOT-SERVERS.NET. . 507343 IN NS I.ROOT-SERVERS.NET. . 507343 IN NS J.ROOT-SERVERS.NET. . 507343 IN NS K.ROOT-SERVERS.NET. . 507343 IN NS L.ROOT-SERVERS.NET. . 507343 IN NS M.ROOT-SERVERS.NET. . 507343 IN NS A.ROOT-SERVERS.NET. . 507343 IN NS B.ROOT-SERVERS.NET. ;; Received 436 bytes from 127.0.0.1#53(127.0.0.1) in 9 ms ;;; But these should be hard coded as the hints

;;; Ask H.ROOT-SERVERS.NET gave:

au. 172800 IN NS NS2.BERKELEY.EDU. au. 172800 IN NS NS1.BERKELEY.EDU. au. 172800 IN NS NS.UU.NET. au. 172800 IN NS BOX2.AUNIC.NET. au. 172800 IN NS SEC1.APNIC.NET. au. 172800 IN NS SEC3.APNIC.NET. ;; Received 300 bytes from 128.63.2.53#53(H.ROOT-SERVERS.NET) in 322 ms ;;; A little closer than before

;;; Ask NS2.BERKELEY.EDU gave:

com.au. 259200 IN NS ns4.ausregistry.net. com.au. 259200 IN NS dns1.telstra.net. com.au. 259200 IN NS au2ld.CSIRO.au. com.au. 259200 IN NS audns01.syd.optus.net. com.au. 259200 IN NS ns.ripe.net. com.au. 259200 IN NS ns1.ausregistry.net. com.au. 259200 IN NS ns2.ausregistry.net. com.au. 259200 IN NS ns3.ausregistry.net. com.au. 259200 IN NS ns3.melbourneit.com. ;; Received 387 bytes from 128.32.206.12#53(NS2.BERKELEY.EDU) in 10312 ms ;;; A little closer than before

;;; Ask ns4.ausregistry.net gave:

com.au. 259200 IN NS ns1.ausregistry.net. com.au. 259200 IN NS ns2.ausregistry.net. com.au. 259200 IN NS ns3.ausregistry.net. com.au. 259200 IN NS ns4.ausregistry.net. com.au. 259200 IN NS ns3.melbourneit.com. com.au. 259200 IN NS dns1.telstra.net. com.au. 259200 IN NS au2ld.CSIRO.au. com.au. 259200 IN NS ns.ripe.net. com.au. 259200 IN NS audns01.syd.optus.net. ;; Received 259 bytes from 137.39.1.3#53(ns4.ausregistry.net) in 606 ms ;;; Uh... yeah... I already knew this ;;; from what NS2.BERKELEY.EDU told me. ;;; ns4.ausregistry.net must have brain damage

;;; Ask ns1.ausregistry.net gave:

rob.com.au. 86400 IN NS sy-dns02.tmns.net.au. rob.com.au. 86400 IN NS sy-dns01.tmns.net.au. ;; Received 87 bytes from 203.18.56.41#53(ns1.ausregistry.net) in 372 ms ;;; Ah, much better. Something more useful.

;;; Ask sy-dns02.tmns.net.au gave:

www.rob.com.au. 7200 IN A 139.134.5.123 rob.com.au. 7200 IN NS sy-dns01.tmns.net.au. rob.com.au. 7200 IN NS sy-dns02.tmns.net.au. ;; Received 135 bytes from 139.134.2.18#53(sy-dns02.tmns.net.au) in 525 ms ;;; FINALLY, THE ANSWER! Now,DNSSEC validation is performed (unless disabled).

Defined Under Namespace

Classes: AddressCache

Constant Summary collapse

CACHE_LIMIT =
16_384
ADDRESS_CACHE_LIMIT =
256
DEFAULT_RECURSION_LIMITS =
{
  timeout: 30.0, max_queries: 128, max_steps: 256, max_workers: 8
}.freeze
@@mutex =

For guarding access to shared caches.

Mutex.new
@@hints_mutex =

:nodoc: all

Mutex.new
@@hints_generation =
0
@@stale_hints =
nil
@@hints =
nil
@@authority_cache =
Hash.new
@@zones_cache =
nil
@@zone_expirations =

Keep delegation lifetimes independent of the A/AAAA glue lifetimes. The stored Hash identity prevents stale metadata from expiring a replacement.

{}
@@nameservers =
nil

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(res = nil) ⇒ Recursor

Returns a new instance of Recursor.



301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
# File 'lib/dnsruby/recursor.rb', line 301

def initialize(res = nil)
  if (res)
    @resolver = res
  else
    nameservers = @@mutex.synchronize do
      # Hints already contain addresses. Re-resolving their owner names
      # would start separate bootstrap queries outside this lookup.
      if @@hints && !@@hints.equal?(@@stale_hints)
        @@hints.values.flat_map(&:values).uniq
      end
    end
    if nameservers && !nameservers.empty?
      @resolver = Resolver.new({:nameserver => nameservers})
    else
      @resolver = Resolver.new
    end
  end
  @resolver.dnssec = @dnssec
  @ipv6_ok = false
  @response_cache = Cache::ResolutionCache.new
end

Instance Attribute Details

#callback ⇒ Object

Returns the value of attribute callback.



278
279
280
# File 'lib/dnsruby/recursor.rb', line 278

def callback
  @callback
end

#dnssec ⇒ Object

Returns the value of attribute dnssec.



279
280
281
# File 'lib/dnsruby/recursor.rb', line 279

def dnssec
  @dnssec
end

#hints ⇒ Object

Returns the value of attribute hints.



279
280
281
# File 'lib/dnsruby/recursor.rb', line 279

def hints
  @hints
end

#ipv6_ok ⇒ Object

Returns the value of attribute ipv6_ok.



278
279
280
# File 'lib/dnsruby/recursor.rb', line 278

def ipv6_ok
  @ipv6_ok
end

#nameservers ⇒ Object

Returns the value of attribute nameservers.



278
279
280
# File 'lib/dnsruby/recursor.rb', line 278

def nameservers
  @nameservers
end

#recurse ⇒ Object

Returns the value of attribute recurse.



278
279
280
# File 'lib/dnsruby/recursor.rb', line 278

def recurse
  @recurse
end

#resolver ⇒ Object

The resolver to use for the queries



281
282
283
# File 'lib/dnsruby/recursor.rb', line 281

def resolver
  @resolver
end

Class Method Details

.cache_authority(name, addresses) ⇒ Object

These helpers are called with the shared cache mutex held. Root hints are retained as the recursion bootstrap; learned delegations are bounded.



561
562
563
564
565
566
567
568
569
570
# File 'lib/dnsruby/recursor.rb', line 561

def self.cache_authority(name, addresses) # :nodoc:
  unless @@mutex.owned?
    return @@mutex.synchronize { cache_authority(name, addresses) }
  end
  generation = Thread.current[:dnsruby_recursor_generation]
  return if generation && generation != @@hints_generation
  @@authority_cache.delete(name)
  @@authority_cache[name] = addresses.is_a?(AddressCache) ? addresses.snapshot : addresses.dup
  @@authority_cache.shift while @@authority_cache.length > CACHE_LIMIT
end

.cache_zone(name, authorities, ttl, parent: nil) ⇒ Object

:nodoc:



572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
# File 'lib/dnsruby/recursor.rb', line 572

def self.cache_zone(name, authorities, ttl, parent: nil) # :nodoc:
  unless @@mutex.owned?
    return @@mutex.synchronize { cache_zone(name, authorities, ttl, parent: parent) }
  end
  generation = Thread.current[:dnsruby_recursor_generation]
  return if generation && generation != @@hints_generation
  name = Name.create(name)
  name.absolute = true
  name = name.to_s(true).downcase
  if parent
    parent = Name.create(parent)
    parent.absolute = true
    parent = parent.to_s(true).downcase
  end
  return if name == "."
  @@zones_cache.delete(name)
  @@zone_expirations.delete(name)
  return if ttl.nil? || ttl <= 0
  expiration = Time.now + ttl
  if parent
    lifetime = @@zone_expirations[parent]
    # Retain the parent's deadline, not a reference to its cache entry.
    # LRU eviction must not invalidate descendants already learned, while
    # a descendant cannot extend its route beyond the parent admission.
    return unless lifetime && lifetime.first.equal?(@@zones_cache[parent])
    expiration = [expiration, lifetime[1]].min
    return if expiration <= Time.now
  end
  snapshot = authorities.transform_values { |addresses| addresses.is_a?(AddressCache) ? addresses.snapshot : addresses.dup }
  @@zones_cache[name] = snapshot
  @@zone_expirations[name] = [snapshot, expiration]
  while @@zones_cache.length > CACHE_LIMIT
    oldest = @@zones_cache.each_key.find { |zone| zone != "." }
    break unless oldest
    @@zones_cache.delete(oldest)
    @@zone_expirations.delete(oldest)
  end
end

.reset_hints ⇒ Object



353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
# File 'lib/dnsruby/recursor.rb', line 353

def self.reset_hints
  with_hints_configuration do
    @@mutex.synchronize do
      # Existing queries may still hold the previous root bootstrap.
      # Keep it readable until a replacement is ready, but require the
      # next query to refresh it and prevent old work from seeding caches.
      @@stale_hints = @@hints
      @@zones_cache = @@hints && {'.' => @@hints}
      @@nameservers = nil
      @@zone_expirations = {}
      @@authority_cache = {}
      @@hints_generation += 1
      Cache.invalidate_resolutions
    end
  end
end

.set_hints(hints, resolver) ⇒ Object



404
405
406
407
408
# File 'lib/dnsruby/recursor.rb', line 404

def self.set_hints(hints, resolver)
  with_limits(resolver) do
    with_hints_configuration { configure_hints(hints, resolver) }
  end
end

Instance Method Details

#_dorecursion(name, type, klass, known_zone, known_authorities, depth, no_validation) ⇒ Object

:nodoc:



885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
# File 'lib/dnsruby/recursor.rb', line 885

def _dorecursion(name, type, klass, known_zone, known_authorities, depth, no_validation) # :nodoc:
  QueryControl.current&.check!
  Recursor.send(:current_budget)&.step!

  if ( depth > 255 )
    TheLog.debug(";; _dorecursion() Recursion too deep, aborting...\n")
    @errorstring="Recursion too deep, aborted"
    return nil
  end

  known_zone = known_zone.sub(/\.*$/, ".")

  ns = [] # Snapshot each address list once for this hop.
  missing_authorities = []
  @@mutex.synchronize{
    #  Get IPs from authorities
    known_authorities.keys.each do |ns_rec|
      addresses = known_authorities[ns_rec]
      cached = @@authority_cache[ns_rec]
      values = addresses.is_a?(AddressCache) ? addresses.current_values : Array(addresses)
      cached_values = if values.empty?
        cached.respond_to?(:values) ? cached.values : Array(cached)
      end
      if !values.empty?
        Recursor.cache_authority(ns_rec, known_authorities[ns_rec])
        ns.push(values)
      elsif !cached_values.empty?
        known_authorities[ns_rec] = cached.is_a?(AddressCache) ? cached.snapshot : cached.dup
        ns.push(cached_values)
      else
        @@authority_cache.delete(ns_rec)
        missing_authorities << ns_rec
      end
    end
  }

  if known_zone == '.'
    if ns.empty?
      # Root addresses can expire after query admission, including while
      # finding an address for a delegated server. Refresh the bootstrap
      # instead of recursively looking up root servers against empty hints.
      Recursor.send(:ensure_hints, @resolver)
      ns = @@mutex.synchronize { Recursor.send(:query_hints).values.map(&:current_values).reject(&:empty?) }
      raise ResolvError, 'Root hints expired before use' if ns.empty?
      # Retain this query's original generation: a refresh or reset must
      # not let earlier traversal work populate the replacement caches.
    end
    # Missing root addresses need bootstrap refresh, not hostname lookup
    # through the same root servers after their other addresses fail.
    missing_authorities.clear
  end

  if (ns.length == 0)
    found_auth = 0
    TheLog.debug(";; _dorecursion() Failed to extract nameserver IPs:")
    TheLog.debug(known_authorities.inspect + @@authority_cache.inspect)
    missing_authorities.each do |ns_rec|
      TheLog.debug(";; _dorecursion() Manual lookup for authority [#{ns_rec}]")

      # Recursive lookups must run outside the shared cache mutex.
      # Propagate cancellation and validation policy into both workers.
      control = QueryControl.new(parent: QueryControl.current)
      transmission_budget = SelectThread::TransmissionBudget.current
      hints_generation = Thread.current[:dnsruby_recursor_generation]
      hints = @@mutex.synchronize { Recursor.send(:query_hints).dup }
      workers = []
      budget = Recursor.send(:current_budget)
      dependencies = Thread.current[:dnsruby_recursion_dependencies]
      results = QueryControl::Queue.new
      ans = []
      begin
        address_types = @ipv6_ok ? ['AAAA', 'A'] : ['A']
        address_types.each do |address_type|
          lookup = lambda do
            previous_dependencies = Thread.current[:dnsruby_recursion_dependencies]
            Thread.current[:dnsruby_recursion_dependencies] = dependencies
            begin
              answer = SelectThread::TransmissionBudget.with(transmission_budget) do
                QueryControl.with(control) do
                  local_hints = hints.transform_values do |addresses|
                    addresses.is_a?(AddressCache) ? addresses.snapshot(include_current: true) : addresses.dup
                  end
                  recurse = -> { follow_aliases(ns_rec, address_type, klass, '.', local_hints,
                    depth + 1, no_validation) }
                  budget ? budget.with_dependency(ns_rec, address_type, klass, &recurse) : recurse.call
                end
              end
              results << [answer, nil]
            rescue StandardError => error
              results << [nil, error]
            ensure
              Thread.current[:dnsruby_recursion_dependencies] = previous_dependencies
            end
          end
          reserved = !budget || budget.reserve_worker
          if reserved
            begin
              workers << Thread.new(lookup) do |operation|
                Thread.current.report_on_exception = false
                Thread.current[:dnsruby_recursor_generation] = hints_generation
                begin
                  operation.call
                ensure
                  budget&.release_worker
                end
              end
            rescue Exception
              budget&.release_worker
              raise
            end
          else
            lookup.call
          end
        end
        address_types.length.times do
          answer, error = control.pop(results)
          if error
            # A failed family or nameserver must not hide a usable
            # alternative. Budget failures and cancellation still stop
            # the entire operation, as do unexpected programming errors.
            raise error if error.is_a?(VerifyError) || error.is_a?(RecursionLimitError)
            case error
            when ResolvError, ResolvTimeout, IOError, SystemCallError
              TheLog.debug(";; _dorecursion() Address lookup failed: #{error}")
            else
              raise error
            end
          elsif answer
            ans << answer.answer
          end
        end
      ensure
        control.cancel
        # A failed lookup must not leave its sibling running.
        workers.each { |worker| worker.join rescue nil }
      end

      if ( ans.length > 0 )
        TheLog.debug(";; _dorecursion() Answers found for [#{ns_rec}]")
        #           foreach my $rr (@ans) {
        @@mutex.synchronize do
          ans.each do |rr_arr|
            rr_arr.each do |rr|
              TheLog.debug(";; RR:" + rr.inspect + "")
              if (rr.type == Types::CNAME)
                #  Follow CNAME
                server = rr.name.to_s.downcase
                if (server)
                  server.sub!(/\.*$/, ".")
                  if (server == ns_rec)
                    cname = rr.cname.to_s.downcase
                    cname.sub!(/\.*$/, ".")
                    TheLog.debug(";; _dorecursion() Following CNAME ns [#{ns_rec}] -> [#{cname}]")
                    if (!(known_authorities[cname]))
                      known_authorities[cname] = AddressCache.new
                    end
                    known_authorities.delete(ns_rec)
                    next
                  end
                end
              elsif (rr.type == Types::A || rr.type == Types::AAAA )
                server = rr.name.to_s.downcase
                if (server)
                  server.sub!(/\.*$/, ".")
                  if known_authorities.key?(server)
                    ip = rr.address.to_s
                    TheLog.debug(";; _dorecursion() Found ns: #{server} IN A #{ip}")
                    addresses = known_authorities[server]
                    unless addresses.is_a?(AddressCache)
                      addresses = known_authorities[server] = AddressCache.new
                    end
                    addresses.push([ip, rr.ttl])
                    Recursor.cache_authority(server, addresses)
                    found_auth+=1
                    next
                  end
                end
              end
              TheLog.debug(";; _dorecursion() Ignoring useless answer: " + rr.inspect + "")
            end
          end
        end
      else
        TheLog.debug(";; _dorecursion() Could not find A records for [#{ns_rec}]")
      end
    end
    if (found_auth > 0)
      TheLog.debug(";; _dorecursion() Found #{found_auth} new NS authorities...")
      return _dorecursion(name, type, klass, known_zone, known_authorities, depth + 1, no_validation)
    end
    TheLog.debug(";; _dorecursion() No authority information could be obtained.")
    return nil
  end

  #  Cut the deck of IPs in a random place.
  TheLog.debug(";; _dorecursion() cutting deck of (" + ns.length.to_s + ") authorities...")
  splitpos = rand(ns.length)
  start = ns[0, splitpos]
  endarr = ns[splitpos, ns.length - splitpos]
  ns = endarr + start

  nameservers = []
  ns.each do |nss|
    nss.each {|n|
      Recursor.send(:current_budget)&.step!
      nameservers.push(n.to_s)
    }
  end
  # TSIG belongs to the configured upstream, not to arbitrary authorities.
  resolver = Resolver.new(hop_settings.merge(nameserver: nameservers))
  # Validation needs signatures even when requesting DNSSEC records was not
  # explicitly enabled. Non-validating lookups retain the caller's setting.
  resolver.dnssec = @dnssec || !no_validation
  resolver.recurse = false
  authority_error = nil
  begin
    #  Should construct packet ourselves and clear RD bit
    query = Message.new(name, type, klass)
    query.header.rd = false
    query.do_validation = true
    query.do_caching = false
    query.do_validation = false if no_validation
    #             print "Sending msg from resolver, dnssec = #{resolver.dnssec}, do_validation = #{query.do_validation}\n"
    packet = resolver.send_message(query)
    #  @TODO@ Now prune unrelated RRSets (RFC 5452 section 6)
    prune_rrsets_to_rfc5452(packet, known_zone)
  rescue ResolvTimeout, IOError
    #             TheLog.debug(";; nameserver #{levelns.to_s} didn't respond")
    #             next
    QueryControl.current&.check!
    TheLog.debug("No response!")
    packet = nil
  rescue ServFail, Refused, NotImp, FormErr, SocketEofResolvError => error
    raise if missing_authorities.empty?
    QueryControl.current&.check!
    authority_error = error
    packet = nil
  ensure
    resolver.close
  end
  if packet.nil? && !missing_authorities.empty?
    # A referral may contain both glue and names that need address
    # discovery. Try the latter if all immediately usable servers fail.
    unresolved = known_authorities.select { |server, _| missing_authorities.include?(server) }
    begin
      alternative = _dorecursion(name, type, klass, known_zone, unresolved, depth + 1, no_validation)
      return alternative if alternative
    rescue ResolvTimeout, IOError, ServFail, Refused, NotImp, FormErr, SocketEofResolvError => error
      QueryControl.current&.check!
      raise(authority_error || error)
    end
    raise authority_error if authority_error
    return nil
  end
  if (packet) # @TODO@ Check that the packet *is* actually authoritative!!
    if (@callback)
      @callback.call(packet)
    end

    of = nil
    TheLog.debug(";; _dorecursion() Response received from [" + @answerfrom.to_s + "]")
    status = packet.rcode
    authority = packet.authority
    if (status)
      if (status == "NXDOMAIN")
        #  I guess NXDOMAIN is the best we'll ever get
        TheLog.debug(";; _dorecursion() returning NXDOMAIN")
        return packet
      elsif (packet.answer.length > 0)
        TheLog.debug(";; _dorecursion() Answers were found.")
        return packet
      elsif (packet.header.aa)
        TheLog.debug(";; _dorecursion() Authoritative answer found")
        return packet
      elsif (authority.length > 0)
        referral = referral_authorities(packet, known_zone, name, klass)
        return nil unless referral
        of, auth, delegation_ttl = referral
        @@mutex.synchronize { Recursor.cache_zone(of, auth.dup, delegation_ttl, parent: known_zone) }
        return _dorecursion(name, type, klass, of, auth, depth + 1, no_validation)
      end
    end
  end

  return nil
end

#get_closest_known_zone_authorities_for(name) ⇒ Object

:nodoc:



852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
# File 'lib/dnsruby/recursor.rb', line 852

def get_closest_known_zone_authorities_for(name) # :nodoc:
  done = false
  known_authorities, known_zone = nil
  while (!done)
    QueryControl.current&.check!
    known_zone = get_closest_known_zone_for(name)
    #         print "GOT KNOWN ZONE : #{known_zone}\n"
    observed_authorities = nil
    @@mutex.synchronize {
      observed_authorities = known_zone == '.' ? Recursor.send(:query_hints) : @@zones_cache[known_zone]
      known_authorities = observed_authorities&.dup # isolate each recursion's working map
      known_authorities&.transform_values! do |addresses|
        addresses.is_a?(AddressCache) ? addresses.snapshot(include_current: known_zone == '.') : addresses.dup
      end
    }
    #         print "Known authorities : #{known_authorities}\n"

    #  Make sure that known_authorities still contains some authorities!
    #  If not, remove the zone from zones_cache, and start again
    if (known_authorities && known_authorities.values.length > 0)
      done = true
    else
      @@mutex.synchronize{
        if @@zones_cache[known_zone].equal?(observed_authorities)
          @@zones_cache.delete(known_zone)
          @@zone_expirations.delete(known_zone)
        end
      }
    end
  end
  return known_zone, known_authorities # @TODO@ Need to synchronize access to these!
end

#get_closest_known_zone_for(n) ⇒ Object

:nodoc:



822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
# File 'lib/dnsruby/recursor.rb', line 822

def get_closest_known_zone_for(n) # :nodoc:
  if (n == nil)
    TheLog.error("Name is nil")
    raise  ResolvError.new("Nameserver invalid!")
  end
  candidate = Name.create(n)
  candidate.absolute = true
  loop do
    QueryControl.current&.check!
    name = candidate.to_s(true).downcase
    @@mutex.synchronize{
      if name == '.' && Recursor.send(:current_budget)&.hints_for(@@hints_generation)
        return name
      end
      zone = @@zones_cache[name]
      lifetime = @@zone_expirations[name]
      if lifetime && lifetime[0].equal?(zone) && lifetime[1] <= Time.now
        @@zones_cache.delete(name)
        @@zone_expirations.delete(name)
        zone = nil
      end
      if (zone != nil)
        return name
      end
    }
    return false if candidate.labels.empty?
    candidate = candidate.strip_label
  end
end

#prune_rrsets_to_rfc5452(packet, zone) ⇒ Object



1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
# File 'lib/dnsruby/recursor.rb', line 1206

def prune_rrsets_to_rfc5452(packet, zone)
  #  Now prune the response of any unrelated rrsets (RFC5452 section6)
  #  "One very simple way to achieve this is to only accept data if it is
  #  part of the domain for which the query was intended."
  # if (!packet.header.aa)
  #   return
  # end
  if (!packet.question()[0])
    return
  end

  section_rrsets = packet.section_rrsets
  section_rrsets.keys.each {|section|
    section_rrsets[section].each {|rrset|
      n = Name.create(rrset.name)
      n.absolute = true
      if ((n.to_s == zone) || (n.to_s == Name.create(zone).to_s) ||
            (n.subdomain_of?(Name.create(zone))) ||
            (rrset.type == Types::OPT))
        #             # @TODO@ Leave in the response if it is an SOA, NSEC or RRSIGfor the parent zone
        # #          elsif ((query_name.subdomain_of?rrset.name) &&
        #           elsif  ((rrset.type == Types.SOA) || (rrset.type == Types.NSEC) || (rrset.type == Types.NSEC3)) #)
      else
        TheLog.debug"Removing #{rrset.name}, #{rrset.type} from response from server for #{zone}"
        packet.send(section).remove_rrset(rrset.name, rrset.type)
      end
    }
  }
end

#query(name, type = Types.A, klass = Classes.IN, no_validation = false) ⇒ Object

This method is much like the normal query() method except it disables the recurse flag in the packet and explicitly performs the recursion.

packet = res.query( "www.netscape.com.", "A")
packet = res.query( "www.netscape.com.", "A", "IN", true) # no validation

The Recursor maintains a cache of known nameservers. DNSSEC validation is performed unless true is passed as the fourth parameter.



623
624
625
626
627
628
629
630
631
632
633
# File 'lib/dnsruby/recursor.rb', line 623

def query(name, type=Types.A, klass=Classes.IN, no_validation = false)
  Recursor.send(:with_limits, @resolver, recursion_limits) do
    if no_validation
      query_internal(name, type, klass, no_validation)
    else
      transmissions = SelectThread::TransmissionBudget.current
      budget = transmissions.context(:validation) { ValidationBudget.current || ValidationBudget.new }
      ValidationBudget.with(budget) { query_internal(name, type, klass, no_validation) }
    end
  end
end

#query_no_validation_or_recursion(name, type = Types.A, klass = Classes.IN) ⇒ Object

:nodoc: all



611
612
613
# File 'lib/dnsruby/recursor.rb', line 611

def query_no_validation_or_recursion(name, type=Types.A, klass=Classes.IN) # :nodoc: all
  return query(name, type, klass, true)
end

#recursion_callback ⇒ Object



547
548
549
# File 'lib/dnsruby/recursor.rb', line 547

def recursion_callback
  return @callback
end

#recursion_callback=(sub) ⇒ Object

This method takes a code reference, which is then invoked each time a packet is received during the recursive lookup. For example to emulate dig's C<+trace> function:

res.recursion_callback(Proc.new { |packet| print packet.additional.inspect

 print";; Received %d bytes from %s\n\n",
     packetanswersize,
     packet.answerfrom);

})



541
542
543
544
545
# File 'lib/dnsruby/recursor.rb', line 541

def recursion_callback=(sub)
  #           if (sub && UNIVERSAL::isa(sub, 'CODE'))
  @callback = sub
  #           end
end

#recursion_limits ⇒ Object



180
181
182
# File 'lib/dnsruby/recursor.rb', line 180

def recursion_limits
  @recursion_limits || DEFAULT_RECURSION_LIMITS
end

#recursion_limits=(settings) ⇒ Object



184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
# File 'lib/dnsruby/recursor.rb', line 184

def recursion_limits=(settings)
  unless settings.is_a?(Hash) && (settings.keys - DEFAULT_RECURSION_LIMITS.keys).empty?
    raise ArgumentError, 'Unknown recursive lookup limit'
  end
  limits = DEFAULT_RECURSION_LIMITS.merge(settings)
  limits.each do |key, value|
    valid = if key == :timeout
      value.is_a?(Numeric) && value.finite? && value > 0
    else
      value.is_a?(Integer) && value > 0
    end
    raise ArgumentError, "Invalid recursive lookup limit #{key}" unless valid
  end
  @recursion_limits = limits.freeze
end

#referral_authorities(packet, known_zone, question_name, question_class) ⇒ Object

A referral advances one enclosing delegation. SOA records describe negative answers; unrelated NS owners must not join this delegation.



1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
# File 'lib/dnsruby/recursor.rb', line 1174

def referral_authorities(packet, known_zone, question_name, question_class) #:nodoc:
  parent = Name.create(known_zone)
  parent.absolute = true
  question = Name.create(question_name)
  question.absolute = true
  klass = Classes.new(question_class)
  candidates = packet.authority.select do |rr|
    rr.type == Types::NS && rr.klass == klass && rr.name.subdomain_of?(parent) &&
      (question == rr.name || question.subdomain_of?(rr.name))
  end
  delegation = candidates.max_by { |rr| rr.name.labels.length }&.name
  return unless delegation
  records = candidates.select { |rr| rr.name == delegation }
  authorities = {}
  records.each do |rr|
    server = rr.nsdname.to_s(true).downcase
    addresses = authorities[server] ||= AddressCache.new
    # RFC 9471 permits sibling glue. Trust addresses within the responding
    # parent's zone, then look up out-of-bailiwick names independently.
    glue = packet.additional.select do |address|
      [Types::A, Types::AAAA].include?(address.type) && address.klass == klass &&
        address.name == rr.nsdname &&
        (address.name == parent || address.name.subdomain_of?(parent))
    end
    # Leave missing addresses empty so _dorecursion resolves them with the
    # same transport settings, deadline and transmission budget. Passing a
    # hostname to Resolver.new would start a separate bootstrap lookup.
    glue.each { |address| addresses.push([address.address.to_s, address.ttl]) }
  end
  [delegation.to_s(true).downcase, authorities, records.map(&:ttl).min]
end