Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions guides/http_guide.md
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,19 @@ large downloads use the streaming API instead.
hackney:get(URL, [], <<>>, [{max_body_size, 10 * 1024 * 1024}]).
```

### Response Header Limits

The header section of an HTTP/1.1 response, trailers included, is capped at
1 MiB and 1000 header fields. Past the size cap the request fails with
`{error, headers_too_large}`; past the count, with
`{error, too_many_headers}`. Set `max_header_size` or `max_headers` to change
them, or `infinity` to disable either.

```erlang
hackney:get(URL, [], <<>>, [{max_header_size, 4 * 1024 * 1024},
{max_headers, 5000}]).
```

### Stream Response Body (Async Mode)

For incremental body streaming, use async mode:
Expand Down
5 changes: 5 additions & 0 deletions include/hackney_lib.hrl
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,11 @@
type = auto :: atom(),
max_line_length = 4096 :: integer(),
max_empty_lines = 10 :: integer(),
max_header_size = 1048576 :: non_neg_integer() | infinity,
max_headers = 1000 :: non_neg_integer() | infinity,
header_size = 0 :: non_neg_integer(),
header_count = 0 :: non_neg_integer(),
scan_from = 0 :: non_neg_integer(),
empty_lines = 0 :: integer(),
state = on_first_line :: atom(),
buffer = <<>> :: binary(),
Expand Down
21 changes: 18 additions & 3 deletions src/hackney.erl
Original file line number Diff line number Diff line change
Expand Up @@ -663,6 +663,12 @@ request(Method, URL, Headers, Body) ->
%% - max_body_size: Cap in bytes on a response body returned whole, after
%% decompression (default 512 MiB, `infinity' disables it). Past it the
%% request fails with {error, body_too_large}; stream larger bodies.
%% - max_header_size: Cap in bytes on an HTTP/1.1 response header section,
%% trailers included (default 1 MiB, `infinity' disables it). Past it the
%% request fails with {error, headers_too_large}.
%% - max_headers: Cap on the number of HTTP/1.1 response header fields,
%% trailers included (default 1000, `infinity' disables it). Past it the
%% request fails with {error, too_many_headers}.
%%
%% Returns:
%% - {ok, Status, Headers, Body}: Success with response body
Expand Down Expand Up @@ -1521,7 +1527,9 @@ sync_request_with_redirect(ConnPid, Method, Path, Headers, Body, WithBody, Optio
MaxBodySize -> [{max_body_size, MaxBodySize} | ReqOpts0]
end,
case hackney_conn:send_request_headers(ConnPid, Method, Path, HeadersList,
with_checkout_timeout(ReqOpts, Options)) of
with_checkout_timeout(
with_header_limits(ReqOpts, Options),
Options)) of
ok -> {ok, ConnPid};
{error, Reason} -> {error, Reason}
end;
Expand Down Expand Up @@ -1559,7 +1567,8 @@ sync_request_with_redirect_body(ConnPid, Method, Path, HeadersList, FinalBody,
MaxBodySize -> [{max_body_size, MaxBodySize} | ReqOpts3]
end,
case hackney_conn:request(ConnPid, Method, Path, HeadersList, FinalBody, infinity,
with_checkout_timeout(ReqOpts, Options)) of
with_checkout_timeout(with_header_limits(ReqOpts, Options),
Options)) of
%% HTTP/2 returns body directly - handle 4-tuple first
{ok, Status, RespHeaders, RespBody} when Status >= 301, Status =< 303; Status =:= 307; Status =:= 308 ->
%% HTTP/2 redirect status
Expand Down Expand Up @@ -1779,7 +1788,8 @@ async_request(ConnPid, Method, Path, Headers, Body, AsyncMode, StreamTo, FollowR
%% is handled atomically inside hackney_conn:do_request_async
case hackney_conn:request_async(ConnPid, Method, Path, HeadersList, FinalBody, AsyncMode,
StreamTo, FollowRedirect,
with_checkout_timeout(ReqOpts, Options)) of
with_checkout_timeout(
with_header_limits(ReqOpts, Options), Options)) of
{ok, Ref} ->
{ok, Ref};
{error, Reason} ->
Expand Down Expand Up @@ -2339,6 +2349,11 @@ parse_proxy_url(Url) when is_binary(Url) ->
_:_ -> {error, invalid_proxy_url}
end.

%% @private Forward the HTTP/1.1 response header limits to the connection.
with_header_limits(ReqOpts, Options) ->
[{K, V} || K <- [max_header_size, max_headers],
V <- [proplists:get_value(K, Options)], V =/= undefined] ++ ReqOpts.

%% @private An HTTP/2 or HTTP/3 request refused at the server's limit on
%% concurrent streams waits on the connection as long as a pool checkout
%% would (hackney_conn:stream_call/3).
Expand Down
29 changes: 23 additions & 6 deletions src/hackney_conn.erl
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,8 @@
inform_fun :: fun((integer(), binary(), list()) -> any()) | undefined,
auto_decompress = false :: boolean(),
max_body_size = ?DEFAULT_MAX_BODY_SIZE :: non_neg_integer() | infinity,
%% Per-request max_header_size / max_headers, as parser options.
header_limits = [] :: list(),

%% Pool integration
pool_pid :: pid() | undefined, %% If set, connection is from a pool
Expand Down Expand Up @@ -1316,17 +1318,20 @@ connected({call, From}, {request, Method, Path, Headers, Body, ReqOpts}, Data) -
auto_decompress = AutoDecompress,
body_length = undefined,
max_body_size = max_body_size(ReqOpts),
header_limits = header_limits(ReqOpts),
recv_timeout = RecvTimeout
},
{next_state, sending, NewData, [{next_event, internal, {send_request, Method, Path, Headers, Body}}]};

