From 2e7e84193c6ece68a7c25b8bab96ec6a2db97605 Mon Sep 17 00:00:00 2001 From: anlicheng <244108715@qq.com> Date: Wed, 11 Feb 2026 17:00:15 +0800 Subject: [PATCH] fix stun server --- apps/sdlan/src/sdlan_stun.erl | 47 ++++----- apps/sdlan/src/sdlan_stun_peer_assist.erl | 117 ++++++++++++++++++++++ apps/sdlan/src/sdlan_stun_port_assist.erl | 113 +++++++++++++++++++++ apps/sdlan/src/sdlan_stun_sup.erl | 65 ++++++++++++ apps/sdlan/src/sdlan_sup.erl | 26 ++--- config/sys-dev.config | 16 ++- config/sys-prod.config | 16 ++- 7 files changed, 354 insertions(+), 46 deletions(-) create mode 100644 apps/sdlan/src/sdlan_stun_peer_assist.erl create mode 100644 apps/sdlan/src/sdlan_stun_port_assist.erl create mode 100644 apps/sdlan/src/sdlan_stun_sup.erl diff --git a/apps/sdlan/src/sdlan_stun.erl b/apps/sdlan/src/sdlan_stun.erl index 08ac1a4..66e1449 100644 --- a/apps/sdlan/src/sdlan_stun.erl +++ b/apps/sdlan/src/sdlan_stun.erl @@ -23,8 +23,7 @@ -define(SERVER, ?MODULE). -record(state, { - socket, - stun_assist + socket }). %%%=================================================================== @@ -52,18 +51,20 @@ start_link(Name, Port) when is_atom(Name), is_integer(Port) -> {stop, Reason :: term()} | ignore). init([Port]) -> %% 需要提高进程的调度优先级 - erlang:process_flag(priority, max), - - {ok, Socket} = gen_udp:open(Port, [binary, {active, true}, {recbuf, 5 * 1024 * 1024}, {sndbuf, 5 * 1024 * 1024}]), + erlang:process_flag(priority, high), + Opts = [ + 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()), - 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. + logger:debug("[sdlan_stun] start at port: ~p", [Port]), + {ok, #state{socket = Socket}}. %% @private %% @doc Handling call messages @@ -117,29 +118,25 @@ handle_info({udp, Sock, Ip, Port, <>}, Stat %% 网络nat类型的探测机制, 需要借助其他服务一起才能实现 %% 辅助节点没有assist的配置,不支持attr = 2的探测 -handle_info({udp, Sock, Ip = {Ip0, Ip1, Ip2, Ip3}, Port, <>}, State = #state{socket = Sock, stun_assist = StunAssist}) -> +handle_info({udp, Sock, ClientIp, ClientPort, <>}, 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]), - ProbeReply = sdlan_pb:encode_msg(#sdl_stun_probe_reply { + ProbeReplyPkt = sdlan_pb:encode_msg(#sdl_stun_probe_reply { cookie = Cookie, - port = Port, - ip = int_ip(Ip) + port = ClientPort, + ip = int_ip(ClientIp) }), - Packet = <>, case Attr of ?STUN_ATTR_CHANGE_NONE -> - ok = gen_udp:send(Sock, Ip, Port, Packet); + ok = gen_udp:send(Sock, ClientIp, ClientPort, <>); ?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 -> - case StunAssist of - {AssistIp, AssistPort} -> - gen_udp:send(Sock, AssistIp, AssistPort, <>); - undefined -> - ok - end + %% 切换端口返回 + sdlan_stun_port_assist:stun_relay(ClientIp, ClientPort, ProbeReplyPkt) end, {noreply, State}; diff --git a/apps/sdlan/src/sdlan_stun_peer_assist.erl b/apps/sdlan/src/sdlan_stun_peer_assist.erl new file mode 100644 index 0000000..d7f8327 --- /dev/null +++ b/apps/sdlan/src/sdlan_stun_peer_assist.erl @@ -0,0 +1,117 @@ +%%%------------------------------------------------------------------- +%%% @author anlicheng +%%% @copyright (C) 2026, +%%% @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 = <>, + 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 +%%%=================================================================== diff --git a/apps/sdlan/src/sdlan_stun_port_assist.erl b/apps/sdlan/src/sdlan_stun_port_assist.erl new file mode 100644 index 0000000..f31921c --- /dev/null +++ b/apps/sdlan/src/sdlan_stun_port_assist.erl @@ -0,0 +1,113 @@ +%%%------------------------------------------------------------------- +%%% @author anlicheng +%%% @copyright (C) 2026, +%%% @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 +%%%=================================================================== diff --git a/apps/sdlan/src/sdlan_stun_sup.erl b/apps/sdlan/src/sdlan_stun_sup.erl new file mode 100644 index 0000000..06ceae7 --- /dev/null +++ b/apps/sdlan/src/sdlan_stun_sup.erl @@ -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)). \ No newline at end of file diff --git a/apps/sdlan/src/sdlan_sup.erl b/apps/sdlan/src/sdlan_sup.erl index 1361b3e..8c4b3b9 100644 --- a/apps/sdlan/src/sdlan_sup.erl +++ b/apps/sdlan/src/sdlan_sup.erl @@ -52,10 +52,19 @@ init([]) -> shutdown => 2000, type => supervisor, 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 @@ -63,17 +72,4 @@ pools() -> {ok, Pools} = application:get_env(sdlan, pools), lists:map(fun({Name, PoolArgs, WorkerArgs}) -> poolboy:child_spec(Name, [{name, {local, Name}}|PoolArgs], WorkerArgs) - 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). \ No newline at end of file + end, Pools). \ No newline at end of file diff --git a/config/sys-dev.config b/config/sys-dev.config index b4635b4..9c78729 100644 --- a/config/sys-dev.config +++ b/config/sys-dev.config @@ -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, [ diff --git a/config/sys-prod.config b/config/sys-prod.config index 86a66ce..79182d0 100644 --- a/config/sys-prod.config +++ b/config/sys-prod.config @@ -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, 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域名解析服务 {public_dns_servers, [