From 361e7899fdae44678395a5bbcc06ce4e0c24a0ca Mon Sep 17 00:00:00 2001 From: Samuel Williams Date: Sun, 16 Feb 2025 11:34:35 +1300 Subject: [PATCH 1/8] Initial rework. --- .editorconfig | 9 + .github/workflows/documentation-coverage.yaml | 25 +++ .github/workflows/documentation.yaml | 58 ++++++ .github/workflows/rubocop.yaml | 24 +++ .github/workflows/test-coverage.yaml | 59 ++++++ .github/workflows/test-external.yaml | 37 ++++ .github/workflows/test.yaml | 51 +++++ .gitignore | 17 +- .rspec | 4 - .rubocop.yml | 53 ++++++ .simplecov | 15 -- .travis.yml | 21 -- Gemfile | 13 -- Rakefile | 6 - bin/rubydns-check | 127 ++++++------ examples/basic-dns.rb | 9 +- examples/cname.rb | 12 +- examples/flakey-dns.rb | 24 ++- examples/fortune-dns.rb | 56 +++--- examples/gems.locked | 62 ++++++ examples/gems.rb | 16 +- examples/geoip-dns.rb | 37 ++-- examples/simple.rb | 19 +- examples/soa-dns.rb | 36 ++-- examples/test-dns-1.rb | 32 ++-- examples/test-dns-2.rb | 26 +-- examples/wikipedia-dns.rb | 60 +++--- gems.rb | 20 ++ lib/rubydns.rb | 46 ++--- lib/rubydns/rule.rb | 80 ++++++++ lib/rubydns/rule_based_server.rb | 180 ------------------ lib/rubydns/server.rb | 99 ++++++++++ lib/rubydns/version.rb | 25 +-- license.md | 39 ++++ README.md => readme.md | 85 ++++----- release.cert | 28 +++ releases.md | 0 rubydns.gemspec | 49 ++--- spec/rubydns/daemon_spec.rb | 114 ----------- spec/rubydns/hosts.txt | 2 - spec/rubydns/injected_supervisor_spec.rb | 64 ------- spec/rubydns/passthrough_spec.rb | 85 --------- spec/rubydns/rules_spec.rb | 73 ------- spec/spec_helper.rb | 14 -- test/rubydns/injected_supervisor.rb | 47 +++++ test/rubydns/passthrough.rb | 67 +++++++ test/rubydns/rules.rb | 55 ++++++ 47 files changed, 1134 insertions(+), 946 deletions(-) create mode 100644 .editorconfig create mode 100644 .github/workflows/documentation-coverage.yaml create mode 100644 .github/workflows/documentation.yaml create mode 100644 .github/workflows/rubocop.yaml create mode 100644 .github/workflows/test-coverage.yaml create mode 100644 .github/workflows/test-external.yaml create mode 100644 .github/workflows/test.yaml delete mode 100644 .rspec create mode 100644 .rubocop.yml delete mode 100644 .simplecov delete mode 100644 .travis.yml delete mode 100644 Gemfile delete mode 100644 Rakefile create mode 100644 examples/gems.locked create mode 100644 gems.rb create mode 100644 lib/rubydns/rule.rb delete mode 100644 lib/rubydns/rule_based_server.rb create mode 100644 lib/rubydns/server.rb create mode 100644 license.md rename README.md => readme.md (54%) create mode 100644 release.cert create mode 100644 releases.md delete mode 100755 spec/rubydns/daemon_spec.rb delete mode 100644 spec/rubydns/hosts.txt delete mode 100644 spec/rubydns/injected_supervisor_spec.rb delete mode 100755 spec/rubydns/passthrough_spec.rb delete mode 100755 spec/rubydns/rules_spec.rb delete mode 100644 spec/spec_helper.rb create mode 100644 test/rubydns/injected_supervisor.rb create mode 100755 test/rubydns/passthrough.rb create mode 100755 test/rubydns/rules.rb diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..a6e7d26 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,9 @@ +root = true + +[*] +indent_style = tab +indent_size = 2 + +[*.{yml,yaml}] +indent_style = space +indent_size = 2 diff --git a/.github/workflows/documentation-coverage.yaml b/.github/workflows/documentation-coverage.yaml new file mode 100644 index 0000000..8d801c5 --- /dev/null +++ b/.github/workflows/documentation-coverage.yaml @@ -0,0 +1,25 @@ +name: Documentation Coverage + +on: [push, pull_request] + +permissions: + contents: read + +env: + CONSOLE_OUTPUT: XTerm + COVERAGE: PartialSummary + +jobs: + validate: + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v4 + - uses: ruby/setup-ruby@v1 + with: + ruby-version: "3.4" + bundler-cache: true + + - name: Validate coverage + timeout-minutes: 5 + run: bundle exec bake decode:index:coverage lib diff --git a/.github/workflows/documentation.yaml b/.github/workflows/documentation.yaml new file mode 100644 index 0000000..e47c6b3 --- /dev/null +++ b/.github/workflows/documentation.yaml @@ -0,0 +1,58 @@ +name: Documentation + +on: + push: + branches: + - main + +# Sets permissions of the GITHUB_TOKEN to allow deployment to GitHub Pages: +permissions: + contents: read + pages: write + id-token: write + +# Allow one concurrent deployment: +concurrency: + group: "pages" + cancel-in-progress: true + +env: + CONSOLE_OUTPUT: XTerm + BUNDLE_WITH: maintenance + +jobs: + generate: + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v4 + + - uses: ruby/setup-ruby@v1 + with: + ruby-version: "3.4" + bundler-cache: true + + - name: Installing packages + run: sudo apt-get install wget + + - name: Generate documentation + timeout-minutes: 5 + run: bundle exec bake utopia:project:static --force no + + - name: Upload documentation artifact + uses: actions/upload-pages-artifact@v3 + with: + path: docs + + deploy: + runs-on: ubuntu-latest + + environment: + name: github-pages + url: ${{steps.deployment.outputs.page_url}} + + needs: generate + steps: + - name: Deploy to GitHub Pages + id: deployment + uses: actions/deploy-pages@v4 diff --git a/.github/workflows/rubocop.yaml b/.github/workflows/rubocop.yaml new file mode 100644 index 0000000..287c06d --- /dev/null +++ b/.github/workflows/rubocop.yaml @@ -0,0 +1,24 @@ +name: RuboCop + +on: [push, pull_request] + +permissions: + contents: read + +env: + CONSOLE_OUTPUT: XTerm + +jobs: + check: + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v4 + - uses: ruby/setup-ruby@v1 + with: + ruby-version: ruby + bundler-cache: true + + - name: Run RuboCop + timeout-minutes: 10 + run: bundle exec rubocop diff --git a/.github/workflows/test-coverage.yaml b/.github/workflows/test-coverage.yaml new file mode 100644 index 0000000..e6dc5c3 --- /dev/null +++ b/.github/workflows/test-coverage.yaml @@ -0,0 +1,59 @@ +name: Test Coverage + +on: [push, pull_request] + +permissions: + contents: read + +env: + CONSOLE_OUTPUT: XTerm + COVERAGE: PartialSummary + +jobs: + test: + name: ${{matrix.ruby}} on ${{matrix.os}} + runs-on: ${{matrix.os}}-latest + + strategy: + matrix: + os: + - ubuntu + - macos + + ruby: + - "3.4" + + steps: + - uses: actions/checkout@v4 + - uses: ruby/setup-ruby@v1 + with: + ruby-version: ${{matrix.ruby}} + bundler-cache: true + + - name: Run tests + timeout-minutes: 5 + run: bundle exec bake test + + - uses: actions/upload-artifact@v4 + with: + include-hidden-files: true + if-no-files-found: error + name: coverage-${{matrix.os}}-${{matrix.ruby}} + path: .covered.db + + validate: + needs: test + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v4 + - uses: ruby/setup-ruby@v1 + with: + ruby-version: "3.4" + bundler-cache: true + + - uses: actions/download-artifact@v4 + + - name: Validate coverage + timeout-minutes: 5 + run: bundle exec bake covered:validate --paths */.covered.db \; diff --git a/.github/workflows/test-external.yaml b/.github/workflows/test-external.yaml new file mode 100644 index 0000000..c9cc200 --- /dev/null +++ b/.github/workflows/test-external.yaml @@ -0,0 +1,37 @@ +name: Test External + +on: [push, pull_request] + +permissions: + contents: read + +env: + CONSOLE_OUTPUT: XTerm + +jobs: + test: + name: ${{matrix.ruby}} on ${{matrix.os}} + runs-on: ${{matrix.os}}-latest + + strategy: + matrix: + os: + - ubuntu + - macos + + ruby: + - "3.1" + - "3.2" + - "3.3" + - "3.4" + + steps: + - uses: actions/checkout@v4 + - uses: ruby/setup-ruby@v1 + with: + ruby-version: ${{matrix.ruby}} + bundler-cache: true + + - name: Run tests + timeout-minutes: 10 + run: bundle exec bake test:external diff --git a/.github/workflows/test.yaml b/.github/workflows/test.yaml new file mode 100644 index 0000000..5d597fa --- /dev/null +++ b/.github/workflows/test.yaml @@ -0,0 +1,51 @@ +name: Test + +on: [push, pull_request] + +permissions: + contents: read + +env: + CONSOLE_OUTPUT: XTerm + +jobs: + test: + name: ${{matrix.ruby}} on ${{matrix.os}} + runs-on: ${{matrix.os}}-latest + continue-on-error: ${{matrix.experimental}} + + strategy: + matrix: + os: + - ubuntu + - macos + + ruby: + - "3.1" + - "3.2" + - "3.3" + - "3.4" + + experimental: [false] + + include: + - os: ubuntu + ruby: truffleruby + experimental: true + - os: ubuntu + ruby: jruby + experimental: true + - os: ubuntu + ruby: head + experimental: true + + steps: + - uses: actions/checkout@v4 + - uses: ruby/setup-ruby@v1 + with: + ruby-version: ${{matrix.ruby}} + bundler-cache: true + + - name: Run tests + timeout-minutes: 10 + run: bundle exec bake test diff --git a/.gitignore b/.gitignore index 91828d7..533382b 100644 --- a/.gitignore +++ b/.gitignore @@ -1,13 +1,8 @@ -*.gem -*.rbc -/.config -/coverage/ -/InstalledFiles +/.bundle/ /pkg/ -/spec/reports/ -/test/tmp/ -/test/version_tmp/ -tmp +/gems.locked +/.covered.db +/external /.yardoc/ /_yardoc/ @@ -17,10 +12,10 @@ tmp /.bundle/ /lib/bundler/man/ -Gemfile.lock +/gems.locked .ruby-version .ruby-gemset /examples/log /examples/run -/spec/rubydns/server/bind9/log/ \ No newline at end of file +/spec/rubydns/server/bind9/log/ diff --git a/.rspec b/.rspec deleted file mode 100644 index 574cbb8..0000000 --- a/.rspec +++ /dev/null @@ -1,4 +0,0 @@ ---color ---format documentation ---warnings ---require spec_helper \ No newline at end of file diff --git a/.rubocop.yml b/.rubocop.yml new file mode 100644 index 0000000..3b8d476 --- /dev/null +++ b/.rubocop.yml @@ -0,0 +1,53 @@ +AllCops: + DisabledByDefault: true + +Layout/IndentationStyle: + Enabled: true + EnforcedStyle: tabs + +Layout/InitialIndentation: + Enabled: true + +Layout/IndentationWidth: + Enabled: true + Width: 1 + +Layout/IndentationConsistency: + Enabled: true + EnforcedStyle: normal + +Layout/BlockAlignment: + Enabled: true + +Layout/EndAlignment: + Enabled: true + EnforcedStyleAlignWith: start_of_line + +Layout/BeginEndAlignment: + Enabled: true + EnforcedStyleAlignWith: start_of_line + +Layout/ElseAlignment: + Enabled: true + +Layout/DefEndAlignment: + Enabled: true + +Layout/CaseIndentation: + Enabled: true + +Layout/CommentIndentation: + Enabled: true + +Layout/EmptyLinesAroundClassBody: + Enabled: true + +Layout/EmptyLinesAroundModuleBody: + Enabled: true + +Style/FrozenStringLiteralComment: + Enabled: true + +Style/StringLiterals: + Enabled: true + EnforcedStyle: double_quotes diff --git a/.simplecov b/.simplecov deleted file mode 100644 index 9fc93f4..0000000 --- a/.simplecov +++ /dev/null @@ -1,15 +0,0 @@ - -SimpleCov.start do - add_filter "/spec/" -end - -# Work correctly across forks: -pid = Process.pid -SimpleCov.at_exit do - SimpleCov.result.format! if Process.pid == pid -end - -if ENV['TRAVIS'] - require 'coveralls' - Coveralls.wear! -end diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index 0b22840..0000000 --- a/.travis.yml +++ /dev/null @@ -1,21 +0,0 @@ -language: ruby -cache: bundler - -addons: - apt: - packages: - - bind9 - -matrix: - include: - - rvm: 2.3 - - rvm: 2.4 - - rvm: 2.5 - - rvm: 2.6 - - rvm: 2.7 - - rvm: jruby-head - env: JRUBY_OPTS="--debug -X+O" - - rvm: ruby-head - allow_failures: - - rvm: ruby-head - - rvm: jruby-head diff --git a/Gemfile b/Gemfile deleted file mode 100644 index be5a637..0000000 --- a/Gemfile +++ /dev/null @@ -1,13 +0,0 @@ -source 'https://rubygems.org' - -gemspec - -group :development do - gem "process-daemon" - gem "nio4r" -end - -group :test do - gem 'simplecov' - gem 'coveralls', require: false -end diff --git a/Rakefile b/Rakefile deleted file mode 100644 index a1d8b92..0000000 --- a/Rakefile +++ /dev/null @@ -1,6 +0,0 @@ -require "bundler/gem_tasks" -require "rspec/core/rake_task" - -RSpec::Core::RakeTask.new - -task :default => :spec diff --git a/bin/rubydns-check b/bin/rubydns-check index 317129f..09a814b 100755 --- a/bin/rubydns-check +++ b/bin/rubydns-check @@ -1,4 +1,5 @@ #!/usr/bin/env ruby +# frozen_string_literal: true # Copyright, 2009, 2012, by Samuel G. D. Williams. # # Permission is hereby granted, free of charge, to any person obtaining a copy @@ -28,59 +29,59 @@ # Check data against new DNS server # rd-dns-check -s 10.0.0.36 -d mydomain.com. -c old-dns.yml -require 'yaml' -require 'optparse' -require 'set' +require "yaml" +require "optparse" +require "set" class DNSRecord def initialize(arr) @record = arr normalize end - + def normalize @record[0] = @record[0].downcase @record[1] = @record[1].upcase @record[2] = @record[2].upcase @record[3] = @record[3].downcase end - + def hostname @record[0] end - + def klass @record[1] end - + def type @record[2] end - + def value @record[3] end - + def is_address? ["A", "AAAA"].include?(type) end - + def is_cname? return type == "CNAME" end - + def to_s "#{hostname.ljust(50)} #{klass.rjust(4)} #{type.rjust(5)} #{value}" end - + def key "#{hostname}:#{klass}:#{type}".downcase end - + def to_a @record end - + def == other return @record == other.to_a end @@ -94,7 +95,7 @@ def dig(dns_server, cmd, exclude = ["TXT", "HINFO", "SOA", "NS"]) r = line.chomp.split(/\s/, 4) next if exclude.include?(r[2]) - + records << DNSRecord.new(r) end end @@ -137,7 +138,7 @@ end def resolve_addresses(records) addresses = {} cnames = {} - + # Extract all hostname -> ip address mappings records.each do |r| if r.is_address? @@ -146,17 +147,17 @@ def resolve_addresses(records) cnames[r.hostname] = r end end - + cnames.each do |hostname, r| q = r trail = [] failed = false - + # Keep track of CNAME records to avoid loops while q.is_cname? trail << q q = cnames[q.value] || addresses[q.value] - + # Q could be nil at this point, which means there was no address record # Q could be already part of the trail, which means there was a loop if q == nil || trail.include?(q) @@ -164,7 +165,7 @@ def resolve_addresses(records) break end end - + if failed q = trail.last puts "*** Warning: CNAME record #{hostname} does not point to actual address!" @@ -172,24 +173,24 @@ def resolve_addresses(records) puts idx.to_s.rjust(10) + ": " + r.to_s end end - + addresses[r.hostname] = q end - + return addresses, cnames end def check_reverse(records, dns_server) errors = 0 okay = [] - + puts "[ Checking Reverse Lookups ]".center(72, "=") - + records.each do |r| next unless r.is_address? - + sr = resolve_address(dns_server, r.value) - + if sr == nil puts "*** Could not resolve host" puts "".rjust(12) + r.to_s @@ -203,7 +204,7 @@ def check_reverse(records, dns_server) okay << [r, sr] end end - + print_summary(records, errors, okay) do |r| puts "Primary:".rjust(12) + r[0].to_s puts "Secondary:".rjust(12) + r[1].to_s @@ -217,12 +218,12 @@ def ping_records(records) okay = [] puts "[ Pinging Records ]".center(72, "=") - + addresses.each do |hostname, r| ping = "ping -c 5 -t 5 -i 1 -o #{r.value} > /dev/null" - + system(ping) - + if $?.exitstatus == 0 okay << r else @@ -231,31 +232,31 @@ def ping_records(records) errors += 1 end end - + print_summary(records, errors, okay) end def query_records(primary, secondary_server) addresses, cnames = resolve_addresses(primary) - + okay = [] errors = 0 - + primary.each do |r| sr = resolve_hostname(secondary_server, r.hostname) - + if sr == nil puts "*** Could not resolve hostname #{r.hostname.dump}" puts "Primary: ".rjust(12) + r.to_s - + rsr = resolve_address(secondary_server, (addresses[r.value] || r).value) puts "Address: ".rjust(12) + rsr.to_s if rsr - + errors += 1 elsif sr.value != r.value ra = addresses[r.value] if r.is_cname? sra = addresses[sr.value] if sr.is_cname? - + if (sra || sr).value != (ra || r).value puts "*** IP Address does not match" puts "Primary: ".rjust(12) + r.to_s @@ -268,7 +269,7 @@ def query_records(primary, secondary_server) okay << r end end - + print_summary(primary, errors, okay) end @@ -276,7 +277,7 @@ def check_records(primary, secondary) s = {} okay = [] errors = 0 - + secondary.each do |r| s[r.key] = r end @@ -285,7 +286,7 @@ def check_records(primary, secondary) primary.each do |r| sr = s[r.key] - + if sr == nil puts "*** Could not find record" puts "Primary: ".rjust(12) + r.to_s @@ -299,7 +300,7 @@ def check_records(primary, secondary) okay << r end end - + print_summary(primary, errors, okay) end @@ -310,65 +311,65 @@ OPTIONS = { ARGV.options do |o| script_name = File.basename($0) - - o.set_summary_indent(' ') + + o.set_summary_indent(" ") o.banner = "Usage: #{script_name} [options]" o.define_head "This script is designed to test and check DNS servers." - + o.on("-s ns.my.domain.", "--server ns.my.domain.", String, "The DNS server to query.") { |host| OPTIONS[:DNSServer] = host } o.on("-d my.domain.", "--domain my.domain.", String, "The DNS zone to transfer/test.") { |host| OPTIONS[:DNSRoot] = host } - + o.on("-f output.yml", "--fetch output.yml", String, "Pull down a list of hosts. Filters TXT and HINFO records. DNS transfers must be enabled.") { |f| records = retrieve_records(OPTIONS[:DNSServer], OPTIONS[:DNSRoot]) - + output = (f ? File.open(f, "w") : STDOUT) - + output.write(YAML::dump(records)) - + puts "#{records.size} record(s) retrieved." } - + o.on("-c input.yml", "--check input.yml", String, "Check that the DNS server returns results as specified by the file.") { |f| input = (f ? File.open(f) : STDIN) - + master_records = YAML::load(input.read) secondary_records = retrieve_records(OPTIONS[:DNSServer], OPTIONS[:DNSRoot]) - + check_records(master_records, secondary_records) } - + o.on("-q input.yml", "--query input.yml", String, "Query the remote DNS server with all hostnames in the given file, and checks the IP addresses are consistent.") { |f| input = (f ? File.open(f) : STDIN) - + master_records = YAML::load(input.read) - + query_records(master_records, OPTIONS[:DNSServer]) } - + o.on("-p input.yml", "--ping input.yml", String, "Ping all hosts to check if they are available or not.") { |f| input = (f ? File.open(f) : STDIN) - + master_records = YAML::load(input.read) - + ping_records(master_records) } - + o.on("-r input.yml", "--reverse input.yml", String, "Check that all address records have appropriate reverse entries.") { |f| input = (f ? File.open(f) : STDIN) - + master_records = YAML::load(input.read) - + check_reverse(master_records, OPTIONS[:DNSServer]) } - + o.separator "" o.separator "Help and Copyright information" - + o.on_tail("--copy", "Display copyright information") { puts "#{script_name}. Copyright (c) 2009, 2011 Samuel Williams. Released under the MIT license." puts "See http://www.oriontransfer.co.nz/ for more information." exit } - + o.on_tail("-h", "--help", "Show this help message.") { puts o; exit } end.parse! \ No newline at end of file diff --git a/examples/basic-dns.rb b/examples/basic-dns.rb index 645feef..bb6be3e 100755 --- a/examples/basic-dns.rb +++ b/examples/basic-dns.rb @@ -1,5 +1,10 @@ #!/usr/bin/env ruby -require 'rubydns' +# frozen_string_literal: true + +# Released under the MIT License. +# Copyright, 2017-2020, by Samuel Williams. + +require "rubydns" INTERFACES = [ [:udp, "127.0.0.2", 53], @@ -19,4 +24,4 @@ otherwise do |transaction| transaction.passthrough!(UPSTREAM) end -end \ No newline at end of file +end diff --git a/examples/cname.rb b/examples/cname.rb index 8658eeb..f057a45 100644 --- a/examples/cname.rb +++ b/examples/cname.rb @@ -1,8 +1,12 @@ #!/usr/bin/env ruby +# frozen_string_literal: true -require 'rubydns' -require 'rubydns/system' - +# Released under the MIT License. +# Copyright, 2015-2017, by Samuel Williams. + +require "rubydns" +require "rubydns/system" + INTERFACES = [ [:udp, "0.0.0.0", 5300], [:tcp, "0.0.0.0", 5300] @@ -16,7 +20,7 @@ RubyDNS::run_server(INTERFACES) do # How to respond to something other than what was requested. match(//, IN::A) do |transaction| - transaction.respond!(Name.create('foo.bar'), resource_class: IN::CNAME) + transaction.respond!(Name.create("foo.bar"), resource_class: IN::CNAME) end otherwise do |transaction| diff --git a/examples/flakey-dns.rb b/examples/flakey-dns.rb index 8c1ebfe..0d12e46 100755 --- a/examples/flakey-dns.rb +++ b/examples/flakey-dns.rb @@ -1,4 +1,10 @@ #!/usr/bin/env ruby +# frozen_string_literal: true + +# Released under the MIT License. +# Copyright, 2014-2017, by Samuel Williams. +# Copyright, 2014, by Peter M. Goldstein. +# Copyright, 2016, by kaleforsale. # Copyright, 2009, 2012, by Samuel G. D. Williams. # @@ -20,13 +26,13 @@ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. -require 'process/daemon' +require "process/daemon" -require 'rubydns' -require 'rubydns/system' +require "rubydns" +require "rubydns/system" INTERFACES = [ - [:udp, '0.0.0.0', 5300] + [:udp, "0.0.0.0", 5300] ] # A DNS server that selectively drops queries based on the requested domain @@ -41,28 +47,28 @@ def startup RubyDNS.run_server(INTERFACES) do # Use a Celluloid supervisor so the system recovers if the actor dies fallback_resolver_supervisor = - RubyDNS::Resolver.supervise(RubyDNS::System.nameservers) + RubyDNS::Resolver.supervise(RubyDNS::System.nameservers) # Fail the resolution of certain domains ;) match(/(m?i?c?r?o?s?o?f?t)/) do |transaction, match_data| if match_data[1].size > 7 - logger.info 'Dropping domain MICROSOFT...' + logger.info "Dropping domain MICROSOFT..." transaction.fail!(:NXDomain) else - logger.info 'Passing DNS request upstream...' + logger.info "Passing DNS request upstream..." transaction.passthrough!(fallback_resolver_supervisor.actors.first) end end # Hmm.... match(/^(.+\.)?sco\./) do |transaction| - logger.info 'Dropping domain SCO...' + logger.info "Dropping domain SCO..." transaction.fail!(:NXDomain) end # Default DNS handler otherwise do |transaction| - logger.info 'Passing DNS request upstream...' + logger.info "Passing DNS request upstream..." transaction.passthrough!(fallback_resolver_supervisor.actors.first) end end diff --git a/examples/fortune-dns.rb b/examples/fortune-dns.rb index 23075e0..9df3359 100755 --- a/examples/fortune-dns.rb +++ b/examples/fortune-dns.rb @@ -1,40 +1,28 @@ #!/usr/bin/env ruby # encoding: utf-8 -# Copyright, 2009, 2012, by Samuel G. D. Williams. -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. - -require 'process/daemon' -require 'process/daemon/privileges' - -require 'rubydns' -require 'rubydns/extensions/string' - -require 'digest/md5' +# Released under the MIT License. +# Copyright, 2014, by Samuel Williams. +# Copyright, 2014, by Peter M. Goldstein. + +# Released under the MIT License. +# Copyright, 2014, by Samuel Williams. +# Copyright, 2014, by Peter M. Goldstein. + +require "process/daemon" +require "process/daemon/privileges" + +require "rubydns" +require "rubydns/extensions/string" + +require "digest/md5" # You might need to change the user name "daemon". This can be a user name # or a user id. -RUN_AS = 'daemon' +RUN_AS = "daemon" -if Process::Daemon::Privileges.current_user != 'root' - $stderr.puts 'Sorry, this command needs to be run as root!' +if Process::Daemon::Privileges.current_user != "root" + $stderr.puts "Sorry, this command needs to be run as root!" exit 1 end @@ -54,7 +42,7 @@ def startup on(:start) do Process::Daemon::Privileges.change_user(RUN_AS) - if ARGV.include?('--debug') + if ARGV.include?("--debug") @logger.level = Logger::DEBUG $stderr.sync = true else @@ -63,7 +51,7 @@ def startup end match(/short\.fortune/, IN::TXT) do |transaction| - fortune = `fortune -s`.gsub(/\s+/, ' ').strip + fortune = `fortune -s`.gsub(/\s+/, " ").strip transaction.respond!(*fortune.chunked, ttl: 0) end @@ -85,13 +73,13 @@ def startup end match(/fortune/, [IN::CNAME, IN::TXT]) do |transaction| - fortune = `fortune`.gsub(/\s+/, ' ').strip + fortune = `fortune`.gsub(/\s+/, " ").strip checksum = Digest::MD5.hexdigest(fortune) cache[checksum] = fortune answer_txt = "Text Size: #{fortune.size} Byte Size: #{fortune.bytesize}" transaction.respond!(answer_txt, resource_class: IN::TXT, ttl: 0) - answer_cname = Name.create(checksum + '.fortune') + answer_cname = Name.create(checksum + ".fortune") transaction.respond!(answer_cname, resource_class: IN::CNAME, ttl: 0) end diff --git a/examples/gems.locked b/examples/gems.locked new file mode 100644 index 0000000..0e41f6c --- /dev/null +++ b/examples/gems.locked @@ -0,0 +1,62 @@ +PATH + remote: .. + specs: + rubydns (2.0.2) + async-dns (~> 1.0) + +GEM + remote: https://rubygems.org/ + specs: + async (2.1.0) + console (~> 1.10) + io-event (~> 1.0.0) + timers (~> 4.1) + async-dns (1.3.0) + async-io (~> 1.15) + async-http (0.59.2) + async (>= 1.25) + async-io (>= 1.28) + async-pool (>= 0.2) + protocol-http (~> 0.23.1) + protocol-http1 (~> 0.14.0) + protocol-http2 (~> 0.14.0) + traces (>= 0.4.0) + async-io (1.34.0) + async + async-pool (0.3.12) + async (>= 1.25) + console (1.15.3) + fiber-local + fiber-local (1.0.0) + geoip (1.6.4) + io-event (1.0.9) + nokogiri (1.13.8-arm64-darwin) + racc (~> 1.4) + process-daemon (1.0.1) + rainbow (~> 2.0) + protocol-hpack (1.4.2) + protocol-http (0.23.12) + protocol-http1 (0.14.6) + protocol-http (~> 0.22) + protocol-http2 (0.14.2) + protocol-hpack (~> 1.4) + protocol-http (~> 0.18) + racc (1.6.0) + rainbow (2.2.2) + rake + rake (13.0.6) + timers (4.3.4) + traces (0.7.0) + +PLATFORMS + arm64-darwin-21 + +DEPENDENCIES + async-http + geoip + nokogiri + process-daemon + rubydns! + +BUNDLED WITH + 2.3.10 diff --git a/examples/gems.rb b/examples/gems.rb index 5436a7e..6410e5d 100644 --- a/examples/gems.rb +++ b/examples/gems.rb @@ -1,9 +1,15 @@ -source 'https://rubygems.org' +# frozen_string_literal: true -gem 'rubydns', path: '../' +# Released under the MIT License. +# Copyright, 2014-2022, by Samuel Williams. +# Copyright, 2014, by Peter M. Goldstein. + +source "https://rubygems.org" + +gem "rubydns", path: "../" gem "process-daemon" -gem 'nokogiri' +gem "nokogiri" -gem 'async-http' +gem "async-http" -gem 'geoip' +gem "geoip" diff --git a/examples/geoip-dns.rb b/examples/geoip-dns.rb index 9364d39..336c11e 100755 --- a/examples/geoip-dns.rb +++ b/examples/geoip-dns.rb @@ -1,4 +1,9 @@ #!/usr/bin/env ruby +# frozen_string_literal: true + +# Released under the MIT License. +# Copyright, 2014-2017, by Samuel Williams. +# Copyright, 2014, by Peter M. Goldstein. # Copyright, 2009, 2012, by Samuel G. D. Williams. # @@ -20,15 +25,15 @@ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. -require 'geoip' +require "geoip" -require 'process/daemon' +require "process/daemon" -require 'rubydns' -require 'rubydns/system' +require "rubydns" +require "rubydns/system" INTERFACES = [ - [:udp, '0.0.0.0', 5300] + [:udp, "0.0.0.0", 5300] ] # Path to the GeoIP file downloaded from @@ -36,7 +41,7 @@ # If you have renamed the ungzipped file, or have placed it somewhere other than # the repository root directory you will need to update this path. PATH_TO_GEOIP_DAT_FILE = - File.expand_path('../GeoIP.dat', File.dirname(__FILE__)) + File.expand_path("../GeoIP.dat", File.dirname(__FILE__)) # A sample DNS daemon that demonstrates how to use RubyDNS to build responses # that vary based on the geolocation of the requesting peer. Clients of @@ -61,7 +66,7 @@ def startup fallback_resolver_supervisor = RubyDNS::Resolver.supervise(RubyDNS::System.nameservers) match(//, IN::A) do |transaction| - logger.debug 'In block' + logger.debug "In block" # The IP Address of the peer is stored in the transaction options # with the key :remote_address @@ -83,7 +88,7 @@ def startup # Default DNS handler otherwise do |transaction| - logger.debug 'In otherwise' + logger.debug "In otherwise" transaction.passthrough!(fallback_resolver_supervisor.actors.first) end end @@ -93,14 +98,14 @@ def startup # A simple mapper to demonstrate the behavior. def self.answer_for_continent_code(code) case code - when 'AF' then '1.1.1.1' - when 'AN' then '1.1.2.1' - when 'AS' then '1.1.3.1' - when 'EU' then '1.1.4.1' - when 'NA' then '1.1.5.1' - when 'OC' then '1.1.6.1' - when 'SA' then '1.1.7.1' - else '1.1.8.1' + when "AF" then "1.1.1.1" + when "AN" then "1.1.2.1" + when "AS" then "1.1.3.1" + when "EU" then "1.1.4.1" + when "NA" then "1.1.5.1" + when "OC" then "1.1.6.1" + when "SA" then "1.1.7.1" + else "1.1.8.1" end end diff --git a/examples/simple.rb b/examples/simple.rb index 0a79265..8fc58b1 100755 --- a/examples/simple.rb +++ b/examples/simple.rb @@ -1,25 +1,30 @@ #!/usr/bin/env ruby -require 'rubydns' +# frozen_string_literal: true + +# Released under the MIT License. +# Copyright, 2017, by Samuel Williams. + +require "rubydns" INTERFACES = [ - [:udp, '0.0.0.0', 5300], - [:tcp, '0.0.0.0', 5300] + [:udp, "0.0.0.0", 5300], + [:tcp, "0.0.0.0", 5300] ] Name = Resolv::DNS::Name IN = Resolv::DNS::Resource::IN # Use upstream DNS for name resolution. -UPSTREAM = RubyDNS::Resolver.new([[:udp, '8.8.8.8', 53], [:tcp, '8.8.8.8', 53]]) +UPSTREAM = RubyDNS::Resolver.new([[:udp, "8.8.8.8", 53], [:tcp, "8.8.8.8", 53]]) # Start the RubyDNS server RubyDNS.run_server(INTERFACES) do match(/test.mydomain.org/, IN::A) do |transaction| - transaction.respond!('10.0.0.80') + transaction.respond!("10.0.0.80") end # Default DNS handler otherwise do |transaction| - transaction.passthrough!(UPSTREAM) - end + transaction.passthrough!(UPSTREAM) + end end diff --git a/examples/soa-dns.rb b/examples/soa-dns.rb index 9743e93..0ee4e22 100755 --- a/examples/soa-dns.rb +++ b/examples/soa-dns.rb @@ -1,4 +1,8 @@ #!/usr/bin/env ruby +# frozen_string_literal: true + +# Released under the MIT License. +# Copyright, 2017, by Samuel Williams. # Copyright, 2009, 2012, by Samuel G. D. Williams. # @@ -20,25 +24,25 @@ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. -require 'rubygems' -require 'rubydns' +require "rubygems" +require "rubydns" $R = Resolv::DNS.new Name = Resolv::DNS::Name IN = Resolv::DNS::Resource::IN -RubyDNS.run_server([[:udp, '0.0.0.0', 5400]]) do +RubyDNS.run_server([[:udp, "0.0.0.0", 5400]]) do # SOA Record # dig @localhost -p 5400 SOA mydomain.org - match('mydomain.org', IN::SOA) do |transaction| + match("mydomain.org", IN::SOA) do |transaction| # # For more details about these headers please see: # http://www.ripe.net/ripe/docs/ripe-203.html # transaction.respond!( - Name.create('ns.mydomain.org.'), # Master Name - Name.create('admin.mydomain.org.'), # Responsible Name + Name.create("ns.mydomain.org."), # Master Name + Name.create("admin.mydomain.org."), # Responsible Name File.mtime(__FILE__).to_i, # Serial Number 1200, # Refresh Time 900, # Retry Time @@ -51,27 +55,27 @@ # Default NS record # dig @localhost -p 5400 mydomain.org NS - match('mydomain.org', IN::NS) do |transaction| - transaction.respond!(Name.create('ns.mydomain.org.')) + match("mydomain.org", IN::NS) do |transaction| + transaction.respond!(Name.create("ns.mydomain.org.")) end # For this exact address record, return an IP address # dig @localhost -p 5400 CNAME bob.mydomain.org match(/([^.]+).mydomain.org/, IN::CNAME) do |transaction| - transaction.respond!(Name.create('www.mydomain.org')) - transaction.append!('www.mydomain.org', IN::A) + transaction.respond!(Name.create("www.mydomain.org")) + transaction.append!("www.mydomain.org", IN::A) end - match('80.0.0.10.in-addr.arpa', IN::PTR) do |transaction| - transaction.respond!(Name.create('www.mydomain.org.')) + match("80.0.0.10.in-addr.arpa", IN::PTR) do |transaction| + transaction.respond!(Name.create("www.mydomain.org.")) end - match('www.mydomain.org', IN::A) do |transaction| - transaction.respond!('10.0.0.80') + match("www.mydomain.org", IN::A) do |transaction| + transaction.respond!("10.0.0.80") end - match('ns.mydomain.org', IN::A) do |transaction| - transaction.respond!('10.0.0.10') + match("ns.mydomain.org", IN::A) do |transaction| + transaction.respond!("10.0.0.10") end # Default DNS handler diff --git a/examples/test-dns-1.rb b/examples/test-dns-1.rb index 492b30f..6123d8e 100755 --- a/examples/test-dns-1.rb +++ b/examples/test-dns-1.rb @@ -1,4 +1,8 @@ #!/usr/bin/env ruby +# frozen_string_literal: true + +# Released under the MIT License. +# Copyright, 2017, by Samuel Williams. # Copyright, 2009, 2012, by Samuel G. D. Williams. # @@ -20,9 +24,9 @@ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. -require 'rubygems' -require 'rubydns' -require 'rubydns/system' +require "rubygems" +require "rubydns" +require "rubydns/system" # You can specify other DNS servers easily # $R = Resolv::DNS.new(:nameserver => ["xx.xx.1.1", "xx.xx.2.2"]) @@ -31,8 +35,8 @@ Name = Resolv::DNS::Name IN = Resolv::DNS::Resource::IN INTERFACES = [ - [:udp, '0.0.0.0', 5300], - [:tcp, '0.0.0.0', 5300], + [:udp, "0.0.0.0", 5300], + [:tcp, "0.0.0.0", 5300], # [:udp, '::0', 5300], # [:tcp, '::0', 5300], ] @@ -51,16 +55,16 @@ end # For this exact address record, return an IP address - match('dev.mydomain.org', IN::A) do |transaction| - transaction.respond!('10.0.0.80') + match("dev.mydomain.org", IN::A) do |transaction| + transaction.respond!("10.0.0.80") end - match('80.0.0.10.in-addr.arpa', IN::PTR) do |transaction| - transaction.respond!(Name.create('dev.mydomain.org.')) + match("80.0.0.10.in-addr.arpa", IN::PTR) do |transaction| + transaction.respond!(Name.create("dev.mydomain.org.")) end - match('dev.mydomain.org', IN::MX) do |transaction| - transaction.respond!(10, Name.create('mail.mydomain.org.')) + match("dev.mydomain.org", IN::MX) do |transaction| + transaction.respond!(10, Name.create("mail.mydomain.org.")) end match(/^test([0-9]+).mydomain.org$/, IN::A) do |transaction, match_data| @@ -68,7 +72,7 @@ if offset > 0 && offset < 10 logger.info "Responding with address #{'10.0.0.' + (90 + offset).to_s}..." - transaction.respond!('10.0.0.' + (90 + offset).to_s) + transaction.respond!("10.0.0." + (90 + offset).to_s) else logger.info "Address out of range: #{offset}!" false @@ -77,7 +81,7 @@ # Default DNS handler otherwise do |transaction| - logger.info 'Passing DNS request upstream...' + logger.info "Passing DNS request upstream..." transaction.passthrough!(R) - end + end end diff --git a/examples/test-dns-2.rb b/examples/test-dns-2.rb index bdbab2d..e379a15 100755 --- a/examples/test-dns-2.rb +++ b/examples/test-dns-2.rb @@ -1,4 +1,8 @@ #!/usr/bin/env ruby +# frozen_string_literal: true + +# Released under the MIT License. +# Copyright, 2017, by Samuel Williams. # Copyright, 2009, 2012, by Samuel G. D. Williams. # @@ -20,8 +24,8 @@ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. -require 'rubydns' -require 'process-daemon' +require "rubydns" +require "process-daemon" # To run this command, use the standard daemon syntax as root # ./daemon2.rb start @@ -35,17 +39,17 @@ # dig +tcp @localhost test.mydomain.org # You might need to change the user name "daemon". This can be a user name or a user id. -RUN_AS = 'daemon' +RUN_AS = "daemon" INTERFACES = [ - [:udp, '0.0.0.0', 53], - [:tcp, '0.0.0.0', 53] + [:udp, "0.0.0.0", 53], + [:tcp, "0.0.0.0", 53] ] # We need to be root in order to bind to privileged port -if RExec.current_user != 'root' - $stderr.puts 'Sorry, this command needs to be run as root!' - exit 1 +if RExec.current_user != "root" + $stderr.puts "Sorry, this command needs to be run as root!" + exit 1 end # The Daemon itself @@ -54,7 +58,7 @@ class Server < Process::Daemon IN = Resolv::DNS::Resource::IN # Use upstream DNS for name resolution. - UPSTREAM = RubyDNS::Resolver.new([[:udp, '8.8.8.8', 53], [:tcp, '8.8.8.8', 53]]) + UPSTREAM = RubyDNS::Resolver.new([[:udp, "8.8.8.8", 53], [:tcp, "8.8.8.8", 53]]) def startup # Don't buffer output (for debug purposes) @@ -66,8 +70,8 @@ def startup RExec.change_user(RUN_AS) end - match('test.mydomain.org', IN::A) do |transaction| - transaction.respond!('10.0.0.80') + match("test.mydomain.org", IN::A) do |transaction| + transaction.respond!("10.0.0.80") end # Default DNS handler diff --git a/examples/wikipedia-dns.rb b/examples/wikipedia-dns.rb index c3fa842..a57ce7b 100755 --- a/examples/wikipedia-dns.rb +++ b/examples/wikipedia-dns.rb @@ -1,36 +1,24 @@ #!/usr/bin/env ruby # encoding: utf-8 -# Copyright, 2009, 2012, by Samuel G. D. Williams. -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. - -require 'rubydns' - -require 'cgi' -require 'json' - -require 'digest/md5' - -require 'async/http/client' -require 'async/dns/extensions/string' -require 'async/http/endpoint' +# Released under the MIT License. +# Copyright, 2014-2022, by Samuel Williams. +# Copyright, 2014, by Peter M. Goldstein. + +# Released under the MIT License. +# Copyright, 2014-2022, by Samuel Williams. +# Copyright, 2014, by Peter M. Goldstein. + +require "rubydns" + +require "cgi" +require "json" + +require "digest/md5" + +require "async/http/client" +require "async/dns/extensions/string" +require "async/http/endpoint" # Encapsulates the logic for fetching information from Wikipedia. module Wikipedia @@ -45,9 +33,9 @@ def self.lookup(title, logger: nil) logger&.debug "Got response #{response.inspect}." if response.status == 301 - return lookup(response.headers['location'], logger: logger) + return lookup(response.headers["location"], logger: logger) else - return self.extract_summary(response.body.read).force_encoding('ASCII-8BIT') + return self.extract_summary(response.body.read).force_encoding("ASCII-8BIT") end ensure response&.close @@ -61,9 +49,9 @@ def self.summary_url(title) def self.extract_summary(json_text) document = JSON.parse(json_text) - return document['extract'] + return document["extract"] rescue - return 'Invalid Article.' + return "Invalid Article." end end @@ -74,8 +62,8 @@ class WikipediaDNS IN = Resolv::DNS::Resource::IN INTERFACES = [ - [:udp, '::', 5300], - [:tcp, '::', 5300], + [:udp, "::", 5300], + [:tcp, "::", 5300], ] def startup diff --git a/gems.rb b/gems.rb new file mode 100644 index 0000000..66cfcd7 --- /dev/null +++ b/gems.rb @@ -0,0 +1,20 @@ +# frozen_string_literal: true +source "https://rubygems.org" + +gemspec + +group :maintenance, optional: true do + gem "bake-modernize" +end + +group :development do + gem "process-daemon" + gem "nio4r" +end + +group :test do + gem "sus" + gem "covered" + gem "decode" + gem "rubocop" +end diff --git a/lib/rubydns.rb b/lib/rubydns.rb index 1cf7b0a..25a88cf 100644 --- a/lib/rubydns.rb +++ b/lib/rubydns.rb @@ -1,41 +1,25 @@ -# Copyright, 2009, 2012, by Samuel G. D. Williams. -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. +# frozen_string_literal: true -require 'async/dns' +# Released under the MIT License. +# Copyright, 2009-2017, by Samuel Williams. +# Copyright, 2014, by Peter M. Goldstein. -require_relative 'rubydns/version' -require_relative 'rubydns/rule_based_server' +require "async/dns" + +require_relative "rubydns/version" +require_relative "rubydns/server" module RubyDNS # Backwards compatibility: Resolver = Async::DNS::Resolver # Run a server with the given rules. - def self.run_server (*args, server_class: RuleBasedServer, **options, &block) - if listen = options.delete(:listen) - warn "Using `listen:` option is deprecated, please pass as the first argument." - args.unshift(listen) - end - - server = server_class.new(*args, **options, &block) - - server.run + def self.run (*arguments, server_class: Server, **options, &block) + server_class.new(*arguments, **options, &block).run + end + + # @deprecated Use {RubyDNS.run} instead. + def self.run_server(...) + self.run(...) end end diff --git a/lib/rubydns/rule.rb b/lib/rubydns/rule.rb new file mode 100644 index 0000000..85b10c9 --- /dev/null +++ b/lib/rubydns/rule.rb @@ -0,0 +1,80 @@ +# frozen_string_literal: true + +# Released under the MIT License. +# Copyright, 2009-2017, by Samuel Williams. +# Copyright, 2011, by Genki Sugawara. +# Copyright, 2014, by Zac Sprackett. +# Copyright, 2015, by Michal Cichra. + +require "async/dns/server" + +module RubyDNS + # Represents a single rule in the server. + class Rule + def initialize(pattern, callback) + @pattern = pattern + @callback = callback + end + + # Returns true if the name and resource_class are sufficient: + def match(name, resource_class) + # If the pattern doesn't specify any resource classes, we implicitly pass this test: + return true if @pattern.size < 2 + + # Otherwise, we try to match against some specific resource classes: + if Class === @pattern[1] + @pattern[1] == resource_class + else + @pattern[1].include?(resource_class) rescue false + end + end + + # Invoke the rule, if it matches the incoming request, it is evaluated and returns `true`, otherwise returns `false`. + def call(server, name, resource_class, transaction) + unless match(name, resource_class) + server.logger.debug "<#{transaction.query.id}> Resource class #{resource_class} failed to match #{@pattern[1].inspect}!" + + return false + end + + # Does this rule match against the supplied name? + case @pattern[0] + when Regexp + match_data = @pattern[0].match(name) + + if match_data + server.logger.debug "<#{transaction.query.id}> Regexp pattern matched with #{match_data.inspect}." + + @callback[transaction, match_data] + + return true + end + when String + if @pattern[0] == name + server.logger.debug "<#{transaction.query.id}> String pattern matched." + + @callback[transaction] + + return true + end + else + if (@pattern[0].call(name, resource_class) rescue false) + server.logger.debug "<#{transaction.query.id}> Callable pattern matched." + + @callback[transaction] + + return true + end + end + + server.logger.debug "<#{transaction.query.id}> No pattern matched." + + # We failed to match the pattern. + return false + end + + def to_s + @pattern.inspect + end + end +end diff --git a/lib/rubydns/rule_based_server.rb b/lib/rubydns/rule_based_server.rb deleted file mode 100644 index bb335d0..0000000 --- a/lib/rubydns/rule_based_server.rb +++ /dev/null @@ -1,180 +0,0 @@ -# Copyright, 2009, 2012, by Samuel G. D. Williams. -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. - -require 'async/dns/server' - -module RubyDNS - # Provides the core of the RubyDNS domain-specific language (DSL). It contains a list of rules which are used to match against incoming DNS questions. These rules are used to generate responses which are either DNS resource records or failures. - class RuleBasedServer < Async::DNS::Server - # Represents a single rule in the server. - class Rule - def initialize(pattern, callback) - @pattern = pattern - @callback = callback - end - - # Returns true if the name and resource_class are sufficient: - def match(name, resource_class) - # If the pattern doesn't specify any resource classes, we implicitly pass this test: - return true if @pattern.size < 2 - - # Otherwise, we try to match against some specific resource classes: - if Class === @pattern[1] - @pattern[1] == resource_class - else - @pattern[1].include?(resource_class) rescue false - end - end - - # Invoke the rule, if it matches the incoming request, it is evaluated and returns `true`, otherwise returns `false`. - def call(server, name, resource_class, transaction) - unless match(name, resource_class) - server.logger.debug "<#{transaction.query.id}> Resource class #{resource_class} failed to match #{@pattern[1].inspect}!" - - return false - end - - # Does this rule match against the supplied name? - case @pattern[0] - when Regexp - match_data = @pattern[0].match(name) - - if match_data - server.logger.debug "<#{transaction.query.id}> Regexp pattern matched with #{match_data.inspect}." - - @callback[transaction, match_data] - - return true - end - when String - if @pattern[0] == name - server.logger.debug "<#{transaction.query.id}> String pattern matched." - - @callback[transaction] - - return true - end - else - if (@pattern[0].call(name, resource_class) rescue false) - server.logger.debug "<#{transaction.query.id}> Callable pattern matched." - - @callback[transaction] - - return true - end - end - - server.logger.debug "<#{transaction.query.id}> No pattern matched." - - # We failed to match the pattern. - return false - end - - def to_s - @pattern.inspect - end - end - - # Instantiate a server with a block - # - # server = Server.new do - # match(/server.mydomain.com/, IN::A) do |transaction| - # transaction.respond!("1.2.3.4") - # end - # end - # - def initialize(*args, &block) - super(*args) - - @events = {} - @rules = [] - @otherwise = nil - - if block_given? - instance_eval(&block) - end - end - - attr_accessor :logger - - # This function connects a pattern with a block. A pattern is either a String or a Regex instance. Optionally, a second argument can be provided which is either a String, Symbol or Array of resource record types which the rule matches against. - # - # match("www.google.com") - # match("gmail.com", IN::MX) - # match(/g?mail.(com|org|net)/, [IN::MX, IN::A]) - # - def match(*pattern, &block) - @rules << Rule.new(pattern, block) - end - - # Register a named event which may be invoked later using #fire - # - # on(:start) do |server| - # Process::Daemon::Permissions.change_user(RUN_AS) - # end - def on(event_name, &block) - @events[event_name] = block - end - - # Fire the named event, which must have been registered using on. - def fire(event_name) - callback = @events[event_name] - - if callback - callback.call(self) - end - end - - # Specify a default block to execute if all other rules fail to match. This block is typially used to pass the request on to another server (i.e. recursive request). - # - # otherwise do |transaction| - # transaction.passthrough!($R) - # end - # - def otherwise(&block) - @otherwise = block - end - - # If you match a rule, but decide within the rule that it isn't the correct one to use, you can call `next!` to evaluate the next rule - in other words, to continue falling down through the list of rules. - def next! - throw :next - end - - # Give a name and a record type, try to match a rule and use it for processing the given arguments. - def process(name, resource_class, transaction) - @logger.debug {"<#{transaction.query.id}> Searching for #{name} #{resource_class.name}"} - - @rules.each do |rule| - @logger.debug {"<#{transaction.query.id}> Checking rule #{rule}..."} - - catch (:next) do - # If the rule returns true, we assume that it was successful and no further rules need to be evaluated. - return if rule.call(self, name, resource_class, transaction) - end - end - - if @otherwise - @otherwise.call(transaction) - else - @logger.warn "<#{transaction.query.id}> Failed to handle #{name} #{resource_class.name}!" - end - end - end -end diff --git a/lib/rubydns/server.rb b/lib/rubydns/server.rb new file mode 100644 index 0000000..76ddabb --- /dev/null +++ b/lib/rubydns/server.rb @@ -0,0 +1,99 @@ +# frozen_string_literal: true + +# Released under the MIT License. +# Copyright, 2009-2017, by Samuel Williams. +# Copyright, 2011, by Genki Sugawara. +# Copyright, 2014, by Zac Sprackett. +# Copyright, 2015, by Michal Cichra. + +require "async/dns/server" + +module RubyDNS + # Provides the core of the RubyDNS domain-specific language (DSL). It contains a list of rules which are used to match against incoming DNS questions. These rules are used to generate responses which are either DNS resource records or failures. + class Server < Async::DNS::Server + # Instantiate a server with a block + # + # server = Server.new do + # match(/server.mydomain.com/, IN::A) do |transaction| + # transaction.respond!("1.2.3.4") + # end + # end + # + def initialize(*args, &block) + super(*args) + + @events = {} + @rules = [] + @otherwise = nil + + if block_given? + instance_eval(&block) + end + end + + attr_accessor :logger + + # This function connects a pattern with a block. A pattern is either a String or a Regex instance. Optionally, a second argument can be provided which is either a String, Symbol or Array of resource record types which the rule matches against. + # + # match("www.google.com") + # match("gmail.com", IN::MX) + # match(/g?mail.(com|org|net)/, [IN::MX, IN::A]) + # + def match(*pattern, &block) + @rules << Rule.new(pattern, block) + end + + # Register a named event which may be invoked later using #fire + # + # on(:start) do |server| + # Process::Daemon::Permissions.change_user(RUN_AS) + # end + def on(event_name, &block) + @events[event_name] = block + end + + # Fire the named event, which must have been registered using on. + def fire(event_name) + callback = @events[event_name] + + if callback + callback.call(self) + end + end + + # Specify a default block to execute if all other rules fail to match. This block is typially used to pass the request on to another server (i.e. recursive request). + # + # otherwise do |transaction| + # transaction.passthrough!($R) + # end + # + def otherwise(&block) + @otherwise = block + end + + # If you match a rule, but decide within the rule that it isn't the correct one to use, you can call `next!` to evaluate the next rule - in other words, to continue falling down through the list of rules. + def next! + throw :next + end + + # Give a name and a record type, try to match a rule and use it for processing the given arguments. + def process(name, resource_class, transaction) + @logger.debug {"<#{transaction.query.id}> Searching for #{name} #{resource_class.name}"} + + @rules.each do |rule| + @logger.debug {"<#{transaction.query.id}> Checking rule #{rule}..."} + + catch (:next) do + # If the rule returns true, we assume that it was successful and no further rules need to be evaluated. + return if rule.call(self, name, resource_class, transaction) + end + end + + if @otherwise + @otherwise.call(transaction) + else + @logger.warn "<#{transaction.query.id}> Failed to handle #{name} #{resource_class.name}!" + end + end + end +end diff --git a/lib/rubydns/version.rb b/lib/rubydns/version.rb index 6409f4a..b09edb1 100644 --- a/lib/rubydns/version.rb +++ b/lib/rubydns/version.rb @@ -1,23 +1,8 @@ -# Copyright, 2009, 2012, by Samuel G. D. Williams. -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. +# frozen_string_literal: true + +# Released under the MIT License. +# Copyright, 2009-2018, by Samuel Williams. module RubyDNS - VERSION = '2.0.2' + VERSION = "2.0.2" end diff --git a/license.md b/license.md new file mode 100644 index 0000000..59fb4e6 --- /dev/null +++ b/license.md @@ -0,0 +1,39 @@ +# MIT License + +Copyright, 2009-2022, by Samuel Williams. +Copyright, 2011, by Genki Sugawara. +Copyright, 2012, by Satoshi Takada. +Copyright, 2013, by Erran Carey. +Copyright, 2013, by Timothy Redaelli. +Copyright, 2013, by Jean-Christophe Cyr. +Copyright, 2013, by Keith Larrimore. +Copyright, 2014, by justfalter. +Copyright, 2014, by Zac Sprackett. +Copyright, 2014, by Mark Van de Vyver. +Copyright, 2014, by Peter M. Goldstein. +Copyright, 2014, by The Gitter Badger. +Copyright, 2014, by Chris Cunningham. +Copyright, 2015, by Michal Cichra. +Copyright, 2015, by Alexey Pisarenko. +Copyright, 2016, by John Bachir. +Copyright, 2016, by kaleforsale. +Copyright, 2018, by Rob Fors. +Copyright, 2020, by Olle Jonsson. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/readme.md similarity index 54% rename from README.md rename to readme.md index 2bac450..69046fb 100644 --- a/README.md +++ b/readme.md @@ -2,10 +2,7 @@ RubyDNS is a high-performance DNS server which can be easily integrated into other projects or used as a stand-alone daemon. By default it uses rule-based pattern matching. Results can be hard-coded, computed, fetched from a remote DNS server or fetched from a local cache, depending on requirements. -[![Build Status](https://travis-ci.org/socketry/rubydns.svg)](https://travis-ci.org/socketry/rubydns) -[![Code Climate](https://codeclimate.com/github/socketry/rubydns.svg)](https://codeclimate.com/github/socketry/rubydns) -[![Coverage Status](https://coveralls.io/repos/socketry/rubydns/badge.svg)](https://coveralls.io/r/socketry/rubydns) -[![Gitter](https://badges.gitter.im/join.svg)](https://gitter.im/socketry/rubydns) +[![Development Status](https://github.com/socketry/rubydns/workflows/Test/badge.svg)](https://github.com/socketry/rubydns/actions?workflow=Test) [![RubyDNS Introduction](http://img.youtube.com/vi/B9ygq0xh3HQ/maxresdefault.jpg)](https://www.youtube.com/watch?v=B9ygq0xh3HQ&feature=youtu.be&hd=1 "RubyDNS Introduction") @@ -13,15 +10,15 @@ RubyDNS is a high-performance DNS server which can be easily integrated into oth Add this line to your application's Gemfile: - gem 'rubydns' + gem 'rubydns' And then execute: - $ bundle + $ bundle Or install it yourself as: - $ gem install rubydns + $ gem install rubydns ## Usage @@ -31,7 +28,7 @@ There are [lots of examples available](examples/README.md) in the `examples/` di Here is the code from `examples/basic-dns.rb`: -```ruby +``` ruby #!/usr/bin/env ruby require 'rubydns' @@ -60,8 +57,8 @@ end Start the server using `RUBYOPT=-w ./examples/basic-dns.rb`. You can then test it using dig: - $ dig @localhost -p 5300 test.local - $ dig @localhost -p 5300 google.com + $ dig @localhost -p 5300 test.local + $ dig @localhost -p 5300 google.com ### File Handle Limitations @@ -71,7 +68,7 @@ On some platforms (e.g. Mac OS X) the number of file descriptors is relatively l It is possible to create and integrate your own custom servers, however this functionality has now moved to [`Async::DNS::Server`](https://github.com/socketry/async-dns). -```ruby +``` ruby class MyServer < Async::DNS::Server def process(name, resource_class, transaction) transaction.fail!(:NXDomain) @@ -100,9 +97,11 @@ We welcome additional benchmarks and feedback regarding RubyDNS performance. To The performance is on the same magnitude as `bind9`. Some basic benchmarks resolving 1000 names concurrently, repeated 5 times, using `RubyDNS::Resolver` gives the following: - user system total real - RubyDNS::Server 4.280000 0.450000 4.730000 ( 4.854862) - Bind9 4.970000 0.520000 5.490000 ( 5.541213) +``` + user system total real +RubyDNS::Server 4.280000 0.450000 4.730000 ( 4.854862) +Bind9 4.970000 0.520000 5.490000 ( 5.541213) +``` These benchmarks are included in the unit tests. To test bind9 performance, it must be installed and `which named` must return the executable. @@ -110,9 +109,11 @@ These benchmarks are included in the unit tests. To test bind9 performance, it m The `RubyDNS::Resolver` is highly concurrent and can resolve individual names as fast as the built in `Resolv::DNS` resolver. Because the resolver is asynchronous, when dealing with multiple names, it can work more efficiently: - user system total real - RubyDNS::Resolver 0.020000 0.010000 0.030000 ( 0.030507) - Resolv::DNS 0.070000 0.010000 0.080000 ( 1.465975) +``` + user system total real +RubyDNS::Resolver 0.020000 0.010000 0.030000 ( 0.030507) +Resolv::DNS 0.070000 0.010000 0.080000 ( 1.465975) +``` These benchmarks are included in the unit tests. @@ -122,46 +123,26 @@ DNSSEC is currently not supported and is [unlikely to be supported in the future ## Contributing -1. Fork it -2. Create your feature branch (`git checkout -b my-new-feature`) -3. Commit your changes (`git commit -am 'Add some feature'`) -4. Push to the branch (`git push origin my-new-feature`) -5. Create new Pull Request +We welcome contributions to this project. -### Desired Features +1. Fork it. +2. Create your feature branch (`git checkout -b my-new-feature`). +3. Commit your changes (`git commit -am 'Add some feature'`). +4. Push to the branch (`git push origin my-new-feature`). +5. Create new Pull Request. -* Support for more features of DNS such as zone transfer. -* Support reverse records more easily. -* Some kind of system level integration, e.g. registering a DNS server with the currently running system resolver. +### Developer Certificate of Origin -## See Also - -The majority of this gem is now implemented by `async-dns`. +In order to protect users of this project, we require all contributors to comply with the [Developer Certificate of Origin](https://developercertificate.org/). This ensures that all contributions are properly licensed and attributed. -- [async-io](https://github.com/socketry/async-io) — Asynchronous networking and sockets. -- [async-dns](https://github.com/socketry/async-dns) — Asynchronous DNS resolver and server. -- [async-rspec](https://github.com/socketry/async-rspec) — Shared contexts for running async specs. +### Community Guidelines -## License +This project is best served by a collaborative and respectful environment. Treat each other professionally, respect differing viewpoints, and engage constructively. Harassment, discrimination, or harmful behavior is not tolerated. Communicate clearly, listen actively, and support one another. If any issues arise, please inform the project maintainers. -Released under the MIT license. - -Copyright, 2017, by [Samuel G. D. Williams](http://www.codeotaku.com/samuel-williams). - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: +## See Also -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. +The majority of this gem is now implemented by `async-dns`. -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. + - [async-io](https://github.com/socketry/async-io) — Asynchronous networking and sockets. + - [async-dns](https://github.com/socketry/async-dns) — Asynchronous DNS resolver and server. + - [async-rspec](https://github.com/socketry/async-rspec) — Shared contexts for running async specs. diff --git a/release.cert b/release.cert new file mode 100644 index 0000000..d98e595 --- /dev/null +++ b/release.cert @@ -0,0 +1,28 @@ +-----BEGIN CERTIFICATE----- +MIIE2DCCA0CgAwIBAgIBATANBgkqhkiG9w0BAQsFADBhMRgwFgYDVQQDDA9zYW11 +ZWwud2lsbGlhbXMxHTAbBgoJkiaJk/IsZAEZFg1vcmlvbnRyYW5zZmVyMRIwEAYK +CZImiZPyLGQBGRYCY28xEjAQBgoJkiaJk/IsZAEZFgJuejAeFw0yMjA4MDYwNDUz +MjRaFw0zMjA4MDMwNDUzMjRaMGExGDAWBgNVBAMMD3NhbXVlbC53aWxsaWFtczEd +MBsGCgmSJomT8ixkARkWDW9yaW9udHJhbnNmZXIxEjAQBgoJkiaJk/IsZAEZFgJj +bzESMBAGCgmSJomT8ixkARkWAm56MIIBojANBgkqhkiG9w0BAQEFAAOCAY8AMIIB +igKCAYEAomvSopQXQ24+9DBB6I6jxRI2auu3VVb4nOjmmHq7XWM4u3HL+pni63X2 +9qZdoq9xt7H+RPbwL28LDpDNflYQXoOhoVhQ37Pjn9YDjl8/4/9xa9+NUpl9XDIW +sGkaOY0eqsQm1pEWkHJr3zn/fxoKPZPfaJOglovdxf7dgsHz67Xgd/ka+Wo1YqoE +e5AUKRwUuvaUaumAKgPH+4E4oiLXI4T1Ff5Q7xxv6yXvHuYtlMHhYfgNn8iiW8WN +XibYXPNP7NtieSQqwR/xM6IRSoyXKuS+ZNGDPUUGk8RoiV/xvVN4LrVm9upSc0ss +RZ6qwOQmXCo/lLcDUxJAgG95cPw//sI00tZan75VgsGzSWAOdjQpFM0l4dxvKwHn +tUeT3ZsAgt0JnGqNm2Bkz81kG4A2hSyFZTFA8vZGhp+hz+8Q573tAR89y9YJBdYM +zp0FM4zwMNEUwgfRzv1tEVVUEXmoFCyhzonUUw4nE4CFu/sE3ffhjKcXcY//qiSW +xm4erY3XAgMBAAGjgZowgZcwCQYDVR0TBAIwADALBgNVHQ8EBAMCBLAwHQYDVR0O +BBYEFO9t7XWuFf2SKLmuijgqR4sGDlRsMC4GA1UdEQQnMCWBI3NhbXVlbC53aWxs +aWFtc0BvcmlvbnRyYW5zZmVyLmNvLm56MC4GA1UdEgQnMCWBI3NhbXVlbC53aWxs +aWFtc0BvcmlvbnRyYW5zZmVyLmNvLm56MA0GCSqGSIb3DQEBCwUAA4IBgQB5sxkE +cBsSYwK6fYpM+hA5B5yZY2+L0Z+27jF1pWGgbhPH8/FjjBLVn+VFok3CDpRqwXCl +xCO40JEkKdznNy2avOMra6PFiQyOE74kCtv7P+Fdc+FhgqI5lMon6tt9rNeXmnW/ +c1NaMRdxy999hmRGzUSFjozcCwxpy/LwabxtdXwXgSay4mQ32EDjqR1TixS1+smp +8C/NCWgpIfzpHGJsjvmH2wAfKtTTqB9CVKLCWEnCHyCaRVuKkrKjqhYCdmMBqCws +JkxfQWC+jBVeG9ZtPhQgZpfhvh+6hMhraUYRQ6XGyvBqEUe+yo6DKIT3MtGE2+CP +eX9i9ZWBydWb8/rvmwmX2kkcBbX0hZS1rcR593hGc61JR6lvkGYQ2MYskBveyaxt +Q2K9NVun/S785AP05vKkXZEFYxqG6EW012U4oLcFl5MySFajYXRYbuUpH6AY+HP8 +voD0MPg1DssDLKwXyt1eKD/+Fq0bFWhwVM/1XiAXL7lyYUyOq24KHgQ2Csg= +-----END CERTIFICATE----- diff --git a/releases.md b/releases.md new file mode 100644 index 0000000..e69de29 diff --git a/rubydns.gemspec b/rubydns.gemspec index 2253b7a..cdde5a6 100644 --- a/rubydns.gemspec +++ b/rubydns.gemspec @@ -1,28 +1,29 @@ +# frozen_string_literal: true -require_relative 'lib/rubydns/version' +require_relative "lib/rubydns/version" Gem::Specification.new do |spec| - spec.name = "rubydns" - spec.version = RubyDNS::VERSION - spec.authors = ["Samuel Williams"] - spec.email = ["samuel.williams@oriontransfer.co.nz"] - spec.description = <<-EOF - RubyDNS provides a rule-based DSL for implementing DNS servers, built on top of `Async::DNS`. - EOF - spec.summary = "An easy to use DNS server and resolver for Ruby." - spec.homepage = "https://github.com/socketry/rubydns" - spec.license = "MIT" - - spec.files = `git ls-files`.split($/) - spec.executables = spec.files.grep(%r{^bin/}).map{ |f| File.basename(f) } - spec.test_files = spec.files.grep(%r{^(test|spec|features)/}) - spec.require_paths = ["lib"] - - spec.add_dependency("async-dns", "~> 1.0") - spec.add_development_dependency("async-rspec", "~> 1.0") - - spec.add_development_dependency "covered" - spec.add_development_dependency "bundler" - spec.add_development_dependency "rspec", "~> 3.4" - spec.add_development_dependency "rake" + spec.name = "rubydns" + spec.version = RubyDNS::VERSION + + spec.summary = "An easy to use DNS server and resolver for Ruby." + spec.authors = ["Samuel Williams", "Peter M. Goldstein", "Erran Carey", "Keith Larrimore", "Alexey Pisarenko", "Chris Cunningham", "Genki Sugawara", "Jean-Christophe Cyr", "John Bachir", "Mark Van de Vyver", "Michal Cichra", "Olle Jonsson", "Rob Fors", "Satoshi Takada", "The Gitter Badger", "Timothy Redaelli", "Zac Sprackett", "justfalter", "kaleforsale"] + spec.license = "MIT" + + spec.cert_chain = ["release.cert"] + spec.signing_key = File.expand_path("~/.gem/release.pem") + + spec.homepage = "https://github.com/socketry/rubydns" + + spec.metadata = { + "source_code_uri" => "https://github.com/socketry/rubydns.git", + } + + spec.files = Dir.glob(["{bin,examples,lib,spec}/**/*", "*.md"], File::FNM_DOTMATCH, base: __dir__) + + spec.executables = ["rubydns-check"] + + spec.required_ruby_version = ">= 3.1" + + spec.add_dependency "async-dns", "~> 1.0" end diff --git a/spec/rubydns/daemon_spec.rb b/spec/rubydns/daemon_spec.rb deleted file mode 100755 index 1be47cf..0000000 --- a/spec/rubydns/daemon_spec.rb +++ /dev/null @@ -1,114 +0,0 @@ -#!/usr/bin/env ruby - -# Copyright, 2012, by Samuel G. D. Williams. -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. - -require 'rubydns' -require 'process/daemon' - -class BasicTestServer < Process::Daemon - SERVER_PORTS = [[:udp, '127.0.0.1', 5350], [:tcp, '127.0.0.1', 5350]] - - IN = Resolv::DNS::Resource::IN - - def working_directory - File.expand_path("../tmp", __FILE__) - end - - def reactor - Async::Reactor.new - end - - def startup - reactor.run do - RubyDNS::run_server(SERVER_PORTS) do - match("test.local", IN::A) do |transaction| - transaction.respond!("192.168.1.1") - end - - match(/foo.*/, IN::A) do |transaction| - transaction.respond!("192.168.1.2") - end - - match(/peername/, IN::A) do |transaction| - transaction.respond!(transaction[:remote_address].ip_address) - end - - # Default DNS handler - otherwise do |transaction| - transaction.fail!(:NXDomain) - end - end - end - end - - def shutdown - @reactor.stop - end -end - -describe "RubyDNS Daemonized Server" do - include_context Async::RSpec::Reactor - - before(:all) do - # BasicTestServer.controller output: $stderr - BasicTestServer.start - end - - after(:all) do - BasicTestServer.stop - end - - it "should resolve local domain correctly" do - expect(BasicTestServer.status).to be == :running - - resolver = RubyDNS::Resolver.new(BasicTestServer::SERVER_PORTS) - - response = resolver.query("test.local") - - answer = response.answer.first - - expect(answer[0].to_s).to be == "test.local." - expect(answer[2].address.to_s).to be == "192.168.1.1" - end - - it "should pattern match correctly" do - expect(BasicTestServer.status).to be == :running - - resolver = RubyDNS::Resolver.new(BasicTestServer::SERVER_PORTS) - - response = resolver.query("foobar") - answer = response.answer.first - - expect(answer[0]).to be == resolver.fully_qualified_name("foobar") - expect(answer[2].address.to_s).to be == "192.168.1.2" - end - - it "should give peer ip address" do - expect(BasicTestServer.status).to be == :running - - resolver = RubyDNS::Resolver.new(BasicTestServer::SERVER_PORTS) - - response = resolver.query("peername") - answer = response.answer.first - - expect(answer[2].address.to_s).to be == "127.0.0.1" - end -end diff --git a/spec/rubydns/hosts.txt b/spec/rubydns/hosts.txt deleted file mode 100644 index 8ff42e0..0000000 --- a/spec/rubydns/hosts.txt +++ /dev/null @@ -1,2 +0,0 @@ -# A testing host: -1.2.3.4 testing apples \ No newline at end of file diff --git a/spec/rubydns/injected_supervisor_spec.rb b/spec/rubydns/injected_supervisor_spec.rb deleted file mode 100644 index e39e0fe..0000000 --- a/spec/rubydns/injected_supervisor_spec.rb +++ /dev/null @@ -1,64 +0,0 @@ -#!/usr/bin/env ruby - -# Copyright, 2012, by Samuel G. D. Williams. -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. - -require 'rubydns' -require 'async/dns/extensions/string' - -module RubyDNS::InjectedSupervisorSpec - class TestServer < RubyDNS::RuleBasedServer - def test_message - 'Testing...' - end - end - - SERVER_PORTS = [[:udp, '127.0.0.1', 5520]] - IN = Resolv::DNS::Resource::IN - - describe "RubyDNS::run_server(server_class: ...)" do - include_context Async::RSpec::Reactor - - let(:server) do - # Start the RubyDNS server - RubyDNS::run_server(SERVER_PORTS, server_class: TestServer) do - match("test_message", IN::TXT) do |transaction| - transaction.respond!(*test_message.chunked) - end - - # Default DNS handler - otherwise do |transaction| - transaction.fail!(:NXDomain) - end - end - end - - it "should use the injected class" do - task = server - - resolver = RubyDNS::Resolver.new(SERVER_PORTS) - response = resolver.query("test_message", IN::TXT) - text = response.answer.first - expect(text[2].strings.join).to be == 'Testing...' - - task.stop - end - end -end diff --git a/spec/rubydns/passthrough_spec.rb b/spec/rubydns/passthrough_spec.rb deleted file mode 100755 index 74f6897..0000000 --- a/spec/rubydns/passthrough_spec.rb +++ /dev/null @@ -1,85 +0,0 @@ -#!/usr/bin/env ruby - -# Copyright, 2012, by Samuel G. D. Williams. -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. - -require 'rubydns' - -module RubyDNS::PassthroughSpec - SERVER_PORTS = [[:udp, '127.0.0.1', 5340], [:tcp, '127.0.0.1', 5340]] - Name = Resolv::DNS::Name - IN = Resolv::DNS::Resource::IN - - describe "RubyDNS Passthrough Server" do - include_context Async::RSpec::Reactor - - def run_server - task = RubyDNS::run_server(listen: SERVER_PORTS) do - resolver = RubyDNS::Resolver.new([[:udp, "8.8.8.8", 53], [:tcp, "8.8.8.8", 53]]) - - match(/.*\.com/, IN::A) do |transaction| - transaction.passthrough!(resolver) - end - - match(/a-(.*\.org)/) do |transaction, match_data| - transaction.passthrough!(resolver, :name => match_data[1]) - end - - # Default DNS handler - otherwise do |transaction| - transaction.fail!(:NXDomain) - end - end - - yield - - ensure - task.stop - end - - it "should resolve domain correctly" do - run_server do - resolver = RubyDNS::Resolver.new(SERVER_PORTS, timeout: 1) - - response = resolver.query("google.com") - expect(response.ra).to be == 1 - - answer = response.answer.first - expect(answer).not_to be == nil - expect(answer.count).to be > 0 - - addresses = answer.select {|record| record.kind_of? Resolv::DNS::Resource::IN::A} - expect(addresses.size).to be > 0 - end - end - - it "should resolve prefixed domain correctly" do - run_server do - resolver = RubyDNS::Resolver.new(SERVER_PORTS) - - response = resolver.query("a-slashdot.org") - answer = response.answer.first - - expect(answer).not_to be == nil - expect(answer.count).to be > 0 - end - end - end -end diff --git a/spec/rubydns/rules_spec.rb b/spec/rubydns/rules_spec.rb deleted file mode 100755 index 5133179..0000000 --- a/spec/rubydns/rules_spec.rb +++ /dev/null @@ -1,73 +0,0 @@ -#!/usr/bin/env ruby - -# Copyright, 2012, by Samuel G. D. Williams. -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. - -require 'rubydns' - -module RubyDNS::RulesSpec - describe RubyDNS::RuleBasedServer do - IN = Resolv::DNS::Resource::IN - - true_callback = Proc.new { true } - - let(:server) {double(:logger => Console.logger)} - - it "should match string patterns correctly" do - transaction = double(:query => Resolv::DNS::Message.new(0)) - - rule = RubyDNS::RuleBasedServer::Rule.new(["foobar", IN::A], true_callback) - - expect(rule.call(server, "foobar", IN::A, transaction)).to be == true - expect(rule.call(server, "barfoo", IN::A, transaction)).to be == false - expect(rule.call(server, "foobar", IN::TXT, transaction)).to be == false - end - - it "should match regular expression patterns correctly" do - transaction = double(:query => Resolv::DNS::Message.new(0)) - - rule = RubyDNS::RuleBasedServer::Rule.new([/foo/, IN::A], true_callback) - - expect(rule.call(server, "foobar", IN::A, transaction)).to be == true - expect(rule.call(server, "barbaz", IN::A, transaction)).to be == false - expect(rule.call(server, "foobar", IN::TXT, transaction)).to be == false - end - - it "should match callback patterns correctly" do - transaction = double(:query => Resolv::DNS::Message.new(0)) - - calls = 0 - - callback = Proc.new do |name, resource_class| - # A counter used to check the number of times this block was invoked. - calls += 1 - - name.size == 6 - end - - rule = RubyDNS::RuleBasedServer::Rule.new([callback], true_callback) - - expect(rule.call(server, "foobar", IN::A, transaction)).to be == true - expect(rule.call(server, "foobarbaz", IN::A, transaction)).to be == false - - expect(calls).to be == 2 - end - end -end diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb deleted file mode 100644 index ac6a2dd..0000000 --- a/spec/spec_helper.rb +++ /dev/null @@ -1,14 +0,0 @@ - -require 'covered/rspec' -require "bundler/setup" -require "async" -require "async/rspec" - -RSpec.configure do |config| - # Enable flags like --only-failures and --next-failure - config.example_status_persistence_file_path = ".rspec_status" - - config.expect_with :rspec do |c| - c.syntax = :expect - end -end diff --git a/test/rubydns/injected_supervisor.rb b/test/rubydns/injected_supervisor.rb new file mode 100644 index 0000000..5008e2c --- /dev/null +++ b/test/rubydns/injected_supervisor.rb @@ -0,0 +1,47 @@ +#!/usr/bin/env ruby +# frozen_string_literal: true + +# Released under the MIT License. +# Copyright, 2014, by Peter M. Goldstein. +# Copyright, 2014-2017, by Samuel Williams. + +require "rubydns" +require "async/dns/extensions/string" + +class TestServer < RubyDNS::RuleBasedServer + def test_message + "Testing..." + end +end + +SERVER_PORTS = [[:udp, "127.0.0.1", 5520]] +IN = Resolv::DNS::Resource::IN + +describe "RubyDNS::run_server(server_class: ...)" do + include_context Async::RSpec::Reactor + + let(:server) do + # Start the RubyDNS server + RubyDNS::run_server(SERVER_PORTS, server_class: TestServer) do + match("test_message", IN::TXT) do |transaction| + transaction.respond!(*test_message.chunked) + end + + # Default DNS handler + otherwise do |transaction| + transaction.fail!(:NXDomain) + end + end + end + + it "should use the injected class" do + task = server + + resolver = RubyDNS::Resolver.new(SERVER_PORTS) + response = resolver.query("test_message", IN::TXT) + text = response.answer.first + expect(text[2].strings.join).to be == "Testing..." + + task.stop + end +end diff --git a/test/rubydns/passthrough.rb b/test/rubydns/passthrough.rb new file mode 100755 index 0000000..2c37828 --- /dev/null +++ b/test/rubydns/passthrough.rb @@ -0,0 +1,67 @@ +#!/usr/bin/env ruby +# frozen_string_literal: true + +# Released under the MIT License. +# Copyright, 2012-2017, by Samuel Williams. + +require "rubydns" + +SERVER_PORTS = [[:udp, "127.0.0.1", 5340], [:tcp, "127.0.0.1", 5340]] +Name = Resolv::DNS::Name +IN = Resolv::DNS::Resource::IN + +describe "RubyDNS Passthrough Server" do + include_context Async::RSpec::Reactor + + def run_server + task = RubyDNS::run_server(listen: SERVER_PORTS) do + resolver = RubyDNS::Resolver.new([[:udp, "8.8.8.8", 53], [:tcp, "8.8.8.8", 53]]) + + match(/.*\.com/, IN::A) do |transaction| + transaction.passthrough!(resolver) + end + + match(/a-(.*\.org)/) do |transaction, match_data| + transaction.passthrough!(resolver, :name => match_data[1]) + end + + # Default DNS handler + otherwise do |transaction| + transaction.fail!(:NXDomain) + end + end + + yield + + ensure + task.stop + end + + it "should resolve domain correctly" do + run_server do + resolver = RubyDNS::Resolver.new(SERVER_PORTS, timeout: 1) + + response = resolver.query("google.com") + expect(response.ra).to be == 1 + + answer = response.answer.first + expect(answer).not_to be == nil + expect(answer.count).to be > 0 + + addresses = answer.select {|record| record.kind_of? Resolv::DNS::Resource::IN::A} + expect(addresses.size).to be > 0 + end + end + + it "should resolve prefixed domain correctly" do + run_server do + resolver = RubyDNS::Resolver.new(SERVER_PORTS) + + response = resolver.query("a-slashdot.org") + answer = response.answer.first + + expect(answer).not_to be == nil + expect(answer.count).to be > 0 + end + end +end diff --git a/test/rubydns/rules.rb b/test/rubydns/rules.rb new file mode 100755 index 0000000..283b3aa --- /dev/null +++ b/test/rubydns/rules.rb @@ -0,0 +1,55 @@ +#!/usr/bin/env ruby +# frozen_string_literal: true + +# Released under the MIT License. +# Copyright, 2012-2020, by Samuel Williams. + +require "rubydns" + +describe RubyDNS::RuleBasedServer do + IN = Resolv::DNS::Resource::IN + + true_callback = Proc.new { true } + + let(:server) {double(:logger => Console.logger)} + + it "should match string patterns correctly" do + transaction = double(:query => Resolv::DNS::Message.new(0)) + + rule = RubyDNS::RuleBasedServer::Rule.new(["foobar", IN::A], true_callback) + + expect(rule.call(server, "foobar", IN::A, transaction)).to be == true + expect(rule.call(server, "barfoo", IN::A, transaction)).to be == false + expect(rule.call(server, "foobar", IN::TXT, transaction)).to be == false + end + + it "should match regular expression patterns correctly" do + transaction = double(:query => Resolv::DNS::Message.new(0)) + + rule = RubyDNS::RuleBasedServer::Rule.new([/foo/, IN::A], true_callback) + + expect(rule.call(server, "foobar", IN::A, transaction)).to be == true + expect(rule.call(server, "barbaz", IN::A, transaction)).to be == false + expect(rule.call(server, "foobar", IN::TXT, transaction)).to be == false + end + + it "should match callback patterns correctly" do + transaction = double(:query => Resolv::DNS::Message.new(0)) + + calls = 0 + + callback = Proc.new do |name, resource_class| + # A counter used to check the number of times this block was invoked. + calls += 1 + + name.size == 6 + end + + rule = RubyDNS::RuleBasedServer::Rule.new([callback], true_callback) + + expect(rule.call(server, "foobar", IN::A, transaction)).to be == true + expect(rule.call(server, "foobarbaz", IN::A, transaction)).to be == false + + expect(calls).to be == 2 + end +end From 8aaeab0962dc92613d3a62c0d4f4a43c4047eba9 Mon Sep 17 00:00:00 2001 From: Samuel Williams Date: Sun, 16 Feb 2025 12:42:49 +1300 Subject: [PATCH 2/8] Update code, tests and examples. Deleted a lot of old stuff. --- examples/README.md | 137 ------------------ examples/basic-dns.rb | 27 ---- examples/cname.rb | 29 ---- examples/flakey-dns.rb | 78 ---------- examples/fortune-dns.rb | 94 ------------ examples/fortune/readme.md | 47 ++++++ examples/fortune/server.rb | 58 ++++++++ examples/gems.locked | 76 ++++++---- examples/gems.rb | 15 -- examples/geoip-dns.rb | 120 --------------- examples/simple.rb | 30 ---- examples/soa-dns.rb | 86 ----------- examples/test-dns-1.rb | 87 ----------- examples/test-dns-2.rb | 87 ----------- examples/wikipedia/readme.md | 23 +++ .../{wikipedia-dns.rb => wikipedia/server.rb} | 69 +++------ lib/rubydns.rb | 10 +- lib/rubydns/rule.rb | 24 ++- lib/rubydns/server.rb | 37 +---- readme.md | 20 +-- test/rubydns/injected_supervisor.rb | 47 ------ test/rubydns/passthrough.rb | 67 --------- test/rubydns/rules.rb | 42 +++--- 23 files changed, 254 insertions(+), 1056 deletions(-) delete mode 100644 examples/README.md delete mode 100755 examples/basic-dns.rb delete mode 100644 examples/cname.rb delete mode 100755 examples/flakey-dns.rb delete mode 100755 examples/fortune-dns.rb create mode 100644 examples/fortune/readme.md create mode 100755 examples/fortune/server.rb delete mode 100644 examples/gems.rb delete mode 100755 examples/geoip-dns.rb delete mode 100755 examples/simple.rb delete mode 100755 examples/soa-dns.rb delete mode 100755 examples/test-dns-1.rb delete mode 100755 examples/test-dns-2.rb create mode 100644 examples/wikipedia/readme.md rename examples/{wikipedia-dns.rb => wikipedia/server.rb} (52%) delete mode 100644 test/rubydns/injected_supervisor.rb delete mode 100755 test/rubydns/passthrough.rb diff --git a/examples/README.md b/examples/README.md deleted file mode 100644 index f7a9d49..0000000 --- a/examples/README.md +++ /dev/null @@ -1,137 +0,0 @@ -# RubyDNS Examples - -This directory contains several examples of customized RubyDNS servers, -intended to demonstrate how RubyDNS can be easily customized to specific -needs. - -## FlakeyDNS (flakey-dns.rb) - -A DNS server that selectively drops queries based on the requested domain name. Queries for domains that match specified regular expressions (like 'microsoft.com' or 'sco.com') return NXDomain, while all other queries are passed to upstream resolvers. - -By default this server will listen for UDP requests on port 5300 and does not need to be started as root. - -To start the server, ensure that you're in the examples subdirectory and type - - bundle - bundle exec ./flakey-dns.rb start - -To see it in action you can then query some domains. For example, - - dig @localhost -p 5300 slashdot.org -t A - dig @localhost -p 5300 www.hackernews.com -t A - -give the correct results. But - - dig @localhost -p 5300 microsoft.com -t A - dig @localhost -p 5300 www.microsoft.com -t A - dig @localhost -p 5300 www.microsoft.com - -all give an NXDomain result. - -## FortuneDNS (fortune-dns.rb) - -A DNS server that allows a client to generate fortunes and fetch them with subsequent requests. The server -'remembers' the fortunes it generates, and can serve them to future requests. The reason for this is because most fortunes won't fit over UDP (maximum size 512 bytes) and the client will request the same fortune via TCP. - -You will need to have the `fortune` app installed on your system. It comes installed by default on -most Linux distributions, and can be installed on a Mac with Homebrew by typing: - - # Homebrew - brew install fortune - # MacPorts - sudo port install fortune - # Arch Linux - sudo pacman -S fortune-mod - -By default this server will listen for UDP and TCP requests on port 53, and needs to be started as root. It -assumes the existence of a user 'daemon', as whom the process will run. If such a user doesn't exist on your -system, you will need to either create such a user or update the script to use a user that exists on your -system. - -To start the server, ensure that you're in the examples subdirectory and type - - bundle - sudo bundle exec ./fortune-dns.rb start - -To create a new fortune type - - dig @localhost fortune -t TXT - -This will result in an DNS answer that looks something like this: - - fortune. 0 IN TXT "Text Size: 714 Byte Size: 714" - fortune. 0 IN CNAME 32bf3bf2b0a2255f2df00ed9e95c8185.fortune. - -Take the CNAME from this result and query it. For our example this would be: - - dig @localhost 32bf3bf2b0a2255f2df00ed9e95c8185.fortune -t TXT - -And your answer will be a fortune. - -You can also generate a 'short' fortune by typing the following: - - dig @localhost short.fortune -t TXT - -or view the fortune stats with: - - dig @localhost stats.fortune -t TXT - -## GeoIPDNS (geoip-dns.rb) - -A sample DNS daemon that demonstrates how to use RubyDNS to build responses -that vary based on the geolocation of the requesting peer. Clients of this -server who request A records will get an answer IP address based on the -continent of the client IP address. - -Please note that use of this example requires that the peer have a public -IP address. IP addresses on private networks or the localhost IP (127.0.0.1) -cannot be resolved to a location, and so will always yield the unknown result. - -This daemon requires the file downloaded from -[MaxMind](http://geolite.maxmind.com/download/geoip/database/GeoLiteCountry/GeoIP.dat.gz) -For more information on the GeoIP library, please click [here](http://www.maxmind.com/en/geolite) -or [here](https://github.com/cjheath/geoip). This file should be unzipped and placed in the -examples root directory, i.e. `examples/GeoLiteCountry.dat`. - -By default this server will listen for UDP requests on port 5300 and does not need to be started as root. - -To start the server, ensure that you're in the examples subdirectory and type - - bundle - sudo bundle exec ./geoip-dns.rb start - -To see the behavior, run a DNS query against the server where you are running the GeoIPDNS -daemon. Depending on the continent to which the client machine's IP address is mapped, -you will receive a different IP address in the answer section: - - Africa - 1.1.1.1 - Antarctica - 1.1.2.1 - Asia - 1.1.3.1 - Europe - 1.1.4.1 - North America - 1.1.5.1 - Oceania - 1.1.6.1 - South America - 1.1.7.1 - -## WikipediaDNS (wikipedia-dns.rb) - -A DNS server that queries Wikipedia and returns summaries for specifically crafted queries. - -By default this server will listen for UDP and TCP requests on port 53, and needs to be started as root. It -assumes the existence of a user 'daemon', as whom the process will run. If such a user doesn't exist on your -system, you will need to either create such a user or update the script to use a user that exists on your -system. - -To start the server, ensure that you're in the examples subdirectory and type - - bundle - sudo bundle exec ./wikipedia-dns.rb start - -To query Wikipedia, pick a term - say, 'helium' - and make a DNS query like - - dig @localhost helium.wikipedia -t TXT - -The answer section should contain the summary for this topic from Wikipedia - - helium.wikipedia. 86400 IN TXT "Helium is a chemical element with symbol He and atomic number 2. It is a colorless, odorless, tasteless, non-toxic, inert, monatomic gas that heads the noble gas group in the periodic table. Its boiling and melting points are the lowest among the elements" " and it exists only as a gas except in extreme conditions." - -Long blocks of text cannot be easily replied in DNS as they must be chunked into segments at most 255 bytes. Long replies must be sent back using TCP. diff --git a/examples/basic-dns.rb b/examples/basic-dns.rb deleted file mode 100755 index bb6be3e..0000000 --- a/examples/basic-dns.rb +++ /dev/null @@ -1,27 +0,0 @@ -#!/usr/bin/env ruby -# frozen_string_literal: true - -# Released under the MIT License. -# Copyright, 2017-2020, by Samuel Williams. - -require "rubydns" - -INTERFACES = [ - [:udp, "127.0.0.2", 53], - [:tcp, "127.0.0.2", 53], -] - -# Use upstream DNS for name resolution. -UPSTREAM = RubyDNS::Resolver.new([ - [:udp, "8.8.8.8", 53], - [:tcp, "8.8.8.8", 53] -]) - -# Start the RubyDNS server -RubyDNS::run_server(INTERFACES) do - @logger.debug! - - otherwise do |transaction| - transaction.passthrough!(UPSTREAM) - end -end diff --git a/examples/cname.rb b/examples/cname.rb deleted file mode 100644 index f057a45..0000000 --- a/examples/cname.rb +++ /dev/null @@ -1,29 +0,0 @@ -#!/usr/bin/env ruby -# frozen_string_literal: true - -# Released under the MIT License. -# Copyright, 2015-2017, by Samuel Williams. - -require "rubydns" -require "rubydns/system" - -INTERFACES = [ - [:udp, "0.0.0.0", 5300], - [:tcp, "0.0.0.0", 5300] -] - -Name = Resolv::DNS::Name -IN = Resolv::DNS::Resource::IN - -UPSTREAM = RubyDNS::Resolver.new([[:udp, "8.8.8.8", 53], [:tcp, "8.8.8.8", 53]]) - -RubyDNS::run_server(INTERFACES) do - # How to respond to something other than what was requested. - match(//, IN::A) do |transaction| - transaction.respond!(Name.create("foo.bar"), resource_class: IN::CNAME) - end - - otherwise do |transaction| - transaction.passthrough!(UPSTREAM) - end -end diff --git a/examples/flakey-dns.rb b/examples/flakey-dns.rb deleted file mode 100755 index 0d12e46..0000000 --- a/examples/flakey-dns.rb +++ /dev/null @@ -1,78 +0,0 @@ -#!/usr/bin/env ruby -# frozen_string_literal: true - -# Released under the MIT License. -# Copyright, 2014-2017, by Samuel Williams. -# Copyright, 2014, by Peter M. Goldstein. -# Copyright, 2016, by kaleforsale. - -# Copyright, 2009, 2012, by Samuel G. D. Williams. -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. - -require "process/daemon" - -require "rubydns" -require "rubydns/system" - -INTERFACES = [ - [:udp, "0.0.0.0", 5300] -] - -# A DNS server that selectively drops queries based on the requested domain -# name. Queries for domains that match specified regular expresssions -# (like 'microsoft.com' or 'sco.com') return NXDomain, while all other -# queries are passed to upstream resolvers. -class FlakeyDNS < Process::Daemon - Name = Resolv::DNS::Name - IN = Resolv::DNS::Resource::IN - - def startup - RubyDNS.run_server(INTERFACES) do - # Use a Celluloid supervisor so the system recovers if the actor dies - fallback_resolver_supervisor = - RubyDNS::Resolver.supervise(RubyDNS::System.nameservers) - - # Fail the resolution of certain domains ;) - match(/(m?i?c?r?o?s?o?f?t)/) do |transaction, match_data| - if match_data[1].size > 7 - logger.info "Dropping domain MICROSOFT..." - transaction.fail!(:NXDomain) - else - logger.info "Passing DNS request upstream..." - transaction.passthrough!(fallback_resolver_supervisor.actors.first) - end - end - - # Hmm.... - match(/^(.+\.)?sco\./) do |transaction| - logger.info "Dropping domain SCO..." - transaction.fail!(:NXDomain) - end - - # Default DNS handler - otherwise do |transaction| - logger.info "Passing DNS request upstream..." - transaction.passthrough!(fallback_resolver_supervisor.actors.first) - end - end - end -end - -FlakeyDNS.daemonize diff --git a/examples/fortune-dns.rb b/examples/fortune-dns.rb deleted file mode 100755 index 9df3359..0000000 --- a/examples/fortune-dns.rb +++ /dev/null @@ -1,94 +0,0 @@ -#!/usr/bin/env ruby -# encoding: utf-8 - -# Released under the MIT License. -# Copyright, 2014, by Samuel Williams. -# Copyright, 2014, by Peter M. Goldstein. - -# Released under the MIT License. -# Copyright, 2014, by Samuel Williams. -# Copyright, 2014, by Peter M. Goldstein. - -require "process/daemon" -require "process/daemon/privileges" - -require "rubydns" -require "rubydns/extensions/string" - -require "digest/md5" - -# You might need to change the user name "daemon". This can be a user name -# or a user id. -RUN_AS = "daemon" - -if Process::Daemon::Privileges.current_user != "root" - $stderr.puts "Sorry, this command needs to be run as root!" - exit 1 -end - -# A DNS server that allows a client to generate fortunes and fetch them with -# subsequent requests. The server 'remembers' the fortunes it generates, -# and can serve them to future requests. -class FortuneDNS < Process::Daemon - Name = Resolv::DNS::Name - IN = Resolv::DNS::Resource::IN - - def startup - cache = {} - stats = { requested: 0 } - - # Start the RubyDNS server - RubyDNS.run_server do - on(:start) do - Process::Daemon::Privileges.change_user(RUN_AS) - - if ARGV.include?("--debug") - @logger.level = Logger::DEBUG - $stderr.sync = true - else - @logger.level = Logger::WARN - end - end - - match(/short\.fortune/, IN::TXT) do |transaction| - fortune = `fortune -s`.gsub(/\s+/, " ").strip - - transaction.respond!(*fortune.chunked, ttl: 0) - end - - match(/stats\.fortune/, IN::TXT) do |transaction| - $stderr.puts "Sending stats: #{stats.inspect}" - transaction.respond!(stats.inspect) - end - - match(/([a-f0-9]*)\.fortune/, IN::TXT) do |transaction, match| - fortune = cache[match[1]] - stats[:requested] += 1 - - if fortune - transaction.respond!(*fortune.chunked) - else - transaction.fail!(:NXDomain) - end - end - - match(/fortune/, [IN::CNAME, IN::TXT]) do |transaction| - fortune = `fortune`.gsub(/\s+/, " ").strip - checksum = Digest::MD5.hexdigest(fortune) - cache[checksum] = fortune - - answer_txt = "Text Size: #{fortune.size} Byte Size: #{fortune.bytesize}" - transaction.respond!(answer_txt, resource_class: IN::TXT, ttl: 0) - answer_cname = Name.create(checksum + ".fortune") - transaction.respond!(answer_cname, resource_class: IN::CNAME, ttl: 0) - end - - # Default DNS handler - otherwise do |transaction| - transaction.fail!(:NXDomain) - end - end - end -end - -FortuneDNS.daemonize diff --git a/examples/fortune/readme.md b/examples/fortune/readme.md new file mode 100644 index 0000000..169474f --- /dev/null +++ b/examples/fortune/readme.md @@ -0,0 +1,47 @@ +# Fortune DNS + +A DNS server that allows a client to generate fortunes and fetch them with subsequent requests. The server +'remembers' the fortunes it generates, and can serve them to future requests. The reason for this is because most fortunes won't fit over UDP (maximum size 512 bytes) and the client will request the same fortune via TCP. + +You will need to have the `fortune` app installed on your system. It comes installed by default on +most Linux distributions, and can be installed on a Mac with Homebrew by typing: + + # Homebrew + brew install fortune + # MacPorts + sudo port install fortune + # Arch Linux + sudo pacman -S fortune-mod + +By default this server will listen for UDP and TCP requests on port 53, and needs to be started as root. It +assumes the existence of a user 'daemon', as whom the process will run. If such a user doesn't exist on your +system, you will need to either create such a user or update the script to use a user that exists on your +system. + +To start the server, ensure that you're in the examples subdirectory and type + + bundle + sudo bundle exec ./fortune-dns.rb start + +To create a new fortune type + + dig @localhost fortune -t TXT + +This will result in an DNS answer that looks something like this: + + fortune. 0 IN TXT "Text Size: 714 Byte Size: 714" + fortune. 0 IN CNAME 32bf3bf2b0a2255f2df00ed9e95c8185.fortune. + +Take the CNAME from this result and query it. For our example this would be: + + dig @localhost 32bf3bf2b0a2255f2df00ed9e95c8185.fortune -t TXT + +And your answer will be a fortune. + +You can also generate a 'short' fortune by typing the following: + + dig @localhost short.fortune -t TXT + +or view the fortune stats with: + + dig @localhost stats.fortune -t TXT diff --git a/examples/fortune/server.rb b/examples/fortune/server.rb new file mode 100755 index 0000000..479954b --- /dev/null +++ b/examples/fortune/server.rb @@ -0,0 +1,58 @@ +#!/usr/bin/env ruby + +# Released under the MIT License. +# Copyright, 2014, by Samuel Williams. +# Copyright, 2014, by Peter M. Goldstein. + +require "rubydns" +require "async/dns/extensions/string" +require "digest/md5" + +Name = Resolv::DNS::Name +IN = Resolv::DNS::Resource::IN + +endpoint = Async::DNS::Endpoint.for("localhost", port: 5300) + +stats = {requested: 0} +cache = {} + +# Start the RubyDNS server +RubyDNS.run(endpoint) do + match(/short\.fortune/, IN::TXT) do |transaction| + fortune = `fortune -s`.gsub(/\s+/, " ").strip + + transaction.respond!(*fortune.chunked, ttl: 0) + end + + match(/stats\.fortune/, IN::TXT) do |transaction| + $stderr.puts "Sending stats: #{stats.inspect}" + transaction.respond!(stats.inspect) + end + + match(/([a-f0-9]*)\.fortune/, IN::TXT) do |transaction, match| + fortune = cache[match[1]] + stats[:requested] += 1 + + if fortune + transaction.respond!(*fortune.chunked) + else + transaction.fail!(:NXDomain) + end + end + + match(/fortune/, [IN::CNAME, IN::TXT]) do |transaction| + fortune = `fortune`.gsub(/\s+/, " ").strip + checksum = Digest::MD5.hexdigest(fortune) + cache[checksum] = fortune + + answer_txt = "Text Size: #{fortune.size} Byte Size: #{fortune.bytesize}" + transaction.respond!(answer_txt, resource_class: IN::TXT, ttl: 0) + answer_cname = Name.create(checksum + ".fortune") + transaction.respond!(answer_cname, resource_class: IN::CNAME, ttl: 0) + end + + # Default DNS handler + otherwise do |transaction| + transaction.fail!(:NXDomain) + end +end diff --git a/examples/gems.locked b/examples/gems.locked index 0e41f6c..b8f6f02 100644 --- a/examples/gems.locked +++ b/examples/gems.locked @@ -7,49 +7,63 @@ PATH GEM remote: https://rubygems.org/ specs: - async (2.1.0) - console (~> 1.10) - io-event (~> 1.0.0) - timers (~> 4.1) - async-dns (1.3.0) - async-io (~> 1.15) - async-http (0.59.2) - async (>= 1.25) - async-io (>= 1.28) - async-pool (>= 0.2) - protocol-http (~> 0.23.1) - protocol-http1 (~> 0.14.0) - protocol-http2 (~> 0.14.0) - traces (>= 0.4.0) - async-io (1.34.0) + async (2.23.0) + console (~> 1.29) + fiber-annotation + io-event (~> 1.9) + metrics (~> 0.12) + traces (~> 0.15) + async-dns (1.4.1) async - async-pool (0.3.12) + io-endpoint + async-http (0.87.0) + async (>= 2.10.2) + async-pool (~> 0.9) + io-endpoint (~> 0.14) + io-stream (~> 0.6) + metrics (~> 0.12) + protocol-http (~> 0.49) + protocol-http1 (~> 0.30) + protocol-http2 (~> 0.22) + traces (~> 0.10) + async-pool (0.10.3) async (>= 1.25) - console (1.15.3) - fiber-local - fiber-local (1.0.0) + console (1.29.2) + fiber-annotation + fiber-local (~> 1.1) + json + fiber-annotation (0.2.0) + fiber-local (1.1.0) + fiber-storage + fiber-storage (1.0.0) geoip (1.6.4) - io-event (1.0.9) - nokogiri (1.13.8-arm64-darwin) + io-endpoint (0.15.1) + io-event (1.9.0) + io-stream (0.6.1) + json (2.10.1) + metrics (0.12.1) + nokogiri (1.18.2-arm64-darwin) + racc (~> 1.4) + nokogiri (1.18.2-x86_64-linux-gnu) racc (~> 1.4) process-daemon (1.0.1) rainbow (~> 2.0) - protocol-hpack (1.4.2) - protocol-http (0.23.12) - protocol-http1 (0.14.6) + protocol-hpack (1.5.1) + protocol-http (0.49.0) + protocol-http1 (0.30.0) protocol-http (~> 0.22) - protocol-http2 (0.14.2) + protocol-http2 (0.22.1) protocol-hpack (~> 1.4) - protocol-http (~> 0.18) - racc (1.6.0) + protocol-http (~> 0.47) + racc (1.8.1) rainbow (2.2.2) rake - rake (13.0.6) - timers (4.3.4) - traces (0.7.0) + rake (13.2.1) + traces (0.15.2) PLATFORMS arm64-darwin-21 + x86_64-linux DEPENDENCIES async-http @@ -59,4 +73,4 @@ DEPENDENCIES rubydns! BUNDLED WITH - 2.3.10 + 2.6.2 diff --git a/examples/gems.rb b/examples/gems.rb deleted file mode 100644 index 6410e5d..0000000 --- a/examples/gems.rb +++ /dev/null @@ -1,15 +0,0 @@ -# frozen_string_literal: true - -# Released under the MIT License. -# Copyright, 2014-2022, by Samuel Williams. -# Copyright, 2014, by Peter M. Goldstein. - -source "https://rubygems.org" - -gem "rubydns", path: "../" -gem "process-daemon" -gem "nokogiri" - -gem "async-http" - -gem "geoip" diff --git a/examples/geoip-dns.rb b/examples/geoip-dns.rb deleted file mode 100755 index 336c11e..0000000 --- a/examples/geoip-dns.rb +++ /dev/null @@ -1,120 +0,0 @@ -#!/usr/bin/env ruby -# frozen_string_literal: true - -# Released under the MIT License. -# Copyright, 2014-2017, by Samuel Williams. -# Copyright, 2014, by Peter M. Goldstein. - -# Copyright, 2009, 2012, by Samuel G. D. Williams. -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. - -require "geoip" - -require "process/daemon" - -require "rubydns" -require "rubydns/system" - -INTERFACES = [ - [:udp, "0.0.0.0", 5300] -] - -# Path to the GeoIP file downloaded from -# http://geolite.maxmind.com/download/geoip/database/GeoLiteCountry/GeoIP.dat.gz -# If you have renamed the ungzipped file, or have placed it somewhere other than -# the repository root directory you will need to update this path. -PATH_TO_GEOIP_DAT_FILE = - File.expand_path("../GeoIP.dat", File.dirname(__FILE__)) - -# A sample DNS daemon that demonstrates how to use RubyDNS to build responses -# that vary based on the geolocation of the requesting peer. Clients of -# this server who request A records will get an answer IP address based -# on the continent of the client IP address. -# -# Please note that use of this example requires that the peer have a public -# IP address. IP addresses on private networks or the localhost IP (127.0.0.1) -# cannot be resolved to a location, and so will always yield the unknown result. -# This daemon requires the file downloaded from -# http://geolite.maxmind.com/download/geoip/database/GeoLiteCountry/GeoIP.dat.gz -# For more information, please see http://www.maxmind.com/en/geolite and -# http://geoip.rubyforge.org -class GeoIPDNS < Process::Daemon - GEO = GeoIP.new(PATH_TO_GEOIP_DAT_FILE) - - Name = Resolv::DNS::Name - IN = Resolv::DNS::Resource::IN - - def startup - RubyDNS.run_server(INTERFACES) do - fallback_resolver_supervisor = RubyDNS::Resolver.supervise(RubyDNS::System.nameservers) - - match(//, IN::A) do |transaction| - logger.debug "In block" - - # The IP Address of the peer is stored in the transaction options - # with the key :remote_address - ip_address = transaction.options[:remote_address].ip_address - logger.debug "Looking up geographic information for peer #{ip_address}" - location = GeoIPDNS.ip_to_location(ip_address) - - if location - logger.debug "Found location #{location} for #{ip_address}" - else - logger.debug "Could not resolve location for #{ip_address}" - end - - code = location ? location.continent_code : nil - answer = GeoIPDNS.answer_for_continent_code(code) - logger.debug "Answer is #{answer}" - transaction.respond!(answer) - end - - # Default DNS handler - otherwise do |transaction| - logger.debug "In otherwise" - transaction.passthrough!(fallback_resolver_supervisor.actors.first) - end - end - end - - # Maps each continent code to a fixed IP address for the response. - # A simple mapper to demonstrate the behavior. - def self.answer_for_continent_code(code) - case code - when "AF" then "1.1.1.1" - when "AN" then "1.1.2.1" - when "AS" then "1.1.3.1" - when "EU" then "1.1.4.1" - when "NA" then "1.1.5.1" - when "OC" then "1.1.6.1" - when "SA" then "1.1.7.1" - else "1.1.8.1" - end - end - - # Finds the continent code for the specified IP address. - # Returns nil if the IP address cannot be mapped to a location. - def self.ip_to_location(ip_address) - return nil unless ip_address - GEO.country(ip_address) - end -end - -GeoIPDNS.daemonize diff --git a/examples/simple.rb b/examples/simple.rb deleted file mode 100755 index 8fc58b1..0000000 --- a/examples/simple.rb +++ /dev/null @@ -1,30 +0,0 @@ -#!/usr/bin/env ruby -# frozen_string_literal: true - -# Released under the MIT License. -# Copyright, 2017, by Samuel Williams. - -require "rubydns" - -INTERFACES = [ - [:udp, "0.0.0.0", 5300], - [:tcp, "0.0.0.0", 5300] -] - -Name = Resolv::DNS::Name -IN = Resolv::DNS::Resource::IN - -# Use upstream DNS for name resolution. -UPSTREAM = RubyDNS::Resolver.new([[:udp, "8.8.8.8", 53], [:tcp, "8.8.8.8", 53]]) - -# Start the RubyDNS server -RubyDNS.run_server(INTERFACES) do - match(/test.mydomain.org/, IN::A) do |transaction| - transaction.respond!("10.0.0.80") - end - - # Default DNS handler - otherwise do |transaction| - transaction.passthrough!(UPSTREAM) - end -end diff --git a/examples/soa-dns.rb b/examples/soa-dns.rb deleted file mode 100755 index 0ee4e22..0000000 --- a/examples/soa-dns.rb +++ /dev/null @@ -1,86 +0,0 @@ -#!/usr/bin/env ruby -# frozen_string_literal: true - -# Released under the MIT License. -# Copyright, 2017, by Samuel Williams. - -# Copyright, 2009, 2012, by Samuel G. D. Williams. -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. - -require "rubygems" -require "rubydns" - -$R = Resolv::DNS.new -Name = Resolv::DNS::Name -IN = Resolv::DNS::Resource::IN - -RubyDNS.run_server([[:udp, "0.0.0.0", 5400]]) do - # SOA Record - # dig @localhost -p 5400 SOA mydomain.org - match("mydomain.org", IN::SOA) do |transaction| - # - # For more details about these headers please see: - # http://www.ripe.net/ripe/docs/ripe-203.html - # - - transaction.respond!( - Name.create("ns.mydomain.org."), # Master Name - Name.create("admin.mydomain.org."), # Responsible Name - File.mtime(__FILE__).to_i, # Serial Number - 1200, # Refresh Time - 900, # Retry Time - 3_600_000, # Maximum TTL / Expiry Time - 172_800 # Minimum TTL - ) - - transaction.append!(transaction.question, IN::NS, section: :authority) - end - - # Default NS record - # dig @localhost -p 5400 mydomain.org NS - match("mydomain.org", IN::NS) do |transaction| - transaction.respond!(Name.create("ns.mydomain.org.")) - end - - # For this exact address record, return an IP address - # dig @localhost -p 5400 CNAME bob.mydomain.org - match(/([^.]+).mydomain.org/, IN::CNAME) do |transaction| - transaction.respond!(Name.create("www.mydomain.org")) - transaction.append!("www.mydomain.org", IN::A) - end - - match("80.0.0.10.in-addr.arpa", IN::PTR) do |transaction| - transaction.respond!(Name.create("www.mydomain.org.")) - end - - match("www.mydomain.org", IN::A) do |transaction| - transaction.respond!("10.0.0.80") - end - - match("ns.mydomain.org", IN::A) do |transaction| - transaction.respond!("10.0.0.10") - end - - # Default DNS handler - otherwise do |transaction| - # Non-Existant Domain - transaction.fail!(:NXDomain) - end -end diff --git a/examples/test-dns-1.rb b/examples/test-dns-1.rb deleted file mode 100755 index 6123d8e..0000000 --- a/examples/test-dns-1.rb +++ /dev/null @@ -1,87 +0,0 @@ -#!/usr/bin/env ruby -# frozen_string_literal: true - -# Released under the MIT License. -# Copyright, 2017, by Samuel Williams. - -# Copyright, 2009, 2012, by Samuel G. D. Williams. -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. - -require "rubygems" -require "rubydns" -require "rubydns/system" - -# You can specify other DNS servers easily -# $R = Resolv::DNS.new(:nameserver => ["xx.xx.1.1", "xx.xx.2.2"]) - -R = RubyDNS::Resolver.new(RubyDNS::System.nameservers) -Name = Resolv::DNS::Name -IN = Resolv::DNS::Resource::IN -INTERFACES = [ - [:udp, "0.0.0.0", 5300], - [:tcp, "0.0.0.0", 5300], - # [:udp, '::0', 5300], - # [:tcp, '::0', 5300], -] - -RubyDNS.run_server(INTERFACES) do - # % dig +nocmd +noall +answer @localhost ANY dev.mydomain.org - # dev.mydomain.org. 16000 IN A 10.0.0.80 - # dev.mydomain.org. 16000 IN MX 10 mail.mydomain.org. - match(/dev.mydomain.org/, IN::ANY) do |transaction| - transaction.append_question! - - [IN::A, IN::CNAME, IN::MX].each do |resource_class| - logger.debug "Appending query for #{resource_class}..." - transaction.append!(transaction.name, resource_class) - end - end - - # For this exact address record, return an IP address - match("dev.mydomain.org", IN::A) do |transaction| - transaction.respond!("10.0.0.80") - end - - match("80.0.0.10.in-addr.arpa", IN::PTR) do |transaction| - transaction.respond!(Name.create("dev.mydomain.org.")) - end - - match("dev.mydomain.org", IN::MX) do |transaction| - transaction.respond!(10, Name.create("mail.mydomain.org.")) - end - - match(/^test([0-9]+).mydomain.org$/, IN::A) do |transaction, match_data| - offset = match_data[1].to_i - - if offset > 0 && offset < 10 - logger.info "Responding with address #{'10.0.0.' + (90 + offset).to_s}..." - transaction.respond!("10.0.0." + (90 + offset).to_s) - else - logger.info "Address out of range: #{offset}!" - false - end - end - - # Default DNS handler - otherwise do |transaction| - logger.info "Passing DNS request upstream..." - transaction.passthrough!(R) - end -end diff --git a/examples/test-dns-2.rb b/examples/test-dns-2.rb deleted file mode 100755 index e379a15..0000000 --- a/examples/test-dns-2.rb +++ /dev/null @@ -1,87 +0,0 @@ -#!/usr/bin/env ruby -# frozen_string_literal: true - -# Released under the MIT License. -# Copyright, 2017, by Samuel Williams. - -# Copyright, 2009, 2012, by Samuel G. D. Williams. -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. - -require "rubydns" -require "process-daemon" - -# To run this command, use the standard daemon syntax as root -# ./daemon2.rb start - -# You should be able to see that the server has dropped priviledges -# # ps aux | grep daemon2.rb -# daemon 16555 0.4 0.0 81392 2024 ?? S 3:35am 0:00.28 ruby ../test/daemon2.rb start - -# Test using the following command -# dig @localhost test.mydomain.org -# dig +tcp @localhost test.mydomain.org - -# You might need to change the user name "daemon". This can be a user name or a user id. -RUN_AS = "daemon" - -INTERFACES = [ - [:udp, "0.0.0.0", 53], - [:tcp, "0.0.0.0", 53] -] - -# We need to be root in order to bind to privileged port -if RExec.current_user != "root" - $stderr.puts "Sorry, this command needs to be run as root!" - exit 1 -end - -# The Daemon itself -class Server < Process::Daemon - Name = Resolv::DNS::Name - IN = Resolv::DNS::Resource::IN - - # Use upstream DNS for name resolution. - UPSTREAM = RubyDNS::Resolver.new([[:udp, "8.8.8.8", 53], [:tcp, "8.8.8.8", 53]]) - - def startup - # Don't buffer output (for debug purposes) - $stderr.sync = true - - # Start the RubyDNS server - RubyDNS.run_server(INTERFACES) do - on(:start) do - RExec.change_user(RUN_AS) - end - - match("test.mydomain.org", IN::A) do |transaction| - transaction.respond!("10.0.0.80") - end - - # Default DNS handler - otherwise do |transaction| - logger.info "Passthrough: #{transaction}" - transaction.passthrough!(UPSTREAM) - end - end - end -end - -# RExec daemon runner -Server.daemonize diff --git a/examples/wikipedia/readme.md b/examples/wikipedia/readme.md new file mode 100644 index 0000000..d53781d --- /dev/null +++ b/examples/wikipedia/readme.md @@ -0,0 +1,23 @@ +# Wikipedia DNS + +A DNS server that queries Wikipedia and returns summaries for specifically crafted queries. + +By default this server will listen for UDP and TCP requests on port 53, and needs to be started as root. It +assumes the existence of a user 'daemon', as whom the process will run. If such a user doesn't exist on your +system, you will need to either create such a user or update the script to use a user that exists on your +system. + +To start the server, ensure that you're in the examples subdirectory and type + + bundle + sudo bundle exec ./wikipedia-dns.rb start + +To query Wikipedia, pick a term - say, 'helium' - and make a DNS query like + + dig @localhost helium.wikipedia -t TXT + +The answer section should contain the summary for this topic from Wikipedia + + helium.wikipedia. 86400 IN TXT "Helium is a chemical element with symbol He and atomic number 2. It is a colorless, odorless, tasteless, non-toxic, inert, monatomic gas that heads the noble gas group in the periodic table. Its boiling and melting points are the lowest among the elements" " and it exists only as a gas except in extreme conditions." + +Long blocks of text cannot be easily replied in DNS as they must be chunked into segments at most 255 bytes. Long replies must be sent back using TCP. diff --git a/examples/wikipedia-dns.rb b/examples/wikipedia/server.rb similarity index 52% rename from examples/wikipedia-dns.rb rename to examples/wikipedia/server.rb index a57ce7b..4da553f 100755 --- a/examples/wikipedia-dns.rb +++ b/examples/wikipedia/server.rb @@ -24,16 +24,16 @@ module Wikipedia ENDPOINT = Async::HTTP::Endpoint.parse("https://en.wikipedia.org") - def self.lookup(title, logger: nil) + def self.lookup(title) client = Async::HTTP::Client.new(ENDPOINT) url = self.summary_url(title) - logger&.debug "Making request to #{ENDPOINT} for #{url}." + Console.debug "Making request to #{ENDPOINT} for #{url}." response = client.get(url, headers: {"user-agent" => "RubyDNS"}) - logger&.debug "Got response #{response.inspect}." + Console.debug "Got response #{response.inspect}." if response.status == 301 - return lookup(response.headers["location"], logger: logger) + return lookup(response.headers["location"]) else return self.extract_summary(response.body.read).force_encoding("ASCII-8BIT") end @@ -55,51 +55,30 @@ def self.extract_summary(json_text) end end -# A DNS server that queries Wikipedia and returns summaries for -# specifically crafted queries. -class WikipediaDNS - Name = Resolv::DNS::Name - IN = Resolv::DNS::Resource::IN - - INTERFACES = [ - [:udp, "::", 5300], - [:tcp, "::", 5300], - ] +stats = {requested: 0} - def startup - # Don't buffer output (for debug purposes) - $stderr.sync = true +endpoint = Async::DNS::Endpoint.for("localhost", port: 5300) - stats = { requested: 0 } +IN = Resolv::DNS::Resource::IN - # Start the RubyDNS server - RubyDNS.run_server(INTERFACES) do - on(:start) do - # Process::Daemon::Privileges.change_user(RUN_AS) - - @logger.info "Starting Wikipedia DNS..." - end - - match(/stats\.wikipedia/, IN::TXT) do |transaction| - transaction.respond!(*stats.inspect.chunked) - end +# A DNS server that queries Wikipedia and returns summaries for +# specifically crafted queries. +RubyDNS.run(endpoint) do + match(/stats\.wikipedia/, IN::TXT) do |transaction| + transaction.respond!(*stats.inspect.chunked) + end - match(/(.+)\.wikipedia/, IN::TXT) do |transaction, match_data| - title = match_data[1] - stats[:requested] += 1 - - summary = Wikipedia.lookup(title, logger: @logger) - - transaction.respond!(*summary.chunked) - end + match(/(.+)\.wikipedia/, IN::TXT) do |transaction, match_data| + title = match_data[1] + stats[:requested] += 1 + + summary = Wikipedia.lookup(title) + + transaction.respond!(*summary.chunked) + end - # Default DNS handler - otherwise do |transaction| - transaction.fail!(:NXDomain) - end - end + # Default DNS handler + otherwise do |transaction| + transaction.fail!(:NXDomain) end end - -wikipedia_dns = WikipediaDNS.new -wikipedia_dns.startup diff --git a/lib/rubydns.rb b/lib/rubydns.rb index 25a88cf..ffd1363 100644 --- a/lib/rubydns.rb +++ b/lib/rubydns.rb @@ -14,8 +14,14 @@ module RubyDNS Resolver = Async::DNS::Resolver # Run a server with the given rules. - def self.run (*arguments, server_class: Server, **options, &block) - server_class.new(*arguments, **options, &block).run + def self.run(*arguments, server_class: Server, **options, &block) + server = server_class.new(*arguments, **options) + + if block_given? + server.instance_eval(&block) + end + + return server.run end # @deprecated Use {RubyDNS.run} instead. diff --git a/lib/rubydns/rule.rb b/lib/rubydns/rule.rb index 85b10c9..703c4c3 100644 --- a/lib/rubydns/rule.rb +++ b/lib/rubydns/rule.rb @@ -11,6 +11,14 @@ module RubyDNS # Represents a single rule in the server. class Rule + def self.for(pattern, &block) + new(pattern, block) + end + + # Create a new rule with a given pattern and callback. + # + # @param pattern [Array] The pattern to match against. + # @param callback [Proc] The callback to invoke when the pattern matches. def initialize(pattern, callback) @pattern = pattern @callback = callback @@ -32,7 +40,7 @@ def match(name, resource_class) # Invoke the rule, if it matches the incoming request, it is evaluated and returns `true`, otherwise returns `false`. def call(server, name, resource_class, transaction) unless match(name, resource_class) - server.logger.debug "<#{transaction.query.id}> Resource class #{resource_class} failed to match #{@pattern[1].inspect}!" + Console.debug "<#{transaction.query.id}> Resource class #{resource_class} failed to match #{@pattern[1].inspect}!" return false end @@ -43,31 +51,31 @@ def call(server, name, resource_class, transaction) match_data = @pattern[0].match(name) if match_data - server.logger.debug "<#{transaction.query.id}> Regexp pattern matched with #{match_data.inspect}." + Console.debug "<#{transaction.query.id}> Regexp pattern matched with #{match_data.inspect}." - @callback[transaction, match_data] + @callback.call(transaction, match_data) return true end when String if @pattern[0] == name - server.logger.debug "<#{transaction.query.id}> String pattern matched." + Console.debug "<#{transaction.query.id}> String pattern matched." - @callback[transaction] + @callback.call(transaction) return true end else if (@pattern[0].call(name, resource_class) rescue false) - server.logger.debug "<#{transaction.query.id}> Callable pattern matched." + Console.debug "<#{transaction.query.id}> Callable pattern matched." - @callback[transaction] + @callback.call(transaction) return true end end - server.logger.debug "<#{transaction.query.id}> No pattern matched." + Console.debug "<#{transaction.query.id}> No pattern matched." # We failed to match the pattern. return false diff --git a/lib/rubydns/server.rb b/lib/rubydns/server.rb index 76ddabb..714d3d0 100644 --- a/lib/rubydns/server.rb +++ b/lib/rubydns/server.rb @@ -6,6 +6,8 @@ # Copyright, 2014, by Zac Sprackett. # Copyright, 2015, by Michal Cichra. +require_relative "rule" + require "async/dns/server" module RubyDNS @@ -19,20 +21,13 @@ class Server < Async::DNS::Server # end # end # - def initialize(*args, &block) - super(*args) + def initialize(...) + super - @events = {} @rules = [] @otherwise = nil - - if block_given? - instance_eval(&block) - end end - - attr_accessor :logger - + # This function connects a pattern with a block. A pattern is either a String or a Regex instance. Optionally, a second argument can be provided which is either a String, Symbol or Array of resource record types which the rule matches against. # # match("www.google.com") @@ -42,24 +37,6 @@ def initialize(*args, &block) def match(*pattern, &block) @rules << Rule.new(pattern, block) end - - # Register a named event which may be invoked later using #fire - # - # on(:start) do |server| - # Process::Daemon::Permissions.change_user(RUN_AS) - # end - def on(event_name, &block) - @events[event_name] = block - end - - # Fire the named event, which must have been registered using on. - def fire(event_name) - callback = @events[event_name] - - if callback - callback.call(self) - end - end # Specify a default block to execute if all other rules fail to match. This block is typially used to pass the request on to another server (i.e. recursive request). # @@ -78,10 +55,10 @@ def next! # Give a name and a record type, try to match a rule and use it for processing the given arguments. def process(name, resource_class, transaction) - @logger.debug {"<#{transaction.query.id}> Searching for #{name} #{resource_class.name}"} + Console.debug(self) {"<#{transaction.query.id}> Searching for #{name} #{resource_class.name}"} @rules.each do |rule| - @logger.debug {"<#{transaction.query.id}> Checking rule #{rule}..."} + Console.debug(self) {"<#{transaction.query.id}> Checking rule #{rule}..."} catch (:next) do # If the rule returns true, we assume that it was successful and no further rules need to be evaluated. diff --git a/readme.md b/readme.md index 69046fb..9a1fe2e 100644 --- a/readme.md +++ b/readme.md @@ -32,25 +32,21 @@ Here is the code from `examples/basic-dns.rb`: #!/usr/bin/env ruby require 'rubydns' -INTERFACES = [ - [:udp, "0.0.0.0", 5300], - [:tcp, "0.0.0.0", 5300], -] +# Use the system default resolver for upstream queries: +upstream = Async::DNS::Resolver.default -IN = Resolv::DNS::Resource::IN +# We will use port 5300 so we don't need to run the server as root: +endpoint = Async::DNS::Endpoint.for("localhost", port: 5300) -# Use upstream DNS for name resolution. -UPSTREAM = RubyDNS::Resolver.new([[:udp, "8.8.8.8", 53], [:tcp, "8.8.8.8", 53]]) - -# Start the RubyDNS server -RubyDNS::run_server(INTERFACES) do - match(%r{test.local}, IN::A) do |transaction| +# Start the RubyDNS server: +RubyDNS.run(endpoint) do + match(%r{test.local}, Resolv::DNS::Resource::IN::A) do |transaction| transaction.respond!("10.0.0.80") end # Default DNS handler otherwise do |transaction| - transaction.passthrough!(UPSTREAM) + transaction.passthrough!(upstream) end end ``` diff --git a/test/rubydns/injected_supervisor.rb b/test/rubydns/injected_supervisor.rb deleted file mode 100644 index 5008e2c..0000000 --- a/test/rubydns/injected_supervisor.rb +++ /dev/null @@ -1,47 +0,0 @@ -#!/usr/bin/env ruby -# frozen_string_literal: true - -# Released under the MIT License. -# Copyright, 2014, by Peter M. Goldstein. -# Copyright, 2014-2017, by Samuel Williams. - -require "rubydns" -require "async/dns/extensions/string" - -class TestServer < RubyDNS::RuleBasedServer - def test_message - "Testing..." - end -end - -SERVER_PORTS = [[:udp, "127.0.0.1", 5520]] -IN = Resolv::DNS::Resource::IN - -describe "RubyDNS::run_server(server_class: ...)" do - include_context Async::RSpec::Reactor - - let(:server) do - # Start the RubyDNS server - RubyDNS::run_server(SERVER_PORTS, server_class: TestServer) do - match("test_message", IN::TXT) do |transaction| - transaction.respond!(*test_message.chunked) - end - - # Default DNS handler - otherwise do |transaction| - transaction.fail!(:NXDomain) - end - end - end - - it "should use the injected class" do - task = server - - resolver = RubyDNS::Resolver.new(SERVER_PORTS) - response = resolver.query("test_message", IN::TXT) - text = response.answer.first - expect(text[2].strings.join).to be == "Testing..." - - task.stop - end -end diff --git a/test/rubydns/passthrough.rb b/test/rubydns/passthrough.rb deleted file mode 100755 index 2c37828..0000000 --- a/test/rubydns/passthrough.rb +++ /dev/null @@ -1,67 +0,0 @@ -#!/usr/bin/env ruby -# frozen_string_literal: true - -# Released under the MIT License. -# Copyright, 2012-2017, by Samuel Williams. - -require "rubydns" - -SERVER_PORTS = [[:udp, "127.0.0.1", 5340], [:tcp, "127.0.0.1", 5340]] -Name = Resolv::DNS::Name -IN = Resolv::DNS::Resource::IN - -describe "RubyDNS Passthrough Server" do - include_context Async::RSpec::Reactor - - def run_server - task = RubyDNS::run_server(listen: SERVER_PORTS) do - resolver = RubyDNS::Resolver.new([[:udp, "8.8.8.8", 53], [:tcp, "8.8.8.8", 53]]) - - match(/.*\.com/, IN::A) do |transaction| - transaction.passthrough!(resolver) - end - - match(/a-(.*\.org)/) do |transaction, match_data| - transaction.passthrough!(resolver, :name => match_data[1]) - end - - # Default DNS handler - otherwise do |transaction| - transaction.fail!(:NXDomain) - end - end - - yield - - ensure - task.stop - end - - it "should resolve domain correctly" do - run_server do - resolver = RubyDNS::Resolver.new(SERVER_PORTS, timeout: 1) - - response = resolver.query("google.com") - expect(response.ra).to be == 1 - - answer = response.answer.first - expect(answer).not_to be == nil - expect(answer.count).to be > 0 - - addresses = answer.select {|record| record.kind_of? Resolv::DNS::Resource::IN::A} - expect(addresses.size).to be > 0 - end - end - - it "should resolve prefixed domain correctly" do - run_server do - resolver = RubyDNS::Resolver.new(SERVER_PORTS) - - response = resolver.query("a-slashdot.org") - answer = response.answer.first - - expect(answer).not_to be == nil - expect(answer.count).to be > 0 - end - end -end diff --git a/test/rubydns/rules.rb b/test/rubydns/rules.rb index 283b3aa..136e0a8 100755 --- a/test/rubydns/rules.rb +++ b/test/rubydns/rules.rb @@ -6,50 +6,44 @@ require "rubydns" -describe RubyDNS::RuleBasedServer do - IN = Resolv::DNS::Resource::IN - - true_callback = Proc.new { true } - - let(:server) {double(:logger => Console.logger)} +IN = Resolv::DNS::Resource::IN +describe RubyDNS::Rule do + let(:server) {RubyDNS::Server.new} + let(:query) {Resolv::DNS::Message.new(0)} + let(:transaction) {Async::DNS::Transaction.new(server, query, nil, nil, nil)} + it "should match string patterns correctly" do - transaction = double(:query => Resolv::DNS::Message.new(0)) - - rule = RubyDNS::RuleBasedServer::Rule.new(["foobar", IN::A], true_callback) - + rule = subject.for(["foobar", IN::A]) {true} + expect(rule.call(server, "foobar", IN::A, transaction)).to be == true expect(rule.call(server, "barfoo", IN::A, transaction)).to be == false expect(rule.call(server, "foobar", IN::TXT, transaction)).to be == false end - + it "should match regular expression patterns correctly" do - transaction = double(:query => Resolv::DNS::Message.new(0)) - - rule = RubyDNS::RuleBasedServer::Rule.new([/foo/, IN::A], true_callback) - + rule = subject.for([/foo/, IN::A]) {true} + expect(rule.call(server, "foobar", IN::A, transaction)).to be == true expect(rule.call(server, "barbaz", IN::A, transaction)).to be == false expect(rule.call(server, "foobar", IN::TXT, transaction)).to be == false end - + it "should match callback patterns correctly" do - transaction = double(:query => Resolv::DNS::Message.new(0)) - calls = 0 - + callback = Proc.new do |name, resource_class| # A counter used to check the number of times this block was invoked. calls += 1 - + name.size == 6 end - - rule = RubyDNS::RuleBasedServer::Rule.new([callback], true_callback) - + + rule = RubyDNS::Rule.for([callback]) {true} + expect(rule.call(server, "foobar", IN::A, transaction)).to be == true expect(rule.call(server, "foobarbaz", IN::A, transaction)).to be == false - + expect(calls).to be == 2 end end From 46da22be03884a627b700217e9aa5bf099afca6f Mon Sep 17 00:00:00 2001 From: Samuel Williams Date: Sun, 16 Feb 2025 12:43:55 +1300 Subject: [PATCH 3/8] Add missing bake gems. --- gems.rb | 3 +++ 1 file changed, 3 insertions(+) diff --git a/gems.rb b/gems.rb index 66cfcd7..090dd27 100644 --- a/gems.rb +++ b/gems.rb @@ -17,4 +17,7 @@ gem "covered" gem "decode" gem "rubocop" + + gem "bake-test" + gem "bake-test-external" end From cb400e74267e964666d70334456306dadc6032f6 Mon Sep 17 00:00:00 2001 From: Samuel Williams Date: Sun, 16 Feb 2025 12:53:19 +1300 Subject: [PATCH 4/8] RuboCop. --- examples/fortune/server.rb | 1 + examples/wikipedia/server.rb | 1 + 2 files changed, 2 insertions(+) diff --git a/examples/fortune/server.rb b/examples/fortune/server.rb index 479954b..3bc4382 100755 --- a/examples/fortune/server.rb +++ b/examples/fortune/server.rb @@ -1,4 +1,5 @@ #!/usr/bin/env ruby +# frozen_string_literal: true # Released under the MIT License. # Copyright, 2014, by Samuel Williams. diff --git a/examples/wikipedia/server.rb b/examples/wikipedia/server.rb index 4da553f..9087b79 100755 --- a/examples/wikipedia/server.rb +++ b/examples/wikipedia/server.rb @@ -1,5 +1,6 @@ #!/usr/bin/env ruby # encoding: utf-8 +# frozen_string_literal: true # Released under the MIT License. # Copyright, 2014-2022, by Samuel Williams. From 2f45a6b60fd5130ab36d4d818fce252eb5c0fab5 Mon Sep 17 00:00:00 2001 From: Samuel Williams Date: Sun, 16 Feb 2025 14:40:22 +1300 Subject: [PATCH 5/8] Add coverage configuration. --- config/sus.rb | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 config/sus.rb diff --git a/config/sus.rb b/config/sus.rb new file mode 100644 index 0000000..f99b9c2 --- /dev/null +++ b/config/sus.rb @@ -0,0 +1,7 @@ +# frozen_string_literal: true + +# Released under the MIT License. +# Copyright, 2024, by Samuel Williams. + +require "covered/sus" +include Covered::Sus From c5ec2fb9948e57707fad548cc93083440a215b1e Mon Sep 17 00:00:00 2001 From: Samuel Williams Date: Sun, 16 Feb 2025 14:48:50 +1300 Subject: [PATCH 6/8] Add compatibilty for old array of interfaces. --- lib/rubydns.rb | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/lib/rubydns.rb b/lib/rubydns.rb index ffd1363..643193e 100644 --- a/lib/rubydns.rb +++ b/lib/rubydns.rb @@ -9,6 +9,7 @@ require_relative "rubydns/version" require_relative "rubydns/server" +# @namespace module RubyDNS # Backwards compatibility: Resolver = Async::DNS::Resolver @@ -25,7 +26,17 @@ def self.run(*arguments, server_class: Server, **options, &block) end # @deprecated Use {RubyDNS.run} instead. - def self.run_server(...) - self.run(...) + def self.run_server(*arguments, **options, &block) + if arguments.first.is_a?(Array) + warn "Using an array of interfaces is deprecated. Please use `Async::DNS::Endpoint` instead.", uplevel: 1 + + endpoints = arguments[0].map do |specification| + IO::Endpoint.public_send(*specification) + end + + arguments[0] = IO::Endpoint.composite(*endpoints) + end + + self.run(*arguments, **options, &block) end end From bd7f93cc6675794ca6f003bc4fc4761658457741 Mon Sep 17 00:00:00 2001 From: Samuel Williams Date: Sun, 16 Feb 2025 14:53:30 +1300 Subject: [PATCH 7/8] Minor improvements to readme.md. --- readme.md | 75 ++++++++++--------------------------------------------- 1 file changed, 13 insertions(+), 62 deletions(-) diff --git a/readme.md b/readme.md index 9a1fe2e..a9f1faa 100644 --- a/readme.md +++ b/readme.md @@ -4,29 +4,21 @@ RubyDNS is a high-performance DNS server which can be easily integrated into oth [![Development Status](https://github.com/socketry/rubydns/workflows/Test/badge.svg)](https://github.com/socketry/rubydns/actions?workflow=Test) -[![RubyDNS Introduction](http://img.youtube.com/vi/B9ygq0xh3HQ/maxresdefault.jpg)](https://www.youtube.com/watch?v=B9ygq0xh3HQ&feature=youtu.be&hd=1 "RubyDNS Introduction") - ## Installation -Add this line to your application's Gemfile: - - gem 'rubydns' - -And then execute: - - $ bundle +Add the gem to your project: -Or install it yourself as: - - $ gem install rubydns +~~~ bash +$ bundle add rubydns +~~~ ## Usage -There are [lots of examples available](examples/README.md) in the `examples/` directory. +There are examples in the `examples` directory which demonstrate how to use RubyDNS. -### Basic DNS Server +### Simple DNS Server -Here is the code from `examples/basic-dns.rb`: +This example demonstrates how to create a simple DNS server that responds to `test.local A` and forwards all other requests to the system default resolver. ``` ruby #!/usr/bin/env ruby @@ -51,15 +43,6 @@ RubyDNS.run(endpoint) do end ``` -Start the server using `RUBYOPT=-w ./examples/basic-dns.rb`. You can then test it using dig: - - $ dig @localhost -p 5300 test.local - $ dig @localhost -p 5300 google.com - -### File Handle Limitations - -On some platforms (e.g. Mac OS X) the number of file descriptors is relatively low by default and should be increased by calling `ulimit -n 10000` before running tests or even before starting a server which expects a large number of concurrent incoming connections. - ### Custom Servers It is possible to create and integrate your own custom servers, however this functionality has now moved to [`Async::DNS::Server`](https://github.com/socketry/async-dns). @@ -71,7 +54,7 @@ class MyServer < Async::DNS::Server end end -Async::Reactor.run do +Async do task = MyServer.new.run # ... do other things, e.g. run specs/tests @@ -83,39 +66,15 @@ end This is the best way to integrate with other projects. -## Performance - -**Due to changes in the underlying code, there have been some very minor performance regressions. The numbers below will be updated in due course.** - -We welcome additional benchmarks and feedback regarding RubyDNS performance. To check the current performance results, consult the [travis build job output](https://travis-ci.org/ioquatix/rubydns). - -### Server - -The performance is on the same magnitude as `bind9`. Some basic benchmarks resolving 1000 names concurrently, repeated 5 times, using `RubyDNS::Resolver` gives the following: - -``` - user system total real -RubyDNS::Server 4.280000 0.450000 4.730000 ( 4.854862) -Bind9 4.970000 0.520000 5.490000 ( 5.541213) -``` - -These benchmarks are included in the unit tests. To test bind9 performance, it must be installed and `which named` must return the executable. - -### Resolver - -The `RubyDNS::Resolver` is highly concurrent and can resolve individual names as fast as the built in `Resolv::DNS` resolver. Because the resolver is asynchronous, when dealing with multiple names, it can work more efficiently: +### DNSSEC support -``` - user system total real -RubyDNS::Resolver 0.020000 0.010000 0.030000 ( 0.030507) -Resolv::DNS 0.070000 0.010000 0.080000 ( 1.465975) -``` +DNSSEC is currently not supported and is [unlikely to be supported in the future](http://sockpuppet.org/blog/2015/01/15/against-dnssec/). -These benchmarks are included in the unit tests. +## See Also -### DNSSEC support +The majority of this gem is now implemented by `async-dns`. -DNSSEC is currently not supported and is [unlikely to be supported in the future](http://sockpuppet.org/blog/2015/01/15/against-dnssec/). + - [async-dns](https://github.com/socketry/async-dns) — Asynchronous DNS resolver and server. ## Contributing @@ -134,11 +93,3 @@ In order to protect users of this project, we require all contributors to comply ### Community Guidelines This project is best served by a collaborative and respectful environment. Treat each other professionally, respect differing viewpoints, and engage constructively. Harassment, discrimination, or harmful behavior is not tolerated. Communicate clearly, listen actively, and support one another. If any issues arise, please inform the project maintainers. - -## See Also - -The majority of this gem is now implemented by `async-dns`. - - - [async-io](https://github.com/socketry/async-io) — Asynchronous networking and sockets. - - [async-dns](https://github.com/socketry/async-dns) — Asynchronous DNS resolver and server. - - [async-rspec](https://github.com/socketry/async-rspec) — Shared contexts for running async specs. From 20b4525369294712f28e903388543a8957d684aa Mon Sep 17 00:00:00 2001 From: Samuel Williams Date: Sun, 16 Feb 2025 14:55:48 +1300 Subject: [PATCH 8/8] Missing documentation. --- lib/rubydns/rule.rb | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/lib/rubydns/rule.rb b/lib/rubydns/rule.rb index 703c4c3..c8f85b7 100644 --- a/lib/rubydns/rule.rb +++ b/lib/rubydns/rule.rb @@ -11,14 +11,17 @@ module RubyDNS # Represents a single rule in the server. class Rule + # Create a new rule with a given pattern and callback. + # + # @parameter pattern [Array] The pattern to match against. def self.for(pattern, &block) new(pattern, block) end # Create a new rule with a given pattern and callback. # - # @param pattern [Array] The pattern to match against. - # @param callback [Proc] The callback to invoke when the pattern matches. + # @parameter pattern [Array] The pattern to match against. + # @parameter callback [Proc] The callback to invoke when the pattern matches. def initialize(pattern, callback) @pattern = pattern @callback = callback @@ -81,8 +84,9 @@ def call(server, name, resource_class, transaction) return false end + # Return a string representation of the rule. def to_s - @pattern.inspect + "#<#{self.class} #{@pattern}>" end end end