diff options
-rw-r--r-- | src/cowboy_http_websocket.erl | 183 | ||||
-rw-r--r-- | src/cowboy_http_websocket_handler.erl | 21 | ||||
-rw-r--r-- | test/http_SUITE.erl | 51 | ||||
-rw-r--r-- | test/websocket_handler.erl | 29 |
4 files changed, 280 insertions, 4 deletions
diff --git a/src/cowboy_http_websocket.erl b/src/cowboy_http_websocket.erl new file mode 100644 index 0000000..46c2ffa --- /dev/null +++ b/src/cowboy_http_websocket.erl @@ -0,0 +1,183 @@ +%% Copyright (c) 2011, Loïc Hoguin <[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. + +-module(cowboy_http_websocket). +-export([upgrade/3]). + +-include("include/types.hrl"). +-include("include/http.hrl"). + +-record(state, { + handler :: module(), + opts :: term(), + origin = undefined :: undefined | string(), + challenge = undefined :: undefined | binary(), + timeout = infinity :: timeout(), + messages = undefined :: undefined | {atom(), atom(), atom()} +}). + +-spec upgrade(Handler::module(), Opts::term(), Req::#http_req{}) -> ok. +upgrade(Handler, Opts, Req) -> + case catch websocket_upgrade(#state{handler=Handler, opts=Opts}, Req) of + {ok, State, Req2} -> handler_init(State, Req2); + {'EXIT', _Reason} -> upgrade_error(Req) + end. + +-spec websocket_upgrade(State::#state{}, Req::#http_req{}) + -> {ok, State::#state{}, Req::#http_req{}}. +websocket_upgrade(State, Req=#http_req{socket=Socket, transport=Transport}) -> + {"Upgrade", Req2} = cowboy_http_req:header('Connection', Req), + {"WebSocket", Req3} = cowboy_http_req:header('Upgrade', Req2), + {Origin, Req4} = cowboy_http_req:header("Origin", Req3), + {Key1, Req5} = cowboy_http_req:header("Sec-Websocket-Key1", Req4), + {Key2, Req6} = cowboy_http_req:header("Sec-Websocket-Key2", Req5), + false = lists:member(undefined, [Origin, Key1, Key2]), + Transport:setopts(Socket, [binary]), + {ok, Key3, Req7} = cowboy_http_req:body(8, Req6), + Challenge = challenge(Key1, Key2, Key3), + {ok, State#state{origin=Origin, challenge=Challenge}, Req7}. + +-spec challenge(Key1::string(), Key2::string(), Key3::binary()) -> binary(). +challenge(Key1, Key2, Key3) -> + IntKey1 = key_to_integer(Key1), + IntKey2 = key_to_integer(Key2), + erlang:md5(<< IntKey1:32, IntKey2:32, Key3/binary >>). + +-spec key_to_integer(Key::string()) -> integer(). +key_to_integer(Key) -> + Number = list_to_integer([C || C <- Key, C >= $0, C =< $9]), + Spaces = length([C || C <- Key, C =:= 32]), + Number div Spaces. + +-spec handler_init(State::#state{}, Req::#http_req{}) -> ok. +handler_init(State=#state{handler=Handler, opts=Opts}, + Req=#http_req{transport=Transport}) -> + case catch Handler:websocket_init(Transport:name(), Req, Opts) of + {ok, Req2, HandlerState} -> + websocket_handshake(State, Req2, HandlerState); + {ok, Req2, HandlerState, Timeout} -> + websocket_handshake(State#state{timeout=Timeout}, + Req2, HandlerState); + {'EXIT', _Reason} -> + upgrade_error(Req) + end. + +-spec upgrade_error(Req::#http_req{}) -> ok. +upgrade_error(Req=#http_req{socket=Socket, transport=Transport}) -> + {ok, _Req} = cowboy_http_req:reply(400, [], [], + Req#http_req{resp_state=waiting}), + Transport:close(Socket). + +-spec websocket_handshake(State::#state{}, Req::#http_req{}, + HandlerState::term()) -> ok. +websocket_handshake(State=#state{origin=Origin, challenge=Challenge}, + Req=#http_req{transport=Transport, raw_host=Host, raw_path=Path}, + HandlerState) -> + Location = websocket_location(Transport:name(), Host, Path), + {ok, Req2} = cowboy_http_req:reply( + "101 WebSocket Protocol Handshake", + [{"Connection", "Upgrade"}, + {"Upgrade", "WebSocket"}, + {"Sec-WebSocket-Location", Location}, + {"Sec-WebSocket-Origin", Origin}], + Challenge, Req#http_req{resp_state=waiting}), + handler_loop(State#state{messages=Transport:messages()}, + Req2, HandlerState, <<>>). + +-spec websocket_location(TransName::atom(), Host::string(), Path::string()) + -> string(). +websocket_location(ssl, Host, Path) -> + "wss://" ++ Host ++ Path; +websocket_location(_Any, Host, Path) -> + "ws://" ++ Host ++ Path. + +-spec handler_loop(State::#state{}, Req::#http_req{}, + HandlerState::term(), SoFar::binary()) -> ok. +handler_loop(State=#state{messages={OK, Closed, Error}, timeout=Timeout}, + Req=#http_req{socket=Socket, transport=Transport}, + HandlerState, SoFar) -> + Transport:setopts(Socket, [{active, once}]), + receive + {OK, Socket, Data} -> + websocket_data(State, Req, HandlerState, + << SoFar/binary, Data/binary >>); + {Closed, Socket} -> + handler_terminate(State, Req, HandlerState, {error, closed}); + {Error, Socket, Reason} -> + handler_terminate(State, Req, HandlerState, {error, Reason}); + Message -> + handler_call(State, Req, HandlerState, + SoFar, Message, fun handler_loop/4) + after Timeout -> + websocket_close(State, Req, HandlerState, {normal, timeout}) + end. + +-spec websocket_data(State::#state{}, Req::#http_req{}, + HandlerState::term(), Data::binary()) -> ok. +websocket_data(State, Req, HandlerState, << 255, 0, _Rest/bits >>) -> + websocket_close(State, Req, HandlerState, {normal, closed}); +websocket_data(State, Req, HandlerState, Data) when byte_size(Data) < 3 -> + handler_loop(State, Req, HandlerState, Data); +websocket_data(State, Req, HandlerState, Data) -> + websocket_frame(State, Req, HandlerState, Data, binary:first(Data)). + +%% We do not support any frame type other than 0 yet. Just like the specs. +-spec websocket_frame(State::#state{}, Req::#http_req{}, + HandlerState::term(), Data::binary(), FrameType::byte()) -> ok. +websocket_frame(State, Req, HandlerState, Data, 0) -> + case binary:match(Data, << 255 >>) of + {Pos, 1} -> + Pos2 = Pos - 1, + << 0, Frame:Pos2/binary, 255, Rest/bits >> = Data, + handler_call(State, Req, HandlerState, + Rest, {websocket, Frame}, fun websocket_data/4); + nomatch -> + %% @todo We probably should allow limiting frame length. + handler_loop(State, Req, HandlerState, Data) + end; +websocket_frame(State, Req, HandlerState, _Data, _FrameType) -> + websocket_close(State, Req, HandlerState, {error, badframe}). + +-spec handler_call(State::#state{}, Req::#http_req{}, HandlerState::term(), + RemainingData::binary(), Message::term(), NextState::fun()) -> ok. +handler_call(State=#state{handler=Handler}, Req, HandlerState, + RemainingData, Message, NextState) -> + case catch Handler:websocket_handle(Message, Req, HandlerState) of + {ok, Req2, HandlerState2} -> + NextState(State, Req2, HandlerState2, RemainingData); + {reply, Data, Req2, HandlerState2} -> + websocket_send(Data, Req2), + NextState(State, Req2, HandlerState2, RemainingData); + {shutdown, Req2, HandlerState2} -> + websocket_close(State, Req2, HandlerState2, {normal, shutdown}); + {'EXIT', _Reason} -> + websocket_close(State, Req, HandlerState, {error, handler}) + end. + +-spec websocket_send(Data::binary(), Req::#http_req{}) -> ok. +websocket_send(Data, #http_req{socket=Socket, transport=Transport}) -> + Transport:send(Socket, << 0, Data/binary, 255 >>). + +-spec websocket_close(State::#state{}, Req::#http_req{}, + HandlerState::term(), Reason::{atom(), atom()}) -> ok. +websocket_close(State, Req=#http_req{socket=Socket, transport=Transport}, + HandlerState, Reason) -> + Transport:send(Socket, << 255, 0 >>), + Transport:close(Socket), + handler_terminate(State, Req, HandlerState, Reason). + +-spec handler_terminate(State::#state{}, Req::#http_req{}, + HandlerState::term(), Reason::atom() | {atom(), atom()}) -> ok. +handler_terminate(#state{handler=Handler}, Req, HandlerState, Reason) -> + Handler:websocket_terminate(Reason, Req, HandlerState). diff --git a/src/cowboy_http_websocket_handler.erl b/src/cowboy_http_websocket_handler.erl new file mode 100644 index 0000000..3de1182 --- /dev/null +++ b/src/cowboy_http_websocket_handler.erl @@ -0,0 +1,21 @@ +%% Copyright (c) 2011, Loïc Hoguin <[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. + +-module(cowboy_http_websocket_handler). +-export([behaviour_info/1]). + +behaviour_info(callbacks) -> + [{websocket_init, 3}, {websocket_handle, 3}, {websocket_terminate, 3}]; +behaviour_info(_Other) -> + undefined. diff --git a/test/http_SUITE.erl b/test/http_SUITE.erl index 30ec709..da43536 100644 --- a/test/http_SUITE.erl +++ b/test/http_SUITE.erl @@ -19,7 +19,7 @@ -export([all/0, groups/0, init_per_suite/1, end_per_suite/1, init_per_group/2, end_per_group/2]). %% ct. -export([headers_dupe/1, pipeline/1, raw/1]). %% http. --export([http_200/1, http_404/1]). %% http and https. +-export([http_200/1, http_404/1, websocket/1]). %% http and https. %% ct. @@ -28,7 +28,7 @@ all() -> groups() -> BaseTests = [http_200, http_404], - [{http, [], [headers_dupe, pipeline, raw] ++ BaseTests}, + [{http, [], [headers_dupe, pipeline, raw, websocket] ++ BaseTests}, {https, [], BaseTests}]. init_per_suite(Config) -> @@ -77,6 +77,7 @@ end_per_group(https, _Config) -> init_http_dispatch() -> [ {["localhost"], [ + {["websocket"], websocket_handler, []}, {["headers", "dupe"], http_handler, [{headers, [{"Connection", "close"}]}]}, {[], http_handler, []} @@ -92,8 +93,8 @@ headers_dupe(Config) -> {port, Port} = lists:keyfind(port, 1, Config), {ok, Socket} = gen_tcp:connect("localhost", Port, [binary, {active, false}, {packet, raw}]), - ok = gen_tcp:send(Socket, - "GET /headers/dupe HTTP/1.1\r\nHost: localhost\r\nConnection: keep-alive\r\n\r\n"), + ok = gen_tcp:send(Socket, "GET /headers/dupe HTTP/1.1\r\n" + "Host: localhost\r\nConnection: keep-alive\r\n\r\n"), {ok, Data} = gen_tcp:recv(Socket, 0, 6000), {_Start, _Length} = binary:match(Data, <<"Connection: close">>), nomatch = binary:match(Data, <<"Connection: keep-alive">>), @@ -160,6 +161,48 @@ raw(Config) -> [{Packet, StatusCode} = raw_req(Packet, Config) || {Packet, StatusCode} <- Tests]. +websocket(Config) -> + {port, Port} = lists:keyfind(port, 1, Config), + {ok, Socket} = gen_tcp:connect("localhost", Port, + [binary, {active, false}, {packet, raw}]), + ok = gen_tcp:send(Socket, [ + "GET /websocket HTTP/1.1\r\n" + "Host: localhost\r\n" + "Connection: Upgrade\r\n" + "Upgrade: WebSocket\r\n" + "Origin: http://localhost\r\n" + "Sec-Websocket-Key1: Y\" 4 1Lj!957b8@0H756!i\r\n" + "Sec-Websocket-Key2: 1711 M;4\\74 80<6\r\n" + "\r\n", <<15,245,8,18,2,204,133,33>>]), + {ok, Handshake} = gen_tcp:recv(Socket, 0, 6000), + {ok, {http_response, {1, 1}, 101, "WebSocket Protocol Handshake"}, Rest} + = erlang:decode_packet(http, Handshake, []), + [Headers, Body] = websocket_headers(erlang:decode_packet(httph, Rest, []), []), + {'Connection', "Upgrade"} = lists:keyfind('Connection', 1, Headers), + {'Upgrade', "WebSocket"} = lists:keyfind('Upgrade', 1, Headers), + {"sec-websocket-location", "ws://localhost/websocket"} + = lists:keyfind("sec-websocket-location", 1, Headers), + {"sec-websocket-origin", "http://localhost"} + = lists:keyfind("sec-websocket-origin", 1, Headers), + <<169,244,191,103,146,33,149,59,74,104,67,5,99,118,171,236>> = Body, + ok = gen_tcp:send(Socket, << 0, "client_msg", 255 >>), + {ok, << 0, "client_msg", 255 >>} = gen_tcp:recv(Socket, 0, 6000), + {ok, << 0, "websocket_init", 255 >>} = gen_tcp:recv(Socket, 0, 6000), + {ok, << 0, "websocket_handle", 255 >>} = gen_tcp:recv(Socket, 0, 6000), + {ok, << 0, "websocket_handle", 255 >>} = gen_tcp:recv(Socket, 0, 6000), + {ok, << 0, "websocket_handle", 255 >>} = gen_tcp:recv(Socket, 0, 6000), + ok = gen_tcp:send(Socket, << 255, 0 >>), + {ok, << 255, 0 >>} = gen_tcp:recv(Socket, 0, 6000), + {error, closed} = gen_tcp:recv(Socket, 0, 6000), + ok. + +websocket_headers({ok, http_eoh, Rest}, Acc) -> + [Acc, Rest]; +websocket_headers({ok, {http_header, _I, Key, _R, Value}, Rest}, Acc) -> + F = fun(S) when is_atom(S) -> S; (S) -> string:to_lower(S) end, + websocket_headers(erlang:decode_packet(httph, Rest, []), + [{F(Key), Value}|Acc]). + %% http and https. build_url(Path, Config) -> diff --git a/test/websocket_handler.erl b/test/websocket_handler.erl new file mode 100644 index 0000000..8e6915b --- /dev/null +++ b/test/websocket_handler.erl @@ -0,0 +1,29 @@ +%% Feel free to use, reuse and abuse the code in this file. + +-module(websocket_handler). +-behaviour(cowboy_http_handler). +-behaviour(cowboy_http_websocket_handler). +-export([init/3, handle/2, terminate/2]). +-export([websocket_init/3, websocket_handle/3, websocket_terminate/3]). + +init(_Any, _Req, _Opts) -> + {upgrade, protocol, cowboy_http_websocket}. + +handle(_Req, _State) -> + exit(badarg). + +terminate(_Req, _State) -> + exit(badarg). + +websocket_init(_TransportName, Req, _Opts) -> + erlang:start_timer(1000, self(), <<"websocket_init">>), + {ok, Req, undefined}. + +websocket_handle({timeout, _Ref, Msg}, Req, State) -> + erlang:start_timer(1000, self(), <<"websocket_handle">>), + {reply, Msg, Req, State}; +websocket_handle({websocket, Data}, Req, State) -> + {reply, Data, Req, State}. + +websocket_terminate(_Reason, _Req, _State) -> + ok. |