connected({call, From}, {request_async, Method, Path, Headers, Body, AsyncMode, StreamTo}, Data) ->
%% Start a new async request (no redirect following)
do_request_async(From, Method, Path, Headers, Body, AsyncMode, StreamTo, false, Data);
do_request_async(From, Method, Path, Headers, Body, AsyncMode, StreamTo, false,
Data#conn_data{header_limits = []});

connected({call, From}, {request_async, Method, Path, Headers, Body, AsyncMode, StreamTo, FollowRedirect}, Data) ->
%% Start a new async request with redirect option (HTTP/1.1)
do_request_async(From, Method, Path, Headers, Body, AsyncMode, StreamTo, FollowRedirect, Data);
do_request_async(From, Method, Path, Headers, Body, AsyncMode, StreamTo, FollowRedirect,
Data#conn_data{header_limits = []});

connected({call, From}, {request_async, Method, Path, Headers, Body, AsyncMode, StreamTo, FollowRedirect, ReqOpts}, #conn_data{protocol = http2} = Data) ->
%% HTTP/2 async request with ReqOpts (fix for issue #832)
Expand All @@ -1345,7 +1350,8 @@ connected({call, From}, {request_async, Method, Path, Headers, Body, AsyncMode,
connected({call, From}, {request_async, Method, Path, Headers, Body, AsyncMode, StreamTo, FollowRedirect, ReqOpts}, Data) ->
%% HTTP/1.1 async request with ReqOpts (fix for issue #832)
RecvTimeout = proplists:get_value(recv_timeout, ReqOpts, Data#conn_data.recv_timeout),
NewData = Data#conn_data{recv_timeout = RecvTimeout},
NewData = Data#conn_data{recv_timeout = RecvTimeout,
header_limits = header_limits(ReqOpts)},
do_request_async(From, Method, Path, Headers, Body, AsyncMode, StreamTo, FollowRedirect, NewData);

connected({call, From}, {send_headers, Method, Path, Headers, ReqOpts}, #conn_data{protocol = http3} = Data) ->
Expand Down Expand Up @@ -1395,6 +1401,7 @@ connected({call, From}, {send_headers, Method, Path, Headers, ReqOpts}, Data) ->
async_ref = undefined,
stream_to = undefined,
max_body_size = max_body_size(ReqOpts),
header_limits = header_limits(ReqOpts),
body_length = undefined
},
%% Transition to streaming_body state
Expand Down Expand Up @@ -1847,7 +1854,7 @@ receiving(internal, {do_recv_response, include_pid}, Data) ->

receiving(internal, do_recv_response_async, Data) ->
%% Receive and parse response status and headers (async mode)
Parser = hackney_http:parser([response]),
Parser = response_parser(Data),
DataWithParser = Data#conn_data{parser = Parser},
#conn_data{async_ref = Ref, stream_to = StreamTo, async = AsyncMode,
follow_redirect = FollowRedirect, method = Method} = Data,
Expand Down Expand Up @@ -2478,7 +2485,7 @@ finish_async_streaming(#conn_data{transport = Transport, socket = Socket,
%% @private Handle receiving response status and headers
%% IncludePid determines whether to include pid in the response
do_recv_response_impl(Data, IncludePid) ->
Parser = hackney_http:parser([response]),
Parser = response_parser(Data),
DataWithParser = Data#conn_data{parser = Parser},
case recv_status_and_headers(DataWithParser) of
{ok, Status, Headers, NewData} ->
Expand Down Expand Up @@ -2870,7 +2877,7 @@ recv_status_and_headers_loop(Data) ->
%% Reset parser for next response, preserving any buffered data
%% The old parser's buffer may contain the start of the next response
OldBuffer = hackney_http:get(OldParser, buffer),
NewParser = hackney_http:parser([response]),
NewParser = response_parser(Data),
recv_status_and_headers_loop(NewData#conn_data{parser = NewParser, buffer = OldBuffer});
Other ->
Other
Expand Down Expand Up @@ -3001,6 +3008,16 @@ max_body_size(ReqOpts) ->
Max -> Max
end.

%% @private Per-request limits on the response header section, passed to
%% the parser. Unset options keep the parser defaults.
header_limits(ReqOpts) ->
[{K, V} || K <- [max_header_size, max_headers],
V <- [proplists:get_value(K, ReqOpts)], V =/= undefined].

%% @private A response parser with the request's header limits.
response_parser(#conn_data{header_limits = Limits}) ->
hackney_http:parser([response | Limits]).

body_within_limit(_Size, infinity) -> true;
body_within_limit(Size, Max) -> Size =< Max.

Expand Down
66 changes: 54 additions & 12 deletions src/hackney_http.erl
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,9 @@

-type parser_option() :: request | response | auto
| {max_empty_lines, integer()}
| {max_line_length, integer()}.
| {max_line_length, integer()}
| {max_header_size, non_neg_integer() | infinity}
| {max_headers, non_neg_integer() | infinity}.

-type parser_options() :: [parser_option()].

Expand All @@ -116,6 +118,12 @@ parser() ->
%% before we give up.</li>
%% <li>`{max_lines_empty, Max}': the maximum number of empty line we
%% accept before the first line happen</li>
%% <li>`{max_header_size, Bytes}': the maximum size of the header section,
%% trailers included (default 1 MiB, or `infinity'). Past it the parser
%% returns `{error, headers_too_large}'.</li>
%% <li>`{max_headers, Count}': the maximum number of header fields,
%% trailers included (default 1000, or `infinity'). Past it the parser
%% returns `{error, too_many_headers}'.</li>
%% </ul>
-spec parser(parser_options()) -> parser().
parser(Options) ->
Expand Down Expand Up @@ -298,8 +306,24 @@ parse_headers(#hparser{}=St) ->
parse_header(St).


parse_header(#hparser{}=St) ->
parse_header_sep([<<"\r\n">>, <<"\n">>], St).
parse_header(#hparser{buffer=Buf, scan_from=From}=St) ->
%% Until a line ends, only scan the bytes that arrived since the last
%% call: rescanning the whole buffer on every read is quadratic in the
%% length of a header line.
Size = byte_size(Buf),
case binary:match(Buf, <<"\n">>, [{scope, {From, Size - From}}]) of
nomatch ->
header_more(St#hparser{scan_from=Size});
_ ->
parse_header_sep([<<"\r\n">>, <<"\n">>], St#hparser{scan_from=0})
end.

%% A header line is still incomplete: wait for more, within max_header_size.
header_more(#hparser{buffer=Buf, header_size=HSize, max_header_size=Max}=St) ->
case HSize + byte_size(Buf) > Max of
true -> {error, headers_too_large};
false -> {more, St}
end.

parse_header_sep([], St) ->
{more, St};
Expand Down Expand Up @@ -328,13 +352,24 @@ parse_header_(Sep, #hparser{buffer=Buf}=St) ->
{more, St}
end.

parse_header(Line, St) ->
{Key, Value} = case binary:split(Line, <<":">>) of
[K] -> {K, <<>>};
[K, V] -> {K, hackney_bstr:trim(V)}
end,
St1 = update_parser_header(Key, Value, St),
{header, {Key, Value}, St1}.
parse_header(Line, #hparser{header_size=HSize, header_count=Count,
max_header_size=MaxSize, max_headers=MaxCount}=St) ->
HSize1 = HSize + byte_size(Line) + 2,
Count1 = Count + 1,
if
HSize1 > MaxSize ->
{error, headers_too_large};
Count1 > MaxCount ->
{error, too_many_headers};
true ->
{Key, Value} = case binary:split(Line, <<":">>) of
[K] -> {K, <<>>};
[K, V] -> {K, hackney_bstr:trim(V)}
end,
St1 = update_parser_header(Key, Value,
St#hparser{header_size=HSize1, header_count=Count1}),
{header, {Key, Value}, St1}
end.

%% Fast path for common headers using case-insensitive pattern matching
%% This avoids calling to_lower/trim for every header
Expand Down Expand Up @@ -410,14 +445,17 @@ parse_trailers(St) ->
{ok, _Trailers, #hparser{buffer=Rest1}} ->
{done, Rest1};
{more, St2} ->
{more, St2}
{more, St2};
{error, _} = Error ->
Error
end.

parse_trailers(St, Acc) ->
case parse_headers(St) of
{header, Header, St2} -> parse_trailers(St2, [Header | Acc]);
{headers_complete, St2} -> {ok, lists:reverse(Acc), St2};
{more, St2} -> {more, St2}
{more, St2} -> {more, St2};
{error, _} = Error -> Error
end.

parse_body(#hparser{body_state=waiting, method= <<"HEAD">>, buffer=Buffer}) ->
Expand Down Expand Up @@ -642,6 +680,10 @@ parse_options([{max_line_length, MaxLength} | Rest], St) ->
parse_options(Rest, St#hparser{max_line_length=MaxLength});
parse_options([{max_empty_lines, MaxEmptyLines} | Rest], St) ->
parse_options(Rest, St#hparser{max_empty_lines=MaxEmptyLines});
parse_options([{max_header_size, Max} | Rest], St) ->
parse_options(Rest, St#hparser{max_header_size=Max});
parse_options([{max_headers, Max} | Rest], St) ->
parse_options(Rest, St#hparser{max_headers=Max});
parse_options([_ | Rest], St) ->
parse_options(Rest, St).

Expand Down
Loading
Loading