Created
May 12, 2015 16:26
-
-
Save davidcaste/ea10f1c48a2d0007b51e to your computer and use it in GitHub Desktop.
Another attempt to inflate a gzip file in Lua with output size restrictions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- Debian package nginx-extras and lzlib (https://github.com/LuaDist/lzlib) required | |
MAX_BUFFER_SIZE = 1048576 | |
function inflate_body (data) | |
local inflate = require("zlib").inflate(data) | |
local buffer = "" | |
repeat | |
chunk = inflate:read(10240) | |
if chunk ~= nil then | |
buffer = buffer .. chunk | |
end | |
if buffer:len() > MAX_BUFFER_SIZE then | |
inflate:close() | |
create_error_response(4005, "Inflated body exceeded limits") | |
end | |
until chunk == nil | |
inflate:close() | |
return buffer | |
end | |
function create_error_response (code, description) | |
local message = string.format('{"status":400,"statusReason":"Bad Request","code":%d,"exception":"","description":"%s","message":"HTTP 400 Bad Request"}', code, description) | |
ngx.status = ngx.HTTP_BAD_REQUEST | |
ngx.header.content_type = "application/json" | |
ngx.say(message) | |
ngx.exit(ngx.HTTP_OK) | |
end | |
local content_encoding = ngx.req.get_headers()["Content-Encoding"] | |
if content_encoding == "gzip" then | |
ngx.req.read_body() | |
local data = ngx.req.get_body_data() | |
local status, buffer = pcall(inflate_body, data) | |
if not status then | |
-- Corrupted GZIP body | |
create_error_response(4001, "Corrupted GZIP body") | |
end | |
ngx.log(ngx.ERR, buffer:len()) | |
ngx.req.clear_header("Content-Encoding") | |
ngx.req.clear_header("Content-Length") | |
ngx.req.set_body_data(buffer) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment