cowboy_http_websocket.erl 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  1. %% Copyright (c) 2011, Loïc Hoguin <essen@dev-extend.eu>
  2. %%
  3. %% Permission to use, copy, modify, and/or distribute this software for any
  4. %% purpose with or without fee is hereby granted, provided that the above
  5. %% copyright notice and this permission notice appear in all copies.
  6. %%
  7. %% THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  8. %% WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  9. %% MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  10. %% ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  11. %% WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  12. %% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  13. %% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  14. -module(cowboy_http_websocket).
  15. -export([upgrade/3]). %% API.
  16. -export([handler_loop/4]). %% Internal.
  17. -include("include/http.hrl").
  18. -record(state, {
  19. handler :: module(),
  20. opts :: any(),
  21. origin = undefined :: undefined | binary(),
  22. challenge = undefined :: undefined | binary(),
  23. timeout = infinity :: timeout(),
  24. messages = undefined :: undefined | {atom(), atom(), atom()},
  25. eop :: tuple(),
  26. hibernate = false :: boolean()
  27. }).
  28. -spec upgrade(module(), any(), #http_req{}) -> ok.
  29. upgrade(Handler, Opts, Req) ->
  30. EOP = binary:compile_pattern(<< 255 >>),
  31. case catch websocket_upgrade(#state{handler=Handler, opts=Opts, eop=EOP}, Req) of
  32. {ok, State, Req2} -> handler_init(State, Req2);
  33. {'EXIT', _Reason} -> upgrade_error(Req)
  34. end.
  35. -spec websocket_upgrade(#state{}, #http_req{}) -> {ok, #state{}, #http_req{}}.
  36. websocket_upgrade(State, Req) ->
  37. {<<"Upgrade">>, Req2} = cowboy_http_req:header('Connection', Req),
  38. {<<"WebSocket">>, Req3} = cowboy_http_req:header('Upgrade', Req2),
  39. {Origin, Req4} = cowboy_http_req:header(<<"Origin">>, Req3),
  40. {Key1, Req5} = cowboy_http_req:header(<<"Sec-Websocket-Key1">>, Req4),
  41. {Key2, Req6} = cowboy_http_req:header(<<"Sec-Websocket-Key2">>, Req5),
  42. false = lists:member(undefined, [Origin, Key1, Key2]),
  43. {ok, Key3, Req7} = cowboy_http_req:body(8, Req6),
  44. Challenge = challenge(Key1, Key2, Key3),
  45. {ok, State#state{origin=Origin, challenge=Challenge}, Req7}.
  46. -spec challenge(binary(), binary(), binary()) -> binary().
  47. challenge(Key1, Key2, Key3) ->
  48. IntKey1 = key_to_integer(Key1),
  49. IntKey2 = key_to_integer(Key2),
  50. erlang:md5(<< IntKey1:32, IntKey2:32, Key3/binary >>).
  51. -spec key_to_integer(binary()) -> integer().
  52. key_to_integer(Key) ->
  53. Number = list_to_integer([C || << C >> <= Key, C >= $0, C =< $9]),
  54. Spaces = length([C || << C >> <= Key, C =:= 32]),
  55. Number div Spaces.
  56. -spec handler_init(#state{}, #http_req{}) -> ok.
  57. handler_init(State=#state{handler=Handler, opts=Opts},
  58. Req=#http_req{transport=Transport}) ->
  59. try Handler:websocket_init(Transport:name(), Req, Opts) of
  60. {ok, Req2, HandlerState} ->
  61. websocket_handshake(State, Req2, HandlerState);
  62. {ok, Req2, HandlerState, Timeout} ->
  63. websocket_handshake(State#state{timeout=Timeout},
  64. Req2, HandlerState)
  65. catch Class:Reason ->
  66. upgrade_error(Req),
  67. error_logger:error_msg(
  68. "** Handler ~p terminating in websocket_init/3~n"
  69. " for the reason ~p:~p~n** Options were ~p~n"
  70. "** Request was ~p~n** Stacktrace: ~p~n~n",
  71. [Handler, Class, Reason, Opts, Req, erlang:get_stacktrace()])
  72. end.
  73. -spec upgrade_error(#http_req{}) -> ok.
  74. upgrade_error(Req=#http_req{socket=Socket, transport=Transport}) ->
  75. {ok, _Req} = cowboy_http_req:reply(400, [], [],
  76. Req#http_req{resp_state=waiting}),
  77. Transport:close(Socket).
  78. -spec websocket_handshake(#state{}, #http_req{}, any()) -> ok.
  79. websocket_handshake(State=#state{origin=Origin, challenge=Challenge},
  80. Req=#http_req{transport=Transport, raw_host=Host, port=Port,
  81. raw_path=Path}, HandlerState) ->
  82. Location = websocket_location(Transport:name(), Host, Port, Path),
  83. {ok, Req2} = cowboy_http_req:reply(
  84. <<"101 WebSocket Protocol Handshake">>,
  85. [{<<"Connection">>, <<"Upgrade">>},
  86. {<<"Upgrade">>, <<"WebSocket">>},
  87. {<<"Sec-WebSocket-Location">>, Location},
  88. {<<"Sec-WebSocket-Origin">>, Origin}],
  89. Challenge, Req#http_req{resp_state=waiting}),
  90. handler_before_loop(State#state{messages=Transport:messages()},
  91. Req2, HandlerState, <<>>).
  92. -spec websocket_location(atom(), binary(), inet:ip_port(), binary())
  93. -> binary().
  94. websocket_location(ssl, Host, Port, Path) ->
  95. << "wss://", Host/binary, ":",
  96. (list_to_binary(integer_to_list(Port)))/binary, Path/binary >>;
  97. websocket_location(_Any, Host, Port, Path) ->
  98. << "ws://", Host/binary, ":",
  99. (list_to_binary(integer_to_list(Port)))/binary, Path/binary >>.
  100. -spec handler_before_loop(#state{}, #http_req{}, any(), binary()) -> ok.
  101. handler_before_loop(State=#state{hibernate=true},
  102. Req=#http_req{socket=Socket, transport=Transport},
  103. HandlerState, SoFar) ->
  104. Transport:setopts(Socket, [{active, once}]),
  105. erlang:hibernate(?MODULE, handler_loop, [State#state{hibernate=false},
  106. Req, HandlerState, SoFar]);
  107. handler_before_loop(State, Req=#http_req{socket=Socket, transport=Transport},
  108. HandlerState, SoFar) ->
  109. Transport:setopts(Socket, [{active, once}]),
  110. handler_loop(State, Req, HandlerState, SoFar).
  111. -spec handler_loop(#state{}, #http_req{}, any(), binary()) -> ok.
  112. handler_loop(State=#state{messages={OK, Closed, Error}, timeout=Timeout},
  113. Req=#http_req{socket=Socket}, HandlerState, SoFar) ->
  114. receive
  115. {OK, Socket, Data} ->
  116. websocket_data(State, Req, HandlerState,
  117. << SoFar/binary, Data/binary >>);
  118. {Closed, Socket} ->
  119. handler_terminate(State, Req, HandlerState, {error, closed});
  120. {Error, Socket, Reason} ->
  121. handler_terminate(State, Req, HandlerState, {error, Reason});
  122. Message ->
  123. handler_call(State, Req, HandlerState,
  124. SoFar, Message, fun handler_before_loop/4)
  125. after Timeout ->
  126. websocket_close(State, Req, HandlerState, {normal, timeout})
  127. end.
  128. -spec websocket_data(#state{}, #http_req{}, any(), binary()) -> ok.
  129. websocket_data(State, Req, HandlerState, << 255, 0, _Rest/bits >>) ->
  130. websocket_close(State, Req, HandlerState, {normal, closed});
  131. websocket_data(State, Req, HandlerState, <<>>) ->
  132. handler_before_loop(State, Req, HandlerState, <<>>);
  133. websocket_data(State, Req, HandlerState, Data) ->
  134. websocket_frame(State, Req, HandlerState, Data, binary:first(Data)).
  135. %% We do not support any frame type other than 0 yet. Just like the specs.
  136. -spec websocket_frame(#state{}, #http_req{}, any(), binary(), byte()) -> ok.
  137. websocket_frame(State=#state{eop=EOP}, Req, HandlerState, Data, 0) ->
  138. case binary:match(Data, EOP) of
  139. {Pos, 1} ->
  140. Pos2 = Pos - 1,
  141. << 0, Frame:Pos2/binary, 255, Rest/bits >> = Data,
  142. handler_call(State, Req, HandlerState,
  143. Rest, {websocket, Frame}, fun websocket_data/4);
  144. nomatch ->
  145. %% @todo We probably should allow limiting frame length.
  146. handler_before_loop(State, Req, HandlerState, Data)
  147. end;
  148. websocket_frame(State, Req, HandlerState, _Data, _FrameType) ->
  149. websocket_close(State, Req, HandlerState, {error, badframe}).
  150. -spec handler_call(#state{}, #http_req{}, any(), binary(), any(), fun()) -> ok.
  151. handler_call(State=#state{handler=Handler, opts=Opts}, Req, HandlerState,
  152. RemainingData, Message, NextState) ->
  153. try Handler:websocket_handle(Message, Req, HandlerState) of
  154. {ok, Req2, HandlerState2} ->
  155. NextState(State, Req2, HandlerState2, RemainingData);
  156. {ok, Req2, HandlerState2, hibernate} ->
  157. NextState(State#state{hibernate=true},
  158. Req2, HandlerState2, RemainingData);
  159. {reply, Data, Req2, HandlerState2} ->
  160. websocket_send(Data, Req2),
  161. NextState(State, Req2, HandlerState2, RemainingData);
  162. {reply, Data, Req2, HandlerState2, hibernate} ->
  163. websocket_send(Data, Req2),
  164. NextState(State#state{hibernate=true},
  165. Req2, HandlerState2, RemainingData);
  166. {shutdown, Req2, HandlerState2} ->
  167. websocket_close(State, Req2, HandlerState2, {normal, shutdown})
  168. catch Class:Reason ->
  169. websocket_close(State, Req, HandlerState, {error, handler}),
  170. error_logger:error_msg(
  171. "** Handler ~p terminating in websocket_handle/3~n"
  172. " for the reason ~p:~p~n** Message was ~p~n"
  173. "** Options were ~p~n** Handler state was ~p~n"
  174. "** Request was ~p~n** Stacktrace: ~p~n~n",
  175. [Handler, Class, Reason, Message, Opts,
  176. HandlerState, Req, erlang:get_stacktrace()])
  177. end.
  178. -spec websocket_send(binary(), #http_req{}) -> ok.
  179. websocket_send(Data, #http_req{socket=Socket, transport=Transport}) ->
  180. Transport:send(Socket, << 0, Data/binary, 255 >>).
  181. -spec websocket_close(#state{}, #http_req{}, any(), {atom(), atom()}) -> ok.
  182. websocket_close(State, Req=#http_req{socket=Socket, transport=Transport},
  183. HandlerState, Reason) ->
  184. Transport:send(Socket, << 255, 0 >>),
  185. Transport:close(Socket),
  186. handler_terminate(State, Req, HandlerState, Reason).
  187. -spec handler_terminate(#state{}, #http_req{},
  188. any(), atom() | {atom(), atom()}) -> ok.
  189. handler_terminate(#state{handler=Handler, opts=Opts},
  190. Req, HandlerState, TerminateReason) ->
  191. try
  192. Handler:websocket_terminate(TerminateReason, Req, HandlerState)
  193. catch Class:Reason ->
  194. error_logger:error_msg(
  195. "** Handler ~p terminating in websocket_terminate/3~n"
  196. " for the reason ~p:~p~n** Initial reason was ~p~n"
  197. "** Options were ~p~n** Handler state was ~p~n"
  198. "** Request was ~p~n** Stacktrace: ~p~n~n",
  199. [Handler, Class, Reason, TerminateReason, Opts,
  200. HandlerState, Req, erlang:get_stacktrace()])
  201. end.