aboutsummaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/cowboy.app.src1
-rw-r--r--src/cowboy_http.erl1066
-rw-r--r--src/cowboy_loop.erl6
-rw-r--r--src/cowboy_middleware.erl2
-rw-r--r--src/cowboy_protocol.erl58
-rw-r--r--src/cowboy_req.erl114
-rw-r--r--src/cowboy_rest.erl30
-rw-r--r--src/cowboy_router.erl10
-rw-r--r--src/cowboy_spdy.erl6
-rw-r--r--src/cowboy_sub_protocol.erl2
-rw-r--r--src/cowboy_websocket.erl565
11 files changed, 234 insertions, 1626 deletions
diff --git a/src/cowboy.app.src b/src/cowboy.app.src
index 7fbb1ce..0ca4a73 100644
--- a/src/cowboy.app.src
+++ b/src/cowboy.app.src
@@ -15,6 +15,7 @@
{application, cowboy, [
{description, "Small, fast, modular HTTP server."},
{vsn, "2.0.0-pre.1"},
+ {id, "git"},
{modules, []},
{registered, [cowboy_clock, cowboy_sup]},
{applications, [
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_loop.erl b/src/cowboy_loop.erl
index b9eb8cd..8920299 100644
--- a/src/cowboy_loop.erl
+++ b/src/cowboy_loop.erl
@@ -36,7 +36,7 @@
-callback info(any(), Req, State)
-> {ok, Req, State}
| {ok, Req, State, hibernate}
- | {shutdown, Req, State}
+ | {stop, Req, State}
when Req::cowboy_req:req(), State::any().
%% @todo optional -callback terminate(terminate_reason(), cowboy_req:req(), state()) -> ok.
@@ -153,8 +153,8 @@ call(Req, State=#state{resp_sent=RespSent},
after_call(Req2, State, Handler, HandlerState2);
{ok, Req2, HandlerState2, hibernate} ->
after_call(Req2, State#state{hibernate=true}, Handler, HandlerState2);
- {shutdown, Req2, HandlerState2} ->
- after_loop(Req2, State, Handler, HandlerState2, shutdown)
+ {stop, Req2, HandlerState2} ->
+ after_loop(Req2, State, Handler, HandlerState2, stop)
catch Class:Reason ->
Stacktrace = erlang:get_stacktrace(),
if RespSent -> ok; true ->
diff --git a/src/cowboy_middleware.erl b/src/cowboy_middleware.erl
index 7ff947e..7b0e760 100644
--- a/src/cowboy_middleware.erl
+++ b/src/cowboy_middleware.erl
@@ -20,5 +20,5 @@
-callback execute(Req, Env)
-> {ok, Req, Env}
| {suspend, module(), atom(), [any()]}
- | {halt, Req}
+ | {stop, Req}
when Req::cowboy_req:req(), Env::env().
diff --git a/src/cowboy_protocol.erl b/src/cowboy_protocol.erl
index 2da3a15..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.
%%
@@ -431,7 +465,7 @@ execute(Req, State, Env, [Middleware|Tail]) ->
{suspend, Module, Function, Args} ->
erlang:hibernate(?MODULE, resume,
[State, Env, Tail, Module, Function, Args]);
- {halt, Req2} ->
+ {stop, Req2} ->
next_request(Req2, State, ok)
end.
@@ -444,7 +478,7 @@ resume(State, Env, Tail, Module, Function, Args) ->
{suspend, Module2, Function2, Args2} ->
erlang:hibernate(?MODULE, resume,
[State, Env, Tail, Module2, Function2, Args2]);
- {halt, Req2} ->
+ {stop, Req2} ->
next_request(Req2, State, ok)
end.
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 306584a..b894354 100644
--- a/src/cowboy_rest.erl
+++ b/src/cowboy_rest.erl
@@ -84,7 +84,7 @@ known_methods(Req, State=#state{method=Method}) ->
next(Req, State, fun uri_too_long/2);
no_call ->
next(Req, State, 501);
- {halt, Req2, HandlerState} ->
+ {stop, Req2, HandlerState} ->
terminate(Req2, State#state{handler_state=HandlerState});
{List, Req2, HandlerState} ->
State2 = State#state{handler_state=HandlerState},
@@ -109,7 +109,7 @@ allowed_methods(Req, State=#state{method=Method}) ->
no_call ->
method_not_allowed(Req, State,
[<<"HEAD">>, <<"GET">>, <<"OPTIONS">>]);
- {halt, Req2, HandlerState} ->
+ {stop, Req2, HandlerState} ->
terminate(Req2, State#state{handler_state=HandlerState});
{List, Req2, HandlerState} ->
State2 = State#state{handler_state=HandlerState},
@@ -140,7 +140,7 @@ is_authorized(Req, State) ->
case call(Req, State, is_authorized) of
no_call ->
forbidden(Req, State);
- {halt, Req2, HandlerState} ->
+ {stop, Req2, HandlerState} ->
terminate(Req2, State#state{handler_state=HandlerState});
{true, Req2, HandlerState} ->
forbidden(Req2, State#state{handler_state=HandlerState});
@@ -172,7 +172,7 @@ options(Req, State=#state{allowed_methods=Methods, method= <<"OPTIONS">>}) ->
= << << ", ", M/binary >> || M <- Methods >>,
Req2 = cowboy_req:set_resp_header(<<"allow">>, Allow, Req),
respond(Req2, State, 200);
- {halt, Req2, HandlerState} ->
+ {stop, Req2, HandlerState} ->
terminate(Req2, State#state{handler_state=HandlerState});
{ok, Req2, HandlerState} ->
respond(Req2, State#state{handler_state=HandlerState}, 200)
@@ -211,7 +211,7 @@ content_types_provided(Req, State) ->
catch _:_ ->
respond(Req, State2, 400)
end;
- {halt, Req2, HandlerState} ->
+ {stop, Req2, HandlerState} ->
terminate(Req2, State#state{handler_state=HandlerState});
{[], Req2, HandlerState} ->
not_acceptable(Req2, State#state{handler_state=HandlerState});
@@ -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.
@@ -313,7 +313,7 @@ languages_provided(Req, State) ->
case call(Req, State, languages_provided) of
no_call ->
charsets_provided(Req, State);
- {halt, Req2, HandlerState} ->
+ {stop, Req2, HandlerState} ->
terminate(Req2, State#state{handler_state=HandlerState});
{[], Req2, HandlerState} ->
not_acceptable(Req2, State#state{handler_state=HandlerState});
@@ -373,7 +373,7 @@ charsets_provided(Req, State) ->
case call(Req, State, charsets_provided) of
no_call ->
set_content_type(Req, State);
- {halt, Req2, HandlerState} ->
+ {stop, Req2, HandlerState} ->
terminate(Req2, State#state{handler_state=HandlerState});
{[], Req2, HandlerState} ->
not_acceptable(Req2, State#state{handler_state=HandlerState});
@@ -645,7 +645,7 @@ moved_permanently(Req, State, OnFalse) ->
respond(Req3, State#state{handler_state=HandlerState}, 301);
{false, Req2, HandlerState} ->
OnFalse(Req2, State#state{handler_state=HandlerState});
- {halt, Req2, HandlerState} ->
+ {stop, Req2, HandlerState} ->
terminate(Req2, State#state{handler_state=HandlerState});
no_call ->
OnFalse(Req, State)
@@ -666,7 +666,7 @@ moved_temporarily(Req, State) ->
respond(Req3, State#state{handler_state=HandlerState}, 307);
{false, Req2, HandlerState} ->
is_post_to_missing_resource(Req2, State#state{handler_state=HandlerState}, 410);
- {halt, Req2, HandlerState} ->
+ {stop, Req2, HandlerState} ->
terminate(Req2, State#state{handler_state=HandlerState});
no_call ->
is_post_to_missing_resource(Req, State, 410)
@@ -716,7 +716,7 @@ accept_resource(Req, State) ->
case call(Req, State, content_types_accepted) of
no_call ->
respond(Req, State, 415);
- {halt, Req2, HandlerState} ->
+ {stop, Req2, HandlerState} ->
terminate(Req2, State#state{handler_state=HandlerState});
{CTA, Req2, HandlerState} ->
CTA2 = [normalize_content_types(P) || P <- CTA],
@@ -751,7 +751,7 @@ choose_content_type(Req, State, ContentType, [_Any|Tail]) ->
process_content_type(Req, State=#state{method=Method, exists=Exists}, Fun) ->
try case call(Req, State, Fun) of
- {halt, Req2, HandlerState2} ->
+ {stop, Req2, HandlerState2} ->
terminate(Req2, State#state{handler_state=HandlerState2});
{true, Req2, HandlerState2} when Exists ->
State2 = State#state{handler_state=HandlerState2},
@@ -832,7 +832,7 @@ set_resp_body_expires(Req, State) ->
%% it to the response.
set_resp_body(Req, State=#state{content_type_a={_, Callback}}) ->
try case call(Req, State, Callback) of
- {halt, Req2, HandlerState2} ->
+ {stop, Req2, HandlerState2} ->
terminate(Req2, State#state{handler_state=HandlerState2});
{Body, Req2, HandlerState2} ->
State2 = State#state{handler_state=HandlerState2},
@@ -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}}
@@ -936,7 +936,7 @@ expect(Req, State, Callback, Expected, OnTrue, OnFalse) ->
case call(Req, State, Callback) of
no_call ->
next(Req, State, OnTrue);
- {halt, Req2, HandlerState} ->
+ {stop, Req2, HandlerState} ->
terminate(Req2, State#state{handler_state=HandlerState});
{Expected, Req2, HandlerState} ->
next(Req2, State#state{handler_state=HandlerState}, OnTrue);
diff --git a/src/cowboy_router.erl b/src/cowboy_router.erl
index 2d1924d..b806da5 100644
--- a/src/cowboy_router.erl
+++ b/src/cowboy_router.erl
@@ -157,7 +157,7 @@ compile_brackets_split(<< C, Rest/bits >>, Acc, N) ->
compile_brackets_split(Rest, << Acc/binary, C >>, N).
-spec execute(Req, Env)
- -> {ok, Req, Env} | {halt, Req}
+ -> {ok, Req, Env} | {stop, Req}
when Req::cowboy_req:req(), Env::cowboy_middleware:env().
execute(Req, Env) ->
{_, Dispatch} = lists:keyfind(dispatch, 1, Env),
@@ -168,11 +168,11 @@ execute(Req, Env) ->
Req2 = cowboy_req:set_bindings(HostInfo, PathInfo, Bindings, Req),
{ok, Req2, [{handler, Handler}, {handler_opts, HandlerOpts}|Env]};
{error, notfound, host} ->
- {halt, cowboy_req:reply(400, Req)};
+ {stop, cowboy_req:reply(400, Req)};
{error, badrequest, path} ->
- {halt, cowboy_req:reply(400, Req)};
+ {stop, cowboy_req:reply(400, Req)};
{error, notfound, path} ->
- {halt, cowboy_req:reply(404, Req)}
+ {stop, cowboy_req:reply(404, Req)}
end.
%% Internal.
@@ -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 4d83ff6..cd43399 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,
@@ -406,7 +406,7 @@ execute(Req, Env, [Middleware|Tail]) ->
{suspend, Module, Function, Args} ->
erlang:hibernate(?MODULE, resume,
[Env, Tail, Module, Function, Args]);
- {halt, Req2} ->
+ {stop, Req2} ->
cowboy_req:ensure_response(Req2, 204)
end.
@@ -419,7 +419,7 @@ resume(Env, Tail, Module, Function, Args) ->
{suspend, Module2, Function2, Args2} ->
erlang:hibernate(?MODULE, resume,
[Env, Tail, Module2, Function2, Args2]);
- {halt, Req2} ->
+ {stop, Req2} ->
cowboy_req:ensure_response(Req2, 204)
end.
diff --git a/src/cowboy_sub_protocol.erl b/src/cowboy_sub_protocol.erl
index f177263..b198a18 100644
--- a/src/cowboy_sub_protocol.erl
+++ b/src/cowboy_sub_protocol.erl
@@ -16,5 +16,5 @@
-module(cowboy_sub_protocol).
-callback upgrade(Req, Env, module(), any(), timeout(), run | hibernate)
- -> {ok, Req, Env} | {suspend, module(), atom(), [any()]} | {halt, Req}
+ -> {ok, Req, Env} | {suspend, module(), atom(), [any()]} | {stop, Req}
when Req::cowboy_req:req(), Env::cowboy_middleware:env().
diff --git a/src/cowboy_websocket.erl b/src/cowboy_websocket.erl
index cdd0365..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 | shutdown | timeout
- | remote | {remote, close_code(), binary()}
+-type terminate_reason() :: normal | stop | timeout
+ | remote | {remote, cow_ws:close_code(), binary()}
| {error, badencoding | badframe | closed | atom()}
| {crash, error | exit | throw, any()}.
@@ -47,16 +34,16 @@
-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}
- | {shutdown, Req, State}
+ | {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}
- | {shutdown, Req, State}
+ | {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,45 +318,45 @@ 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);
- {shutdown, State2} ->
- handler_terminate(State2, Req2, HandlerState2, shutdown);
- {{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);
- {shutdown, State2} ->
- handler_terminate(State2, Req2, HandlerState2, shutdown);
- {{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);
- {shutdown, State2} ->
- handler_terminate(State2, Req2, HandlerState2, shutdown);
- {{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);
- {shutdown, State2} ->
- handler_terminate(State2, Req2, HandlerState2, shutdown);
- {{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;
- {shutdown, Req2, HandlerState2} ->
- websocket_close(State, Req2, HandlerState2, shutdown)
+ {stop, Req2, HandlerState2} ->
+ websocket_close(State, Req2, HandlerState2, stop)
catch Class:Reason ->
_ = websocket_close(State, Req, HandlerState, {crash, Class, Reason}),
erlang:Class([
@@ -630,104 +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{}} | {shutdown, #state{}} | {{error, atom()}, #state{}}.
-websocket_send(Type, State=#state{socket=Socket, transport=Transport})
- when Type =:= close ->
- Opcode = websocket_opcode(Type),
- case Transport:send(Socket, << 1:1, 0:3, Opcode:4, 0:8 >>) of
- ok -> {shutdown, 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]),
- {shutdown, 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{}} | {shutdown, #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);
- {shutdown, State2} -> {shutdown, 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 =:= shutdown; Normal =:= timeout ->
- Transport:send(Socket, << 1:1, 0:3, 8:4, 0:1, 2:7, 1000:16 >>);
+ Normal when Normal =:= stop; Normal =:= timeout ->
+ 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).