简化stun的逻辑

This commit is contained in:
anlicheng 2026-01-22 16:27:08 +08:00
parent ab74389f07
commit ce69bfd730
6 changed files with 272 additions and 31 deletions

View File

@ -25,8 +25,7 @@
-define(SERVER, ?MODULE).
-record(state, {
socket,
stun_assist
socket :: inet:socket()
}).
%%%===================================================================
@ -54,8 +53,7 @@ start_link(Name, Port) when is_atom(Name), is_integer(Port) ->
{stop, Reason :: term()} | ignore).
init([Port]) ->
%%
erlang:process_flag(priority, max),
erlang:process_flag(priority, high),
Opts = [
binary,
{reuseaddr, true},
@ -69,12 +67,7 @@ init([Port]) ->
inet_udp:controlling_process(Socket, self()),
logger:debug("[sdlan_stun] start at port: ~p", [Port]),
case application:get_env(sdlan, stun_assist) of
undefined ->
{ok, #state{socket = Socket, stun_assist = undefined}};
{ok, StunAssist} ->
{ok, #state{socket = Socket, stun_assist = StunAssist}}
end.
{ok, #state{socket = Socket}}.
%% @private
%% @doc Handling call messages
@ -128,7 +121,7 @@ handle_info({udp, Sock, Ip, Port, <<?PACKET_STUN_REQUEST:8, Body/binary>>}, Stat
%% nat类型的探测机制,
%% assist的配置attr = 2
handle_info({udp, Sock, Ip = {Ip0, Ip1, Ip2, Ip3}, Port, <<?PACKET_STUN_PROBE:8, Body/binary>>}, State = #state{socket = Sock, stun_assist = StunAssist}) ->
handle_info({udp, Sock, Ip, Port, <<?PACKET_STUN_PROBE:8, Body/binary>>}, State = #state{socket = Sock}) ->
#sdl_stun_probe{cookie = Cookie, attr = Attr} = sdlan_pb:decode_msg(Body, sdl_stun_probe),
logger:debug("[sdlan_stun] get stun_probe request, att: ~p", [Attr]),
@ -143,14 +136,9 @@ handle_info({udp, Sock, Ip = {Ip0, Ip1, Ip2, Ip3}, Port, <<?PACKET_STUN_PROBE:8,
?STUN_ATTR_CHANGE_NONE ->
ok = gen_udp:send(Sock, Ip, Port, Packet);
?STUN_ATTR_CHANGE_PORT ->
gen_server:cast('sdlan_stun:1:2', {stun_relay, Ip, Port, Packet});
sdlan_stun_port_assist:stun_relay(Ip, Port, Packet);
?STUN_ATTR_CHANGE_PEER ->
case StunAssist of
{AssistIp, AssistPort} ->
gen_udp:send(Sock, AssistIp, AssistPort, <<?PACKET_STUN_PROBE_RELAY, Ip0, Ip1, Ip2, Ip3, Port:16, Packet/binary>>);
undefined ->
ok
end
sdlan_stun_peer_assist:stun_relay(Ip, Port, Packet)
end,
{noreply, State};

View File

@ -0,0 +1,117 @@
%%%-------------------------------------------------------------------
%%% @author anlicheng
%%% @copyright (C) 2026, <COMPANY>
%%% @doc
%%%
%%% @end
%%% Created : 22. 1 2026 16:01
%%%-------------------------------------------------------------------
-module(sdlan_stun_peer_assist).
-author("anlicheng").
-behaviour(gen_server).
%% API
-export([start_link/0]).
-export([stun_relay/3]).
%% gen_server callbacks
-export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]).
-define(SERVER, ?MODULE).
-record(state, {
socket :: inet:socket(),
assist_ip :: inet:ip4_address(),
assist_port :: integer()
}).
%%%===================================================================
%%% API
%%%===================================================================
-spec stun_relay(Ip :: inet:ip_address(), Port :: integer(), Reply :: binary()) -> no_return().
stun_relay(Ip, Port, Reply) when is_integer(Port), is_binary(Reply) ->
gen_server:cast(?SERVER, {stun_relay, Ip, Port, Reply}).
%% @doc Spawns the server and registers the local name (unique)
-spec(start_link() ->
{ok, Pid :: pid()} | ignore | {error, Reason :: term()}).
start_link() ->
gen_server:start_link({local, ?SERVER}, ?MODULE, [], []).
%%%===================================================================
%%% gen_server callbacks
%%%===================================================================
%% @private
%% @doc Initializes the server
-spec(init(Args :: term()) ->
{ok, State :: #state{}} | {ok, State :: #state{}, timeout() | hibernate} |
{stop, Reason :: term()} | ignore).
init([]) ->
{ok, Props} = application:get_env(sdlan, stun_peer_assist),
AssistIp = proplists:get_value(ip, Props),
AssistPort = proplists:get_value(port, Props),
Opts = [binary, {reuseaddr, true}],
{ok, Socket} = gen_udp:open(0, Opts),
inet_udp:controlling_process(Socket, self()),
logger:debug("[sdlan_stun_peer_assist] started"),
{ok, #state{socket = Socket, assist_ip = AssistIp, assist_port = AssistPort}}.
%% @private
%% @doc Handling call messages
-spec(handle_call(Request :: term(), From :: {pid(), Tag :: term()},
State :: #state{}) ->
{reply, Reply :: term(), NewState :: #state{}} |
{reply, Reply :: term(), NewState :: #state{}, timeout() | hibernate} |
{noreply, NewState :: #state{}} |
{noreply, NewState :: #state{}, timeout() | hibernate} |
{stop, Reason :: term(), Reply :: term(), NewState :: #state{}} |
{stop, Reason :: term(), NewState :: #state{}}).
handle_call(_Request, _From, State = #state{}) ->
{reply, ok, State}.
%% @private
%% @doc Handling cast messages
-spec(handle_cast(Request :: term(), State :: #state{}) ->
{noreply, NewState :: #state{}} |
{noreply, NewState :: #state{}, timeout() | hibernate} |
{stop, Reason :: term(), NewState :: #state{}}).
handle_cast({stun_relay, _Ip = {Ip0, Ip1, Ip2, Ip3}, Port, Reply}, State = #state{socket = Sock, assist_ip = AssistIp, assist_port = AssistPort}) ->
Packet = <<Ip0, Ip1, Ip2, Ip3, Port:16, Reply/binary>>,
ok = gen_udp:send(Sock, AssistIp, AssistPort, Packet),
{noreply, State}.
%% @private
%% @doc Handling all non call/cast messages
-spec(handle_info(Info :: timeout() | term(), State :: #state{}) ->
{noreply, NewState :: #state{}} |
{noreply, NewState :: #state{}, timeout() | hibernate} |
{stop, Reason :: term(), NewState :: #state{}}).
handle_info(_Info, State = #state{}) ->
{noreply, State}.
%% @private
%% @doc This function is called by a gen_server when it is about to
%% terminate. It should be the opposite of Module:init/1 and do any
%% necessary cleaning up. When it returns, the gen_server terminates
%% with Reason. The return value is ignored.
-spec(terminate(Reason :: (normal | shutdown | {shutdown, term()} | term()),
State :: #state{}) -> term()).
terminate(_Reason, _State = #state{}) ->
ok.
%% @private
%% @doc Convert process state when code is changed
-spec(code_change(OldVsn :: term() | {down, term()}, State :: #state{},
Extra :: term()) ->
{ok, NewState :: #state{}} | {error, Reason :: term()}).
code_change(_OldVsn, State = #state{}, _Extra) ->
{ok, State}.
%%%===================================================================
%%% Internal functions
%%%===================================================================

View File

@ -0,0 +1,113 @@
%%%-------------------------------------------------------------------
%%% @author anlicheng
%%% @copyright (C) 2026, <COMPANY>
%%% @doc
%%%
%%% @end
%%% Created : 22. 1 2026 16:01
%%%-------------------------------------------------------------------
-module(sdlan_stun_port_assist).
-author("anlicheng").
-behaviour(gen_server).
%% API
-export([start_link/0]).
-export([stun_relay/3]).
%% gen_server callbacks
-export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]).
-define(SERVER, ?MODULE).
-record(state, {
socket :: inet:socket()
}).
%%%===================================================================
%%% API
%%%===================================================================
-spec stun_relay(Ip :: inet:ip_address(), Port :: integer(), Reply :: binary()) -> no_return().
stun_relay(Ip, Port, Reply) when is_integer(Port), is_binary(Reply) ->
gen_server:cast(?SERVER, {stun_relay, Ip, Port, Reply}).
%% @doc Spawns the server and registers the local name (unique)
-spec(start_link() ->
{ok, Pid :: pid()} | ignore | {error, Reason :: term()}).
start_link() ->
gen_server:start_link({local, ?SERVER}, ?MODULE, [], []).
%%%===================================================================
%%% gen_server callbacks
%%%===================================================================
%% @private
%% @doc Initializes the server
-spec(init(Args :: term()) ->
{ok, State :: #state{}} | {ok, State :: #state{}, timeout() | hibernate} |
{stop, Reason :: term()} | ignore).
init([]) ->
{ok, Props} = application:get_env(sdlan, stun_port_assist),
Port = proplists:get_value(port, Props),
Opts = [binary, {reuseaddr, true}],
{ok, Socket} = gen_udp:open(Port, Opts),
inet_udp:controlling_process(Socket, self()),
logger:debug("[sdlan_stun_port_assist] start at port: ~p", [Port]),
{ok, #state{socket = Socket}}.
%% @private
%% @doc Handling call messages
-spec(handle_call(Request :: term(), From :: {pid(), Tag :: term()},
State :: #state{}) ->
{reply, Reply :: term(), NewState :: #state{}} |
{reply, Reply :: term(), NewState :: #state{}, timeout() | hibernate} |
{noreply, NewState :: #state{}} |
{noreply, NewState :: #state{}, timeout() | hibernate} |
{stop, Reason :: term(), Reply :: term(), NewState :: #state{}} |
{stop, Reason :: term(), NewState :: #state{}}).
handle_call(_Request, _From, State = #state{}) ->
{reply, ok, State}.
%% @private
%% @doc Handling cast messages
-spec(handle_cast(Request :: term(), State :: #state{}) ->
{noreply, NewState :: #state{}} |
{noreply, NewState :: #state{}, timeout() | hibernate} |
{stop, Reason :: term(), NewState :: #state{}}).
handle_cast({stun_relay, Ip, Port, Reply}, State = #state{socket = Sock}) ->
ok = gen_udp:send(Sock, Ip, Port, Reply),
{noreply, State}.
%% @private
%% @doc Handling all non call/cast messages
-spec(handle_info(Info :: timeout() | term(), State :: #state{}) ->
{noreply, NewState :: #state{}} |
{noreply, NewState :: #state{}, timeout() | hibernate} |
{stop, Reason :: term(), NewState :: #state{}}).
handle_info(_Info, State = #state{}) ->
{noreply, State}.
%% @private
%% @doc This function is called by a gen_server when it is about to
%% terminate. It should be the opposite of Module:init/1 and do any
%% necessary cleaning up. When it returns, the gen_server terminates
%% with Reason. The return value is ignored.
-spec(terminate(Reason :: (normal | shutdown | {shutdown, term()} | term()),
State :: #state{}) -> term()).
terminate(_Reason, _State = #state{}) ->
ok.
%% @private
%% @doc Convert process state when code is changed
-spec(code_change(OldVsn :: term() | {down, term()}, State :: #state{},
Extra :: term()) ->
{ok, NewState :: #state{}} | {error, Reason :: term()}).
code_change(_OldVsn, State = #state{}, _Extra) ->
{ok, State}.
%%%===================================================================
%%% Internal functions
%%%===================================================================

View File

@ -31,7 +31,26 @@ init([]) ->
Port = proplists:get_value(port, StunServerProps),
AcceptorNums = proplists:get_value(acceptor_nums, StunServerProps),
Specs = lists:map(fun(Id) ->
Specs = [
#{
id => sdlan_stun_port_assist,
start => {sdlan_stun_port_assist, start_link, []},
restart => permanent,
shutdown => 2000,
type => worker,
modules => ['sdlan_stun_port_assist']
},
#{
id => sdlan_stun_peer_assist,
start => {sdlan_stun_peer_assist, start_link, []},
restart => permanent,
shutdown => 2000,
type => worker,
modules => ['sdlan_stun_peer_assist']
}
],
StunSpecs = lists:map(fun(Id) ->
Name = sdlan_stun:get_name(Id),
#{
id => Name,
@ -43,4 +62,4 @@ init([]) ->
}
end, lists:seq(1, AcceptorNums)),
{ok, {SupFlags, Specs}}.
{ok, {SupFlags, Specs ++ StunSpecs}}.

View File

@ -21,7 +21,7 @@
%% stun类型探测相当于有个类型
{stun_servers, [
{port, 1265},
{acceptor_nums, 50}
{acceptor_nums, 5}
]},
{stun_port_assist, [
@ -33,12 +33,6 @@
{port, 1266}
]},
%{stun_assist, {{47,98,178,3}, 1266}},
%{stun_servers, [{'sdlan_stun:1:1', 1265}, {'sdlan_stun:1:2', 1266}]},
%{stun_assist, {{47,98,178,3}, 1266}},
% {stun_servers, [{'sdlan_stun:2:1', 1265}, {'sdlan_stun:2:2', 1266}]},
%% 公共的dns域名解析服务
{public_dns_servers, [
{{114, 114, 114, 114}, 53},

View File

@ -18,10 +18,20 @@
%% 网络带宽, 单位为: kb
{band_width, 2048},
{stun_servers, [{'sdlan_stun:1:1', 1265}, {'sdlan_stun:1:2', 1266}]},
{stun_assist, {{47,98,178,3}, 1266}},
%% stun类型探测相当于有个类型
{stun_servers, [
{port, 1265},
{acceptor_nums, 5}
]},
% {stun_servers, [{'sdlan_stun:2:1', 1265}, {'sdlan_stun:2:2', 1266}]},
{stun_port_assist, [
{port, 1266}
]},
{stun_peer_assist, [
{ip, {47,98,178,3}},
{port, 1266}
]},
%% 公共的dns域名解析服务
{public_dns_servers, [