-- SPDX-License-Identifier: CC0-1.0
-- vim:syntax=lua:set ts=4 sw=4:
-- Config file example usable for ISP resolver
-- Refer to manual: https://knot-resolver.readthedocs.io/en/stable/

-- Network interface configuration
net.listen('127.0.0.1', 53, { kind = 'dns' })
net.listen('::1', 53, { kind = 'dns'})
net.listen('127.0.0.1', 853, { kind = 'tls' })
net.listen('::1', 853, { kind = 'tls' })
net.listen('127.0.0.1', 443, { kind = 'doh2' })
net.listen('::1', 443, { kind = 'doh2' })

-- Refer to manual for optimal cache size
cache.size = 4 * GB

-- load modules
modules = {
    'view',
    'stats'
}

local ffi = require('ffi')

-- log statistics every second
local stat_id = event.recurrent(1 * second, function(evid)
    log_info(ffi.C.LOG_GRP_STATISTICS, table_print(stats.list()))
end)

-- stop printing statistics after first minute
event.after(1 * minute, function(evid)
        event.cancel(stat_id)
end)

-- speed_monitor definition
-- prints warning if more than 5% of total answers was slow
function speed_monitor()
        local previous = stats.list()   -- store statistics in persistent variable
        return function(evid)
                local now = stats.list()    -- save actual statistics to variable
                -- number of total answers between 'now' and 'previous' states
                local total_increment = now['answer.total'] - previous['answer.total']
                -- number of slow answers between 'now' and 'previous' states
                local slow_increment = now['answer.slow'] - previous['answer.slow']
                -- if percentage of slow answers is bigger than 5%, print warning
                if slow_increment / total_increment > 0.05 then
                        log_warn(ffi.C.LOG_GRP_STATISTICS, 'WARNING! More than 5 %% of queries was slow!')
                end
                previous = now
         end
end

-- execute speed_monitor every minute
local monitor_id = event.recurrent(1 * minute, speed_monitor())

-- apply RPZ for all clients, default rule is DENY
policy.add(policy.rpz(policy.DENY, 'blacklist.rpz'))

-- whitelist queries identified by subnet
view:addr(''192.168.1.0/24'', policy.all(policy.PASS))

-- drop everything that hasn't matched
view:addr('0.0.0.0/0', policy.all(policy.DROP))

