1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
| local redis = require("resty.redis") local ngx_log = ngx.log local ngx_ERR = ngx.ERR local ngx_INFO = ngx.INFO local ngx_exit = ngx.exit local ngx_var = ngx.var
local cache_idle = 60 local forbidden_list = ngx.shared.forbidden_list
local function close_redis(red) if not red then return end local pool_max_idle_time = 10000 local pool_size = 100 local ok, err = red:set_keepalive(pool_max_idle_time, pool_size) if not ok then ngx_log(ngx_ERR, "set redis keepalive error : ", err) end end
local function get_forbidden_list() local red = redis:new() red:set_timeout(1000) local ip = "127.0.0.1" local port = 6379 local password = "password" local ok, err = red:connect(ip, port) if not ok then ngx_log(ngx_ERR, "connect to redis error : ", err) close_redis(red) return end local res, err = red:auth(password) if not res then ngx_log(ngx_ERR, "failed to authenticate: ", err) close_redis(red) return end local resp, err = red:smembers("forbidden_list") if not resp then ngx_log(ngx_ERR, "get redis connect error : ", err) close_redis(red) return end if resp == ngx.null then resp = nil end close_redis(red) return resp end
local function reflush_forbidden_list() local current_time = ngx.now() local last_update_time = forbidden_list:get("last_update_time"); if last_update_time == nil or last_update_time < (current_time - cache_idle) then local new_forbidden_list = get_forbidden_list(); if not new_forbidden_list then return end forbidden_list:flush_all() for i, forbidden_ip in ipairs(new_forbidden_list) do forbidden_list:set(forbidden_ip, true); end forbidden_list:set("last_update_time", current_time); end end
reflush_forbidden_list() local ip = ngx_var.remote_addr if forbidden_list:get(ip) then ngx_log(ngx_INFO, "forbidden ip refused access : ", ip) return ngx_exit(ngx.HTTP_FORBIDDEN) end
|