cowboy_http_websocket.erl 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  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{}) -> ok | 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{}) -> ok | 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{}) -> ok.
  133. upgrade_error(Req) ->
  134. {ok, Req2} = cowboy_http_req:reply(400, [], [],
  135. Req#http_req{resp_state=waiting}),
  136. upgrade_terminate(Req2).
  137. %% @see cowboy_http_protocol:ensure_response/1
  138. -spec upgrade_denied(#http_req{}) -> ok.
  139. upgrade_denied(Req=#http_req{resp_state=done}) ->
  140. upgrade_terminate(Req);
  141. upgrade_denied(Req=#http_req{resp_state=waiting}) ->
  142. {ok, Req2} = cowboy_http_req:reply(400, [], [], Req),
  143. upgrade_terminate(Req2);
  144. upgrade_denied(Req=#http_req{method='HEAD', resp_state=chunks}) ->
  145. upgrade_terminate(Req);
  146. upgrade_denied(Req=#http_req{socket=Socket, transport=Transport,
  147. resp_state=chunks}) ->
  148. Transport:send(Socket, <<"0\r\n\r\n">>),
  149. upgrade_terminate(Req).
  150. -spec upgrade_terminate(#http_req{}) -> ok.
  151. upgrade_terminate(#http_req{socket=Socket, transport=Transport}) ->
  152. Transport:close(Socket).
  153. -spec websocket_handshake(#state{}, #http_req{}, any()) -> ok | none().
  154. websocket_handshake(State=#state{version=0, origin=Origin,
  155. challenge={Key1, Key2}}, Req=#http_req{socket=Socket,
  156. transport=Transport, raw_host=Host, port=Port,
  157. raw_path=Path, raw_qs=QS}, HandlerState) ->
  158. Location = hixie76_location(Transport:name(), Host, Port, Path, QS),
  159. {ok, Req2} = cowboy_http_req:upgrade_reply(
  160. <<"101 WebSocket Protocol Handshake">>,
  161. [{<<"Upgrade">>, <<"WebSocket">>},
  162. {<<"Sec-Websocket-Location">>, Location},
  163. {<<"Sec-Websocket-Origin">>, Origin}],
  164. Req#http_req{resp_state=waiting}),
  165. %% We replied with a proper response. Proxies should be happy enough,
  166. %% we can now read the 8 last bytes of the challenge keys and send
  167. %% the challenge response directly to the socket.
  168. {ok, Key3, Req3} = cowboy_http_req:body(8, Req2),
  169. Challenge = hixie76_challenge(Key1, Key2, Key3),
  170. Transport:send(Socket, Challenge),
  171. handler_before_loop(State#state{messages=Transport:messages()},
  172. Req3, HandlerState, <<>>);
  173. websocket_handshake(State=#state{challenge=Challenge},
  174. Req=#http_req{transport=Transport}, HandlerState) ->
  175. {ok, Req2} = cowboy_http_req:upgrade_reply(
  176. 101,
  177. [{<<"Upgrade">>, <<"websocket">>},
  178. {<<"Sec-Websocket-Accept">>, Challenge}],
  179. Req#http_req{resp_state=waiting}),
  180. handler_before_loop(State#state{messages=Transport:messages()},
  181. Req2, HandlerState, <<>>).
  182. -spec handler_before_loop(#state{}, #http_req{}, any(), binary()) -> ok | none().
  183. handler_before_loop(State=#state{hibernate=true},
  184. Req=#http_req{socket=Socket, transport=Transport},
  185. HandlerState, SoFar) ->
  186. Transport:setopts(Socket, [{active, once}]),
  187. State2 = handler_loop_timeout(State),
  188. erlang:hibernate(?MODULE, handler_loop, [State2#state{hibernate=false},
  189. Req, HandlerState, SoFar]);
  190. handler_before_loop(State, Req=#http_req{socket=Socket, transport=Transport},
  191. HandlerState, SoFar) ->
  192. Transport:setopts(Socket, [{active, once}]),
  193. State2 = handler_loop_timeout(State),
  194. handler_loop(State2, Req, HandlerState, SoFar).
  195. -spec handler_loop_timeout(#state{}) -> #state{}.
  196. handler_loop_timeout(State=#state{timeout=infinity}) ->
  197. State#state{timeout_ref=undefined};
  198. handler_loop_timeout(State=#state{timeout=Timeout, timeout_ref=PrevRef}) ->
  199. _ = case PrevRef of undefined -> ignore; PrevRef ->
  200. erlang:cancel_timer(PrevRef) end,
  201. TRef = make_ref(),
  202. erlang:send_after(Timeout, self(), {?MODULE, timeout, TRef}),
  203. State#state{timeout_ref=TRef}.
  204. %% @private
  205. -spec handler_loop(#state{}, #http_req{}, any(), binary()) -> ok | none().
  206. handler_loop(State=#state{messages={OK, Closed, Error}, timeout_ref=TRef},
  207. Req=#http_req{socket=Socket}, HandlerState, SoFar) ->
  208. receive
  209. {OK, Socket, Data} ->
  210. websocket_data(State, Req, HandlerState,
  211. << SoFar/binary, Data/binary >>);
  212. {Closed, Socket} ->
  213. handler_terminate(State, Req, HandlerState, {error, closed});
  214. {Error, Socket, Reason} ->
  215. handler_terminate(State, Req, HandlerState, {error, Reason});
  216. {?MODULE, timeout, TRef} ->
  217. websocket_close(State, Req, HandlerState, {normal, timeout});
  218. {?MODULE, timeout, OlderTRef} when is_reference(OlderTRef) ->
  219. handler_loop(State, Req, HandlerState, SoFar);
  220. Message ->
  221. handler_call(State, Req, HandlerState,
  222. SoFar, websocket_info, Message, fun handler_before_loop/4)
  223. end.
  224. -spec websocket_data(#state{}, #http_req{}, any(), binary()) -> ok | none().
  225. %% No more data.
  226. websocket_data(State, Req, HandlerState, <<>>) ->
  227. handler_before_loop(State, Req, HandlerState, <<>>);
  228. %% hixie-76 close frame.
  229. websocket_data(State=#state{version=0}, Req, HandlerState,
  230. << 255, 0, _Rest/bits >>) ->
  231. websocket_close(State, Req, HandlerState, {normal, closed});
  232. %% hixie-76 data frame. We only support the frame type 0, same as the specs.
  233. websocket_data(State=#state{version=0, eop=EOP}, Req, HandlerState,
  234. Data = << 0, _/bits >>) ->
  235. case binary:match(Data, EOP) of
  236. {Pos, 1} ->
  237. Pos2 = Pos - 1,
  238. << 0, Payload:Pos2/binary, 255, Rest/bits >> = Data,
  239. handler_call(State, Req, HandlerState,
  240. Rest, websocket_handle, {text, Payload}, fun websocket_data/4);
  241. nomatch ->
  242. %% @todo We probably should allow limiting frame length.
  243. handler_before_loop(State, Req, HandlerState, Data)
  244. end;
  245. %% incomplete hybi data frame.
  246. websocket_data(State=#state{version=Version}, Req, HandlerState, Data)
  247. when Version =/= 0, byte_size(Data) =:= 1 ->
  248. handler_before_loop(State, Req, HandlerState, Data);
  249. %% hybi data frame.
  250. %% @todo Handle Fin.
  251. websocket_data(State=#state{version=Version}, Req, HandlerState, Data)
  252. when Version =/= 0 ->
  253. << 1:1, 0:3, Opcode:4, Mask:1, PayloadLen:7, Rest/bits >> = Data,
  254. {PayloadLen2, Rest2} = case {PayloadLen, Rest} of
  255. {126, << L:16, R/bits >>} -> {L, R};
  256. {126, Rest} -> {undefined, Rest};
  257. {127, << 0:1, L:63, R/bits >>} -> {L, R};
  258. {127, Rest} -> {undefined, Rest};
  259. {PayloadLen, Rest} -> {PayloadLen, Rest}
  260. end,
  261. case {Mask, PayloadLen2} of
  262. {0, 0} ->
  263. websocket_dispatch(State, Req, HandlerState, Rest2, Opcode, <<>>);
  264. {1, N} when N + 4 > byte_size(Rest2); N =:= undefined ->
  265. %% @todo We probably should allow limiting frame length.
  266. handler_before_loop(State, Req, HandlerState, Data);
  267. {1, _N} ->
  268. << MaskKey:32, Payload:PayloadLen2/binary, Rest3/bits >> = Rest2,
  269. websocket_unmask(State, Req, HandlerState, Rest3,
  270. Opcode, Payload, MaskKey)
  271. end;
  272. %% Something was wrong with the frame. Close the connection.
  273. websocket_data(State, Req, HandlerState, _Bad) ->
  274. websocket_close(State, Req, HandlerState, {error, badframe}).
  275. %% hybi unmasking.
  276. -spec websocket_unmask(#state{}, #http_req{}, any(), binary(),
  277. opcode(), binary(), mask_key()) -> ok | none().
  278. websocket_unmask(State, Req, HandlerState, RemainingData,
  279. Opcode, Payload, MaskKey) ->
  280. websocket_unmask(State, Req, HandlerState, RemainingData,
  281. Opcode, Payload, MaskKey, <<>>).
  282. -spec websocket_unmask(#state{}, #http_req{}, any(), binary(),
  283. opcode(), binary(), mask_key(), binary()) -> ok | none().
  284. websocket_unmask(State, Req, HandlerState, RemainingData,
  285. Opcode, << O:32, Rest/bits >>, MaskKey, Acc) ->
  286. T = O bxor MaskKey,
  287. websocket_unmask(State, Req, HandlerState, RemainingData,
  288. Opcode, Rest, MaskKey, << Acc/binary, T:32 >>);
  289. websocket_unmask(State, Req, HandlerState, RemainingData,
  290. Opcode, << O:24 >>, MaskKey, Acc) ->
  291. << MaskKey2:24, _:8 >> = << MaskKey:32 >>,
  292. T = O bxor MaskKey2,
  293. websocket_dispatch(State, Req, HandlerState, RemainingData,
  294. Opcode, << Acc/binary, T:24 >>);
  295. websocket_unmask(State, Req, HandlerState, RemainingData,
  296. Opcode, << O:16 >>, MaskKey, Acc) ->
  297. << MaskKey2:16, _:16 >> = << MaskKey:32 >>,
  298. T = O bxor MaskKey2,
  299. websocket_dispatch(State, Req, HandlerState, RemainingData,
  300. Opcode, << Acc/binary, T:16 >>);
  301. websocket_unmask(State, Req, HandlerState, RemainingData,
  302. Opcode, << O:8 >>, MaskKey, Acc) ->
  303. << MaskKey2:8, _:24 >> = << MaskKey:32 >>,
  304. T = O bxor MaskKey2,
  305. websocket_dispatch(State, Req, HandlerState, RemainingData,
  306. Opcode, << Acc/binary, T:8 >>);
  307. websocket_unmask(State, Req, HandlerState, RemainingData,
  308. Opcode, <<>>, _MaskKey, Acc) ->
  309. websocket_dispatch(State, Req, HandlerState, RemainingData,
  310. Opcode, Acc).
  311. %% hybi dispatching.
  312. -spec websocket_dispatch(#state{}, #http_req{}, any(), binary(),
  313. opcode(), binary()) -> ok | none().
  314. %% @todo Fragmentation.
  315. %~ websocket_dispatch(State, Req, HandlerState, RemainingData, 0, Payload) ->
  316. %% Text frame.
  317. websocket_dispatch(State, Req, HandlerState, RemainingData, 1, Payload) ->
  318. handler_call(State, Req, HandlerState, RemainingData,
  319. websocket_handle, {text, Payload}, fun websocket_data/4);
  320. %% Binary frame.
  321. websocket_dispatch(State, Req, HandlerState, RemainingData, 2, Payload) ->
  322. handler_call(State, Req, HandlerState, RemainingData,
  323. websocket_handle, {binary, Payload}, fun websocket_data/4);
  324. %% Close control frame.
  325. %% @todo Handle the optional Payload.
  326. websocket_dispatch(State, Req, HandlerState, _RemainingData, 8, _Payload) ->
  327. websocket_close(State, Req, HandlerState, {normal, closed});
  328. %% Ping control frame. Send a pong back and forward the ping to the handler.
  329. websocket_dispatch(State, Req=#http_req{socket=Socket, transport=Transport},
  330. HandlerState, RemainingData, 9, Payload) ->
  331. Len = hybi_payload_length(byte_size(Payload)),
  332. Transport:send(Socket, << 1:1, 0:3, 10:4, 0:1, Len/bits, Payload/binary >>),
  333. handler_call(State, Req, HandlerState, RemainingData,
  334. websocket_handle, {ping, Payload}, fun websocket_data/4);
  335. %% Pong control frame.
  336. websocket_dispatch(State, Req, HandlerState, RemainingData, 10, Payload) ->
  337. handler_call(State, Req, HandlerState, RemainingData,
  338. websocket_handle, {pong, Payload}, fun websocket_data/4).
  339. -spec handler_call(#state{}, #http_req{}, any(), binary(),
  340. atom(), any(), fun()) -> ok | none().
  341. handler_call(State=#state{handler=Handler, opts=Opts}, Req, HandlerState,
  342. RemainingData, Callback, Message, NextState) ->
  343. try Handler:Callback(Message, Req, HandlerState) of
  344. {ok, Req2, HandlerState2} ->
  345. NextState(State, Req2, HandlerState2, RemainingData);
  346. {ok, Req2, HandlerState2, hibernate} ->
  347. NextState(State#state{hibernate=true},
  348. Req2, HandlerState2, RemainingData);
  349. {reply, Payload, Req2, HandlerState2} ->
  350. websocket_send(Payload, State, Req2),
  351. NextState(State, Req2, HandlerState2, RemainingData);
  352. {reply, Payload, Req2, HandlerState2, hibernate} ->
  353. websocket_send(Payload, State, Req2),
  354. NextState(State#state{hibernate=true},
  355. Req2, HandlerState2, RemainingData);
  356. {shutdown, Req2, HandlerState2} ->
  357. websocket_close(State, Req2, HandlerState2, {normal, shutdown})
  358. catch Class:Reason ->
  359. error_logger:error_msg(
  360. "** Handler ~p terminating in ~p/3~n"
  361. " for the reason ~p:~p~n** Message was ~p~n"
  362. "** Options were ~p~n** Handler state was ~p~n"
  363. "** Request was ~p~n** Stacktrace: ~p~n~n",
  364. [Handler, Callback, Class, Reason, Message, Opts,
  365. HandlerState, Req, erlang:get_stacktrace()]),
  366. websocket_close(State, Req, HandlerState, {error, handler})
  367. end.
  368. -spec websocket_send(binary(), #state{}, #http_req{}) -> ok | ignore.
  369. %% hixie-76 text frame.
  370. websocket_send({text, Payload}, #state{version=0},
  371. #http_req{socket=Socket, transport=Transport}) ->
  372. Transport:send(Socket, [0, Payload, 255]);
  373. %% Ignore all unknown frame types for compatibility with hixie 76.
  374. websocket_send(_Any, #state{version=0}, _Req) ->
  375. ignore;
  376. websocket_send({Type, Payload}, _State,
  377. #http_req{socket=Socket, transport=Transport}) ->
  378. Opcode = case Type of
  379. text -> 1;
  380. binary -> 2;
  381. ping -> 9;
  382. pong -> 10
  383. end,
  384. Len = hybi_payload_length(iolist_size(Payload)),
  385. Transport:send(Socket, [<< 1:1, 0:3, Opcode:4, 0:1, Len/bits >>,
  386. Payload]).
  387. -spec websocket_close(#state{}, #http_req{}, any(), {atom(), atom()}) -> ok.
  388. websocket_close(State=#state{version=0}, Req=#http_req{socket=Socket,
  389. transport=Transport}, HandlerState, Reason) ->
  390. Transport:send(Socket, << 255, 0 >>),
  391. Transport:close(Socket),
  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. Transport:close(Socket),
  398. handler_terminate(State, Req, HandlerState, Reason).
  399. -spec handler_terminate(#state{}, #http_req{},
  400. any(), atom() | {atom(), atom()}) -> ok.
  401. handler_terminate(#state{handler=Handler, opts=Opts},
  402. Req, HandlerState, TerminateReason) ->
  403. try
  404. Handler:websocket_terminate(TerminateReason, Req, HandlerState)
  405. catch Class:Reason ->
  406. error_logger:error_msg(
  407. "** Handler ~p terminating in websocket_terminate/3~n"
  408. " for the reason ~p:~p~n** Initial reason was ~p~n"
  409. "** Options were ~p~n** Handler state was ~p~n"
  410. "** Request was ~p~n** Stacktrace: ~p~n~n",
  411. [Handler, Class, Reason, TerminateReason, Opts,
  412. HandlerState, Req, erlang:get_stacktrace()])
  413. end.
  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.