lib/httpx/resolver.rb in httpx-0.18.7 vs lib/httpx/resolver.rb in httpx-0.19.0

- old
+ new

@@ -1,58 +1,84 @@ # frozen_string_literal: true require "resolv" +require "ipaddr" module HTTPX module Resolver extend Registry RESOLVE_TIMEOUT = 5 - require "httpx/resolver/resolver_mixin" + require "httpx/resolver/resolver" require "httpx/resolver/system" require "httpx/resolver/native" require "httpx/resolver/https" + require "httpx/resolver/multi" register :system, System register :native, Native register :https, HTTPS @lookup_mutex = Mutex.new @lookups = Hash.new { |h, k| h[k] = [] } @identifier_mutex = Mutex.new @identifier = 1 + @system_resolver = Resolv::Hosts.new module_function + def nolookup_resolve(hostname) + ip_resolve(hostname) || cached_lookup(hostname) || system_resolve(hostname) + end + + def ip_resolve(hostname) + [IPAddr.new(hostname)] + rescue ArgumentError + end + + def system_resolve(hostname) + ips = @system_resolver.getaddresses(hostname) + return if ips.empty? + + ips.map { |ip| IPAddr.new(ip) } + rescue IOError + end + def cached_lookup(hostname) now = Utils.now @lookup_mutex.synchronize do lookup(hostname, now) end end - def cached_lookup_set(hostname, entries) + def cached_lookup_set(hostname, family, entries) now = Utils.now entries.each do |entry| entry["TTL"] += now end @lookup_mutex.synchronize do - @lookups[hostname] += entries + case family + when Socket::AF_INET6 + @lookups[hostname].concat(entries) + when Socket::AF_INET + @lookups[hostname].unshift(*entries) + end entries.each do |entry| - @lookups[entry["name"]] << entry if entry["name"] != hostname + next unless entry["name"] != hostname + + case family + when Socket::AF_INET6 + @lookups[entry["name"]] << entry + when Socket::AF_INET + @lookups[entry["name"]].unshift(entry) + end end end end - def uncache(hostname) - @lookup_mutex.synchronize do - @lookups.delete(hostname) - end - end - # do not use directly! def lookup(hostname, ttl) return unless @lookups.key?(hostname) @lookups[hostname] = @lookups[hostname].select do |address| @@ -60,10 +86,10 @@ end ips = @lookups[hostname].flat_map do |address| if address.key?("alias") lookup(address["alias"], ttl) else - address["data"] + IPAddr.new(address["data"]) end end ips unless ips.empty? end