59 lines
2.1 KiB
Plaintext

log_by_lua_block {
local bunkernet = require "bunkernet.bunkernet"
local utils = require "utils"
local datastore = require "datastore"
local logger = require "logger"
local disable_default_server = utils.get_variable("DISABLE_DEFAULT_SERVER", false)
local use_bunkernet = utils.has_variable("USE_BUNKERNET", "yes")
if disable_default_server == "yes" and use_bunkernet then
-- Instantiate bunkernet
local bnet, err = bunkernet.new()
if not bnet then
ngx.log(ngx.ERR, "BUNKERNET", "can't instantiate bunkernet " .. err)
return
end
-- Check if BunkerNet ID is generated
if not bnet.id then
return
end
-- Check if IP has been blocked
if ngx.status ~= ngx.HTTP_CLOSE then
return
end
-- Check if IP is global
local is_global, err = utils.ip_is_global(ngx.var.remote_addr)
if is_global == nil then
return
end
if not is_global then
return
end
-- Only report if it hasn't been reported for the same reason recently
local reported = datastore:get("plugin_bunkernet_cache_" .. ngx.var.remote_addr .. "default")
if reported then
return
end
-- report callback called in a light thread
local function report_callback(premature, obj, ip, reason, method, url, headers)
local ok, err, status, data = obj:report(ip, reason, method, url, headers)
if not ok then
logger.log(ngx.ERR, "BUNKERNET", "Can't report IP : " .. err)
elseif status ~= 200 then
logger.log(ngx.ERR, "BUNKERNET", "Error from remote server : " .. tostring(status))
else
logger.log(ngx.NOTICE, "BUNKERNET", "Successfully reported IP " .. ip .. " (reason : " .. reason .. ")")
local ok, err = datastore:set("plugin_bunkernet_cache_" .. ip .. reason, true, 3600)
if not ok then
logger.log(ngx.ERR, "BUNKERNET", "Can't store cached report : " .. err)
end
end
end
-- Set a timer at the end of log()
local hdr, err = ngx.timer.at(0, report_callback, bnet, ngx.var.remote_addr, "default", ngx.var.request_method, ngx.var.request_uri, ngx.req.get_headers())
if not hdr then
logger.log(ngx.ERR, "BUNKERNET", "can't create report timer : " .. err)
end
return
end
}