Login
Artifact [09281d3bc1]
Login

Artifact 09281d3bc16453680476579b0dc99c9ccc5bdb8bf8579444f4ccba1adada9cfe:


require "time"

module AsyncDNS
  class Settings
    @local_domain : String?
    @last_reload : Time?

    getter :static_hosts, :name_servers, :local_domain, :search_domains,
      :timeout, :max_attempts, :abs_num_dots, :uses_tcp
    setter :static_hosts, :name_servers, :local_domain, :search_domains,
      :uses_tcp

    def initialize
      @static_hosts = Hash(String, Array(String)).new
      @name_servers = [] of String
      @search_domains = [] of String
      @timeout = Time::Span.new(seconds: 2)
      @max_attempts = 2
      @abs_num_dots = 1
      @uses_tcp = false

      self.reload
    end

    def reload
      {% if flag?(:unix) %}
      self.parse_hosts "/etc/hosts"
      {% else %}
      {% raise "Your OS is not supported by AsyncDNS" %}
      {% end %}
    end

    def parse_hosts(path)
      file = File.open(path, "r")

      @static_hosts.clear
      file.each_line do |line|
        pos = line.index('#')
        line = line[0, pos] if pos

        split = line.split(/[ \t]/, remove_empty: true)
        next unless split.size >= 2

        address = split[0]
        split[1, split.size - 1].each do |host|
          addresses = @static_hosts[host]?
          if addresses.nil?
            addresses = [] of String
            @static_hosts[host] = addresses
          end

          addresses << address
        end
      end
    end
  end
end