cowboy_http_websocket.erl 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  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("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.
  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. -spec websocket_upgrade(#state{}, #http_req{}) -> {ok, #state{}, #http_req{}}.
  69. websocket_upgrade(State, Req) ->
  70. {ConnTokens, Req2}
  71. = cowboy_http_req:parse_header('Connection', Req),
  72. true = lists:member(<<"upgrade">>, ConnTokens),
  73. %% @todo Should probably send a 426 if the Upgrade header is missing.
  74. {[<<"websocket">>], Req3} = cowboy_http_req:parse_header('Upgrade', Req2),
  75. {Version, Req4} = cowboy_http_req:header(<<"Sec-Websocket-Version">>, Req3),
  76. websocket_upgrade(Version, State, Req4).
  77. %% @todo Handle the Sec-Websocket-Protocol header.
  78. %% @todo Reply a proper error, don't die, if a required header is undefined.
  79. -spec websocket_upgrade(undefined | <<_:8>>, #state{}, #http_req{})
  80. -> {ok, #state{}, #http_req{}}.
  81. %% No version given. Assuming hixie-76 draft.
  82. %%
  83. %% We need to wait to send a reply back before trying to read the
  84. %% third part of the challenge key, because proxies will wait for
  85. %% a reply before sending it. Therefore we calculate the challenge
  86. %% key only in websocket_handshake/3.
  87. websocket_upgrade(undefined, State, Req=#http_req{meta=Meta}) ->
  88. {Origin, Req2} = cowboy_http_req:header(<<"Origin">>, Req),
  89. {Key1, Req3} = cowboy_http_req:header(<<"Sec-Websocket-Key1">>, Req2),
  90. {Key2, Req4} = cowboy_http_req:header(<<"Sec-Websocket-Key2">>, Req3),
  91. false = lists:member(undefined, [Origin, Key1, Key2]),
  92. EOP = binary:compile_pattern(<< 255 >>),
  93. {ok, State#state{version=0, origin=Origin, challenge={Key1, Key2},
  94. eop=EOP}, Req4#http_req{meta=[{websocket_version, 0}|Meta]}};
  95. %% Versions 7 and 8. Implementation follows the hybi 7 through 17 drafts.
  96. websocket_upgrade(Version, State, Req=#http_req{meta=Meta})
  97. when Version =:= <<"7">>; Version =:= <<"8">>;
  98. Version =:= <<"13">> ->
  99. {Key, Req2} = cowboy_http_req:header(<<"Sec-Websocket-Key">>, Req),
  100. false = Key =:= undefined,
  101. Challenge = hybi_challenge(Key),
  102. IntVersion = list_to_integer(binary_to_list(Version)),
  103. {ok, State#state{version=IntVersion, challenge=Challenge},
  104. Req2#http_req{meta=[{websocket_version, IntVersion}|Meta]}}.
  105. -spec handler_init(#state{}, #http_req{}) -> closed.
  106. handler_init(State=#state{handler=Handler, opts=Opts},
  107. Req=#http_req{transport=Transport}) ->
  108. try Handler:websocket_init(Transport:name(), Req, Opts) of
  109. {ok, Req2, HandlerState} ->
  110. websocket_handshake(State, Req2, HandlerState);
  111. {ok, Req2, HandlerState, hibernate} ->
  112. websocket_handshake(State#state{hibernate=true},
  113. Req2, HandlerState);
  114. {ok, Req2, HandlerState, Timeout} ->
  115. websocket_handshake(State#state{timeout=Timeout},
  116. Req2, HandlerState);
  117. {ok, Req2, HandlerState, Timeout, hibernate} ->
  118. websocket_handshake(State#state{timeout=Timeout,
  119. hibernate=true}, Req2, HandlerState);
  120. {shutdown, Req2} ->
  121. upgrade_denied(Req2)
  122. catch Class:Reason ->
  123. upgrade_error(Req),
  124. error_logger:error_msg(
  125. "** Handler ~p terminating in websocket_init/3~n"
  126. " for the reason ~p:~p~n** Options were ~p~n"
  127. "** Request was ~p~n** Stacktrace: ~p~n~n",
  128. [Handler, Class, Reason, Opts, Req, erlang:get_stacktrace()])
  129. end.
  130. -spec upgrade_error(#http_req{}) -> closed.
  131. upgrade_error(Req) ->
  132. {ok, _Req2} = cowboy_http_req:reply(400, [], [],
  133. Req#http_req{resp_state=waiting}),
  134. closed.
  135. %% @see cowboy_http_protocol:ensure_response/1
  136. -spec upgrade_denied(#http_req{}) -> closed.
  137. upgrade_denied(#http_req{resp_state=done}) ->
  138. closed;
  139. upgrade_denied(Req=#http_req{resp_state=waiting}) ->
  140. {ok, _Req2} = cowboy_http_req:reply(400, [], [], Req),
  141. closed;
  142. upgrade_denied(#http_req{method='HEAD', resp_state=chunks}) ->
  143. closed;
  144. upgrade_denied(#http_req{socket=Socket, transport=Transport,
  145. resp_state=chunks}) ->
  146. Transport:send(Socket, <<"0\r\n\r\n">>),
  147. closed.
  148. -spec websocket_handshake(#state{}, #http_req{}, any()) -> closed.
  149. websocket_handshake(State=#state{version=0, origin=Origin,
  150. challenge={Key1, Key2}}, Req=#http_req{socket=Socket,
  151. transport=Transport, raw_host=Host, port=Port,
  152. raw_path=Path, raw_qs=QS}, HandlerState) ->
  153. Location = hixie76_location(Transport:name(), Host, Port, Path, QS),
  154. {ok, Req2} = cowboy_http_req:upgrade_reply(
  155. <<"101 WebSocket Protocol Handshake">>,
  156. [{<<"Upgrade">>, <<"WebSocket">>},
  157. {<<"Sec-Websocket-Location">>, Location},
  158. {<<"Sec-Websocket-Origin">>, Origin}],
  159. Req#http_req{resp_state=waiting}),
  160. %% Flush the resp_sent message before moving on.
  161. receive {cowboy_http_req, resp_sent} -> ok after 0 -> ok end,
  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. %% Flush the resp_sent message before moving on.
  182. receive {cowboy_http_req, resp_sent} -> ok after 0 -> ok end,
  183. handler_before_loop(State#state{messages=Transport:messages()},
  184. Req2, HandlerState, <<>>).
  185. -spec handler_before_loop(#state{}, #http_req{}, any(), binary()) -> closed.
  186. handler_before_loop(State=#state{hibernate=true},
  187. Req=#http_req{socket=Socket, transport=Transport},
  188. HandlerState, SoFar) ->
  189. Transport:setopts(Socket, [{active, once}]),
  190. State2 = handler_loop_timeout(State),
  191. catch erlang:hibernate(?MODULE, handler_loop,
  192. [State2#state{hibernate=false}, Req, HandlerState, SoFar]),
  193. closed;
  194. handler_before_loop(State, Req=#http_req{socket=Socket, transport=Transport},
  195. HandlerState, SoFar) ->
  196. Transport:setopts(Socket, [{active, once}]),
  197. State2 = handler_loop_timeout(State),
  198. handler_loop(State2, Req, HandlerState, SoFar).
  199. -spec handler_loop_timeout(#state{}) -> #state{}.
  200. handler_loop_timeout(State=#state{timeout=infinity}) ->
  201. State#state{timeout_ref=undefined};
  202. handler_loop_timeout(State=#state{timeout=Timeout, timeout_ref=PrevRef}) ->
  203. _ = case PrevRef of undefined -> ignore; PrevRef ->
  204. erlang:cancel_timer(PrevRef) end,
  205. TRef = make_ref(),
  206. erlang:send_after(Timeout, self(), {?MODULE, timeout, TRef}),
  207. State#state{timeout_ref=TRef}.
  208. %% @private
  209. -spec handler_loop(#state{}, #http_req{}, any(), binary()) -> closed.
  210. handler_loop(State=#state{messages={OK, Closed, Error}, timeout_ref=TRef},
  211. Req=#http_req{socket=Socket}, HandlerState, SoFar) ->
  212. receive
  213. {OK, Socket, Data} ->
  214. websocket_data(State, Req, HandlerState,
  215. << SoFar/binary, Data/binary >>);
  216. {Closed, Socket} ->
  217. handler_terminate(State, Req, HandlerState, {error, closed});
  218. {Error, Socket, Reason} ->
  219. handler_terminate(State, Req, HandlerState, {error, Reason});
  220. {?MODULE, timeout, TRef} ->
  221. websocket_close(State, Req, HandlerState, {normal, timeout});
  222. {?MODULE, timeout, OlderTRef} when is_reference(OlderTRef) ->
  223. handler_loop(State, Req, HandlerState, SoFar);
  224. Message ->
  225. handler_call(State, Req, HandlerState,
  226. SoFar, websocket_info, Message, fun handler_before_loop/4)
  227. end.
  228. -spec websocket_data(#state{}, #http_req{}, any(), binary()) -> closed.
  229. %% No more data.
  230. websocket_data(State, Req, HandlerState, <<>>) ->
  231. handler_before_loop(State, Req, HandlerState, <<>>);
  232. %% hixie-76 close frame.
  233. websocket_data(State=#state{version=0}, Req, HandlerState,
  234. << 255, 0, _Rest/binary >>) ->
  235. websocket_close(State, Req, HandlerState, {normal, closed});
  236. %% hixie-76 data frame. We only support the frame type 0, same as the specs.
  237. websocket_data(State=#state{version=0, eop=EOP}, Req, HandlerState,
  238. Data = << 0, _/binary >>) ->
  239. case binary:match(Data, EOP) of
  240. {Pos, 1} ->
  241. Pos2 = Pos - 1,
  242. << 0, Payload:Pos2/binary, 255, Rest/bits >> = Data,
  243. handler_call(State, Req, HandlerState,
  244. Rest, websocket_handle, {text, Payload}, fun websocket_data/4);
  245. nomatch ->
  246. %% @todo We probably should allow limiting frame length.
  247. handler_before_loop(State, Req, HandlerState, Data)
  248. end;
  249. %% incomplete hybi data frame.
  250. websocket_data(State=#state{version=Version}, Req, HandlerState, Data)
  251. when Version =/= 0, byte_size(Data) =:= 1 ->
  252. handler_before_loop(State, Req, HandlerState, Data);
  253. %% hybi data frame.
  254. %% @todo Handle Fin.
  255. websocket_data(State=#state{version=Version}, Req, HandlerState, Data)
  256. when Version =/= 0 ->
  257. << 1:1, 0:3, Opcode:4, Mask:1, PayloadLen:7, Rest/bits >> = Data,
  258. case {PayloadLen, Rest} of
  259. {126, _} when Opcode >= 8 -> websocket_close(
  260. State, Req, HandlerState, {error, protocol});
  261. {127, _} when Opcode >= 8 -> websocket_close(
  262. State, Req, HandlerState, {error, protocol});
  263. {126, << L:16, R/bits >>} -> websocket_before_unmask(
  264. State, Req, HandlerState, Data, R, Opcode, Mask, L);
  265. {126, Rest} -> websocket_before_unmask(
  266. State, Req, HandlerState, Data, Rest, Opcode, Mask, undefined);
  267. {127, << 0:1, L:63, R/bits >>} -> websocket_before_unmask(
  268. State, Req, HandlerState, Data, R, Opcode, Mask, L);
  269. {127, Rest} -> websocket_before_unmask(
  270. State, Req, HandlerState, Data, Rest, Opcode, Mask, undefined);
  271. {PayloadLen, Rest} -> websocket_before_unmask(
  272. State, Req, HandlerState, Data, Rest, Opcode, Mask, PayloadLen)
  273. end;
  274. %% Something was wrong with the frame. Close the connection.
  275. websocket_data(State, Req, HandlerState, _Bad) ->
  276. websocket_close(State, Req, HandlerState, {error, badframe}).
  277. %% hybi routing depending on whether unmasking is needed.
  278. -spec websocket_before_unmask(#state{}, #http_req{}, any(), binary(),
  279. binary(), opcode(), 0 | 1, non_neg_integer() | undefined) -> closed.
  280. websocket_before_unmask(State, Req, HandlerState, Data,
  281. Rest, Opcode, Mask, PayloadLen) ->
  282. case {Mask, PayloadLen} of
  283. {0, 0} ->
  284. websocket_dispatch(State, Req, HandlerState, Rest, Opcode, <<>>);
  285. {1, N} when N + 4 > byte_size(Rest); N =:= undefined ->
  286. %% @todo We probably should allow limiting frame length.
  287. handler_before_loop(State, Req, HandlerState, Data);
  288. {1, _N} ->
  289. << MaskKey:32, Payload:PayloadLen/binary, Rest2/bits >> = Rest,
  290. websocket_unmask(State, Req, HandlerState, Rest2,
  291. Opcode, Payload, MaskKey)
  292. end.
  293. %% hybi unmasking.
  294. -spec websocket_unmask(#state{}, #http_req{}, any(), binary(),
  295. opcode(), binary(), mask_key()) -> closed.
  296. websocket_unmask(State, Req, HandlerState, RemainingData,
  297. Opcode, Payload, MaskKey) ->
  298. websocket_unmask(State, Req, HandlerState, RemainingData,
  299. Opcode, Payload, MaskKey, <<>>).
  300. -spec websocket_unmask(#state{}, #http_req{}, any(), binary(),
  301. opcode(), binary(), mask_key(), binary()) -> closed.
  302. websocket_unmask(State, Req, HandlerState, RemainingData,
  303. Opcode, << O:32, Rest/bits >>, MaskKey, Acc) ->
  304. T = O bxor MaskKey,
  305. websocket_unmask(State, Req, HandlerState, RemainingData,
  306. Opcode, Rest, MaskKey, << Acc/binary, T:32 >>);
  307. websocket_unmask(State, Req, HandlerState, RemainingData,
  308. Opcode, << O:24 >>, MaskKey, Acc) ->
  309. << MaskKey2:24, _:8 >> = << MaskKey:32 >>,
  310. T = O bxor MaskKey2,
  311. websocket_dispatch(State, Req, HandlerState, RemainingData,
  312. Opcode, << Acc/binary, T:24 >>);
  313. websocket_unmask(State, Req, HandlerState, RemainingData,
  314. Opcode, << O:16 >>, MaskKey, Acc) ->
  315. << MaskKey2:16, _:16 >> = << MaskKey:32 >>,
  316. T = O bxor MaskKey2,
  317. websocket_dispatch(State, Req, HandlerState, RemainingData,
  318. Opcode, << Acc/binary, T:16 >>);
  319. websocket_unmask(State, Req, HandlerState, RemainingData,
  320. Opcode, << O:8 >>, MaskKey, Acc) ->
  321. << MaskKey2:8, _:24 >> = << MaskKey:32 >>,
  322. T = O bxor MaskKey2,
  323. websocket_dispatch(State, Req, HandlerState, RemainingData,
  324. Opcode, << Acc/binary, T:8 >>);
  325. websocket_unmask(State, Req, HandlerState, RemainingData,
  326. Opcode, <<>>, _MaskKey, Acc) ->
  327. websocket_dispatch(State, Req, HandlerState, RemainingData,
  328. Opcode, Acc).
  329. %% hybi dispatching.
  330. -spec websocket_dispatch(#state{}, #http_req{}, any(), binary(),
  331. opcode(), binary()) -> closed.
  332. %% @todo Fragmentation.
  333. %~ websocket_dispatch(State, Req, HandlerState, RemainingData, 0, Payload) ->
  334. %% Text frame.
  335. websocket_dispatch(State, Req, HandlerState, RemainingData, 1, Payload) ->
  336. handler_call(State, Req, HandlerState, RemainingData,
  337. websocket_handle, {text, Payload}, fun websocket_data/4);
  338. %% Binary frame.
  339. websocket_dispatch(State, Req, HandlerState, RemainingData, 2, Payload) ->
  340. handler_call(State, Req, HandlerState, RemainingData,
  341. websocket_handle, {binary, Payload}, fun websocket_data/4);
  342. %% Close control frame.
  343. %% @todo Handle the optional Payload.
  344. websocket_dispatch(State, Req, HandlerState, _RemainingData, 8, _Payload) ->
  345. websocket_close(State, Req, HandlerState, {normal, closed});
  346. %% Ping control frame. Send a pong back and forward the ping to the handler.
  347. websocket_dispatch(State, Req=#http_req{socket=Socket, transport=Transport},
  348. HandlerState, RemainingData, 9, Payload) ->
  349. Len = hybi_payload_length(byte_size(Payload)),
  350. Transport:send(Socket, << 1:1, 0:3, 10:4, 0:1, Len/bits, Payload/binary >>),
  351. handler_call(State, Req, HandlerState, RemainingData,
  352. websocket_handle, {ping, Payload}, fun websocket_data/4);
  353. %% Pong control frame.
  354. websocket_dispatch(State, Req, HandlerState, RemainingData, 10, Payload) ->
  355. handler_call(State, Req, HandlerState, RemainingData,
  356. websocket_handle, {pong, Payload}, fun websocket_data/4).
  357. -spec handler_call(#state{}, #http_req{}, any(), binary(),
  358. atom(), any(), fun()) -> closed.
  359. handler_call(State=#state{handler=Handler, opts=Opts}, Req, HandlerState,
  360. RemainingData, Callback, Message, NextState) ->
  361. try Handler:Callback(Message, Req, HandlerState) of
  362. {ok, Req2, HandlerState2} ->
  363. NextState(State, Req2, HandlerState2, RemainingData);
  364. {ok, Req2, HandlerState2, hibernate} ->
  365. NextState(State#state{hibernate=true},
  366. Req2, HandlerState2, RemainingData);
  367. {reply, Payload, Req2, HandlerState2} ->
  368. websocket_send(Payload, State, Req2),
  369. NextState(State, Req2, HandlerState2, RemainingData);
  370. {reply, Payload, Req2, HandlerState2, hibernate} ->
  371. websocket_send(Payload, State, Req2),
  372. NextState(State#state{hibernate=true},
  373. Req2, HandlerState2, RemainingData);
  374. {shutdown, Req2, HandlerState2} ->
  375. websocket_close(State, Req2, HandlerState2, {normal, shutdown})
  376. catch Class:Reason ->
  377. error_logger:error_msg(
  378. "** Handler ~p terminating in ~p/3~n"
  379. " for the reason ~p:~p~n** Message was ~p~n"
  380. "** Options were ~p~n** Handler state was ~p~n"
  381. "** Request was ~p~n** Stacktrace: ~p~n~n",
  382. [Handler, Callback, Class, Reason, Message, Opts,
  383. HandlerState, Req, erlang:get_stacktrace()]),
  384. websocket_close(State, Req, HandlerState, {error, handler})
  385. end.
  386. -spec websocket_send(binary(), #state{}, #http_req{}) -> closed | ignore.
  387. %% hixie-76 text frame.
  388. websocket_send({text, Payload}, #state{version=0},
  389. #http_req{socket=Socket, transport=Transport}) ->
  390. Transport:send(Socket, [0, Payload, 255]);
  391. %% Ignore all unknown frame types for compatibility with hixie 76.
  392. websocket_send(_Any, #state{version=0}, _Req) ->
  393. ignore;
  394. websocket_send({Type, Payload}, _State,
  395. #http_req{socket=Socket, transport=Transport}) ->
  396. Opcode = case Type of
  397. text -> 1;
  398. binary -> 2;
  399. ping -> 9;
  400. pong -> 10
  401. end,
  402. Len = hybi_payload_length(iolist_size(Payload)),
  403. Transport:send(Socket, [<< 1:1, 0:3, Opcode:4, 0:1, Len/bits >>,
  404. Payload]).
  405. -spec websocket_close(#state{}, #http_req{}, any(), {atom(), atom()}) -> closed.
  406. websocket_close(State=#state{version=0}, Req=#http_req{socket=Socket,
  407. transport=Transport}, HandlerState, Reason) ->
  408. Transport:send(Socket, << 255, 0 >>),
  409. handler_terminate(State, Req, HandlerState, Reason);
  410. %% @todo Send a Payload? Using Reason is usually good but we're quite careless.
  411. websocket_close(State, Req=#http_req{socket=Socket,
  412. transport=Transport}, HandlerState, Reason) ->
  413. Transport:send(Socket, << 1:1, 0:3, 8:4, 0:8 >>),
  414. handler_terminate(State, Req, HandlerState, Reason).
  415. -spec handler_terminate(#state{}, #http_req{},
  416. any(), atom() | {atom(), atom()}) -> closed.
  417. handler_terminate(#state{handler=Handler, opts=Opts},
  418. Req, HandlerState, TerminateReason) ->
  419. try
  420. Handler:websocket_terminate(TerminateReason, Req, HandlerState)
  421. catch Class:Reason ->
  422. error_logger:error_msg(
  423. "** Handler ~p terminating in websocket_terminate/3~n"
  424. " for the reason ~p:~p~n** Initial reason was ~p~n"
  425. "** Options were ~p~n** Handler state was ~p~n"
  426. "** Request was ~p~n** Stacktrace: ~p~n~n",
  427. [Handler, Class, Reason, TerminateReason, Opts,
  428. HandlerState, Req, erlang:get_stacktrace()])
  429. end,
  430. closed.
  431. %% hixie-76 specific.
  432. -spec hixie76_challenge(binary(), binary(), binary()) -> binary().
  433. hixie76_challenge(Key1, Key2, Key3) ->
  434. IntKey1 = hixie76_key_to_integer(Key1),
  435. IntKey2 = hixie76_key_to_integer(Key2),
  436. erlang:md5(<< IntKey1:32, IntKey2:32, Key3/binary >>).
  437. -spec hixie76_key_to_integer(binary()) -> integer().
  438. hixie76_key_to_integer(Key) ->
  439. Number = list_to_integer([C || << C >> <= Key, C >= $0, C =< $9]),
  440. Spaces = length([C || << C >> <= Key, C =:= 32]),
  441. Number div Spaces.
  442. -spec hixie76_location(atom(), binary(), inet:port_number(),
  443. binary(), binary()) -> binary().
  444. hixie76_location(Protocol, Host, Port, Path, <<>>) ->
  445. << (hixie76_location_protocol(Protocol))/binary, "://", Host/binary,
  446. (hixie76_location_port(Protocol, Port))/binary, Path/binary>>;
  447. hixie76_location(Protocol, Host, Port, Path, QS) ->
  448. << (hixie76_location_protocol(Protocol))/binary, "://", Host/binary,
  449. (hixie76_location_port(Protocol, Port))/binary, Path/binary, "?", QS/binary >>.
  450. -spec hixie76_location_protocol(atom()) -> binary().
  451. hixie76_location_protocol(ssl) -> <<"wss">>;
  452. hixie76_location_protocol(_) -> <<"ws">>.
  453. %% @todo We should add a secure/0 function to transports
  454. %% instead of relying on their name.
  455. -spec hixie76_location_port(atom(), inet:port_number()) -> binary().
  456. hixie76_location_port(ssl, 443) ->
  457. <<>>;
  458. hixie76_location_port(tcp, 80) ->
  459. <<>>;
  460. hixie76_location_port(_, Port) ->
  461. <<":", (list_to_binary(integer_to_list(Port)))/binary>>.
  462. %% hybi specific.
  463. -spec hybi_challenge(binary()) -> binary().
  464. hybi_challenge(Key) ->
  465. Bin = << Key/binary, "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" >>,
  466. base64:encode(crypto:sha(Bin)).
  467. -spec hybi_payload_length(0..16#7fffffffffffffff)
  468. -> << _:7 >> | << _:23 >> | << _:71 >>.
  469. hybi_payload_length(N) ->
  470. case N of
  471. N when N =< 125 -> << N:7 >>;
  472. N when N =< 16#ffff -> << 126:7, N:16 >>;
  473. N when N =< 16#7fffffffffffffff -> << 127:7, N:64 >>
  474. end.
  475. %% Tests.
  476. -ifdef(TEST).
  477. hixie76_location_test() ->
  478. ?assertEqual(<<"ws://localhost/path">>,
  479. hixie76_location(tcp, <<"localhost">>, 80, <<"/path">>, <<>>)),
  480. ?assertEqual(<<"ws://localhost:443/path">>,
  481. hixie76_location(tcp, <<"localhost">>, 443, <<"/path">>, <<>>)),
  482. ?assertEqual(<<"ws://localhost:8080/path">>,
  483. hixie76_location(tcp, <<"localhost">>, 8080, <<"/path">>, <<>>)),
  484. ?assertEqual(<<"ws://localhost:8080/path?dummy=2785">>,
  485. hixie76_location(tcp, <<"localhost">>, 8080, <<"/path">>, <<"dummy=2785">>)),
  486. ?assertEqual(<<"wss://localhost/path">>,
  487. hixie76_location(ssl, <<"localhost">>, 443, <<"/path">>, <<>>)),
  488. ?assertEqual(<<"wss://localhost:8443/path">>,
  489. hixie76_location(ssl, <<"localhost">>, 8443, <<"/path">>, <<>>)),
  490. ?assertEqual(<<"wss://localhost:8443/path?dummy=2785">>,
  491. hixie76_location(ssl, <<"localhost">>, 8443, <<"/path">>, <<"dummy=2785">>)),
  492. ok.
  493. -endif.