Compare commits
20 Commits
0.1.0
...
138c8eaaeb
| Author | SHA1 | Date | |
|---|---|---|---|
| 138c8eaaeb | |||
| b3599633f9 | |||
| f3a107111f | |||
| 8b938fdd42 | |||
| 80945de92d | |||
| 2151fff0fa | |||
| 73fc38b7ad | |||
| a0418788c5 | |||
| cb600dc0da | |||
| 027c020a34 | |||
| 079c47962a | |||
| 7ed8b12c4e | |||
| 4509a328a8 | |||
| 04970142aa | |||
| b44292a790 | |||
| 1865f03085 | |||
| 5824aaaf36 | |||
| 35dbf06a55 | |||
| 62d0710fcf | |||
| 9107679dfc |
+1
-1
@@ -4,7 +4,7 @@
|
|||||||
qargs = undefined :: undefined | #{Key :: binary() := Value :: binary()},
|
qargs = undefined :: undefined | #{Key :: binary() := Value :: binary()},
|
||||||
fragment = undefined :: undefined | none | binary(),
|
fragment = undefined :: undefined | none | binary(),
|
||||||
version = undefined :: undefined | http10 | http11 | http20,
|
version = undefined :: undefined | http10 | http11 | http20,
|
||||||
headers = undefined :: undefined | [{Key :: binary(), Value :: binary()}],
|
headers = undefined :: undefined | #{Key :: binary() := Value :: binary()},
|
||||||
cookies = undefined :: undefined | #{Key :: binary() := Value :: binary()},
|
cookies = undefined :: undefined | #{Key :: binary() := Value :: binary()},
|
||||||
enctype = undefined :: undefined | none | urlencoded | json | multipart(),
|
enctype = undefined :: undefined | none | urlencoded | json | multipart(),
|
||||||
size = undefined :: undefined | none | non_neg_integer(),
|
size = undefined :: undefined | none | non_neg_integer(),
|
||||||
|
|||||||
@@ -0,0 +1,100 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<title>Chat with Websockets</title>
|
||||||
|
<link rel="stylesheet" href="./default.css">
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div class="content">
|
||||||
|
<h1 class="content-title">Chat with websockets</h1>
|
||||||
|
|
||||||
|
<div class="content-body">
|
||||||
|
<input autofocus label="Nick" id="nick"></input>
|
||||||
|
<textarea hidden disabled id="wfc-output"></textarea>
|
||||||
|
<input hidden id="wfc-input"></input>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
let nelt = document.getElementById('nick');
|
||||||
|
let ielt = document.getElementById('wfc-input');
|
||||||
|
let oelt = document.getElementById('wfc-output');
|
||||||
|
let ws = new WebSocket("/ws/chat");
|
||||||
|
let nick = '';
|
||||||
|
|
||||||
|
// when user hits any key while typing in nick
|
||||||
|
function on_nick(evt) {
|
||||||
|
if (evt.key === 'Enter') {
|
||||||
|
// don't do default thing
|
||||||
|
evt.preventDefault();
|
||||||
|
// grab contents
|
||||||
|
let contents = nelt.value;
|
||||||
|
let trimmed = contents.trim();
|
||||||
|
// if contents are nonempty
|
||||||
|
let nonempty_contents = trimmed.length > 0;
|
||||||
|
if (nonempty_contents) {
|
||||||
|
nick = trimmed;
|
||||||
|
let msg_obj = ['nick', nick];
|
||||||
|
let msg_str = JSON.stringify(msg_obj);
|
||||||
|
console.log('message to server:', contents.trim());
|
||||||
|
// query backend for result
|
||||||
|
ws.send(msg_str);
|
||||||
|
|
||||||
|
// delete element from dom
|
||||||
|
nelt.remove();
|
||||||
|
oelt.hidden = false;
|
||||||
|
ielt.hidden = false;
|
||||||
|
ielt.autofocus = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// when user hits any key while typing in ielt
|
||||||
|
function on_input_key(evt) {
|
||||||
|
if (evt.key === 'Enter') {
|
||||||
|
// don't do default thing
|
||||||
|
evt.preventDefault();
|
||||||
|
// grab contents
|
||||||
|
let contents = ielt.value;
|
||||||
|
let trimmed = contents.trim();
|
||||||
|
// if contents are nonempty
|
||||||
|
let nonempty_contents = trimmed.length > 0;
|
||||||
|
if (nonempty_contents) {
|
||||||
|
let msg_obj = ['chat', trimmed];
|
||||||
|
let msg_str = JSON.stringify(msg_obj);
|
||||||
|
console.log('message to server:', contents.trim());
|
||||||
|
// query backend for result
|
||||||
|
ws.send(msg_str);
|
||||||
|
|
||||||
|
// clear input
|
||||||
|
ielt.value = '';
|
||||||
|
|
||||||
|
// add to output
|
||||||
|
oelt.value += '> ';
|
||||||
|
oelt.value += trimmed;
|
||||||
|
oelt.value += '\n';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function main() {
|
||||||
|
nelt.addEventListener('keydown', on_nick);
|
||||||
|
ielt.addEventListener('keydown', on_input_key);
|
||||||
|
ws.onmessage =
|
||||||
|
function (msg_evt) {
|
||||||
|
console.log('message from server:', msg_evt);
|
||||||
|
let msg_str = msg_evt.data;
|
||||||
|
let msg_obj = JSON.parse(msg_str);
|
||||||
|
|
||||||
|
oelt.value += msg_obj.nick;
|
||||||
|
oelt.value += '> ';
|
||||||
|
oelt.value += msg_obj.msg;
|
||||||
|
oelt.value += '\n';
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
main();
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -9,11 +9,14 @@
|
|||||||
<div class="content">
|
<div class="content">
|
||||||
<h1 class="content-title">WFC Demo</h1>
|
<h1 class="content-title">WFC Demo</h1>
|
||||||
|
|
||||||
|
<ul>
|
||||||
|
<li><a href="/chat.html">Websocket Chatroom</a></li>
|
||||||
|
<li><a href="/ws-test-echo.html">Websocket Echo Test</a></li>
|
||||||
|
</ul>
|
||||||
|
|
||||||
<div class="content-body">
|
<div class="content-body">
|
||||||
<textarea id="wfc-output"
|
<textarea disabled id="wfc-output"></textarea>
|
||||||
disabled
|
<input autofocus id="wfc-input"></input>
|
||||||
></textarea>
|
|
||||||
<input autofocus id="wfc-input"></textarea>
|
|
||||||
|
|
||||||
<h2>Settings</h2>
|
<h2>Settings</h2>
|
||||||
<input type="checkbox" checked id="auto-resize-output">Auto-resize output</input> <br>
|
<input type="checkbox" checked id="auto-resize-output">Auto-resize output</input> <br>
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<title>Websockets echo test</title>
|
||||||
|
<link rel="stylesheet" href="./default.css">
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div class="content">
|
||||||
|
<h1 class="content-title">Websockets echo test</h1>
|
||||||
|
|
||||||
|
<div class="content-body">
|
||||||
|
<textarea id="wfc-output"
|
||||||
|
disabled></textarea>
|
||||||
|
<input autofocus id="wfc-input"></input>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
let ielt = document.getElementById('wfc-input');
|
||||||
|
let oelt = document.getElementById('wfc-output');
|
||||||
|
let ws = new WebSocket("/ws/echo");
|
||||||
|
|
||||||
|
// when user hits any key while typing in ielt
|
||||||
|
function on_input_key(evt) {
|
||||||
|
if (evt.key === 'Enter') {
|
||||||
|
// don't do default thing
|
||||||
|
evt.preventDefault();
|
||||||
|
// grab contents
|
||||||
|
let contents = ielt.value;
|
||||||
|
let trimmed = contents.trim();
|
||||||
|
// if contents are nonempty
|
||||||
|
let nonempty_contents = trimmed.length > 0;
|
||||||
|
if (nonempty_contents) {
|
||||||
|
console.log('message to server:', contents.trim());
|
||||||
|
// query backend for result
|
||||||
|
ws.send(contents.trim());
|
||||||
|
|
||||||
|
// clear input
|
||||||
|
ielt.value = '';
|
||||||
|
|
||||||
|
// add to output
|
||||||
|
oelt.value += '> ';
|
||||||
|
oelt.value += trimmed;
|
||||||
|
oelt.value += '\n';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function main() {
|
||||||
|
ielt.addEventListener('keydown', on_input_key);
|
||||||
|
ws.onmessage =
|
||||||
|
function (msg_evt) {
|
||||||
|
console.log('message from server:', msg_evt);
|
||||||
|
let msg_str = msg_evt.data;
|
||||||
|
oelt.value += '< ';
|
||||||
|
oelt.value += msg_str;
|
||||||
|
oelt.value += '\n';
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
main();
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
+262
@@ -0,0 +1,262 @@
|
|||||||
|
% @doc
|
||||||
|
% controller for chat
|
||||||
|
-module(fd_chat).
|
||||||
|
-vsn("0.1.0").
|
||||||
|
-behavior(gen_server).
|
||||||
|
-author("Peter Harpending <peterharpending@qpq.swiss>").
|
||||||
|
-copyright("Peter Harpending <peterharpending@qpq.swiss>").
|
||||||
|
-license("BSD-2-Clause-FreeBSD").
|
||||||
|
|
||||||
|
-export([
|
||||||
|
join/1,
|
||||||
|
relay/1,
|
||||||
|
nick_available/1
|
||||||
|
]).
|
||||||
|
-export([start_link/0]).
|
||||||
|
-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
|
||||||
|
code_change/3, terminate/2]).
|
||||||
|
|
||||||
|
-include("$zx_include/zx_logger.hrl").
|
||||||
|
|
||||||
|
|
||||||
|
-record(o, {pid :: pid(),
|
||||||
|
nick :: string()}).
|
||||||
|
-type orator() :: #o{}.
|
||||||
|
|
||||||
|
-record(s, {orators = [] :: [orator()]}).
|
||||||
|
|
||||||
|
-type state() :: #s{}.
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
%%% Service Interface
|
||||||
|
|
||||||
|
-spec join(Nick) -> Result
|
||||||
|
when Nick :: string(),
|
||||||
|
Result :: ok
|
||||||
|
| {error, Reason :: any()}.
|
||||||
|
|
||||||
|
join(Nick) ->
|
||||||
|
gen_server:call(?MODULE, {join, Nick}).
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
-spec nick_available(Nick) -> Result
|
||||||
|
when Nick :: string(),
|
||||||
|
Result :: boolean().
|
||||||
|
|
||||||
|
nick_available(Nick) ->
|
||||||
|
gen_server:call(?MODULE, {nick_available, Nick}).
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
-spec relay(Message) -> ok
|
||||||
|
when Message :: string().
|
||||||
|
|
||||||
|
relay(Message) ->
|
||||||
|
gen_server:cast(?MODULE, {relay, self(), Message}).
|
||||||
|
|
||||||
|
|
||||||
|
%%% Startup Functions
|
||||||
|
|
||||||
|
|
||||||
|
-spec start_link() -> Result
|
||||||
|
when Result :: {ok, pid()}
|
||||||
|
| {error, Reason :: term()}.
|
||||||
|
%% @private
|
||||||
|
%% This should only ever be called by fd_chat_orators (the service-level supervisor).
|
||||||
|
|
||||||
|
start_link() ->
|
||||||
|
gen_server:start_link({local, ?MODULE}, ?MODULE, none, []).
|
||||||
|
|
||||||
|
|
||||||
|
-spec init(none) -> {ok, state()}.
|
||||||
|
%% @private
|
||||||
|
%% Called by the supervisor process to give the process a chance to perform any
|
||||||
|
%% preparatory work necessary for proper function.
|
||||||
|
|
||||||
|
init(none) ->
|
||||||
|
ok = tell("~p Starting.", [?MODULE]),
|
||||||
|
State = #s{},
|
||||||
|
{ok, State}.
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
%%% gen_server Message Handling Callbacks
|
||||||
|
|
||||||
|
|
||||||
|
-spec handle_call(Message, From, State) -> Result
|
||||||
|
when Message :: term(),
|
||||||
|
From :: {pid(), reference()},
|
||||||
|
State :: state(),
|
||||||
|
Result :: {reply, Response, NewState}
|
||||||
|
| {noreply, State},
|
||||||
|
Response :: term(),
|
||||||
|
NewState :: state().
|
||||||
|
%% @private
|
||||||
|
%% The gen_server:handle_call/3 callback.
|
||||||
|
%% See: http://erlang.org/doc/man/gen_server.html#Module:handle_call-3
|
||||||
|
|
||||||
|
handle_call({join, Nick}, {Pid, _}, State) ->
|
||||||
|
{Reply, NewState} = do_join(Pid, Nick, State),
|
||||||
|
{reply, Reply, NewState};
|
||||||
|
handle_call({nick_available, Nick}, _, State = #s{orators = Orators}) ->
|
||||||
|
Reply = is_nick_available(Nick, Orators),
|
||||||
|
{reply, Reply, State};
|
||||||
|
handle_call(Unexpected, From, State) ->
|
||||||
|
ok = tell("~p Unexpected call from ~tp: ~tp~n", [?MODULE, From, Unexpected]),
|
||||||
|
{noreply, State}.
|
||||||
|
|
||||||
|
|
||||||
|
-spec handle_cast(Message, State) -> {noreply, NewState}
|
||||||
|
when Message :: term(),
|
||||||
|
State :: state(),
|
||||||
|
NewState :: state().
|
||||||
|
%% @private
|
||||||
|
%% The gen_server:handle_cast/2 callback.
|
||||||
|
%% See: http://erlang.org/doc/man/gen_server.html#Module:handle_cast-2
|
||||||
|
|
||||||
|
handle_cast({relay, From, Message}, State = #s{orators = Orators}) ->
|
||||||
|
do_relay(From, Message, Orators),
|
||||||
|
{noreply, State};
|
||||||
|
handle_cast(Unexpected, State) ->
|
||||||
|
ok = tell("~p Unexpected cast: ~tp~n", [?MODULE, Unexpected]),
|
||||||
|
{noreply, State}.
|
||||||
|
|
||||||
|
|
||||||
|
-spec handle_info(Message, State) -> {noreply, NewState}
|
||||||
|
when Message :: term(),
|
||||||
|
State :: state(),
|
||||||
|
NewState :: state().
|
||||||
|
%% @private
|
||||||
|
%% The gen_server:handle_info/2 callback.
|
||||||
|
%% See: http://erlang.org/doc/man/gen_server.html#Module:handle_info-2
|
||||||
|
|
||||||
|
handle_info(Msg = {'DOWN', _Mon, process, _Pid, _Reason}, State) ->
|
||||||
|
NewState = handle_down(Msg, State),
|
||||||
|
{noreply, NewState};
|
||||||
|
handle_info(Unexpected, State) ->
|
||||||
|
ok = tell("~p Unexpected info: ~tp~n", [?MODULE, Unexpected]),
|
||||||
|
{noreply, State}.
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
%%% OTP Service Functions
|
||||||
|
|
||||||
|
-spec code_change(OldVersion, State, Extra) -> Result
|
||||||
|
when OldVersion :: {down, Version} | Version,
|
||||||
|
Version :: term(),
|
||||||
|
State :: state(),
|
||||||
|
Extra :: term(),
|
||||||
|
Result :: {ok, NewState}
|
||||||
|
| {error, Reason :: term()},
|
||||||
|
NewState :: state().
|
||||||
|
%% @private
|
||||||
|
%% The gen_server:code_change/3 callback.
|
||||||
|
%% See: http://erlang.org/doc/man/gen_server.html#Module:code_change-3
|
||||||
|
|
||||||
|
code_change(_, State, _) ->
|
||||||
|
{ok, State}.
|
||||||
|
|
||||||
|
|
||||||
|
-spec terminate(Reason, State) -> no_return()
|
||||||
|
when Reason :: normal
|
||||||
|
| shutdown
|
||||||
|
| {shutdown, term()}
|
||||||
|
| term(),
|
||||||
|
State :: state().
|
||||||
|
%% @private
|
||||||
|
%% The gen_server:terminate/2 callback.
|
||||||
|
%% See: http://erlang.org/doc/man/gen_server.html#Module:terminate-2
|
||||||
|
|
||||||
|
terminate(_, _) ->
|
||||||
|
ok.
|
||||||
|
|
||||||
|
|
||||||
|
%%% internals
|
||||||
|
|
||||||
|
-spec do_join(Pid, Nick, State) -> {Reply, NewState}
|
||||||
|
when Pid :: pid(),
|
||||||
|
Nick :: string(),
|
||||||
|
Reply :: ok | {error, Reason :: any()},
|
||||||
|
NewState :: State.
|
||||||
|
|
||||||
|
do_join(Pid, Nick, State = #s{orators = Orators}) ->
|
||||||
|
case ensure_can_join(Pid, Nick, Orators) of
|
||||||
|
ok -> do_join2(Pid, Nick, State);
|
||||||
|
Error -> {Error, State}
|
||||||
|
end.
|
||||||
|
|
||||||
|
|
||||||
|
do_join2(Pid, Nick, State = #s{orators = Orators}) ->
|
||||||
|
_Monitor = erlang:monitor(process, Pid),
|
||||||
|
NewOrator = #o{pid = Pid, nick = Nick},
|
||||||
|
NewOrators = [NewOrator | Orators],
|
||||||
|
NewState = State#s{orators = NewOrators},
|
||||||
|
{ok, NewState}.
|
||||||
|
|
||||||
|
|
||||||
|
-spec ensure_can_join(Pid, Nick, Orators) -> Result
|
||||||
|
when Pid :: pid(),
|
||||||
|
Nick :: string(),
|
||||||
|
Orators :: [orator()],
|
||||||
|
Result :: ok
|
||||||
|
| {error, Reason},
|
||||||
|
Reason :: any().
|
||||||
|
% @private
|
||||||
|
% ensures both Pid and Nick are unique
|
||||||
|
|
||||||
|
ensure_can_join(Pid, _ , [#o{pid = Pid} | _ ]) -> {error, already_joined};
|
||||||
|
ensure_can_join(_ , Nick, [#o{nick = Nick} | _ ]) -> {error, {nick_taken, Nick}};
|
||||||
|
ensure_can_join(Pid, Nick, [_ | Rest]) -> ensure_can_join(Pid, Nick, Rest);
|
||||||
|
ensure_can_join(_ , _ , [] ) -> ok.
|
||||||
|
|
||||||
|
|
||||||
|
-spec is_nick_available(Nick, Orators) -> boolean()
|
||||||
|
when Nick :: string(),
|
||||||
|
Orators :: [orator()].
|
||||||
|
|
||||||
|
is_nick_available(Nick, [#o{nick = Nick} | _ ]) -> false;
|
||||||
|
is_nick_available(Nick, [_ | Rest]) -> is_nick_available(Nick, Rest);
|
||||||
|
is_nick_available(_ , [] ) -> true.
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
-spec handle_down(Msg, State) -> NewState
|
||||||
|
when Msg :: {'DOWN', Mon, process, Pid, Reason},
|
||||||
|
Mon :: erlang:monitor(),
|
||||||
|
Pid :: pid(),
|
||||||
|
Reason :: any(),
|
||||||
|
State :: state(),
|
||||||
|
NewState :: State.
|
||||||
|
|
||||||
|
handle_down(Msg = {'DOWN', _, process, Pid, _}, State = #s{orators = Orators}) ->
|
||||||
|
NewOrators = hdn(Msg, Pid, Orators, []),
|
||||||
|
NewState = State#s{orators = NewOrators},
|
||||||
|
NewState.
|
||||||
|
|
||||||
|
% encountered item, removing
|
||||||
|
hdn(_, Pid, [#o{pid = Pid} | Rest], Acc) -> Rest ++ Acc;
|
||||||
|
hdn(Msg, Pid, [Skip | Rest], Acc) -> hdn(Msg, Pid, Rest, [Skip | Acc]);
|
||||||
|
hdn(Msg, _, [] , Acc) ->
|
||||||
|
log("~tp: Unexpected message: ~tp", [?MODULE, Msg]),
|
||||||
|
Acc.
|
||||||
|
|
||||||
|
|
||||||
|
do_relay(Pid, Message, Orators) ->
|
||||||
|
case lists:keyfind(Pid, #o.pid, Orators) of
|
||||||
|
#o{nick = Nick} ->
|
||||||
|
do_relay2(Nick, Message, Orators);
|
||||||
|
false ->
|
||||||
|
tell("~tp: Message received from outsider ~tp: ~tp", [?MODULE, Pid, Message]),
|
||||||
|
error
|
||||||
|
end.
|
||||||
|
|
||||||
|
% skip
|
||||||
|
do_relay2(Nick, Msg, [#o{nick = Nick} | Rest]) ->
|
||||||
|
do_relay2(Nick, Msg, Rest);
|
||||||
|
do_relay2(Nick, Msg, [#o{pid = Pid} | Rest]) ->
|
||||||
|
Pid ! {chat, {relay, Nick, Msg}},
|
||||||
|
do_relay2(Nick, Msg, Rest);
|
||||||
|
do_relay2(_, _, []) ->
|
||||||
|
ok.
|
||||||
+59
-24
@@ -222,11 +222,11 @@ handle_request(Sock, R = #request{method = M, path = P}) when M =/= undefined, P
|
|||||||
route(Sock, M, P, R).
|
route(Sock, M, P, R).
|
||||||
|
|
||||||
|
|
||||||
route(Sock, get, Route, _Request) ->
|
route(Sock, get, Route, Request) ->
|
||||||
case Route of
|
case Route of
|
||||||
<<"/">> -> home(Sock);
|
<<"/ws/echo">> -> ws_echo(Sock, Request);
|
||||||
<<"/default.css">> -> default_css(Sock);
|
<<"/">> -> route_static(Sock, <<"/index.html">>);
|
||||||
_ -> http_err(Sock, 404)
|
_ -> route_static(Sock, Route)
|
||||||
end;
|
end;
|
||||||
route(Sock, post, Route, Request) ->
|
route(Sock, post, Route, Request) ->
|
||||||
case Route of
|
case Route of
|
||||||
@@ -237,30 +237,65 @@ route(Sock, _, _, _) ->
|
|||||||
http_err(Sock, 404).
|
http_err(Sock, 404).
|
||||||
|
|
||||||
|
|
||||||
home(Sock) ->
|
route_static(Sock, Route) ->
|
||||||
%% fixme: cache
|
respond_static(Sock, fd_sfc:query(Route)).
|
||||||
Path_IH = filename:join([zx:get_home(), "priv", "index.html"]),
|
|
||||||
case file:read_file(Path_IH) of
|
respond_static(Sock, {found, Entry}) ->
|
||||||
{ok, Body} ->
|
% -record(e, {fs_path :: file:filename(),
|
||||||
Resp = #response{headers = [{"content-type", "text/html"}],
|
% last_modified :: file:date_time(),
|
||||||
body = Body},
|
% mime_type :: string(),
|
||||||
respond(Sock, Resp);
|
% encoding :: encoding(),
|
||||||
Error ->
|
% contents :: binary()}).
|
||||||
tell("error: ~p~n", [self(), Error]),
|
Headers0 =
|
||||||
|
case fd_sfc_entry:encoding(Entry) of
|
||||||
|
gzip -> [{"content-encoding", "gzip"}];
|
||||||
|
none -> []
|
||||||
|
end,
|
||||||
|
Headers1 = [{"content-type", fd_sfc_entry:mime_type(Entry)} | Headers0],
|
||||||
|
Response = #response{headers = Headers1,
|
||||||
|
body = fd_sfc_entry:contents(Entry)},
|
||||||
|
respond(Sock, Response);
|
||||||
|
respond_static(Sock, not_found) ->
|
||||||
|
http_err(Sock, 404).
|
||||||
|
|
||||||
|
|
||||||
|
ws_echo(Sock, Request) ->
|
||||||
|
try
|
||||||
|
ws_echo2(Sock, Request)
|
||||||
|
catch
|
||||||
|
X:Y:Z ->
|
||||||
|
tell(error, "CRASH ws_echo: ~tp:~tp:~tp", [X, Y, Z]),
|
||||||
http_err(Sock, 500)
|
http_err(Sock, 500)
|
||||||
end.
|
end.
|
||||||
|
|
||||||
default_css(Sock) ->
|
ws_echo2(Sock, Request) ->
|
||||||
%% fixme: cache
|
tell("~p: ws_echo request: ~tp", [?LINE, Request]),
|
||||||
Path_IH = filename:join([zx:get_home(), "priv", "default.css"]),
|
case fd_ws:handshake(Request) of
|
||||||
case file:read_file(Path_IH) of
|
{ok, Response} ->
|
||||||
{ok, Body} ->
|
tell("~p: ws_echo response: ~tp", [?LINE, Response]),
|
||||||
Resp = #response{headers = [{"content-type", "text/css"}],
|
respond(Sock, Response),
|
||||||
body = Body},
|
tell("~p: ws_echo: entering loop", [?LINE]),
|
||||||
respond(Sock, Resp);
|
ws_echo_loop(Sock);
|
||||||
Error ->
|
Error ->
|
||||||
io:format("~p error: ~p~n", [self(), Error]),
|
tell("ws_echo: error: ~tp", [Error]),
|
||||||
http_err(Sock, 500)
|
http_err(Sock, 400)
|
||||||
|
end.
|
||||||
|
|
||||||
|
ws_echo_loop(Sock) ->
|
||||||
|
ws_echo_loop(Sock, [], <<>>).
|
||||||
|
|
||||||
|
ws_echo_loop(Sock, Frames, Received) ->
|
||||||
|
tell("~p: ws_echo_loop: entering loop", [?LINE]),
|
||||||
|
case fd_ws:recv(Sock, Received, 5*fd_ws:min(), Frames) of
|
||||||
|
Result = {ok, Message, NewFrames, NewReceived} ->
|
||||||
|
tell("~p: ws_echo_loop ok: ~tp", [?LINE, Result]),
|
||||||
|
% send the same message back
|
||||||
|
ok = fd_ws:send(Sock, Message),
|
||||||
|
ws_echo_loop(Sock, NewFrames, NewReceived);
|
||||||
|
Error ->
|
||||||
|
tell("ws_echo_loop: error: ~tp", [Error]),
|
||||||
|
fd_ws:send(Sock, {close, <<>>}),
|
||||||
|
error(Error)
|
||||||
end.
|
end.
|
||||||
|
|
||||||
wfcin(Sock, #request{enctype = json,
|
wfcin(Sock, #request{enctype = json,
|
||||||
|
|||||||
@@ -0,0 +1,96 @@
|
|||||||
|
% @doc static file cache
|
||||||
|
-module(fd_sfc).
|
||||||
|
|
||||||
|
-behavior(gen_server).
|
||||||
|
|
||||||
|
-export([
|
||||||
|
%% caller context
|
||||||
|
base_path/0,
|
||||||
|
renew/0, query/1,
|
||||||
|
start_link/0,
|
||||||
|
|
||||||
|
%% process context
|
||||||
|
init/1, handle_call/3, handle_cast/2, handle_info/2,
|
||||||
|
code_change/3, terminate/2
|
||||||
|
]).
|
||||||
|
|
||||||
|
-include("$zx_include/zx_logger.hrl").
|
||||||
|
|
||||||
|
|
||||||
|
-record(s, {base_path = base_path() :: file:filename(),
|
||||||
|
cache = fd_sfc_cache:new(base_path()) :: fd_sfc_cache:cache(),
|
||||||
|
auto_renew = 5_000 :: pos_integer()}).
|
||||||
|
%-type state() :: #s{}.
|
||||||
|
|
||||||
|
|
||||||
|
%%-----------------------------------------------------------------------------
|
||||||
|
%% caller context
|
||||||
|
%%-----------------------------------------------------------------------------
|
||||||
|
|
||||||
|
base_path() ->
|
||||||
|
filename:join([zx:get_home(), "priv", "static"]).
|
||||||
|
|
||||||
|
renew() ->
|
||||||
|
gen_server:cast(?MODULE, renew).
|
||||||
|
|
||||||
|
query(Path) ->
|
||||||
|
gen_server:call(?MODULE, {query, Path}).
|
||||||
|
|
||||||
|
start_link() ->
|
||||||
|
gen_server:start_link({local, ?MODULE}, ?MODULE, none, []).
|
||||||
|
|
||||||
|
|
||||||
|
%%-----------------------------------------------------------------------------
|
||||||
|
%% process context below this line
|
||||||
|
%%-----------------------------------------------------------------------------
|
||||||
|
|
||||||
|
%% gen_server callbacks
|
||||||
|
|
||||||
|
init(none) ->
|
||||||
|
log(info, "starting fd_cache"),
|
||||||
|
InitState = #s{},
|
||||||
|
erlang:send_after(InitState#s.auto_renew, self(), auto_renew),
|
||||||
|
{ok, InitState}.
|
||||||
|
|
||||||
|
|
||||||
|
handle_call({query, Path}, _, State = #s{cache = Cache}) ->
|
||||||
|
Reply = fd_sfc_cache:query(Path, Cache),
|
||||||
|
{reply, Reply, State};
|
||||||
|
handle_call(Unexpected, From, State) ->
|
||||||
|
tell("~tp: unexpected call from ~tp: ~tp", [?MODULE, Unexpected, From]),
|
||||||
|
{noreply, State}.
|
||||||
|
|
||||||
|
|
||||||
|
handle_cast(renew, State) ->
|
||||||
|
NewState = i_renew(State),
|
||||||
|
{noreply, NewState};
|
||||||
|
handle_cast(Unexpected, State) ->
|
||||||
|
tell("~tp: unexpected cast: ~tp", [?MODULE, Unexpected]),
|
||||||
|
{noreply, State}.
|
||||||
|
|
||||||
|
|
||||||
|
handle_info(auto_renew, State = #s{auto_renew = MS}) ->
|
||||||
|
log(info, "~tp: auto_renew", [?MODULE]),
|
||||||
|
erlang:send_after(MS, self(), auto_renew),
|
||||||
|
NewState = i_renew(State),
|
||||||
|
{noreply, NewState};
|
||||||
|
handle_info(Unexpected, State) ->
|
||||||
|
tell("~tp: unexpected info: ~tp", [?MODULE, Unexpected]),
|
||||||
|
{noreply, State}.
|
||||||
|
|
||||||
|
|
||||||
|
code_change(_, State, _) ->
|
||||||
|
{ok, State}.
|
||||||
|
|
||||||
|
terminate(_, _) ->
|
||||||
|
ok.
|
||||||
|
|
||||||
|
|
||||||
|
%%-----------------------------------------------------------------------------
|
||||||
|
%% internals
|
||||||
|
%%-----------------------------------------------------------------------------
|
||||||
|
|
||||||
|
i_renew(State = #s{base_path = BasePath}) ->
|
||||||
|
NewCache = fd_sfc_cache:new(BasePath),
|
||||||
|
NewState = State#s{cache = NewCache},
|
||||||
|
NewState.
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
% @doc
|
||||||
|
% cache data management
|
||||||
|
-module(fd_sfc_cache).
|
||||||
|
|
||||||
|
-export_type([
|
||||||
|
cache/0
|
||||||
|
]).
|
||||||
|
|
||||||
|
-export([
|
||||||
|
query/2,
|
||||||
|
new/0, new/1
|
||||||
|
]).
|
||||||
|
|
||||||
|
-include("$zx_include/zx_logger.hrl").
|
||||||
|
|
||||||
|
-type cache() :: #{HttpPath :: binary() := Entry :: fd_sfc_entry:entry()}.
|
||||||
|
|
||||||
|
|
||||||
|
-spec query(HttpPath, Cache) -> Result
|
||||||
|
when HttpPath :: binary(),
|
||||||
|
Cache :: cache(),
|
||||||
|
Result :: {found, Entry}
|
||||||
|
| not_found,
|
||||||
|
Entry :: fd_sfc_entry:entry().
|
||||||
|
|
||||||
|
query(HttpPath, Cache) ->
|
||||||
|
case maps:find(HttpPath, Cache) of
|
||||||
|
{ok, Entry} -> {found, Entry};
|
||||||
|
error -> not_found
|
||||||
|
end.
|
||||||
|
|
||||||
|
|
||||||
|
-spec new() -> cache().
|
||||||
|
new() -> #{}.
|
||||||
|
|
||||||
|
|
||||||
|
-spec new(BasePath) -> cache()
|
||||||
|
when BasePath :: file:filename().
|
||||||
|
% @doc
|
||||||
|
% if you give a file path it just takes the parent dir
|
||||||
|
%
|
||||||
|
% recursively crawls through file tree and picks
|
||||||
|
%
|
||||||
|
% IO errors will be logged but will result in cache misses
|
||||||
|
|
||||||
|
new(BasePath) ->
|
||||||
|
case filelib:is_file(BasePath) of
|
||||||
|
true -> new2(BasePath);
|
||||||
|
false ->
|
||||||
|
tell("~p:new(~p): no such file or directory, returning empty cache", [?MODULE, BasePath]),
|
||||||
|
#{}
|
||||||
|
end.
|
||||||
|
|
||||||
|
new2(BasePath) ->
|
||||||
|
BaseDir =
|
||||||
|
case filelib:is_dir(BasePath) of
|
||||||
|
true -> filename:absname(BasePath);
|
||||||
|
false -> filename:absname(filename:dirname(BasePath))
|
||||||
|
end,
|
||||||
|
%% hacky, fuck you
|
||||||
|
RemovePrefix =
|
||||||
|
fun (Prefix, Size, From) ->
|
||||||
|
<<Prefix:Size/bytes, Rest/bytes>> = From,
|
||||||
|
Rest
|
||||||
|
end,
|
||||||
|
BBaseDir = unicode:characters_to_binary(BaseDir),
|
||||||
|
BBS = byte_size(BBaseDir),
|
||||||
|
HandlePath =
|
||||||
|
fun(AbsPath, AccCache) ->
|
||||||
|
BAbsPath = unicode:characters_to_binary(AbsPath),
|
||||||
|
HttpPath = RemovePrefix(BBaseDir, BBS, BAbsPath),
|
||||||
|
NewCache =
|
||||||
|
case fd_sfc_entry:new(AbsPath) of
|
||||||
|
{found, Entry} -> maps:put(HttpPath, Entry, AccCache);
|
||||||
|
not_found -> AccCache
|
||||||
|
end,
|
||||||
|
NewCache
|
||||||
|
end,
|
||||||
|
filelib:fold_files(_dir = BaseDir,
|
||||||
|
_match = ".+",
|
||||||
|
_recursive = true,
|
||||||
|
_fun = HandlePath,
|
||||||
|
_init_acc = #{}).
|
||||||
@@ -0,0 +1,99 @@
|
|||||||
|
% @doc non-servery functions for static file caching
|
||||||
|
%
|
||||||
|
% this spams the filesystem, so it's not "pure" code
|
||||||
|
-module(fd_sfc_entry).
|
||||||
|
|
||||||
|
-export_type([
|
||||||
|
encoding/0,
|
||||||
|
entry/0
|
||||||
|
]).
|
||||||
|
|
||||||
|
-export([
|
||||||
|
%% constructor
|
||||||
|
new/1,
|
||||||
|
%% accessors
|
||||||
|
fs_path/1, last_modified/1, mime_type/1, encoding/1, contents/1
|
||||||
|
]).
|
||||||
|
|
||||||
|
-include("$zx_include/zx_logger.hrl").
|
||||||
|
|
||||||
|
%% types
|
||||||
|
|
||||||
|
% id = not compressed
|
||||||
|
-type encoding() :: none | gzip.
|
||||||
|
|
||||||
|
-record(e, {fs_path :: file:filename(),
|
||||||
|
last_modified :: file:date_time(),
|
||||||
|
mime_type :: string(),
|
||||||
|
encoding :: encoding(),
|
||||||
|
contents :: binary()}).
|
||||||
|
|
||||||
|
-opaque entry() :: #e{}.
|
||||||
|
|
||||||
|
%% accessors
|
||||||
|
|
||||||
|
fs_path(#e{fs_path = X}) -> X.
|
||||||
|
last_modified(#e{last_modified = X}) -> X.
|
||||||
|
mime_type(#e{mime_type = X}) -> X.
|
||||||
|
encoding(#e{encoding = X}) -> X.
|
||||||
|
contents(#e{contents = X}) -> X.
|
||||||
|
|
||||||
|
%% API
|
||||||
|
|
||||||
|
-spec new(Path) -> Result
|
||||||
|
when Path :: file:filename(),
|
||||||
|
Result :: {found, entry()}
|
||||||
|
| not_found.
|
||||||
|
% @doc
|
||||||
|
% absolute file path stored in resulting record
|
||||||
|
%
|
||||||
|
% returns not_found if ANY I/O error occurs during the process. will be logged
|
||||||
|
|
||||||
|
new(Path) ->
|
||||||
|
log(info, "~tp:new(~tp)", [?MODULE, Path]),
|
||||||
|
case file:read_file(Path) of
|
||||||
|
{ok, Binary} ->
|
||||||
|
{found, new2(Path, Binary)};
|
||||||
|
Error ->
|
||||||
|
tell("~tp:new(~tp): file read error: ~tp", [?MODULE, Path, Error]),
|
||||||
|
not_found
|
||||||
|
end.
|
||||||
|
|
||||||
|
%% can assume file exists
|
||||||
|
new2(FsPath, FileBytes) ->
|
||||||
|
LastModified = filelib:last_modified(FsPath),
|
||||||
|
{Encoding, MimeType} = mimetype_compress(FsPath),
|
||||||
|
Contents =
|
||||||
|
case Encoding of
|
||||||
|
none -> FileBytes;
|
||||||
|
gzip -> zlib:gzip(FileBytes)
|
||||||
|
end,
|
||||||
|
#e{fs_path = FsPath,
|
||||||
|
last_modified = LastModified,
|
||||||
|
mime_type = MimeType,
|
||||||
|
encoding = Encoding,
|
||||||
|
contents = Contents}.
|
||||||
|
|
||||||
|
mimetype_compress(FsPath) ->
|
||||||
|
case string:casefold(filename:extension(FsPath)) of
|
||||||
|
%% only including the ones i anticipate encountering
|
||||||
|
%% plaintext formats
|
||||||
|
".css" -> {gzip, "text/css"};
|
||||||
|
".htm" -> {gzip, "text/html"};
|
||||||
|
".html" -> {gzip, "text/html"};
|
||||||
|
".js" -> {gzip, "text/javascript"};
|
||||||
|
".json" -> {gzip, "application/json"};
|
||||||
|
".map" -> {gzip, "application/json"};
|
||||||
|
".md" -> {gzip, "text/markdown"};
|
||||||
|
".ts" -> {gzip, "text/x-typescript"};
|
||||||
|
".txt" -> {gzip, "text/plain"};
|
||||||
|
%% binary formats
|
||||||
|
".gif" -> {none, "image/gif"};
|
||||||
|
".jpg" -> {none, "image/jpeg"};
|
||||||
|
".jpeg" -> {none, "image/jpeg"};
|
||||||
|
".mp4" -> {none, "video/mp4"};
|
||||||
|
".png" -> {none, "image/png"};
|
||||||
|
".webm" -> {none, "video/webm"};
|
||||||
|
".webp" -> {none, "image/webp"};
|
||||||
|
_ -> {none, "application/octet-stream"}
|
||||||
|
end.
|
||||||
+13
-1
@@ -42,11 +42,23 @@ init([]) ->
|
|||||||
5000,
|
5000,
|
||||||
supervisor,
|
supervisor,
|
||||||
[fd_clients]},
|
[fd_clients]},
|
||||||
|
Chat = {fd_chat,
|
||||||
|
{fd_chat, start_link, []},
|
||||||
|
permanent,
|
||||||
|
5000,
|
||||||
|
worker,
|
||||||
|
[fd_chat]},
|
||||||
|
FileCache = {fd_sfc,
|
||||||
|
{fd_sfc, start_link, []},
|
||||||
|
permanent,
|
||||||
|
5000,
|
||||||
|
worker,
|
||||||
|
[fd_sfc]},
|
||||||
Cache = {fd_cache,
|
Cache = {fd_cache,
|
||||||
{fd_cache, start_link, []},
|
{fd_cache, start_link, []},
|
||||||
permanent,
|
permanent,
|
||||||
5000,
|
5000,
|
||||||
worker,
|
worker,
|
||||||
[fd_cache]},
|
[fd_cache]},
|
||||||
Children = [Clients, Cache],
|
Children = [Clients, Chat, FileCache, Cache],
|
||||||
{ok, {RestartStrategy, Children}}.
|
{ok, {RestartStrategy, Children}}.
|
||||||
|
|||||||
+819
@@ -0,0 +1,819 @@
|
|||||||
|
% @doc websockets
|
||||||
|
%
|
||||||
|
% ref: https://datatracker.ietf.org/doc/html/rfc6455
|
||||||
|
-module(fd_ws).
|
||||||
|
|
||||||
|
-export_type([
|
||||||
|
opcode/0,
|
||||||
|
frame/0,
|
||||||
|
ws_msg/0
|
||||||
|
]).
|
||||||
|
|
||||||
|
-export([
|
||||||
|
%% time units
|
||||||
|
ms/0, sec/0, min/0, hr/0, day/0,
|
||||||
|
%% porcelain
|
||||||
|
handshake/1,
|
||||||
|
recv/3, recv/4,
|
||||||
|
send/2
|
||||||
|
]).
|
||||||
|
|
||||||
|
-include("http.hrl").
|
||||||
|
-include("$zx_include/zx_logger.hrl").
|
||||||
|
|
||||||
|
-type request() :: #request{}.
|
||||||
|
-type response() :: #response{}.
|
||||||
|
-type tcp_error() :: closed
|
||||||
|
| {timeout, RestData :: binary() | erlang:iovec()}
|
||||||
|
| inet:posix().
|
||||||
|
|
||||||
|
-define(MAX_PAYLOAD_SIZE, ((1 bsl 63) - 1)).
|
||||||
|
|
||||||
|
%% Frames
|
||||||
|
%% https://datatracker.ietf.org/doc/html/rfc6455#section-5.2
|
||||||
|
|
||||||
|
-type opcode() :: continuation
|
||||||
|
| text
|
||||||
|
| binary
|
||||||
|
| close
|
||||||
|
| ping
|
||||||
|
| pong.
|
||||||
|
|
||||||
|
-record(frame,
|
||||||
|
{fin = none :: none | boolean(),
|
||||||
|
rsv = none :: none | <<_:3>>,
|
||||||
|
opcode = none :: none | opcode(),
|
||||||
|
mask = none :: none | boolean(),
|
||||||
|
payload_length = none :: none | non_neg_integer(),
|
||||||
|
masking_key = none :: none | <<>> | <<_:32>>,
|
||||||
|
payload = none :: none | binary()}).
|
||||||
|
|
||||||
|
-type frame() :: #frame{}.
|
||||||
|
|
||||||
|
|
||||||
|
%% porcelain messages
|
||||||
|
|
||||||
|
-type ws_msg() :: {text, Payload :: iodata()}
|
||||||
|
| {binary, Payload :: iodata()}
|
||||||
|
| {close, Payload :: iodata()}
|
||||||
|
| {ping, Payload :: iodata()}
|
||||||
|
| {pong, Payload :: iodata()}.
|
||||||
|
|
||||||
|
|
||||||
|
%% time units
|
||||||
|
ms() -> 1.
|
||||||
|
sec() -> 1_000.
|
||||||
|
min() -> 60*sec().
|
||||||
|
hr() -> 60*min().
|
||||||
|
day() -> 24*hr().
|
||||||
|
|
||||||
|
|
||||||
|
-spec handshake(Req) -> Result
|
||||||
|
when Req :: request(),
|
||||||
|
Result :: {ok, ClientProtocols, ClientExtensions, DraftResponse}
|
||||||
|
| {error, Reason},
|
||||||
|
ClientProtocols :: [binary()],
|
||||||
|
ClientExtensions :: binary(),
|
||||||
|
DraftResponse :: response(),
|
||||||
|
Reason :: any().
|
||||||
|
% @doc
|
||||||
|
% This mostly just validates that all the 't's have been dotted and 'i's have
|
||||||
|
% been crossed.
|
||||||
|
%
|
||||||
|
% given an HTTP request:
|
||||||
|
%
|
||||||
|
% - if it is NOT a valid websocket handshake request, error
|
||||||
|
% - if it IS a valid websocket handshake request, form an initial candidate
|
||||||
|
% response record with the following fields:
|
||||||
|
%
|
||||||
|
% code = 101
|
||||||
|
% slogan = "Switching Protocols"
|
||||||
|
% headers = [{"Sec-WebSocket-Accept", ChallengeResponse},
|
||||||
|
% {"Connection", "Upgrade"},
|
||||||
|
% {"Upgrade", "websocket"}].
|
||||||
|
%
|
||||||
|
% YOU are responsible for dealing with any cookie logic, authentication logic,
|
||||||
|
% validating the Origin field, implementing cross-site-request-forgery, adding
|
||||||
|
% the retarded web date, rendering the response, sending it over the socket,
|
||||||
|
% etc.
|
||||||
|
%
|
||||||
|
% The returned ClientExtensions is the result of joining the
|
||||||
|
% <<"sec-websocket-extensions">> fields with ", "
|
||||||
|
%
|
||||||
|
% quoth section 9.1: https://datatracker.ietf.org/doc/html/rfc6455#section-9.1
|
||||||
|
%
|
||||||
|
% > Note that like other HTTP header fields, this header field MAY be
|
||||||
|
% > split or combined across multiple lines. Ergo, the following are
|
||||||
|
% > equivalent:
|
||||||
|
% >
|
||||||
|
% > Sec-WebSocket-Extensions: foo
|
||||||
|
% > Sec-WebSocket-Extensions: bar; baz=2
|
||||||
|
% >
|
||||||
|
% > is exactly equivalent to
|
||||||
|
% >
|
||||||
|
% > Sec-WebSocket-Extensions: foo, bar; baz=2
|
||||||
|
%
|
||||||
|
% Nobody actually uses extensions, so how you choose to parse this is on you.
|
||||||
|
|
||||||
|
handshake(R = #request{method = get, headers = Hs}) ->
|
||||||
|
%% downcase the headers because have to match on them
|
||||||
|
handshake2(R#request{headers = casefold_headers(Hs)});
|
||||||
|
handshake(_) ->
|
||||||
|
{error, bad_method}.
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
-spec casefold_headers(Headers) -> DowncaseHeaders
|
||||||
|
when Headers :: #{Key := Value},
|
||||||
|
Key :: binary(),
|
||||||
|
Value :: binary(),
|
||||||
|
DowncaseHeaders :: Headers.
|
||||||
|
% @private
|
||||||
|
% casefold all the keys in the header because they're case insensitive
|
||||||
|
|
||||||
|
casefold_headers(Headers) ->
|
||||||
|
Downcase =
|
||||||
|
fun({K, V}) ->
|
||||||
|
NewKey = unicode:characters_to_binary(string:casefold(K)),
|
||||||
|
{NewKey, V}
|
||||||
|
end,
|
||||||
|
maps:from_list(lists:map(Downcase, maps:to_list(Headers))).
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
-spec handshake2(DowncaseReq) -> Result
|
||||||
|
when DowncaseReq :: request(),
|
||||||
|
Result :: {ok, DraftResponse}
|
||||||
|
| {error, Reason},
|
||||||
|
DraftResponse :: response(),
|
||||||
|
Reason :: any().
|
||||||
|
% @private
|
||||||
|
% we may assume (WMA) method=get and headers have all been downcased
|
||||||
|
|
||||||
|
handshake2(#request{headers = DowncaseHeaders}) ->
|
||||||
|
% headers MUST contain fields:
|
||||||
|
% sec-websocket-key: _ % arbitrary
|
||||||
|
% sec-websocket-version: 13 % must be EXACTLY 13
|
||||||
|
% connection: Upgrade % must include the token "Upgrade"
|
||||||
|
% upgrade: websocket % must include the token "websocket"
|
||||||
|
MaybeResponseToken = validate_headers(DowncaseHeaders),
|
||||||
|
case MaybeResponseToken of
|
||||||
|
{ok, ResponseToken} ->
|
||||||
|
DraftResponse =
|
||||||
|
#response{code = 101,
|
||||||
|
slogan = "Switching Protocols",
|
||||||
|
headers = [{"Sec-WebSocket-Accept", ResponseToken},
|
||||||
|
{"Connection", "Upgrade"},
|
||||||
|
{"Upgrade", "websocket"}]},
|
||||||
|
{ok, DraftResponse};
|
||||||
|
Error ->
|
||||||
|
Error
|
||||||
|
end.
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
-spec validate_headers(HeadersMap) -> Result
|
||||||
|
when HeadersMap :: #{Key :: binary() := Val :: binary()},
|
||||||
|
Result :: {ok, ResponseToken}
|
||||||
|
| {error, Reason},
|
||||||
|
ResponseToken :: binary(),
|
||||||
|
Reason :: any().
|
||||||
|
% @private
|
||||||
|
% validate:
|
||||||
|
% Upgrade: websocket
|
||||||
|
% Connection: Upgrade
|
||||||
|
% Sec-WebSocket-Version: 13
|
||||||
|
|
||||||
|
validate_headers(#{<<"sec-websocket-key">> := ChallengeToken,
|
||||||
|
<<"sec-websocket-version">> := WS_Vsn,
|
||||||
|
<<"connection">> := Connection,
|
||||||
|
<<"upgrade">> := Upgrade}) ->
|
||||||
|
BadUpgrade = bad_upgrade(Upgrade),
|
||||||
|
BadConnection = bad_connection(Connection),
|
||||||
|
BadVersion = bad_version(WS_Vsn),
|
||||||
|
if
|
||||||
|
BadUpgrade -> {error, {bad_upgrade, Upgrade}};
|
||||||
|
BadConnection -> {error, {bad_connection, Connection}};
|
||||||
|
BadVersion -> {error, {bad_version, WS_Vsn}};
|
||||||
|
true -> {ok, response_token(ChallengeToken)}
|
||||||
|
end;
|
||||||
|
validate_headers(_) ->
|
||||||
|
{error, bad_request}.
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
-spec bad_upgrade(binary()) -> true | false.
|
||||||
|
% @private string must include "websocket" as a token
|
||||||
|
|
||||||
|
bad_upgrade(Str) ->
|
||||||
|
case string:find(Str, "websocket") of
|
||||||
|
nomatch -> true;
|
||||||
|
_ -> false
|
||||||
|
end.
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
-spec bad_connection(binary()) -> true | false.
|
||||||
|
% @private string must include "Upgrade" as a token
|
||||||
|
|
||||||
|
bad_connection(Str) ->
|
||||||
|
case string:find(Str, "Upgrade") of
|
||||||
|
nomatch -> true;
|
||||||
|
_ -> false
|
||||||
|
end.
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
-spec bad_version(binary()) -> true | false.
|
||||||
|
% @private version must be EXACTLY <<"13">>
|
||||||
|
|
||||||
|
bad_version(<<"13">>) -> false;
|
||||||
|
bad_version(_) -> true.
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
-spec response_token(binary()) -> binary().
|
||||||
|
% @doc
|
||||||
|
% Quoth the RFC:
|
||||||
|
%
|
||||||
|
% > Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
|
||||||
|
% >
|
||||||
|
% > For this header field, the server has to take the value (as present
|
||||||
|
% > in the header field, e.g., the base64-encoded [RFC4648] version minus
|
||||||
|
% > any leading and trailing whitespace) and concatenate this with the
|
||||||
|
% > Globally Unique Identifier (GUID, [RFC4122]) "258EAFA5-E914-47DA-
|
||||||
|
% > 95CA-C5AB0DC85B11" in string form, which is unlikely to be used by
|
||||||
|
% > network endpoints that do not understand the WebSocket Protocol. A
|
||||||
|
% > SHA-1 hash (160 bits) [FIPS.180-3], base64-encoded (see Section 4 of
|
||||||
|
% > [RFC4648]), of this concatenation is then returned in the server's
|
||||||
|
% > handshake.
|
||||||
|
% >
|
||||||
|
% > Concretely, if as in the example above, the |Sec-WebSocket-Key|
|
||||||
|
% > header field had the value "dGhlIHNhbXBsZSBub25jZQ==", the server
|
||||||
|
% > would concatenate the string "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
|
||||||
|
% > to form the string "dGhlIHNhbXBsZSBub25jZQ==258EAFA5-E914-47DA-95CA-
|
||||||
|
% > C5AB0DC85B11". The server would then take the SHA-1 hash of this,
|
||||||
|
% > giving the value 0xb3 0x7a 0x4f 0x2c 0xc0 0x62 0x4f 0x16 0x90 0xf6
|
||||||
|
% > 0x46 0x06 0xcf 0x38 0x59 0x45 0xb2 0xbe 0xc4 0xea. This value is
|
||||||
|
% > then base64-encoded (see Section 4 of [RFC4648]), to give the value
|
||||||
|
% > "s3pPLMBiTxaQ9kYGzzhZRbK+xOo=". This value would then be echoed in
|
||||||
|
% > the |Sec-WebSocket-Accept| header field.
|
||||||
|
|
||||||
|
response_token(ChallengeToken) when is_binary(ChallengeToken) ->
|
||||||
|
MagicString = <<"258EAFA5-E914-47DA-95CA-C5AB0DC85B11">>,
|
||||||
|
ConcatString = <<ChallengeToken/binary, MagicString/binary>>,
|
||||||
|
Sha1 = crypto:hash(sha, ConcatString),
|
||||||
|
base64:encode(Sha1).
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
-spec recv(Socket, Received, TimeoutMS) -> Result
|
||||||
|
when Socket :: gen_tcp:socket(),
|
||||||
|
Received :: binary(),
|
||||||
|
TimeoutMS :: non_neg_integer(),
|
||||||
|
Result :: {ok, Message, Frames, Remainder}
|
||||||
|
| {error, Reason},
|
||||||
|
Message :: ws_msg(),
|
||||||
|
Frames :: [frame()],
|
||||||
|
Remainder :: binary(),
|
||||||
|
Reason :: any().
|
||||||
|
% @doc
|
||||||
|
% Equivalent to recv(Socket, Received, [])
|
||||||
|
|
||||||
|
recv(Sock, Recv, TimeoutMS) ->
|
||||||
|
recv(Sock, Recv, TimeoutMS, []).
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
-spec recv(Socket, Received, TimeoutMS, Frames) -> Result
|
||||||
|
when Socket :: gen_tcp:socket(),
|
||||||
|
Received :: binary(),
|
||||||
|
TimeoutMS :: non_neg_integer(),
|
||||||
|
Frames :: [frame()],
|
||||||
|
Result :: {ok, Message, NewFrames, Remainder}
|
||||||
|
| {error, Reason},
|
||||||
|
Message :: ws_msg(),
|
||||||
|
NewFrames :: Frames,
|
||||||
|
Remainder :: binary(),
|
||||||
|
Reason :: any().
|
||||||
|
% @doc
|
||||||
|
% Pull a message off the socket
|
||||||
|
|
||||||
|
recv(Sock, Received, Timeout, Frames) ->
|
||||||
|
case maybe_pop_msg(Frames) of
|
||||||
|
{ok, Message, NewFrames} ->
|
||||||
|
{ok, Message, NewFrames, Received};
|
||||||
|
incomplete ->
|
||||||
|
case recv_frame(#frame{}, Sock, Received, Timeout) of
|
||||||
|
{ok, Frame, NewReceived} ->
|
||||||
|
NewFrames = [Frame | Frames],
|
||||||
|
recv(Sock, NewReceived, Timeout, NewFrames);
|
||||||
|
Error ->
|
||||||
|
Error
|
||||||
|
end;
|
||||||
|
Error ->
|
||||||
|
Error
|
||||||
|
end.
|
||||||
|
|
||||||
|
|
||||||
|
-spec maybe_pop_msg(Frames) -> Result
|
||||||
|
when Frames :: [frame()],
|
||||||
|
Result :: {ok, Message, NewFrames}
|
||||||
|
| incomplete
|
||||||
|
| {error, Reason},
|
||||||
|
Message :: ws_msg(),
|
||||||
|
NewFrames :: Frames,
|
||||||
|
Reason :: any().
|
||||||
|
% @private
|
||||||
|
% try to parse the stack of frames into a single message
|
||||||
|
%
|
||||||
|
% ignores RSV bits
|
||||||
|
% @end
|
||||||
|
|
||||||
|
maybe_pop_msg([]) ->
|
||||||
|
incomplete;
|
||||||
|
% case 1: control frames
|
||||||
|
% note that maybe_control_msg checks that the fin bit is true
|
||||||
|
%
|
||||||
|
% meaning if the client sends a malicious control frame with fin=false, that
|
||||||
|
% error will be caught in maybe_control_msg
|
||||||
|
maybe_pop_msg([Frame = #frame{opcode = ControlOpcode} | Frames])
|
||||||
|
when (ControlOpcode =:= close)
|
||||||
|
orelse (ControlOpcode =:= ping)
|
||||||
|
orelse (ControlOpcode =:= pong) ->
|
||||||
|
case maybe_control_msg(Frame) of
|
||||||
|
{ok, Msg} -> {ok, Msg, Frames};
|
||||||
|
Error -> Error
|
||||||
|
end;
|
||||||
|
% case 2: messages
|
||||||
|
% finished message in a single frame, just pull here
|
||||||
|
maybe_pop_msg([Frame = #frame{fin = true,
|
||||||
|
opcode = DataOpcode,
|
||||||
|
mask = Mask,
|
||||||
|
masking_key = Key,
|
||||||
|
payload = Payload}
|
||||||
|
| Rest])
|
||||||
|
when DataOpcode =:= text; DataOpcode =:= binary ->
|
||||||
|
case maybe_unmask(Frame, Mask, Key, Payload) of
|
||||||
|
{ok, Unmasked} ->
|
||||||
|
Message = {DataOpcode, Unmasked},
|
||||||
|
{ok, Message, Rest};
|
||||||
|
Error ->
|
||||||
|
Error
|
||||||
|
end;
|
||||||
|
% end of a long message
|
||||||
|
maybe_pop_msg(Frames = [#frame{fin = true,
|
||||||
|
opcode = continuation} | _]) ->
|
||||||
|
maybe_long_data_msg(Frames);
|
||||||
|
% unfinished message, say we need more
|
||||||
|
maybe_pop_msg([#frame{fin = false,
|
||||||
|
opcode = continuation}
|
||||||
|
| _]) ->
|
||||||
|
incomplete;
|
||||||
|
% wtf... this case should be impossible
|
||||||
|
maybe_pop_msg([Frame | _]) ->
|
||||||
|
{error, {wtf_frame, Frame}}.
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
-spec maybe_long_data_msg(Frames) -> Result
|
||||||
|
when Frames :: [frame()],
|
||||||
|
Result :: {ok, Message, NewFrames}
|
||||||
|
| {error, Reason},
|
||||||
|
Message :: ws_msg(),
|
||||||
|
NewFrames :: Frames,
|
||||||
|
Reason :: any().
|
||||||
|
% @private
|
||||||
|
% assumes:
|
||||||
|
% 1. top of stack is a finished frame
|
||||||
|
% 2. top opcode is continuation
|
||||||
|
% 3. the stack corresponds to a linear sequence of frames all corresponding to
|
||||||
|
% one message, until we get to the leading frame of the message, which must
|
||||||
|
% have opcode text|binary
|
||||||
|
%
|
||||||
|
% the reason we can make this assumption is because anterior in the call
|
||||||
|
% chain is recv/3, which eagerly consumes control messages
|
||||||
|
%
|
||||||
|
% meaning if we encounter a control frame in the middle here, we can assume
|
||||||
|
% there is some sort of bug
|
||||||
|
%
|
||||||
|
% TODO: I am NOT enforcing that the data message consumes the entire stack of
|
||||||
|
% frames. Given that the context here is eager consumption, this might be a
|
||||||
|
% point of enforcement. Need to think about this.
|
||||||
|
% @end
|
||||||
|
|
||||||
|
maybe_long_data_msg(Frames) ->
|
||||||
|
mldm(Frames, Frames, <<>>).
|
||||||
|
|
||||||
|
|
||||||
|
% general case: decode the payload in this frame
|
||||||
|
mldm(OrigFrames, [Frame | Rest], Acc) ->
|
||||||
|
Opcode = Frame#frame.opcode,
|
||||||
|
Mask = Frame#frame.mask,
|
||||||
|
Key = Frame#frame.masking_key,
|
||||||
|
Payload = Frame#frame.payload,
|
||||||
|
case maybe_unmask(Frame, Mask, Key, Payload) of
|
||||||
|
{ok, Unmasked} ->
|
||||||
|
NewAcc = <<Unmasked/binary, Acc/binary>>,
|
||||||
|
case Opcode of
|
||||||
|
continuation -> mldm(OrigFrames, Rest, NewAcc);
|
||||||
|
text -> {ok, {text, NewAcc}, Rest};
|
||||||
|
binary -> {ok, {binary, NewAcc}, Rest};
|
||||||
|
_ -> {error, {illegal_data_frame, Frame, OrigFrames, Acc}}
|
||||||
|
end;
|
||||||
|
Error ->
|
||||||
|
Error
|
||||||
|
end;
|
||||||
|
% out of frames
|
||||||
|
mldm(OrigFrames, [], Acc) ->
|
||||||
|
{error, {no_start_frame, Acc, OrigFrames}}.
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
-spec maybe_control_msg(Frame) -> Result
|
||||||
|
when Frame :: frame(),
|
||||||
|
Result :: {ok, Message}
|
||||||
|
| {error, Reason},
|
||||||
|
Message :: ws_msg(),
|
||||||
|
Reason :: any().
|
||||||
|
% @private
|
||||||
|
% assume the frame is a control frame, validate it, and unmask the payload
|
||||||
|
%
|
||||||
|
% TODO: this doesn't enforce that messages from the client HAVE to be masked,
|
||||||
|
% which strictly speaking is part of the protocol.
|
||||||
|
|
||||||
|
maybe_control_msg(F = #frame{fin = true,
|
||||||
|
opcode = Opcode,
|
||||||
|
mask = Mask,
|
||||||
|
payload_length = Len,
|
||||||
|
masking_key = Key,
|
||||||
|
payload = Payload})
|
||||||
|
when ((Opcode =:= close) orelse (Opcode =:= ping) orelse (Opcode =:= pong))
|
||||||
|
andalso (Len =< 125) ->
|
||||||
|
case maybe_unmask(F, Mask, Key, Payload) of
|
||||||
|
{ok, UnmaskedPayload} ->
|
||||||
|
Msg = {Opcode, UnmaskedPayload},
|
||||||
|
{ok, Msg};
|
||||||
|
Error ->
|
||||||
|
Error
|
||||||
|
end;
|
||||||
|
maybe_control_msg(F) ->
|
||||||
|
{error, {illegal_frame, F}}.
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
-spec maybe_unmask(Frame, Mask, Key, Payload) -> Result
|
||||||
|
when Frame :: frame(),
|
||||||
|
Mask :: boolean(),
|
||||||
|
Key :: <<>> | <<_:32>>,
|
||||||
|
Payload :: binary(),
|
||||||
|
Result :: {ok, Unmasked}
|
||||||
|
| {error, Reason},
|
||||||
|
Unmasked :: binary(),
|
||||||
|
Reason :: any().
|
||||||
|
% @private
|
||||||
|
% unmask the payload
|
||||||
|
% @end
|
||||||
|
|
||||||
|
% eliminate invalid pairs of {mask, masking_key}
|
||||||
|
maybe_unmask(_, true, <<Key:4/bytes>>, Payload) -> {ok, mask_unmask(Key, Payload)};
|
||||||
|
maybe_unmask(_, false, <<>>, Payload) -> {ok, Payload};
|
||||||
|
maybe_unmask(F, true, <<>>, _) -> {error, {illegal_frame, F}};
|
||||||
|
maybe_unmask(F, false, <<_:4/bytes>>, _) -> {error, {illegal_frame, F}}.
|
||||||
|
|
||||||
|
|
||||||
|
%% invertible
|
||||||
|
%% see: https://datatracker.ietf.org/doc/html/rfc6455#section-5.3
|
||||||
|
mask_unmask(Key = <<_:4/bytes>>, Payload) ->
|
||||||
|
mu(Key, Key, Payload, <<>>).
|
||||||
|
|
||||||
|
% essentially this is a modular zipWith xor of the masking key with the payload
|
||||||
|
mu(Key, <<KeyByte:8, KeyRest/binary>>, <<PayloadByte:8, PayloadRest/binary>>, Acc) ->
|
||||||
|
NewByte = KeyByte bxor PayloadByte,
|
||||||
|
NewAcc = <<Acc/binary, NewByte:8>>,
|
||||||
|
mu(Key, KeyRest, PayloadRest, NewAcc);
|
||||||
|
% this is the case where we need to refresh the active key
|
||||||
|
mu(Key, <<>>, Payload, Acc) ->
|
||||||
|
mu(Key, Key, Payload, Acc);
|
||||||
|
% done
|
||||||
|
mu(_, _, <<>>, Acc) ->
|
||||||
|
Acc.
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
-spec recv_frame(Parsed, Socket, Received, TimeoutMS) -> Result
|
||||||
|
when Parsed :: frame(),
|
||||||
|
Socket :: gen_tcp:socket(),
|
||||||
|
Received :: bitstring(),
|
||||||
|
TimeoutMS :: non_neg_integer(),
|
||||||
|
Result :: {ok, frame(), Remainder}
|
||||||
|
| {error, Reason},
|
||||||
|
Remainder :: bitstring(),
|
||||||
|
Reason :: any().
|
||||||
|
% @private
|
||||||
|
% parse a single frame off the socket
|
||||||
|
% @end
|
||||||
|
|
||||||
|
%% frame: 1 bit
|
||||||
|
recv_frame(Frame = #frame{fin = none}, Sock, <<FinBit:1, Rest/bits>>, Timeout) ->
|
||||||
|
NewFin =
|
||||||
|
case FinBit of
|
||||||
|
0 -> false;
|
||||||
|
1 -> true
|
||||||
|
end,
|
||||||
|
NewFrame = Frame#frame{fin = NewFin},
|
||||||
|
recv_frame(NewFrame, Sock, Rest, Timeout);
|
||||||
|
recv_frame(Frame = #frame{fin = none}, Sock, Received = <<>>, Timeout) ->
|
||||||
|
recv_frame_await(Frame, Sock, Received, Timeout);
|
||||||
|
%% rsv: 3 bits
|
||||||
|
recv_frame(Frame = #frame{rsv = none}, Sock, <<RSV:3/bits, Rest/bits>>, Timeout) ->
|
||||||
|
NewFrame = Frame#frame{rsv = RSV},
|
||||||
|
recv_frame(NewFrame, Sock, Rest, Timeout);
|
||||||
|
recv_frame(Frame = #frame{rsv = none}, Sock, Received, Timeout) ->
|
||||||
|
recv_frame_await(Frame, Sock, Received, Timeout);
|
||||||
|
%% opcode: 4 bits
|
||||||
|
recv_frame(Frame = #frame{opcode = none}, Sock, <<OpcodeInt:4, Rest/bits>>, Timeout) ->
|
||||||
|
Opcode =
|
||||||
|
case OpcodeInt of
|
||||||
|
0 -> continuation;
|
||||||
|
1 -> text;
|
||||||
|
2 -> binary;
|
||||||
|
8 -> close;
|
||||||
|
9 -> ping;
|
||||||
|
10 -> pong;
|
||||||
|
_ -> bad_opcode
|
||||||
|
end,
|
||||||
|
case Opcode of
|
||||||
|
bad_opcode ->
|
||||||
|
{error, {bad_opcode, OpcodeInt}};
|
||||||
|
_ ->
|
||||||
|
NewFrame = Frame#frame{opcode = Opcode},
|
||||||
|
recv_frame(NewFrame, Sock, Rest, Timeout)
|
||||||
|
end;
|
||||||
|
recv_frame(Frame = #frame{opcode = none}, Sock, Received, Timeout) ->
|
||||||
|
recv_frame_await(Frame, Sock, Received, Timeout);
|
||||||
|
%% mask: 1 bit
|
||||||
|
recv_frame(Frame = #frame{mask = none}, Sock, <<MaskBit:1, Rest/bits>>, Timeout) ->
|
||||||
|
NewMask =
|
||||||
|
case MaskBit of
|
||||||
|
0 -> false;
|
||||||
|
1 -> true
|
||||||
|
end,
|
||||||
|
NewFrame = Frame#frame{mask = NewMask},
|
||||||
|
recv_frame(NewFrame, Sock, Rest, Timeout);
|
||||||
|
recv_frame(Frame = #frame{mask = none}, Sock, Received = <<>>, Timeout) ->
|
||||||
|
recv_frame_await(Frame, Sock, Received, Timeout);
|
||||||
|
%% payload length: variable (yay)
|
||||||
|
% first case: short length 0..125
|
||||||
|
recv_frame(Frame = #frame{payload_length = none}, Sock, <<Len:7, Rest/bits>>, Timeout) when Len =< 125 ->
|
||||||
|
NewFrame = Frame#frame{payload_length = Len},
|
||||||
|
recv_frame(NewFrame, Sock, Rest, Timeout);
|
||||||
|
% second case: 126 -> 2 bytes to follow
|
||||||
|
recv_frame(Frame = #frame{payload_length = none}, Sock, <<126:7, Len:16, Rest/bits>>, Timeout) ->
|
||||||
|
NewFrame = Frame#frame{payload_length = Len},
|
||||||
|
recv_frame(NewFrame, Sock, Rest, Timeout);
|
||||||
|
% third case: 127 -> 8 bytes to follow
|
||||||
|
% bytes must start with a 0 bit
|
||||||
|
recv_frame(_Frame = #frame{payload_length = none}, _Sock, <<127:7, 1:1, _/bits>>, _Timeout) ->
|
||||||
|
{error, {illegal_frame, "payload length >= 1 bsl 63"}};
|
||||||
|
% 127, next is a legal length, continue
|
||||||
|
recv_frame(Frame = #frame{payload_length = none}, Sock, <<127:7, Len:64, Rest/bits>>, Timeout) ->
|
||||||
|
NewFrame = Frame#frame{payload_length = Len},
|
||||||
|
recv_frame(NewFrame, Sock, Rest, Timeout);
|
||||||
|
% otherwise wait
|
||||||
|
recv_frame(Frame = #frame{payload_length = none}, Sock, Received, Timeout) ->
|
||||||
|
recv_frame_await(Frame, Sock, Received, Timeout);
|
||||||
|
%% masking key: 0 or 4 bits
|
||||||
|
% not expecting a masking key, fill in that field here
|
||||||
|
recv_frame(Frame = #frame{mask = false, masking_key = none}, Sock, Received, Timeout) ->
|
||||||
|
NewFrame = Frame#frame{masking_key = <<>>},
|
||||||
|
recv_frame(NewFrame, Sock, Received, Timeout);
|
||||||
|
% expecting one
|
||||||
|
recv_frame(Frame = #frame{mask = true, masking_key = none}, Sock, <<Key:4/bytes, Rest/bits>>, Timeout) ->
|
||||||
|
NewFrame = Frame#frame{masking_key = Key},
|
||||||
|
recv_frame(NewFrame, Sock, Rest, Timeout);
|
||||||
|
% not found
|
||||||
|
recv_frame(Frame = #frame{mask = true, masking_key = none}, Sock, Received, Timeout) ->
|
||||||
|
recv_frame_await(Frame, Sock, Received, Timeout);
|
||||||
|
%% payload
|
||||||
|
recv_frame(Frame = #frame{payload_length = Len, payload = none}, Sock, Received, Timeout) when is_integer(Len) ->
|
||||||
|
case Received of
|
||||||
|
% we have enough bytes
|
||||||
|
<<Payload:Len/bytes, Rest/bits>> ->
|
||||||
|
FinalFrame = Frame#frame{payload = Payload},
|
||||||
|
{ok, FinalFrame, Rest};
|
||||||
|
% we do not have enough bytes
|
||||||
|
_ ->
|
||||||
|
recv_frame_await(Frame, Sock, Received, Timeout)
|
||||||
|
end.
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
%% factoring this out into a function to reduce repetition
|
||||||
|
recv_frame_await(Frame, Sock, Received, Timeout) ->
|
||||||
|
case inet:setopts(Sock, [{active, once}]) of
|
||||||
|
ok ->
|
||||||
|
receive
|
||||||
|
{tcp, Sock, Bin} -> recv_frame(Frame, Sock, <<Received/bits, Bin/binary>>, Timeout);
|
||||||
|
{tcp_closed, Sock} -> {error, tcp_closed};
|
||||||
|
{tcp_error, Sock, Reason} -> {error, {tcp_error, Reason}}
|
||||||
|
after Timeout ->
|
||||||
|
{error, timeout}
|
||||||
|
end;
|
||||||
|
{error, Reason} ->
|
||||||
|
{error, {inet, Reason}}
|
||||||
|
end.
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
-spec send(Socket, Message) -> Result
|
||||||
|
when Socket :: gen_tcp:socket(),
|
||||||
|
Message :: ws_msg(),
|
||||||
|
Result :: ok
|
||||||
|
| {error, Reason},
|
||||||
|
Reason :: any().
|
||||||
|
% @doc
|
||||||
|
% send message to client over Socket. handles frame nonsense
|
||||||
|
%
|
||||||
|
% max payload size is 2^63 - 1 bytes
|
||||||
|
% @end
|
||||||
|
|
||||||
|
send(Socket, {Type, Payload}) ->
|
||||||
|
tell("fd_ws: send(~tp, {~tp, ~tp})", [Socket, Type, Payload]),
|
||||||
|
BPayload = payload_to_binary(Payload),
|
||||||
|
tell("fd_ws: BPayload = ~tp", [BPayload]),
|
||||||
|
Frame = message_to_frame(Type, BPayload),
|
||||||
|
tell("fd_ws: Frame = ~tp", [Frame]),
|
||||||
|
send_frame(Socket, Frame).
|
||||||
|
|
||||||
|
payload_to_binary(Bin) when is_binary(Bin) -> Bin;
|
||||||
|
payload_to_binary(X) -> unicode:characters_to_binary(X).
|
||||||
|
|
||||||
|
|
||||||
|
% data messages
|
||||||
|
message_to_frame(Data, Payload)
|
||||||
|
when ((Data =:= text) orelse (Data =:= binary)),
|
||||||
|
is_binary(Payload),
|
||||||
|
(byte_size(Payload) =< ?MAX_PAYLOAD_SIZE) ->
|
||||||
|
#frame{fin = true,
|
||||||
|
opcode = Data,
|
||||||
|
payload_length = byte_size(Payload),
|
||||||
|
payload = Payload};
|
||||||
|
message_to_frame(Control, Payload)
|
||||||
|
when ((Control =:= close) orelse (Control =:= ping) orelse (Control =:= pong)),
|
||||||
|
is_binary(Payload),
|
||||||
|
(byte_size(Payload) =< 125) ->
|
||||||
|
#frame{fin = true,
|
||||||
|
opcode = Control,
|
||||||
|
payload_length = byte_size(Payload),
|
||||||
|
payload = Payload}.
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
-spec send_frame(Sock, Frame) -> Result
|
||||||
|
when Sock :: gen_tcp:socket(),
|
||||||
|
Frame :: frame(),
|
||||||
|
Result :: ok
|
||||||
|
| {error, Reason},
|
||||||
|
Reason :: tcp_error().
|
||||||
|
% @private
|
||||||
|
% send a frame on the socket
|
||||||
|
% @end
|
||||||
|
|
||||||
|
send_frame(Sock, Frame) ->
|
||||||
|
Binary = render_frame(Frame),
|
||||||
|
tell("send_frame: rendered frame: ~tp", [Binary]),
|
||||||
|
gen_tcp:send(Sock, Binary).
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
-spec render_frame(Frame) -> Binary
|
||||||
|
when Frame :: frame(),
|
||||||
|
Binary :: binary().
|
||||||
|
% @private
|
||||||
|
% render a frame
|
||||||
|
%
|
||||||
|
% All fields in a `#frame{}` record have default values of `none`.
|
||||||
|
%
|
||||||
|
% ```erlang
|
||||||
|
% -record(frame,
|
||||||
|
% {fin = none :: none | boolean(),
|
||||||
|
% rsv = none :: none | <<_:3>>,
|
||||||
|
% opcode = none :: none | opcode(),
|
||||||
|
% mask = none :: none | boolean(),
|
||||||
|
% payload_length = none :: none | non_neg_integer(),
|
||||||
|
% masking_key = none :: none | <<>> | <<_:32>>,
|
||||||
|
% payload = none :: none | binary()}).
|
||||||
|
% ```
|
||||||
|
%
|
||||||
|
% Given a value of `none`, some of these fields are inferred, some cannot be
|
||||||
|
% inferred.
|
||||||
|
%
|
||||||
|
% Inference cases:
|
||||||
|
%
|
||||||
|
% ```
|
||||||
|
% rsv = none -> <<0:3>>
|
||||||
|
% mask = none -> false
|
||||||
|
% masking_key = none -> <<>>
|
||||||
|
% payload_length = none -> byte_size(Payload)
|
||||||
|
% ```
|
||||||
|
%
|
||||||
|
% Non-inference:
|
||||||
|
%
|
||||||
|
% ```
|
||||||
|
% fin
|
||||||
|
% opcode
|
||||||
|
% payload
|
||||||
|
% ```
|
||||||
|
% @end
|
||||||
|
|
||||||
|
render_frame(#frame{fin = Fin,
|
||||||
|
rsv = RSV,
|
||||||
|
opcode = Opcode,
|
||||||
|
mask = Mask,
|
||||||
|
payload_length = Len,
|
||||||
|
masking_key = MaskingKey,
|
||||||
|
payload = Payload}) ->
|
||||||
|
BFin =
|
||||||
|
case Fin of
|
||||||
|
true -> <<1:1>>;
|
||||||
|
false -> <<0:1>>
|
||||||
|
end,
|
||||||
|
BRSV =
|
||||||
|
case RSV of
|
||||||
|
none -> <<0:3>>;
|
||||||
|
<<_:3>> -> RSV;
|
||||||
|
_ -> error({illegal_rsv, RSV})
|
||||||
|
end,
|
||||||
|
BOpcode =
|
||||||
|
case Opcode of
|
||||||
|
continuation -> << 0:4>>;
|
||||||
|
text -> << 1:4>>;
|
||||||
|
binary -> << 2:4>>;
|
||||||
|
close -> << 8:4>>;
|
||||||
|
ping -> << 9:4>>;
|
||||||
|
pong -> <<10:4>>
|
||||||
|
end,
|
||||||
|
BoolMask =
|
||||||
|
case Mask of
|
||||||
|
none -> false;
|
||||||
|
false -> false;
|
||||||
|
true -> true
|
||||||
|
end,
|
||||||
|
BMask =
|
||||||
|
case BoolMask of
|
||||||
|
true -> <<1:1>>;
|
||||||
|
false -> <<0:1>>
|
||||||
|
end,
|
||||||
|
IntPayloadLength =
|
||||||
|
case Len of
|
||||||
|
none -> byte_size(Payload);
|
||||||
|
_ -> Len
|
||||||
|
end,
|
||||||
|
BPayloadLength = render_payload_length(IntPayloadLength),
|
||||||
|
BMaskingKey =
|
||||||
|
case {BoolMask, MaskingKey} of
|
||||||
|
{false, none} -> <<>>;
|
||||||
|
{false, <<>>} -> <<>>;
|
||||||
|
{true, <<BKey:4/bytes>>} -> BKey;
|
||||||
|
{false, _} -> error({not_masking_but_have_masking_key, {Mask, MaskingKey}});
|
||||||
|
{true, _} -> error({illegal_masking_key, MaskingKey})
|
||||||
|
end,
|
||||||
|
% failure case here is same as error case just above, so no need to worry
|
||||||
|
% about cryptic "illegal frame" message
|
||||||
|
%
|
||||||
|
% masking = unmasking, so `maybe_unmask` is a bit of a misnomer
|
||||||
|
{ok, BPayload} = maybe_unmask(#frame{}, BoolMask, BMaskingKey, Payload),
|
||||||
|
<<BFin/bits,
|
||||||
|
BRSV/bits,
|
||||||
|
BOpcode/bits,
|
||||||
|
BMask/bits,
|
||||||
|
BPayloadLength/bits,
|
||||||
|
BMaskingKey/binary,
|
||||||
|
BPayload/binary>>.
|
||||||
|
|
||||||
|
|
||||||
|
-spec render_payload_length(non_neg_integer()) -> binary().
|
||||||
|
% @private
|
||||||
|
% > Payload length: 7 bits, 7+16 bits, or 7+64 bits
|
||||||
|
% >
|
||||||
|
% > The length of the "Payload data", in bytes: if 0-125, that is the
|
||||||
|
% > payload length. If 126, the following 2 bytes interpreted as a
|
||||||
|
% > 16-bit unsigned integer are the payload length. If 127, the
|
||||||
|
% > following 8 bytes interpreted as a 64-bit unsigned integer (the
|
||||||
|
% > most significant bit MUST be 0) are the payload length. Multibyte
|
||||||
|
% > length quantities are expressed in network byte order. Note that
|
||||||
|
% > in all cases, the minimal number of bytes MUST be used to encode
|
||||||
|
% > the length, for example, the length of a 124-byte-long string
|
||||||
|
% > can't be encoded as the sequence 126, 0, 124. The payload length
|
||||||
|
% > is the length of the "Extension data" + the length of the
|
||||||
|
% > "Application data". The length of the "Extension data" may be
|
||||||
|
% > zero, in which case the payload length is the length of the
|
||||||
|
% > "Application data".
|
||||||
|
|
||||||
|
render_payload_length(Len) when 0 =< Len, Len =< 125 ->
|
||||||
|
<<Len:7>>;
|
||||||
|
render_payload_length(Len) when 126 =< Len, Len =< 2#1111_1111_1111_1111 ->
|
||||||
|
<<126:7, Len:16>>;
|
||||||
|
render_payload_length(Len) when (1 bsl 16) =< Len, Len =< ?MAX_PAYLOAD_SIZE ->
|
||||||
|
<<127:7, Len:64>>.
|
||||||
Reference in New Issue
Block a user