Merge branch 'master' into depfu/update/jaeger-client-1.0.0

This commit is contained in:
Christian Nicolai 2020-08-11 15:56:29 +02:00 committed by GitHub
commit d51461f8b0
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
28 changed files with 569 additions and 107 deletions

1
.gitignore vendored
View File

@ -1,3 +1,4 @@
.DS_Store
*.lock
pkg/*
.yardoc

View File

@ -1,13 +1,6 @@
inherit_from: .rubocop_todo.yml
AllCops:
TargetRubyVersion: '2.3'
Gemspec/OrderedDependencies:
Enabled: false
Layout/AlignHash:
Enabled: false
TargetRubyVersion: '2.5'
NewCops: enable
Layout/EmptyLineAfterGuardClause:
Enabled: false
@ -16,9 +9,15 @@ Layout/EmptyLineAfterGuardClause:
Layout/EmptyLinesAroundArguments:
Enabled: false
Layout/LeadingBlankLines:
Layout/HashAlignment:
Enabled: false
Layout/LeadingEmptyLines:
Enabled: false
Layout/LineLength:
Max: 200
Layout/SpaceInsideHashLiteralBraces:
Enabled: false
@ -34,16 +33,13 @@ Metrics/ClassLength:
Metrics/CyclomaticComplexity:
Enabled: false
Metrics/LineLength:
Max: 200
Metrics/MethodLength:
Enabled: false
Metrics/PerceivedComplexity:
Enabled: false
Naming/UncommunicativeMethodParamName:
Naming/MethodParameterName:
Enabled: false
Naming/MemoizedInstanceVariableName:
@ -58,15 +54,24 @@ Style/Documentation:
Style/FormatStringToken:
Enabled: false
Style/FrozenStringLiteralComment:
Enabled: false
Style/GuardClause:
Enabled: false
Style/HashEachMethods:
Enabled: true
Style/HashTransformKeys:
Enabled: true
Style/HashTransformValues:
Enabled: true
Style/IdenticalConditionalBranches:
Enabled: false
Style/IfUnlessModifier:
Enabled: false
Style/InverseMethods:
Enabled: false
@ -78,3 +83,6 @@ Style/RescueModifier:
Style/SymbolArray:
Enabled: false
Style/TrailingCommaInArrayLiteral:
Enabled: false

View File

@ -1,7 +0,0 @@
# This configuration was generated by
# `rubocop --auto-gen-config`
# on 2018-02-23 12:54:10 +0100 using RuboCop version 0.52.1.
# The point is for the user to remove these configuration records
# one by one as the offenses are removed from the code base.
# Note that changes in the inspected code, or installation of new
# versions of RuboCop, may require this file to be generated again.

16
.solargraph.yml Normal file
View File

@ -0,0 +1,16 @@
---
include:
- "**/*.rb"
- "bin/dyndnsd"
exclude:
- spec/**/*
- test/**/*
- vendor/**/*
- ".bundle/**/*"
require: []
domains: []
reporters:
- rubocop
- require_not_found
require_paths: []
max_files: 5000

View File

@ -1,8 +1,10 @@
---
sudo: false
os: linux
language: ruby
rvm:
- 2.6
- 2.5
- 2.4
- 2.3
- 2.7
- 2.6
- 2.5
script:
- bundle exec rake travis

View File

