25
1
mirror of https://github.com/processone/ejabberd.git synced 2024-11-20 16:15:59 +01:00

Move move randoms module to p1_utils repo

This commit is contained in:
Evgeniy Khramtsov 2018-07-05 11:51:49 +03:00
parent 50b645aa92
commit ed1ee6061e
35 changed files with 58 additions and 149 deletions

View File

@ -20,7 +20,7 @@
{deps, [{lager, ".*", {git, "https://github.com/erlang-lager/lager",
{tag, {if_version_above, "17", "3.4.2", "3.2.1"}}}},
{p1_utils, ".*", {git, "https://github.com/processone/p1_utils", "b49f804"}},
{p1_utils, ".*", {git, "https://github.com/processone/p1_utils", "6ff85e8"}},
{cache_tab, ".*", {git, "https://github.com/processone/cache_tab", {tag, "1.0.14"}}},
{fast_tls, ".*", {git, "https://github.com/processone/fast_tls", {tag, "1.0.23"}}},
{stringprep, ".*", {git, "https://github.com/processone/stringprep", {tag, "1.0.12"}}},

View File

@ -43,7 +43,7 @@ mech_new(Host, _GetPassword, _CheckPassword, _CheckPasswordDigest) ->
{ok, #state{server = Host}}.
mech_step(#state{}, _ClientIn) ->
User = iolist_to_binary([randoms:get_string(),
User = iolist_to_binary([p1_rand:get_string(),
integer_to_binary(p1_time_compat:unique_integer([positive]))]),
{ok, [{username, User},
{authzid, User},

View File

@ -78,7 +78,7 @@ format_error(unexpected_response) ->
mech_new(Host, GetPassword, _CheckPassword,
CheckPasswordDigest) ->
{ok,
#state{step = 1, nonce = randoms:get_string(),
#state{step = 1, nonce = p1_rand:get_string(),
host = Host, hostfqdn = get_local_fqdn(),
get_password = GetPassword,
check_password = CheckPasswordDigest}}.

View File

@ -118,7 +118,7 @@ mech_step(#state{step = 2} = State, ClientIn) ->
Pass#scram.iterationcount};
true ->
TempSalt =
randoms:bytes(?SALT_LENGTH),
p1_rand:bytes(?SALT_LENGTH),
SaltedPassword =
scram:salted_password(Pass,
TempSalt,
@ -132,7 +132,7 @@ mech_step(#state{step = 2} = State, ClientIn) ->
str:substr(ClientIn,
str:str(ClientIn, <<"n=">>)),
ServerNonce =
base64:encode(randoms:bytes(?NONCE_LENGTH)),
base64:encode(p1_rand:bytes(?NONCE_LENGTH)),
ServerFirstMessage =
iolist_to_binary(
["r=",

View File

@ -143,7 +143,7 @@ exit_or_halt(Reason, StartFlag) ->
end.
sleep(N) ->
timer:sleep(randoms:uniform(N)).
timer:sleep(p1_rand:uniform(N)).
get_module_file(App, Mod) ->
BaseName = atom_to_list(Mod),

View File

@ -693,7 +693,7 @@ password_to_scram(Password) ->
password_to_scram(#scram{} = Password, _IterationCount) ->
Password;
password_to_scram(Password, IterationCount) ->
Salt = randoms:bytes(?SALT_LENGTH),
Salt = p1_rand:bytes(?SALT_LENGTH),
SaltedPassword = scram:salted_password(Password, Salt, IterationCount),
StoredKey = scram:stored_key(scram:client_key(SaltedPassword)),
ServerKey = scram:server_key(SaltedPassword),

View File

@ -984,7 +984,7 @@ http_error(Status, Reason, Type) ->
end,
{Status, Reason, ?HEADER(CType), <<"">>}.
make_sid() -> str:sha(randoms:get_string()).
make_sid() -> str:sha(p1_rand:get_string()).
-compile({no_auto_import, [{min, 2}]}).
@ -1075,7 +1075,7 @@ start_shaper_timer(Timeout) ->
erlang:start_timer(Timeout, self(), shaper_timeout).
make_random_jid(Host) ->
User = randoms:get_string(),
jid:make(User, Host, randoms:get_string()).
User = p1_rand:get_string(),
jid:make(User, Host, p1_rand:get_string()).
make_socket(Pid, IP) -> {http_bind, Pid, IP}.

View File

@ -881,7 +881,7 @@ bounce_message_queue() ->
-spec new_uniq_id() -> binary().
new_uniq_id() ->
iolist_to_binary(
[randoms:get_string(),
[p1_rand:get_string(),
integer_to_binary(p1_time_compat:unique_integer([positive]))]).
-spec get_conn_type(state()) -> c2s | c2s_tls | c2s_compressed | websocket |

View File

@ -89,7 +89,7 @@ mk_field(Type, Var, Value) ->
create_captcha(SID, From, To, Lang, Limiter, Args) ->
case create_image(Limiter) of
{ok, Type, Key, Image} ->
Id = <<(randoms:get_string())/binary>>,
Id = <<(p1_rand:get_string())/binary>>,
JID = jid:encode(From),
CID = <<"sha1+", (str:sha(Image))/binary, "@bob.xmpp.org">>,
Data = #bob_data{cid = CID, 'max-age' = 0, type = Type,
@ -120,7 +120,7 @@ create_captcha(SID, From, To, Lang, Limiter, Args) ->
create_captcha_x(SID, To, Lang, Limiter, #xdata{fields = Fs} = X) ->
case create_image(Limiter) of
{ok, Type, Key, Image} ->
Id = <<(randoms:get_string())/binary>>,
Id = <<(p1_rand:get_string())/binary>>,
CID = <<"sha1+", (str:sha(Image))/binary, "@bob.xmpp.org">>,
Data = #bob_data{cid = CID, 'max-age' = 0, type = Type, data = Image},
HelpTxt = translate:translate(Lang,
@ -376,7 +376,7 @@ code_change(_OldVsn, State, _Extra) -> {ok, State}.
create_image() -> create_image(undefined).
create_image(Limiter) ->
Key = str:substr(randoms:get_string(), 1, 6),
Key = str:substr(p1_rand:get_string(), 1, 6),
create_image(Limiter, Key).
create_image(Limiter, Key) ->

View File

@ -75,7 +75,7 @@ start() ->
UnixTime = p1_time_compat:system_time(seconds),
SharedKey = case erlang:get_cookie() of
nocookie ->
str:sha(randoms:get_string());
str:sha(p1_rand:get_string());
Cookie ->
str:sha(misc:atom_to_binary(Cookie))
end,
@ -115,7 +115,7 @@ start(Hosts, Opts) ->
UnixTime = p1_time_compat:system_time(seconds),
SharedKey = case erlang:get_cookie() of
nocookie ->
str:sha(randoms:get_string());
str:sha(p1_rand:get_string());
Cookie ->
str:sha(misc:atom_to_binary(Cookie))
end,

View File

@ -49,7 +49,7 @@ start_link() ->
-spec route(iq(), atom() | pid(), term(), non_neg_integer()) -> ok.
route(#iq{type = T} = IQ, Proc, Ctx, Timeout) when T == set; T == get ->
Expire = current_time() + Timeout,
Rnd = randoms:get_string(),
Rnd = p1_rand:get_string(),
ID = encode_id(Expire, Rnd),
ets:insert(?MODULE, {{Expire, Rnd}, Proc, Ctx}),
gen_server:cast(?MODULE, {restart_timer, Expire}),

View File

@ -478,7 +478,7 @@ process_privacy(#privacy_query{lists = Lists,
active = Active} = PrivacyQuery,
State = #state{user = U, server = S}) ->
JID = jid:make(U, S),
IQ = #iq{type = set, id = randoms:get_string(),
IQ = #iq{type = set, id = p1_rand:get_string(),
from = JID, to = JID, sub_els = [PrivacyQuery]},
case mod_privacy:process_iq(IQ) of
#iq{type = error} = ResIQ ->
@ -498,7 +498,7 @@ process_privacy(#privacy_query{lists = Lists,
-spec process_private(private(), state()) -> {ok, state()} | {error, _}.
process_private(Private, State = #state{user = U, server = S}) ->
JID = jid:make(U, S),
IQ = #iq{type = set, id = randoms:get_string(),
IQ = #iq{type = set, id = p1_rand:get_string(),
from = JID, to = JID, sub_els = [Private]},
case mod_private:process_sm_iq(IQ) of
#iq{type = result} ->
@ -510,7 +510,7 @@ process_private(Private, State = #state{user = U, server = S}) ->
-spec process_vcard(xmlel(), state()) -> {ok, state()} | {error, _}.
process_vcard(El, State = #state{user = U, server = S}) ->
JID = jid:make(U, S),
IQ = #iq{type = set, id = randoms:get_string(),
IQ = #iq{type = set, id = p1_rand:get_string(),
from = JID, to = JID, sub_els = [El]},
case mod_vcard:process_sm_iq(IQ) of
#iq{type = result} ->

View File

@ -437,7 +437,7 @@ connect(#state{num = Num}) ->
erlang:error(Why)
end
catch _:Reason ->
Timeout = randoms:uniform(
Timeout = p1_rand:uniform(
min(10, ejabberd_redis_sup:get_pool_size())),
?ERROR_MSG("Redis connection #~p at ~s:~p has failed: ~p; "
"reconnecting in ~p seconds",
@ -502,7 +502,7 @@ log_error(Cmd, Reason) ->
-spec get_rnd_id() -> pos_integer().
get_rnd_id() ->
randoms:round_robin(ejabberd_redis_sup:get_pool_size() - 1) + 2.
p1_rand:round_robin(ejabberd_redis_sup:get_pool_size() - 1) + 2.
-spec get_result([{error, atom() | binary()} | {ok, iodata()}]) ->
{ok, [redis_reply()]} | {error, binary()}.

View File

@ -162,7 +162,7 @@ get_pids() ->
[ejabberd_riak:get_proc(I) || I <- lists:seq(1, get_pool_size())].
get_random_pid() ->
I = randoms:round_robin(get_pool_size()) + 1,
I = p1_rand:round_robin(get_pool_size()) + 1,
ejabberd_riak:get_proc(I).
transform_options(Opts) ->

View File

@ -375,7 +375,7 @@ mk_bounce_error(_Lang, _State) ->
-spec get_delay() -> non_neg_integer().
get_delay() ->
MaxDelay = ejabberd_config:get_option(s2s_max_retry_delay, 300),
randoms:uniform(MaxDelay).
p1_rand:uniform(MaxDelay).
-spec set_idle_timeout(state()) -> state().
set_idle_timeout(#{on_route := send, server := LServer} = State) ->

View File

@ -261,7 +261,7 @@ check_from(From, #{host_opts := HostOpts}) ->
dict:is_key(Server, HostOpts).
random_password() ->
str:sha(randoms:bytes(20)).
str:sha(p1_rand:bytes(20)).
transform_listen_option({hosts, Hosts, O}, Opts) ->
case lists:keyfind(hosts, 1, Opts) of

View File

@ -91,7 +91,7 @@ get_random_pid(Host) ->
case get_pids(Host) of
[] -> none;
Pids ->
I = randoms:round_robin(length(Pids)) + 1,
I = p1_rand:round_robin(length(Pids)) + 1,
lists:nth(I, Pids)
end.

View File

@ -186,7 +186,7 @@ call_port(Server, Args, Timeout) ->
StartTime = p1_time_compat:monotonic_time(milli_seconds),
Pool = pool_name(Server),
PoolSize = pool_size(Server),
I = randoms:round_robin(PoolSize),
I = p1_rand:round_robin(PoolSize),
Cmd = str:join(Args, <<":">>),
do_call(Cmd, I, I + PoolSize, Pool, PoolSize,
StartTime + Timeout, StartTime).

View File

@ -974,7 +974,7 @@ build_random_password(Reason) ->
{{Year, Month, Day}, {Hour, Minute, Second}} = calendar:universal_time(),
Date = str:format("~4..0B~2..0B~2..0BT~2..0B:~2..0B:~2..0B",
[Year, Month, Day, Hour, Minute, Second]),
RandomString = randoms:get_string(),
RandomString = p1_rand:get_string(),
<<"BANNED_ACCOUNT--", Date/binary, "--", RandomString/binary, "--", Reason/binary>>.
set_password_auth(User, Server, Password) ->
@ -1515,7 +1515,7 @@ send_message(Type, From, To, Subject, Body) ->
build_packet(Type, Subject, Body) ->
#message{type = misc:binary_to_atom(Type),
body = xmpp:mk_text(Body),
id = randoms:get_string(),
id = p1_rand:get_string(),
subject = xmpp:mk_text(Subject)}.
send_stanza(FromString, ToString, Stanza) ->

View File

@ -359,7 +359,7 @@ set_vcard_avatar(JID, VCardPhoto, Meta) ->
ok;
{ok, VCard} ->
VCard1 = VCard#vcard_temp{photo = VCardPhoto},
IQ = #iq{from = JID, to = JID, id = randoms:get_string(),
IQ = #iq{from = JID, to = JID, id = p1_rand:get_string(),
type = set, sub_els = [VCard1], meta = Meta},
LServer = JID#jid.lserver,
ejabberd_hooks:run_fold(vcard_iq_set, LServer, IQ, []),

View File

@ -241,7 +241,7 @@ broadcast_event(#jid{luser = LUser, lserver = LServer} = From, Event) ->
fun(R) ->
To = jid:replace_resource(From, R),
IQ = #iq{type = set, from = BFrom, to = To,
id = <<"push", (randoms:get_string())/binary>>,
id = <<"push", (p1_rand:get_string())/binary>>,
sub_els = [Event]},
ejabberd_router:route(IQ)
end, ejabberd_sm:get_user_resources(LUser, LServer)).

View File

@ -188,12 +188,12 @@ code_change(_OldVsn, State, _Extra) -> {ok, State}.
do_client_version(disabled, _From, _To) -> ok;
do_client_version(enabled, From, To) ->
Random_resource = randoms:get_string(),
Random_resource = p1_rand:get_string(),
From2 = From#jid{resource = Random_resource,
lresource = Random_resource},
ID = randoms:get_string(),
ID = p1_rand:get_string(),
Packet = #iq{from = From2, to = To, type = get,
id = randoms:get_string(),
id = p1_rand:get_string(),
sub_els = [#version{}]},
ejabberd_router:route(Packet),
receive

View File

@ -586,7 +586,7 @@ create_slot(#state{service_url = undefined,
case ejabberd_hooks:run_fold(http_upload_slot_request, ServerHost, allow,
[JID, UserDir, Size, Lang]) of
allow ->
RandStr = randoms:get_alphanum_string(SecretLength),
RandStr = p1_rand:get_alphanum_string(SecretLength),
FileStr = make_file_string(File),
?INFO_MSG("Got HTTP upload slot for ~s (file: ~s, size: ~B)",
[jid:encode(JID), File, Size]),
@ -887,7 +887,7 @@ convert(Path, #media_info{type = T, width = W, height = H} = Info) ->
true ->
Dir = filename:dirname(Path),
Ext = atom_to_binary(T, latin1),
FileName = <<(randoms:get_string())/binary, $., Ext/binary>>,
FileName = <<(p1_rand:get_string())/binary, $., Ext/binary>>,
OutPath = filename:join(Dir, FileName),
{W1, H1} = if W > H -> {300, round(H*300/W)};
H > W -> {round(W*300/H), 300};

View File

@ -568,7 +568,7 @@ process_muc_unique(#iq{type = set, lang = Lang} = IQ) ->
process_muc_unique(#iq{from = From, type = get,
sub_els = [#muc_unique{}]} = IQ) ->
Name = str:sha(term_to_binary([From, p1_time_compat:timestamp(),
randoms:get_string()])),
p1_rand:get_string()])),
xmpp:make_iq_result(IQ, #muc_unique{name = Name}).
-spec process_mucsub(iq()) -> iq().

View File

@ -546,7 +546,7 @@ handle_sync_event(get_subscribers, _From, StateName, StateData) ->
{reply, {ok, JIDs}, StateName, StateData};
handle_sync_event({muc_subscribe, From, Nick, Nodes}, _From,
StateName, StateData) ->
IQ = #iq{type = set, id = randoms:get_string(),
IQ = #iq{type = set, id = p1_rand:get_string(),
from = From, sub_els = [#muc_subscribe{nick = Nick,
events = Nodes}]},
Config = StateData#state.config,
@ -572,7 +572,7 @@ handle_sync_event({muc_subscribe, From, Nick, Nodes}, _From,
{reply, {error, get_error_text(Err)}, StateName, StateData}
end;
handle_sync_event({muc_unsubscribe, From}, _From, StateName, StateData) ->
IQ = #iq{type = set, id = randoms:get_string(),
IQ = #iq{type = set, id = p1_rand:get_string(),
from = From, sub_els = [#muc_unsubscribe{}]},
case process_iq_mucsub(From, IQ, StateData) of
{result, _, NewState} ->
@ -2162,7 +2162,7 @@ send_self_presence(JID, State) ->
Els1
end,
ejabberd_router:route(#presence{from = State#state.jid, to = JID,
id = randoms:get_string(),
id = p1_rand:get_string(),
sub_els = Els2}).
-spec send_initial_presence(jid(), state(), state()) -> ok.
@ -2465,7 +2465,7 @@ send_affiliation(JID, Affiliation, StateData) ->
Item = #muc_item{jid = JID,
affiliation = Affiliation,
role = none},
Message = #message{id = randoms:get_string(),
Message = #message{id = p1_rand:get_string(),
sub_els = [#muc_user{items = [Item]}]},
Users = get_users_and_subscribers(StateData),
Recipients = case (StateData#state.config)#config.anonymous of
@ -3479,7 +3479,7 @@ send_config_change_info(New, #state{config = Old} = StateData) ->
send_self_presence(JID, StateData#state{config = New})
end, ?DICT:to_list(StateData#state.users)),
Message = #message{type = groupchat,
id = randoms:get_string(),
id = p1_rand:get_string(),
sub_els = [#muc_user{status_codes = Codes}]},
send_wrapped_multiple(StateData#state.jid,
get_users_and_subscribers(StateData),
@ -4324,7 +4324,7 @@ send_subscriptions_change_notifications(From, Nick, Type, State) ->
items = #ps_items{
node = ?NS_MUCSUB_NODES_SUBSCRIBERS,
items = [#ps_item{
id = randoms:get_string(),
id = p1_rand:get_string(),
sub_els = [Payload]}]}}]},
ejabberd_router:route(xmpp:set_from_to(Packet, From, JID));
false ->
@ -4367,7 +4367,7 @@ send_wrapped(From, To, Packet, Node, State) ->
true ->
ejabberd_router:route(
#presence{from = State#state.jid, to = To,
id = randoms:get_string(),
id = p1_rand:get_string(),
type = unavailable});
false ->
ok
@ -4389,7 +4389,7 @@ wrap(From, To, Packet, Node) ->
items = #ps_items{
node = Node,
items = [#ps_item{
id = randoms:get_string(),
id = p1_rand:get_string(),
sub_els = [El]}]}}]}.
%% -spec send_multiple(jid(), binary(), [#user{}], stanza()) -> ok.

View File

@ -715,7 +715,7 @@ process_discoinfo_result2(From, FromS, LServiceS,
false ->
case ST of
{wait_for_info, _ID} ->
Random = randoms:get_string(),
Random = p1_rand:get_string(),
ID = <<RServer/binary, $/, Random/binary>>,
send_query_items(FromS, LServiceS, ID),
add_response(RServer, Response, {wait_for_items, ID});
@ -784,7 +784,7 @@ process_discoitems_result(From, LServiceS, ID, #disco_items{items = Items}) ->
[] ->
add_response(RServer, not_supported, cached);
_ ->
Random = randoms:get_string(),
Random = p1_rand:get_string(),
ID2 = <<RServer/binary, $/, Random/binary>>,
[send_query_info(Item, LServiceS, ID2) || Item <- List],
add_response(RServer, Response,
@ -859,7 +859,7 @@ search_server_on_cache(RServer, _LServerS, LServiceS, Maxmins) ->
end.
query_info(RServer, LServiceS, Response) ->
Random = randoms:get_string(),
Random = p1_rand:get_string(),
ID = <<RServer/binary, $/, Random/binary>>,
send_query_info(RServer, LServiceS, ID),
add_response(RServer, Response, {wait_for_info, ID}).

View File

@ -364,7 +364,7 @@ push_list_update(From, Name) ->
fun(R) ->
To = jid:replace_resource(From, R),
IQ = #iq{type = set, from = BareFrom, to = To,
id = <<"push", (randoms:get_string())/binary>>,
id = <<"push", (p1_rand:get_string())/binary>>,
sub_els = [#privacy_query{
lists = [#privacy_list{name = Name}]}]},
ejabberd_router:route(IQ)

View File

@ -1468,7 +1468,7 @@ create_node(Host, ServerHost, Node, Owner, Type) ->
create_node(Host, ServerHost, <<>>, Owner, Type, Access, Configuration) ->
case lists:member(<<"instant-nodes">>, plugin_features(Host, Type)) of
true ->
Node = randoms:get_string(),
Node = p1_rand:get_string(),
case create_node(Host, ServerHost, Node, Owner, Type, Access, Configuration) of
{result, _} ->
{result, #pubsub{create = Node}};

View File

@ -464,7 +464,7 @@ notify(LServer, PushLJID, Node, XData, Pkt, Dir, HandleResponse) ->
IQ = #iq{type = set,
from = From,
to = jid:make(PushLJID),
id = randoms:get_string(),
id = p1_rand:get_string(),
sub_els = [PubSub]},
ejabberd_router:route_iq(IQ, HandleResponse).

View File

@ -492,7 +492,7 @@ push_item(To, OldItem, NewItem, Ver) ->
route_presence_change(To, OldItem, NewItem),
IQ = #iq{type = set, to = To,
from = jid:remove_resource(To),
id = <<"push", (randoms:get_string())/binary>>,
id = <<"push", (p1_rand:get_string())/binary>>,
sub_els = [#roster_query{ver = Ver,
items = [encode_item(NewItem)]}]},
ejabberd_router:route(IQ).
@ -1071,7 +1071,7 @@ user_roster_item_parse_query(User, Server, Items,
#iq{type = set,
from = UJID,
to = UJID,
id = randoms:get_string(),
id = p1_rand:get_string(),
sub_els = [#roster_query{
items = [RosterItem]}]}),
throw(submitted);

View File

@ -69,7 +69,7 @@ log_user_receive({Packet, C2SState}) ->
log_packet(Packet, Host) ->
Loggers = gen_mod:get_module_opt(Host, ?MODULE, loggers),
ForwardedMsg = #message{from = jid:make(Host),
id = randoms:get_string(),
id = p1_rand:get_string(),
sub_els = [#forwarded{
sub_els = [Packet]}]},
lists:foreach(

View File

@ -287,7 +287,7 @@ set_new_rosteritems(UserFrom, ServerFrom, UserTo,
set_item(User, Server, Resource, Item) ->
ResIQ = #iq{from = jid:make(User, Server, Resource),
to = jid:make(Server),
type = set, id = <<"push", (randoms:get_string())/binary>>,
type = set, id = <<"push", (p1_rand:get_string())/binary>>,
sub_els = [#roster_query{
items = [mod_roster:encode_item(Item)]}]},
ejabberd_router:route(ResIQ).

View File

@ -1,91 +0,0 @@
%%%----------------------------------------------------------------------
%%% File : randoms.erl
%%% Author : Alexey Shchepin <alexey@process-one.net>
%%% Purpose : Random generation number wrapper
%%% Created : 13 Dec 2002 by Alexey Shchepin <alexey@process-one.net>
%%%
%%%
%%% ejabberd, Copyright (C) 2002-2018 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(randoms).
-author('alexey@process-one.net').
-export([get_string/0, uniform/0, uniform/1, uniform/2, bytes/1,
round_robin/1, get_alphanum_string/1]).
-define(THRESHOLD, 16#10000000000000000).
-ifdef(RAND_UNIFORM).
get_string() ->
R = rand:uniform(?THRESHOLD),
integer_to_binary(R).
uniform() ->
rand:uniform().
uniform(N) ->
rand:uniform(N).
uniform(N, M) ->
rand:uniform(M-N+1) + N-1.
-else.
get_string() ->
R = crypto:rand_uniform(0, ?THRESHOLD),
integer_to_binary(R).
uniform() ->
crypto:rand_uniform(0, ?THRESHOLD)/?THRESHOLD.
uniform(N) ->
crypto:rand_uniform(1, N+1).
uniform(N, M) ->
crypto:rand_uniform(N, M+1).
-endif.
-ifdef(STRONG_RAND_BYTES).
bytes(N) ->
crypto:strong_rand_bytes(N).
-else.
bytes(N) ->
crypto:rand_bytes(N).
-endif.
-spec round_robin(pos_integer()) -> non_neg_integer().
round_robin(N) ->
p1_time_compat:unique_integer([monotonic, positive]) rem N.
-spec get_alphanum_string(non_neg_integer()) -> binary().
get_alphanum_string(Length) ->
list_to_binary(get_alphanum_string([], Length)).
-spec get_alphanum_string(string(), non_neg_integer()) -> string().
get_alphanum_string(S, 0) -> S;
get_alphanum_string(S, N) ->
get_alphanum_string([make_rand_char() | S], N - 1).
-spec make_rand_char() -> char().
make_rand_char() ->
map_int_to_char(uniform(0, 61)).
-spec map_int_to_char(0..61) -> char().
map_int_to_char(N) when N =< 9 -> N + 48; % Digit.
map_int_to_char(N) when N =< 35 -> N + 55; % Upper-case character.
map_int_to_char(N) when N =< 61 -> N + 61. % Lower-case character.

View File

@ -428,7 +428,7 @@ noreply(#{stream_timeout := {MSecs, StartTime}} = State) ->
-spec new_id() -> binary().
new_id() ->
randoms:get_string().
p1_rand:get_string().
-spec is_disconnected(state()) -> boolean().
is_disconnected(#{stream_state := StreamState}) ->

View File

@ -464,7 +464,7 @@ noreply(#{stream_timeout := {MSecs, OldTime}} = State) ->
-spec new_id() -> binary().
new_id() ->
randoms:get_string().
p1_rand:get_string().
-spec is_disconnected(state()) -> boolean().
is_disconnected(#{stream_state := StreamState}) ->
@ -1190,7 +1190,7 @@ h_addr_list_to_host_ports(AddrList) ->
fun({{Priority, Weight, Port, Host}, TLS}) ->
N = case Weight of
0 -> 0;
_ -> (Weight + 1) * randoms:uniform()
_ -> (Weight + 1) * p1_rand:uniform()
end,
[{Priority * 65536 - N, Host, Port, TLS}];
(_) ->