%%%---------------------------------------------------------------------- %%% File : ejabberd_s2s.erl %%% Author : Alexey Shchepin %%% Purpose : S2S connections manager %%% Created : 7 Dec 2002 by Alexey Shchepin %%% %%% %%% ejabberd, Copyright (C) 2002-2016 ProcessOne %%% %%% This program is free software; you can redistribute it and/or %%% modify it under the terms of the GNU General Public License as %%% published by the Free Software Foundation; either version 2 of the %%% License, or (at your option) any later version. %%% %%% This program is distributed in the hope that it will be useful, %%% but WITHOUT ANY WARRANTY; without even the implied warranty of %%% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU %%% General Public License for more details. %%% %%% You should have received a copy of the GNU General Public License along %%% with this program; if not, write to the Free Software Foundation, Inc., %%% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. %%% %%%---------------------------------------------------------------------- -module(ejabberd_s2s). -protocol({xep, 220, '1.1'}). -behaviour(ejabberd_config). -author('alexey@process-one.net'). -behaviour(gen_server). %% API -export([start_link/0, route/3, have_connection/1, make_key/2, get_connections_pids/1, try_register/1, remove_connection/2, find_connection/2, dirty_get_connections/0, allow_host/2, incoming_s2s_number/0, outgoing_s2s_number/0, clean_temporarily_blocked_table/0, list_temporarily_blocked_hosts/0, external_host_overloaded/1, is_temporarly_blocked/1, check_peer_certificate/3, get_commands_spec/0]). %% gen_server callbacks -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -export([get_info_s2s_connections/1, transform_options/1, opt_type/1]). -include("ejabberd.hrl"). -include("logger.hrl"). -include("jlib.hrl"). -include("ejabberd_commands.hrl"). -include_lib("public_key/include/public_key.hrl"). -define(PKIXEXPLICIT, 'OTP-PUB-KEY'). -define(PKIXIMPLICIT, 'OTP-PUB-KEY'). -include("XmppAddr.hrl"). -define(DEFAULT_MAX_S2S_CONNECTIONS_NUMBER, 1). -define(DEFAULT_MAX_S2S_CONNECTIONS_NUMBER_PER_NODE, 1). -define(S2S_OVERLOAD_BLOCK_PERIOD, 60). %% once a server is temporarly blocked, it stay blocked for 60 seconds -record(s2s, {fromto = {<<"">>, <<"">>} :: {binary(), binary()} | '_', pid = self() :: pid() | '_' | '$1'}). -record(state, {}). -record(temporarily_blocked, {host = <<"">> :: binary(), timestamp :: integer()}). -type temporarily_blocked() :: #temporarily_blocked{}. start_link() -> gen_server:start_link({local, ?MODULE}, ?MODULE, [], []). -spec route(jid(), jid(), xmlel()) -> ok. route(From, To, Packet) -> case catch do_route(From, To, Packet) of {'EXIT', Reason} -> ?ERROR_MSG("~p~nwhen processing: ~p", [Reason, {From, To, Packet}]); _ -> ok end. clean_temporarily_blocked_table() -> mnesia:clear_table(temporarily_blocked). -spec list_temporarily_blocked_hosts() -> [temporarily_blocked()]. list_temporarily_blocked_hosts() -> ets:tab2list(temporarily_blocked). -spec external_host_overloaded(binary()) -> {aborted, any()} | {atomic, ok}. external_host_overloaded(Host) -> ?INFO_MSG("Disabling connections from ~s for ~p " "seconds", [Host, ?S2S_OVERLOAD_BLOCK_PERIOD]), mnesia:transaction(fun () -> Time = p1_time_compat:monotonic_time(), mnesia:write(#temporarily_blocked{host = Host, timestamp = Time}) end). -spec is_temporarly_blocked(binary()) -> boolean(). is_temporarly_blocked(Host) -> case mnesia:dirty_read(temporarily_blocked, Host) of [] -> false; [#temporarily_blocked{timestamp = T} = Entry] -> Diff = p1_time_compat:monotonic_time() - T, case p1_time_compat:convert_time_unit(Diff, native, micro_seconds) of N when N > (?S2S_OVERLOAD_BLOCK_PERIOD) * 1000 * 1000 -> mnesia:dirty_delete_object(Entry), false; _ -> true end end. -spec remove_connection({binary(), binary()}, pid()) -> {atomic, ok} | ok | {aborted, any()}. remove_connection(FromTo, Pid) -> case catch mnesia:dirty_match_object(s2s, #s2s{fromto = FromTo, pid = Pid}) of [#s2s{pid = Pid}] -> F = fun () -> mnesia:delete_object(#s2s{fromto = FromTo, pid = Pid}) end, mnesia:transaction(F); _ -> ok end. -spec have_connection({binary(), binary()}) -> boolean(). have_connection(FromTo) -> case catch mnesia:dirty_read(s2s, FromTo) of [_] -> true; _ -> false end. -spec get_connections_pids({binary(), binary()}) -> [pid()]. get_connections_pids(FromTo) -> case catch mnesia:dirty_read(s2s, FromTo) of L when is_list(L) -> [Connection#s2s.pid || Connection <- L]; _ -> [] end. -spec try_register({binary(), binary()}) -> boolean(). try_register(FromTo) -> MaxS2SConnectionsNumber = max_s2s_connections_number(FromTo), MaxS2SConnectionsNumberPerNode = max_s2s_connections_number_per_node(FromTo), F = fun () -> L = mnesia:read({s2s, FromTo}), NeededConnections = needed_connections_number(L, MaxS2SConnectionsNumber, MaxS2SConnectionsNumberPerNode), if NeededConnections > 0 -> mnesia:write(#s2s{fromto = FromTo, pid = self()}), true; true -> false end end, case mnesia:transaction(F) of {atomic, Res} -> Res; _ -> false end. -spec dirty_get_connections() -> [{binary(), binary()}]. dirty_get_connections() -> mnesia:dirty_all_keys(s2s). check_peer_certificate(SockMod, Sock, Peer) -> case SockMod:get_peer_certificate(Sock) of {ok, Cert} -> case SockMod:get_verify_result(Sock) of 0 -> case ejabberd_idna:domain_utf8_to_ascii(Peer) of false -> {error, <<"Cannot decode remote server name">>}; AsciiPeer -> case lists:any(fun(D) -> match_domain(AsciiPeer, D) end, get_cert_domains(Cert)) of true -> {ok, <<"Verification successful">>}; false -> {error, <<"Certificate host name mismatch">>} end end; VerifyRes -> {error, fast_tls:get_cert_verify_string(VerifyRes, Cert)} end; {error, _Reason} -> {error, <<"Cannot get peer certificate">>}; error -> {error, <<"Cannot get peer certificate">>} end. make_key({From, To}, StreamID) -> Secret = ejabberd_config:get_option(shared_key, fun(V) -> V end), p1_sha:to_hexlist( crypto:hmac(sha256, p1_sha:to_hexlist(crypto:hash(sha256, Secret)), [To, " ", From, " ", StreamID])). %%==================================================================== %% gen_server callbacks %%==================================================================== init([]) -> update_tables(), mnesia:create_table(s2s, [{ram_copies, [node()]}, {type, bag}, {attributes, record_info(fields, s2s)}]), mnesia:add_table_copy(s2s, node(), ram_copies), mnesia:subscribe(system), ejabberd_commands:register_commands(get_commands_spec()), mnesia:create_table(temporarily_blocked, [{ram_copies, [node()]}, {attributes, record_info(fields, temporarily_blocked)}]), {ok, #state{}}. handle_call(_Request, _From, State) -> {reply, ok, State}. handle_cast(_Msg, State) -> {noreply, State}. handle_info({mnesia_system_event, {mnesia_down, Node}}, State) -> clean_table_from_bad_node(Node), {noreply, State}; handle_info({route, From, To, Packet}, State) -> case catch do_route(From, To, Packet) of {'EXIT', Reason} -> ?ERROR_MSG("~p~nwhen processing: ~p", [Reason, {From, To, Packet}]); _ -> ok end, {noreply, State}; handle_info(_Info, State) -> {noreply, State}. terminate(_Reason, _State) -> ejabberd_commands:unregister_commands(get_commands_spec()), ok. code_change(_OldVsn, State, _Extra) -> {ok, State}. %%-------------------------------------------------------------------- %%% Internal functions %%-------------------------------------------------------------------- clean_table_from_bad_node(Node) -> F = fun() -> Es = mnesia:select( s2s, [{#s2s{pid = '$1', _ = '_'}, [{'==', {node, '$1'}, Node}], ['$_']}]), lists:foreach(fun(E) -> mnesia:delete_object(E) end, Es) end, mnesia:async_dirty(F). do_route(From, To, Packet) -> ?DEBUG("s2s manager~n\tfrom ~p~n\tto ~p~n\tpacket " "~P~n", [From, To, Packet, 8]), case find_connection(From, To) of {atomic, Pid} when is_pid(Pid) -> ?DEBUG("sending to process ~p~n", [Pid]), #xmlel{name = Name, attrs = Attrs, children = Els} = Packet, NewAttrs = jlib:replace_from_to_attrs(jid:to_string(From), jid:to_string(To), Attrs), #jid{lserver = MyServer} = From, ejabberd_hooks:run(s2s_send_packet, MyServer, [From, To, Packet]), send_element(Pid, #xmlel{name = Name, attrs = NewAttrs, children = Els}), ok; {aborted, _Reason} -> case fxml:get_tag_attr_s(<<"type">>, Packet) of <<"error">> -> ok; <<"result">> -> ok; _ -> Lang = fxml:get_tag_attr_s(<<"xml:lang">>, Packet), Txt = <<"No s2s connection found">>, Err = jlib:make_error_reply( Packet, ?ERRT_SERVICE_UNAVAILABLE(Lang, Txt)), ejabberd_router:route(To, From, Err) end, false end. -spec find_connection(jid(), jid()) -> {aborted, any()} | {atomic, pid()}. find_connection(From, To) -> #jid{lserver = MyServer} = From, #jid{lserver = Server} = To, FromTo = {MyServer, Server}, MaxS2SConnectionsNumber = max_s2s_connections_number(FromTo), MaxS2SConnectionsNumberPerNode = max_s2s_connections_number_per_node(FromTo), ?DEBUG("Finding connection for ~p~n", [FromTo]), case catch mnesia:dirty_read(s2s, FromTo) of {'EXIT', Reason} -> {aborted, Reason}; [] -> %% We try to establish all the connections if the host is not a %% service and if the s2s host is not blacklisted or %% is in whitelist: case not is_service(From, To) andalso allow_host(MyServer, Server) of true -> NeededConnections = needed_connections_number([], MaxS2SConnectionsNumber, MaxS2SConnectionsNumberPerNode), open_several_connections(NeededConnections, MyServer, Server, From, FromTo, MaxS2SConnectionsNumber, MaxS2SConnectionsNumberPerNode); false -> {aborted, error} end; L when is_list(L) -> NeededConnections = needed_connections_number(L, MaxS2SConnectionsNumber, MaxS2SConnectionsNumberPerNode), if NeededConnections > 0 -> %% We establish the missing connections for this pair. open_several_connections(NeededConnections, MyServer, Server, From, FromTo, MaxS2SConnectionsNumber, MaxS2SConnectionsNumberPerNode); true -> %% We choose a connexion from the pool of opened ones. {atomic, choose_connection(From, L)} end end. choose_connection(From, Connections) -> choose_pid(From, [C#s2s.pid || C <- Connections]). choose_pid(From, Pids) -> Pids1 = case [P || P <- Pids, node(P) == node()] of [] -> Pids; Ps -> Ps end, Pid = lists:nth(erlang:phash(jid:remove_resource(From), length(Pids1)), Pids1), ?DEBUG("Using ejabberd_s2s_out ~p~n", [Pid]), Pid. open_several_connections(N, MyServer, Server, From, FromTo, MaxS2SConnectionsNumber, MaxS2SConnectionsNumberPerNode) -> ConnectionsResult = [new_connection(MyServer, Server, From, FromTo, MaxS2SConnectionsNumber, MaxS2SConnectionsNumberPerNode) || _N <- lists:seq(1, N)], case [PID || {atomic, PID} <- ConnectionsResult] of [] -> hd(ConnectionsResult); PIDs -> {atomic, choose_pid(From, PIDs)} end. new_connection(MyServer, Server, From, FromTo, MaxS2SConnectionsNumber, MaxS2SConnectionsNumberPerNode) -> {ok, Pid} = ejabberd_s2s_out:start( MyServer, Server, new), F = fun() -> L = mnesia:read({s2s, FromTo}), NeededConnections = needed_connections_number(L, MaxS2SConnectionsNumber, MaxS2SConnectionsNumberPerNode), if NeededConnections > 0 -> mnesia:write(#s2s{fromto = FromTo, pid = Pid}), ?INFO_MSG("New s2s connection started ~p", [Pid]), Pid; true -> choose_connection(From, L) end end, TRes = mnesia:transaction(F), case TRes of {atomic, Pid} -> ejabberd_s2s_out:start_connection(Pid); _ -> ejabberd_s2s_out:stop_connection(Pid) end, TRes. max_s2s_connections_number({From, To}) -> case acl:match_rule(From, max_s2s_connections, jid:make(<<"">>, To, <<"">>)) of Max when is_integer(Max) -> Max; _ -> ?DEFAULT_MAX_S2S_CONNECTIONS_NUMBER end. max_s2s_connections_number_per_node({From, To}) -> case acl:match_rule(From, max_s2s_connections_per_node, jid:make(<<"">>, To, <<"">>)) of Max when is_integer(Max) -> Max; _ -> ?DEFAULT_MAX_S2S_CONNECTIONS_NUMBER_PER_NODE end. needed_connections_number(Ls, MaxS2SConnectionsNumber, MaxS2SConnectionsNumberPerNode) -> LocalLs = [L || L <- Ls, node(L#s2s.pid) == node()], lists:min([MaxS2SConnectionsNumber - length(Ls), MaxS2SConnectionsNumberPerNode - length(LocalLs)]). %%-------------------------------------------------------------------- %% Function: is_service(From, To) -> true | false %% Description: Return true if the destination must be considered as a %% service. %% -------------------------------------------------------------------- is_service(From, To) -> LFromDomain = From#jid.lserver, case ejabberd_config:get_option( {route_subdomains, LFromDomain}, fun(s2s) -> s2s; (local) -> local end, local) of s2s -> % bypass RFC 3920 10.3 false; local -> Hosts = (?MYHOSTS), P = fun (ParentDomain) -> lists:member(ParentDomain, Hosts) end, lists:any(P, parent_domains(To#jid.lserver)) end. parent_domains(Domain) -> lists:foldl(fun (Label, []) -> [Label]; (Label, [Head | Tail]) -> [<