@ -1,5 +1,45 @@
# Changelog
## 3.0.0 (July 29, 2020)
IMPROVEMENTS:
- Drop EOL Ruby 2.4 and lower support, now minimum version supported is Ruby 2.5
## 2.3.1 (July 27, 2020)
IMPROVEMENTS:
- Fix annoying error message `log writing failed. can't be called from trap context` on shutdown by not attempting to log redundant information there
## 2.3.0 (July 20, 2020)
IMPROVEMENTS:
- Allow enabling debug logging
- Add updater that uses [DNS zone transfers via AXFR (RFC5936)](https://tools.ietf.org/html/rfc5936) to allow any secondary nameserver(s) to fetch the zone contents after (optionally) receiving a [DNS NOTIFY (RFC1996)](https://tools.ietf.org/html/rfc1996) request
## 2.2.0 (March 6, 2020)
IMPROVEMENTS:
- Refactor gemspec based on [recommendations](https://piotrmurach.com/articles/writing-a-ruby-gem-specification/) so tests are now excluded from gem and binaries move to `./exe` directory
- Adopt Ruby 2.3 frozen string literals for source code potentially reducing memory consumption
## 2.1.1 (March 1, 2020)
IMPROVEMENTS:
- Fix potential `nil` cases detected by [Sorbet](https://sorbet.org) including refactorings
## 2.1.0 (March 1, 2020)
IMPROVEMENTS:
- Add Ruby 2.7 support
- Add [solargraph](https://github.com/castwide/solargraph) to dev tooling as Ruby Language Server usable e.g. for IDEs (used solargraph version not compatible with Ruby 2.7 as bundler-audit 0.6.x requires old `thor` gem)
- Document code using YARD tags, e.g. for type information and better code completion
## 2.0.0 (January 25, 2019)
IMPROVEMENTS:
@ -9,7 +49,7 @@ IMPROVEMENTS:
- Better code maintainability by refactorings
- Update dependencies, mainly `rack` to new major version 2
- Add Ruby 2.5 and Ruby 2.6 support
- Add experimental [OpenTracing](http://opentracing.io/) support with [CNCF Jaeger](https://github.com/jaegertracing/jaeger)
- Add experimental [OpenTracing](https://opentracing.io/) support with [CNCF Jaeger](https://github.com/jaegertracing/jaeger)
- Support host offlining by deleting the associated DNS records
- Add textfile reporter to write Graphite-style metrics (also compatible with [Prometheus](https://prometheus.io/)) into a file

View File

@ -1,3 +1,5 @@
# frozen_string_literal: true
source 'https://rubygems.org'
gemspec

100
README.md
View File

@ -4,16 +4,20 @@
A small, lightweight and extensible DynDNS server written with Ruby and Rack.
## Description
dyndnsd.rb aims to implement a small [DynDNS-compliant](https://help.dyn.com/remote-access-api/) server in Ruby supporting IPv4 and IPv6 addresses. It has an integrated user and hostname database in it's configuration file that is used for authentication and authorization. Besides talking the DynDNS protocol it is able to invoke a so-called *updater*, a small Ruby module that takes care of supplying the current hostname => ip mapping to a DNS server.
dyndnsd.rb aims to implement a small [DynDNS-compliant](https://help.dyn.com/remote-access-api/) server in Ruby supporting IPv4 and IPv6 addresses. It has an integrated user and hostname database in its configuration file that is used for authentication and authorization. Besides talking the DynDNS protocol it is able to invoke a so-called *updater*, a small Ruby module that takes care of supplying the current hostname => ip mapping to a DNS server.
There is currently one updater shipped with dyndnsd.rb `command_with_bind_zone` that writes out a zone file in BIND syntax onto the current system and invokes a user-supplied command afterwards that is assumed to trigger the DNS server (not necessarily BIND since it's zone files are read by other DNS servers, too) to reload it's zone configuration.
There are currently two updaters shipped with dyndnsd.rb:
- `zone_transfer_server` that uses [DNS zone transfers via AXFR (RFC5936)](https://tools.ietf.org/html/rfc5936) to allow any secondary nameserver(s) to fetch the zone contents after (optionally) receiving a [DNS NOTIFY (RFC1996)](https://tools.ietf.org/html/rfc1996) request
- `command_with_bind_zone` that writes out a zone file in BIND syntax onto the current system and invokes a user-supplied command afterwards that is assumed to trigger the DNS server (not necessarily BIND since its zone files are read by other DNS servers, too) to reload its zone configuration
Because of the mechanisms used, dyndnsd.rb is known to work only on \*nix systems.
See the [changelog](CHANGELOG.md) before upgrading. The older version 1.x of dyndnsd.rb is still available on [branch dyndnsd-1.x](https://github.com/cmur2/dyndnsd/tree/dyndnsd-1.x).
## General Usage
Install the gem:
@ -25,14 +29,16 @@ Create a configuration file in YAML format somewhere:
```yaml
# listen address and port
host: "0.0.0.0"
port: "80"
# optional: drop priviliges in case you want to but you may need sudo for external commands
port: 80
# optional: drop privileges in case you want to but you may need sudo for external commands
user: "nobody"
group: "nogroup"
# logfile is optional, logs to STDOUT else
# logfile is optional, logs to STDOUT otherwise
logfile: "dyndnsd.log"
# interal database file
# internal database file
db: "db.json"
# enable debug mode?
debug: false
# all hostnames are required to be cool-name.example.org
domain: "example.org"
# configure the updater, here we use command_with_bind_zone, params are updater-specific
@ -60,15 +66,61 @@ Run dyndnsd.rb by:
dyndnsd /path/to/config.yaml
## Using dyndnsd.rb with [NSD](https://www.nlnetlabs.nl/nsd/)
NSD is a nice opensource, authoritative-only, low-memory DNS server that reads BIND-style zone files (and converts them into it's own database) and has a simple config file.
## Using dyndnsd.rb with any nameserver via DNS zone transfers (AXFR)
A feature NSD is lacking is the [Dynamic DNS update](https://tools.ietf.org/html/rfc2136) functionality BIND offers but one can fake it using the following dyndnsd.rb config:
By using [DNS zone transfers via AXFR (RFC5936)](https://tools.ietf.org/html/rfc5936) any secondary nameserver can retrieve the DNS zone contents from dyndnsd.rb and serve them to clients.
To speedup propagation after changes dyndnsd.rb can issue a [DNS NOTIFY (RFC1996)](https://tools.ietf.org/html/rfc1996) to inform the nameserver that the DNS zone contents changed and should be fetched even before the time indicated in the SOA record is up.
Currently dyndnsd.rb does not support any authentication for incoming DNS zone transfer requests so it should be isolated from the internet on these ports.
This approach has several advantages:
- dyndnsd.rb can be used in *hidden primary* fashion isolated from client's DNS traffic and does not need to implement full nameserver features
- any existing, production-grade, caching, geo-replicated nameserver setup can be used to pull DNS zone contents from the *hidden primary* dyndnsd.rb and serve it to clients
- any nameserver(s) and dyndnsd.rb do not need to be located on the same host
Example dyndnsd.rb configuration:
```yaml
host: "0.0.0.0"
port: "8245" # the DynDNS.com alternative HTTP port
port: 8245 # the DynDNS.com alternative HTTP port
db: "/opt/dyndnsd/db.json"
domain: "dyn.example.org"
updater:
name: "zone_transfer_server"
params:
# endpoint(s) to listen for incoming zone transfer (AXFR) requests, default 0.0.0.0@53
server_listens:
- 127.0.0.1@5300
# where to send DNS NOTIFY request(s) to on zone content change
send_notifies:
- '127.0.0.1'
# TTL for all records in the zone (in seconds)
zone_ttl: 300 # 5m
# zone's NS record(s) (at least one)
zone_nameservers:
- "dns.example.org."
# info for zone's SOA record
zone_email_address: "admin.example.org."
# zone's additional A/AAAA records
zone_additional_ips:
- "127.0.0.1"
users:
foo:
password: "secret"
hosts:
- foo.example.org
```
## Using dyndnsd.rb with [NSD](https://www.nlnetlabs.nl/projects/nsd/about/)
NSD is a nice, open source, authoritative-only, low-memory DNS server that reads BIND-style zone files (and converts them into its own database) and has a simple configuration file.
A feature NSD is lacking is the [Dynamic DNS update (RFC2136)](https://tools.ietf.org/html/rfc2136) functionality BIND offers but one can fake it using the following dyndnsd.rb configuration:
```yaml
host: "0.0.0.0"
port: 8245 # the DynDNS.com alternative HTTP port
db: "/opt/dyndnsd/db.json"
domain: "dyn.example.org"
updater:
@ -88,17 +140,20 @@ users:
foo:
password: "secret"
hosts:
- foo.example.org
- foo.example.org
```
Start dyndnsd.rb before NSD to make sure the zone file exists else NSD complains.
## Using dyndnsd.rb with X
Please provide ideas if you are using dyndnsd.rb with other DNS servers :)
## Advanced topics
### Update URL
The update URL you want to tell your clients (humans or scripts ^^) consists of the following
@ -111,10 +166,11 @@ where:
* USER and PASSWORD are needed for HTTP Basic Auth and valid combinations are defined in your config.yaml
* DOMAIN should match what you defined in your config.yaml as domain but may be anything else when using a webserver as proxy
* PORT depends on your (webserver/proxy) settings
* HOSTNAMES is a required list of comma separated FQDNs (they all have to end with your config.yaml domain) the user wants to update
* HOSTNAMES is a required list of comma-separated FQDNs (they all have to end with your config.yaml domain) the user wants to update
* MYIP is optional and the HTTP client's IP address will be used if missing
* MYIP6 is optional but if present also requires presence of MYIP
### IP address determination
The following rules apply:
@ -123,15 +179,20 @@ The following rules apply:
* use any IP address provided via the X-Real-IP header e.g. when used behind HTTP reverse proxy such as nginx, or
* use any IP address used by the connecting HTTP client
If you want to provide an additional IPv6 address as myip6 parameter the myip parameter containing an IPv4 address has to be present, too! No automatism is applied then.
If you want to provide an additional IPv6 address as myip6 parameter, the myip parameter containing an IPv4 address has to be present, too! No automatism is applied then.
### SSL, multiple listen ports
Use a webserver as a proxy to handle SSL and/or multiple listen addresses and ports. DynDNS.com provides HTTP on port 80 and 8245 and HTTPS on port 443.
### Init scripts
The [Debian 6 init.d script](init.d/debian-6-dyndnsd) assumes that dyndnsd.rb is installed into the system ruby (no RVM support) and the config.yaml is at /opt/dyndnsd/config.yaml. Modify to your needs.
### Startup
There is a [Dockerfile](docs/Dockerfile) that can be used to build a Docker image for running dyndnsd.rb.
The [Debian 6 init.d script](docs/debian-6-init-dyndnsd) assumes that dyndnsd.rb is installed into the system ruby (no RVM support) and the config.yaml is at /opt/dyndnsd/config.yaml. Modify to your needs.
### Monitoring
@ -139,7 +200,7 @@ For monitoring dyndnsd.rb uses the [metriks](https://github.com/eric/metriks) fr
```yaml
host: "0.0.0.0"
port: "8245" # the DynDNS.com alternative HTTP port
port: 8245 # the DynDNS.com alternative HTTP port
db: "/opt/dyndnsd/db.json"
domain: "dyn.example.org"
# configure the Graphite backend to be used instead of proctitle
@ -172,14 +233,16 @@ users:
password: "ihavenohosts"
```
### Tracing (experimental)
For tracing dyndnsd.rb is instrumented using the [OpenTracing](http://opentracing.io/) framework and will emit span tracing data for the most important operations happening during the request/response cycle. Using a middleware for Rack allows handling incoming OpenTracing span information properly.
For tracing, dyndnsd.rb is instrumented using the [OpenTracing](http://opentracing.io/) framework and will emit span tracing data for the most important operations happening during the request/response cycle. Using a middleware for Rack allows handling incoming OpenTracing span information properly.
Currently only one OpenTracing-compatible tracer implementation named [CNCF Jaeger](https://github.com/jaegertracing/jaeger) can be configured to use with dyndnsd.rb.
```yaml
host: "0.0.0.0"
port: "8245" # the DynDNS.com alternative HTTP port
port: 8245 # the DynDNS.com alternative HTTP port
db: "/opt/dyndnsd/db.json"
domain: "dyn.example.org"
# enable and configure tracing using the (currently only) tracer jaeger
@ -210,6 +273,7 @@ users:
password: "ihavenohosts"
```
## License
dyndnsd.rb is licensed under the Apache License, Version 2.0. See LICENSE for more information.

View File

@ -1,3 +1,5 @@
# frozen_string_literal: true
require 'bundler/gem_tasks'
require 'rspec/core/rake_task'
require 'rubocop/rake_task'
@ -7,4 +9,16 @@ RSpec::Core::RakeTask.new(:spec)
RuboCop::RakeTask.new
Bundler::Audit::Task.new
desc 'Should be run by developer once to prepare initial solargraph usage (fill caches etc.)'
task :'solargraph:init' do
sh 'solargraph download-core'
end
desc 'Run experimental solargraph type checker'
task :'solargraph:tc' do
sh 'solargraph typecheck'
end
task default: [:rubocop, :spec, 'bundle:audit']
task travis: [:default, :'solargraph:tc']

View File

@ -1,4 +0,0 @@
require 'dyndnsd'
Dyndnsd::Daemon.run!

15
docs/Dockerfile Normal file
View File

@ -0,0 +1,15 @@
FROM alpine:3.12
EXPOSE 5353 8080
ENV VERSION=3.0.0
RUN apk --no-cache add openssl ca-certificates && \
apk --no-cache add ruby ruby-etc ruby-io-console ruby-json ruby-webrick && \
apk --no-cache add --virtual .build-deps ruby-dev build-base tzdata && \
gem install --no-document dyndnsd -v ${VERSION} && \
# set timezone to Berlin
cp /usr/share/zoneinfo/Europe/Berlin /etc/localtime && \
apk del .build-deps
ENTRYPOINT ["dyndnsd", "/etc/dyndnsd/config.yml"]

0
init.d/debian-6-dyndnsd → docs/debian-6-init-dyndnsd Normal file → Executable file
View File

View File

@ -1,7 +1,6 @@
# frozen_string_literal: true
$LOAD_PATH.push File.expand_path('lib', __dir__)
require 'dyndnsd/version'
require_relative 'lib/dyndnsd/version'
Gem::Specification.new do |s|
s.name = 'dyndnsd'
@ -9,28 +8,38 @@ Gem::Specification.new do |s|
s.summary = 'dyndnsd.rb'
s.description = 'A small, lightweight and extensible DynDNS server written with Ruby and Rack.'
s.author = 'Christian Nicolai'
s.email = 'chrnicolai@gmail.com'
s.homepage = 'https://github.com/cmur2/dyndnsd'
s.license = 'Apache-2.0'
s.metadata = {
'bug_tracker_uri' => "#{s.homepage}/issues",
'changelog_uri' => "#{s.homepage}/blob/master/CHANGELOG.md",
'source_code_uri' => s.homepage
}
s.files = `git ls-files`.split($INPUT_RECORD_SEPARATOR)
s.test_files = s.files.grep(%r{^(test|spec|features)/})
s.files = `git ls-files -z`.split("\x0").select do |f|
f.match(%r{^(init.d|lib)/})
end
s.require_paths = ['lib']
s.bindir = 'exe'
s.executables = ['dyndnsd']
s.extra_rdoc_files = Dir['README.md', 'CHANGELOG.md', 'LICENSE']
s.required_ruby_version = '>= 2.3'
s.required_ruby_version = '>= 2.5'
s.add_runtime_dependency 'rack', '~> 2.0'
s.add_runtime_dependency 'json'
s.add_runtime_dependency 'async-dns', '~> 1.2.0'
s.add_runtime_dependency 'jaeger-client', '~> 0.10.0'
s.add_runtime_dependency 'metriks'
s.add_runtime_dependency 'opentracing', '~> 0.5.0'
s.add_runtime_dependency 'rack', '~> 2.0'
s.add_runtime_dependency 'rack-tracer', '~> 0.9.0'
s.add_runtime_dependency 'jaeger-client', '~> 1.0.0'
s.add_development_dependency 'bundler'
s.add_development_dependency 'bundler-audit', '~> 0.7.0'
s.add_development_dependency 'rack-test'
s.add_development_dependency 'rake'
s.add_development_dependency 'rspec'
s.add_development_dependency 'rack-test'
s.add_development_dependency 'rubocop', '~> 0.74.0'
s.add_development_dependency 'bundler-audit'
s.add_development_dependency 'rubocop', '~> 0.89.0'
s.add_development_dependency 'solargraph'
end

6
exe/dyndnsd Executable file
View File

@ -0,0 +1,6 @@
#!/usr/bin/env ruby
# frozen_string_literal: true
require 'dyndnsd'
Dyndnsd::Daemon.run!

66
lib/dyndnsd.rb Executable file → Normal file
View File

@ -1,4 +1,4 @@
#!/usr/bin/env ruby
# frozen_string_literal: true
require 'etc'
require 'logger'
@ -13,6 +13,7 @@ require 'rack/tracer'
require 'dyndnsd/generator/bind'
require 'dyndnsd/updater/command_with_bind_zone'
require 'dyndnsd/updater/zone_transfer_server'
require 'dyndnsd/responder/dyndns_style'
require 'dyndnsd/responder/rest_style'
require 'dyndnsd/database'
@ -21,21 +22,32 @@ require 'dyndnsd/textfile_reporter'
require 'dyndnsd/version'
module Dyndnsd
# @return [Logger]
def self.logger
@logger
end
# @param logger [Logger]
# @return [Logger]
def self.logger=(logger)
@logger = logger
end
class LogFormatter
# @param lvl [Object]
# @param _time [DateTime]
# @param _progname [String]
# @param msg [Object]
# @return [String]
def call(lvl, _time, _progname, msg)
format("[%s] %-5s %s\n", Time.now.strftime('%Y-%m-%d %H:%M:%S'), lvl, msg.to_s)
end
end
class Daemon
# @param config [Hash{String => Object}]
# @param db [Dyndnsd::Database]
# @param updater [#update]
def initialize(config, db, updater)
@users = config['users']
@domain = config['domain']
@ -45,12 +57,15 @@ module Dyndnsd
@db.load
@db['serial'] ||= 1
@db['hosts'] ||= {}
@updater.update(@db)
if @db.changed?
@db.save
@updater.update(@db)
end
end
# @param username [String]
# @param password [String]
# @return [Boolean]
def authorized?(username, password)
Helper.span('check_authorized') do |span|
span.set_tag('dyndnsd.user', username)
@ -64,6 +79,8 @@ module Dyndnsd
end
end
# @param env [Hash{String => String}]
# @return [Array{Integer,Hash{String => String},Array{String}}]
def call(env)
return [422, {'X-DynDNS-Response' => 'method_forbidden'}, []] if env['REQUEST_METHOD'] != 'GET'
return [422, {'X-DynDNS-Response' => 'not_found'}, []] if env['PATH_INFO'] != '/nic/update'
@ -71,6 +88,7 @@ module Dyndnsd
handle_dyndns_request(env)
end
# @return [void]
def self.run!
if ARGV.length != 1
puts 'Usage: dyndnsd config_file'
@ -95,8 +113,14 @@ module Dyndnsd
# drop priviliges as soon as possible
# NOTE: first change group than user
Process::Sys.setgid(Etc.getgrnam(config['group']).gid) if config['group']
Process::Sys.setuid(Etc.getpwnam(config['user']).uid) if config['user']
if config['group']
group = Etc.getgrnam(config['group'])
Process::Sys.setgid(group.gid) if group
end
if config['user']
user = Etc.getpwnam(config['user'])
Process::Sys.setuid(user.uid) if user
end
setup_traps
@ -109,6 +133,8 @@ module Dyndnsd
private
# @param params [Hash{String => String}]
# @return [Array{String}]
def extract_v4_and_v6_address(params)
return [] if !(params['myip'])
begin
@ -120,6 +146,9 @@ module Dyndnsd
end
end
# @param env [Hash{String => String}]
# @param params [Hash{String => String}]
# @return [Array{String}]
def extract_myips(env, params)
# require presence of myip parameter as valid IPAddr (v4) and valid myip6
return extract_v4_and_v6_address(params) if params.key?('myip6')
@ -134,6 +163,9 @@ module Dyndnsd
[env['REMOTE_ADDR']]
end
# @param hostnames [String]
# @param myips [Array{String}]
# @return [Array{Symbol}]
def process_changes(hostnames, myips)
changes = []
Helper.span('process_changes') do |span|
@ -158,14 +190,17 @@ module Dyndnsd
changes
end
# @return [void]
def update_db
@db['serial'] += 1
Dyndnsd.logger.info "Committing update ##{@db['serial']}"
@db.save
@updater.update(@db)
@db.save
Metriks.meter('updates.committed').mark
end
# @param env [Hash{String => String}]
# @return [Array{Integer,Hash{String => String},Array{String}}]
def handle_dyndns_request(env)
params = Rack::Utils.parse_query(env['QUERY_STRING'])
@ -204,28 +239,32 @@ module Dyndnsd
# SETUP
# @param config [Hash{String => Object}]
# @return [void]
private_class_method def self.setup_logger(config)
if config['logfile']
Dyndnsd.logger = Logger.new(config['logfile'])
else
Dyndnsd.logger = Logger.new(STDOUT)
Dyndnsd.logger = Logger.new($stdout)
end
Dyndnsd.logger.progname = 'dyndnsd'
Dyndnsd.logger.formatter = LogFormatter.new
Dyndnsd.logger.level = config['debug'] ? Logger::DEBUG : Logger::INFO
end
# @return [void]
private_class_method def self.setup_traps
Signal.trap('INT') do
Dyndnsd.logger.info 'Quitting...'
Rack::Handler::WEBrick.shutdown
end
Signal.trap('TERM') do
Dyndnsd.logger.info 'Quitting...'
Rack::Handler::WEBrick.shutdown
end
end
# @param config [Hash{String => Object}]
# @return [void]
private_class_method def self.setup_monitoring(config)
# configure metriks
if config['graphite']
@ -253,6 +292,8 @@ module Dyndnsd
end
end
# @param config [Hash{String => Object}]
# @return [void]
private_class_method def self.setup_tracing(config)
# configure OpenTracing
if config.dig('tracing', 'jaeger')
@ -267,10 +308,17 @@ module Dyndnsd
end
end
# @param config [Hash{String => Object}]
# @return [void]
private_class_method def self.setup_rack(config)
# configure daemon
db = Database.new(config['db'])
updater = Updater::CommandWithBindZone.new(config['domain'], config['updater']['params']) if config['updater']['name'] == 'command_with_bind_zone'
case config.dig('updater', 'name')
when 'command_with_bind_zone'
updater = Updater::CommandWithBindZone.new(config['domain'], config.dig('updater', 'params'))
when 'zone_transfer_server'
updater = Updater::ZoneTransferServer.new(config['domain'], config.dig('updater', 'params'))
end
daemon = Daemon.new(config, db, updater)
# configure rack

View File

@ -1,3 +1,4 @@
# frozen_string_literal: true
require 'forwardable'
@ -7,19 +8,22 @@ module Dyndnsd
def_delegators :@db, :[], :[]=, :each, :has_key?
# @param db_file [String]
def initialize(db_file)
@db_file = db_file
end
# @return [void]
def load
if File.file?(@db_file)
@db = JSON.parse(File.open(@db_file, 'r', &:read))
@db = JSON.parse(File.read(@db_file, mode: 'r'))
else
@db = {}
end
@db_hash = @db.hash
end
# @return [void]
def save
Helper.span('database_save') do |_span|
File.open(@db_file, 'w') { |f| JSON.dump(@db, f) }
@ -27,6 +31,7 @@ module Dyndnsd
end
end
# @return [Boolean]
def changed?
@db_hash != @db.hash
end

View File

@ -1,15 +1,20 @@
# frozen_string_literal: true
module Dyndnsd
module Generator
class Bind
def initialize(domain, config)
# @param domain [String]
# @param updater_params [Hash{String => Object}]
def initialize(domain, updater_params)
@domain = domain
@ttl = config['ttl']
@dns = config['dns']
@email_addr = config['email_addr']
@additional_zone_content = config['additional_zone_content']
@ttl = updater_params['ttl']
@dns = updater_params['dns']
@email_addr = updater_params['email_addr']
@additional_zone_content = updater_params['additional_zone_content']
end
# @param db [Dyndnsd::Database]
# @return [String]
def generate(db)
out = []
out << "$TTL #{@ttl}"
@ -22,7 +27,7 @@ module Dyndnsd
ips.each do |ip|
ip = IPAddr.new(ip).native
type = ip.ipv6? ? 'AAAA' : 'A'
name = hostname.chomp('.' + @domain)
name = hostname.chomp(".#{@domain}")
out << "#{name} IN #{type} #{ip}"
end
end

View File

@ -1,8 +1,12 @@
# frozen_string_literal: true
require 'ipaddr'
module Dyndnsd
class Helper
# @param hostname [String]
# @param domain [String]
# @return [Boolean]
def self.fqdn_valid?(hostname, domain)
return false if hostname.length < domain.length + 2
return false if !hostname.end_with?(domain)
@ -11,6 +15,8 @@ module Dyndnsd
true
end
# @param ip [String]
# @return [Boolean]
def self.ip_valid?(ip)
IPAddr.new(ip)
true
@ -18,15 +24,26 @@ module Dyndnsd
false
end
# @param username [String]
# @param password [String]
# @param users [Hash]
# @return [Boolean]
def self.user_allowed?(username, password, users)
(users.key? username) && (users[username]['password'] == password)
end
# @param hostname [String]
# @param myips [Array]
# @param hosts [Hash]
# @return [Boolean]
def self.changed?(hostname, myips, hosts)
# myips order is always deterministic
((!hosts.include? hostname) || (hosts[hostname] != myips)) && !myips.empty?
end
# @param operation [String]
# @param block [Proc]
# @return [void]
def self.span(operation, &block)
scope = OpenTracing.start_active_span(operation)
span = scope.span
@ -41,7 +58,7 @@ module Dyndnsd
'error.kind': e.class.to_s,
'error.object': e,
message: e.message,
stack: e.backtrace.join("\n")
stack: e.backtrace&.join("\n") || ''
)
raise
ensure

View File

@ -1,11 +1,15 @@
# frozen_string_literal: true
module Dyndnsd
module Responder
class DynDNSStyle
# @param app [#call]
def initialize(app)
@app = app
end
# @param env [Hash{String => String}]
# @return [Array{Integer,Hash{String => String},Array{String}}]
def call(env)
@app.call(env).tap do |status_code, headers, body|
if headers.key?('X-DynDNS-Response')
@ -18,26 +22,40 @@ module Dyndnsd
private
# @param status_code [Integer]
# @param headers [Hash{String => String}]
# @param body [Array{String}]
# @return [Array{Integer,Hash{String => String},Array{String}}]
def decorate_dyndnsd_response(status_code, headers, body)
if status_code == 200
case status_code
when 200
[200, {'Content-Type' => 'text/plain'}, [get_success_body(body[0], body[1])]]
elsif status_code == 422
when 422
error_response_map[headers['X-DynDNS-Response']]
end
end
# @param status_code [Integer]
# @param headers [Hash{String => String}]
# @param _body [Array{String}]
# @return [Array{Integer,Hash{String => String},Array{String}}]
def decorate_other_response(status_code, headers, _body)
if status_code == 400
case status_code
when 400
[status_code, headers, ['Bad Request']]
elsif status_code == 401
when 401
[status_code, headers, ['badauth']]
end
end
# @param changes [Array{Symbol}]
# @param myips [Array{String}]
# @return [String]
def get_success_body(changes, myips)
changes.map { |change| "#{change} #{myips.join(' ')}" }.join("\n")
end
# @return [Hash{String => Object}]
def error_response_map
{
# general http errors

View File

@ -1,11 +1,15 @@
# frozen_string_literal: true
module Dyndnsd
module Responder
class RestStyle
# @param app [#call]
def initialize(app)
@app = app
end
# @param env [Hash{String => String}]
# @return [Array{Integer,Hash{String => String},Array{String}}]
def call(env)
@app.call(env).tap do |status_code, headers, body|
if headers.key?('X-DynDNS-Response')
@ -18,26 +22,40 @@ module Dyndnsd
private
# @param status_code [Integer]
# @param headers [Hash{String => String}]
# @param body [Array{String}]
# @return [Array{Integer,Hash{String => String},Array{String}}]
def decorate_dyndnsd_response(status_code, headers, body)
if status_code == 200
case status_code
when 200
[200, {'Content-Type' => 'text/plain'}, [get_success_body(body[0], body[1])]]
elsif status_code == 422
when 422
error_response_map[headers['X-DynDNS-Response']]
end
end
# @param status_code [Integer]
# @param headers [Hash{String => String}]
# @param _body [Array{String}]
# @return [Array{Integer,Hash{String => String},Array{String}}]
def decorate_other_response(status_code, headers, _body)
if status_code == 400
case status_code
when 400
[status_code, headers, ['Bad Request']]
elsif status_code == 401
when 401
[status_code, headers, ['Unauthorized']]
end
end
# @param changes [Array{Symbol}]
# @param myips [Array{String}]
# @return [String]
def get_success_body(changes, myips)
changes.map { |change| change == :good ? "Changed to #{myips.join(' ')}" : "No change needed for #{myips.join(' ')}" }.join("\n")
end
# @return [Hash{String => Object}]
def error_response_map
{
# general http errors

View File

@ -1,3 +1,4 @@
# frozen_string_literal: true
# Adapted from https://github.com/eric/metriks-graphite/blob/master/lib/metriks/reporter/graphite.rb
@ -5,8 +6,11 @@ require 'metriks'
module Dyndnsd
class TextfileReporter
# @return [String]
attr_reader :file
# @param file [String]
# @param options [Hash{Symbol => Object}]
def initialize(file, options = {})
@file = file
@ -17,32 +21,34 @@ module Dyndnsd
@on_error = options[:on_error] || proc { |ex| }
end
# @return [void]
def start
@thread ||= Thread.new do
loop do
sleep @interval
Thread.new do
begin
write
rescue StandardError => e
@on_error[e] rescue nil
end
write
rescue StandardError => e
@on_error[e] rescue nil
end
end
end
end
# @return [void]
def stop
@thread&.kill
@thread = nil
end
# @return [void]
def restart
stop
start
end
# @return [void]
def write
File.open(@file, 'w') do |f|
@registry.each do |name, metric|
@ -85,6 +91,12 @@ module Dyndnsd
end
end
# @param file [String]
# @param base_name [String]
# @param metric [Object]
# @param keys [Array{Symbol}]
# @param snapshot_keys [Array{Symbol}]
# @return [void]
def write_metric(file, base_name, metric, keys, snapshot_keys = [])
time = Time.now.to_i

View File

@ -1,26 +1,34 @@
# frozen_string_literal: true
module Dyndnsd
module Updater
class CommandWithBindZone
def initialize(domain, config)
@zone_file = config['zone_file']
@command = config['command']
@generator = Generator::Bind.new(domain, config)
# @param domain [String]
# @param updater_params [Hash{String => Object}]
def initialize(domain, updater_params)
@zone_file = updater_params['zone_file']
@command = updater_params['command']
@generator = Generator::Bind.new(domain, updater_params)
end
def update(zone)
# @param db [Dyndnsd::Database]
# @return [void]
def update(db)
# do not regenerate zone file (assumed to be persistent) if DB did not change
return if !db.changed?
Helper.span('updater_update') do |span|
span.set_tag('dyndnsd.updater.name', self.class.name.split('::').last)
span.set_tag('dyndnsd.updater.name', self.class.name&.split('::')&.last || 'None')
# write zone file in bind syntax
File.open(@zone_file, 'w') { |f| f.write(@generator.generate(zone)) }
File.open(@zone_file, 'w') { |f| f.write(@generator.generate(db)) }
# call user-defined command
pid = fork do
exec @command
end
# detach so children don't become zombies
Process.detach(pid)
Process.detach(pid) if pid
end
end
end

View File

@ -0,0 +1,158 @@
# frozen_string_literal: true
require 'resolv'
require 'securerandom'
require 'async/dns'
module Dyndnsd
module Updater
class ZoneTransferServer
DEFAULT_SERVER_LISTENS = ['0.0.0.0@53'].freeze
# @param domain [String]
# @param updater_params [Hash{String => Object}]
def initialize(domain, updater_params)
@domain = domain
@server_listens = self.class.parse_endpoints(updater_params['server_listens'] || DEFAULT_SERVER_LISTENS)
@notify_targets = (updater_params['send_notifies'] || []).map { |e| self.class.parse_endpoints([e]) }
@zone_rr_ttl = updater_params['zone_ttl']
@zone_nameservers = updater_params['zone_nameservers'].map { |n| Resolv::DNS::Name.create(n) }
@zone_email_address = Resolv::DNS::Name.create(updater_params['zone_email_address'])
@zone_additional_ips = updater_params['zone_additional_ips'] || []
@server = ZoneTransferServerHelper.new(@server_listens, @domain)
# run Async::DNS server in background thread
Thread.new do
@server.run
end
end
# @param db [Dyndnsd::Database]
# @return [void]
def update(db)
Helper.span('updater_update') do |span|
span.set_tag('dyndnsd.updater.name', self.class.name&.split('::')&.last || 'None')
soa_rr = Resolv::DNS::Resource::IN::SOA.new(
@zone_nameservers[0], @zone_email_address,
db['serial'],
10_800, # 3h
300, # 5m
604_800, # 1w
3_600 # 1h
)
default_options = {ttl: @zone_rr_ttl}
# array containing all resource records for an AXFR request in the right order
rrs = []
# AXFR responses need to start with zone's SOA RR
rrs << [soa_rr, default_options]
# return RRs for all of the zone's nameservers
@zone_nameservers.each do |ns|
rrs << [Resolv::DNS::Resource::IN::NS.new(ns), default_options]
end
# return A/AAAA RRs for all additional IPv4s/IPv6s for the domain itself
@zone_additional_ips.each do |ip|
rrs << [create_addr_rr_for_ip(ip), default_options]
end
# return A/AAAA RRs for the dyndns hostnames
db['hosts'].each do |hostname, ips|
ips.each do |ip|
rrs << [create_addr_rr_for_ip(ip), default_options.merge({name: hostname})]
end
end
# AXFR responses need to end with zone's SOA RR again
rrs << [soa_rr, default_options]
# point Async::DNS server thread's variable to this new RR array
@server.axfr_rrs = rrs
# only send DNS NOTIFY if there really was a change
if db.changed?
send_dns_notify
end
end
end
# converts into suitable parameter form for Async::DNS::Resolver or Async::DNS::Server
#
# @param endpoint_list [Array{String}]
# @return [Array{Array{Object}}]
def self.parse_endpoints(endpoint_list)
endpoint_list.map { |addr_string| addr_string.split('@') }
.map { |addr_parts| [addr_parts[0], addr_parts[1].to_i || 53] }
.map { |addr| [:tcp, :udp].map { |type| [type] + addr } }
.flatten(1)
end
private
# creates correct Resolv::DNS::Resource object for IP address type
#
# @param ip_string [String]
# @return [Resolv::DNS::Resource::IN::A,Resolv::DNS::Resource::IN::AAAA]
def create_addr_rr_for_ip(ip_string)
ip = IPAddr.new(ip_string).native
if ip.ipv6?
Resolv::DNS::Resource::IN::AAAA.new(ip.to_s)
else
Resolv::DNS::Resource::IN::A.new(ip.to_s)
end
end
# https://tools.ietf.org/html/rfc1996
#
# @return [void]
def send_dns_notify
Async::Reactor.run do
@notify_targets.each do |notify_target|
target = Async::DNS::Resolver.new(notify_target)
# assemble DNS NOTIFY message
request = Resolv::DNS::Message.new(SecureRandom.random_number(2**16))
request.opcode = Resolv::DNS::OpCode::Notify
request.add_question("#{@domain}.", Resolv::DNS::Resource::IN::SOA)
_response = target.dispatch_request(request)
end
end
end
end
class ZoneTransferServerHelper < Async::DNS::Server
attr_accessor :axfr_rrs
def initialize(endpoints, domain)
super(endpoints, logger: Dyndnsd.logger)
@domain = domain
end
# @param name [String]
# @param resource_class [Resolv::DNS::Resource]
# @param transaction [Async::DNS::Transaction]
# @return [void]
def process(name, resource_class, transaction)
if name != @domain || resource_class != Resolv::DNS::Resource::Generic::Type252_Class1
transaction.fail!(:NXDomain)
return
end
# https://tools.ietf.org/html/rfc5936
transaction.append_question!
@axfr_rrs.each do |rr|
transaction.add([rr[0]], rr[1])
end
end
end
end
end

View File

@ -1,4 +1,5 @@
# frozen_string_literal: true
module Dyndnsd
VERSION = '2.0.0'.freeze
VERSION = '3.0.0'
end

View File

@ -1,10 +1,12 @@
require 'spec_helper'
# frozen_string_literal: true
require_relative 'spec_helper'
describe Dyndnsd::Daemon do
include Rack::Test::Methods
def app
Dyndnsd.logger = Logger.new(STDOUT)
Dyndnsd.logger = Logger.new($stdout)
Dyndnsd.logger.level = Logger::UNKNOWN
config = {

View File

@ -1,8 +1,10 @@
# frozen_string_literal: true
require 'rubygems'
require 'bundler/setup'
require 'rack/test'
require 'dyndnsd'
require 'support/dummy_database'
require 'support/dummy_updater'
require_relative 'support/dummy_database'
require_relative 'support/dummy_updater'

View File

@ -1,3 +1,4 @@
# frozen_string_literal: true
require 'forwardable'

View File

@ -1,3 +1,4 @@
# frozen_string_literal: true
module Dyndnsd
module Updater