Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add OTP-25 support #833

Draft
wants to merge 4 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ $(REBAR3):
@chmod a+x rebar3

upgrade: $(REBAR3)
@$(REBAR3) upgrade
@$(REBAR3) upgrade --all

clean: $(REBAR3)
@$(REBAR3) clean --all
Expand Down
18 changes: 9 additions & 9 deletions rebar.config
Original file line number Diff line number Diff line change
Expand Up @@ -15,17 +15,17 @@
]}.

{deps, [
{lager, "3.7.0"},
{lager, "3.9.2"},
{eid, {git, "https://github.com/jur0/eid.git", {tag, "0.6.0"}}},
{cowlib, {git, "https://github.com/ninenines/cowlib", {tag, "2.6.0"}}},
{cowboy, {git, "https://github.com/ninenines/cowboy", {tag, "2.5.0"}}},
{gun, {git, "https://github.com/ninenines/gun.git", {tag, "1.3.0"}}},
{jsx, "2.10.0"},
{iso8601, "1.3.1"},
{cowlib, "2.11.0"},
{cowboy, "2.9.0"},
{gun, "1.3.3"},
{jsx, "3.1.0"},
{iso8601, "1.3.3"},
{cbor, {git, "https://github.com/yjh0502/cbor-erlang.git", {ref, "b5c9dbc2de15753b2db15e13d88c11738c2ac292"}}},
{gen_smtp, "0.15.0"},
{amqp_client, "3.7.18"},
{emqtt, {git, "https://github.com/emqx/emqtt.git", {tag, "v1.1.1"}}},
{gen_smtp, "1.2.0"},
{amqp_client, "3.10.5"},
{emqtt, "1.2.1"},
{erlmongo, {git, "https://github.com/SergejJurecko/erlmongo.git", {ref, "f0d03cd4592f7bf28059b81214b61c28ccf046c0"}}},
{prometheus_cowboy, "0.1.8"}
]}.
Expand Down
4 changes: 2 additions & 2 deletions src/lorawan_admin_connections.erl
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ handle_get(Req, #state{app=undefined}=State) ->
fun(Conn) ->
filter_matches(Conn, Filter)
end,
get_connections(pg2:which_groups(), [])),
get_connections(pg:which_groups(), [])),
{jsx:encode(Items), Req, State};
handle_get(Req, #state{app=App}=State) ->
{jsx:encode(get_connection(App)), Req, State}.
Expand Down Expand Up @@ -82,7 +82,7 @@ get_connections([], Acc)->
Acc.

get_connection(App) ->
case pg2:get_members({backend, App}) of
case pg:get_members({backend, App}) of
List when is_list(List) ->
lists:foldl(
fun(Pid, Acc) ->
Expand Down
4 changes: 2 additions & 2 deletions src/lorawan_admin_feed.erl
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ get_filters(Req) ->
end.

websocket_init(#state{table=Table} = State) ->
ok = pg2:join({feed, Table}, self()),
ok = pg:join({feed, Table}, self()),
{reply, {text, encoded_records(State)}, State}.

websocket_handle({ping, _}, State) ->
Expand Down Expand Up @@ -69,7 +69,7 @@ lists_match(_, _) ->

notify(Scope) ->
Table = element(1, Scope),
case pg2:get_members({feed, Table}) of
case pg:get_members({feed, Table}) of
{error, _Error} ->
ok;
List when is_list(List) ->
Expand Down
5 changes: 2 additions & 3 deletions src/lorawan_backend_factory.erl
Original file line number Diff line number Diff line change
Expand Up @@ -97,11 +97,10 @@ item_deleted(#connector{}=Connector) ->
stop_connector(Connector).


start_connector(#connector{connid=Id, app=App, uri=Uri, enabled=true,
start_connector(#connector{connid=Id, app=_App, uri=Uri, enabled=true,
failed=Failed}=Connector) when Failed == undefined; Failed == [] ->
case find_module(Uri) of
{ok, Module} ->
pg2:create({backend, App}),
apply(Module, start_connector, [Connector]);
{error, Error} ->
lorawan_utils:throw_error({connector, Id}, Error)
Expand Down Expand Up @@ -171,7 +170,7 @@ nodes_with_backend(App) ->
[], mnesia:dirty_index_read(profile, App, #profile.app)).

send_to_connectors(App, Message) ->
case pg2:get_members({backend, App}) of
case pg:get_members({backend, App}) of
{error, _Error} ->
% the application is internal or not defined
ok;
Expand Down
6 changes: 3 additions & 3 deletions src/lorawan_connector.erl
Original file line number Diff line number Diff line change
Expand Up @@ -168,14 +168,14 @@ build_access_token(Res0, AccessKey) ->
build_access_token(Res0, AccessKey, 60*60*24*7). % expires in a week

build_access_token(Res0, AccessKey, Expiry) ->
Res = http_uri:encode(Res0),
Res = uri_string:quote(Res0),
% seconds since the UNIX epoch
Now = calendar:datetime_to_gregorian_seconds(calendar:universal_time())
- calendar:datetime_to_gregorian_seconds({{1970,1,1}, {0,0,0}}),
ToSign = lists:flatten(
io_lib:format("~s~n~B", [Res, Now+Expiry])),
Sig = http_uri:encode(base64:encode_to_string(
crypto:hmac(sha256, base64:decode(AccessKey), ToSign))),
Sig = uri_string:quote(base64:encode_to_string(
crypto:mac(hmac, sha256, base64:decode(AccessKey), ToSign))),
io_lib:format("SharedAccessSignature sr=~s&sig=~s&se=~B", [Res, Sig, Now+Expiry]).


Expand Down
2 changes: 1 addition & 1 deletion src/lorawan_connector_amqp.erl
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ start_link(Connector) ->

init([#connector{connid=Id, app=App, publish_uplinks=PubUp, publish_events=PubEv, received=Cons}=Connector]) ->
process_flag(trap_exit, true),
ok = pg2:join({backend, App}, self()),
ok = pg:join({backend, App}, self()),
self() ! connect,
try
{ok, #state{
Expand Down
13 changes: 7 additions & 6 deletions src/lorawan_connector_http.erl
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ start_link(Connector) ->

init([#connector{connid=Id, app=App,
publish_uplinks=PubUp, publish_events=PubEv, name=UserName, pass=Password}=Conn]) ->
ok = pg2:join({backend, App}, self()),
ok = pg:join({backend, App}, self()),
try
{ok, ensure_gun(
#state{conn=Conn,
Expand Down Expand Up @@ -165,14 +165,15 @@ ensure_gun(#state{conn=#connector{uri= <<"http:">>}, pid=undefined}=State) ->
State;
ensure_gun(#state{conn=#connector{connid=ConnId, uri=Uri}, pid=undefined}=State) ->
lager:debug("Connecting ~s to ~s", [ConnId, Uri]),
#{scheme := Scheme, host := Host, port := Port, path := Path} = uri_string:parse(binary_to_list(Uri)),
{ConnPid, Prefix} =
case http_uri:parse(binary_to_list(Uri), [{scheme_defaults, [{http, 80}, {https, 443}]}]) of
{ok, {http, _UserInfo, HostName, Port, Path, _Query}} ->
{ok, Pid} = gun:open(HostName, Port),
case Scheme of
"http" ->
{ok, Pid} = gun:open(Host, Port),
{Pid, Path};
{ok, {https, _UserInfo, HostName, Port, Path, _Query}} ->
"https" ->
Opts = application:get_env(lorawan_server, ssl_options, []),
{ok, Pid} = gun:open(HostName, Port, #{transport=>ssl, transport_opts=>Opts}),
{ok, Pid} = gun:open(Host, Port, #{transport=>ssl, transport_opts=>Opts}),
{Pid, Path}
end,
MRef = monitor(process, ConnPid),
Expand Down
2 changes: 1 addition & 1 deletion src/lorawan_connector_mongodb.erl
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ start_link(Connector) ->
init([#connector{connid=Id, app=App, uri= <<"mongodb://", Servers0/binary>>,
publish_uplinks=PubUp, publish_events=PubEv}=Connector]) ->
process_flag(trap_exit, true),
ok = pg2:join({backend, App}, self()),
ok = pg:join({backend, App}, self()),
lager:debug("Connecting ~s to mongodb ~s", [Id, Servers0]),
Pool = binary_to_atom(Id, latin1),
% connect
Expand Down
12 changes: 6 additions & 6 deletions src/lorawan_connector_mqtt.erl
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ start_link(Connector) ->
init([#connector{connid=Id, app=App, uri=Uri, client_id=ClientId, name=UserName, pass=Password,
subscribe=Sub, publish_uplinks=PubUp, publish_events=PubEv, received=Cons}=Connector]) ->
process_flag(trap_exit, true),
ok = pg2:join({backend, App}, self()),
ok = pg:join({backend, App}, self()),
self() ! nodes_changed,
timer:send_interval(60*1000, ping),
try
Expand Down Expand Up @@ -140,14 +140,14 @@ connect(Vers, Arguments, Conn) ->

connection_args([Uri, ClientId, UserName, Password], Conn) ->
lager:debug("Connecting ~s to ~p, id ~p, user ~p", [Conn#connector.connid, Uri, ClientId, UserName]),
{ok, ConnUri} = http_uri:parse(binary_to_list(Uri), [{scheme_defaults, [{mqtt, 1883}, {mqtts, 8883}]}]),
{Scheme, _UserInfo, HostName, Port, _Path, _Query} = ConnUri,
ConnUri = uri_string:parse(binary_to_list(Uri)),
#{scheme := Scheme, host := Host, port := Port} = ConnUri,
lists:append([
[{host, HostName},
[{host, Host},
{port, Port},
{keepalive, 0}],
auth_args(HostName, Conn#connector.auth, ClientId, UserName, Password),
ssl_args(Scheme, Conn)
auth_args(Host, Conn#connector.auth, ClientId, UserName, Password),
ssl_args(list_to_atom(Scheme), Conn)
]).

connect0([Ver | Rest], CArgs) ->
Expand Down
2 changes: 1 addition & 1 deletion src/lorawan_connector_ws.erl
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ validate_key(_Else, _) ->

websocket_init(#state{conn=#connector{connid=Id, app=App}, bindings=Bindings} = State) ->
lager:debug("WebSocket connector ~p with ~p", [Id, Bindings]),
ok = pg2:join({backend, App}, self()),
ok = pg:join({backend, App}, self()),
{ok, State}.

websocket_handle({text, Msg}, State) ->
Expand Down
2 changes: 1 addition & 1 deletion src/lorawan_gw_lns.erl
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ handle_message(#{router:=Router}, #state{mac=undefined}=State) ->
ID6 = lorawan_eid:as_id6(MAC),
% determine own address
[#config{admin_url=Prefix}] = mnesia:dirty_read(config, <<"main">>),
{ok, {Scheme, _, Host, Port, Path, _}} = http_uri:parse(Prefix),
#{scheme := Scheme, host := Host, port := Port, path := Path} = uri_string:parse(Prefix),
Scheme2 =
case Scheme of
http -> <<"ws">>;
Expand Down
22 changes: 11 additions & 11 deletions src/lorawan_mac.erl
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ ingest_join_frame(MAC, Msg, AppEUI, DevEUI, DevNonce, MIC) ->
[D] when D#device.appeui /= undefined, D#device.appeui /= AppEUI ->
{error, {device, DevEUI}, {bad_appeui, binary_to_hex(AppEUI)}, aggregated};
[D] ->
case crypto:cmac(aes_cbc128, D#device.appkey, Msg, 4) of
case crypto:macN(cmac, aes_128_cbc, D#device.appkey, Msg, 4) of
MIC ->
verify_join(MAC, D, DevNonce);
_MIC2 ->
Expand All @@ -70,7 +70,7 @@ ingest_data_frame(_MAC, MType, Msg, FOpts, FRMPayload, MIC,
when MType == 2#010; MType == 2#100 ->
case accept_node_frame(DevAddr, FCnt) of
{ok, Fresh, {Network, Profile, Node}} ->
case crypto:cmac(aes_cbc128, Node#node.nwkskey,
case crypto:macN(cmac, aes_128_cbc, Node#node.nwkskey,
<<(b0(MType band 1, DevAddr, Node#node.fcntup, byte_size(Msg)))/binary, Msg/binary>>, 4) of
MIC ->
ok = lorawan_admin:write(
Expand Down Expand Up @@ -381,10 +381,10 @@ handle_accept(Gateways, {Network, Profile, Device}, DevAddr, DevNonce) ->

create_node(Gateways, {#network{netid=NetID}=Network, Profile, #device{deveui=DevEUI, appkey=AppKey}},
AppNonce, DevAddr, DevNonce) ->
NwkSKey = crypto:block_encrypt(aes_ecb, AppKey,
padded(16, <<16#01, AppNonce/binary, NetID/binary, DevNonce/binary>>)),
AppSKey = crypto:block_encrypt(aes_ecb, AppKey,
padded(16, <<16#02, AppNonce/binary, NetID/binary, DevNonce/binary>>)),
NwkSKey = crypto:crypto_one_time(aes_ecb, AppKey,
padded(16, <<16#01, AppNonce/binary, NetID/binary, DevNonce/binary>>), true),
AppSKey = crypto:crypto_one_time(aes_ecb, AppKey,
padded(16, <<16#02, AppNonce/binary, NetID/binary, DevNonce/binary>>), true),

[Device] = mnesia:read(device, DevEUI, write),
Device2 = append_join({calendar:universal_time(), DevNonce}, Device#device{node=DevAddr}),
Expand Down Expand Up @@ -447,10 +447,10 @@ encode_accept(#network{netid=NetID, rx1_delay=RxDelay, cflist=CFList}, #device{a
MHDR = <<2#001:3, 0:3, 0:2>>,
MACPayload = <<AppNonce/binary, NetID/binary, (reverse(DevAddr))/binary, 0:1,
RX1DROffset:3, RX2DataRate:4, RxDelay, (encode_cflist(CFList))/binary>>,
MIC = crypto:cmac(aes_cbc128, AppKey, <<MHDR/binary, MACPayload/binary>>, 4),
MIC = crypto:macN(cmac, aes_128_cbc, AppKey, <<MHDR/binary, MACPayload/binary>>, 4),

% yes, decrypt; see LoRaWAN specification, Section 6.2.5
PHYPayload = crypto:block_decrypt(aes_ecb, AppKey, padded(16, <<MACPayload/binary, MIC/binary>>)),
PHYPayload = crypto:crypto_one_time(aes_ecb, AppKey, padded(16, <<MACPayload/binary, MIC/binary>>), false),
{ok, Node, <<MHDR/binary, PHYPayload/binary>>}.

encode_cflist(List) when is_list(List), length(List) > 0, length(List) =< 5 ->
Expand Down Expand Up @@ -531,7 +531,7 @@ sign_frame(Confirmed, DevAddr, NwkSKey, FCnt, MACPayload) ->
true -> 2#101
end,
Msg = <<MType:3, 0:3, 0:2, MACPayload/binary>>,
MIC = crypto:cmac(aes_cbc128, NwkSKey, <<(b0(1, DevAddr, FCnt, byte_size(Msg)))/binary, Msg/binary>>, 4),
MIC = crypto:macN(cmac, aes_128_cbc, NwkSKey, <<(b0(1, DevAddr, FCnt, byte_size(Msg)))/binary, Msg/binary>>, 4),
<<Msg/binary, MIC/binary>>.

bool_to_pending(true) -> 1;
Expand All @@ -543,11 +543,11 @@ cipher(Bin, Key, Dir, DevAddr, FCnt) ->
cipher(Bin, Key, Dir, DevAddr, FCnt, 1, <<>>).

cipher(<<Block:16/binary, Rest/binary>>, Key, Dir, DevAddr, FCnt, I, Acc) ->
Si = crypto:block_encrypt(aes_ecb, Key, ai(Dir, DevAddr, FCnt, I)),
Si = crypto:crypto_one_time(aes_ecb, Key, ai(Dir, DevAddr, FCnt, I), true),
cipher(Rest, Key, Dir, DevAddr, FCnt, I+1, <<(binxor(Block, Si, <<>>))/binary, Acc/binary>>);
cipher(<<>>, _Key, _Dir, _DevAddr, _FCnt, _I, Acc) -> Acc;
cipher(<<LastBlock/binary>>, Key, Dir, DevAddr, FCnt, I, Acc) ->
Si = crypto:block_encrypt(aes_ecb, Key, ai(Dir, DevAddr, FCnt, I)),
Si = crypto:crypto_one_time(aes_ecb, Key, ai(Dir, DevAddr, FCnt, I), true),
<<(binxor(LastBlock, binary:part(Si, 0, byte_size(LastBlock)), <<>>))/binary, Acc/binary>>.

ai(Dir, DevAddr, FCnt, I) ->
Expand Down
6 changes: 3 additions & 3 deletions test/test_forwarder.erl
Original file line number Diff line number Diff line change
Expand Up @@ -80,10 +80,10 @@ handle_info({pull_expired, Token}, #state{pull_tokens=Tokens}=State) ->
handle_info({udp, Socket, _, _, <<1, _:16, 3, Data/binary>>},
#state{socket=Socket, motes=Motes}=State) ->
Pk = jsx:decode(Data, [{labels, atom}]),
TxPk = proplists:get_value(txpk, Pk),
Frame = proplists:get_value(data, TxPk),
TxPk = maps:get(txpk, Pk),
Frame = maps:get(data, TxPk),
% send to the device that opened the window
get_mote(proplists:get_value(tmst, TxPk), Motes) ! {ok, Frame},
get_mote(maps:get(tmst, TxPk), Motes) ! {ok, Frame},
{noreply, State}.

store_rxpk(Mote, Frame, #state{motes=Motes, rxpks=Pks}=State) ->
Expand Down
4 changes: 2 additions & 2 deletions test/test_mote.erl
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ encode_frame(MType, FCnt, ADR, ADRACKReq, ACK, FOpts, FPort, FData,
<<FHDR/binary, FPort:8, (reverse(FRMPayload))/binary>>
end,
Msg = <<MType:3, 0:3, 0:2, MACPayload/binary>>,
MIC = crypto:cmac(aes_cbc128, NwkSKey, <<(b0(MType band 1, DevAddr, FCnt, byte_size(Msg)))/binary, Msg/binary>>, 4),
MIC = crypto:macN(cmac, aes_128_cbc, NwkSKey, <<(b0(MType band 1, DevAddr, FCnt, byte_size(Msg)))/binary, Msg/binary>>, 4),
<<Msg/binary, MIC/binary>>.

process_frame(PHYPayload, State) ->
Expand All @@ -100,7 +100,7 @@ process_frame0(MType, Msg, MIC, #state{devaddr=DevAddr, nwkskey=NwkSKey, appskey
<<Port:8, Payload/binary>> -> {Port, Payload}
end,
DevAddr = reverse(DevAddr0),
case crypto:cmac(aes_cbc128, NwkSKey, <<(b0(MType band 1, DevAddr, FCnt, byte_size(Msg)))/binary, Msg/binary>>, 4) of
case crypto:macN(cmac, aes_128_cbc, NwkSKey, <<(b0(MType band 1, DevAddr, FCnt, byte_size(Msg)))/binary, Msg/binary>>, 4) of
MIC ->
case FPort of
0 when FOptsLen == 0 ->
Expand Down