Files
haproxy-s3-customname/conf/s3_rewrite.lua
T

92 lines
3.2 KiB
Lua
Raw Normal View History

-- Переписывание реального FQDN S3 на приватный в текстовых телах ответов
-- (XML, JSON, HTML, text), в том числе внутри presigned-ссылок.
-- Бинарные объекты не затрагиваются: фильтр включается только по Content-Type.
local REAL = "hb.ru-msk.vkcloud-storage.ru"
local PRIVATE = "s3-v.myhost.local"
local TYPES = { "xml", "json", "html", "text/" }
-- plain-замена без regexp: имя содержит спецсимволы Lua-паттернов
local function replace_all(s, from, to)
local out, pos = {}, 1
while true do
local a, b = s:find(from, pos, true)
if not a then break end
out[#out + 1] = s:sub(pos, a - 1)
out[#out + 1] = to
pos = b + 1
end
out[#out + 1] = s:sub(pos)
return table.concat(out)
end
-- Потоковая обработка. Имя может быть разрезано границей порций, поэтому
-- последние (#REAL - 1) байт удерживаются до следующей порции или конца тела.
local Stream = {}
Stream.__index = Stream
function Stream.new()
return setmetatable({ carry = "" }, Stream)
end
function Stream:process(data, eom)
local s = replace_all(self.carry .. data, REAL, PRIVATE)
if eom then
self.carry = ""
return s
end
local keep = math.min(#REAL - 1, #s)
self.carry = s:sub(#s - keep + 1)
return s:sub(1, #s - keep)
end
-- Подключение к HAProxy (filter lua.s3rewrite)
local Filter = {}
Filter.id = "s3rewrite"
Filter.flags = filter.FLT_CFG_FL_HTX
Filter.__index = Filter
function Filter:new()
return setmetatable({ active = false, stream = Stream.new() }, Filter)
end
local function is_text(ctype)
ctype = (ctype or ""):lower()
for _, t in ipairs(TYPES) do
if ctype:find(t, 1, true) then return true end
end
return false
end
function Filter:http_headers(txn, http_msg)
if not http_msg:is_resp() then return filter.CONTINUE end
local code = tonumber(http_msg:get_stline().code)
local headers = http_msg:get_headers()
local ctype = headers["content-type"] and headers["content-type"][0]
local enc = headers["content-encoding"] and headers["content-encoding"][0]
local no_body = code < 200 or code == 204 or code == 304 or txn.sf:method() == "HEAD"
if no_body or not is_text(ctype) or (enc and enc ~= "identity") then
return filter.CONTINUE
end
self.active = true
-- длина тела меняется: Content-Length заменяем на chunked
http_msg:set_body_len("chunked")
filter.register_data_filter(self, http_msg.channel)
return filter.CONTINUE
end
function Filter:http_payload(txn, http_msg)
if not self.active then return end
local data = http_msg:body(0, -1) or ""
http_msg:remove(0, #data)
local out = self.stream:process(data, http_msg:eom())
if #out > 0 then http_msg:send(out) end
end
core.register_filter("s3rewrite", Filter, function(flt) return flt end)
-- для автономных тестов (вне HAProxy)
return { Stream = Stream, replace_all = replace_all }