Skip to content

Commit

Permalink
Explicitly signal keepalives in HTTP/1.0 requests
Browse files Browse the repository at this point in the history
  • Loading branch information
mtrudel committed Nov 13, 2024
1 parent 4e145b8 commit 9036df8
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 0 deletions.
9 changes: 9 additions & 0 deletions lib/bandit/http1/socket.ex
Original file line number Diff line number Diff line change
Expand Up @@ -325,6 +325,8 @@ defmodule Bandit.HTTP1.Socket do
def send_headers(%@for{write_state: :unsent} = socket, status, headers, body_disposition) do
resp_line = "#{socket.version} #{status} #{Plug.Conn.Status.reason_phrase(status)}\r\n"

headers = maybe_add_keepalive_header(status, headers, socket)

case body_disposition do
:raw ->
# This is an optimization for the common case of sending a non-encoded body (or file),
Expand All @@ -347,6 +349,13 @@ defmodule Bandit.HTTP1.Socket do
end
end

# RFC 9112§9.3
defp maybe_add_keepalive_header(status, headers, %@for{version: :"HTTP/1.0", keepalive: true})
when status not in 100..199,
do: [{"connection", "keep-alive"} | headers]

defp maybe_add_keepalive_header(_status, headers, _socket), do: headers

defp encode_headers(headers) do
headers
|> Enum.map(fn {k, v} -> [k, ": ", v, "\r\n"] end)
Expand Down
15 changes: 15 additions & 0 deletions test/bandit/http1/request_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -297,6 +297,21 @@ defmodule HTTP1RequestTest do
assert {:ok, "200 OK", _headers, _body} = SimpleHTTP1Client.recv_reply(client)
end

test "keepalive are explicitly signalled in HTTP/1.0", context do
client = SimpleHTTP1Client.tcp_client(context)

SimpleHTTP1Client.send(
client,
"GET",
"/echo_components",
["host: localhost", "connection: keep-alive"],
"1.0"
)

assert {:ok, "200 OK", headers, _body} = SimpleHTTP1Client.recv_reply(client)
assert [{:connection, "keep-alive"} | _headers] = headers
end

test "unread content length bodies are read before starting a new request", context do
client = SimpleHTTP1Client.tcp_client(context)

Expand Down

0 comments on commit 9036df8

Please sign in to comment.