PageRenderTime 24ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

/src/misultin_websocket_draft-hixie-76.erl

http://github.com/ostinelli/misultin
Erlang | 160 lines | 80 code | 13 blank | 67 comment | 4 complexity | b1aff0cb896f9c39ee0d160e706fb98d MD5 | raw file
  1. % ==========================================================================================================
  2. % MISULTIN - WebSocket
  3. %
  4. % >-|-|-(°>
  5. %
  6. % Copyright (C) 2011, Roberto Ostinelli <roberto@ostinelli.net>, Joe Armstrong.
  7. % All rights reserved.
  8. %
  9. % Code portions from Joe Armstrong have been originally taken under MIT license at the address:
  10. % <http://armstrongonsoftware.blogspot.com/2009/12/comet-is-dead-long-live-websockets.html>
  11. %
  12. % BSD License
  13. %
  14. % Redistribution and use in source and binary forms, with or without modification, are permitted provided
  15. % that the following conditions are met:
  16. %
  17. % * Redistributions of source code must retain the above copyright notice, this list of conditions and the
  18. % following disclaimer.
  19. % * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
  20. % the following disclaimer in the documentation and/or other materials provided with the distribution.
  21. % * Neither the name of the authors nor the names of its contributors may be used to endorse or promote
  22. % products derived from this software without specific prior written permission.
  23. %
  24. % THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
  25. % WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
  26. % PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
  27. % ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
  28. % TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  29. % HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  30. % NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  31. % POSSIBILITY OF SUCH DAMAGE.
  32. % ==========================================================================================================
  33. -module('misultin_websocket_draft-hixie-76').
  34. -behaviour(misultin_websocket).
  35. -vsn("0.9").
  36. % API
  37. -export([check_websocket/1, handshake/3, handle_data/3, send_format/2]).
  38. % includes
  39. -include("../include/misultin.hrl").
  40. % ============================ \/ API ======================================================================
  41. % ----------------------------------------------------------------------------------------------------------
  42. % Function: -> true | false
  43. % Description: Callback to check if the incoming request is a websocket request according to this protocol.
  44. % ----------------------------------------------------------------------------------------------------------
  45. -spec check_websocket(Headers::http_headers()) -> boolean().
  46. check_websocket(Headers) ->
  47. % set required headers
  48. RequiredHeaders = [
  49. {'Upgrade', "WebSocket"}, {'Connection', "Upgrade"}, {'Host', ignore}, {'Origin', ignore},
  50. {'Sec-WebSocket-Key1', ignore}, {'Sec-WebSocket-Key2', ignore}
  51. ],
  52. % check for headers existance
  53. case misultin_websocket:check_headers(Headers, RequiredHeaders) of
  54. true ->
  55. % return
  56. true;
  57. _RemainingHeaders ->
  58. ?LOG_DEBUG("not this protocol, remaining headers: ~p", [_RemainingHeaders]),
  59. false
  60. end.
  61. % ----------------------------------------------------------------------------------------------------------
  62. % Function: -> iolist() | binary()
  63. % Description: Callback to build handshake data.
  64. % ----------------------------------------------------------------------------------------------------------
  65. -spec handshake(Req::#req{}, Headers::http_headers(), {Path::string(), Origin::string(), Host::string()}) -> iolist().
  66. handshake(#req{socket = Sock, socket_mode = SocketMode, ws_force_ssl = WsForceSsl}, Headers, {Path, Origin, Host}) ->
  67. % build data
  68. Key1 = misultin_utility:header_get_value('Sec-WebSocket-Key1', Headers),
  69. Key2 = misultin_utility:header_get_value('Sec-WebSocket-Key2', Headers),
  70. % handshake needs body of the request, still need to read it [TODO: default recv timeout hard set, will be exported when WS protocol is final]
  71. misultin_socket:setopts(Sock, [{packet, raw}, {active, false}], SocketMode),
  72. Body = case misultin_socket:recv(Sock, 8, 30*1000, SocketMode) of
  73. {ok, Bin} -> Bin;
  74. {error, timeout} ->
  75. ?LOG_WARNING("timeout in reading websocket body", []),
  76. <<>>;
  77. _Other ->
  78. ?LOG_ERROR("tcp error treating data: ~p", [_Other]),
  79. <<>>
  80. end,
  81. ?LOG_DEBUG("got content in body of websocket request: ~p", [Body]),
  82. % prepare handhsake response
  83. WsMode = case SocketMode of
  84. ssl -> "wss";
  85. http when WsForceSsl =:= true -> "wss"; % behind stunnel or similar, client is using ssl
  86. http when WsForceSsl =:= false -> "ws"
  87. end,
  88. % build challenge
  89. Ikey1 = [D || D <- Key1, $0 =< D, D =< $9],
  90. Ikey2 = [D || D <- Key2, $0 =< D, D =< $9],
  91. Blank1 = length([D || D <- Key1, D =:= 32]),
  92. Blank2 = length([D || D <- Key2, D =:= 32]),
  93. Part1 = erlang:list_to_integer(Ikey1) div Blank1,
  94. Part2 = erlang:list_to_integer(Ikey2) div Blank2,
  95. Ckey = <<Part1:4/big-unsigned-integer-unit:8, Part2:4/big-unsigned-integer-unit:8, Body/binary>>,
  96. Challenge = erlang:md5(Ckey),
  97. % format
  98. ["HTTP/1.1 101 WebSocket Protocol Handshake\r\n",
  99. "Upgrade: WebSocket\r\n",
  100. "Connection: Upgrade\r\n",
  101. "Sec-WebSocket-Origin: ", Origin, "\r\n",
  102. "Sec-WebSocket-Location: ", WsMode, "://", lists:concat([Host, Path]), "\r\n\r\n",
  103. Challenge
  104. ].
  105. % ----------------------------------------------------------------------------------------------------------
  106. % Function: -> websocket_close | {websocket_close, DataToSendBeforeClose::binary() | iolist()} | NewState
  107. % Description: Callback to handle incomed data.
  108. % ----------------------------------------------------------------------------------------------------------
  109. -spec handle_data(Data::binary(), State::undefined | term(), {Socket::socket(), SocketMode::socketmode(), WsHandleLoopPid::pid()}) -> websocket_close | term().
  110. handle_data(Data, undefined, {Socket, SocketMode, WsHandleLoopPid}) ->
  111. % init status
  112. handle_data(Data, {buffer, none}, {Socket, SocketMode, WsHandleLoopPid});
  113. handle_data(Data, {buffer, B} = _State, {Socket, SocketMode, WsHandleLoopPid}) ->
  114. % read status
  115. i_handle_data(Data, B, {Socket, SocketMode, WsHandleLoopPid}).
  116. % ----------------------------------------------------------------------------------------------------------
  117. % Function: -> binary() | iolist()
  118. % Description: Callback to format data before it is sent into the socket.
  119. % ----------------------------------------------------------------------------------------------------------
  120. -spec send_format(Data::iolist(), State::term()) -> iolist().
  121. send_format(Data, _State) ->
  122. [0, Data, 255].
  123. % ============================ /\ API ======================================================================
  124. % ============================ \/ INTERNAL FUNCTIONS =======================================================
  125. % Buffering and data handling
  126. -spec i_handle_data(
  127. Data::binary(),
  128. Buffer::binary() | none,
  129. {Socket::socket(), SocketMode::socketmode(), WsHandleLoopPid::pid()}) -> websocket_close | term().
  130. i_handle_data(<<0, T/binary>>, none, {Socket, SocketMode, WsHandleLoopPid}) ->
  131. i_handle_data(T, <<>>, {Socket, SocketMode, WsHandleLoopPid});
  132. i_handle_data(<<>>, none, {_Socket, _SocketMode, _WsHandleLoopPid}) ->
  133. % return status
  134. {buffer, none};
  135. i_handle_data(<<255, 0>>, _L, {Socket, SocketMode, _WsHandleLoopPid}) ->
  136. ?LOG_DEBUG("websocket close message received from client, closing websocket with pid ~p", [self()]),
  137. misultin_socket:send(Socket, <<255, 0>>, SocketMode),
  138. % return command
  139. websocket_close;
  140. i_handle_data(<<255, T/binary>>, L, {Socket, SocketMode, WsHandleLoopPid}) ->
  141. misultin_websocket:send_to_browser(WsHandleLoopPid, binary_to_list(L)),
  142. i_handle_data(T, none, {Socket, SocketMode, WsHandleLoopPid});
  143. i_handle_data(<<H, T/binary>>, L, {Socket, SocketMode, WsHandleLoopPid}) ->
  144. i_handle_data(T, <<L/binary, H>>, {Socket, SocketMode, WsHandleLoopPid});
  145. i_handle_data(<<>>, L, {_Socket, _SocketMode, _WsHandleLoopPid}) ->
  146. {buffer, L}.
  147. % ============================ /\ INTERNAL FUNCTIONS =======================================================