Skip to content

Commit 7367a23

Browse files
LubinLewdoujiang24
authored andcommitted
bugfix: ngx.resp.get_headers(): may return a wrong (like: negative) value of the Content-Length field when it is larger than 2^32.
1 parent 57ebdd3 commit 7367a23

File tree

2 files changed

+55
-2
lines changed

2 files changed

+55
-2
lines changed

src/ngx_http_lua_headers.c

+17-1
Original file line numberDiff line numberDiff line change
@@ -424,6 +424,8 @@ ngx_http_lua_ngx_resp_get_headers(lua_State *L)
424424
int count = 0;
425425
int truncated = 0;
426426
int extra = 0;
427+
u_char *p = NULL;
428+
size_t len = 0;
427429

428430
n = lua_gettop(L);
429431

@@ -485,7 +487,21 @@ ngx_http_lua_ngx_resp_get_headers(lua_State *L)
485487
{
486488
extra++;
487489
lua_pushliteral(L, "content-length");
488-
lua_pushfstring(L, "%d", (int) r->headers_out.content_length_n);
490+
if (r->headers_out.content_length_n > NGX_MAX_INT32_VALUE) {
491+
p = ngx_palloc(r->pool, NGX_OFF_T_LEN);
492+
if (p == NULL) {
493+
return luaL_error(L, "no memory");
494+
}
495+
496+
len = ngx_snprintf(p, NGX_OFF_T_LEN, "%O",
497+
r->headers_out.content_length_n) - p;
498+
499+
lua_pushfstring(L, "%s", (char *) p, len);
500+
501+
} else {
502+
lua_pushfstring(L, "%d", (int) r->headers_out.content_length_n);
503+
}
504+
489505
lua_rawset(L, -3);
490506
}
491507

t/016-resp-header.t

+38-1
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ use Test::Nginx::Socket::Lua;
88

99
repeat_each(2);
1010

11-
plan tests => repeat_each() * (blocks() * 3 + 77);
11+
plan tests => repeat_each() * (blocks() * 3 + 79);
1212

1313
#no_diff();
1414
no_long_string();
@@ -2104,3 +2104,40 @@ xxx:
21042104
foo: foo%0Axx:bar\r\nfoo: bar%0Dxxx:foo\r\n
21052105
--- no_error_log
21062106
[error]
2107+
2108+
2109+
2110+
=== TEST 94: fix negative content-length number(#1791)
2111+
--- config
2112+
location = /big-upstream {
2113+
content_by_lua_block {
2114+
ngx.header['Content-Length'] = math.pow(2, 33) - 1
2115+
ngx.say('hi')
2116+
}
2117+
}
2118+
2119+
location = /t {
2120+
proxy_pass http://127.0.0.1:$TEST_NGINX_SERVER_PORT/big-upstream;
2121+
proxy_buffering off;
2122+
2123+
header_filter_by_lua_block {
2124+
local hs, err = ngx.resp.get_headers()
2125+
if err then
2126+
ngx.log(ngx.ERR, "err: ", err)
2127+
return ngx.exit(500)
2128+
end
2129+
2130+
print("my Content-Length: ", hs["Content-Length"])
2131+
2132+
ngx.header['Content-Length'] = 3
2133+
}
2134+
}
2135+
--- request
2136+
GET /t
2137+
--- response_body
2138+
hi
2139+
--- no_error_log
2140+
[alert]
2141+
--- error_log
2142+
my Content-Length: 8589934591
2143+
upstream prematurely closed connection while sending to client

0 commit comments

Comments
 (0)