Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Read a minimal number of bytes when sniffing for protocol #449

Merged
merged 1 commit into from
Jan 4, 2025
Merged
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
19 changes: 15 additions & 4 deletions lib/bandit/initial_handler.ex
Original file line number Diff line number Diff line change
Expand Up @@ -57,19 +57,30 @@ defmodule Bandit.InitialHandler do
end
end

# Returns the protocol as suggested by received data, if possible
# Returns the protocol as suggested by received data, if possible.
# We do this in two phases so that we don't hang on *really* short HTTP/1
# requests that are less than 24 bytes
@spec sniff_wire(ThousandIsland.Socket.t()) ::
Bandit.HTTP2.Handler
| :likely_tls
| {:no_match, binary()}
| {:error, :closed | :timeout | :inet.posix()}
defp sniff_wire(socket) do
case ThousandIsland.Socket.recv(socket, 24) do
{:ok, "PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n"} -> Bandit.HTTP2.Handler
{:ok, <<22::8, 3::8, minor::8, _::binary>>} when minor in [1, 3] -> :likely_tls
case ThousandIsland.Socket.recv(socket, 3) do
{:ok, "PRI" = buffer} -> sniff_wire_for_http2(socket, buffer)
{:ok, <<22::8, 3::8, minor::8>>} when minor in [1, 3] -> :likely_tls
{:ok, data} -> {:no_match, data}
{:error, :timeout} -> {:no_match, <<>>}
{:error, error} -> {:error, error}
end
end

defp sniff_wire_for_http2(socket, buffer) do
case ThousandIsland.Socket.recv(socket, 21) do
{:ok, " * HTTP/2.0\r\n\r\nSM\r\n\r\n"} -> Bandit.HTTP2.Handler
{:ok, data} -> {:no_match, buffer <> data}
{:error, :timeout} -> {:no_match, buffer}
{:error, error} -> {:error, error}
end
end
end
Loading