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
3 changes: 2 additions & 1 deletion examples/genserver.exs
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,8 @@ defmodule Ws do
|> handle_responses(rest)

{:error, websocket, reason} ->
put_in(state.websocket, websocket)
# extension state may hold data from the failed message, so close
%{state | websocket: websocket, closing?: true}
|> reply({:error, reason})
end
end
Expand Down
44 changes: 40 additions & 4 deletions lib/mint/web_socket.ex
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ defmodule Mint.WebSocket do
"permessage-deflate" extension.
"""

alias __MODULE__.{Utils, Extension, Frame}
alias __MODULE__.{Utils, Extension, Frame, PerMessageDeflate}
alias Mint.{WebSocketError, WebSocket.UpgradeFailureError}
import Mint.HTTP, only: [get_private: 2, put_private: 3, protocol: 1]

Expand All @@ -128,12 +128,16 @@ defmodule Mint.WebSocket do
extensions: [Extension.t()],
fragment: tuple(),
private: map(),
buffer: binary()
buffer: binary(),
max_message_size: pos_integer() | :infinity
}
defstruct extensions: [],
fragment: nil,
private: %{},
buffer: <<>>
buffer: <<>>,
max_message_size: :infinity

@default_max_message_size 8_000_000

@type error :: Mint.Types.error() | WebSocketError.t() | UpgradeFailureError.t()

Expand Down Expand Up @@ -322,6 +326,17 @@ defmodule Mint.WebSocket do
* `:mode` - (default: `:active`) either `:active` or `:passive`. This
corresponds to the same option in `Mint.HTTP.connect/4`.

* `:max_message_size` - (default: `#{@default_max_message_size}`) the
maximum size in bytes of an incoming message. The limit applies both to
the size on the wire and to the size after extensions (such as
permessage-deflate) run, so a small incompressible message whose
compressed form is larger than the limit is rejected too. `decode/2`
returns a `Mint.WebSocketError` with reason `:message_too_large` for
bigger messages: the connection should then be closed, because
extension state (e.g. the inflater) may still hold data from the
rejected message. Must be at least 125 (the maximum control frame
payload) or `:infinity` to disable the limit.

## Examples

http_reply = receive(do: (message -> message))
Expand All @@ -342,13 +357,34 @@ defmodule Mint.WebSocket do
{:ok, Mint.HTTP.t(), t()} | {:error, Mint.HTTP.t(), error()}
def new(conn, request_ref, status, response_headers, opts \\ []) do
websockets = [request_ref | get_private(conn, :websockets) || []]
max_message_size = Keyword.get(opts, :max_message_size, @default_max_message_size)

unless max_message_size == :infinity or
(is_integer(max_message_size) and max_message_size >= 125) do
raise ArgumentError,
"expected :max_message_size to be :infinity or an integer >= 125, " <>
"got: #{inspect(max_message_size)}"
end

# permessage-deflate reads the limit from its opts to stop inflating early
extensions =
for extension <- get_private(conn, :extensions) do
if extension.module == PerMessageDeflate do
%{extension | opts: Keyword.put(extension.opts, :max_message_size, max_message_size)}
else
extension
end
end

conn =
conn
|> put_private(:websockets, websockets)
|> put_private(:mode, Keyword.get(opts, :mode, :active))
|> put_private(:extensions, extensions)

do_new(protocol(conn), conn, status, response_headers)
with {:ok, conn, websocket} <- do_new(protocol(conn), conn, status, response_headers) do
{:ok, conn, %{websocket | max_message_size: max_message_size}}
end
end

defp do_new(:http1, conn, status, headers) when status != 101 do
Expand Down
38 changes: 29 additions & 9 deletions lib/mint/web_socket/frame.ex
Original file line number Diff line number Diff line change
Expand Up @@ -215,8 +215,11 @@ defmodule Mint.WebSocket.Frame do

frame, {websocket, acc} ->
{frame, extensions} = Extension.decode(frame, websocket.extensions)
frame = translate(frame)
# extensions can expand the payload, so the final size is checked too
check_data_size(frame, websocket.max_message_size)

{put_in(websocket.extensions, extensions), [translate(frame) | acc]}
{put_in(websocket.extensions, extensions), [frame | acc]}
end)

{:ok, websocket, :lists.reverse(frames)}
Expand All @@ -242,7 +245,7 @@ defmodule Mint.WebSocket.Frame do
websocket,
acc
) do
case decode_payload_and_mask(payload_and_mask, masked == 0b1) do
case decode_payload_and_mask(payload_and_mask, masked == 0b1, websocket.max_message_size) do
{:ok, payload, mask, rest} ->
frame = decode_full_frame_binary(opcode, fin, reserved, mask, payload)

Expand All @@ -262,8 +265,9 @@ defmodule Mint.WebSocket.Frame do
{:buffer, partial, :lists.reverse(acc)}
end

defp decode_payload_and_mask(payload, masked?) do
defp decode_payload_and_mask(payload, masked?, max_message_size) do
with {:ok, payload_length, rest} <- decode_payload_length(payload),
:ok <- check_message_size(payload_length, max_message_size),
{:ok, mask, rest} <- decode_mask(rest, masked?),
<<payload::binary-size(^payload_length), more::bitstring>> <- rest do
{:ok, payload, mask, more}
Expand All @@ -274,6 +278,17 @@ defmodule Mint.WebSocket.Frame do
end
end

@doc false
def check_message_size(size, max) when is_integer(max) and size > max,
do: throw({:mint, %WebSocketError{reason: :message_too_large}})

def check_message_size(_size, _max), do: :ok

defp check_data_size({type, data}, max) when type in [:text, :binary],
do: check_message_size(byte_size(data), max)

defp check_data_size(_frame, _max), do: :ok

defp decode_full_frame_binary(opcode, fin, reserved, mask, payload) do
with {:ok, opcode} <- decode_opcode(opcode) do
into_frame(
Expand Down Expand Up @@ -459,14 +474,14 @@ defmodule Mint.WebSocket.Frame do
end

def resolve_fragments(websocket, [frame | rest], acc) when is_fin(frame) do
frame = combine(websocket.fragment, frame)
frame = combine(websocket.fragment, frame, websocket.max_message_size)

put_in(websocket.fragment, nil)
|> resolve_fragments(rest, [frame | acc])
end

def resolve_fragments(websocket, [frame | rest], acc) do
case combine(websocket.fragment, frame) do
case combine(websocket.fragment, frame, websocket.max_message_size) do
{:error, reason} ->
put_in(websocket.fragment, nil)
|> resolve_fragments(rest, [{:error, reason} | acc])
Expand All @@ -477,18 +492,23 @@ defmodule Mint.WebSocket.Frame do
end
end

defp combine(nil, continuation(fin?: true)), do: {:error, :insular_continuation}
defp combine(nil, continuation(fin?: true), _max_message_size),
do: {:error, :insular_continuation}

defp combine(nil, frame), do: frame
defp combine(nil, frame, _max_message_size), do: frame

for type <- [:continuation, :text, :binary] do
defp combine(
unquote(type)(data: frame_data) = frame,
continuation(data: continuation_data, fin?: fin?)
continuation(data: continuation_data, fin?: fin?),
max_message_size
) do
:ok =
check_message_size(byte_size(frame_data) + byte_size(continuation_data), max_message_size)

unquote(type)(frame, data: Utils.maybe_concat(frame_data, continuation_data), fin?: fin?)
end
end

defp combine(a, b), do: {:error, {:cannot_combine_frames, a, b}}
defp combine(a, b, _max_message_size), do: {:error, {:cannot_combine_frames, a, b}}
end
26 changes: 19 additions & 7 deletions lib/mint/web_socket/per_message_deflate.ex
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,11 @@ defmodule Mint.WebSocket.PerMessageDeflate do
inflate: :zlib.zstream(),
deflate: :zlib.zstream(),
inflate_takeover?: boolean(),
deflate_takeover?: boolean()
deflate_takeover?: boolean(),
max_message_size: non_neg_integer() | :infinity
}

defstruct [:inflate, :deflate, :inflate_takeover?, :deflate_takeover?]
defstruct [:inflate, :deflate, :inflate_takeover?, :deflate_takeover?, :max_message_size]

@behaviour Extension

Expand Down Expand Up @@ -59,7 +60,8 @@ defmodule Mint.WebSocket.PerMessageDeflate do
inflate: inflate_zstream,
deflate: deflate_zstream,
inflate_takeover?: get_takeover(params, "server_no_context_takeover", true),
deflate_takeover?: get_takeover(params, "client_no_context_takeover", true)
deflate_takeover?: get_takeover(params, "client_no_context_takeover", true),
max_message_size: Keyword.get(opts, :max_message_size, :infinity)
}

{:ok, put_in(this_extension.state, state)}
Expand All @@ -84,10 +86,7 @@ defmodule Mint.WebSocket.PerMessageDeflate do
# Append 4 octets of 0x00 0x00 0xff 0xff to the tail end of the
# payload of the message

data =
state.inflate
|> :zlib.inflate(<<data::binary, 0x00, 0x00, 0xFF, 0xFF>>)
|> IO.iodata_to_binary()
data = inflate(state, <<data::binary, 0x00, 0x00, 0xFF, 0xFF>>)

if state.inflate_takeover? == false do
:zlib.inflateReset(state.inflate)
Expand All @@ -105,6 +104,19 @@ defmodule Mint.WebSocket.PerMessageDeflate do

def decode(frame, state), do: {:ok, frame, state}

# Known limitation: the limit is checked after each chunk returned by
# :zlib.safeInflate/2, so up to one chunk (16 KB on OTP 27) may be inflated past it.
defp inflate(state, data, acc \\ [], size \\ 0) do
{status, output} = :zlib.safeInflate(state.inflate, data)
size = size + IO.iodata_length(output)
:ok = Frame.check_message_size(size, state.max_message_size)

case status do
:continue -> inflate(state, [], [acc | output], size)
:finished -> IO.iodata_to_binary([acc | output])
end
end

@doc false
@impl Extension
def encode(frame, state)
Expand Down
5 changes: 5 additions & 0 deletions lib/mint/web_socket_error.ex
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ defmodule Mint.WebSocketError do
quote do
:extended_connect_disabled
| :payload_too_large
| :message_too_large
| {:extension_not_negotiated, Mint.WebSocket.Extension.t()}
end

Expand All @@ -30,6 +31,10 @@ defmodule Mint.WebSocketError do
"frame payload cannot exceed 9,223,372,036,854,775,807 bytes"
end

defp format_reason(:message_too_large) do
"message exceeds the :max_message_size option"
end

defp format_reason({:extension_not_negotiated, extension}) do
"the remote server accepted an extension the client did not offer: #{inspect(extension)}"
end
Expand Down
4 changes: 3 additions & 1 deletion test/fixtures/autobahn_client.ex
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,9 @@ defmodule AutobahnClient do
[{:done, ^ref}] -> <<>>
end

{:ok, conn, websocket} = Mint.WebSocket.new(conn, ref, status, resp_headers)
# the performance cases send messages up to 16 MiB
{:ok, conn, websocket} =
Mint.WebSocket.new(conn, ref, status, resp_headers, max_message_size: :infinity)

%__MODULE__{
next: :cont,
Expand Down
Loading