File: resolver.rb

package info (click to toggle)
ruby-github-pages-health-check 1.16.1-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, sid
  • size: 276 kB
  • sloc: ruby: 998; sh: 46; makefile: 2
file content (70 lines) | stat: -rw-r--r-- 2,096 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# frozen_string_literal: true

module GitHubPages
  module HealthCheck
    class Resolver
      DEFAULT_RESOLVER_OPTIONS = {
        :retry_times => 2,
        :query_timeout => 5,
        :dnssec => false,
        :do_caching => false
      }.freeze
      PUBLIC_NAMESERVERS = %w(
        8.8.8.8
        1.1.1.1
      ).freeze

      class << self
        def default_resolver
          @default_resolver ||= Dnsruby::Resolver.new(DEFAULT_RESOLVER_OPTIONS)
        end
      end

      attr_reader :domain, :nameservers

      # Create a new resolver.
      #
      # domain - the domain we're getting answers for
      # nameserver - (optional) a case
      def initialize(domain, nameservers: :default)
        @domain = domain
        @nameservers = nameservers
      end

      def query(type)
        resolver.query(Addressable::IDNA.to_ascii(domain), type).answer
      end

      private

      def resolver
        @resolver ||= case nameservers
                      when :default
                        self.class.default_resolver
                      when :authoritative
                        Dnsruby::Resolver.new(DEFAULT_RESOLVER_OPTIONS.merge(
                          :nameservers => authoritative_nameservers
                        ))
                      when :public
                        Dnsruby::Resolver.new(DEFAULT_RESOLVER_OPTIONS.merge(
                          :nameservers => PUBLIC_NAMESERVERS
                        ))
                      when Array
                        Dnsruby::Resolver.new(DEFAULT_RESOLVER_OPTIONS.merge(
                          :nameservers => nameservers
                        ))
                      else
                        raise "Invalid nameserver type: #{nameservers.inspect}"
                      end
      end

      def authoritative_nameservers
        @authoritative_nameservers ||= begin
          self.class.default_resolver.query(domain, Dnsruby::Types::NS).answer.map do |rr|
            next rr.nsdname.to_s if rr.type == Dnsruby::Types::NS
          end.compact
        end
      end
    end
  end
end