mirror of
https://github.com/cmur2/dyndnsd.git
synced 2025-06-26 02:30:22 +02:00
gem: fix applicable rubocop todos
This commit is contained in:
81
lib/dyndnsd.rb
Normal file → Executable file
81
lib/dyndnsd.rb
Normal file → Executable file
@ -27,8 +27,8 @@ module Dyndnsd
|
||||
end
|
||||
|
||||
class LogFormatter
|
||||
def call(lvl, time, progname, msg)
|
||||
"[%s] %-5s %s\n" % [Time.now.strftime('%Y-%m-%d %H:%M:%S'), lvl, msg.to_s]
|
||||
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
|
||||
|
||||
@ -42,12 +42,15 @@ module Dyndnsd
|
||||
@db.load
|
||||
@db['serial'] ||= 1
|
||||
@db['hosts'] ||= {}
|
||||
(@db.save; @updater.update(@db)) if @db.changed?
|
||||
if @db.changed?
|
||||
@db.save
|
||||
@updater.update(@db)
|
||||
end
|
||||
end
|
||||
|
||||
def is_authorized?(username, password)
|
||||
allow = ((@users.has_key? username) and (@users[username]['password'] == password))
|
||||
if not allow
|
||||
def authorized?(username, password)
|
||||
allow = ((@users.key? username) && (@users[username]['password'] == password))
|
||||
if !allow
|
||||
Dyndnsd.logger.warn "Login failed for #{username}"
|
||||
Metriks.meter('requests.auth_failed').mark
|
||||
end
|
||||
@ -55,40 +58,40 @@ module Dyndnsd
|
||||
end
|
||||
|
||||
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"
|
||||
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)
|
||||
end
|
||||
|
||||
def self.run!
|
||||
if ARGV.length != 1
|
||||
puts "Usage: dyndnsd config_file"
|
||||
puts 'Usage: dyndnsd config_file'
|
||||
exit 1
|
||||
end
|
||||
|
||||
config_file = ARGV[0]
|
||||
|
||||
if not File.file?(config_file)
|
||||
puts "Config file not found!"
|
||||
if !File.file?(config_file)
|
||||
puts 'Config file not found!'
|
||||
exit 1
|
||||
end
|
||||
|
||||
puts "DynDNSd version #{Dyndnsd::VERSION}"
|
||||
puts "Using config file #{config_file}"
|
||||
|
||||
config = YAML::load(File.open(config_file, 'r') { |f| f.read })
|
||||
config = YAML.safe_load(File.open(config_file, 'r', &:read))
|
||||
|
||||
setup_logger(config)
|
||||
|
||||
Dyndnsd.logger.info "Starting..."
|
||||
Dyndnsd.logger.info 'Starting...'
|
||||
|
||||
# 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']
|
||||
|
||||
setup_traps()
|
||||
setup_traps
|
||||
|
||||
setup_monitoring(config)
|
||||
|
||||
@ -97,12 +100,12 @@ module Dyndnsd
|
||||
|
||||
private
|
||||
|
||||
def extract_v4_and_v6_address(env, params)
|
||||
return [] if not params["myip"]
|
||||
def extract_v4_and_v6_address(params)
|
||||
return [] if !(params['myip'])
|
||||
begin
|
||||
IPAddr.new(params["myip"], Socket::AF_INET)
|
||||
IPAddr.new(params["myip6"], Socket::AF_INET6)
|
||||
[params["myip"], params["myip6"]]
|
||||
IPAddr.new(params['myip'], Socket::AF_INET)
|
||||
IPAddr.new(params['myip6'], Socket::AF_INET6)
|
||||
[params['myip'], params['myip6']]
|
||||
rescue ArgumentError
|
||||
[]
|
||||
end
|
||||
@ -110,23 +113,23 @@ module Dyndnsd
|
||||
|
||||
def extract_myips(env, params)
|
||||
# require presence of myip parameter as valid IPAddr (v4) and valid myip6
|
||||
return extract_v4_and_v6_address(env, params) if params.has_key?("myip6")
|
||||
return extract_v4_and_v6_address(params) if params.key?('myip6')
|
||||
|
||||
# check whether myip parameter has valid IPAddr
|
||||
return [params["myip"]] if params.has_key?("myip") and Helper.is_ip_valid?(params["myip"])
|
||||
return [params['myip']] if params.key?('myip') && Helper.ip_valid?(params['myip'])
|
||||
|
||||
# check whether X-Real-IP header has valid IPAddr
|
||||
return [env["HTTP_X_REAL_IP"]] if env.has_key?("HTTP_X_REAL_IP") and Helper.is_ip_valid?(env["HTTP_X_REAL_IP"])
|
||||
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
|
||||
[env["REMOTE_ADDR"]]
|
||||
[env['REMOTE_ADDR']]
|
||||
end
|
||||
|
||||
def process_changes(hostnames, myips)
|
||||
changes = []
|
||||
hostnames.each do |hostname|
|
||||
# myips order is always deterministic
|
||||
if (not @db['hosts'].include? hostname) or (@db['hosts'][hostname] != myips)
|
||||
if (!@db['hosts'].include? hostname) || (@db['hosts'][hostname] != myips)
|
||||
@db['hosts'][hostname] = myips
|
||||
changes << :good
|
||||
Metriks.meter('requests.good').mark
|
||||
@ -138,7 +141,7 @@ module Dyndnsd
|
||||
changes
|
||||
end
|
||||
|
||||
def update_db()
|
||||
def update_db
|
||||
@db['serial'] += 1
|
||||
Dyndnsd.logger.info "Committing update ##{@db['serial']}"
|
||||
@db.save
|
||||
@ -147,18 +150,18 @@ module Dyndnsd
|
||||
end
|
||||
|
||||
def handle_dyndns_request(env)
|
||||
params = Rack::Utils.parse_query(env["QUERY_STRING"])
|
||||
params = Rack::Utils.parse_query(env['QUERY_STRING'])
|
||||
|
||||
# require hostname parameter
|
||||
return [422, {'X-DynDNS-Response' => 'hostname_missing'}, []] if not params["hostname"]
|
||||
return [422, {'X-DynDNS-Response' => 'hostname_missing'}, []] if !(params['hostname'])
|
||||
|
||||
hostnames = params["hostname"].split(',')
|
||||
hostnames = params['hostname'].split(',')
|
||||
|
||||
# check for invalid hostnames
|
||||
invalid_hostnames = hostnames.select { |hostname| not Helper.is_fqdn_valid?(hostname, @domain) }
|
||||
invalid_hostnames = hostnames.select { |hostname| !Helper.fqdn_valid?(hostname, @domain) }
|
||||
return [422, {'X-DynDNS-Response' => 'hostname_malformed'}, []] if invalid_hostnames.any?
|
||||
|
||||
user = env["REMOTE_USER"]
|
||||
user = env['REMOTE_USER']
|
||||
|
||||
# check for hostnames that the user does not own
|
||||
forbidden_hostnames = hostnames - @users[user]['hosts']
|
||||
@ -181,29 +184,29 @@ module Dyndnsd
|
||||
|
||||
# SETUP
|
||||
|
||||
def self.setup_logger(config)
|
||||
private_class_method def self.setup_logger(config)
|
||||
if config['logfile']
|
||||
Dyndnsd.logger = Logger.new(config['logfile'])
|
||||
else
|
||||
Dyndnsd.logger = Logger.new(STDOUT)
|
||||
end
|
||||
|
||||
Dyndnsd.logger.progname = "dyndnsd"
|
||||
Dyndnsd.logger.progname = 'dyndnsd'
|
||||
Dyndnsd.logger.formatter = LogFormatter.new
|
||||
end
|
||||
|
||||
def self.setup_traps()
|
||||
private_class_method def self.setup_traps
|
||||
Signal.trap('INT') do
|
||||
Dyndnsd.logger.info "Quitting..."
|
||||
Dyndnsd.logger.info 'Quitting...'
|
||||
Rack::Handler::WEBrick.shutdown
|
||||
end
|
||||
Signal.trap('TERM') do
|
||||
Dyndnsd.logger.info "Quitting..."
|
||||
Dyndnsd.logger.info 'Quitting...'
|
||||
Rack::Handler::WEBrick.shutdown
|
||||
end
|
||||
end
|
||||
|
||||
def self.setup_monitoring(config)
|
||||
private_class_method def self.setup_monitoring(config)
|
||||
# configure metriks
|
||||
if config['graphite']
|
||||
host = config['graphite']['host'] || 'localhost'
|
||||
@ -224,14 +227,14 @@ module Dyndnsd
|
||||
end
|
||||
end
|
||||
|
||||
def self.setup_rack(config)
|
||||
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
|
||||
app = Rack::Auth::Basic.new(daemon, "DynDNS", &daemon.method(:is_authorized?))
|
||||
app = Rack::Auth::Basic.new(daemon, 'DynDNS', &daemon.method(:authorized?))
|
||||
|
||||
if config['responder'] == 'RestStyle'
|
||||
app = Responder::RestStyle.new(app)
|
||||
@ -239,7 +242,7 @@ module Dyndnsd
|
||||
app = Responder::DynDNSStyle.new(app)
|
||||
end
|
||||
|
||||
Rack::Handler::WEBrick.run app, :Host => config['host'], :Port => config['port']
|
||||
Rack::Handler::WEBrick.run app, Host: config['host'], Port: config['port']
|
||||
end
|
||||
end
|
||||
end
|
||||
|
@ -4,27 +4,27 @@ require 'forwardable'
|
||||
module Dyndnsd
|
||||
class Database
|
||||
extend Forwardable
|
||||
|
||||
|
||||
def_delegators :@db, :[], :[]=, :each, :has_key?
|
||||
|
||||
|
||||
def initialize(db_file)
|
||||
@db_file = db_file
|
||||
end
|
||||
|
||||
|
||||
def load
|
||||
if File.file?(@db_file)
|
||||
@db = JSON.load(File.open(@db_file, 'r') { |f| f.read })
|
||||
@db = JSON.parse(File.open(@db_file, 'r', &:read))
|
||||
else
|
||||
@db = {}
|
||||
end
|
||||
@db_hash = @db.hash
|
||||
end
|
||||
|
||||
|
||||
def save
|
||||
File.open(@db_file, 'w') { |f| JSON.dump(@db, f) }
|
||||
@db_hash = @db.hash
|
||||
end
|
||||
|
||||
|
||||
def changed?
|
||||
@db_hash != @db.hash
|
||||
end
|
||||
|
@ -14,21 +14,21 @@ module Dyndnsd
|
||||
out = []
|
||||
out << "$TTL #{@ttl}"
|
||||
out << "$ORIGIN #{@domain}."
|
||||
out << ""
|
||||
out << ''
|
||||
out << "@ IN SOA #{@dns} #{@email_addr} ( #{zone['serial']} 3h 5m 1w 1h )"
|
||||
out << "@ IN NS #{@dns}"
|
||||
out << ""
|
||||
zone['hosts'].each do |hostname,ips|
|
||||
out << ''
|
||||
zone['hosts'].each do |hostname, ips|
|
||||
ips.each do |ip|
|
||||
ip = IPAddr.new(ip).native
|
||||
type = ip.ipv6? ? "AAAA" : "A"
|
||||
type = ip.ipv6? ? 'AAAA' : 'A'
|
||||
name = hostname.chomp('.' + @domain)
|
||||
out << "#{name} IN #{type} #{ip}"
|
||||
end
|
||||
end
|
||||
out << ""
|
||||
out << ''
|
||||
out << @additional_zone_content
|
||||
out << ""
|
||||
out << ''
|
||||
out.join("\n")
|
||||
end
|
||||
end
|
||||
|
@ -3,21 +3,19 @@ require 'ipaddr'
|
||||
|
||||
module Dyndnsd
|
||||
class Helper
|
||||
def self.is_fqdn_valid?(hostname, domain)
|
||||
def self.fqdn_valid?(hostname, domain)
|
||||
return false if hostname.length < domain.length + 2
|
||||
return false if not hostname.end_with?(domain)
|
||||
return false if !hostname.end_with?(domain)
|
||||
name = hostname.chomp(domain)
|
||||
return false if not name.match(/^[a-zA-Z0-9_-]+\.$/)
|
||||
return false if !name.match(/^[a-zA-Z0-9_-]+\.$/)
|
||||
true
|
||||
end
|
||||
|
||||
def self.is_ip_valid?(ip)
|
||||
begin
|
||||
IPAddr.new(ip)
|
||||
return true
|
||||
rescue ArgumentError
|
||||
return false
|
||||
end
|
||||
def self.ip_valid?(ip)
|
||||
IPAddr.new(ip)
|
||||
return true
|
||||
rescue ArgumentError
|
||||
return false
|
||||
end
|
||||
end
|
||||
end
|
||||
|
@ -8,7 +8,7 @@ module Dyndnsd
|
||||
|
||||
def call(env)
|
||||
@app.call(env).tap do |status_code, headers, body|
|
||||
if headers.has_key?("X-DynDNS-Response")
|
||||
if headers.key?('X-DynDNS-Response')
|
||||
return decorate_dyndnsd_response(status_code, headers, body)
|
||||
else
|
||||
return decorate_other_response(status_code, headers, body)
|
||||
@ -20,17 +20,17 @@ module Dyndnsd
|
||||
|
||||
def decorate_dyndnsd_response(status_code, headers, body)
|
||||
if status_code == 200
|
||||
[200, {"Content-Type" => "text/plain"}, [get_success_body(body[0], body[1])]]
|
||||
[200, {'Content-Type' => 'text/plain'}, [get_success_body(body[0], body[1])]]
|
||||
elsif status_code == 422
|
||||
get_error_response_map[headers["X-DynDNS-Response"]]
|
||||
error_response_map[headers['X-DynDNS-Response']]
|
||||
end
|
||||
end
|
||||
|
||||
def decorate_other_response(status_code, headers, body)
|
||||
def decorate_other_response(status_code, headers, _body)
|
||||
if status_code == 400
|
||||
[status_code, headers, ["Bad Request"]]
|
||||
[status_code, headers, ['Bad Request']]
|
||||
elsif status_code == 401
|
||||
[status_code, headers, ["badauth"]]
|
||||
[status_code, headers, ['badauth']]
|
||||
end
|
||||
end
|
||||
|
||||
@ -38,15 +38,15 @@ module Dyndnsd
|
||||
changes.map { |change| "#{change} #{myips.join(' ')}" }.join("\n")
|
||||
end
|
||||
|
||||
def get_error_response_map
|
||||
def error_response_map
|
||||
{
|
||||
# general http errors
|
||||
'method_forbidden' => [405, {"Content-Type" => "text/plain"}, ["Method Not Allowed"]],
|
||||
'not_found' => [404, {"Content-Type" => "text/plain"}, ["Not Found"]],
|
||||
'method_forbidden' => [405, {'Content-Type' => 'text/plain'}, ['Method Not Allowed']],
|
||||
'not_found' => [404, {'Content-Type' => 'text/plain'}, ['Not Found']],
|
||||
# specific errors
|
||||
'hostname_missing' => [200, {"Content-Type" => "text/plain"}, ["notfqdn"]],
|
||||
'hostname_malformed' => [200, {"Content-Type" => "text/plain"}, ["notfqdn"]],
|
||||
'host_forbidden' => [200, {"Content-Type" => "text/plain"}, ["nohost"]]
|
||||
'hostname_missing' => [200, {'Content-Type' => 'text/plain'}, ['notfqdn']],
|
||||
'hostname_malformed' => [200, {'Content-Type' => 'text/plain'}, ['notfqdn']],
|
||||
'host_forbidden' => [200, {'Content-Type' => 'text/plain'}, ['nohost']]
|
||||
}
|
||||
end
|
||||
end
|
||||
|
@ -8,7 +8,7 @@ module Dyndnsd
|
||||
|
||||
def call(env)
|
||||
@app.call(env).tap do |status_code, headers, body|
|
||||
if headers.has_key?("X-DynDNS-Response")
|
||||
if headers.key?('X-DynDNS-Response')
|
||||
return decorate_dyndnsd_response(status_code, headers, body)
|
||||
else
|
||||
return decorate_other_response(status_code, headers, body)
|
||||
@ -20,17 +20,17 @@ module Dyndnsd
|
||||
|
||||
def decorate_dyndnsd_response(status_code, headers, body)
|
||||
if status_code == 200
|
||||
[200, {"Content-Type" => "text/plain"}, [get_success_body(body[0], body[1])]]
|
||||
[200, {'Content-Type' => 'text/plain'}, [get_success_body(body[0], body[1])]]
|
||||
elsif status_code == 422
|
||||
get_error_response_map[headers["X-DynDNS-Response"]]
|
||||
error_response_map[headers['X-DynDNS-Response']]
|
||||
end
|
||||
end
|
||||
|
||||
def decorate_other_response(status_code, headers, body)
|
||||
def decorate_other_response(status_code, headers, _body)
|
||||
if status_code == 400
|
||||
[status_code, headers, ["Bad Request"]]
|
||||
[status_code, headers, ['Bad Request']]
|
||||
elsif status_code == 401
|
||||
[status_code, headers, ["Unauthorized"]]
|
||||
[status_code, headers, ['Unauthorized']]
|
||||
end
|
||||
end
|
||||
|
||||
@ -38,15 +38,15 @@ module Dyndnsd
|
||||
changes.map { |change| change == :good ? "Changed to #{myips.join(' ')}" : "No change needed for #{myips.join(' ')}" }.join("\n")
|
||||
end
|
||||
|
||||
def get_error_response_map
|
||||
def error_response_map
|
||||
{
|
||||
# general http errors
|
||||
'method_forbidden' => [405, {"Content-Type" => "text/plain"}, ["Method Not Allowed"]],
|
||||
'not_found' => [404, {"Content-Type" => "text/plain"}, ["Not Found"]],
|
||||
'method_forbidden' => [405, {'Content-Type' => 'text/plain'}, ['Method Not Allowed']],
|
||||
'not_found' => [404, {'Content-Type' => 'text/plain'}, ['Not Found']],
|
||||
# specific errors
|
||||
'hostname_missing' => [422, {"Content-Type" => "text/plain"}, ["Hostname missing"]],
|
||||
'hostname_malformed' => [422, {"Content-Type" => "text/plain"}, ["Hostname malformed"]],
|
||||
'host_forbidden' => [403, {"Content-Type" => "text/plain"}, ["Forbidden"]]
|
||||
'hostname_missing' => [422, {'Content-Type' => 'text/plain'}, ['Hostname missing']],
|
||||
'hostname_malformed' => [422, {'Content-Type' => 'text/plain'}, ['Hostname malformed']],
|
||||
'host_forbidden' => [403, {'Content-Type' => 'text/plain'}, ['Forbidden']]
|
||||
}
|
||||
end
|
||||
end
|
||||
|
@ -7,7 +7,7 @@ module Dyndnsd
|
||||
@command = config['command']
|
||||
@generator = Generator::Bind.new(domain, config)
|
||||
end
|
||||
|
||||
|
||||
def update(zone)
|
||||
# write zone file in bind syntax
|
||||
File.open(@zone_file, 'w') { |f| f.write(@generator.generate(zone)) }
|
||||
|
@ -1,4 +1,4 @@
|
||||
|
||||
module Dyndnsd
|
||||
VERSION = "1.6.1"
|
||||
VERSION = '1.6.1'.freeze
|
||||
end
|
||||
|
Reference in New Issue
Block a user