%%%------------------------------------------------------------------- %%% @author anlicheng %%% @copyright (C) 2025, %%% @doc %%% %%% @end %%% Created : 03. 12月 2025 18:26 %%%------------------------------------------------------------------- -module(dns_resolver). -author("anlicheng"). -include_lib("dns_erlang/include/dns.hrl"). -behaviour(gen_server). %% API -export([start_link/1]). %% gen_server callbacks -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -export([forward/5]). -define(SERVER, ?MODULE). -record(state, { socket, idx :: integer(), dns_servers = [] }). %%%=================================================================== %%% API %%%=================================================================== forward(Pid, ReceiverPid, Ref, Request, QueryMsg) -> gen_server:cast(Pid, {forward, ReceiverPid, Ref, Request, QueryMsg}). %% @doc Spawns the server and registers the local name (unique) -spec(start_link(Args :: list()) -> {ok, Pid :: pid()} | ignore | {error, Reason :: term()}). start_link(Args) when is_list(Args) -> gen_server:start_link(?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, DnsServers} = application:get_env(sdlan, public_dns_servers), {ok, Sock} = gen_udp:open(0, [binary, {active, true}]), Idx = erlang:unique_integer([monotonic, positive]), {ok, #state{socket = Sock, idx = Idx, dns_servers = DnsServers}}. %% @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({forward, ReceiverPid, Ref, Request, #dns_message{id = TxId, questions = [#dns_query{name = QName, type = QType, class = QClass}|_]}}, State = #state{socket = Socket, idx = Idx, dns_servers = DnsServers}) -> lists:foreach(fun({DnsIp, DnsPort}) -> ok = gen_udp:send(Socket, DnsIp, DnsPort, Request), Key = {Idx, TxId, DnsIp, DnsPort, QName, QType, QClass}, logger:debug("[dns_resolver] key: ~p, send to: ~p, packet: ~p", [Key, {DnsIp, DnsPort}, Request]), dns_pending_wheel:insert(Key, {Ref, ReceiverPid}) end, DnsServers), {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({udp, Socket, TargetIp, TargetPort, Resp}, State = #state{socket = Socket, idx = Idx}) -> try dns:decode_message(Resp) of #dns_message{id = TxId, questions = [#dns_query{name = QName, type = QType, class = QClass}|_]} -> Key = {Idx, TxId, TargetIp, TargetPort, QName, QType, QClass}, Records = dns_pending_wheel:lookup(Key), dns_pending_wheel:delete(Key), resolver_reply(Records, Resp); _ -> ok catch error:_ -> ok end, {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 %%%=================================================================== -spec resolver_reply(list(), Resp :: binary()) -> no_return(). resolver_reply(Records, Resp) when is_binary(Resp) -> lists:foreach(fun({_, {Ref, ReceiverPid}}) -> case is_process_alive(ReceiverPid) of true -> ReceiverPid ! {dns_resolver_reply, Ref, Resp}; false -> ok end end, Records).