cowboy_http_websocket.erl 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512
  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. %% @doc WebSocket protocol implementation.
  15. %%
  16. %% Supports the protocol version 0 (hixie-76), version 7 (hybi-7)
  17. %% and version 8 (hybi-8, hybi-9 and hybi-10).
  18. %%
  19. %% Version 0 is supported by the following browsers:
  20. %% <ul>
  21. %% <li>Firefox 4-5 (disabled by default)</li>
  22. %% <li>Chrome 6-13</li>
  23. %% <li>Safari 5.0.1+</li>
  24. %% <li>Opera 11.00+ (disabled by default)</li>
  25. %% </ul>
  26. %%
  27. %% Version 7 is supported by the following browser:
  28. %% <ul>
  29. %% <li>Firefox 6</li>
  30. %% </ul>
  31. %%
  32. %% Version 8 is supported by the following browsers:
  33. %% <ul>
  34. %% <li>Firefox 7</li>
  35. %% <li>Chrome 14+</li>
  36. %% </ul>
  37. -module(cowboy_http_websocket).
  38. -export([upgrade/4]). %% API.
  39. -export([handler_loop/4]). %% Internal.
  40. -include("include/http.hrl").
  41. -include_lib("eunit/include/eunit.hrl").
  42. -type opcode() :: 0 | 1 | 2 | 8 | 9 | 10.
  43. -type mask_key() :: 0..16#ffffffff.
  44. -record(state, {
  45. version :: 0 | 7 | 8 | 13,
  46. handler :: module(),
  47. opts :: any(),
  48. challenge = undefined :: undefined | binary() | {binary(), binary()},
  49. timeout = infinity :: timeout(),
  50. timeout_ref = undefined :: undefined | reference(),
  51. messages = undefined :: undefined | {atom(), atom(), atom()},
  52. hibernate = false :: boolean(),
  53. eop :: undefined | tuple(), %% hixie-76 specific.
  54. origin = undefined :: undefined | binary() %% hixie-76 specific.
  55. }).
  56. %% @doc Upgrade a HTTP request to the WebSocket protocol.
  57. %%
  58. %% You do not need to call this function manually. To upgrade to the WebSocket
  59. %% protocol, you simply need to return <em>{upgrade, protocol, {@module}}</em>
  60. %% in your <em>cowboy_http_handler:init/3</em> handler function.
  61. -spec upgrade(pid(), module(), any(), #http_req{}) -> closed | none().
  62. upgrade(ListenerPid, Handler, Opts, Req) ->
  63. cowboy_listener:move_connection(ListenerPid, websocket, self()),
  64. case catch websocket_upgrade(#state{handler=Handler, opts=Opts}, Req) of
  65. {ok, State, Req2} -> handler_init(State, Req2);
  66. {'EXIT', _Reason} -> upgrade_error(Req)
  67. end.
  68. %% @todo We need a function to properly parse headers according to their ABNF,
  69. %% instead of having ugly code like this case here.
  70. %% @todo Upgrade is a list of products and should be parsed as such.
  71. -spec websocket_upgrade(#state{}, #http_req{}) -> {ok, #state{}, #http_req{}}.
  72. websocket_upgrade(State, Req) ->
  73. {ConnTokens, Req2}
  74. = cowboy_http_req:parse_header('Connection', Req),
  75. true = lists:member(<<"upgrade">>, ConnTokens),
  76. {WS, Req3} = cowboy_http_req:header('Upgrade', Req2),
  77. <<"websocket">> = cowboy_bstr:to_lower(WS),
  78. {Version, Req4} = cowboy_http_req:header(<<"Sec-Websocket-Version">>, Req3),
  79. websocket_upgrade(Version, State, Req4).
  80. %% @todo Handle the Sec-Websocket-Protocol header.
  81. %% @todo Reply a proper error, don't die, if a required header is undefined.
  82. -spec websocket_upgrade(undefined | <<_:8>>, #state{}, #http_req{})
  83. -> {ok, #state{}, #http_req{}}.
  84. %% No version given. Assuming hixie-76 draft.
  85. %%
  86. %% We need to wait to send a reply back before trying to read the
  87. %% third part of the challenge key, because proxies will wait for
  88. %% a reply before sending it. Therefore we calculate the challenge
  89. %% key only in websocket_handshake/3.
  90. websocket_upgrade(undefined, State, Req) ->
  91. {Origin, Req2} = cowboy_http_req:header(<<"Origin">>, Req),
  92. {Key1, Req3} = cowboy_http_req:header(<<"Sec-Websocket-Key1">>, Req2),
  93. {Key2, Req4} = cowboy_http_req:header(<<"Sec-Websocket-Key2">>, Req3),
  94. false = lists:member(undefined, [Origin, Key1, Key2]),
  95. EOP = binary:compile_pattern(<< 255 >>),
  96. {ok, State#state{version=0, origin=Origin, challenge={Key1, Key2},
  97. eop=EOP}, Req4};
  98. %% Versions 7 and 8. Implementation follows the hybi 7 through 17 drafts.
  99. websocket_upgrade(Version, State, Req)
  100. when Version =:= <<"7">>; Version =:= <<"8">>;
  101. Version =:= <<"13">> ->
  102. {Key, Req2} = cowboy_http_req:header(<<"Sec-Websocket-Key">>, Req),
  103. false = Key =:= undefined,
  104. Challenge = hybi_challenge(Key),
  105. IntVersion = list_to_integer(binary_to_list(Version)),
  106. {ok, State#state{version=IntVersion, challenge=Challenge}, Req2}.
  107. -spec handler_init(#state{}, #http_req{}) -> closed | none().
  108. handler_init(State=#state{handler=Handler, opts=Opts},
  109. Req=#http_req{transport=Transport}) ->
  110. try Handler:websocket_init(Transport:name(), Req, Opts) of
  111. {ok, Req2, HandlerState} ->
  112. websocket_handshake(State, Req2, HandlerState);
  113. {ok, Req2, HandlerState, hibernate} ->
  114. websocket_handshake(State#state{hibernate=true},
  115. Req2, HandlerState);
  116. {ok, Req2, HandlerState, Timeout} ->
  117. websocket_handshake(State#state{timeout=Timeout},
  118. Req2, HandlerState);
  119. {ok, Req2, HandlerState, Timeout, hibernate} ->
  120. websocket_handshake(State#state{timeout=Timeout,
  121. hibernate=true}, Req2, HandlerState);
  122. {shutdown, Req2} ->
  123. upgrade_denied(Req2)
  124. catch Class:Reason ->
  125. upgrade_error(Req),
  126. error_logger:error_msg(
  127. "** Handler ~p terminating in websocket_init/3~n"
  128. " for the reason ~p:~p~n** Options were ~p~n"
  129. "** Request was ~p~n** Stacktrace: ~p~n~n",
  130. [Handler, Class, Reason, Opts, Req, erlang:get_stacktrace()])
  131. end.
  132. -spec upgrade_error(#http_req{}) -> closed.
  133. upgrade_error(Req) ->
  134. {ok, _Req2} = cowboy_http_req:reply(400, [], [],
  135. Req#http_req{resp_state=waiting}),
  136. closed.
  137. %% @see cowboy_http_protocol:ensure_response/1
  138. -spec upgrade_denied(#http_req{}) -> closed.
  139. upgrade_denied(#http_req{resp_state=done}) ->
  140. closed;
  141. upgrade_denied(Req=#http_req{resp_state=waiting}) ->
  142. {ok, _Req2} = cowboy_http_req:reply(400, [], [], Req),
  143. closed;
  144. upgrade_denied(#http_req{method='HEAD', resp_state=chunks}) ->
  145. closed;
  146. upgrade_denied(#http_req{socket=Socket, transport=Transport,
  147. resp_state=chunks}) ->
  148. Transport:send(Socket, <<"0\r\n\r\n">>),
  149. closed.
  150. -spec websocket_handshake(#state{}, #http_req{}, any()) -> closed | none().
  151. websocket_handshake(State=#state{version=0, origin=Origin,
  152. challenge={Key1, Key2}}, Req=#http_req{socket=Socket,
  153. transport=Transport, raw_host=Host, port=Port,
  154. raw_path=Path, raw_qs=QS}, HandlerState) ->
  155. Location = hixie76_location(Transport:name(), Host, Port, Path, QS),
  156. {ok, Req2} = cowboy_http_req:upgrade_reply(
  157. <<"101 WebSocket Protocol Handshake">>,
  158. [{<<"Upgrade">>, <<"WebSocket">>},
  159. {<<"Sec-Websocket-Location">>, Location},
  160. {<<"Sec-Websocket-Origin">>, Origin}],
  161. Req#http_req{resp_state=waiting}),
  162. %% We replied with a proper response. Proxies should be happy enough,
  163. %% we can now read the 8 last bytes of the challenge keys and send
  164. %% the challenge response directly to the socket.
  165. case cowboy_http_req:body(8, Req2) of
  166. {ok, Key3, Req3} ->
  167. Challenge = hixie76_challenge(Key1, Key2, Key3),
  168. Transport:send(Socket, Challenge),
  169. handler_before_loop(State#state{messages=Transport:messages()},
  170. Req3, HandlerState, <<>>);
  171. _Any ->
  172. closed %% If an error happened reading the body, stop there.
  173. end;
  174. websocket_handshake(State=#state{challenge=Challenge},
  175. Req=#http_req{transport=Transport}, HandlerState) ->
  176. {ok, Req2} = cowboy_http_req:upgrade_reply(
  177. 101,
  178. [{<<"Upgrade">>, <<"websocket">>},
  179. {<<"Sec-Websocket-Accept">>, Challenge}],
  180. Req#http_req{resp_state=waiting}),
  181. handler_before_loop(State#state{messages=Transport:messages()},
  182. Req2, HandlerState, <<>>).
  183. -spec handler_before_loop(#state{}, #http_req{}, any(), binary()) -> closed | none().
  184. handler_before_loop(State=#state{hibernate=true},
  185. Req=#http_req{socket=Socket, transport=Transport},
  186. HandlerState, SoFar) ->
  187. Transport:setopts(Socket, [{active, once}]),
  188. State2 = handler_loop_timeout(State),
  189. erlang:hibernate(?MODULE, handler_loop, [State2#state{hibernate=false},
  190. Req, HandlerState, SoFar]);
  191. handler_before_loop(State, Req=#http_req{socket=Socket, transport=Transport},
  192. HandlerState, SoFar) ->
  193. Transport:setopts(Socket, [{active, once}]),
  194. State2 = handler_loop_timeout(State),
  195. handler_loop(State2, Req, HandlerState, SoFar).
  196. -spec handler_loop_timeout(#state{}) -> #state{}.
  197. handler_loop_timeout(State=#state{timeout=infinity}) ->
  198. State#state{timeout_ref=undefined};
  199. handler_loop_timeout(State=#state{timeout=Timeout, timeout_ref=PrevRef}) ->
  200. _ = case PrevRef of undefined -> ignore; PrevRef ->
  201. erlang:cancel_timer(PrevRef) end,
  202. TRef = make_ref(),
  203. erlang:send_after(Timeout, self(), {?MODULE, timeout, TRef}),
  204. State#state{timeout_ref=TRef}.
  205. %% @private
  206. -spec handler_loop(#state{}, #http_req{}, any(), binary()) -> closed | none().
  207. handler_loop(State=#state{messages={OK, Closed, Error}, timeout_ref=TRef},
  208. Req=#http_req{socket=Socket}, HandlerState, SoFar) ->
  209. receive
  210. {OK, Socket, Data} ->
  211. websocket_data(State, Req, HandlerState,
  212. << SoFar/binary, Data/binary >>);
  213. {Closed, Socket} ->
  214. handler_terminate(State, Req, HandlerState, {error, closed});
  215. {Error, Socket, Reason} ->
  216. handler_terminate(State, Req, HandlerState, {error, Reason});
  217. {?MODULE, timeout, TRef} ->
  218. websocket_close(State, Req, HandlerState, {normal, timeout});
  219. {?MODULE, timeout, OlderTRef} when is_reference(OlderTRef) ->
  220. handler_loop(State, Req, HandlerState, SoFar);
  221. Message ->
  222. handler_call(State, Req, HandlerState,
  223. SoFar, websocket_info, Message, fun handler_before_loop/4)
  224. end.
  225. -spec websocket_data(#state{}, #http_req{}, any(), binary()) -> closed | none().
  226. %% No more data.
  227. websocket_data(State, Req, HandlerState, <<>>) ->
  228. handler_before_loop(State, Req, HandlerState, <<>>);
  229. %% hixie-76 close frame.
  230. websocket_data(State=#state{version=0}, Req, HandlerState,
  231. << 255, 0, _Rest/binary >>) ->
  232. websocket_close(State, Req, HandlerState, {normal, closed});
  233. %% hixie-76 data frame. We only support the frame type 0, same as the specs.
  234. websocket_data(State=#state{version=0, eop=EOP}, Req, HandlerState,
  235. Data = << 0, _/binary >>) ->
  236. case binary:match(Data, EOP) of
  237. {Pos, 1} ->
  238. Pos2 = Pos - 1,
  239. << 0, Payload:Pos2/binary, 255, Rest/bits >> = Data,
  240. handler_call(State, Req, HandlerState,
  241. Rest, websocket_handle, {text, Payload}, fun websocket_data/4);
  242. nomatch ->
  243. %% @todo We probably should allow limiting frame length.
  244. handler_before_loop(State, Req, HandlerState, Data)
  245. end;
  246. %% incomplete hybi data frame.
  247. websocket_data(State=#state{version=Version}, Req, HandlerState, Data)
  248. when Version =/= 0, byte_size(Data) =:= 1 ->
  249. handler_before_loop(State, Req, HandlerState, Data);
  250. %% hybi data frame.
  251. %% @todo Handle Fin.
  252. websocket_data(State=#state{version=Version}, Req, HandlerState, Data)
  253. when Version =/= 0 ->
  254. << 1:1, 0:3, Opcode:4, Mask:1, PayloadLen:7, Rest/bits >> = Data,
  255. {PayloadLen2, Rest2} = case {PayloadLen, Rest} of
  256. {126, << L:16, R/bits >>} -> {L, R};
  257. {126, Rest} -> {undefined, Rest};
  258. {127, << 0:1, L:63, R/bits >>} -> {L, R};
  259. {127, Rest} -> {undefined, Rest};
  260. {PayloadLen, Rest} -> {PayloadLen, Rest}
  261. end,
  262. case {Mask, PayloadLen2} of
  263. {0, 0} ->
  264. websocket_dispatch(State, Req, HandlerState, Rest2, Opcode, <<>>);
  265. {1, N} when N + 4 > byte_size(Rest2); N =:= undefined ->
  266. %% @todo We probably should allow limiting frame length.
  267. handler_before_loop(State, Req, HandlerState, Data);
  268. {1, _N} ->
  269. << MaskKey:32, Payload:PayloadLen2/binary, Rest3/bits >> = Rest2,
  270. websocket_unmask(State, Req, HandlerState, Rest3,
  271. Opcode, Payload, MaskKey)
  272. end;
  273. %% Something was wrong with the frame. Close the connection.
  274. websocket_data(State, Req, HandlerState, _Bad) ->
  275. websocket_close(State, Req, HandlerState, {error, badframe}).
  276. %% hybi unmasking.
  277. -spec websocket_unmask(#state{}, #http_req{}, any(), binary(),
  278. opcode(), binary(), mask_key()) -> closed | none().
  279. websocket_unmask(State, Req, HandlerState, RemainingData,
  280. Opcode, Payload, MaskKey) ->
  281. websocket_unmask(State, Req, HandlerState, RemainingData,
  282. Opcode, Payload, MaskKey, <<>>).
  283. -spec websocket_unmask(#state{}, #http_req{}, any(), binary(),
  284. opcode(), binary(), mask_key(), binary()) -> closed | none().
  285. websocket_unmask(State, Req, HandlerState, RemainingData,
  286. Opcode, << O:32, Rest/bits >>, MaskKey, Acc) ->
  287. T = O bxor MaskKey,
  288. websocket_unmask(State, Req, HandlerState, RemainingData,
  289. Opcode, Rest, MaskKey, << Acc/binary, T:32 >>);
  290. websocket_unmask(State, Req, HandlerState, RemainingData,
  291. Opcode, << O:24 >>, MaskKey, Acc) ->
  292. << MaskKey2:24, _:8 >> = << MaskKey:32 >>,
  293. T = O bxor MaskKey2,
  294. websocket_dispatch(State, Req, HandlerState, RemainingData,
  295. Opcode, << Acc/binary, T:24 >>);
  296. websocket_unmask(State, Req, HandlerState, RemainingData,
  297. Opcode, << O:16 >>, MaskKey, Acc) ->
  298. << MaskKey2:16, _:16 >> = << MaskKey:32 >>,
  299. T = O bxor MaskKey2,
  300. websocket_dispatch(State, Req, HandlerState, RemainingData,
  301. Opcode, << Acc/binary, T:16 >>);
  302. websocket_unmask(State, Req, HandlerState, RemainingData,
  303. Opcode, << O:8 >>, MaskKey, Acc) ->
  304. << MaskKey2:8, _:24 >> = << MaskKey:32 >>,
  305. T = O bxor MaskKey2,
  306. websocket_dispatch(State, Req, HandlerState, RemainingData,
  307. Opcode, << Acc/binary, T:8 >>);
  308. websocket_unmask(State, Req, HandlerState, RemainingData,
  309. Opcode, <<>>, _MaskKey, Acc) ->
  310. websocket_dispatch(State, Req, HandlerState, RemainingData,
  311. Opcode, Acc).
  312. %% hybi dispatching.
  313. -spec websocket_dispatch(#state{}, #http_req{}, any(), binary(),
  314. opcode(), binary()) -> closed | none().
  315. %% @todo Fragmentation.
  316. %~ websocket_dispatch(State, Req, HandlerState, RemainingData, 0, Payload) ->
  317. %% Text frame.
  318. websocket_dispatch(State, Req, HandlerState, RemainingData, 1, Payload) ->
  319. handler_call(State, Req, HandlerState, RemainingData,
  320. websocket_handle, {text, Payload}, fun websocket_data/4);
  321. %% Binary frame.
  322. websocket_dispatch(State, Req, HandlerState, RemainingData, 2, Payload) ->
  323. handler_call(State, Req, HandlerState, RemainingData,
  324. websocket_handle, {binary, Payload}, fun websocket_data/4);
  325. %% Close control frame.
  326. %% @todo Handle the optional Payload.
  327. websocket_dispatch(State, Req, HandlerState, _RemainingData, 8, _Payload) ->
  328. websocket_close(State, Req, HandlerState, {normal, closed});
  329. %% Ping control frame. Send a pong back and forward the ping to the handler.
  330. websocket_dispatch(State, Req=#http_req{socket=Socket, transport=Transport},
  331. HandlerState, RemainingData, 9, Payload) ->
  332. Len = hybi_payload_length(byte_size(Payload)),
  333. Transport:send(Socket, << 1:1, 0:3, 10:4, 0:1, Len/bits, Payload/binary >>),
  334. handler_call(State, Req, HandlerState, RemainingData,
  335. websocket_handle, {ping, Payload}, fun websocket_data/4);
  336. %% Pong control frame.
  337. websocket_dispatch(State, Req, HandlerState, RemainingData, 10, Payload) ->
  338. handler_call(State, Req, HandlerState, RemainingData,
  339. websocket_handle, {pong, Payload}, fun websocket_data/4).
  340. -spec handler_call(#state{}, #http_req{}, any(), binary(),
  341. atom(), any(), fun()) -> closed | none().
  342. handler_call(State=#state{handler=Handler, opts=Opts}, Req, HandlerState,
  343. RemainingData, Callback, Message, NextState) ->
  344. try Handler:Callback(Message, Req, HandlerState) of
  345. {ok, Req2, HandlerState2} ->
  346. NextState(State, Req2, HandlerState2, RemainingData);
  347. {ok, Req2, HandlerState2, hibernate} ->
  348. NextState(State#state{hibernate=true},
  349. Req2, HandlerState2, RemainingData);
  350. {reply, Payload, Req2, HandlerState2} ->
  351. websocket_send(Payload, State, Req2),
  352. NextState(State, Req2, HandlerState2, RemainingData);
  353. {reply, Payload, Req2, HandlerState2, hibernate} ->
  354. websocket_send(Payload, State, Req2),
  355. NextState(State#state{hibernate=true},
  356. Req2, HandlerState2, RemainingData);
  357. {shutdown, Req2, HandlerState2} ->
  358. websocket_close(State, Req2, HandlerState2, {normal, shutdown})
  359. catch Class:Reason ->
  360. error_logger:error_msg(
  361. "** Handler ~p terminating in ~p/3~n"
  362. " for the reason ~p:~p~n** Message was ~p~n"
  363. "** Options were ~p~n** Handler state was ~p~n"
  364. "** Request was ~p~n** Stacktrace: ~p~n~n",
  365. [Handler, Callback, Class, Reason, Message, Opts,
  366. HandlerState, Req, erlang:get_stacktrace()]),
  367. websocket_close(State, Req, HandlerState, {error, handler})
  368. end.
  369. -spec websocket_send(binary(), #state{}, #http_req{}) -> closed | ignore.
  370. %% hixie-76 text frame.
  371. websocket_send({text, Payload}, #state{version=0},
  372. #http_req{socket=Socket, transport=Transport}) ->
  373. Transport:send(Socket, [0, Payload, 255]);
  374. %% Ignore all unknown frame types for compatibility with hixie 76.
  375. websocket_send(_Any, #state{version=0}, _Req) ->
  376. ignore;
  377. websocket_send({Type, Payload}, _State,
  378. #http_req{socket=Socket, transport=Transport}) ->
  379. Opcode = case Type of
  380. text -> 1;
  381. binary -> 2;
  382. ping -> 9;
  383. pong -> 10
  384. end,
  385. Len = hybi_payload_length(iolist_size(Payload)),
  386. Transport:send(Socket, [<< 1:1, 0:3, Opcode:4, 0:1, Len/bits >>,
  387. Payload]).
  388. -spec websocket_close(#state{}, #http_req{}, any(), {atom(), atom()}) -> closed.
  389. websocket_close(State=#state{version=0}, Req=#http_req{socket=Socket,
  390. transport=Transport}, HandlerState, Reason) ->
  391. Transport:send(Socket, << 255, 0 >>),
  392. handler_terminate(State, Req, HandlerState, Reason);
  393. %% @todo Send a Payload? Using Reason is usually good but we're quite careless.
  394. websocket_close(State, Req=#http_req{socket=Socket,
  395. transport=Transport}, HandlerState, Reason) ->
  396. Transport:send(Socket, << 1:1, 0:3, 8:4, 0:8 >>),
  397. handler_terminate(State, Req, HandlerState, Reason).
  398. -spec handler_terminate(#state{}, #http_req{},
  399. any(), atom() | {atom(), atom()}) -> closed.
  400. handler_terminate(#state{handler=Handler, opts=Opts},
  401. Req, HandlerState, TerminateReason) ->
  402. try
  403. Handler:websocket_terminate(TerminateReason, Req, HandlerState)
  404. catch Class:Reason ->
  405. error_logger:error_msg(
  406. "** Handler ~p terminating in websocket_terminate/3~n"
  407. " for the reason ~p:~p~n** Initial reason was ~p~n"
  408. "** Options were ~p~n** Handler state was ~p~n"
  409. "** Request was ~p~n** Stacktrace: ~p~n~n",
  410. [Handler, Class, Reason, TerminateReason, Opts,
  411. HandlerState, Req, erlang:get_stacktrace()])
  412. end,
  413. closed.
  414. %% hixie-76 specific.
  415. -spec hixie76_challenge(binary(), binary(), binary()) -> binary().
  416. hixie76_challenge(Key1, Key2, Key3) ->
  417. IntKey1 = hixie76_key_to_integer(Key1),
  418. IntKey2 = hixie76_key_to_integer(Key2),
  419. erlang:md5(<< IntKey1:32, IntKey2:32, Key3/binary >>).
  420. -spec hixie76_key_to_integer(binary()) -> integer().
  421. hixie76_key_to_integer(Key) ->
  422. Number = list_to_integer([C || << C >> <= Key, C >= $0, C =< $9]),
  423. Spaces = length([C || << C >> <= Key, C =:= 32]),
  424. Number div Spaces.
  425. -spec hixie76_location(atom(), binary(), inet:ip_port(), binary(), binary())
  426. -> binary().
  427. hixie76_location(Protocol, Host, Port, Path, <<>>) ->
  428. << (hixie76_location_protocol(Protocol))/binary, "://", Host/binary,
  429. (hixie76_location_port(Protocol, Port))/binary, Path/binary>>;
  430. hixie76_location(Protocol, Host, Port, Path, QS) ->
  431. << (hixie76_location_protocol(Protocol))/binary, "://", Host/binary,
  432. (hixie76_location_port(Protocol, Port))/binary, Path/binary, "?", QS/binary >>.
  433. -spec hixie76_location_protocol(atom()) -> binary().
  434. hixie76_location_protocol(ssl) -> <<"wss">>;
  435. hixie76_location_protocol(_) -> <<"ws">>.
  436. %% @todo We should add a secure/0 function to transports
  437. %% instead of relying on their name.
  438. -spec hixie76_location_port(atom(), inet:ip_port()) -> binary().
  439. hixie76_location_port(ssl, 443) ->
  440. <<>>;
  441. hixie76_location_port(tcp, 80) ->
  442. <<>>;
  443. hixie76_location_port(_, Port) ->
  444. <<":", (list_to_binary(integer_to_list(Port)))/binary>>.
  445. %% hybi specific.
  446. -spec hybi_challenge(binary()) -> binary().
  447. hybi_challenge(Key) ->
  448. Bin = << Key/binary, "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" >>,
  449. base64:encode(crypto:sha(Bin)).
  450. -spec hybi_payload_length(0..16#7fffffffffffffff)
  451. -> << _:7 >> | << _:23 >> | << _:71 >>.
  452. hybi_payload_length(N) ->
  453. case N of
  454. N when N =< 125 -> << N:7 >>;
  455. N when N =< 16#ffff -> << 126:7, N:16 >>;
  456. N when N =< 16#7fffffffffffffff -> << 127:7, N:64 >>
  457. end.
  458. %% Tests.
  459. -ifdef(TEST).
  460. hixie76_location_test() ->
  461. ?assertEqual(<<"ws://localhost/path">>,
  462. hixie76_location(tcp, <<"localhost">>, 80, <<"/path">>, <<>>)),
  463. ?assertEqual(<<"ws://localhost:443/path">>,
  464. hixie76_location(tcp, <<"localhost">>, 443, <<"/path">>, <<>>)),
  465. ?assertEqual(<<"ws://localhost:8080/path">>,
  466. hixie76_location(tcp, <<"localhost">>, 8080, <<"/path">>, <<>>)),
  467. ?assertEqual(<<"ws://localhost:8080/path?dummy=2785">>,
  468. hixie76_location(tcp, <<"localhost">>, 8080, <<"/path">>, <<"dummy=2785">>)),
  469. ?assertEqual(<<"wss://localhost/path">>,
  470. hixie76_location(ssl, <<"localhost">>, 443, <<"/path">>, <<>>)),
  471. ?assertEqual(<<"wss://localhost:8443/path">>,
  472. hixie76_location(ssl, <<"localhost">>, 8443, <<"/path">>, <<>>)),
  473. ?assertEqual(<<"wss://localhost:8443/path?dummy=2785">>,
  474. hixie76_location(ssl, <<"localhost">>, 8443, <<"/path">>, <<"dummy=2785">>)),
  475. ok.
  476. -endif.