aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--Makefile2
-rw-r--r--doc/src/guide/getting_started.ezdoc2
-rw-r--r--doc/src/guide/handlers.ezdoc16
-rw-r--r--doc/src/guide/loop_handlers.ezdoc14
-rw-r--r--doc/src/guide/middlewares.ezdoc2
-rw-r--r--doc/src/guide/rest_handlers.ezdoc4
-rw-r--r--doc/src/guide/sub_protocols.ezdoc8
-rw-r--r--doc/src/guide/ws_handlers.ezdoc4
-rw-r--r--doc/src/manual/cowboy_websocket.ezdoc16
-rw-r--r--doc/src/specs/rfc7230_server.ezdoc6
-rw-r--r--examples/cookie/src/toppage_handler.erl2
-rw-r--r--rebar.config2
-rw-r--r--src/cowboy_http.erl1066
-rw-r--r--src/cowboy_protocol.erl54
-rw-r--r--src/cowboy_req.erl114
-rw-r--r--src/cowboy_rest.erl4
-rw-r--r--src/cowboy_router.erl2
-rw-r--r--src/cowboy_spdy.erl2
-rw-r--r--src/cowboy_websocket.erl552
-rw-r--r--test/handlers/input_crash_h.erl2
-rw-r--r--test/http_SUITE.erl4
-rw-r--r--test/http_SUITE_data/rest_resource_etags.erl4
22 files changed, 240 insertions, 1642 deletions
diff --git a/Makefile b/Makefile
index 2863118..db46c32 100644
--- a/Makefile
+++ b/Makefile
@@ -13,6 +13,8 @@ PLT_APPS = crypto public_key ssl
# Dependencies.
DEPS = cowlib ranch
+dep_cowlib = git https://github.com/ninenines/cowlib 1.1.0
+
TEST_DEPS = ct_helper gun
dep_ct_helper = git https://github.com/extend/ct_helper.git master
diff --git a/doc/src/guide/getting_started.ezdoc b/doc/src/guide/getting_started.ezdoc
index a959b45..deb7bf2 100644
--- a/doc/src/guide/getting_started.ezdoc
+++ b/doc/src/guide/getting_started.ezdoc
@@ -121,7 +121,7 @@ start(_Type, _Args) ->
Dispatch = cowboy_router:compile([
{'_', [{"/", hello_handler, []}]}
]),
- cowboy:start_http(my_http_listener, 100, [{port, 8080}],
+ {ok, _} = cowboy:start_http(my_http_listener, 100, [{port, 8080}],
[{env, [{dispatch, Dispatch}]}]
),
hello_erlang_sup:start_link().
diff --git a/doc/src/guide/handlers.ezdoc b/doc/src/guide/handlers.ezdoc
index c0fb97e..9336488 100644
--- a/doc/src/guide/handlers.ezdoc
+++ b/doc/src/guide/handlers.ezdoc
@@ -14,8 +14,8 @@ defined during the ^"router configuration^routing^.
A handler that does nothing would look like this:
``` erlang
-init(Req, Opts) ->
- {ok, Req, Opts}.
+init(Req, _Opts) ->
+ {ok, Req, #state{}}.
```
Despite sending no reply, a `204 No Content` reply will be
@@ -25,11 +25,11 @@ sent for every request.
We need to use the Req object for sending a reply.
``` erlang
-init(Req, Opts) ->
+init(Req, _Opts) ->
Req2 = cowboy_req:reply(200, [
{<<"content-type">>, <<"text/plain">>}
], <<"Hello World!">>, Req),
- {ok, Req2, Opts}.
+ {ok, Req2, #state{}}.
```
As you can see we return a 3-tuple. `ok` means that the
@@ -60,15 +60,15 @@ return the name of the handler type you want to use. The
following snippet switches to a Websocket handler:
``` erlang
-init(Req, Opts) ->
- {cowboy_websocket, Req, Opts}.
+init(Req, _Opts) ->
+ {cowboy_websocket, Req, #state{}}.
```
You can also switch to your own custom handler type:
``` erlang
-init(Req, Opts) ->
- {my_handler_type, Req, Opts}.
+init(Req, _Opts) ->
+ {my_handler_type, Req, #state{}}.
```
How to implement a custom handler type is described in the
diff --git a/doc/src/guide/loop_handlers.ezdoc b/doc/src/guide/loop_handlers.ezdoc
index 879013b..47893a9 100644
--- a/doc/src/guide/loop_handlers.ezdoc
+++ b/doc/src/guide/loop_handlers.ezdoc
@@ -34,8 +34,8 @@ process enter hibernation until a message is received.
This snippet enables the loop handler.
``` erlang
-init(Req, Opts) ->
- {cowboy_loop, Req, Opts}.
+init(Req, _Opts) ->
+ {cowboy_loop, Req, #state{}}.
```
However it is largely recommended that you set a timeout
@@ -43,8 +43,8 @@ value. The next example sets a timeout value of 30s and
also makes the process hibernate.
``` erlang
-init(Req, Opts) ->
- {cowboy_loop, Req, Opts, 30000, hibernate}.
+init(Req, _Opts) ->
+ {cowboy_loop, Req, #state{}, 30000, hibernate}.
```
:: Receive loop
@@ -94,9 +94,9 @@ a chunk is sent every time a `chunk` message is received,
and the loop is stopped by sending an `eof` message.
``` erlang
-init(Req, Opts) ->
- Req2 = cowboy_req:chunked_reply(200, [], Req),
- {cowboy_loop, Req2, Opts}.
+init(Req, _Opts) ->
+ Req2 = cowboy_req:chunked_reply(200, [], Req),
+ {cowboy_loop, Req2, #state{}}.
info(eof, Req, State) ->
{stop, Req, State};
diff --git a/doc/src/guide/middlewares.ezdoc b/doc/src/guide/middlewares.ezdoc
index 35e9ea9..8b047d7 100644
--- a/doc/src/guide/middlewares.ezdoc
+++ b/doc/src/guide/middlewares.ezdoc
@@ -19,7 +19,7 @@ It is defined in the `cowboy_middleware` behavior.
This callback has two arguments. The first is the `Req` object.
The second is the environment.
-Middlewares can return one of four different values:
+Middlewares can return one of three different values:
* `{ok, Req, Env}` to continue the request processing
* `{suspend, Module, Function, Args}` to hibernate
diff --git a/doc/src/guide/rest_handlers.ezdoc b/doc/src/guide/rest_handlers.ezdoc
index e09790a..e6bb092 100644
--- a/doc/src/guide/rest_handlers.ezdoc
+++ b/doc/src/guide/rest_handlers.ezdoc
@@ -13,8 +13,8 @@ to all handlers. To use REST for the current request, this function
must return a `cowboy_rest` tuple.
``` erlang
-init(Req, Opts) ->
- {cowboy_rest, Req, Opts}.
+init(Req, _Opts) ->
+ {cowboy_rest, Req, #state{}}.
```
Cowboy will then switch to the REST protocol and start executing
diff --git a/doc/src/guide/sub_protocols.ezdoc b/doc/src/guide/sub_protocols.ezdoc
index d34f21e..54e57aa 100644
--- a/doc/src/guide/sub_protocols.ezdoc
+++ b/doc/src/guide/sub_protocols.ezdoc
@@ -14,8 +14,8 @@ the name of the sub protocol module. Everything past this point
is handled by the sub protocol.
``` erlang
-init(Req, Opts) ->
- {cowboy_websocket, Req, Opts}.
+init(Req, _Opts) ->
+ {cowboy_websocket, Req, #state{}}.
```
The return value may also have a `Timeout` value and/or the
@@ -28,8 +28,8 @@ protocol, sets the timeout value to 5 seconds and enables
hibernation:
``` erlang
-init(Req, Opts) ->
- {my_protocol, Req, Opts, 5000, hibernate}.
+init(Req, _Opts) ->
+ {my_protocol, Req, #state{}, 5000, hibernate}.
```
If a sub protocol does not make use of these options, it should
diff --git a/doc/src/guide/ws_handlers.ezdoc b/doc/src/guide/ws_handlers.ezdoc
index 4cdf526..a0cfc29 100644
--- a/doc/src/guide/ws_handlers.ezdoc
+++ b/doc/src/guide/ws_handlers.ezdoc
@@ -16,8 +16,8 @@ to all handlers. To establish a Websocket connection, this function
must return a `ws` tuple.
``` erlang
-init(Req, Opts) ->
- {cowboy_websocket, Req, Opts}.
+init(Req, _Opts) ->
+ {cowboy_websocket, Req, #state{}}.
```
Upon receiving this tuple, Cowboy will switch to the code
diff --git a/doc/src/manual/cowboy_websocket.ezdoc b/doc/src/manual/cowboy_websocket.ezdoc
index 8aac4cf..2519dba 100644
--- a/doc/src/manual/cowboy_websocket.ezdoc
+++ b/doc/src/manual/cowboy_websocket.ezdoc
@@ -22,18 +22,6 @@ Cowboy will terminate the process right after closing the
Websocket connection. This means that there is no real need to
perform any cleanup in the optional `terminate/3` callback.
-:: Types
-
-: close_code() = 1000..4999
-
-Reason for closing the connection.
-
-: frame() = close | ping | pong
- | {text | binary | close | ping | pong, iodata()}
- | {close, close_code(), iodata()}
-
-Frames that can be sent to the client.
-
:: Meta values
: websocket_compress
@@ -118,7 +106,7 @@ Types:
* InFrame = {text | binary | ping | pong, binary()}
* Req = cowboy_req:req()
* State = any()
-* OutFrame = frame()
+* OutFrame = cow_ws:frame()
Handle the data received from the Websocket connection.
@@ -145,7 +133,7 @@ Types:
* Info = any()
* Req = cowboy_req:req()
* State = any()
-* OutFrame = frame()
+* OutFrame = cow_ws:frame()
Handle the Erlang message received.
diff --git a/doc/src/specs/rfc7230_server.ezdoc b/doc/src/specs/rfc7230_server.ezdoc
index d35d877..9ccac94 100644
--- a/doc/src/specs/rfc7230_server.ezdoc
+++ b/doc/src/specs/rfc7230_server.ezdoc
@@ -57,9 +57,9 @@ features understood or safely ignored by HTTP/1.0 clients. (RFC7230 A)
:: Request line
-It is recommended to limit the request-line length to a minimum
-of 8000 octets. However, as the possible line length is highly
-dependent on what form the request-target takes, it is preferrable
+It is recommended to limit the request-line length to a configurable
+limit of at least 8000 octets. However, as the possible line length is
+highly dependent on what form the request-target takes, it is preferrable
to limit each individual components of the request-target. (RFC7230 3.1.1)
A request line too long must be rejected with a 414 status code
diff --git a/examples/cookie/src/toppage_handler.erl b/examples/cookie/src/toppage_handler.erl
index 7331906..745f626 100644
--- a/examples/cookie/src/toppage_handler.erl
+++ b/examples/cookie/src/toppage_handler.erl
@@ -10,7 +10,7 @@ init(Req, Opts) ->
Req2 = cowboy_req:set_resp_cookie(
<<"server">>, NewValue, [{path, <<"/">>}], Req),
#{client := ClientCookie, server := ServerCookie}
- = cowboy_req:match_cookies([client, server], Req2),
+ = cowboy_req:match_cookies([{client, [], <<>>}, {server, [], <<>>}], Req2),
{ok, Body} = toppage_dtl:render([
{client, ClientCookie},
{server, ServerCookie}
diff --git a/rebar.config b/rebar.config
index 4018be8..92cf75c 100644
--- a/rebar.config
+++ b/rebar.config
@@ -1,4 +1,4 @@
{deps, [
- {cowlib, ".*", {git, "git://github.com/ninenines/cowlib.git", "1.0.0"}},
+ {cowlib, ".*", {git, "git://github.com/ninenines/cowlib.git", "1.1.0"}},
{ranch, ".*", {git, "git://github.com/ninenines/ranch.git", "1.0.0"}}
]}.
diff --git a/src/cowboy_http.erl b/src/cowboy_http.erl
deleted file mode 100644
index 177787f..0000000
--- a/src/cowboy_http.erl
+++ /dev/null
@@ -1,1066 +0,0 @@
-%% Copyright (c) 2011-2014, Loïc Hoguin <[email protected]>
-%% Copyright (c) 2011, Anthony Ramine <[email protected]>
-%%
-%% Permission to use, copy, modify, and/or distribute this software for any
-%% purpose with or without fee is hereby granted, provided that the above
-%% copyright notice and this permission notice appear in all copies.
-%%
-%% THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
-%% WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
-%% MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
-%% ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
-%% WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
-%% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
-%% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
-
-%% Deprecated HTTP parsing API.
--module(cowboy_http).
-
-%% Parsing.
--export([list/2]).
--export([nonempty_list/2]).
--export([content_type/1]).
--export([media_range/2]).
--export([conneg/2]).
--export([language_range/2]).
--export([entity_tag_match/1]).
--export([expectation/2]).
--export([params/2]).
--export([http_date/1]).
--export([rfc1123_date/1]).
--export([rfc850_date/1]).
--export([asctime_date/1]).
--export([whitespace/2]).
--export([digits/1]).
--export([token/2]).
--export([token_ci/2]).
--export([quoted_string/2]).
--export([authorization/2]).
--export([range/1]).
--export([parameterized_tokens/1]).
-
-%% Decoding.
--export([ce_identity/1]).
-
-%% Parsing.
-
--spec nonempty_list(binary(), fun()) -> [any(), ...] | {error, badarg}.
-nonempty_list(Data, Fun) ->
- case list(Data, Fun, []) of
- {error, badarg} -> {error, badarg};
- [] -> {error, badarg};
- L -> lists:reverse(L)
- end.
-
--spec list(binary(), fun()) -> list() | {error, badarg}.
-list(Data, Fun) ->
- case list(Data, Fun, []) of
- {error, badarg} -> {error, badarg};
- L -> lists:reverse(L)
- end.
-
--spec list(binary(), fun(), [binary()]) -> [any()] | {error, badarg}.
-%% From the RFC:
-%% <blockquote>Wherever this construct is used, null elements are allowed,
-%% but do not contribute to the count of elements present.
-%% That is, "(element), , (element) " is permitted, but counts
-%% as only two elements. Therefore, where at least one element is required,
-%% at least one non-null element MUST be present.</blockquote>
-list(Data, Fun, Acc) ->
- whitespace(Data,
- fun (<<>>) -> Acc;
- (<< $,, Rest/binary >>) -> list(Rest, Fun, Acc);
- (Rest) -> Fun(Rest,
- fun (D, I) -> whitespace(D,
- fun (<<>>) -> [I|Acc];
- (<< $,, R/binary >>) -> list(R, Fun, [I|Acc]);
- (_Any) -> {error, badarg}
- end)
- end)
- end).
-
-%% We lowercase the charset header as we know it's case insensitive.
--spec content_type(binary()) -> any().
-content_type(Data) ->
- media_type(Data,
- fun (Rest, Type, SubType) ->
- params(Rest,
- fun (<<>>, Params) ->
- case lists:keyfind(<<"charset">>, 1, Params) of
- false ->
- {Type, SubType, Params};
- {_, Charset} ->
- Charset2 = cowboy_bstr:to_lower(Charset),
- Params2 = lists:keyreplace(<<"charset">>,
- 1, Params, {<<"charset">>, Charset2}),
- {Type, SubType, Params2}
- end;
- (_Rest2, _) ->
- {error, badarg}
- end)
- end).
-
--spec media_range(binary(), fun()) -> any().
-media_range(Data, Fun) ->
- media_type(Data,
- fun (Rest, Type, SubType) ->
- media_range_params(Rest, Fun, Type, SubType, [])
- end).
-
--spec media_range_params(binary(), fun(), binary(), binary(),
- [{binary(), binary()}]) -> any().
-media_range_params(Data, Fun, Type, SubType, Acc) ->
- whitespace(Data,
- fun (<< $;, Rest/binary >>) ->
- whitespace(Rest,
- fun (Rest2) ->
- media_range_param_attr(Rest2, Fun, Type, SubType, Acc)
- end);
- (Rest) -> Fun(Rest, {{Type, SubType, lists:reverse(Acc)}, 1000, []})
- end).
-
--spec media_range_param_attr(binary(), fun(), binary(), binary(),
- [{binary(), binary()}]) -> any().
-media_range_param_attr(Data, Fun, Type, SubType, Acc) ->
- token_ci(Data,
- fun (_Rest, <<>>) -> {error, badarg};
- (<< $=, Rest/binary >>, Attr) ->
- media_range_param_value(Rest, Fun, Type, SubType, Acc, Attr)
- end).
-
--spec media_range_param_value(binary(), fun(), binary(), binary(),
- [{binary(), binary()}], binary()) -> any().
-media_range_param_value(Data, Fun, Type, SubType, Acc, <<"q">>) ->
- qvalue(Data,
- fun (Rest, Quality) ->
- accept_ext(Rest, Fun, Type, SubType, Acc, Quality, [])
- end);
-media_range_param_value(Data, Fun, Type, SubType, Acc, Attr) ->
- word(Data,
- fun (Rest, Value) ->
- media_range_params(Rest, Fun,
- Type, SubType, [{Attr, Value}|Acc])
- end).
-
--spec media_type(binary(), fun()) -> any().
-media_type(Data, Fun) ->
- token_ci(Data,
- fun (_Rest, <<>>) -> {error, badarg};
- (<< $/, Rest/binary >>, Type) ->
- token_ci(Rest,
- fun (_Rest2, <<>>) -> {error, badarg};
- (Rest2, SubType) -> Fun(Rest2, Type, SubType)
- end);
- %% This is a non-strict parsing clause required by some user agents
- %% that use * instead of */* in the list of media types.
- (Rest, <<"*">> = Type) ->
- token_ci(<<"*", Rest/binary>>,
- fun (_Rest2, <<>>) -> {error, badarg};
- (Rest2, SubType) -> Fun(Rest2, Type, SubType)
- end);
- (_Rest, _Type) -> {error, badarg}
- end).
-
--spec accept_ext(binary(), fun(), binary(), binary(),
- [{binary(), binary()}], 0..1000,
- [{binary(), binary()} | binary()]) -> any().
-accept_ext(Data, Fun, Type, SubType, Params, Quality, Acc) ->
- whitespace(Data,
- fun (<< $;, Rest/binary >>) ->
- whitespace(Rest,
- fun (Rest2) ->
- accept_ext_attr(Rest2, Fun,
- Type, SubType, Params, Quality, Acc)
- end);
- (Rest) ->
- Fun(Rest, {{Type, SubType, lists:reverse(Params)},
- Quality, lists:reverse(Acc)})
- end).
-
--spec accept_ext_attr(binary(), fun(), binary(), binary(),
- [{binary(), binary()}], 0..1000,
- [{binary(), binary()} | binary()]) -> any().
-accept_ext_attr(Data, Fun, Type, SubType, Params, Quality, Acc) ->
- token_ci(Data,
- fun (_Rest, <<>>) -> {error, badarg};
- (<< $=, Rest/binary >>, Attr) ->
- accept_ext_value(Rest, Fun, Type, SubType, Params,
- Quality, Acc, Attr);
- (Rest, Attr) ->
- accept_ext(Rest, Fun, Type, SubType, Params,
- Quality, [Attr|Acc])
- end).
-
--spec accept_ext_value(binary(), fun(), binary(), binary(),
- [{binary(), binary()}], 0..1000,
- [{binary(), binary()} | binary()], binary()) -> any().
-accept_ext_value(Data, Fun, Type, SubType, Params, Quality, Acc, Attr) ->
- word(Data,
- fun (Rest, Value) ->
- accept_ext(Rest, Fun,
- Type, SubType, Params, Quality, [{Attr, Value}|Acc])
- end).
-
--spec conneg(binary(), fun()) -> any().
-conneg(Data, Fun) ->
- token_ci(Data,
- fun (_Rest, <<>>) -> {error, badarg};
- (Rest, Conneg) ->
- maybe_qparam(Rest,
- fun (Rest2, Quality) ->
- Fun(Rest2, {Conneg, Quality})
- end)
- end).
-
--spec language_range(binary(), fun()) -> any().
-language_range(<< $*, Rest/binary >>, Fun) ->
- language_range_ret(Rest, Fun, '*');
-language_range(Data, Fun) ->
- language_tag(Data,
- fun (Rest, LanguageTag) ->
- language_range_ret(Rest, Fun, LanguageTag)
- end).
-
--spec language_range_ret(binary(), fun(), '*' | {binary(), [binary()]}) -> any().
-language_range_ret(Data, Fun, LanguageTag) ->
- maybe_qparam(Data,
- fun (Rest, Quality) ->
- Fun(Rest, {LanguageTag, Quality})
- end).
-
--spec language_tag(binary(), fun()) -> any().
-language_tag(Data, Fun) ->
- alpha(Data,
- fun (_Rest, Tag) when byte_size(Tag) =:= 0; byte_size(Tag) > 8 ->
- {error, badarg};
- (<< $-, Rest/binary >>, Tag) ->
- language_subtag(Rest, Fun, Tag, []);
- (Rest, Tag) ->
- Fun(Rest, Tag)
- end).
-
--spec language_subtag(binary(), fun(), binary(), [binary()]) -> any().
-language_subtag(Data, Fun, Tag, Acc) ->
- alphanumeric(Data,
- fun (_Rest, SubTag) when byte_size(SubTag) =:= 0;
- byte_size(SubTag) > 8 -> {error, badarg};
- (<< $-, Rest/binary >>, SubTag) ->
- language_subtag(Rest, Fun, Tag, [SubTag|Acc]);
- (Rest, SubTag) ->
- %% Rebuild the full tag now that we know it's correct
- Sub = << << $-, S/binary >> || S <- lists:reverse([SubTag|Acc]) >>,
- Fun(Rest, << Tag/binary, Sub/binary >>)
- end).
-
--spec maybe_qparam(binary(), fun()) -> any().
-maybe_qparam(Data, Fun) ->
- whitespace(Data,
- fun (<< $;, Rest/binary >>) ->
- whitespace(Rest,
- fun (Rest2) ->
- %% This is a non-strict parsing clause required by some user agents
- %% that use the wrong delimiter putting a charset where a qparam is
- %% expected.
- try qparam(Rest2, Fun) of
- Result -> Result
- catch
- error:function_clause ->
- Fun(<<",", Rest2/binary>>, 1000)
- end
- end);
- (Rest) ->
- Fun(Rest, 1000)
- end).
-
--spec qparam(binary(), fun()) -> any().
-qparam(<< Q, $=, Data/binary >>, Fun) when Q =:= $q; Q =:= $Q ->
- qvalue(Data, Fun).
-
--spec entity_tag_match(binary()) -> any().
-entity_tag_match(<< $*, Rest/binary >>) ->
- whitespace(Rest,
- fun (<<>>) -> '*';
- (_Any) -> {error, badarg}
- end);
-entity_tag_match(Data) ->
- nonempty_list(Data, fun entity_tag/2).
-
--spec entity_tag(binary(), fun()) -> any().
-entity_tag(<< "W/", Rest/binary >>, Fun) ->
- opaque_tag(Rest, Fun, weak);
-entity_tag(Data, Fun) ->
- opaque_tag(Data, Fun, strong).
-
--spec opaque_tag(binary(), fun(), weak | strong) -> any().
-opaque_tag(Data, Fun, Strength) ->
- quoted_string(Data,
- fun (_Rest, <<>>) -> {error, badarg};
- (Rest, OpaqueTag) -> Fun(Rest, {Strength, OpaqueTag})
- end).
-
--spec expectation(binary(), fun()) -> any().
-expectation(Data, Fun) ->
- token_ci(Data,
- fun (_Rest, <<>>) -> {error, badarg};
- (<< $=, Rest/binary >>, Expectation) ->
- word(Rest,
- fun (Rest2, ExtValue) ->
- params(Rest2, fun (Rest3, ExtParams) ->
- Fun(Rest3, {Expectation, ExtValue, ExtParams})
- end)
- end);
- (Rest, Expectation) ->
- Fun(Rest, Expectation)
- end).
-
--spec params(binary(), fun()) -> any().
-params(Data, Fun) ->
- params(Data, Fun, []).
-
--spec params(binary(), fun(), [{binary(), binary()}]) -> any().
-params(Data, Fun, Acc) ->
- whitespace(Data,
- fun (<< $;, Rest/binary >>) ->
- param(Rest,
- fun (Rest2, Attr, Value) ->
- params(Rest2, Fun, [{Attr, Value}|Acc])
- end);
- (Rest) ->
- Fun(Rest, lists:reverse(Acc))
- end).
-
--spec param(binary(), fun()) -> any().
-param(Data, Fun) ->
- whitespace(Data,
- fun (Rest) ->
- token_ci(Rest,
- fun (_Rest2, <<>>) -> {error, badarg};
- (<< $=, Rest2/binary >>, Attr) ->
- word(Rest2,
- fun (Rest3, Value) ->
- Fun(Rest3, Attr, Value)
- end);
- (_Rest2, _Attr) -> {error, badarg}
- end)
- end).
-
-%% While this may not be the most efficient date parsing we can do,
-%% it should work fine for our purposes because all HTTP dates should
-%% be sent as RFC1123 dates in HTTP/1.1.
--spec http_date(binary()) -> any().
-http_date(Data) ->
- case rfc1123_date(Data) of
- {error, badarg} ->
- case rfc850_date(Data) of
- {error, badarg} ->
- case asctime_date(Data) of
- {error, badarg} ->
- {error, badarg};
- HTTPDate ->
- HTTPDate
- end;
- HTTPDate ->
- HTTPDate
- end;
- HTTPDate ->
- HTTPDate
- end.
-
--spec rfc1123_date(binary()) -> any().
-rfc1123_date(Data) ->
- wkday(Data,
- fun (<< ", ", Rest/binary >>, _WkDay) ->
- date1(Rest,
- fun (<< " ", Rest2/binary >>, Date) ->
- time(Rest2,
- fun (<< " GMT", Rest3/binary >>, Time) ->
- http_date_ret(Rest3, {Date, Time});
- (_Any, _Time) ->
- {error, badarg}
- end);
- (_Any, _Date) ->
- {error, badarg}
- end);
- (_Any, _WkDay) ->
- {error, badarg}
- end).
-
--spec rfc850_date(binary()) -> any().
-%% From the RFC:
-%% HTTP/1.1 clients and caches SHOULD assume that an RFC-850 date
-%% which appears to be more than 50 years in the future is in fact
-%% in the past (this helps solve the "year 2000" problem).
-rfc850_date(Data) ->
- weekday(Data,
- fun (<< ", ", Rest/binary >>, _WeekDay) ->
- date2(Rest,
- fun (<< " ", Rest2/binary >>, Date) ->
- time(Rest2,
- fun (<< " GMT", Rest3/binary >>, Time) ->
- http_date_ret(Rest3, {Date, Time});
- (_Any, _Time) ->
- {error, badarg}
- end);
- (_Any, _Date) ->
- {error, badarg}
- end);
- (_Any, _WeekDay) ->
- {error, badarg}
- end).
-
--spec asctime_date(binary()) -> any().
-asctime_date(Data) ->
- wkday(Data,
- fun (<< " ", Rest/binary >>, _WkDay) ->
- date3(Rest,
- fun (<< " ", Rest2/binary >>, PartialDate) ->
- time(Rest2,
- fun (<< " ", Rest3/binary >>, Time) ->
- asctime_year(Rest3,
- PartialDate, Time);
- (_Any, _Time) ->
- {error, badarg}
- end);
- (_Any, _PartialDate) ->
- {error, badarg}
- end);
- (_Any, _WkDay) ->
- {error, badarg1}
- end).
-
--spec asctime_year(binary(), tuple(), tuple()) -> any().
-asctime_year(<< Y1, Y2, Y3, Y4, Rest/binary >>, {Month, Day}, Time)
- when Y1 >= $0, Y1 =< $9, Y2 >= $0, Y2 =< $9,
- Y3 >= $0, Y3 =< $9, Y4 >= $0, Y4 =< $9 ->
- Year = (Y1 - $0) * 1000 + (Y2 - $0) * 100 + (Y3 - $0) * 10 + (Y4 - $0),
- http_date_ret(Rest, {{Year, Month, Day}, Time}).
-
--spec http_date_ret(binary(), tuple()) -> any().
-http_date_ret(Data, DateTime = {Date, _Time}) ->
- whitespace(Data,
- fun (<<>>) ->
- case calendar:valid_date(Date) of
- true -> DateTime;
- false -> {error, badarg}
- end;
- (_Any) ->
- {error, badarg}
- end).
-
-%% We never use it, pretty much just checks the wkday is right.
--spec wkday(binary(), fun()) -> any().
-wkday(<< WkDay:3/binary, Rest/binary >>, Fun)
- when WkDay =:= <<"Mon">>; WkDay =:= <<"Tue">>; WkDay =:= <<"Wed">>;
- WkDay =:= <<"Thu">>; WkDay =:= <<"Fri">>; WkDay =:= <<"Sat">>;
- WkDay =:= <<"Sun">> ->
- Fun(Rest, WkDay);
-wkday(_Any, _Fun) ->
- {error, badarg}.
-
-%% We never use it, pretty much just checks the weekday is right.
--spec weekday(binary(), fun()) -> any().
-weekday(<< "Monday", Rest/binary >>, Fun) ->
- Fun(Rest, <<"Monday">>);
-weekday(<< "Tuesday", Rest/binary >>, Fun) ->
- Fun(Rest, <<"Tuesday">>);
-weekday(<< "Wednesday", Rest/binary >>, Fun) ->
- Fun(Rest, <<"Wednesday">>);
-weekday(<< "Thursday", Rest/binary >>, Fun) ->
- Fun(Rest, <<"Thursday">>);
-weekday(<< "Friday", Rest/binary >>, Fun) ->
- Fun(Rest, <<"Friday">>);
-weekday(<< "Saturday", Rest/binary >>, Fun) ->
- Fun(Rest, <<"Saturday">>);
-weekday(<< "Sunday", Rest/binary >>, Fun) ->
- Fun(Rest, <<"Sunday">>);
-weekday(_Any, _Fun) ->
- {error, badarg}.
-
--spec date1(binary(), fun()) -> any().
-date1(<< D1, D2, " ", M:3/binary, " ", Y1, Y2, Y3, Y4, Rest/binary >>, Fun)
- when D1 >= $0, D1 =< $9, D2 >= $0, D2 =< $9,
- Y1 >= $0, Y1 =< $9, Y2 >= $0, Y2 =< $9,
- Y3 >= $0, Y3 =< $9, Y4 >= $0, Y4 =< $9 ->
- case month(M) of
- {error, badarg} ->
- {error, badarg};
- Month ->
- Fun(Rest, {
- (Y1 - $0) * 1000 + (Y2 - $0) * 100 + (Y3 - $0) * 10 + (Y4 - $0),
- Month,
- (D1 - $0) * 10 + (D2 - $0)
- })
- end;
-date1(_Data, _Fun) ->
- {error, badarg}.
-
--spec date2(binary(), fun()) -> any().
-date2(<< D1, D2, "-", M:3/binary, "-", Y1, Y2, Rest/binary >>, Fun)
- when D1 >= $0, D1 =< $9, D2 >= $0, D2 =< $9,
- Y1 >= $0, Y1 =< $9, Y2 >= $0, Y2 =< $9 ->
- case month(M) of
- {error, badarg} ->
- {error, badarg};
- Month ->
- Year = (Y1 - $0) * 10 + (Y2 - $0),
- Year2 = case Year > 50 of
- true -> Year + 1900;
- false -> Year + 2000
- end,
- Fun(Rest, {
- Year2,
- Month,
- (D1 - $0) * 10 + (D2 - $0)
- })
- end;
-date2(_Data, _Fun) ->
- {error, badarg}.
-
--spec date3(binary(), fun()) -> any().
-date3(<< M:3/binary, " ", D1, D2, Rest/binary >>, Fun)
- when (D1 >= $0 andalso D1 =< $3) orelse D1 =:= $\s,
- D2 >= $0, D2 =< $9 ->
- case month(M) of
- {error, badarg} ->
- {error, badarg};
- Month ->
- Day = case D1 of
- $\s -> D2 - $0;
- D1 -> (D1 - $0) * 10 + (D2 - $0)
- end,
- Fun(Rest, {Month, Day})
- end;
-date3(_Data, _Fun) ->
- {error, badarg}.
-
--spec month(<< _:24 >>) -> 1..12 | {error, badarg}.
-month(<<"Jan">>) -> 1;
-month(<<"Feb">>) -> 2;
-month(<<"Mar">>) -> 3;
-month(<<"Apr">>) -> 4;
-month(<<"May">>) -> 5;
-month(<<"Jun">>) -> 6;
-month(<<"Jul">>) -> 7;
-month(<<"Aug">>) -> 8;
-month(<<"Sep">>) -> 9;
-month(<<"Oct">>) -> 10;
-month(<<"Nov">>) -> 11;
-month(<<"Dec">>) -> 12;
-month(_Any) -> {error, badarg}.
-
--spec time(binary(), fun()) -> any().
-time(<< H1, H2, ":", M1, M2, ":", S1, S2, Rest/binary >>, Fun)
- when H1 >= $0, H1 =< $2, H2 >= $0, H2 =< $9,
- M1 >= $0, M1 =< $5, M2 >= $0, M2 =< $9,
- S1 >= $0, S1 =< $5, S2 >= $0, S2 =< $9 ->
- Hour = (H1 - $0) * 10 + (H2 - $0),
- case Hour < 24 of
- true ->
- Time = {
- Hour,
- (M1 - $0) * 10 + (M2 - $0),
- (S1 - $0) * 10 + (S2 - $0)
- },
- Fun(Rest, Time);
- false ->
- {error, badarg}
- end.
-
--spec whitespace(binary(), fun()) -> any().
-whitespace(<< C, Rest/binary >>, Fun)
- when C =:= $\s; C =:= $\t ->
- whitespace(Rest, Fun);
-whitespace(Data, Fun) ->
- Fun(Data).
-
--spec digits(binary()) -> non_neg_integer() | {error, badarg}.
-digits(Data) ->
- digits(Data,
- fun (Rest, I) ->
- whitespace(Rest,
- fun (<<>>) ->
- I;
- (_Rest2) ->
- {error, badarg}
- end)
- end).
-
--spec digits(binary(), fun()) -> any().
-digits(<< C, Rest/binary >>, Fun)
- when C >= $0, C =< $9 ->
- digits(Rest, Fun, C - $0);
-digits(_Data, _Fun) ->
- {error, badarg}.
-
--spec digits(binary(), fun(), non_neg_integer()) -> any().
-digits(<< C, Rest/binary >>, Fun, Acc)
- when C >= $0, C =< $9 ->
- digits(Rest, Fun, Acc * 10 + (C - $0));
-digits(Data, Fun, Acc) ->
- Fun(Data, Acc).
-
-%% Changes all characters to lowercase.
--spec alpha(binary(), fun()) -> any().
-alpha(Data, Fun) ->
- alpha(Data, Fun, <<>>).
-
--spec alpha(binary(), fun(), binary()) -> any().
-alpha(<<>>, Fun, Acc) ->
- Fun(<<>>, Acc);
-alpha(<< C, Rest/binary >>, Fun, Acc)
- when C >= $a andalso C =< $z;
- C >= $A andalso C =< $Z ->
- C2 = cowboy_bstr:char_to_lower(C),
- alpha(Rest, Fun, << Acc/binary, C2 >>);
-alpha(Data, Fun, Acc) ->
- Fun(Data, Acc).
-
--spec alphanumeric(binary(), fun()) -> any().
-alphanumeric(Data, Fun) ->
- alphanumeric(Data, Fun, <<>>).
-
--spec alphanumeric(binary(), fun(), binary()) -> any().
-alphanumeric(<<>>, Fun, Acc) ->
- Fun(<<>>, Acc);
-alphanumeric(<< C, Rest/binary >>, Fun, Acc)
- when C >= $a andalso C =< $z;
- C >= $A andalso C =< $Z;
- C >= $0 andalso C =< $9 ->
- C2 = cowboy_bstr:char_to_lower(C),
- alphanumeric(Rest, Fun, << Acc/binary, C2 >>);
-alphanumeric(Data, Fun, Acc) ->
- Fun(Data, Acc).
-
-%% @doc Parse either a token or a quoted string.
--spec word(binary(), fun()) -> any().
-word(Data = << $", _/binary >>, Fun) ->
- quoted_string(Data, Fun);
-word(Data, Fun) ->
- token(Data,
- fun (_Rest, <<>>) -> {error, badarg};
- (Rest, Token) -> Fun(Rest, Token)
- end).
-
-%% Changes all characters to lowercase.
--spec token_ci(binary(), fun()) -> any().
-token_ci(Data, Fun) ->
- token(Data, Fun, ci, <<>>).
-
--spec token(binary(), fun()) -> any().
-token(Data, Fun) ->
- token(Data, Fun, cs, <<>>).
-
--spec token(binary(), fun(), ci | cs, binary()) -> any().
-token(<<>>, Fun, _Case, Acc) ->
- Fun(<<>>, Acc);
-token(Data = << C, _Rest/binary >>, Fun, _Case, Acc)
- when C =:= $(; C =:= $); C =:= $<; C =:= $>; C =:= $@;
- C =:= $,; C =:= $;; C =:= $:; C =:= $\\; C =:= $";
- C =:= $/; C =:= $[; C =:= $]; C =:= $?; C =:= $=;
- C =:= ${; C =:= $}; C =:= $\s; C =:= $\t;
- C < 32; C =:= 127 ->
- Fun(Data, Acc);
-token(<< C, Rest/binary >>, Fun, Case = ci, Acc) ->
- C2 = cowboy_bstr:char_to_lower(C),
- token(Rest, Fun, Case, << Acc/binary, C2 >>);
-token(<< C, Rest/binary >>, Fun, Case, Acc) ->
- token(Rest, Fun, Case, << Acc/binary, C >>).
-
--spec quoted_string(binary(), fun()) -> any().
-quoted_string(<< $", Rest/binary >>, Fun) ->
- quoted_string(Rest, Fun, <<>>).
-
--spec quoted_string(binary(), fun(), binary()) -> any().
-quoted_string(<<>>, _Fun, _Acc) ->
- {error, badarg};
-quoted_string(<< $", Rest/binary >>, Fun, Acc) ->
- Fun(Rest, Acc);
-quoted_string(<< $\\, C, Rest/binary >>, Fun, Acc) ->
- quoted_string(Rest, Fun, << Acc/binary, C >>);
-quoted_string(<< C, Rest/binary >>, Fun, Acc) ->
- quoted_string(Rest, Fun, << Acc/binary, C >>).
-
--spec qvalue(binary(), fun()) -> any().
-qvalue(<< $0, $., Rest/binary >>, Fun) ->
- qvalue(Rest, Fun, 0, 100);
-%% Some user agents use q=.x instead of q=0.x
-qvalue(<< $., Rest/binary >>, Fun) ->
- qvalue(Rest, Fun, 0, 100);
-qvalue(<< $0, Rest/binary >>, Fun) ->
- Fun(Rest, 0);
-qvalue(<< $1, $., $0, $0, $0, Rest/binary >>, Fun) ->
- Fun(Rest, 1000);
-qvalue(<< $1, $., $0, $0, Rest/binary >>, Fun) ->
- Fun(Rest, 1000);
-qvalue(<< $1, $., $0, Rest/binary >>, Fun) ->
- Fun(Rest, 1000);
-qvalue(<< $1, Rest/binary >>, Fun) ->
- Fun(Rest, 1000);
-qvalue(_Data, _Fun) ->
- {error, badarg}.
-
--spec qvalue(binary(), fun(), integer(), 1 | 10 | 100) -> any().
-qvalue(Data, Fun, Q, 0) ->
- Fun(Data, Q);
-qvalue(<< C, Rest/binary >>, Fun, Q, M)
- when C >= $0, C =< $9 ->
- qvalue(Rest, Fun, Q + (C - $0) * M, M div 10);
-qvalue(Data, Fun, Q, _M) ->
- Fun(Data, Q).
-
-%% Only RFC2617 Basic authorization is supported so far.
--spec authorization(binary(), binary()) -> {binary(), any()} | {error, badarg}.
-authorization(UserPass, Type = <<"basic">>) ->
- whitespace(UserPass,
- fun(D) ->
- authorization_basic_userid(base64:mime_decode(D),
- fun(Rest, Userid) ->
- authorization_basic_password(Rest,
- fun(Password) ->
- {Type, {Userid, Password}}
- end)
- end)
- end);
-authorization(String, Type) ->
- whitespace(String, fun(Rest) -> {Type, Rest} end).
-
--spec authorization_basic_userid(binary(), fun()) -> any().
-authorization_basic_userid(Data, Fun) ->
- authorization_basic_userid(Data, Fun, <<>>).
-
-authorization_basic_userid(<<>>, _Fun, _Acc) ->
- {error, badarg};
-authorization_basic_userid(<<C, _Rest/binary>>, _Fun, Acc)
- when C < 32; C =:= 127; (C =:=$: andalso Acc =:= <<>>) ->
- {error, badarg};
-authorization_basic_userid(<<$:, Rest/binary>>, Fun, Acc) ->
- Fun(Rest, Acc);
-authorization_basic_userid(<<C, Rest/binary>>, Fun, Acc) ->
- authorization_basic_userid(Rest, Fun, <<Acc/binary, C>>).
-
--spec authorization_basic_password(binary(), fun()) -> any().
-authorization_basic_password(Data, Fun) ->
- authorization_basic_password(Data, Fun, <<>>).
-
-authorization_basic_password(<<C, _Rest/binary>>, _Fun, _Acc)
- when C < 32; C=:= 127 ->
- {error, badarg};
-authorization_basic_password(<<>>, Fun, Acc) ->
- Fun(Acc);
-authorization_basic_password(<<C, Rest/binary>>, Fun, Acc) ->
- authorization_basic_password(Rest, Fun, <<Acc/binary, C>>).
-
--spec range(binary()) -> {Unit, [Range]} | {error, badarg} when
- Unit :: binary(),
- Range :: {non_neg_integer(), non_neg_integer() | infinity} | neg_integer().
-range(Data) ->
- token_ci(Data, fun range/2).
-
-range(Data, Token) ->
- whitespace(Data,
- fun(<<"=", Rest/binary>>) ->
- case list(Rest, fun range_beginning/2) of
- {error, badarg} ->
- {error, badarg};
- Ranges ->
- {Token, Ranges}
- end;
- (_) ->
- {error, badarg}
- end).
-
-range_beginning(Data, Fun) ->
- range_digits(Data, suffix,
- fun(D, RangeBeginning) ->
- range_ending(D, Fun, RangeBeginning)
- end).
-
-range_ending(Data, Fun, RangeBeginning) ->
- whitespace(Data,
- fun(<<"-", R/binary>>) ->
- case RangeBeginning of
- suffix ->
- range_digits(R, fun(D, RangeEnding) -> Fun(D, -RangeEnding) end);
- _ ->
- range_digits(R, infinity,
- fun(D, RangeEnding) ->
- Fun(D, {RangeBeginning, RangeEnding})
- end)
- end;
- (_) ->
- {error, badarg}
- end).
-
--spec range_digits(binary(), fun()) -> any().
-range_digits(Data, Fun) ->
- whitespace(Data,
- fun(D) ->
- digits(D, Fun)
- end).
-
--spec range_digits(binary(), any(), fun()) -> any().
-range_digits(Data, Default, Fun) ->
- whitespace(Data,
- fun(<< C, Rest/binary >>) when C >= $0, C =< $9 ->
- digits(Rest, Fun, C - $0);
- (_) ->
- Fun(Data, Default)
- end).
-
--spec parameterized_tokens(binary()) -> any().
-parameterized_tokens(Data) ->
- nonempty_list(Data,
- fun (D, Fun) ->
- token(D,
- fun (_Rest, <<>>) -> {error, badarg};
- (Rest, Token) ->
- parameterized_tokens_params(Rest,
- fun (Rest2, Params) ->
- Fun(Rest2, {Token, Params})
- end, [])
- end)
- end).
-
--spec parameterized_tokens_params(binary(), fun(), [binary() | {binary(), binary()}]) -> any().
-parameterized_tokens_params(Data, Fun, Acc) ->
- whitespace(Data,
- fun (<< $;, Rest/binary >>) ->
- parameterized_tokens_param(Rest,
- fun (Rest2, Param) ->
- parameterized_tokens_params(Rest2, Fun, [Param|Acc])
- end);
- (Rest) ->
- Fun(Rest, lists:reverse(Acc))
- end).
-
--spec parameterized_tokens_param(binary(), fun()) -> any().
-parameterized_tokens_param(Data, Fun) ->
- whitespace(Data,
- fun (Rest) ->
- token(Rest,
- fun (_Rest2, <<>>) -> {error, badarg};
- (<< $=, Rest2/binary >>, Attr) ->
- word(Rest2,
- fun (Rest3, Value) ->
- Fun(Rest3, {Attr, Value})
- end);
- (Rest2, Attr) ->
- Fun(Rest2, Attr)
- end)
- end).
-
-%% Decoding.
-
-%% @todo Move this to cowlib too I suppose. :-)
--spec ce_identity(Data) -> Data when Data::binary().
-ce_identity(Data) ->
- Data.
-
-%% Tests.
-
--ifdef(TEST).
-nonempty_charset_list_test_() ->
- Tests = [
- {<<>>, {error, badarg}},
- {<<"iso-8859-5, unicode-1-1;q=0.8">>, [
- {<<"iso-8859-5">>, 1000},
- {<<"unicode-1-1">>, 800}
- ]},
- %% Some user agents send this invalid value for the Accept-Charset header
- {<<"ISO-8859-1;utf-8;q=0.7,*;q=0.7">>, [
- {<<"iso-8859-1">>, 1000},
- {<<"utf-8">>, 700},
- {<<"*">>, 700}
- ]}
- ],
- [{V, fun() -> R = nonempty_list(V, fun conneg/2) end} || {V, R} <- Tests].
-
-nonempty_language_range_list_test_() ->
- Tests = [
- {<<"da, en-gb;q=0.8, en;q=0.7">>, [
- {<<"da">>, 1000},
- {<<"en-gb">>, 800},
- {<<"en">>, 700}
- ]},
- {<<"en, en-US, en-cockney, i-cherokee, x-pig-latin, es-419">>, [
- {<<"en">>, 1000},
- {<<"en-us">>, 1000},
- {<<"en-cockney">>, 1000},
- {<<"i-cherokee">>, 1000},
- {<<"x-pig-latin">>, 1000},
- {<<"es-419">>, 1000}
- ]}
- ],
- [{V, fun() -> R = nonempty_list(V, fun language_range/2) end}
- || {V, R} <- Tests].
-
-nonempty_token_list_test_() ->
- Tests = [
- {<<>>, {error, badarg}},
- {<<" ">>, {error, badarg}},
- {<<" , ">>, {error, badarg}},
- {<<",,,">>, {error, badarg}},
- {<<"a b">>, {error, badarg}},
- {<<"a , , , ">>, [<<"a">>]},
- {<<" , , , a">>, [<<"a">>]},
- {<<"a, , b">>, [<<"a">>, <<"b">>]},
- {<<"close">>, [<<"close">>]},
- {<<"keep-alive, upgrade">>, [<<"keep-alive">>, <<"upgrade">>]}
- ],
- [{V, fun() -> R = nonempty_list(V, fun token/2) end} || {V, R} <- Tests].
-
-media_range_list_test_() ->
- Tests = [
- {<<"audio/*; q=0.2, audio/basic">>, [
- {{<<"audio">>, <<"*">>, []}, 200, []},
- {{<<"audio">>, <<"basic">>, []}, 1000, []}
- ]},
- {<<"text/plain; q=0.5, text/html, "
- "text/x-dvi; q=0.8, text/x-c">>, [
- {{<<"text">>, <<"plain">>, []}, 500, []},
- {{<<"text">>, <<"html">>, []}, 1000, []},
- {{<<"text">>, <<"x-dvi">>, []}, 800, []},
- {{<<"text">>, <<"x-c">>, []}, 1000, []}
- ]},
- {<<"text/*, text/html, text/html;level=1, */*">>, [
- {{<<"text">>, <<"*">>, []}, 1000, []},
- {{<<"text">>, <<"html">>, []}, 1000, []},
- {{<<"text">>, <<"html">>, [{<<"level">>, <<"1">>}]}, 1000, []},
- {{<<"*">>, <<"*">>, []}, 1000, []}
- ]},
- {<<"text/*;q=0.3, text/html;q=0.7, text/html;level=1, "
- "text/html;level=2;q=0.4, */*;q=0.5">>, [
- {{<<"text">>, <<"*">>, []}, 300, []},
- {{<<"text">>, <<"html">>, []}, 700, []},
- {{<<"text">>, <<"html">>, [{<<"level">>, <<"1">>}]}, 1000, []},
- {{<<"text">>, <<"html">>, [{<<"level">>, <<"2">>}]}, 400, []},
- {{<<"*">>, <<"*">>, []}, 500, []}
- ]},
- {<<"text/html;level=1;quoted=\"hi hi hi\";"
- "q=0.123;standalone;complex=gits, text/plain">>, [
- {{<<"text">>, <<"html">>,
- [{<<"level">>, <<"1">>}, {<<"quoted">>, <<"hi hi hi">>}]}, 123,
- [<<"standalone">>, {<<"complex">>, <<"gits">>}]},
- {{<<"text">>, <<"plain">>, []}, 1000, []}
- ]},
- {<<"text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2">>, [
- {{<<"text">>, <<"html">>, []}, 1000, []},
- {{<<"image">>, <<"gif">>, []}, 1000, []},
- {{<<"image">>, <<"jpeg">>, []}, 1000, []},
- {{<<"*">>, <<"*">>, []}, 200, []},
- {{<<"*">>, <<"*">>, []}, 200, []}
- ]}
- ],
- [{V, fun() -> R = list(V, fun media_range/2) end} || {V, R} <- Tests].
-
-entity_tag_match_test_() ->
- Tests = [
- {<<"\"xyzzy\"">>, [{strong, <<"xyzzy">>}]},
- {<<"\"xyzzy\", W/\"r2d2xxxx\", \"c3piozzzz\"">>,
- [{strong, <<"xyzzy">>},
- {weak, <<"r2d2xxxx">>},
- {strong, <<"c3piozzzz">>}]},
- {<<"*">>, '*'}
- ],
- [{V, fun() -> R = entity_tag_match(V) end} || {V, R} <- Tests].
-
-http_date_test_() ->
- Tests = [
- {<<"Sun, 06 Nov 1994 08:49:37 GMT">>, {{1994, 11, 6}, {8, 49, 37}}},
- {<<"Sunday, 06-Nov-94 08:49:37 GMT">>, {{1994, 11, 6}, {8, 49, 37}}},
- {<<"Sun Nov 6 08:49:37 1994">>, {{1994, 11, 6}, {8, 49, 37}}}
- ],
- [{V, fun() -> R = http_date(V) end} || {V, R} <- Tests].
-
-rfc1123_date_test_() ->
- Tests = [
- {<<"Sun, 06 Nov 1994 08:49:37 GMT">>, {{1994, 11, 6}, {8, 49, 37}}}
- ],
- [{V, fun() -> R = rfc1123_date(V) end} || {V, R} <- Tests].
-
-rfc850_date_test_() ->
- Tests = [
- {<<"Sunday, 06-Nov-94 08:49:37 GMT">>, {{1994, 11, 6}, {8, 49, 37}}}
- ],
- [{V, fun() -> R = rfc850_date(V) end} || {V, R} <- Tests].
-
-asctime_date_test_() ->
- Tests = [
- {<<"Sun Nov 6 08:49:37 1994">>, {{1994, 11, 6}, {8, 49, 37}}}
- ],
- [{V, fun() -> R = asctime_date(V) end} || {V, R} <- Tests].
-
-content_type_test_() ->
- Tests = [
- {<<"text/plain; charset=iso-8859-4">>,
- {<<"text">>, <<"plain">>, [{<<"charset">>, <<"iso-8859-4">>}]}},
- {<<"multipart/form-data \t;Boundary=\"MultipartIsUgly\"">>,
- {<<"multipart">>, <<"form-data">>, [
- {<<"boundary">>, <<"MultipartIsUgly">>}
- ]}},
- {<<"foo/bar; one=FirstParam; two=SecondParam">>,
- {<<"foo">>, <<"bar">>, [
- {<<"one">>, <<"FirstParam">>},
- {<<"two">>, <<"SecondParam">>}
- ]}}
- ],
- [{V, fun () -> R = content_type(V) end} || {V, R} <- Tests].
-
-parameterized_tokens_test_() ->
- Tests = [
- {<<"foo">>, [{<<"foo">>, []}]},
- {<<"bar; baz=2">>, [{<<"bar">>, [{<<"baz">>, <<"2">>}]}]},
- {<<"bar; baz=2;bat">>, [{<<"bar">>, [{<<"baz">>, <<"2">>}, <<"bat">>]}]},
- {<<"bar; baz=2;bat=\"z=1,2;3\"">>, [{<<"bar">>, [{<<"baz">>, <<"2">>}, {<<"bat">>, <<"z=1,2;3">>}]}]},
- {<<"foo, bar; baz=2">>, [{<<"foo">>, []}, {<<"bar">>, [{<<"baz">>, <<"2">>}]}]}
- ],
- [{V, fun () -> R = parameterized_tokens(V) end} || {V, R} <- Tests].
-
-digits_test_() ->
- Tests = [
- {<<"42 ">>, 42},
- {<<"69\t">>, 69},
- {<<"1337">>, 1337}
- ],
- [{V, fun() -> R = digits(V) end} || {V, R} <- Tests].
-
-http_authorization_test_() ->
- Tests = [
- {<<"basic">>, <<"QWxsYWRpbjpvcGVuIHNlc2FtZQ==">>,
- {<<"basic">>, {<<"Alladin">>, <<"open sesame">>}}},
- {<<"basic">>, <<"dXNlcm5hbWU6">>,
- {<<"basic">>, {<<"username">>, <<>>}}},
- {<<"basic">>, <<"dXNlcm5hbWUK">>,
- {error, badarg}},
- {<<"basic">>, <<"_[]@#$%^&*()-AA==">>,
- {error, badarg}},
- {<<"basic">>, <<"dXNlcjpwYXNzCA==">>,
- {error, badarg}},
- {<<"bearer">>, <<" some_secret_key">>,
- {<<"bearer">>,<<"some_secret_key">>}}
- ],
- [{V, fun() -> R = authorization(V,T) end} || {T, V, R} <- Tests].
-
-http_range_test_() ->
- Tests = [
- {<<"bytes=1-20">>,
- {<<"bytes">>, [{1, 20}]}},
- {<<"bytes=-100">>,
- {<<"bytes">>, [-100]}},
- {<<"bytes=1-">>,
- {<<"bytes">>, [{1, infinity}]}},
- {<<"bytes=1-20,30-40,50-">>,
- {<<"bytes">>, [{1, 20}, {30, 40}, {50, infinity}]}},
- {<<"bytes = 1 - 20 , 50 - , - 300 ">>,
- {<<"bytes">>, [{1, 20}, {50, infinity}, -300]}},
- {<<"bytes=1-20,-500,30-40">>,
- {<<"bytes">>, [{1, 20}, -500, {30, 40}]}},
- {<<"test=1-20,-500,30-40">>,
- {<<"test">>, [{1, 20}, -500, {30, 40}]}},
- {<<"bytes=-">>,
- {error, badarg}},
- {<<"bytes=-30,-">>,
- {error, badarg}}
- ],
- [fun() -> R = range(V) end ||{V, R} <- Tests].
--endif.
diff --git a/src/cowboy_protocol.erl b/src/cowboy_protocol.erl
index e469bc7..b1cdc3a 100644
--- a/src/cowboy_protocol.erl
+++ b/src/cowboy_protocol.erl
@@ -55,6 +55,7 @@
}).
-include_lib("cowlib/include/cow_inline.hrl").
+-include_lib("cowlib/include/cow_parse.hrl").
%% API.
@@ -264,13 +265,12 @@ match_colon(<< _, Rest/bits >>, N) ->
match_colon(_, _) ->
nomatch.
+parse_hd_name(<< $:, Rest/bits >>, S, M, P, Q, V, H, SoFar) ->
+ parse_hd_before_value(Rest, S, M, P, Q, V, H, SoFar);
+parse_hd_name(<< C, Rest/bits >>, S, M, P, Q, V, H, SoFar) when ?IS_WS(C) ->
+ parse_hd_name_ws(Rest, S, M, P, Q, V, H, SoFar);
parse_hd_name(<< C, Rest/bits >>, S, M, P, Q, V, H, SoFar) ->
- case C of
- $: -> parse_hd_before_value(Rest, S, M, P, Q, V, H, SoFar);
- $\s -> parse_hd_name_ws(Rest, S, M, P, Q, V, H, SoFar);
- $\t -> parse_hd_name_ws(Rest, S, M, P, Q, V, H, SoFar);
- ?INLINE_LOWERCASE(parse_hd_name, Rest, S, M, P, Q, V, H, SoFar)
- end.
+ ?LOWER(parse_hd_name, Rest, S, M, P, Q, V, H, SoFar).
parse_hd_name_ws(<< C, Rest/bits >>, S, M, P, Q, V, H, Name) ->
case C of
@@ -348,7 +348,7 @@ parse_hd_value(<< $\r, Rest/bits >>, S, M, P, Q, V, Headers, Name, SoFar) ->
parse_hd_value(Rest2, S, M, P, Q, V, Headers, Name,
<< SoFar/binary, C >>);
<< $\n, Rest2/bits >> ->
- parse_header(Rest2, S, M, P, Q, V, [{Name, SoFar}|Headers])
+ parse_header(Rest2, S, M, P, Q, V, [{Name, clean_value_ws_end(SoFar, byte_size(SoFar) - 1)}|Headers])
end;
parse_hd_value(<< C, Rest/bits >>, S, M, P, Q, V, H, N, SoFar) ->
parse_hd_value(Rest, S, M, P, Q, V, H, N, << SoFar/binary, C >>);
@@ -358,6 +358,42 @@ parse_hd_value(<<>>, State=#state{max_header_value_length=MaxLength},
parse_hd_value(<<>>, S, M, P, Q, V, H, N, SoFar) ->
wait_hd_value(<<>>, S, M, P, Q, V, H, N, SoFar).
+clean_value_ws_end(_, -1) ->
+ <<>>;
+clean_value_ws_end(Value, N) ->
+ case binary:at(Value, N) of
+ $\s -> clean_value_ws_end(Value, N - 1);
+ $\t -> clean_value_ws_end(Value, N - 1);
+ _ ->
+ S = N + 1,
+ << Value2:S/binary, _/bits >> = Value,
+ Value2
+ end.
+
+-ifdef(TEST).
+clean_value_ws_end_test_() ->
+ Tests = [
+ {<<>>, <<>>},
+ {<<" ">>, <<>>},
+ {<<"text/*;q=0.3, text/html;q=0.7, text/html;level=1, "
+ "text/html;level=2;q=0.4, */*;q=0.5 \t \t ">>,
+ <<"text/*;q=0.3, text/html;q=0.7, text/html;level=1, "
+ "text/html;level=2;q=0.4, */*;q=0.5">>}
+ ],
+ [{V, fun() -> R = clean_value_ws_end(V, byte_size(V) - 1) end} || {V, R} <- Tests].
+-endif.
+
+-ifdef(PERF).
+horse_clean_value_ws_end() ->
+ horse:repeat(200000,
+ clean_value_ws_end(
+ <<"text/*;q=0.3, text/html;q=0.7, text/html;level=1, "
+ "text/html;level=2;q=0.4, */*;q=0.5 ">>,
+ byte_size(<<"text/*;q=0.3, text/html;q=0.7, text/html;level=1, "
+ "text/html;level=2;q=0.4, */*;q=0.5 ">>) - 1)
+ ).
+-endif.
+
request(B, State=#state{transport=Transport}, M, P, Q, Version, Headers) ->
case lists:keyfind(<<"host">>, 1, Headers) of
false when Version =:= 'HTTP/1.1' ->
@@ -393,9 +429,7 @@ parse_host(<< $:, Rest/bits >>, false, Acc) ->
parse_host(<< $], Rest/bits >>, true, Acc) ->
parse_host(Rest, false, << Acc/binary, $] >>);
parse_host(<< C, Rest/bits >>, E, Acc) ->
- case C of
- ?INLINE_LOWERCASE(parse_host, Rest, E, Acc)
- end.
+ ?LOWER(parse_host, Rest, E, Acc).
%% End of request parsing.
%%
diff --git a/src/cowboy_req.erl b/src/cowboy_req.erl
index a197110..5e23a7b 100644
--- a/src/cowboy_req.erl
+++ b/src/cowboy_req.erl
@@ -289,91 +289,43 @@ headers(Req) ->
-spec parse_header(binary(), Req) -> any() when Req::req().
parse_header(Name = <<"content-length">>, Req) ->
- parse_header(Name, Req, 0);
+ parse_header(Name, Req, 0, fun cow_http_hd:parse_content_length/1);
parse_header(Name = <<"cookie">>, Req) ->
- parse_header(Name, Req, []);
+ parse_header(Name, Req, [], fun cow_cookie:parse_cookie/1);
parse_header(Name = <<"transfer-encoding">>, Req) ->
- parse_header(Name, Req, [<<"identity">>]);
+ parse_header(Name, Req, [<<"identity">>], fun cow_http_hd:parse_transfer_encoding/1);
parse_header(Name, Req) ->
parse_header(Name, Req, undefined).
-spec parse_header(binary(), Req, any()) -> any() when Req::req().
-parse_header(Name = <<"accept">>, Req, Default) ->
- parse_header(Name, Req, Default, fun (Value) ->
- cowboy_http:list(Value, fun cowboy_http:media_range/2) end);
-parse_header(Name = <<"accept-charset">>, Req, Default) ->
- parse_header(Name, Req, Default, fun (Value) ->
- cowboy_http:nonempty_list(Value, fun cowboy_http:conneg/2) end);
-parse_header(Name = <<"accept-encoding">>, Req, Default) ->
- parse_header(Name, Req, Default, fun (Value) ->
- cowboy_http:list(Value, fun cowboy_http:conneg/2) end);
-parse_header(Name = <<"accept-language">>, Req, Default) ->
- parse_header(Name, Req, Default, fun (Value) ->
- cowboy_http:nonempty_list(Value, fun cowboy_http:language_range/2) end);
-parse_header(Name = <<"authorization">>, Req, Default) ->
- parse_header(Name, Req, Default, fun (Value) ->
- cowboy_http:token_ci(Value, fun cowboy_http:authorization/2) end);
-parse_header(Name = <<"connection">>, Req, Default) ->
- case header(Name, Req) of
- undefined -> Default;
- Value -> cow_http_hd:parse_connection(Value)
- end;
-parse_header(Name = <<"content-length">>, Req, Default) ->
- case header(Name, Req) of
- undefined -> Default;
- Value -> cow_http_hd:parse_content_length(Value)
- end;
-parse_header(Name = <<"content-type">>, Req, Default) ->
- parse_header(Name, Req, Default, fun cowboy_http:content_type/1);
-parse_header(Name = <<"cookie">>, Req, Default) ->
- case header(Name, Req) of
- undefined -> Default;
- %% Flash player incorrectly sends an empty Cookie header.
- <<>> -> Default;
- Value -> cow_cookie:parse_cookie(Value)
- end;
-parse_header(Name = <<"expect">>, Req, Default) ->
- parse_header(Name, Req, Default, fun (Value) ->
- cowboy_http:nonempty_list(Value, fun cowboy_http:expectation/2) end);
-parse_header(Name, Req, Default)
- when Name =:= <<"if-match">>;
- Name =:= <<"if-none-match">> ->
- parse_header(Name, Req, Default, fun cowboy_http:entity_tag_match/1);
-parse_header(Name, Req, Default)
- when Name =:= <<"if-modified-since">>;
- Name =:= <<"if-unmodified-since">> ->
- parse_header(Name, Req, Default, fun cowboy_http:http_date/1);
-parse_header(Name = <<"range">>, Req, Default) ->
- parse_header(Name, Req, Default, fun cowboy_http:range/1);
-parse_header(Name, Req, Default)
- when Name =:= <<"sec-websocket-protocol">>;
- Name =:= <<"x-forwarded-for">> ->
- parse_header(Name, Req, Default, fun (Value) ->
- cowboy_http:nonempty_list(Value, fun cowboy_http:token/2) end);
-parse_header(Name = <<"transfer-encoding">>, Req, Default) ->
- case header(Name, Req) of
- undefined -> Default;
- Value -> cow_http_hd:parse_transfer_encoding(Value)
- end;
-%% @todo Product version.
-parse_header(Name = <<"upgrade">>, Req, Default) ->
- parse_header(Name, Req, Default, fun (Value) ->
- cowboy_http:nonempty_list(Value, fun cowboy_http:token_ci/2) end);
-parse_header(Name = <<"sec-websocket-extensions">>, Req, Default) ->
- parse_header(Name, Req, Default, fun cowboy_http:parameterized_tokens/1).
-
-%% @todo Remove this function when everything moved to cowlib.
+parse_header(Name, Req, Default) ->
+ parse_header(Name, Req, Default, parse_header_fun(Name)).
+
+parse_header_fun(<<"accept">>) -> fun cow_http_hd:parse_accept/1;
+parse_header_fun(<<"accept-charset">>) -> fun cow_http_hd:parse_accept_charset/1;
+parse_header_fun(<<"accept-encoding">>) -> fun cow_http_hd:parse_accept_encoding/1;
+parse_header_fun(<<"accept-language">>) -> fun cow_http_hd:parse_accept_language/1;
+parse_header_fun(<<"authorization">>) -> fun cow_http_hd:parse_authorization/1;
+parse_header_fun(<<"connection">>) -> fun cow_http_hd:parse_connection/1;
+parse_header_fun(<<"content-length">>) -> fun cow_http_hd:parse_content_length/1;
+parse_header_fun(<<"content-type">>) -> fun cow_http_hd:parse_content_type/1;
+parse_header_fun(<<"cookie">>) -> fun cow_cookie:parse_cookie/1;
+parse_header_fun(<<"expect">>) -> fun cow_http_hd:parse_expect/1;
+parse_header_fun(<<"if-match">>) -> fun cow_http_hd:parse_if_match/1;
+parse_header_fun(<<"if-modified-since">>) -> fun cow_http_hd:parse_if_modified_since/1;
+parse_header_fun(<<"if-none-match">>) -> fun cow_http_hd:parse_if_none_match/1;
+parse_header_fun(<<"if-unmodified-since">>) -> fun cow_http_hd:parse_if_unmodified_since/1;
+parse_header_fun(<<"range">>) -> fun cow_http_hd:parse_range/1;
+parse_header_fun(<<"sec-websocket-extensions">>) -> fun cow_http_hd:parse_sec_websocket_extensions/1;
+parse_header_fun(<<"sec-websocket-protocol">>) -> fun cow_http_hd:parse_sec_websocket_protocol_req/1;
+parse_header_fun(<<"transfer-encoding">>) -> fun cow_http_hd:parse_transfer_encoding/1;
+parse_header_fun(<<"upgrade">>) -> fun cow_http_hd:parse_upgrade/1;
+parse_header_fun(<<"x-forwarded-for">>) -> fun cow_http_hd:parse_x_forwarded_for/1.
+
parse_header(Name, Req, Default, ParseFun) ->
case header(Name, Req) of
- undefined ->
- Default;
- Value ->
- case ParseFun(Value) of
- {error, badarg} ->
- error(badarg);
- ParsedValue ->
- ParsedValue
- end
+ undefined -> Default;
+ Value -> ParseFun(Value)
end.
-spec parse_cookies(req()) -> [{binary(), binary()}].
@@ -443,7 +395,7 @@ body(Req=#http_req{body_state=waiting}, Opts) ->
%% Initialize body streaming state.
CFun = case lists:keyfind(content_decode, 1, Opts) of
false ->
- fun cowboy_http:ce_identity/1;
+ fun body_content_decode_identity/1;
{_, CFun0} ->
CFun0
end,
@@ -484,6 +436,10 @@ body(Req, Opts) ->
end,
body_loop(Req, ReadTimeout, ReadLen, ChunkLen, <<>>).
+%% Default identity function for content decoding.
+%% @todo Move into cowlib when more content decode functions get implemented.
+body_content_decode_identity(Data) -> Data.
+
body_loop(Req=#http_req{buffer=Buffer, body_state={stream, Length, _, _, _}},
ReadTimeout, ReadLength, ChunkLength, Acc) ->
{Tag, Res, Req2} = case Buffer of
@@ -906,6 +862,8 @@ maybe_reply(Stacktrace, Req) ->
ok
end.
+do_maybe_reply([{erlang, binary_to_integer, _, _}, {cow_http_hd, parse_content_length, _, _}|_], Req) ->
+ cowboy_req:reply(400, Req);
do_maybe_reply([{cow_http_hd, _, _, _}|_], Req) ->
cowboy_req:reply(400, Req);
do_maybe_reply(_, Req) ->
diff --git a/src/cowboy_rest.erl b/src/cowboy_rest.erl
index dea47d8..b894354 100644
--- a/src/cowboy_rest.erl
+++ b/src/cowboy_rest.erl
@@ -234,7 +234,7 @@ content_types_provided(Req, State) ->
normalize_content_types({ContentType, Callback})
when is_binary(ContentType) ->
- {cowboy_http:content_type(ContentType), Callback};
+ {cow_http_hd:parse_content_type(ContentType), Callback};
normalize_content_types(Normalized) ->
Normalized.
@@ -896,7 +896,7 @@ generate_etag(Req, State=#state{etag=undefined}) ->
no_call ->
{undefined, Req, State#state{etag=no_call}};
{Etag, Req2, HandlerState} when is_binary(Etag) ->
- [Etag2] = cowboy_http:entity_tag_match(Etag),
+ Etag2 = cow_http_hd:parse_etag(Etag),
{Etag2, Req2, State#state{handler_state=HandlerState, etag=Etag2}};
{Etag, Req2, HandlerState} ->
{Etag, Req2, State#state{handler_state=HandlerState, etag=Etag}}
diff --git a/src/cowboy_router.erl b/src/cowboy_router.erl
index f3fde32..b806da5 100644
--- a/src/cowboy_router.erl
+++ b/src/cowboy_router.erl
@@ -425,6 +425,8 @@ split_host_test_() ->
[<<"eu">>, <<"ninenines">>, <<"cowboy">>]},
{<<"ninenines.eu">>,
[<<"eu">>, <<"ninenines">>]},
+ {<<"ninenines.eu.">>,
+ [<<"eu">>, <<"ninenines">>]},
{<<"a.b.c.d.e.f.g.h.i.j.k.l.m.n.o.p.q.r.s.t.u.v.w.x.y.z">>,
[<<"z">>, <<"y">>, <<"x">>, <<"w">>, <<"v">>, <<"u">>, <<"t">>,
<<"s">>, <<"r">>, <<"q">>, <<"p">>, <<"o">>, <<"n">>, <<"m">>,
diff --git a/src/cowboy_spdy.erl b/src/cowboy_spdy.erl
index 656f414..2628ab5 100644
--- a/src/cowboy_spdy.erl
+++ b/src/cowboy_spdy.erl
@@ -387,7 +387,7 @@ delete_child(Pid, State=#state{children=Children}) ->
-> ok.
request_init(FakeSocket, Peer, OnResponse,
Env, Middlewares, Method, Host, Path, Version, Headers) ->
- {Host2, Port} = cow_http:parse_fullhost(Host),
+ {Host2, Port} = cow_http_hd:parse_host(Host),
{Path2, Qs} = cow_http:parse_fullpath(Path),
Version2 = cow_http:parse_version(Version),
Req = cowboy_req:new(FakeSocket, ?MODULE, Peer,
diff --git a/src/cowboy_websocket.erl b/src/cowboy_websocket.erl
index 36190a5..681470f 100644
--- a/src/cowboy_websocket.erl
+++ b/src/cowboy_websocket.erl
@@ -20,21 +20,8 @@
-export([upgrade/6]).
-export([handler_loop/4]).
--type close_code() :: 1000..4999.
--export_type([close_code/0]).
-
--type frame() :: close | ping | pong
- | {text | binary | close | ping | pong, iodata()}
- | {close, close_code(), iodata()}.
--export_type([frame/0]).
-
--type opcode() :: 0 | 1 | 2 | 8 | 9 | 10.
--type mask_key() :: 0..16#ffffffff.
--type frag_state() :: undefined
- | {nofin, opcode(), binary()} | {fin, opcode(), binary()}.
--type rsv() :: << _:3 >>.
-type terminate_reason() :: normal | stop | timeout
- | remote | {remote, close_code(), binary()}
+ | remote | {remote, cow_ws:close_code(), binary()}
| {error, badencoding | badframe | closed | atom()}
| {crash, error | exit | throw, any()}.
@@ -47,15 +34,15 @@
-callback websocket_handle({text | binary | ping | pong, binary()}, Req, State)
-> {ok, Req, State}
| {ok, Req, State, hibernate}
- | {reply, frame() | [frame()], Req, State}
- | {reply, frame() | [frame()], Req, State, hibernate}
+ | {reply, cow_ws:frame() | [cow_ws:frame()], Req, State}
+ | {reply, cow_ws:frame() | [cow_ws:frame()], Req, State, hibernate}
| {stop, Req, State}
when Req::cowboy_req:req(), State::any().
-callback websocket_info(any(), Req, State)
-> {ok, Req, State}
| {ok, Req, State, hibernate}
- | {reply, frame() | [frame()], Req, State}
- | {reply, frame() | [frame()], Req, State, hibernate}
+ | {reply, cow_ws:frame() | [cow_ws:frame()], Req, State}
+ | {reply, cow_ws:frame() | [cow_ws:frame()], Req, State, hibernate}
| {stop, Req, State}
when Req::cowboy_req:req(), State::any().
%% @todo optional -callback terminate(terminate_reason(), cowboy_req:req(), state()) -> ok.
@@ -70,11 +57,11 @@
timeout_ref = undefined :: undefined | reference(),
messages = undefined :: undefined | {atom(), atom(), atom()},
hibernate = false :: boolean(),
- frag_state = undefined :: frag_state(),
+ frag_state = undefined :: cow_ws:frag_state(),
+ frag_buffer = <<>> :: binary(),
utf8_state = <<>> :: binary(),
- deflate_frame = false :: boolean(),
- inflate_state :: undefined | port(),
- deflate_state :: undefined | port()
+ recv_extensions = #{} :: map(),
+ send_extensions = #{} :: map()
}).
-spec upgrade(Req, Env, module(), any(), timeout(), run | hibernate)
@@ -135,9 +122,8 @@ websocket_extensions(State, Req) ->
% the zlib headers.
ok = zlib:deflateInit(Deflate, best_compression, deflated, -15, 8, default),
{ok, State#state{
- deflate_frame = true,
- inflate_state = Inflate,
- deflate_state = Deflate
+ recv_extensions = #{deflate_frame => Inflate},
+ send_extensions = #{deflate_frame => Deflate}
}, cowboy_req:set_meta(websocket_compress, true, Req)};
_ ->
{ok, State, cowboy_req:set_meta(websocket_compress, false, Req)}
@@ -149,16 +135,16 @@ websocket_extensions(State, Req) ->
| {suspend, module(), atom(), [any()]}
when Req::cowboy_req:req().
websocket_handshake(State=#state{
- transport=Transport, key=Key, deflate_frame=DeflateFrame},
+ transport=Transport, key=Key, recv_extensions=Extensions},
Req, HandlerState) ->
Challenge = base64:encode(crypto:hash(sha,
<< Key/binary, "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" >>)),
- Extensions = case DeflateFrame of
- false -> [];
- true -> [{<<"sec-websocket-extensions">>, <<"x-webkit-deflate-frame">>}]
+ ExtHeader = case Extensions of
+ #{deflate_frame := _} -> [{<<"sec-websocket-extensions">>, <<"x-webkit-deflate-frame">>}];
+ _ -> []
end,
Req2 = cowboy_req:upgrade_reply(101, [{<<"upgrade">>, <<"websocket">>},
- {<<"sec-websocket-accept">>, Challenge}|Extensions], Req),
+ {<<"sec-websocket-accept">>, Challenge}|ExtHeader], Req),
%% Flush the resp_sent message before moving on.
receive {cowboy_req, resp_sent} -> ok after 0 -> ok end,
State2 = handler_loop_timeout(State),
@@ -213,299 +199,59 @@ handler_loop(State=#state{socket=Socket, messages={OK, Closed, Error},
SoFar, websocket_info, Message, fun handler_before_loop/4)
end.
-%% All frames passing through this function are considered valid,
-%% with the only exception of text and close frames with a payload
-%% which may still contain errors.
-spec websocket_data(#state{}, Req, any(), binary())
-> {ok, Req, cowboy_middleware:env()}
| {suspend, module(), atom(), [any()]}
when Req::cowboy_req:req().
-%% RSV bits MUST be 0 unless an extension is negotiated
-%% that defines meanings for non-zero values.
-websocket_data(State, Req, HandlerState, << _:1, Rsv:3, _/bits >>)
- when Rsv =/= 0, State#state.deflate_frame =:= false ->
- websocket_close(State, Req, HandlerState, {error, badframe});
-%% Invalid opcode. Note that these opcodes may be used by extensions.
-websocket_data(State, Req, HandlerState, << _:4, Opcode:4, _/bits >>)
- when Opcode > 2, Opcode =/= 8, Opcode =/= 9, Opcode =/= 10 ->
- websocket_close(State, Req, HandlerState, {error, badframe});
-%% Control frames MUST NOT be fragmented.
-websocket_data(State, Req, HandlerState, << 0:1, _:3, Opcode:4, _/bits >>)
- when Opcode >= 8 ->
- websocket_close(State, Req, HandlerState, {error, badframe});
-%% A frame MUST NOT use the zero opcode unless fragmentation was initiated.
-websocket_data(State=#state{frag_state=undefined}, Req, HandlerState,
- << _:4, 0:4, _/bits >>) ->
- websocket_close(State, Req, HandlerState, {error, badframe});
-%% Non-control opcode when expecting control message or next fragment.
-websocket_data(State=#state{frag_state={nofin, _, _}}, Req, HandlerState,
- << _:4, Opcode:4, _/bits >>)
- when Opcode =/= 0, Opcode < 8 ->
- websocket_close(State, Req, HandlerState, {error, badframe});
-%% Close control frame length MUST be 0 or >= 2.
-websocket_data(State, Req, HandlerState, << _:4, 8:4, _:1, 1:7, _/bits >>) ->
- websocket_close(State, Req, HandlerState, {error, badframe});
-%% Close control frame with incomplete close code. Need more data.
-websocket_data(State, Req, HandlerState,
- Data = << _:4, 8:4, 1:1, Len:7, _/bits >>)
- when Len > 1, byte_size(Data) < 8 ->
- handler_before_loop(State, Req, HandlerState, Data);
-%% 7 bits payload length.
-websocket_data(State, Req, HandlerState, << Fin:1, Rsv:3/bits, Opcode:4, 1:1,
- Len:7, MaskKey:32, Rest/bits >>)
- when Len < 126 ->
- websocket_data(State, Req, HandlerState,
- Opcode, Len, MaskKey, Rest, Rsv, Fin);
-%% 16 bits payload length.
-websocket_data(State, Req, HandlerState, << Fin:1, Rsv:3/bits, Opcode:4, 1:1,
- 126:7, Len:16, MaskKey:32, Rest/bits >>)
- when Len > 125, Opcode < 8 ->
- websocket_data(State, Req, HandlerState,
- Opcode, Len, MaskKey, Rest, Rsv, Fin);
-%% 63 bits payload length.
-websocket_data(State, Req, HandlerState, << Fin:1, Rsv:3/bits, Opcode:4, 1:1,
- 127:7, 0:1, Len:63, MaskKey:32, Rest/bits >>)
- when Len > 16#ffff, Opcode < 8 ->
- websocket_data(State, Req, HandlerState,
- Opcode, Len, MaskKey, Rest, Rsv, Fin);
-%% When payload length is over 63 bits, the most significant bit MUST be 0.
-websocket_data(State, Req, HandlerState, << _:8, 1:1, 127:7, 1:1, _:7, _/bits >>) ->
- websocket_close(State, Req, HandlerState, {error, badframe});
-%% All frames sent from the client to the server are masked.
-websocket_data(State, Req, HandlerState, << _:8, 0:1, _/bits >>) ->
- websocket_close(State, Req, HandlerState, {error, badframe});
-%% For the next two clauses, it can be one of the following:
-%%
-%% * The minimal number of bytes MUST be used to encode the length
-%% * All control frames MUST have a payload length of 125 bytes or less
-websocket_data(State, Req, HandlerState, << _:9, 126:7, _:48, _/bits >>) ->
- websocket_close(State, Req, HandlerState, {error, badframe});
-websocket_data(State, Req, HandlerState, << _:9, 127:7, _:96, _/bits >>) ->
- websocket_close(State, Req, HandlerState, {error, badframe});
-%% Need more data.
-websocket_data(State, Req, HandlerState, Data) ->
- handler_before_loop(State, Req, HandlerState, Data).
-
-%% Initialize or update fragmentation state.
--spec websocket_data(#state{}, Req, any(),
- opcode(), non_neg_integer(), mask_key(), binary(), rsv(), 0 | 1)
- -> {ok, Req, cowboy_middleware:env()}
- | {suspend, module(), atom(), [any()]}
- when Req::cowboy_req:req().
-%% The opcode is only included in the first frame fragment.
-websocket_data(State=#state{frag_state=undefined}, Req, HandlerState,
- Opcode, Len, MaskKey, Data, Rsv, 0) ->
- websocket_payload(State#state{frag_state={nofin, Opcode, <<>>}},
- Req, HandlerState, 0, Len, MaskKey, <<>>, 0, Data, Rsv);
-%% Subsequent frame fragments.
-websocket_data(State=#state{frag_state={nofin, _, _}}, Req, HandlerState,
- 0, Len, MaskKey, Data, Rsv, 0) ->
- websocket_payload(State, Req, HandlerState,
- 0, Len, MaskKey, <<>>, 0, Data, Rsv);
-%% Final frame fragment.
-websocket_data(State=#state{frag_state={nofin, Opcode, SoFar}},
- Req, HandlerState, 0, Len, MaskKey, Data, Rsv, 1) ->
- websocket_payload(State#state{frag_state={fin, Opcode, SoFar}},
- Req, HandlerState, 0, Len, MaskKey, <<>>, 0, Data, Rsv);
-%% Unfragmented frame.
-websocket_data(State, Req, HandlerState, Opcode, Len, MaskKey, Data, Rsv, 1) ->
- websocket_payload(State, Req, HandlerState,
- Opcode, Len, MaskKey, <<>>, 0, Data, Rsv).
-
--spec websocket_payload(#state{}, Req, any(),
- opcode(), non_neg_integer(), mask_key(), binary(), non_neg_integer(),
- binary(), rsv())
- -> {ok, Req, cowboy_middleware:env()}
- | {suspend, module(), atom(), [any()]}
- when Req::cowboy_req:req().
-%% Close control frames with a payload MUST contain a valid close code.
-websocket_payload(State, Req, HandlerState,
- Opcode=8, Len, MaskKey, <<>>, 0,
- << MaskedCode:2/binary, Rest/bits >>, Rsv) ->
- Unmasked = << Code:16 >> = websocket_unmask(MaskedCode, MaskKey, <<>>),
- if Code < 1000; Code =:= 1004; Code =:= 1005; Code =:= 1006;
- (Code > 1011) and (Code < 3000); Code > 4999 ->
+websocket_data(State=#state{frag_state=FragState, recv_extensions=Extensions}, Req, HandlerState, Data) ->
+ case cow_ws:parse_header(Data, Extensions, FragState) of
+ %% All frames sent from the client to the server are masked.
+ {_, _, _, _, undefined, _} ->
websocket_close(State, Req, HandlerState, {error, badframe});
- true ->
- websocket_payload(State, Req, HandlerState,
- Opcode, Len - 2, MaskKey, Unmasked, byte_size(MaskedCode),
- Rest, Rsv)
- end;
-%% Text frames and close control frames MUST have a payload that is valid UTF-8.
-websocket_payload(State=#state{utf8_state=Incomplete},
- Req, HandlerState, Opcode, Len, MaskKey, Unmasked, UnmaskedLen,
- Data, Rsv)
- when (byte_size(Data) < Len) andalso ((Opcode =:= 1) orelse
- ((Opcode =:= 8) andalso (Unmasked =/= <<>>))) ->
- Unmasked2 = websocket_unmask(Data,
- rotate_mask_key(MaskKey, UnmaskedLen), <<>>),
- {Unmasked3, State2} = websocket_inflate_frame(Unmasked2, Rsv, false, State),
- case is_utf8(<< Incomplete/binary, Unmasked3/binary >>) of
- false ->
- websocket_close(State2, Req, HandlerState, {error, badencoding});
- Utf8State ->
- websocket_payload_loop(State2#state{utf8_state=Utf8State},
- Req, HandlerState, Opcode, Len - byte_size(Data), MaskKey,
- << Unmasked/binary, Unmasked3/binary >>,
- UnmaskedLen + byte_size(Data), Rsv)
- end;
-websocket_payload(State=#state{utf8_state=Incomplete},
- Req, HandlerState, Opcode, Len, MaskKey, Unmasked, UnmaskedLen,
- Data, Rsv)
- when Opcode =:= 1; (Opcode =:= 8) and (Unmasked =/= <<>>) ->
- << End:Len/binary, Rest/bits >> = Data,
- Unmasked2 = websocket_unmask(End,
- rotate_mask_key(MaskKey, UnmaskedLen), <<>>),
- {Unmasked3, State2} = websocket_inflate_frame(Unmasked2, Rsv, true, State),
- case is_utf8(<< Incomplete/binary, Unmasked3/binary >>) of
- <<>> ->
- websocket_dispatch(State2#state{utf8_state= <<>>},
- Req, HandlerState, Rest, Opcode,
- << Unmasked/binary, Unmasked3/binary >>);
- _ ->
- websocket_close(State2, Req, HandlerState, {error, badencoding})
- end;
-%% Fragmented text frames may cut payload in the middle of UTF-8 codepoints.
-websocket_payload(State=#state{frag_state={_, 1, _}, utf8_state=Incomplete},
- Req, HandlerState, Opcode=0, Len, MaskKey, Unmasked, UnmaskedLen,
- Data, Rsv)
- when byte_size(Data) < Len ->
- Unmasked2 = websocket_unmask(Data,
- rotate_mask_key(MaskKey, UnmaskedLen), <<>>),
- {Unmasked3, State2} = websocket_inflate_frame(Unmasked2, Rsv, false, State),
- case is_utf8(<< Incomplete/binary, Unmasked3/binary >>) of
- false ->
- websocket_close(State2, Req, HandlerState, {error, badencoding});
- Utf8State ->
- websocket_payload_loop(State2#state{utf8_state=Utf8State},
- Req, HandlerState, Opcode, Len - byte_size(Data), MaskKey,
- << Unmasked/binary, Unmasked3/binary >>,
- UnmaskedLen + byte_size(Data), Rsv)
- end;
-websocket_payload(State=#state{frag_state={Fin, 1, _}, utf8_state=Incomplete},
- Req, HandlerState, Opcode=0, Len, MaskKey, Unmasked, UnmaskedLen,
- Data, Rsv) ->
- << End:Len/binary, Rest/bits >> = Data,
- Unmasked2 = websocket_unmask(End,
- rotate_mask_key(MaskKey, UnmaskedLen), <<>>),
- {Unmasked3, State2} = websocket_inflate_frame(Unmasked2, Rsv, Fin =:= fin, State),
- case is_utf8(<< Incomplete/binary, Unmasked3/binary >>) of
- <<>> ->
- websocket_dispatch(State2#state{utf8_state= <<>>},
- Req, HandlerState, Rest, Opcode,
- << Unmasked/binary, Unmasked3/binary >>);
- Utf8State when is_binary(Utf8State), Fin =:= nofin ->
- websocket_dispatch(State2#state{utf8_state=Utf8State},
- Req, HandlerState, Rest, Opcode,
- << Unmasked/binary, Unmasked3/binary >>);
- _ ->
- websocket_close(State, Req, HandlerState, {error, badencoding})
- end;
-%% Other frames have a binary payload.
-websocket_payload(State, Req, HandlerState,
- Opcode, Len, MaskKey, Unmasked, UnmaskedLen, Data, Rsv)
- when byte_size(Data) < Len ->
- Unmasked2 = websocket_unmask(Data,
- rotate_mask_key(MaskKey, UnmaskedLen), <<>>),
- {Unmasked3, State2} = websocket_inflate_frame(Unmasked2, Rsv, false, State),
- websocket_payload_loop(State2, Req, HandlerState,
- Opcode, Len - byte_size(Data), MaskKey,
- << Unmasked/binary, Unmasked3/binary >>, UnmaskedLen + byte_size(Data),
- Rsv);
-websocket_payload(State, Req, HandlerState,
- Opcode, Len, MaskKey, Unmasked, UnmaskedLen, Data, Rsv) ->
- << End:Len/binary, Rest/bits >> = Data,
- Unmasked2 = websocket_unmask(End,
- rotate_mask_key(MaskKey, UnmaskedLen), <<>>),
- {Unmasked3, State2} = websocket_inflate_frame(Unmasked2, Rsv, true, State),
- websocket_dispatch(State2, Req, HandlerState, Rest, Opcode,
- << Unmasked/binary, Unmasked3/binary >>).
-
--spec websocket_inflate_frame(binary(), rsv(), boolean(), #state{}) ->
- {binary(), #state{}}.
-websocket_inflate_frame(Data, << Rsv1:1, _:2 >>, _,
- #state{deflate_frame = DeflateFrame} = State)
- when DeflateFrame =:= false orelse Rsv1 =:= 0 ->
- {Data, State};
-websocket_inflate_frame(Data, << 1:1, _:2 >>, false, State) ->
- Result = zlib:inflate(State#state.inflate_state, Data),
- {iolist_to_binary(Result), State};
-websocket_inflate_frame(Data, << 1:1, _:2 >>, true, State) ->
- Result = zlib:inflate(State#state.inflate_state,
- << Data/binary, 0:8, 0:8, 255:8, 255:8 >>),
- {iolist_to_binary(Result), State}.
-
--spec websocket_unmask(B, mask_key(), B) -> B when B::binary().
-websocket_unmask(<<>>, _, Unmasked) ->
- Unmasked;
-websocket_unmask(<< O:32, Rest/bits >>, MaskKey, Acc) ->
- T = O bxor MaskKey,
- websocket_unmask(Rest, MaskKey, << Acc/binary, T:32 >>);
-websocket_unmask(<< O:24 >>, MaskKey, Acc) ->
- << MaskKey2:24, _:8 >> = << MaskKey:32 >>,
- T = O bxor MaskKey2,
- << Acc/binary, T:24 >>;
-websocket_unmask(<< O:16 >>, MaskKey, Acc) ->
- << MaskKey2:16, _:16 >> = << MaskKey:32 >>,
- T = O bxor MaskKey2,
- << Acc/binary, T:16 >>;
-websocket_unmask(<< O:8 >>, MaskKey, Acc) ->
- << MaskKey2:8, _:24 >> = << MaskKey:32 >>,
- T = O bxor MaskKey2,
- << Acc/binary, T:8 >>.
+ %% No payload.
+ {Type, FragState2, _, 0, _, Rest} ->
+ websocket_dispatch(State#state{frag_state=FragState2}, Req, HandlerState, Type, <<>>, undefined, Rest);
+ {Type, FragState2, Rsv, Len, MaskKey, Rest} ->
+ websocket_payload(State#state{frag_state=FragState2}, Req, HandlerState, Type, Len, MaskKey, Rsv, Rest);
+ more ->
+ handler_before_loop(State, Req, HandlerState, Data);
+ error ->
+ websocket_close(State, Req, HandlerState, {error, badframe})
+ end.
-%% Because we unmask on the fly we need to continue from the right mask byte.
--spec rotate_mask_key(mask_key(), non_neg_integer()) -> mask_key().
-rotate_mask_key(MaskKey, UnmaskedLen) ->
- Left = UnmaskedLen rem 4,
- Right = 4 - Left,
- (MaskKey bsl (Left * 8)) + (MaskKey bsr (Right * 8)).
+websocket_payload(State, Req, HandlerState, Type = close, Len, MaskKey, Rsv, Data) ->
+ case cow_ws:parse_close_code(Data, MaskKey) of
+ {ok, CloseCode, Rest} ->
+ websocket_payload(State, Req, HandlerState, Type, Len - 2, MaskKey, Rsv, CloseCode, <<>>, 2, Rest);
+ error ->
+ websocket_close(State, Req, HandlerState, {error, badframe})
+ end;
+websocket_payload(State, Req, HandlerState, Type, Len, MaskKey, Rsv, Data) ->
+ websocket_payload(State, Req, HandlerState, Type, Len, MaskKey, Rsv, undefined, <<>>, 0, Data).
-%% Returns <<>> if the argument is valid UTF-8, false if not,
-%% or the incomplete part of the argument if we need more data.
--spec is_utf8(binary()) -> false | binary().
-is_utf8(Valid = <<>>) ->
- Valid;
-is_utf8(<< _/utf8, Rest/bits >>) ->
- is_utf8(Rest);
-%% 2 bytes. Codepages C0 and C1 are invalid; fail early.
-is_utf8(<< 2#1100000:7, _/bits >>) ->
- false;
-is_utf8(Incomplete = << 2#110:3, _:5 >>) ->
- Incomplete;
-%% 3 bytes.
-is_utf8(Incomplete = << 2#1110:4, _:4 >>) ->
- Incomplete;
-is_utf8(Incomplete = << 2#1110:4, _:4, 2#10:2, _:6 >>) ->
- Incomplete;
-%% 4 bytes. Codepage F4 may have invalid values greater than 0x10FFFF.
-is_utf8(<< 2#11110100:8, 2#10:2, High:6, _/bits >>) when High >= 2#10000 ->
- false;
-is_utf8(Incomplete = << 2#11110:5, _:3 >>) ->
- Incomplete;
-is_utf8(Incomplete = << 2#11110:5, _:3, 2#10:2, _:6 >>) ->
- Incomplete;
-is_utf8(Incomplete = << 2#11110:5, _:3, 2#10:2, _:6, 2#10:2, _:6 >>) ->
- Incomplete;
-%% Invalid.
-is_utf8(_) ->
- false.
+websocket_payload(State=#state{frag_state=FragState, utf8_state=Incomplete, recv_extensions=Extensions},
+ Req, HandlerState, Type, Len, MaskKey, Rsv, CloseCode, Unmasked, UnmaskedLen, Data) ->
+ case cow_ws:parse_payload(Data, MaskKey, Incomplete, UnmaskedLen, Type, Len, FragState, Extensions, Rsv) of
+ {ok, Payload, Utf8State, Rest} ->
+ websocket_dispatch(State#state{utf8_state=Utf8State},
+ Req, HandlerState, Type, << Unmasked/binary, Payload/binary >>, CloseCode, Rest);
+ {more, Payload, Utf8State} ->
+ websocket_payload_loop(State#state{utf8_state=Utf8State},
+ Req, HandlerState, Type, Len - byte_size(Data), MaskKey, Rsv, CloseCode,
+ << Unmasked/binary, Payload/binary >>, UnmaskedLen + byte_size(Data));
+ error ->
+ websocket_close(State, Req, HandlerState, {error, badencoding})
+ end.
--spec websocket_payload_loop(#state{}, Req, any(),
- opcode(), non_neg_integer(), mask_key(), binary(),
- non_neg_integer(), rsv())
- -> {ok, Req, cowboy_middleware:env()}
- | {suspend, module(), atom(), [any()]}
- when Req::cowboy_req:req().
websocket_payload_loop(State=#state{socket=Socket, transport=Transport,
messages={OK, Closed, Error}, timeout_ref=TRef},
- Req, HandlerState, Opcode, Len, MaskKey, Unmasked, UnmaskedLen, Rsv) ->
+ Req, HandlerState, Type, Len, MaskKey, Rsv, CloseCode, Unmasked, UnmaskedLen) ->
Transport:setopts(Socket, [{active, once}]),
receive
{OK, Socket, Data} ->
State2 = handler_loop_timeout(State),
websocket_payload(State2, Req, HandlerState,
- Opcode, Len, MaskKey, Unmasked, UnmaskedLen, Data, Rsv);
+ Type, Len, MaskKey, Rsv, CloseCode, Unmasked, UnmaskedLen, Data);
{Closed, Socket} ->
handler_terminate(State, Req, HandlerState, {error, closed});
{Error, Socket, Reason} ->
@@ -514,53 +260,46 @@ websocket_payload_loop(State=#state{socket=Socket, transport=Transport,
websocket_close(State, Req, HandlerState, timeout);
{timeout, OlderTRef, ?MODULE} when is_reference(OlderTRef) ->
websocket_payload_loop(State, Req, HandlerState,
- Opcode, Len, MaskKey, Unmasked, UnmaskedLen, Rsv);
+ Type, Len, MaskKey, Rsv, CloseCode, Unmasked, UnmaskedLen);
Message ->
handler_call(State, Req, HandlerState,
<<>>, websocket_info, Message,
fun (State2, Req2, HandlerState2, _) ->
websocket_payload_loop(State2, Req2, HandlerState2,
- Opcode, Len, MaskKey, Unmasked, UnmaskedLen, Rsv)
+ Type, Len, MaskKey, Rsv, CloseCode, Unmasked, UnmaskedLen)
end)
end.
--spec websocket_dispatch(#state{}, Req, any(), binary(), opcode(), binary())
- -> {ok, Req, cowboy_middleware:env()}
- | {suspend, module(), atom(), [any()]}
- when Req::cowboy_req:req().
%% Continuation frame.
-websocket_dispatch(State=#state{frag_state={nofin, Opcode, SoFar}},
- Req, HandlerState, RemainingData, 0, Payload) ->
- websocket_data(State#state{frag_state={nofin, Opcode,
- << SoFar/binary, Payload/binary >>}}, Req, HandlerState, RemainingData);
+websocket_dispatch(State=#state{frag_state={nofin, _}, frag_buffer=SoFar},
+ Req, HandlerState, fragment, Payload, _, RemainingData) ->
+ websocket_data(State#state{frag_buffer= << SoFar/binary, Payload/binary >>}, Req, HandlerState, RemainingData);
%% Last continuation frame.
-websocket_dispatch(State=#state{frag_state={fin, Opcode, SoFar}},
- Req, HandlerState, RemainingData, 0, Payload) ->
- websocket_dispatch(State#state{frag_state=undefined}, Req, HandlerState,
- RemainingData, Opcode, << SoFar/binary, Payload/binary >>);
+websocket_dispatch(State=#state{frag_state={fin, Type}, frag_buffer=SoFar},
+ Req, HandlerState, fragment, Payload, CloseCode, RemainingData) ->
+ websocket_dispatch(State#state{frag_state=undefined, frag_buffer= <<>>}, Req, HandlerState,
+ Type, << SoFar/binary, Payload/binary >>, CloseCode, RemainingData);
%% Text frame.
-websocket_dispatch(State, Req, HandlerState, RemainingData, 1, Payload) ->
+websocket_dispatch(State, Req, HandlerState, text, Payload, _, RemainingData) ->
handler_call(State, Req, HandlerState, RemainingData,
websocket_handle, {text, Payload}, fun websocket_data/4);
%% Binary frame.
-websocket_dispatch(State, Req, HandlerState, RemainingData, 2, Payload) ->
+websocket_dispatch(State, Req, HandlerState, binary, Payload, _, RemainingData) ->
handler_call(State, Req, HandlerState, RemainingData,
websocket_handle, {binary, Payload}, fun websocket_data/4);
%% Close control frame.
-websocket_dispatch(State, Req, HandlerState, _RemainingData, 8, <<>>) ->
+websocket_dispatch(State, Req, HandlerState, close, _, undefined, _) ->
websocket_close(State, Req, HandlerState, remote);
-websocket_dispatch(State, Req, HandlerState, _RemainingData, 8,
- << Code:16, Payload/bits >>) ->
+websocket_dispatch(State, Req, HandlerState, close, Payload, Code, _) ->
websocket_close(State, Req, HandlerState, {remote, Code, Payload});
%% Ping control frame. Send a pong back and forward the ping to the handler.
-websocket_dispatch(State=#state{socket=Socket, transport=Transport},
- Req, HandlerState, RemainingData, 9, Payload) ->
- Len = payload_length_to_binary(byte_size(Payload)),
- Transport:send(Socket, << 1:1, 0:3, 10:4, 0:1, Len/bits, Payload/binary >>),
+websocket_dispatch(State=#state{socket=Socket, transport=Transport, send_extensions=Extensions},
+ Req, HandlerState, ping, Payload, _, RemainingData) ->
+ Transport:send(Socket, cow_ws:frame({pong, Payload}, Extensions)),
handler_call(State, Req, HandlerState, RemainingData,
websocket_handle, {ping, Payload}, fun websocket_data/4);
%% Pong control frame.
-websocket_dispatch(State, Req, HandlerState, RemainingData, 10, Payload) ->
+websocket_dispatch(State, Req, HandlerState, pong, Payload, _, RemainingData) ->
handler_call(State, Req, HandlerState, RemainingData,
websocket_handle, {pong, Payload}, fun websocket_data/4).
@@ -579,42 +318,42 @@ handler_call(State=#state{handler=Handler}, Req, HandlerState,
{reply, Payload, Req2, HandlerState2}
when is_list(Payload) ->
case websocket_send_many(Payload, State) of
- {ok, State2} ->
- NextState(State2, Req2, HandlerState2, RemainingData);
- {stop, State2} ->
- handler_terminate(State2, Req2, HandlerState2, stop);
- {{error, _} = Error, State2} ->
- handler_terminate(State2, Req2, HandlerState2, Error)
+ ok ->
+ NextState(State, Req2, HandlerState2, RemainingData);
+ stop ->
+ handler_terminate(State, Req2, HandlerState2, stop);
+ Error = {error, _} ->
+ handler_terminate(State, Req2, HandlerState2, Error)
end;
{reply, Payload, Req2, HandlerState2, hibernate}
when is_list(Payload) ->
case websocket_send_many(Payload, State) of
- {ok, State2} ->
- NextState(State2#state{hibernate=true},
+ ok ->
+ NextState(State#state{hibernate=true},
Req2, HandlerState2, RemainingData);
- {stop, State2} ->
- handler_terminate(State2, Req2, HandlerState2, stop);
- {{error, _} = Error, State2} ->
- handler_terminate(State2, Req2, HandlerState2, Error)
+ stop ->
+ handler_terminate(State, Req2, HandlerState2, stop);
+ Error = {error, _} ->
+ handler_terminate(State, Req2, HandlerState2, Error)
end;
{reply, Payload, Req2, HandlerState2} ->
case websocket_send(Payload, State) of
- {ok, State2} ->
- NextState(State2, Req2, HandlerState2, RemainingData);
- {stop, State2} ->
- handler_terminate(State2, Req2, HandlerState2, stop);
- {{error, _} = Error, State2} ->
- handler_terminate(State2, Req2, HandlerState2, Error)
+ ok ->
+ NextState(State, Req2, HandlerState2, RemainingData);
+ stop ->
+ handler_terminate(State, Req2, HandlerState2, stop);
+ Error = {error, _} ->
+ handler_terminate(State, Req2, HandlerState2, Error)
end;
{reply, Payload, Req2, HandlerState2, hibernate} ->
case websocket_send(Payload, State) of
- {ok, State2} ->
- NextState(State2#state{hibernate=true},
+ ok ->
+ NextState(State#state{hibernate=true},
Req2, HandlerState2, RemainingData);
- {stop, State2} ->
- handler_terminate(State2, Req2, HandlerState2, stop);
- {{error, _} = Error, State2} ->
- handler_terminate(State2, Req2, HandlerState2, Error)
+ stop ->
+ handler_terminate(State, Req2, HandlerState2, stop);
+ Error = {error, _} ->
+ handler_terminate(State, Req2, HandlerState2, Error)
end;
{stop, Req2, HandlerState2} ->
websocket_close(State, Req2, HandlerState2, stop)
@@ -630,103 +369,44 @@ handler_call(State=#state{handler=Handler}, Req, HandlerState,
])
end.
-websocket_opcode(text) -> 1;
-websocket_opcode(binary) -> 2;
-websocket_opcode(close) -> 8;
-websocket_opcode(ping) -> 9;
-websocket_opcode(pong) -> 10.
-
--spec websocket_deflate_frame(opcode(), binary(), #state{}) ->
- {binary(), rsv(), #state{}}.
-websocket_deflate_frame(Opcode, Payload,
- State=#state{deflate_frame = DeflateFrame})
- when DeflateFrame =:= false orelse Opcode >= 8 ->
- {Payload, << 0:3 >>, State};
-websocket_deflate_frame(_, Payload, State=#state{deflate_state = Deflate}) ->
- Deflated = iolist_to_binary(zlib:deflate(Deflate, Payload, sync)),
- DeflatedBodyLength = erlang:size(Deflated) - 4,
- Deflated1 = case Deflated of
- << Body:DeflatedBodyLength/binary, 0:8, 0:8, 255:8, 255:8 >> -> Body;
- _ -> Deflated
- end,
- {Deflated1, << 1:1, 0:2 >>, State}.
-
--spec websocket_send(frame(), #state{})
--> {ok, #state{}} | {stop, #state{}} | {{error, atom()}, #state{}}.
-websocket_send(Type = close, State=#state{socket=Socket, transport=Transport}) ->
- Opcode = websocket_opcode(Type),
- case Transport:send(Socket, << 1:1, 0:3, Opcode:4, 0:8 >>) of
- ok -> {stop, State};
- Error -> {Error, State}
- end;
-websocket_send(Type, State=#state{socket=Socket, transport=Transport})
- when Type =:= ping; Type =:= pong ->
- Opcode = websocket_opcode(Type),
- {Transport:send(Socket, << 1:1, 0:3, Opcode:4, 0:8 >>), State};
-websocket_send({close, Payload}, State) ->
- websocket_send({close, 1000, Payload}, State);
-websocket_send({Type = close, StatusCode, Payload}, State=#state{
- socket=Socket, transport=Transport}) ->
- Opcode = websocket_opcode(Type),
- Len = 2 + iolist_size(Payload),
- %% Control packets must not be > 125 in length.
- true = Len =< 125,
- BinLen = payload_length_to_binary(Len),
- Transport:send(Socket,
- [<< 1:1, 0:3, Opcode:4, 0:1, BinLen/bits, StatusCode:16 >>, Payload]),
- {stop, State};
-websocket_send({Type, Payload0}, State=#state{socket=Socket, transport=Transport}) ->
- Opcode = websocket_opcode(Type),
- {Payload, Rsv, State2} = websocket_deflate_frame(Opcode, iolist_to_binary(Payload0), State),
- Len = iolist_size(Payload),
- %% Control packets must not be > 125 in length.
- true = if Type =:= ping; Type =:= pong ->
- Len =< 125;
- true ->
- true
- end,
- BinLen = payload_length_to_binary(Len),
- {Transport:send(Socket,
- [<< 1:1, Rsv/bits, Opcode:4, 0:1, BinLen/bits >>, Payload]), State2}.
-
--spec payload_length_to_binary(0..16#7fffffffffffffff)
- -> << _:7 >> | << _:23 >> | << _:71 >>.
-payload_length_to_binary(N) ->
- case N of
- N when N =< 125 -> << N:7 >>;
- N when N =< 16#ffff -> << 126:7, N:16 >>;
- N when N =< 16#7fffffffffffffff -> << 127:7, N:64 >>
+-spec websocket_send(cow_ws:frame(), #state{}) -> ok | stop | {error, atom()}.
+websocket_send(Frame, #state{socket=Socket, transport=Transport, send_extensions=Extensions}) ->
+ Res = Transport:send(Socket, cow_ws:frame(Frame, Extensions)),
+ case Frame of
+ close -> stop;
+ {close, _} -> stop;
+ {close, _, _} -> stop;
+ _ -> Res
end.
--spec websocket_send_many([frame()], #state{})
- -> {ok, #state{}} | {stop, #state{}} | {{error, atom()}, #state{}}.
-websocket_send_many([], State) ->
- {ok, State};
+-spec websocket_send_many([cow_ws:frame()], #state{}) -> ok | stop | {error, atom()}.
+websocket_send_many([], _) ->
+ ok;
websocket_send_many([Frame|Tail], State) ->
case websocket_send(Frame, State) of
- {ok, State2} -> websocket_send_many(Tail, State2);
- {stop, State2} -> {stop, State2};
- {Error, State2} -> {Error, State2}
+ ok -> websocket_send_many(Tail, State);
+ stop -> stop;
+ Error -> Error
end.
-spec websocket_close(#state{}, Req, any(), terminate_reason())
-> {ok, Req, cowboy_middleware:env()}
when Req::cowboy_req:req().
-websocket_close(State=#state{socket=Socket, transport=Transport},
+websocket_close(State=#state{socket=Socket, transport=Transport, send_extensions=Extensions},
Req, HandlerState, Reason) ->
case Reason of
Normal when Normal =:= stop; Normal =:= timeout ->
- Transport:send(Socket, << 1:1, 0:3, 8:4, 0:1, 2:7, 1000:16 >>);
+ Transport:send(Socket, cow_ws:frame({close, 1000, <<>>}, Extensions));
{error, badframe} ->
- Transport:send(Socket, << 1:1, 0:3, 8:4, 0:1, 2:7, 1002:16 >>);
+ Transport:send(Socket, cow_ws:frame({close, 1002, <<>>}, Extensions));
{error, badencoding} ->
- Transport:send(Socket, << 1:1, 0:3, 8:4, 0:1, 2:7, 1007:16 >>);
+ Transport:send(Socket, cow_ws:frame({close, 1007, <<>>}, Extensions));
{crash, _, _} ->
- Transport:send(Socket, << 1:1, 0:3, 8:4, 0:1, 2:7, 1011:16 >>);
+ Transport:send(Socket, cow_ws:frame({close, 1011, <<>>}, Extensions));
remote ->
- Transport:send(Socket, << 1:1, 0:3, 8:4, 0:8 >>);
+ Transport:send(Socket, cow_ws:frame(close, Extensions));
{remote, Code, _} ->
- Transport:send(Socket, << 1:1, 0:3, 8:4, 0:1, 2:7, Code:16 >>)
+ Transport:send(Socket, cow_ws:frame({close, Code, <<>>}, Extensions))
end,
handler_terminate(State, Req, HandlerState, Reason).
diff --git a/test/handlers/input_crash_h.erl b/test/handlers/input_crash_h.erl
index e941cca..c67bb0c 100644
--- a/test/handlers/input_crash_h.erl
+++ b/test/handlers/input_crash_h.erl
@@ -6,5 +6,5 @@
-export([init/2]).
init(Req, content_length) ->
- cowboy_error_h:ignore(cow_http_hd, number, 2),
+ cowboy_error_h:ignore(erlang, binary_to_integer, 1),
cowboy_req:parse_header(<<"content-length">>, Req).
diff --git a/test/http_SUITE.erl b/test/http_SUITE.erl
index 1b819ae..12b974c 100644
--- a/test/http_SUITE.erl
+++ b/test/http_SUITE.erl
@@ -748,8 +748,8 @@ rest_resource_etags(Config) ->
{200, <<"\"etag-header-value\"">>, "tuple-strong"},
{200, <<"W/\"etag-header-value\"">>, "binary-weak-quoted"},
{200, <<"\"etag-header-value\"">>, "binary-strong-quoted"},
- {500, false, "binary-strong-unquoted"},
- {500, false, "binary-weak-unquoted"}
+ {400, false, "binary-strong-unquoted"},
+ {400, false, "binary-weak-unquoted"}
],
_ = [{Status, ETag, Type} = begin
{Ret, RespETag} = rest_resource_get_etag(Config, Type),
diff --git a/test/http_SUITE_data/rest_resource_etags.erl b/test/http_SUITE_data/rest_resource_etags.erl
index 1ea3005..0585761 100644
--- a/test/http_SUITE_data/rest_resource_etags.erl
+++ b/test/http_SUITE_data/rest_resource_etags.erl
@@ -23,10 +23,10 @@ generate_etag(Req, State) ->
{<<"\"etag-header-value\"">>, Req, State};
%% Invalid return values from generate_etag/2.
<<"binary-strong-unquoted">> ->
- cowboy_error_h:ignore(cowboy_http, quoted_string, 2),
+ cowboy_error_h:ignore(cow_http_hd, parse_etag, 1),
{<<"etag-header-value">>, Req, State};
<<"binary-weak-unquoted">> ->
- cowboy_error_h:ignore(cowboy_http, quoted_string, 2),
+ cowboy_error_h:ignore(cow_http_hd, parse_etag, 1),
{<<"W/etag-header-value">>, Req, State}
end.