fix stun server

This commit is contained in:
anlicheng 2026-02-11 17:00:15 +08:00
parent e7af8a6019
commit 2e7e84193c
7 changed files with 354 additions and 46 deletions

View File

@ -23,8 +23,7 @@
-define(SERVER, ?MODULE). -define(SERVER, ?MODULE).
-record(state, { -record(state, {
socket, socket
stun_assist
}). }).
%%%=================================================================== %%%===================================================================
@ -52,18 +51,20 @@ start_link(Name, Port) when is_atom(Name), is_integer(Port) ->
{stop, Reason :: term()} | ignore). {stop, Reason :: term()} | ignore).
init([Port]) -> init([Port]) ->
%% %%
erlang:process_flag(priority, max), erlang:process_flag(priority, high),
Opts = [
{ok, Socket} = gen_udp:open(Port, [binary, {active, true}, {recbuf, 5 * 1024 * 1024}, {sndbuf, 5 * 1024 * 1024}]), binary,
{reuseaddr, true},
{reuseport, true},
{active, true},
{recbuf, 5 * 1024 * 1024},
{sndbuf, 5 * 1024 * 1024}
],
{ok, Socket} = gen_udp:open(Port, Opts),
inet_udp:controlling_process(Socket, self()), inet_udp:controlling_process(Socket, self()),
logger:debug("[sdlan_stun] start at port: ~p", [Port]),
case application:get_env(sdlan, stun_assist) of logger:debug("[sdlan_stun] start at port: ~p", [Port]),
undefined -> {ok, #state{socket = Socket}}.
{ok, #state{socket = Socket, stun_assist = undefined}};
{ok, StunAssist} ->
{ok, #state{socket = Socket, stun_assist = StunAssist}}
end.
%% @private %% @private
%% @doc Handling call messages %% @doc Handling call messages
@ -117,29 +118,25 @@ handle_info({udp, Sock, Ip, Port, <<?PACKET_STUN_REQUEST:8, Body/binary>>}, Stat
%% nat类型的探测机制, %% nat类型的探测机制,
%% assist的配置attr = 2 %% 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, ClientIp, ClientPort, <<?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), #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]), logger:debug("[sdlan_stun] get stun_probe request, att: ~p", [Attr]),
ProbeReply = sdlan_pb:encode_msg(#sdl_stun_probe_reply { ProbeReplyPkt = sdlan_pb:encode_msg(#sdl_stun_probe_reply {
cookie = Cookie, cookie = Cookie,
port = Port, port = ClientPort,
ip = int_ip(Ip) ip = int_ip(ClientIp)
}), }),
Packet = <<?PACKET_STUN_PROBE_REPLY, ProbeReply/binary>>,
case Attr of case Attr of
?STUN_ATTR_CHANGE_NONE -> ?STUN_ATTR_CHANGE_NONE ->
ok = gen_udp:send(Sock, Ip, Port, Packet); ok = gen_udp:send(Sock, ClientIp, ClientPort, <<?PACKET_STUN_PROBE_REPLY, ProbeReplyPkt/binary>>);
?STUN_ATTR_CHANGE_PORT -> ?STUN_ATTR_CHANGE_PORT ->
gen_server:cast('sdlan_stun:1:2', {stun_relay, Ip, Port, Packet}); %% ip
sdlan_stun_peer_assist:stun_relay(ClientIp, ClientPort, ProbeReplyPkt);
?STUN_ATTR_CHANGE_PEER -> ?STUN_ATTR_CHANGE_PEER ->
case StunAssist of %%
{AssistIp, AssistPort} -> sdlan_stun_port_assist:stun_relay(ClientIp, ClientPort, ProbeReplyPkt)
gen_udp:send(Sock, AssistIp, AssistPort, <<?PACKET_STUN_PROBE_RELAY, Ip0, Ip1, Ip2, Ip3, Port:16, Packet/binary>>);
undefined ->
ok
end
end, end,
{noreply, State}; {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

@ -0,0 +1,65 @@
%%%-------------------------------------------------------------------
%% @doc sdlan top level supervisor.
%% @end
%%%-------------------------------------------------------------------
-module(sdlan_stun_sup).
-behaviour(supervisor).
-export([start_link/0]).
-export([init/1]).
-define(SERVER, ?MODULE).
start_link() ->
supervisor:start_link({local, ?SERVER}, ?MODULE, []).
%% sup_flags() = #{strategy => strategy(), % optional
%% intensity => non_neg_integer(), % optional
%% period => pos_integer()} % optional
%% child_spec() = #{id => child_id(), % mandatory
%% start => mfargs(), % mandatory
%% restart => restart(), % optional
%% shutdown => shutdown(), % optional
%% type => worker(), % optional
%% modules => modules()} % optional
init([]) ->
SupFlags = #{strategy => one_for_one, intensity => 1000, period => 3600},
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']
}
],
{ok, {SupFlags, Specs ++ stun_acceptors()}}.
stun_acceptors() ->
{ok, StunServers} = application:get_env(sdlan, stun_servers),
Port = proplists:get_value(port, StunServers),
AcceptorNums = proplists:get_value(acceptor_nums, StunServers),
lists:map(fun(Id) ->
Name = sdlan_stun:get_name(Id),
#{
id => Name,
start => {sdlan_stun, start_link, [Name, Port]},
restart => permanent,
shutdown => 2000,
type => worker,
modules => ['sdlan_stun']
}
end, lists:seq(1, AcceptorNums)).

View File

@ -52,10 +52,19 @@ init([]) ->
shutdown => 2000, shutdown => 2000,
type => supervisor, type => supervisor,
modules => ['sdlan_network_sup'] modules => ['sdlan_network_sup']
},
#{
id => sdlan_stun_sup,
start => {sdlan_stun_sup, start_link, []},
restart => permanent,
shutdown => 2000,
type => supervisor,
modules => ['sdlan_stun_sup']
} }
], ],
{ok, {SupFlags, pools() ++ Specs ++ stun_specs()}}. {ok, {SupFlags, pools() ++ Specs}}.
%% internal functions %% internal functions
@ -63,17 +72,4 @@ pools() ->
{ok, Pools} = application:get_env(sdlan, pools), {ok, Pools} = application:get_env(sdlan, pools),
lists:map(fun({Name, PoolArgs, WorkerArgs}) -> lists:map(fun({Name, PoolArgs, WorkerArgs}) ->
poolboy:child_spec(Name, [{name, {local, Name}}|PoolArgs], WorkerArgs) poolboy:child_spec(Name, [{name, {local, Name}}|PoolArgs], WorkerArgs)
end, Pools). end, Pools).
stun_specs() ->
{ok, StunServers} = application:get_env(sdlan, stun_servers),
lists:map(fun({Name, Port}) ->
#{
id => Name,
start => {sdlan_stun, start_link, [Name, Port]},
restart => permanent,
shutdown => 2000,
type => worker,
modules => ['sdlan_stun']
}
end, StunServers).

View File

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

View File

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