Skip to content

Instantly share code, notes, and snippets.

@davidcaste
Created May 12, 2015 16:26
Show Gist options
  • Save davidcaste/ea10f1c48a2d0007b51e to your computer and use it in GitHub Desktop.
Save davidcaste/ea10f1c48a2d0007b51e to your computer and use it in GitHub Desktop.

Revisions

  1. davidcaste created this gist May 12, 2015.
    53 changes: 53 additions & 0 deletions gistfile1.lua
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,53 @@
    -- 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