1
0
mirror of https://github.com/cmur2/dyndnsd.git synced 2024-12-22 20:54:24 +01:00
dyndnsd/lib/dyndnsd.rb

295 lines
8.6 KiB
Ruby
Raw Normal View History

2013-04-27 14:07:14 +02:00
#!/usr/bin/env ruby
2013-04-30 23:19:08 +02:00
require 'etc'
2013-04-27 14:07:14 +02:00
require 'logger'
require 'ipaddr'
require 'json'
require 'yaml'
require 'rack'
require 'metriks'
require 'metriks/reporter/graphite'
require 'opentracing'
require 'rack/tracer'
require 'spanmanager'
2013-04-27 14:07:14 +02:00
require 'dyndnsd/generator/bind'
require 'dyndnsd/updater/command_with_bind_zone'
2013-04-27 14:30:41 +02:00
require 'dyndnsd/responder/dyndns_style'
2013-04-27 14:07:14 +02:00
require 'dyndnsd/responder/rest_style'
require 'dyndnsd/database'
2018-02-03 21:40:44 +01:00
require 'dyndnsd/helper'
require 'dyndnsd/textfile_reporter'
2013-04-27 14:07:14 +02:00
require 'dyndnsd/version'
module Dyndnsd
def self.logger
@logger
end
def self.logger=(logger)
@logger = logger
end
class LogFormatter
2018-02-23 12:54:43 +01:00
def call(lvl, _time, _progname, msg)
format("[%s] %-5s %s\n", Time.now.strftime('%Y-%m-%d %H:%M:%S'), lvl, msg.to_s)
2013-04-27 14:07:14 +02:00
end
end
class Daemon
def initialize(config, db, updater)
2013-04-27 14:07:14 +02:00
@users = config['users']
2013-04-27 14:59:25 +02:00
@domain = config['domain']
2013-04-27 14:07:14 +02:00
@db = db
@updater = updater
@db.load
@db['serial'] ||= 1
@db['hosts'] ||= {}
2018-02-23 12:54:43 +01:00
if @db.changed?
@db.save
@updater.update(@db)
end
2013-04-27 14:59:25 +02:00
end
2018-02-23 12:54:43 +01:00
def authorized?(username, password)
Helper.span('check_authorized') do |span|
span.set_tag('dyndnsd.user', username)
allow = Helper.user_allowed?(username, password, @users)
if !allow
Dyndnsd.logger.warn "Login failed for #{username}"
Metriks.meter('requests.auth_failed').mark
end
allow
end
end
2013-04-27 14:07:14 +02:00
def call(env)
2018-02-23 12:54:43 +01:00
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'
handle_dyndns_request(env)
2013-04-27 14:07:14 +02:00
end
def self.run!
if ARGV.length != 1
2018-02-23 12:54:43 +01:00
puts 'Usage: dyndnsd config_file'
2013-04-27 14:07:14 +02:00
exit 1
end
config_file = ARGV[0]
2018-02-23 12:54:43 +01:00
if !File.file?(config_file)
puts 'Config file not found!'
2013-04-27 14:07:14 +02:00
exit 1
end
2013-04-27 22:02:54 +02:00
puts "DynDNSd version #{Dyndnsd::VERSION}"
puts "Using config file #{config_file}"
2013-04-27 14:07:14 +02:00
2018-02-23 12:54:43 +01:00
config = YAML.safe_load(File.open(config_file, 'r', &:read))
setup_logger(config)
2013-04-27 22:02:54 +02:00
2018-02-23 12:54:43 +01:00
Dyndnsd.logger.info 'Starting...'
# drop priviliges as soon as possible
# NOTE: first change group than user
2013-04-30 23:19:08 +02:00
Process::Sys.setgid(Etc.getgrnam(config['group']).gid) if config['group']
Process::Sys.setuid(Etc.getpwnam(config['user']).uid) if config['user']
2013-04-27 14:07:14 +02:00
2018-02-23 12:54:43 +01:00
setup_traps
setup_monitoring(config)
setup_tracing(config)
setup_rack(config)
2013-04-27 14:07:14 +02:00
end
private
2018-02-23 12:54:43 +01:00
def extract_v4_and_v6_address(params)
return [] if !(params['myip'])
begin
2018-02-23 12:54:43 +01:00
IPAddr.new(params['myip'], Socket::AF_INET)
IPAddr.new(params['myip6'], Socket::AF_INET6)
[params['myip'], params['myip6']]
rescue ArgumentError
[]
end
end
def extract_myips(env, params)
# require presence of myip parameter as valid IPAddr (v4) and valid myip6
2018-02-23 12:54:43 +01:00
return extract_v4_and_v6_address(params) if params.key?('myip6')
# check whether myip parameter has valid IPAddr
2018-02-23 12:54:43 +01:00
return [params['myip']] if params.key?('myip') && Helper.ip_valid?(params['myip'])
# check whether X-Real-IP header has valid IPAddr
2018-02-23 12:54:43 +01:00
return [env['HTTP_X_REAL_IP']] if env.key?('HTTP_X_REAL_IP') && Helper.ip_valid?(env['HTTP_X_REAL_IP'])
# fallback value, always present
2018-02-23 12:54:43 +01:00
[env['REMOTE_ADDR']]
end
def process_changes(hostnames, myips)
changes = []
Helper.span('process_changes') do |span|
span.set_tag('dyndnsd.hostnames', hostnames.join(','))
hostnames.each do |hostname|
# myips order is always deterministic
if myips.empty? && @db['hosts'].include?(hostname)
@db['hosts'].delete(hostname)
changes << :good
Metriks.meter('requests.good').mark
elsif Helper.changed?(hostname, myips, @db['hosts'])
@db['hosts'][hostname] = myips
changes << :good
Metriks.meter('requests.good').mark
else
changes << :nochg
Metriks.meter('requests.nochg').mark
end
end
end
changes
end
2018-02-23 12:54:43 +01:00
def update_db
@db['serial'] += 1
Dyndnsd.logger.info "Committing update ##{@db['serial']}"
@db.save
@updater.update(@db)
Metriks.meter('updates.committed').mark
end
def handle_dyndns_request(env)
2018-02-23 12:54:43 +01:00
params = Rack::Utils.parse_query(env['QUERY_STRING'])
# require hostname parameter
2018-02-23 12:54:43 +01:00
return [422, {'X-DynDNS-Response' => 'hostname_missing'}, []] if !(params['hostname'])
2018-02-23 12:54:43 +01:00
hostnames = params['hostname'].split(',')
# check for invalid hostnames
invalid_hostnames = hostnames.select { |h| !Helper.fqdn_valid?(h, @domain) }
return [422, {'X-DynDNS-Response' => 'hostname_malformed'}, []] if invalid_hostnames.any?
2018-02-23 12:54:43 +01:00
user = env['REMOTE_USER']
# check for hostnames that the user does not own
forbidden_hostnames = hostnames - @users[user]['hosts']
return [422, {'X-DynDNS-Response' => 'host_forbidden'}, []] if forbidden_hostnames.any?
if params['offline'] == 'YES'
myips = []
else
myips = extract_myips(env, params)
# require at least one IP to update
return [422, {'X-DynDNS-Response' => 'host_forbidden'}, []] if myips.empty?
end
Metriks.meter('requests.valid').mark
Dyndnsd.logger.info "Request to update #{hostnames} to #{myips} for user #{user}"
changes = process_changes(hostnames, myips)
update_db if @db.changed?
[200, {'X-DynDNS-Response' => 'success'}, [changes, myips]]
end
# SETUP
2018-02-23 12:54:43 +01:00
private_class_method def self.setup_logger(config)
if config['logfile']
Dyndnsd.logger = Logger.new(config['logfile'])
else
Dyndnsd.logger = Logger.new(STDOUT)
end
2018-02-23 12:54:43 +01:00
Dyndnsd.logger.progname = 'dyndnsd'
Dyndnsd.logger.formatter = LogFormatter.new
end
2018-02-23 12:54:43 +01:00
private_class_method def self.setup_traps
Signal.trap('INT') do
2018-02-23 12:54:43 +01:00
Dyndnsd.logger.info 'Quitting...'
Rack::Handler::WEBrick.shutdown
end
Signal.trap('TERM') do
2018-02-23 12:54:43 +01:00
Dyndnsd.logger.info 'Quitting...'
Rack::Handler::WEBrick.shutdown
end
end
2018-02-23 12:54:43 +01:00
private_class_method def self.setup_monitoring(config)
# configure metriks
if config['graphite']
host = config['graphite']['host'] || 'localhost'
port = config['graphite']['port'] || 2003
options = {}
options[:prefix] = config['graphite']['prefix'] if config['graphite']['prefix']
reporter = Metriks::Reporter::Graphite.new(host, port, options)
reporter.start
elsif config['textfile']
file = config['textfile']['file'] || '/tmp/dyndnsd-metrics.prom'
options = {}
options[:prefix] = config['textfile']['prefix'] if config['textfile']['prefix']
reporter = Dyndnsd::TextfileReporter.new(file, options)
reporter.start
else
reporter = Metriks::Reporter::ProcTitle.new
reporter.add 'good', 'sec' do
Metriks.meter('requests.good').mean_rate
end
reporter.add 'nochg', 'sec' do
Metriks.meter('requests.nochg').mean_rate
end
reporter.start
end
end
private_class_method def self.setup_tracing(config)
# configure OpenTracing
if config.dig('tracing', 'jaeger')
require 'jaeger/client'
host = config['tracing']['jaeger']['host'] || '127.0.0.1'
port = config['tracing']['jaeger']['port'] || 6831
service_name = config['tracing']['jaeger']['service_name'] || 'dyndnsd'
OpenTracing.global_tracer = Jaeger::Client.build(
host: host, port: port, service_name: service_name, flush_interval: 1
)
end
# always use SpanManager
OpenTracing.global_tracer = SpanManager::Tracer.new(OpenTracing.global_tracer)
end
2018-02-23 12:54:43 +01:00
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'
daemon = Daemon.new(config, db, updater)
# configure rack
2018-02-23 12:54:43 +01:00
app = Rack::Auth::Basic.new(daemon, 'DynDNS', &daemon.method(:authorized?))
if config['responder'] == 'RestStyle'
app = Responder::RestStyle.new(app)
else
app = Responder::DynDNSStyle.new(app)
end
trust_incoming_span = config.dig('tracing', 'trust_incoming_span') || false
app = Rack::Tracer.new(app, trust_incoming_span: trust_incoming_span)
2018-02-23 12:54:43 +01:00
Rack::Handler::WEBrick.run app, Host: config['host'], Port: config['port']
end
2013-04-27 14:07:14 +02:00
end
end