iot_cloud/src/transport/tcp/ssl_channel.erl
2026-04-27 11:14:58 +08:00

294 lines
13 KiB
Erlang

%%%-------------------------------------------------------------------
%%% @author licheng5
%%% @copyright (C) 2021, <COMPANY>
%%% @doc
%%%
%%% @end
%%% Created : 11. 1月 2021 上午12:17
%%%-------------------------------------------------------------------
-module(ssl_channel).
-author("licheng5").
-behaviour(ranch_protocol).
-define(INFLIGHT_TIMEOUT, 60000).
%% API
-export([pub/4, container_call/3, cancel_request_call/2, command/2, activate/2]).
-export([start_link/3, stop/2]).
%% gen_server callbacks
-export([init/3, handle_call/3, handle_cast/2, handle_info/2, code_change/3, terminate/2]).
-record(state, {
transport,
socket,
uuid :: undefined | binary(),
%% 用户进程id
host_pid = undefined,
%% 请求响应的对应关系
inflight = #{}
}).
-record(inflight_request, {
receiver_pid :: pid(),
timer_ref :: reference()
}).
%% 向通道中写入消息
-spec pub(Pid :: pid(), Topic :: binary(), Qos :: integer(), Content :: binary()) -> no_return().
pub(Pid, Topic, Qos, Content) when is_pid(Pid), is_binary(Topic), is_integer(Qos), is_binary(Content) ->
gen_server:cast(Pid, {pub, Topic, Qos, Content}).
%% 向通道中写入消息
-spec command(Pid :: pid(), Command :: activate | deactivate) -> no_return().
command(Pid, Command) when is_pid(Pid), (Command =:= activate orelse Command =:= deactivate) ->
gen_server:cast(Pid, {command, Command}).
-spec activate(Pid :: pid(), Auth :: boolean()) -> no_return().
activate(Pid, Auth) when is_pid(Pid), is_boolean(Auth) ->
Command = case Auth of true -> activate; false -> deactivate end,
gen_server:cast(Pid, {command, Command}).
-spec container_call(Pid :: pid(), ReceiverPid :: pid(), Request :: map()) -> Ref :: reference().
container_call(Pid, ReceiverPid, Request) when is_pid(Pid), is_pid(ReceiverPid), is_map(Request) ->
Ref = make_ref(),
gen_server:cast(Pid, {request_call, ReceiverPid, Ref, {container_request, Request}}),
Ref.
-spec cancel_request_call(Pid :: pid(), Ref :: reference()) -> ok.
cancel_request_call(Pid, Ref) when is_pid(Pid), is_reference(Ref) ->
gen_server:call(Pid, {cancel_request_call, Ref}).
%% 关闭方法
-spec stop(Pid :: pid(), Reason :: any()) -> no_return().
stop(undefined, _Reason) ->
ok;
stop(Pid, Reason) when is_pid(Pid) ->
gen_server:stop(Pid, Reason, 5000).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% 逻辑处理方法
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
start_link(Ref, Transport, Opts) ->
{ok, proc_lib:spawn_link(?MODULE, init, [Ref, Transport, Opts])}.
init(Ref, Transport, _Opts = []) ->
ok = iot_log:set_metadata(),
{ok, Socket} = ranch:handshake(Ref),
logger:debug("[ssl_channel] get a new connection: ~p", [Socket]),
Transport:setopts(Socket, [binary, {active, true}, {packet, 4}]),
% erlang:start_timer(?PING_TICKER, self(), ping_ticker),
gen_server:enter_loop(?MODULE, [], #state{transport = Transport, socket = Socket}).
handle_call({cancel_request_call, Ref}, _From, State = #state{inflight = Inflight}) ->
case maps:take(Ref, Inflight) of
{#inflight_request{timer_ref = TimerRef}, NInflight} ->
erlang:cancel_timer(TimerRef),
{reply, ok, State#state{inflight = NInflight}};
error ->
{reply, ok, State}
end;
handle_call(_Request, _From, State) ->
{reply, ok, State}.
%% 发送消息, 基于pub/sub机制
handle_cast({pub, Topic, Qos, Content}, State = #state{transport = Transport, socket = Socket}) ->
Packet = term_to_binary({message, {pub, #{topic => Topic, qos => Qos, content => Content}}}),
Transport:send(Socket, Packet),
{noreply, State};
%% 发送Command消息
handle_cast({command, Command}, State = #state{transport = Transport, socket = Socket}) ->
Packet = term_to_binary({message, {auth_control, Command}}),
Transport:send(Socket, Packet),
{noreply, State};
%% 推送需要响应的请求
handle_cast({request_call, ReceiverPid, Ref, Body}, State = #state{transport = Transport, socket = Socket, inflight = Inflight}) ->
Packet = term_to_binary({request, Ref, Body}),
TimerRef = erlang:start_timer(?INFLIGHT_TIMEOUT, self(), {request_timeout, Ref}),
Transport:send(Socket, Packet),
RequestInfo = #inflight_request{receiver_pid = ReceiverPid, timer_ref = TimerRef},
{noreply, State#state{inflight = maps:put(Ref, RequestInfo, Inflight)}}.
handle_info({timeout, TimerRef, {request_timeout, Ref}}, State = #state{inflight = Inflight}) ->
case maps:get(Ref, Inflight, undefined) of
#inflight_request{timer_ref = TimerRef} ->
logger:warning("[ws_channel] request timeout, ref: ~p", [Ref]),
{noreply, State#state{inflight = maps:remove(Ref, Inflight)}};
_ ->
{noreply, State}
end;
%% 关闭当前通道
handle_info({stop, Reason}, State) ->
{stop, Reason, State};
%% 主机进程挂掉的时候,需要关闭掉链接
handle_info({'DOWN', _, process, HostPid, Reason}, State = #state{uuid = UUID, host_pid = HostPid}) ->
logger:debug("[ws_channel] uuid: ~p, channel will close because host exited with reason: ~p", [UUID, Reason]),
{stop, Reason, State};
handle_info({ssl, Socket, PacketBin}, State = #state{transport = Transport, socket = Socket, host_pid = HostPid, inflight = Inflight})
when is_binary(PacketBin) ->
case catch binary_to_term(PacketBin, [safe]) of
{request, Ref, Body} ->
handle_request_frame(Ref, Body, Transport, Socket, State);
{message, Body} ->
handle_message_frame(Body, HostPid, State);
{response, Ref, Response} ->
handle_response_frame(Ref, Response, Inflight, State);
{'EXIT', Reason} ->
logger:warning("[ssl_channel] invalid packet: ~p", [Reason]),
{stop, bad_packet, State};
Other ->
logger:warning("[ssl_channel] unsupported packet: ~p", [Other]),
{stop, bad_packet, State}
end;
handle_info({ssl_closed, Socket}, State = #state{socket = Socket}) ->
logger:notice("[ssl_channel] ssl socket closed"),
{stop, normal, State};
handle_info({ssl_error, Socket, Reason}, State = #state{socket = Socket}) ->
logger:notice("[ssl_channel] ssl socket error: ~p", [Reason]),
{stop, normal, State};
handle_info({ssl_passive, Socket}, State = #state{transport = Transport, socket = Socket}) ->
ok = Transport:setopts(Socket, [{active, true}]),
{noreply, State};
handle_info(Info, State) ->
logger:warning("[ssl_channel] get a unknown message: ~p, state: ~p", [Info, State]),
{noreply, State}.
terminate(Reason, #state{}) ->
logger:warning("[ssl_channel] stop with reason: ~p", [Reason]),
ok.
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%% helper methods
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-spec handle_request_frame(reference(), tuple(), module(), any(), #state{}) -> {noreply, #state{}} | {stop, term(), #state{}}.
handle_request_frame(Ref,
{auth_request, #{uuid := UUID, token := Token, timestamp := Timestamp}},
Transport, Socket, State) ->
logger:debug("[ws_channel] auth uuid: ~p", [UUID]),
case auth(Token, UUID, Timestamp) of
ok ->
case iot_api_client:get_host_by_uuid(UUID) of
undefined ->
logger:warning("[ws_channel] uuid: ~p, token: ~p, host not found", [UUID, Token]),
{stop, normal, State};
{ok, _} ->
%% 尝试启动主机的服务进程
{ok, HostPid} = iot_host_sup:ensured_host_started(UUID),
case iot_host:attach_channel(HostPid, self()) of
ok ->
erlang:monitor(process, HostPid),
send_reply_frame(Transport, Socket, Ref, {auth_response, {ok, <<"ok">>}}),
{noreply, State#state{uuid = UUID, host_pid = HostPid}};
{denied, Reason} when is_binary(Reason) ->
erlang:monitor(process, HostPid),
send_reply_frame(Transport, Socket, Ref, {auth_response, {error, {denied, Reason}}}),
logger:debug("[ws_channel] uuid: ~p, attach channel get error: ~p, stop channel", [UUID, Reason]),
{noreply, State#state{uuid = UUID, host_pid = HostPid}};
{error, Reason} when is_binary(Reason) ->
send_reply_frame(Transport, Socket, Ref, {auth_response, {error, {failed, Reason}}}),
logger:debug("[ws_channel] uuid: ~p, attach channel get error: ~p, stop channel", [UUID, Reason]),
{stop, Reason, State}
end
end;
{error, Reason} ->
send_reply_frame(Transport, Socket, Ref, {auth_response, {error, {failed, Reason}}}),
logger:warning("[ws_channel] uuid: ~p, token: ~p, auth failed, reason: ~p", [UUID, Token, Reason]),
{stop, Reason, State}
end;
handle_request_frame(Ref, {container_request, ContainerRequest}, _Transport, _Socket, State) ->
logger:warning("[ws_channel] unsupported request message type: container_request, ref: ~p, request: ~p", [Ref, ContainerRequest]),
{stop, normal, State};
handle_request_frame(Ref, Body, _Transport, _Socket, State) ->
logger:warning("[ws_channel] unsupported request body, ref: ~p, body: ~p", [Ref, Body]),
{stop, normal, State}.
-spec handle_message_frame(tuple(), undefined | pid(), #state{}) ->
{noreply, #state{}}.
handle_message_frame({data, #{route_key := RouteKey, metric := Metric}}, HostPid, State) when is_pid(HostPid) ->
iot_host:handle(HostPid, {data, RouteKey, Metric}),
{noreply, State};
handle_message_frame({task_event, Event}, HostPid, State) when is_pid(HostPid) ->
handle_event_stream_frame(Event),
{noreply, State};
handle_message_frame(Body, _HostPid, State) ->
logger:warning("[ssl_channel] unsupported message body: ~p", [Body]),
{noreply, State}.
-spec handle_event_stream_frame(map()) -> any().
handle_event_stream_frame(#{task_id := TaskId, type := <<"close">>, stream := Reason}) ->
iot_event_stream_observer:stream_close(TaskId, Reason);
handle_event_stream_frame(#{task_id := TaskId, type := Type, stream := Stream}) ->
logger:debug("[ssl_channel] get task_id: ~p, type: ~ts, stream: ~ts", [TaskId, Type, Stream]),
iot_event_stream_observer:stream_data(TaskId, Type, Stream).
-spec handle_response_frame(reference(), tuple(), map(), #state{}) ->
{noreply, #state{}}.
handle_response_frame(Ref, Reply, Inflight, State) when is_reference(Ref) ->
case maps:take(Ref, Inflight) of
error ->
{noreply, State};
{#inflight_request{receiver_pid = ReceiverPid, timer_ref = TimerRef}, NInflight} ->
erlang:cancel_timer(TimerRef),
case is_pid(ReceiverPid) andalso is_process_alive(ReceiverPid) of
true ->
ReceiverPid ! {request_reply, Ref, decode_reply(Reply)};
false ->
logger:warning("[ws_channel] get reply message: ~p, ref: ~p, but receiver_pid is deaded", [Reply, Ref])
end,
{noreply, State#state{inflight = NInflight}}
end;
handle_response_frame(Ref, Reply, _Inflight, State) ->
logger:warning("[ws_channel] unexpected response frame, ref: ~p, reply: ~p", [Ref, Reply]),
{noreply, State}.
-spec send_reply_frame(module(), any(), reference(), tuple()) -> any().
send_reply_frame(Transport, Socket, Ref, Reply) ->
Packet = term_to_binary({response, Ref, Reply}),
Transport:send(Socket, Packet).
-spec decode_reply({container_response, {ok, term()} | {error, term()}} | tuple()) ->
{ok, term()} | {error, term()}.
decode_reply({container_response, {ok, Result}}) ->
{ok, Result};
decode_reply({container_response, {error, Reason}}) ->
{error, Reason};
decode_reply(_Reply) ->
{error, invalid_response}.
%% 检测token是否是合法值
-spec auth(Token :: binary(), UUID :: binary(), Timestamp :: integer()) ->
ok | {error, Reason :: binary()}.
auth(Token, UUID, Timestamp) when is_binary(Token), is_binary(UUID), is_integer(Timestamp) ->
%% 1分钟内有效
Now = iot_util:current_time(),
case Timestamp =< Now andalso Now - Timestamp =< 60 of
true ->
case efka_client_store:auth(UUID, Token) of
true ->
ok;
false ->
{error, <<"invalid token">>}
end;
false ->
{error, <<"invalid timestamp">>}
end.