stun-0.9.1/0000755000175000017500000000000012650733700013073 5ustar debalancedebalancestun-0.9.1/rebar.config0000644000175000017500000000045112650733700015355 0ustar debalancedebalance{erl_opts, [debug_info, {i, "include"}]}. {deps, [{p1_tls, ".*", {git, "https://github.com/processone/tls", {tag, "1.0.0"}}}, {p1_utils, ".*", {git, "https://github.com/processone/p1_utils", {tag, "1.0.3"}}}]}. %% Local Variables: %% mode: erlang %% End: %% vim: set filetype=erlang tabstop=8: stun-0.9.1/include/0000755000175000017500000000000012650733700014516 5ustar debalancedebalancestun-0.9.1/include/stun.hrl0000644000175000017500000000721712650733700016225 0ustar debalancedebalance%%%------------------------------------------------------------------- %%% File : stun.hrl %%% Author : Evgeniy Khramtsov %%% Description : STUN values %%% Created : 8 Aug 2009 by Evgeniy Khramtsov %%% %%% %%% stun, Copyright (C) 2002-2015 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., 59 Temple Place, Suite 330, Boston, MA %%% 02111-1307 USA %%% %%%------------------------------------------------------------------- -define(STUN_MAGIC, 16#2112a442). %% I know, this is terrible. Refer to 'STUN Message Structure' of %% RFC5389 to understand this. -define(STUN_METHOD(Type), ((Type band 16#3e00) bsr 2) bor ((Type band 16#e0) bsr 1) bor (Type band 16#f)). -define(STUN_CLASS(Type), ((Type band 16#100) bsr 7) bor ((Type band 16#10) bsr 4)). -define(STUN_TYPE(C, M), (((M band 16#f80) bsl 2) bor ((M band 16#70) bsl 1) bor (M band 16#f) ) bor (((C band 16#2) bsl 7) bor ((C band 16#1) bsl 4))). -define(is_required(A), (A =< 16#7fff)). -define(STUN_METHOD_BINDING, 16#001). -define(STUN_METHOD_ALLOCATE, 16#003). -define(STUN_METHOD_REFRESH, 16#004). -define(STUN_METHOD_SEND, 16#006). -define(STUN_METHOD_DATA, 16#007). -define(STUN_METHOD_CREATE_PERMISSION, 16#008). -define(STUN_METHOD_CHANNEL_BIND, 16#009). %% Comprehension-required range (0x0000-0x7FFF) -define(STUN_ATTR_MAPPED_ADDRESS, 16#0001). -define(STUN_ATTR_USERNAME, 16#0006). -define(STUN_ATTR_MESSAGE_INTEGRITY, 16#0008). -define(STUN_ATTR_ERROR_CODE, 16#0009). -define(STUN_ATTR_UNKNOWN_ATTRIBUTES, 16#000a). -define(STUN_ATTR_REALM, 16#0014). -define(STUN_ATTR_NONCE, 16#0015). -define(STUN_ATTR_XOR_MAPPED_ADDRESS, 16#0020). -define(STUN_ATTR_CHANNEL_NUMBER, 16#000c). -define(STUN_ATTR_LIFETIME, 16#000d). -define(STUN_ATTR_XOR_PEER_ADDRESS, 16#0012). -define(STUN_ATTR_DATA, 16#0013). -define(STUN_ATTR_XOR_RELAYED_ADDRESS, 16#0016). -define(STUN_ATTR_EVEN_PORT, 16#0018). -define(STUN_ATTR_REQUESTED_TRANSPORT, 16#0019). -define(STUN_ATTR_DONT_FRAGMENT, 16#001a). -define(STUN_ATTR_RESERVATION_TOKEN, 16#0022). %% Comprehension-optional range (0x8000-0xFFFF) -define(STUN_ATTR_SOFTWARE, 16#8022). -define(STUN_ATTR_ALTERNATE_SERVER, 16#8023). -define(STUN_ATTR_FINGERPRINT, 16#8028). -record(stun, {class = request :: request | response | error | indication, method = ?STUN_METHOD_BINDING :: non_neg_integer(), magic = ?STUN_MAGIC :: non_neg_integer(), trid = 0 :: non_neg_integer(), raw = <<>> :: binary(), unsupported = [], 'ALTERNATE-SERVER', 'CHANNEL-NUMBER', 'DATA', 'DONT-FRAGMENT' = false, 'ERROR-CODE', 'LIFETIME', 'MAPPED-ADDRESS', 'MESSAGE-INTEGRITY', 'NONCE', 'REALM', 'REQUESTED-TRANSPORT', 'SOFTWARE', 'UNKNOWN-ATTRIBUTES' = [], 'USERNAME', 'XOR-MAPPED-ADDRESS', 'XOR-PEER-ADDRESS' = [], 'XOR-RELAYED-ADDRESS'}). -record(turn, {channel = 0 :: non_neg_integer(), data = <<>> :: binary()}). %% Workarounds. %%-define(NO_PADDING, true). stun-0.9.1/Makefile0000644000175000017500000000027612650733700014540 0ustar debalancedebalanceall: deps/% src deps/%: rebar get-deps src: rebar compile clean: rebar clean doc: rebar skip_deps=true doc test: all rebar -v skip_deps=true eunit .PHONY: clean src all doc rebar stun-0.9.1/src/0000755000175000017500000000000012650733700013662 5ustar debalancedebalancestun-0.9.1/src/p1_stun.app.src0000644000175000017500000000116112650733700016542 0ustar debalancedebalance%%%------------------------------------------------------------------- %%% @author Evgeniy Khramtsov %%% @copyright (C) 2013, Evgeniy Khramtsov %%% @doc %%% %%% @end %%% Created : 4 Apr 2013 by Evgeniy Khramtsov %%%------------------------------------------------------------------- {application, p1_stun, [{description, "STUN library"}, {vsn, "0.9.0"}, {modules, []}, {registered, []}, {applications, [kernel, stdlib]}, {mod, {stun_app,[]}}]}. %% Local Variables: %% mode: erlang %% End: %% vim: set filetype=erlang tabstop=8: stun-0.9.1/src/turn_sm.erl0000644000175000017500000000536312650733700016064 0ustar debalancedebalance%%%------------------------------------------------------------------- %%% File : turn_sm.erl %%% Author : Evgeniy Khramtsov %%% Description : Registers TURN sessions and credentials %%% Created : 23 Aug 2009 by Evgeniy Khramtsov %%% %%% %%% stun, Copyright (C) 2002-2015 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., 59 Temple Place, Suite 330, Boston, MA %%% 02111-1307 USA %%% %%%------------------------------------------------------------------- -module(turn_sm). -behaviour(gen_server). %% API -export([start_link/0, start/0, find_allocation/1, add_allocation/5, del_allocation/3]). %% gen_server callbacks -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -include("stun.hrl"). -record(state, {}). %%==================================================================== %% API %%==================================================================== start() -> gen_server:start({local, ?MODULE}, ?MODULE, [], []). start_link() -> gen_server:start_link({local, ?MODULE}, ?MODULE, [], []). find_allocation(AddrPort) -> case ets:lookup(turn_allocs, AddrPort) of [{_, Pid}] -> {ok, Pid}; _ -> {error, notfound} end. add_allocation(AddrPort, _User, _Realm, _MaxAllocs, Pid) -> ets:insert(turn_allocs, {AddrPort, Pid}), ok. del_allocation(AddrPort, _User, _Realm) -> ets:delete(turn_allocs, AddrPort), ok. %%==================================================================== %% gen_server callbacks %%==================================================================== init([]) -> ets:new(turn_allocs, [named_table, public]), {ok, #state{}}. handle_call(_Request, _From, State) -> {reply, {error, badarg}, State}. handle_cast(_Msg, State) -> {noreply, State}. handle_info(_Info, State) -> {noreply, State}. terminate(_Reason, _State) -> ok. code_change(_OldVsn, State, _Extra) -> {ok, State}. %%-------------------------------------------------------------------- %% Internal functions %%-------------------------------------------------------------------- stun-0.9.1/src/stun_shaper.erl0000644000175000017500000000465712650733700016735 0ustar debalancedebalance%%%---------------------------------------------------------------------- %%% File : stun_shaper.erl %%% Author : Alexey Shchepin %%% Purpose : Functions to control connections traffic %%% Created : 9 Feb 2003 by Alexey Shchepin %%% %%% %%% stun, Copyright (C) 2002-2015 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., 59 Temple Place, Suite 330, Boston, MA %%% 02111-1307 USA %%% %%%---------------------------------------------------------------------- -module(stun_shaper). -author('alexey@process-one.net'). -export([new/1, update/2]). -record(maxrate, {maxrate = 0 :: integer(), lastrate = 0.0 :: float(), lasttime = 0 :: integer()}). -type shaper() :: none | #maxrate{}. -export_type([shaper/0]). %%%=================================================================== %%% API %%%=================================================================== -spec new(none | integer()) -> shaper(). new(none) -> none; new(MaxRate) when is_integer(MaxRate) -> #maxrate{maxrate = MaxRate, lastrate = 0.0, lasttime = now_to_usec(now())}. -spec update(shaper(), integer()) -> {shaper(), integer()}. update(none, _Size) -> {none, 0}; update(#maxrate{} = State, Size) -> MinInterv = 1000 * Size / (2 * State#maxrate.maxrate - State#maxrate.lastrate), Interv = (now_to_usec(now()) - State#maxrate.lasttime) / 1000, Pause = if MinInterv > Interv -> 1 + trunc(MinInterv - Interv); true -> 0 end, NextNow = now_to_usec(now()) + Pause * 1000, {State#maxrate{lastrate = (State#maxrate.lastrate + 1000000 * Size / (NextNow - State#maxrate.lasttime)) / 2, lasttime = NextNow}, Pause}. now_to_usec({MSec, Sec, USec}) -> (MSec * 1000000 + Sec) * 1000000 + USec. stun-0.9.1/src/stun_test.erl0000644000175000017500000003704412650733700016426 0ustar debalancedebalance%%%------------------------------------------------------------------- %%% File : stun_test.erl %%% Author : Evgeniy Khramtsov %%% Description : STUN test suite %%% Created : 7 Aug 2009 by Evgeniy Khramtsov %%% %%% %%% stun, Copyright (C) 2002-2015 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., 59 Temple Place, Suite 330, Boston, MA %%% 02111-1307 USA %%% %%%------------------------------------------------------------------- -module(stun_test). -export([bind_udp/2, bind_tcp/2, allocate_udp/5]). -define(STUN_PORT, 34780). -define(STUNS_PORT, 53490). -define(RECV_TIMEOUT, timer:seconds(5)). -define(CHANNEL, 16#4000). -define(REALM, <<"localhost">>). -define(USER, <<"user">>). -define(PASS, <<"pass">>). -include_lib("eunit/include/eunit.hrl"). -include("stun.hrl"). init_test() -> ?assertEqual(ok, application:start(p1_tls)), ?assertEqual(ok, application:start(p1_stun)). mk_cert_test() -> ?assertEqual(ok, file:write_file("certfile.pem", get_cert())). add_udp_listener_test() -> ?assertEqual(ok, stun_listener:add_listener( ?STUN_PORT, udp, [use_turn, {auth_type, user}, {auth_realm, ?REALM}, {auth_fun, fun(?USER, ?REALM) -> ?PASS; (_, _) -> <<"">> end}])). add_tcp_listener_test() -> ?assertEqual(ok, stun_listener:add_listener(?STUN_PORT, tcp, [])). add_tls_listener_test() -> ?assertEqual(ok, stun_listener:add_listener( ?STUNS_PORT, tcp, [tls, {certfile, "certfile.pem"}])). bind_udp_test() -> TrID = mk_trid(), Msg = #stun{method = ?STUN_METHOD_BINDING, class = request, trid = TrID}, {ok, Socket} = gen_udp:open(0, [binary, {ip, {127,0,0,1}}, {active, false}]), {ok, Addr} = inet:sockname(Socket), PktOut = stun_codec:encode(Msg), ?assertEqual(ok, gen_udp:send(Socket, {127,0,0,1}, ?STUN_PORT, PktOut)), {ok, {_, _, PktIn}} = gen_udp:recv(Socket, 0, ?RECV_TIMEOUT), ?assertMatch( {ok, #stun{trid = TrID, 'XOR-MAPPED-ADDRESS' = Addr}}, stun_codec:decode(PktIn, datagram)), ?assertEqual(ok, gen_udp:close(Socket)). bind_tcp_test() -> TrID = mk_trid(), Msg = #stun{method = ?STUN_METHOD_BINDING, class = request, trid = TrID}, {ok, Socket} = gen_tcp:connect({127,0,0,1}, ?STUN_PORT, [binary, {active, false}]), {ok, Addr} = inet:sockname(Socket), Pkt = stun_codec:encode(Msg), ?assertEqual(ok, gen_tcp:send(Socket, Pkt)), ?assertMatch( {ok, #stun{trid = TrID, 'XOR-MAPPED-ADDRESS' = Addr}}, recv(Socket, <<>>, false)), ?assertEqual(ok, gen_tcp:close(Socket)). bind_tls_test() -> TrID = mk_trid(), Msg = #stun{method = ?STUN_METHOD_BINDING, class = request, trid = TrID}, {ok, Socket} = gen_tcp:connect({127,0,0,1}, ?STUNS_PORT, [binary, {active, true}]), {ok, TLSSocket} = p1_tls:tcp_to_tls( Socket, [{certfile, <<"certfile.pem">>}, connect]), ?assertEqual({ok, <<>>}, p1_tls:recv_data(TLSSocket, <<>>)), {ok, Addr} = p1_tls:sockname(TLSSocket), Pkt = stun_codec:encode(Msg), recv(TLSSocket, <<>>, true), ?assertEqual(ok, p1_tls:send(TLSSocket, Pkt)), ?assertMatch( {ok, #stun{trid = TrID, 'XOR-MAPPED-ADDRESS' = Addr}}, recv(TLSSocket, <<>>, true)), ?assertEqual(ok, gen_tcp:close(Socket)). del_tcp_listener_test() -> ?assertEqual(ok, stun_listener:del_listener(?STUN_PORT, tcp)). del_tls_listener_test() -> ?assertEqual(ok, stun_listener:del_listener(?STUNS_PORT, tcp)). allocate_udp_test() -> {ok, Socket} = gen_udp:open(0, [binary, {ip, {127,0,0,1}}, {active, false}]), {ok, PeerSocket} = gen_udp:open(0, [binary, {ip, {127,0,0,1}}, {active, false}]), {ok, PeerAddr} = inet:sockname(PeerSocket), {ok, Addr} = inet:sockname(Socket), %% Allocating address, receiving 401 with nonce and realm TrID1 = mk_trid(), Msg1 = #stun{method = ?STUN_METHOD_ALLOCATE, class = request, trid = TrID1}, PktOut1 = stun_codec:encode(Msg1), ?assertEqual(ok, gen_udp:send(Socket, {127,0,0,1}, ?STUN_PORT, PktOut1)), {ok, {_, _, PktIn1}} = gen_udp:recv(Socket, 0, ?RECV_TIMEOUT), {ok, #stun{trid = TrID1, class = error, 'ERROR-CODE' = {401, _}, 'NONCE' = Nonce, 'REALM' = ?REALM}} = stun_codec:decode(PktIn1, datagram), %% Repeating allocation from the first step TrID2 = mk_trid(), Msg2 = #stun{method = ?STUN_METHOD_ALLOCATE, trid = TrID2, 'REQUESTED-TRANSPORT' = udp, 'NONCE' = Nonce, 'REALM' = ?REALM, 'USERNAME' = ?USER}, PktOut2 = stun_codec:encode(Msg2, {?USER, ?REALM, ?PASS}), ?assertEqual(ok, gen_udp:send(Socket, {127,0,0,1}, ?STUN_PORT, PktOut2)), {ok, {_, _, PktIn2}} = gen_udp:recv(Socket, 0, ?RECV_TIMEOUT), {ok, #stun{trid = TrID2, class = response, 'XOR-RELAYED-ADDRESS' = {RelayIP, RelayPort}, 'XOR-MAPPED-ADDRESS' = Addr}} = stun_codec:decode(PktIn2, datagram), %% Creating permission for the peer TrID3 = mk_trid(), Msg3 = #stun{method = ?STUN_METHOD_CREATE_PERMISSION, trid = TrID3, 'XOR-PEER-ADDRESS' = [PeerAddr], 'NONCE' = Nonce, 'REALM' = ?REALM, 'USERNAME' = ?USER}, PktOut3 = stun_codec:encode(Msg3, {?USER, ?REALM, ?PASS}), ?assertEqual(ok, gen_udp:send(Socket, {127,0,0,1}, ?STUN_PORT, PktOut3)), {ok, {_, _, PktIn3}} = gen_udp:recv(Socket, 0, ?RECV_TIMEOUT), {ok, #stun{trid = TrID3, class = response}} = stun_codec:decode(PktIn3, datagram), %% Sending some data to the peer. Peer receives it. Data1 = crypto:rand_bytes(20), TrID4 = mk_trid(), Msg4 = #stun{method = ?STUN_METHOD_SEND, trid = TrID4, class = indication, 'XOR-PEER-ADDRESS' = [PeerAddr], 'DATA' = Data1}, PktOut4 = stun_codec:encode(Msg4), ?assertEqual(ok, gen_udp:send(Socket, {127,0,0,1}, ?STUN_PORT, PktOut4)), ?assertMatch({ok, {_, _, Data1}}, gen_udp:recv(PeerSocket, 0, ?RECV_TIMEOUT)), %% Peer sends the data back. We receive it. ?assertEqual(ok, gen_udp:send(PeerSocket, RelayIP, RelayPort, Data1)), {ok, {_, _, Data2}} = gen_udp:recv(Socket, 0, ?RECV_TIMEOUT), ?assertMatch( {ok, #stun{'DATA' = Data1, 'XOR-PEER-ADDRESS' = [PeerAddr], class = indication}}, stun_codec:decode(Data2, datagram)), %% We're binding channel for our peer TrID5 = mk_trid(), Msg5 = #stun{method = ?STUN_METHOD_CHANNEL_BIND, trid = TrID5, class = request, 'CHANNEL-NUMBER' = ?CHANNEL, 'XOR-PEER-ADDRESS' = [PeerAddr], 'NONCE' = Nonce, 'REALM' = ?REALM, 'USERNAME' = ?USER}, PktOut5 = stun_codec:encode(Msg5, {?USER, ?REALM, ?PASS}), ?assertEqual(ok, gen_udp:send(Socket, {127,0,0,1}, ?STUN_PORT, PktOut5)), {ok, {_, _, PktIn5}} = gen_udp:recv(Socket, 0, ?RECV_TIMEOUT), ?assertMatch( {ok, #stun{trid = TrID5, class = response}}, stun_codec:decode(PktIn5, datagram)), %% Now we send data to this channel. The peer receives it. Data3 = crypto:rand_bytes(20), Msg6 = #turn{channel = ?CHANNEL, data = Data3}, PktOut6 = stun_codec:encode(Msg6), ?assertEqual(ok, gen_udp:send(Socket, {127,0,0,1}, ?STUN_PORT, PktOut6)), ?assertMatch({ok, {_, _, Data3}}, gen_udp:recv(PeerSocket, 0, ?RECV_TIMEOUT)), %% The peer sends the data back. We receive it. ?assertEqual(ok, gen_udp:send(PeerSocket, RelayIP, RelayPort, Data3)), {ok, {_, _, Data4}} = gen_udp:recv(Socket, 0, ?RECV_TIMEOUT), ?assertMatch( {ok, #turn{channel = ?CHANNEL, data = Data3}}, stun_codec:decode(Data4, datagram)), %% Destroying the allocation via Refresh method (with LIFETIME set to zero) TrID7 = mk_trid(), Msg7 = #stun{method = ?STUN_METHOD_REFRESH, trid = TrID7, 'LIFETIME' = 0, 'NONCE' = Nonce, 'REALM' = ?REALM, 'USERNAME' = ?USER}, PktOut7 = stun_codec:encode(Msg7, {?USER, ?REALM, ?PASS}), ?assertEqual(ok, gen_udp:send(Socket, {127,0,0,1}, ?STUN_PORT, PktOut7)), {ok, {_, _, PktIn7}} = gen_udp:recv(Socket, 0, ?RECV_TIMEOUT), ?assertMatch( {ok, #stun{trid = TrID7, 'LIFETIME' = 0, class = response}}, stun_codec:decode(PktIn7, datagram)), ?assertEqual(ok, gen_udp:close(PeerSocket)), ?assertEqual(ok, gen_udp:close(Socket)). %%-------------------------------------------------------------------- %% External functions %%-------------------------------------------------------------------- bind_udp(Host, Port) -> TrID = mk_trid(), MsgOut = #stun{method = ?STUN_METHOD_BINDING, class = request, trid = TrID}, try {ok, Socket} = gen_udp:open(0, [binary, {active, false}]), PktOut = stun_codec:encode(MsgOut), ok = gen_udp:send(Socket, Host, Port, PktOut), {ok, {_, _, PktIn}} = gen_udp:recv(Socket, 0, ?RECV_TIMEOUT), {ok, MsgIn = #stun{trid = TrID, 'XOR-MAPPED-ADDRESS' = _Addr}} = stun_codec:decode(PktIn, datagram), gen_udp:close(Socket), MsgIn catch _:{badmatch, Err} -> Err end. bind_tcp(Host, Port) -> TrID = mk_trid(), MsgOut = #stun{method = ?STUN_METHOD_BINDING, class = request, trid = TrID}, try {ok, Socket} = gen_tcp:connect(Host, Port, [binary, {active, false}]), Pkt = stun_codec:encode(MsgOut), ok = gen_tcp:send(Socket, Pkt), {ok, MsgIn = #stun{trid = TrID, 'XOR-MAPPED-ADDRESS' = _Addr}} = recv(Socket, <<>>, false), gen_tcp:close(Socket), MsgIn catch _:{badmatch, Err} -> Err end. allocate_udp(Host, Port, User, Realm, Pass) -> try {ok, Socket} = gen_udp:open(0, [binary, {active, false}]), %% Allocating address, receiving 401 with nonce and realm TrID1 = mk_trid(), Msg1 = #stun{method = ?STUN_METHOD_ALLOCATE, class = request, trid = TrID1}, PktOut1 = stun_codec:encode(Msg1), ok = gen_udp:send(Socket, Host, Port, PktOut1), {ok, {_, _, PktIn1}} = gen_udp:recv(Socket, 0, ?RECV_TIMEOUT), {ok, #stun{trid = TrID1, class = error, 'ERROR-CODE' = {401, _}, 'NONCE' = Nonce, 'REALM' = Realm}} = stun_codec:decode(PktIn1, datagram), %% Repeating allocation from the first step TrID2 = mk_trid(), Msg2 = #stun{method = ?STUN_METHOD_ALLOCATE, trid = TrID2, 'REQUESTED-TRANSPORT' = udp, 'NONCE' = Nonce, 'REALM' = Realm, 'USERNAME' = User}, PktOut2 = stun_codec:encode(Msg2, {User, Realm, Pass}), ok = gen_udp:send(Socket, Host, Port, PktOut2), {ok, {_, _, PktIn2}} = gen_udp:recv(Socket, 0, ?RECV_TIMEOUT), {ok, #stun{trid = TrID2, class = response, 'XOR-MAPPED-ADDRESS' = _Addr}} = stun_codec:decode(PktIn2, datagram), %% Destroying the allocation via Refresh method (with LIFETIME set to zero) TrID7 = mk_trid(), Msg7 = #stun{method = ?STUN_METHOD_REFRESH, trid = TrID7, 'LIFETIME' = 0, 'NONCE' = Nonce, 'REALM' = Realm, 'USERNAME' = User}, PktOut7 = stun_codec:encode(Msg7, {User, Realm, Pass}), ok = gen_udp:send(Socket, Host, Port, PktOut7), {ok, {_, _, PktIn7}} = gen_udp:recv(Socket, 0, ?RECV_TIMEOUT), {ok, #stun{trid = TrID7, 'LIFETIME' = 0, class = response}} = stun_codec:decode(PktIn7, datagram), gen_udp:close(Socket) catch _:{badmatch, Err} -> Err end. %%-------------------------------------------------------------------- %%% Internal functions %%-------------------------------------------------------------------- recv(Socket, Buf, false) -> {ok, Data} = gen_tcp:recv(Socket, 0, ?RECV_TIMEOUT), NewBuf = <>, case stun_codec:decode(NewBuf, stream) of {ok, Msg, _Tail} -> {ok, Msg}; empty -> recv(Socket, <<>>, false); more -> recv(Socket, NewBuf, false) end; recv(TLSSocket, Buf, true) -> receive {tcp, _Sock, TLSData} -> {ok, Data} = p1_tls:recv_data(TLSSocket, TLSData), NewBuf = <>, case stun_codec:decode(NewBuf, stream) of {ok, Msg, _Tail} -> {ok, Msg}; empty -> recv(TLSSocket, <<>>, true); more -> recv(TLSSocket, NewBuf, true) end after 100 -> ok end. mk_trid() -> {A, B, C} = now(), random:seed(A, B, C), random:uniform(1 bsl 96). get_cert() -> <<"-----BEGIN CERTIFICATE----- MIIDtTCCAp2gAwIBAgIJANlKDLlVYd/VMA0GCSqGSIb3DQEBCwUAMEUxCzAJBgNV BAYTAkFVMRMwEQYDVQQIEwpTb21lLVN0YXRlMSEwHwYDVQQKExhJbnRlcm5ldCBX aWRnaXRzIFB0eSBMdGQwHhcNMTQwNTA2MDQ1MzUzWhcNNDEwOTIxMDQ1MzUzWjBF MQswCQYDVQQGEwJBVTETMBEGA1UECBMKU29tZS1TdGF0ZTEhMB8GA1UEChMYSW50 ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB CgKCAQEAtTUN+zzYHZxsmK3/OfAa8M8dA61k6B3pKF4FqlBFXsih0ug7HJFFSuBf yt6mmtmNwiyYuj8Wjq+Ab97tVGscuuhrG+6tiL07L8zTUtJF9CbO9cq0+d/0axDH AhMdxjfIhtXUNJGvjvF7gPR63nRkBFc1+K/JgJKLRRTj3pWW2LKX9DZoI+VzUFDG Aaky1pbcTqfTy0OlPx2cGWB8/3XcNCaqdx+AgX65GJl3GaaJ8D60FtDv0Nfjnctt /qnefYiEKFugqJz5kDGC3wiHEhlJDY5qzKcYVm3jFsOmnLDOPQ82Sb5j2ZUroxM7 lwZAnCnVVIGlXWLA5snuxxcS4LJPTQIDAQABo4GnMIGkMB0GA1UdDgQWBBT0FCNT iq3HJPNAiOIpadSMgJU/LzB1BgNVHSMEbjBsgBT0FCNTiq3HJPNAiOIpadSMgJU/ L6FJpEcwRTELMAkGA1UEBhMCQVUxEzARBgNVBAgTClNvbWUtU3RhdGUxITAfBgNV BAoTGEludGVybmV0IFdpZGdpdHMgUHR5IEx0ZIIJANlKDLlVYd/VMAwGA1UdEwQF MAMBAf8wDQYJKoZIhvcNAQELBQADggEBABYy3wmp7MvyXM/JN5gJI39vo57XZSCa nXV/g09z8xP5MYvdUdKLXlss1211+9GNb4l5z545HDgg55fBeHhqw5x9H/gFNM4i ueSVWDdMaTQ7poE9u3aPeKiS+vhMvzpnFo2Ss21DznBqvWxh+4UpoT3sV9A0crV1 LP4GpbIbFJGW50UTg09NYl0qxTWU1yldrlSXZduV8+Oi4I1+KMgH3H/YD2oU8Olu KP3TakDiw45YW43Dn5ElljXKjq7xKxbv+PRbYM3/4odQot12tdpKyI9MLJZxUXjW VEqVAR0K1ssVEpXBE5QqD5Od5YV0zD1JTtaBqcYrqxngn8nujPgFXDo= -----END CERTIFICATE----- -----BEGIN PRIVATE KEY----- MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQC1NQ37PNgdnGyY rf858Brwzx0DrWToHekoXgWqUEVeyKHS6DsckUVK4F/K3qaa2Y3CLJi6PxaOr4Bv 3u1Uaxy66Gsb7q2IvTsvzNNS0kX0Js71yrT53/RrEMcCEx3GN8iG1dQ0ka+O8XuA 9HredGQEVzX4r8mAkotFFOPelZbYspf0Nmgj5XNQUMYBqTLWltxOp9PLQ6U/HZwZ YHz/ddw0Jqp3H4CBfrkYmXcZponwPrQW0O/Q1+Ody23+qd59iIQoW6ConPmQMYLf CIcSGUkNjmrMpxhWbeMWw6acsM49DzZJvmPZlSujEzuXBkCcKdVUgaVdYsDmye7H FxLgsk9NAgMBAAECggEAWeC40JZ7MyS1EH2tDBW1px9zarGETUUYsncAJFuwLLUi 3rNlLmQ3lE359Wu+AyxJDbiFAEvualNORy6xVJ/UHjjNd4tI83u4cZsMbhXxsInX OT6TySR13OzzaGoG6JwekBJbML/Z7fKEqY+ZqeDdAvImyPSX43fMMDWOWIalzVDi II63zd2KRklToDGfV1geEaa1NVIQucPnOQOjrID7bIDpg6UvtZkOJzZG8fhEpM19 UpYphT14UO1w8fCxSu7+V3GIDuTnYKDg98WTQejeCZk28/MIYnzAy4H5uyQFu+IJ YieWRy2RICPTDq4OUEA9bLGgFmcvGxX2sg3elVkPgQKBgQDd6i1szwNY20iDt8P5 nn4R9E+S8iPNMswIi9PM88p5Ig44eLSRkSy3nnRdFHlu3lRvsWykKT6iTVsJCmK9 1j6FsJ9xd8ozZTdXiBRrOhNb6JjcYGWfIcsParAth/P+luFv9VhKMjuqNjRNAWwn 0zeT6+HQ8W2IN4sLSRDxaiLUPQKBgQDRCjuyaneYKrDjoRk4lNu+krIK6q05V87V 96gm4qIUKZvnCN7tqCC1ETVzKyhsQfRUvrQi3U0yhV018Um7hQdLZFCwJ/Ku8F2v 2OD2mNBLeRtKjwSoDXxqfEAJ0sZJS1xXHF13HR7g0LVjJzHheyHfhmat4QJEXp+6 JVuC86xIUQKBgFbiR9SxHFNez35apY0G478t0zXqPeAqQj4aWNuGm8BfeAfeInxX xZVCobaLvJuOyqpMYgfH6jDrbngUq+I9jo8TPunTB8SlnUxVCAGPZGL4p1ipGUB7 n6AymjXJY9tKwYrvGRk7n6adwE5h/zF8fecZVHlU/Rh2/qZ1ff+3GVnVAoGALYuE PDhUPFQ43C+ydhCA3EHMBvLgsRi/mQDvoyFH3Qq/zBOztqYmEi1gruodUZEBMiGm z93Vvwctqt4aiX/Peg6uQeNCTflTAEhJo5Dh+T+2wYTtp8vgarcNoNZKm5eO0+/7 MUOoAaWXj7XveUhBthjrcEERJGJVfNI84QhEZjECgYEAgFga2Cw7LxZ9Sc8I+a5O 7nLykkHLOq1fMs2byjX2A7LcxPuq0ebSiFWQ/0avbS8QoTMSJLrFCnt9DJ8JDxX4 j7iD63xhs0Ue1eW2l2QX5q9iCUXfcjsSo6FJ5wFqp4GYkMMsoP99/toEifz9qxLN ySqCx+ihshDA0yipJbUuU2c= -----END PRIVATE KEY-----">>. stun-0.9.1/src/turn.erl0000644000175000017500000004114212650733700015360 0ustar debalancedebalance%%%------------------------------------------------------------------- %%% File : turn.erl %%% Author : Evgeniy Khramtsov %%% Description : Handles TURN allocations, see RFC5766 %%% Created : 23 Aug 2009 by Evgeniy Khramtsov %%% %%% %%% stun, Copyright (C) 2002-2015 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., 59 Temple Place, Suite 330, Boston, MA %%% 02111-1307 USA %%% %%%------------------------------------------------------------------- -module(turn). -define(GEN_FSM, gen_fsm). -behaviour(?GEN_FSM). %% API -export([start_link/1, start/1, stop/1, route/2]). %% gen_fsm callbacks -export([init/1, handle_event/3, handle_sync_event/4, handle_info/3, terminate/3, code_change/4]). %% gen_fsm states -export([wait_for_allocate/2, active/2]). -include("stun.hrl"). %%-define(debug, true). -ifdef(debug). -define(dbg(Str, Args), error_logger:info_msg(Str, Args)). -else. -define(dbg(Str, Args), ok). -endif. -define(MAX_LIFETIME, 3600000). %% 1 hour -define(DEFAULT_LIFETIME, 300000). %% 5 minutes -define(PERMISSION_LIFETIME, 300000). %% 5 minutes -define(CHANNEL_LIFETIME, 600000). %% 10 minutes -define(DICT, dict). -type addr() :: {inet:ip_address(), inet:port_number()}. -record(state, {sock_mod = gen_udp :: gen_udp | gen_tcp | p1_tls, sock :: inet:socket() | p1_tls:tls_socket(), addr = {{0,0,0,0}, 0} :: addr(), owner = self() :: pid(), username = <<"">> :: binary(), realm = <<"">> :: binary(), key = {<<"">>, <<"">>, <<"">>} :: {binary(), binary(), binary()}, server_name = <<"">> :: binary(), permissions = ?DICT:new(), channels = ?DICT:new(), max_permissions :: non_neg_integer() | atom(), relay_ip = {127,0,0,1} :: inet:ip_address(), min_port = 49152 :: non_neg_integer(), max_port = 65535 :: non_neg_integer(), relay_addr :: addr(), relay_sock :: inet:socket(), last_trid :: non_neg_integer(), last_pkt = <<>> :: binary(), seq = 1 :: non_neg_integer(), life_timer :: reference()}). %%==================================================================== %% API %%==================================================================== start_link(Opts) -> ?GEN_FSM:start_link(?MODULE, [Opts], []). start(Opts) -> supervisor:start_child(turn_tmp_sup, [Opts]). stop(Pid) -> ?GEN_FSM:send_all_state_event(Pid, stop). route(Pid, Msg) -> ?GEN_FSM:send_event(Pid, Msg). %%==================================================================== %% gen_fsm callbacks %%==================================================================== init([Opts]) -> Owner = proplists:get_value(owner, Opts), Username = proplists:get_value(username, Opts), Realm = proplists:get_value(realm, Opts), AddrPort = proplists:get_value(addr, Opts), State = #state{sock_mod = proplists:get_value(sock_mod, Opts), sock = proplists:get_value(sock, Opts), key = proplists:get_value(key, Opts), relay_ip = proplists:get_value(relay_ip, Opts), min_port = proplists:get_value(min_port, Opts), max_port = proplists:get_value(max_port, Opts), max_permissions = proplists:get_value(max_permissions, Opts), server_name = proplists:get_value(server_name, Opts), realm = Realm, addr = AddrPort, username = Username, owner = Owner}, MaxAllocs = proplists:get_value(max_allocs, Opts), if is_pid(Owner) -> erlang:monitor(process, Owner); true -> ok end, TRef = erlang:start_timer(?DEFAULT_LIFETIME, self(), stop), {A1, A2, A3} = now(), random:seed(A1, A2, A3), case turn_sm:add_allocation(AddrPort, Username, Realm, MaxAllocs, self()) of ok -> {ok, wait_for_allocate, State#state{life_timer = TRef}}; {error, Reason} -> {stop, Reason} end. wait_for_allocate(#stun{class = request, method = ?STUN_METHOD_ALLOCATE} = Msg, State) -> Resp = prepare_response(State, Msg), if Msg#stun.'REQUESTED-TRANSPORT' == undefined -> R = Resp#stun{class = error, 'ERROR-CODE' = stun_codec:error(400)}, {stop, normal, send(State, R)}; Msg#stun.'REQUESTED-TRANSPORT' == unknown -> R = Resp#stun{class = error, 'ERROR-CODE' = stun_codec:error(442)}, {stop, normal, send(State, R)}; Msg#stun.'DONT-FRAGMENT' == true -> R = Resp#stun{class = error, 'UNKNOWN-ATTRIBUTES' = [?STUN_ATTR_DONT_FRAGMENT], 'ERROR-CODE' = stun_codec:error(420)}, {stop, normal, send(State, R)}; true -> case allocate_addr({State#state.min_port, State#state.max_port}) of {ok, RelayPort, RelaySock} -> Lifetime = time_left(State#state.life_timer), AddrPort = State#state.addr, RelayAddr = {State#state.relay_ip, RelayPort}, error_logger:info_msg( "created TURN allocation for ~s@~s from ~s: ~s", [State#state.username, State#state.realm, addr_to_str(AddrPort), addr_to_str(RelayAddr)]), R = Resp#stun{class = response, 'XOR-RELAYED-ADDRESS' = RelayAddr, 'LIFETIME' = Lifetime, 'XOR-MAPPED-ADDRESS' = AddrPort}, NewState = send(State, R), {next_state, active, NewState#state{relay_sock = RelaySock, relay_addr = RelayAddr}}; Err -> error_logger:error_msg( "unable to allocate relay port for ~s@~s: ~s", [State#state.username, State#state.realm, format_error(Err)]), R = Resp#stun{class = error, 'ERROR-CODE' = stun_codec:error(508)}, {stop, normal, send(State, R)} end end; wait_for_allocate(Event, State) -> error_logger:error_msg("unexpected event in wait_for_allocate: ~p", [Event]), {next_state, wait_for_allocate, State}. active(#stun{trid = TrID}, #state{last_trid = TrID} = State) -> send(State, State#state.last_pkt), {next_state, active, State}; active(#stun{class = request, method = ?STUN_METHOD_ALLOCATE} = Msg, State) -> Resp = prepare_response(State, Msg), R = Resp#stun{class = error, 'ERROR-CODE' = stun_codec:error(437)}, {next_state, active, send(State, R)}; active(#stun{class = request, method = ?STUN_METHOD_REFRESH} = Msg, State) -> Resp = prepare_response(State, Msg), case Msg#stun.'LIFETIME' of 0 -> R = Resp#stun{class = response, 'LIFETIME' = 0}, {stop, normal, send(State, R)}; LifeTime -> cancel_timer(State#state.life_timer), MSecs = if LifeTime == undefined -> ?DEFAULT_LIFETIME; true -> lists:min([LifeTime*1000, ?MAX_LIFETIME]) end, TRef = erlang:start_timer(MSecs, self(), stop), R = Resp#stun{class = response, 'LIFETIME' = (MSecs div 1000)}, {next_state, active, send(State#state{life_timer = TRef}, R)} end; active(#stun{class = request, 'XOR-PEER-ADDRESS' = XorPeerAddrs, method = ?STUN_METHOD_CREATE_PERMISSION} = Msg, State) -> Resp = prepare_response(State, Msg), PermLen = ?DICT:size(State#state.permissions) + length(XorPeerAddrs), if XorPeerAddrs == [] -> R = Resp#stun{class = error, 'ERROR-CODE' = stun_codec:error(400)}, {next_state, active, send(State, R)}; PermLen < State#state.max_permissions -> Perms = lists:foldl( fun({Addr, _Port}, Acc) -> Channel = case ?DICT:find(Addr, Acc) of {ok, {Chan, OldTRef}} -> cancel_timer(OldTRef), Chan; error -> undefined end, TRef = erlang:start_timer( ?PERMISSION_LIFETIME, self(), {permission_timeout, Addr}), error_logger:info_msg( "created/updated TURN permission for user " "~s@~s from ~s: ~s <-> ~s", [State#state.username, State#state.realm, addr_to_str(State#state.addr), addr_to_str(State#state.relay_addr), addr_to_str({Addr, _Port})]), ?DICT:store(Addr, {Channel, TRef}, Acc) end, State#state.permissions, XorPeerAddrs), NewState = State#state{permissions = Perms}, R = Resp#stun{class = response}, {next_state, active, send(NewState, R)}; true -> R = Resp#stun{class = error, 'ERROR-CODE' = stun_codec:error(508)}, {next_state, active, send(State, R)} end; active(#stun{class = indication, method = ?STUN_METHOD_SEND, 'XOR-PEER-ADDRESS' = [{Addr, Port}], 'DATA' = Data}, State) when is_binary(Data) -> case ?DICT:find(Addr, State#state.permissions) of {ok, _} -> gen_udp:send(State#state.relay_sock, Addr, Port, Data); error -> ok end, {next_state, active, State}; active(#stun{class = request, 'CHANNEL-NUMBER' = Channel, 'XOR-PEER-ADDRESS' = [{Addr, Port}], method = ?STUN_METHOD_CHANNEL_BIND} = Msg, State) when is_integer(Channel), Channel >= 16#4000, Channel =< 16#7ffe -> Resp = prepare_response(State, Msg), AddrPort = {Addr, Port}, case ?DICT:find(Channel, State#state.channels) of {ok, {AddrPort, OldTRef}} -> cancel_timer(OldTRef), TRef = erlang:start_timer(?CHANNEL_LIFETIME, self(), {channel_timeout, Channel}), Chans = ?DICT:store(Channel, {AddrPort, TRef}, State#state.channels), NewState = State#state{channels = Chans}, R = Resp#stun{class = response}, {next_state, active, send(NewState, R)}; error -> case ?DICT:find(Addr, State#state.permissions) of {ok, {undefined, PermTRef}} -> ChanTRef = erlang:start_timer( ?CHANNEL_LIFETIME, self(), {channel_timeout, Channel}), Perms = ?DICT:store(Addr, {Channel, PermTRef}, State#state.permissions), Chans = ?DICT:store(Channel, {AddrPort, ChanTRef}, State#state.channels), NewState = State#state{channels = Chans, permissions = Perms}, R = Resp#stun{class = response}, {next_state, active, send(NewState, R)}; _ -> R = Resp#stun{class = error, 'ERROR-CODE' = stun_codec:error(400)}, {next_state, active, send(State, R)} end end; active(#stun{class = request, method = ?STUN_METHOD_CHANNEL_BIND} = Msg, State) -> Resp = prepare_response(State, Msg), R = Resp#stun{class = error, 'ERROR-CODE' = stun_codec:error(400)}, {next_state, active, send(State, R)}; active(#turn{channel = Channel, data = Data}, State) -> case ?DICT:find(Channel, State#state.channels) of {ok, {{Addr, Port}, _}} -> gen_udp:send(State#state.relay_sock, Addr, Port, Data), {next_state, active, State}; error -> {next_state, active, State} end; active(Event, State) -> error_logger:error_msg("got unexpected event in active: ~p", [Event]), {next_state, active, State}. handle_event(stop, _StateName, State) -> {stop, normal, State}; handle_event(Event, StateName, State) -> error_logger:error_msg("got unexpected event in ~s: ~p", [StateName, Event]), {next_state, StateName, State}. handle_sync_event(_Event, _From, StateName, State) -> {reply, {error, badarg}, StateName, State}. handle_info({udp, Sock, Addr, Port, Data}, StateName, State) -> inet:setopts(Sock, [{active, once}]), case ?DICT:find(Addr, State#state.permissions) of {ok, {undefined, _}} -> Seq = State#state.seq, Ind = #stun{class = indication, method = ?STUN_METHOD_DATA, trid = Seq, 'XOR-PEER-ADDRESS' = [{Addr, Port}], 'DATA' = Data}, {next_state, StateName, send(State#state{seq = Seq+1}, Ind)}; {ok, {Channel, _}} -> TurnMsg = #turn{channel = Channel, data = Data}, {next_state, StateName, send(State, TurnMsg)}; error -> {next_state, StateName, State} end; handle_info({timeout, _Tref, stop}, _StateName, State) -> {stop, normal, State}; handle_info({timeout, _Tref, {permission_timeout, Addr}}, StateName, State) -> ?dbg("permission for ~s timed out", [Addr]), case ?DICT:find(Addr, State#state.permissions) of {ok, {Channel, _}} -> Perms = ?DICT:erase(Addr, State#state.permissions), Chans = case ?DICT:find(Channel, State#state.channels) of {ok, {_, TRef}} -> cancel_timer(TRef), ?DICT:erase(Channel, State#state.channels); error -> State#state.channels end, {next_state, StateName, State#state{permissions = Perms, channels = Chans}}; error -> {next_state, StateName, State} end; handle_info({timeout, _Tref, {channel_timeout, Channel}}, StateName, State) -> ?dbg("channel ~p timed out", [Channel]), case ?DICT:find(Channel, State#state.channels) of {ok, {{Addr, _Port}, _}} -> Chans = ?DICT:erase(Channel, State#state.channels), Perms = case ?DICT:find(Addr, State#state.permissions) of {ok, {_, TRef}} -> ?DICT:store(Addr, {undefined, TRef}, State#state.permissions); error -> State#state.permissions end, {next_state, StateName, State#state{channels = Chans, permissions = Perms}}; error -> {next_state, StateName, State} end; handle_info({'DOWN', _Ref, _, _, _}, _StateName, State) -> {stop, normal, State}; handle_info(Info, StateName, State) -> error_logger:error_msg("got unexpected info in ~p: ~p", [StateName, Info]), {next_state, StateName, State}. terminate(_Reason, _StateName, State) -> AddrPort = State#state.addr, Username = State#state.username, Realm = State#state.realm, case State#state.relay_addr of undefined -> ok; RAddrPort -> error_logger:info_msg( "deleting TURN allocation for ~s@~s from ~s: ~s", [Username, Realm, addr_to_str(AddrPort), addr_to_str(RAddrPort)]) end, if is_pid(State#state.owner) -> stun:stop(State#state.owner); true -> ok end, turn_sm:del_allocation(AddrPort, Username, Realm). code_change(_OldVsn, StateName, State, _Extra) -> {ok, StateName, State}. %%-------------------------------------------------------------------- %%% Internal functions %%-------------------------------------------------------------------- send(State, Pkt) when is_binary(Pkt) -> SockMod = State#state.sock_mod, Sock = State#state.sock, if SockMod == gen_udp -> {Addr, Port} = State#state.addr, gen_udp:send(Sock, Addr, Port, Pkt); true -> case SockMod:send(Sock, Pkt) of ok -> ok; _ -> exit(normal) end end; send(State, Msg) -> ?dbg("send:~n~s", [stun_codec:pp(Msg)]), Key = State#state.key, case Msg of #stun{class = indication} -> send(State, stun_codec:encode(Msg)), State; #stun{class = response} -> Pkt = stun_codec:encode(Msg, Key), send(State, Pkt), State#state{last_trid = Msg#stun.trid, last_pkt = Pkt}; _ -> send(State, stun_codec:encode(Msg, Key)), State end. time_left(TRef) -> erlang:read_timer(TRef) div 1000. %% Simple port randomization algorithm from %% draft-ietf-tsvwg-port-randomization-04 allocate_addr({Min, Max}) -> Count = Max - Min + 1, Next = Min + random:uniform(Count) - 1, allocate_addr(Min, Max, Next, Count). allocate_addr(_Min, _Max, _Next, 0) -> {error, eaddrinuse}; allocate_addr(Min, Max, Next, Count) -> case gen_udp:open(Next, [binary, {active, once}]) of {ok, Sock} -> case inet:sockname(Sock) of {ok, {_, Port}} -> {ok, Port, Sock}; Err -> Err end; {error, eaddrinuse} -> if Next == Max -> allocate_addr(Min, Max, Min, Count-1); true -> allocate_addr(Min, Max, Next+1, Count-1) end; Err -> Err end. format_error({error, Reason}) -> case inet:format_error(Reason) of "unknown POSIX error" -> Reason; Res -> Res end. addr_to_str({Addr, Port}) -> [inet_parse:ntoa(Addr), $:, integer_to_list(Port)]; addr_to_str(Addr) -> inet_parse:ntoa(Addr). cancel_timer(undefined) -> ok; cancel_timer(TRef) -> case erlang:cancel_timer(TRef) of false -> receive {timeout, TRef, _} -> ok after 0 -> ok end; _ -> ok end. prepare_response(State, Msg) -> #stun{method = Msg#stun.method, magic = Msg#stun.magic, trid = Msg#stun.trid, 'SOFTWARE' = State#state.server_name}. stun-0.9.1/src/stun.erl0000644000175000017500000005033712650733700015367 0ustar debalancedebalance%%%------------------------------------------------------------------- %%% File : stun.erl %%% Author : Evgeniy Khramtsov %%% Description : RFC5389/RFC5766 implementation. %%% Created : 8 Aug 2009 by Evgeniy Khramtsov %%% %%% %%% stun, Copyright (C) 2002-2015 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., 59 Temple Place, Suite 330, Boston, MA %%% 02111-1307 USA %%% %%%------------------------------------------------------------------- -module(stun). -define(GEN_FSM, gen_fsm). -behaviour(?GEN_FSM). %% API -export([start_link/2, start/2, stop/1, socket_type/0, tcp_init/2, udp_init/2, udp_recv/5]). %% gen_fsm callbacks -export([init/1, handle_event/3, handle_sync_event/4, handle_info/3, terminate/3, code_change/4]). %% gen_fsm states -export([session_established/2]). -include("stun.hrl"). -define(MAX_BUF_SIZE, 64*1024). %% 64kb -define(TIMEOUT, 60000). %% 1 minute -define(NONCE_LIFETIME, 60*1000*1000). %% 1 minute (in usec) -define(SERVER_NAME, <<"P1 STUN library">>). %%-define(debug, true). -ifdef(debug). -define(dbg(Str, Args), error_logger:info_msg(Str, Args)). -else. -define(dbg(Str, Args), ok). -endif. -type addr() :: {inet:ip_address(), inet:port_number()}. -record(state, {sock :: inet:socket() | p1_tls:tls_socket(), sock_mod = gen_tcp :: gen_udp | gen_tcp | p1_tls, certfile :: iodata(), peer = {{0,0,0,0}, 0} :: addr(), tref = make_ref() :: reference(), use_turn = false :: boolean(), relay_ip = {127,0,0,1} :: inet:ip_address(), min_port = 49152 :: non_neg_integer(), max_port = 65535 :: non_neg_integer(), max_allocs = 10 :: non_neg_integer() | infinity, shaper = none :: stun_shaper:shaper(), max_permissions = 10 :: non_neg_integer() | infinity, auth = user :: anonymous | user, nonces = treap:empty() :: treap:treap(), realm = <<"">> :: binary(), auth_fun :: function(), server_name = ?SERVER_NAME :: binary(), buf = <<>> :: binary()}). %%==================================================================== %% API %%==================================================================== start({gen_tcp, Sock}, Opts) -> supervisor:start_child(stun_tmp_sup, [Sock, Opts]). stop(Pid) -> ?GEN_FSM:send_all_state_event(Pid, stop). start_link(Sock, Opts) -> ?GEN_FSM:start_link(?MODULE, [Sock, Opts], []). socket_type() -> raw. tcp_init(_Sock, Opts) -> Opts. udp_init(Sock, Opts) -> seed(), prepare_state(Opts, Sock, {{0,0,0,0}, 0}, gen_udp). udp_recv(Sock, Addr, Port, Data, State) -> NewState = prepare_state(State, Sock, {Addr, Port}, gen_udp), case stun_codec:decode(Data, datagram) of {ok, Msg} -> ?dbg("got: ~s", [stun_codec:pp(Msg)]), process(NewState, Msg); _ -> NewState end. %%==================================================================== %% gen_fsm callbacks %%==================================================================== init([Sock, Opts]) -> case inet:peername(Sock) of {ok, Addr} -> seed(), TRef = erlang:start_timer(?TIMEOUT, self(), stop), SockMod = get_sockmod(Opts), State = prepare_state(Opts, Sock, Addr, SockMod), CertFile = get_certfile(Opts), case maybe_starttls(Sock, SockMod, CertFile, Addr) of {ok, NewSock} -> inet:setopts(Sock, [{active, once}]), {ok, session_established, State#state{tref = TRef, sock = NewSock}}; {error, Why} -> {stop, Why} end; Err -> Err end. session_established(Event, State) -> error_logger:error_msg("unexpected event in session_established: ~p", [Event]), {next_state, session_established, State}. handle_event(stop, _StateName, State) -> {stop, normal, State}; handle_event(_Event, StateName, State) -> {next_state, StateName, State}. handle_sync_event(_Event, _From, StateName, State) -> {reply, {error, badarg}, StateName, State}. handle_info({tcp, _Sock, TLSData}, StateName, #state{sock_mod = p1_tls} = State) -> NewState = update_shaper(State, TLSData), case p1_tls:recv_data(NewState#state.sock, TLSData) of {ok, Data} -> process_data(StateName, NewState, Data); _Err -> {stop, normal, NewState} end; handle_info({tcp, _Sock, Data}, StateName, State) -> NewState = update_shaper(State, Data), process_data(StateName, NewState, Data); handle_info({tcp_closed, _Sock}, _StateName, State) -> ?dbg("connection reset by peer", []), {stop, normal, State}; handle_info({tcp_error, _Sock, _Reason}, _StateName, State) -> ?dbg("connection error: ~p", [_Reason]), {stop, normal, State}; handle_info({timeout, TRef, stop}, _StateName, #state{tref = TRef} = State) -> {stop, normal, State}; handle_info({timeout, _TRef, activate}, StateName, State) -> activate_socket(State), {next_state, StateName, State}; handle_info(Info, StateName, State) -> error_logger:error_msg("unexpected info: ~p", [Info]), {next_state, StateName, State}. terminate(_Reason, _StateName, State) -> catch (State#state.sock_mod):close(State#state.sock), ok. code_change(_OldVsn, StateName, State, _Extra) -> {ok, StateName, State}. %%-------------------------------------------------------------------- %%% Internal functions %%-------------------------------------------------------------------- process(State, #stun{class = request, method = ?STUN_METHOD_BINDING, 'MESSAGE-INTEGRITY' = undefined} = Msg) -> process(State, Msg, undefined); process(#state{auth = anonymous} = State, #stun{class = request, 'MESSAGE-INTEGRITY' = undefined} = Msg) -> process(State, Msg, undefined); process(#state{auth = user} = State, #stun{class = request, 'MESSAGE-INTEGRITY' = undefined} = Msg) -> Resp = prepare_response(State, Msg), {Nonce, Nonces} = make_nonce(State#state.peer, State#state.nonces), R = Resp#stun{class = error, 'ERROR-CODE' = stun_codec:error(401), 'REALM' = State#state.realm, 'NONCE' = Nonce}, send(State#state{nonces = Nonces}, R); process(#state{auth = anonymous} = State, #stun{class = request, 'USERNAME' = User, 'REALM' = Realm, 'NONCE' = Nonce} = Msg) when User /= undefined, Realm /= undefined, Nonce /= undefined -> Resp = prepare_response(State, Msg), R = Resp#stun{class = error, 'ERROR-CODE' = stun_codec:error(401)}, send(State, R); process(#state{auth = user} = State, #stun{class = request, 'USERNAME' = User, 'REALM' = Realm, 'NONCE' = Nonce} = Msg) when User /= undefined, Realm /= undefined, Nonce /= undefined -> Resp = prepare_response(State, Msg), {HaveNonce, Nonces} = have_nonce(Nonce, State#state.nonces), case HaveNonce of true -> NewState = State#state{nonces = Nonces}, R = Resp#stun{class = error, 'ERROR-CODE' = stun_codec:error(401), 'REALM' = State#state.realm, 'NONCE' = Nonce}, case (State#state.auth_fun)(User, Realm) of <<"">> -> error_logger:info_msg( "failed long-term STUN authentication " "for ~s@~s from ~s", [User, Realm, addr_to_str(State#state.peer)]), send(NewState, R); Pass -> Key = {User, Realm, Pass}, case stun_codec:check_integrity(Msg, Key) of true -> error_logger:info_msg( "accepted long-term STUN authentication " "for ~s@~s from ~s", [User, Realm, addr_to_str(State#state.peer)]), process(NewState, Msg, Key); false -> error_logger:info_msg( "failed long-term STUN authentication " "for ~s@~s from ~s", [User, Realm, addr_to_str(State#state.peer)]), send(NewState, R) end end; false -> {NewNonce, NewNonces} = make_nonce(State#state.peer, Nonces), R = Resp#stun{class = error, 'ERROR-CODE' = stun_codec:error(438), 'REALM' = State#state.realm, 'NONCE' = NewNonce}, send(State#state{nonces = NewNonces}, R) end; process(State, #stun{class = request, 'USERNAME' = User, 'REALM' = undefined, 'NONCE' = undefined} = Msg) when User /= undefined -> Resp = prepare_response(State, Msg), R = Resp#stun{class = error, 'ERROR-CODE' = stun_codec:error(401)}, send(State, R); process(State, #stun{class = request} = Msg) -> Resp = prepare_response(State, Msg), R = Resp#stun{class = error, 'ERROR-CODE' = stun_codec:error(400)}, send(State, R); process(State, #stun{class = indication, method = ?STUN_METHOD_SEND} = Msg) -> route_on_turn(State, Msg); process(State, Msg) when is_record(Msg, turn) -> route_on_turn(State, Msg); process(State, _Msg) -> State. process(State, #stun{class = request, unsupported = [_|_]} = Msg, Secret) -> Resp = prepare_response(State, Msg), R = Resp#stun{class = error, 'UNKNOWN-ATTRIBUTES' = Msg#stun.unsupported, 'ERROR-CODE' = stun_codec:error(420)}, send(State, R, Secret); process(State, #stun{class = request, method = ?STUN_METHOD_BINDING} = Msg, Secret) -> Resp = prepare_response(State, Msg), AddrPort = State#state.peer, R = case stun_codec:version(Msg) of old -> Resp#stun{class = response, 'MAPPED-ADDRESS' = AddrPort}; new -> Resp#stun{class = response, 'XOR-MAPPED-ADDRESS' = AddrPort} end, send(State, R, Secret); process(#state{use_turn = false} = State, #stun{class = request} = Msg, Secret) -> Resp = prepare_response(State, Msg), R = Resp#stun{class = error, 'ERROR-CODE' = stun_codec:error(405)}, send(State, R, Secret); process(State, #stun{class = request, method = ?STUN_METHOD_ALLOCATE} = Msg, Secret) -> Resp = prepare_response(State, Msg), AddrPort = State#state.peer, SockMod = State#state.sock_mod, case turn_sm:find_allocation(AddrPort) of {ok, Pid} -> turn:route(Pid, Msg), State; _ -> Opts = [{sock, State#state.sock}, {sock_mod, SockMod}, {username, Msg#stun.'USERNAME'}, {realm, State#state.realm}, {key, Secret}, {server, State#state.server_name}, {max_allocs, State#state.max_allocs}, {max_permissions, State#state.max_permissions}, {addr, AddrPort}, {relay_ip, State#state.relay_ip}, {min_port, State#state.min_port}, {max_port, State#state.max_port} | if SockMod /= gen_udp -> [{owner, self()}]; true -> [] end], case turn:start(Opts) of {ok, Pid} -> cancel_timer(State#state.tref), turn:route(Pid, Msg), State; {error, limit} -> R = Resp#stun{class = error, 'ERROR-CODE' = stun_codec:error(486)}, send(State, R, Secret); {error, stale} -> R = Resp#stun{class = error, 'ERROR-CODE' = stun_codec:error(438)}, send(State, R); Err -> error_logger:error_msg( "failed to start turn session: ~p", [Err]), R = Resp#stun{class = error, 'ERROR-CODE' = stun_codec:error(500)}, send(State, R, Secret) end end; process(State, #stun{class = request, method = ?STUN_METHOD_REFRESH} = Msg, Secret) -> route_on_turn(State, Msg, Secret); process(State, #stun{class = request, method = ?STUN_METHOD_CREATE_PERMISSION} = Msg, Secret) -> route_on_turn(State, Msg, Secret); process(State, #stun{class = request, method = ?STUN_METHOD_CHANNEL_BIND} = Msg, Secret) -> route_on_turn(State, Msg, Secret); process(State, #stun{class = request} = Msg, Secret) -> Resp = prepare_response(State, Msg), R = Resp#stun{class = error, 'ERROR-CODE' = stun_codec:error(405)}, send(State, R, Secret); process(State, _Msg, _Secret) -> State. process_data(NextStateName, #state{buf = Buf} = State, Data) -> NewBuf = <>, case stun_codec:decode(NewBuf, stream) of {ok, Msg, Tail} -> ?dbg("got:~n~s", [stun_codec:pp(Msg)]), NewState = process(State, Msg), process_data(NextStateName, NewState#state{buf = <<>>}, Tail); empty -> NewState = State#state{buf = <<>>}, {next_state, NextStateName, NewState}; more when size(NewBuf) < ?MAX_BUF_SIZE -> NewState = State#state{buf = NewBuf}, {next_state, NextStateName, NewState}; _ -> {stop, normal, State} end. update_shaper(#state{shaper = Shaper} = State, Data) -> {NewShaper, Pause} = stun_shaper:update(Shaper, size(Data)), if Pause > 0 -> erlang:start_timer(Pause, self(), activate); true -> activate_socket(State) end, State#state{shaper = NewShaper}. send(State, Data) when is_binary(Data) -> SockMod = State#state.sock_mod, Sock = State#state.sock, case SockMod of gen_udp -> {Addr, Port} = State#state.peer, gen_udp:send(Sock, Addr, Port, Data); _ -> case SockMod:send(Sock, Data) of ok -> ok; _ -> exit(normal) end end, State; send(State, Msg) -> send(State, Msg, undefined). send(State, Msg, {_JID, Pass}) -> send(State, Msg, Pass); send(State, Msg, Pass) -> ?dbg("send:~n~s", [stun_codec:pp(Msg)]), case Msg of #stun{class = indication} -> send(State, stun_codec:encode(Msg, undefined)); _ -> send(State, stun_codec:encode(Msg, Pass)) end. route_on_turn(State, Msg) -> route_on_turn(State, Msg, undefined). route_on_turn(State, Msg, {_JID, Pass}) -> route_on_turn(State, Msg, Pass); route_on_turn(State, Msg, Pass) -> case turn_sm:find_allocation(State#state.peer) of {ok, Pid} -> turn:route(Pid, Msg), State; _ -> case Msg of #stun{class = request} -> Resp = prepare_response(State, Msg), R = Resp#stun{class = error, 'ERROR-CODE' = stun_codec:error(437)}, send(State, R, Pass); _ -> State end end. prepare_state(Opts, Sock, Peer, SockMod) when is_list(Opts) -> case proplists:get_bool(use_turn, Opts) of true -> lists:foldl( fun({turn_ip, IP}, State) -> case prepare_addr(IP) of {ok, Addr} -> State#state{relay_ip = Addr}; {error, _} -> error_logger:error_msg("wrong 'turn_ip' " "value: ~p", [IP]), State end; ({turn_min_port, Min}, State) when is_integer(Min), Min > 1024, Min < 65536 -> State#state{min_port = Min}; ({turn_min_port, Wrong}, State) -> error_logger:error_msg("wrong 'turn_min_port' value: " "~p", [Wrong]), State; ({turn_max_port, Max}, State) when is_integer(Max), Max > 1024, Max < 65536 -> State#state{max_port = Max}; ({turn_max_port, Wrong}, State) -> error_logger:error_msg("wrong 'turn_max_port' value: " "~p", [Wrong]), State; ({turn_max_allocations, N}, State) when (is_integer(N) andalso N > 0) orelse is_atom(N) -> State#state{max_allocs = N}; ({turn_max_allocations, Wrong}, State) -> error_logger:error_msg("wrong 'turn_max_allocations' " "value: ~p", [Wrong]), State; ({turn_max_permissions, N}, State) when (is_integer(N) andalso N > 0) orelse is_atom(N) -> State#state{max_permissions = N}; ({turn_max_permissions, Wrong}, State) -> error_logger:error_msg("wrong 'turn_max_permissions' " "value: ~p", [Wrong]), State; ({shaper, S}, State) when S == none orelse (is_integer(S) andalso (S > 0)) -> State#state{shaper = stun_shaper:new(S)}; ({shaper, Wrong}, State) -> error_logger:error_msg("wrong 'shaper' " "value: ~p", [Wrong]), State; ({server_name, S}, State) -> try State#state{server_name = iolist_to_binary(S)} catch _:_ -> error_logger:error_msg("wrong 'server_name' " "value: ~p", [S]), State end; ({auth_realm, R}, State) -> try State#state{realm = iolist_to_binary(R)} catch _:_ -> error_logger:error_msg("wrong 'auth_realm' " "value: ~p", [R]), State end; ({auth_fun, F}, State) when is_function(F) -> State#state{auth_fun = F}; ({auth_fun, Wrong}, State) -> error_logger:error_msg("wrong 'auth_fun' " "value: ~p", [Wrong]), State; ({auth_type, anonymous}, State) -> State#state{auth = anonymous}; ({auth_type, user}, State) -> State#state{auth = user}; ({auth_type, Wrong}, State) -> error_logger:error_msg("wrong 'auth_type' " "value: ~p", [Wrong]), State; ({use_turn, _}, State) -> State; (use_turn, State) -> State; (inet, State) -> State; ({ip, _}, State) -> State; ({backlog, _}, State) -> State; ({certfile, _}, State) -> State; ({tls, _}, State) -> State; (tls, State) -> State; (Opt, State) -> error_logger:error_msg( "ignoring unknown option ~p", [Opt]), State end, #state{peer = Peer, sock = Sock, sock_mod = SockMod, use_turn = true}, Opts); _ -> #state{sock = Sock, sock_mod = SockMod, peer = Peer} end; prepare_state(State, _Sock, Peer, _SockMod) -> State#state{peer = Peer}. prepare_addr(IPBin) when is_binary(IPBin) -> prepare_addr(binary_to_list(IPBin)); prepare_addr(IPS) when is_list(IPS) -> inet_parse:address(IPS); prepare_addr(T) when is_tuple(T) -> try inet_parse:address(inet_parse:ntoa(T)) catch _:_ -> {error, einval} end. activate_socket(#state{sock = Sock, sock_mod = SockMod}) -> case SockMod of gen_tcp -> inet:setopts(Sock, [{active, once}]); _ -> SockMod:setopts(Sock, [{active, once}]) end. cancel_timer(undefined) -> ok; cancel_timer(TRef) -> case erlang:cancel_timer(TRef) of false -> receive {timeout, TRef, _} -> ok after 0 -> ok end; _ -> ok end. now_priority() -> {MSec, Sec, USec} = now(), -((MSec*1000000 + Sec)*1000000 + USec). clean_treap(Treap, CleanPriority) -> case treap:is_empty(Treap) of true -> Treap; false -> {_Key, Priority, _Value} = treap:get_root(Treap), if Priority > CleanPriority -> clean_treap(treap:delete_root(Treap), CleanPriority); true -> Treap end end. make_nonce(Addr, Nonces) -> Priority = now_priority(), Nonce = list_to_binary(integer_to_list(random:uniform(1 bsl 32))), NewNonces = clean_treap(Nonces, Priority + ?NONCE_LIFETIME), {Nonce, treap:insert(Nonce, Priority, Addr, NewNonces)}. have_nonce(Nonce, Nonces) -> Priority = now_priority(), NewNonces = clean_treap(Nonces, Priority + ?NONCE_LIFETIME), case treap:lookup(Nonce, NewNonces) of {ok, _, _} -> {true, NewNonces}; _ -> {false, NewNonces} end. addr_to_str({Addr, Port}) -> [inet_parse:ntoa(Addr), $:, integer_to_list(Port)]; addr_to_str(Addr) -> inet_parse:ntoa(Addr). get_sockmod(Opts) -> case proplists:get_bool(tls, Opts) of true -> p1_tls; false -> gen_tcp end. get_certfile(Opts) -> case catch iolist_to_binary(proplists:get_value(certfile, Opts)) of Filename when is_binary(Filename), Filename /= <<"">> -> Filename; _ -> undefined end. maybe_starttls(_Sock, p1_tls, undefined, {IP, Port}) -> error_logger:error_msg("failed to start TLS connection for ~s:~p: " "option 'certfile' is not set", [inet_parse:ntoa(IP), Port]), {error, eprotonosupport}; maybe_starttls(Sock, p1_tls, CertFile, _PeerAddr) -> p1_tls:tcp_to_tls(Sock, [{certfile, CertFile}]); maybe_starttls(Sock, gen_tcp, _CertFile, _PeerAddr) -> {ok, Sock}. seed() -> {A, B, C} = now(), random:seed(A, B, C). prepare_response(State, Msg) -> #stun{method = Msg#stun.method, magic = Msg#stun.magic, trid = Msg#stun.trid, 'SOFTWARE' = State#state.server_name}. stun-0.9.1/src/stun_app.erl0000644000175000017500000000553712650733700016231 0ustar debalancedebalance%%%---------------------------------------------------------------------- %%% File : stun_app.erl %%% Author : Evgeniy Khramtsov %%% Purpose : stun application %%% Created : 2 May 2013 by Evgeniy Khramtsov %%% %%% %%% stun, Copyright (C) 2002-2015 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., 59 Temple Place, Suite 330, Boston, MA %%% 02111-1307 USA %%% %%%---------------------------------------------------------------------- -module(stun_app). -behaviour(application). %% Application callbacks -export([start/2, stop/1]). %%%=================================================================== %%% Application callbacks %%%=================================================================== %%-------------------------------------------------------------------- %% @private %% @doc %% This function is called whenever an application is started using %% application:start/[1,2], and should start the processes of the %% application. If the application is structured according to the OTP %% design principles as a supervision tree, this means starting the %% top supervisor of the tree. %% %% @spec start(StartType, StartArgs) -> {ok, Pid} | %% {ok, Pid, State} | %% {error, Reason} %% StartType = normal | {takeover, Node} | {failover, Node} %% StartArgs = term() %% @end %%-------------------------------------------------------------------- start(_StartType, _StartArgs) -> application:start(p1_tls), case stun_sup:start_link() of {ok, Pid} -> {ok, Pid}; Error -> Error end. %%-------------------------------------------------------------------- %% @private %% @doc %% This function is called whenever an application has stopped. It %% is intended to be the opposite of Module:start/2 and should do %% any necessary cleaning up. The return value is ignored. %% %% @spec stop(State) -> void() %% @end %%-------------------------------------------------------------------- stop(_State) -> ok. %%%=================================================================== %%% Internal functions %%%=================================================================== stun-0.9.1/src/stun_listener.erl0000644000175000017500000001545012650733700017271 0ustar debalancedebalance%%%---------------------------------------------------------------------- %%% File : stun_listener.erl %%% Author : Evgeniy Khramtsov %%% Purpose : %%% Created : 9 Jan 2011 by Evgeniy Khramtsov %%% %%% %%% stun, Copyright (C) 2002-2015 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., 59 Temple Place, Suite 330, Boston, MA %%% 02111-1307 USA %%% %%%---------------------------------------------------------------------- -module(stun_listener). -behaviour(gen_server). %% API -export([start_link/0, add_listener/3, del_listener/2, start_listener/4]). %% gen_server callbacks -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -define(TCP_SEND_TIMEOUT, 10000). -record(state, {listeners = dict:new()}). %%%=================================================================== %%% API %%%=================================================================== start_link() -> gen_server:start_link({local, ?MODULE}, ?MODULE, [], []). add_listener(Port, Transport, Opts) -> gen_server:call(?MODULE, {add_listener, Port, Transport, Opts}). del_listener(Port, Transport) -> gen_server:call(?MODULE, {del_listener, Port, Transport}). %%%=================================================================== %%% gen_server callbacks %%%=================================================================== init([]) -> {ok, #state{}}. handle_call({add_listener, Port, Transport, Opts}, _From, State) -> case dict:find({Port, Transport}, State#state.listeners) of {ok, _} -> Err = {error, already_started}, {reply, Err, State}; error -> {Pid, MRef} = spawn_monitor(?MODULE, start_listener, [Port, Transport, Opts, self()]), receive {'DOWN', MRef, _Type, _Object, Info} -> Res = {error, Info}, format_listener_error(Port, Transport, Opts, Res), {reply, Res, State}; {Pid, Reply} -> case Reply of {error, _} = Err -> format_listener_error(Port, Transport, Opts, Err), {reply, Reply, State}; ok -> Listeners = dict:store( {Port, Transport}, {MRef, Pid, Opts}, State#state.listeners), {reply, ok, State#state{listeners = Listeners}} end end end; handle_call({del_listener, Port, Transport}, _From, State) -> case dict:find({Port, Transport}, State#state.listeners) of {ok, {MRef, Pid, _Opts}} -> catch erlang:demonitor(MRef, [flush]), catch exit(Pid, kill), Listeners = dict:erase({Port, Transport}, State#state.listeners), {reply, ok, State#state{listeners = Listeners}}; error -> {reply, {error, notfound}, State} end; handle_call(_Request, _From, State) -> Reply = ok, {reply, Reply, State}. handle_cast(_Msg, State) -> {noreply, State}. handle_info({'DOWN', MRef, _Type, _Pid, Info}, State) -> Listeners = dict:filter( fun({Port, Transport}, {Ref, _, _}) when Ref == MRef -> error_logger:error_msg("listener on ~p/~p failed: ~p", [Port, Transport, Info]), false; (_, _) -> true end, State#state.listeners), {noreply, State#state{listeners = Listeners}}; handle_info(_Info, State) -> {noreply, State}. terminate(_Reason, _State) -> ok. code_change(_OldVsn, State, _Extra) -> {ok, State}. %%%=================================================================== %%% Internal functions %%%=================================================================== start_listener(Port, Transport, Opts, Owner) when Transport == tcp; Transport == tls -> OptsWithTLS = case Transport of tls -> [tls|Opts]; tcp -> Opts end, case gen_tcp:listen(Port, [binary, {packet, 0}, {active, false}, {reuseaddr, true}, {nodelay, true}, {keepalive, true}, {send_timeout, ?TCP_SEND_TIMEOUT}, {send_timeout_close, true}]) of {ok, ListenSocket} -> Owner ! {self(), ok}, OptsWithTLS1 = stun:tcp_init(ListenSocket, OptsWithTLS), accept(ListenSocket, OptsWithTLS1); Err -> Owner ! {self(), Err} end; start_listener(Port, udp, Opts, Owner) -> case gen_udp:open(Port, [binary, {active, false}, {reuseaddr, true}]) of {ok, Socket} -> Owner ! {self(), ok}, Opts1 = stun:udp_init(Socket, Opts), udp_recv(Socket, Opts1); Err -> Owner ! {self(), Err} end. accept(ListenSocket, Opts) -> case gen_tcp:accept(ListenSocket) of {ok, Socket} -> case {inet:peername(Socket), inet:sockname(Socket)} of {{ok, {PeerAddr, PeerPort}}, {ok, {Addr, Port}}} -> error_logger:info_msg("accepted connection: ~s:~p -> ~s:~p", [inet_parse:ntoa(PeerAddr), PeerPort, inet_parse:ntoa(Addr), Port]), case stun:start({gen_tcp, Socket}, Opts) of {ok, Pid} -> gen_tcp:controlling_process(Socket, Pid); Err -> Err end; Err -> error_logger:error_msg("unable to fetch peername: ~p", [Err]), Err end, accept(ListenSocket, Opts); Err -> Err end. udp_recv(Socket, Opts) -> case gen_udp:recv(Socket, 0) of {ok, {Addr, Port, Packet}} -> case catch stun:udp_recv(Socket, Addr, Port, Packet, Opts) of {'EXIT', Reason} -> error_logger:error_msg("failed to process UDP packet:~n" "** Source: {~p, ~p}~n" "** Reason: ~p~n** Packet: ~p", [Addr, Port, Reason, Packet]), udp_recv(Socket, Opts); NewOpts -> udp_recv(Socket, NewOpts) end; {error, Reason} -> error_logger:error_msg( "unexpected UDP error: ~s", [inet:format_error(Reason)]), erlang:error(Reason) end. format_listener_error(Port, Transport, Opts, Err) -> error_logger:error_msg("failed to start listener:~n" "** Port: ~p~n" "** Transport: ~p~n" "** Options: ~p~n" "** Reason: ~p", [Port, Transport, Opts, Err]). stun-0.9.1/src/stun_codec.erl0000644000175000017500000003065312650733700016523 0ustar debalancedebalance%%%------------------------------------------------------------------- %%% File : stun_codec.erl %%% Author : Evgeniy Khramtsov %%% Description : STUN codec %%% Created : 7 Aug 2009 by Evgeniy Khramtsov %%% %%% %%% stun, Copyright (C) 2002-2015 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., 59 Temple Place, Suite 330, Boston, MA %%% 02111-1307 USA %%% %%%------------------------------------------------------------------- -module(stun_codec). %% API -export([decode/2, encode/1, encode/2, version/1, error/1, check_integrity/2, add_fingerprint/1, pp/1]). -include("stun.hrl"). %%==================================================================== %% API %%==================================================================== decode(<<0:2, Type:14, Len:16, Magic:32, TrID:96, Body:Len/binary, Tail/binary>> = Data, Transport) -> case catch decode(Type, Magic, TrID, Body) of {'EXIT', _} -> {error, unparsed}; {Res, RawSize} when Transport == datagram -> {ok, add_raw(Res, Data, RawSize)}; {Res, RawSize} -> {ok, add_raw(Res, Data, RawSize), Tail} end; decode(<<1:2, _:6, _/binary>> = Pkt, datagram) -> case Pkt of <> -> {ok, #turn{channel = Channel, data = Data}}; _ -> {error, unparsed} end; decode(<<1:2, _:6, _/binary>> = Pkt, stream) -> case Pkt of <> -> PaddLen = padd_len(Len), case Rest of <> -> {ok, #turn{channel = Channel, data = Data}, Tail}; _ -> more end; _ -> more end; decode(<<0:2, _:6, _/binary>>, stream) -> more; decode(<<>>, stream) -> empty; decode(_, _Transport) -> {error, unparsed}. encode(Msg) -> encode(Msg, undefined). encode(#turn{channel = Channel, data = Data}, _Password) -> Len = size(Data), PaddLen = padd_len(Len), <>; encode(#stun{class = Class, method = Method, magic = Magic, trid = TrID} = Msg, Key) -> ClassCode = case Class of request -> 0; indication -> 1; response -> 2; error -> 3 end, Type = ?STUN_TYPE(ClassCode, Method), Attrs = enc_attrs(Msg), Len = size(Attrs), if Key /= undefined -> NewKey = case Key of {User, Realm, Password} -> crypto:hash(md5, [User, $:, Realm, $:, Password]); _ -> Key end, Data = <<0:2, Type:14, (Len+24):16, Magic:32, TrID:96, Attrs/binary>>, MessageIntegrity = crypto:hmac(sha, NewKey, Data), <>; true -> <<0:2, Type:14, Len:16, Magic:32, TrID:96, Attrs/binary>> end. add_fingerprint(<>) -> Data = <>, CRC32 = erlang:crc32(Data), <>. check_integrity(#stun{raw = Raw, 'MESSAGE-INTEGRITY' = MI}, Key) when is_binary(Raw), is_binary(MI), Key /= undefined -> NewKey = case Key of {User, Realm, Password} -> crypto:hash(md5, [User, $:, Realm, $:, Password]); _ -> Key end, crypto:hmac(sha, NewKey, Raw) == MI; check_integrity(_Msg, _Key) -> false. pp(Term) -> io_lib_pretty:print(Term, fun pp/2). version(#stun{magic = ?STUN_MAGIC}) -> new; version(#stun{}) -> old. error(300) -> {300, <<"Try Alternate">>}; error(400) -> {400, <<"Bad Request">>}; error(401) -> {401, <<"Unauthorized">>}; error(403) -> {403, <<"Forbidden">>}; error(405) -> {405, <<"Method Not Allowed">>}; error(420) -> {420, <<"Unknown Attribute">>}; error(437) -> {437, <<"Allocation Mismatch">>}; error(438) -> {438, <<"Stale Nonce">>}; error(441) -> {441, <<"Wrong Credentials">>}; error(442) -> {442, <<"Unsupported Transport Protocol">>}; error(486) -> {486, <<"Allocation Quota Reached">>}; error(500) -> {500, <<"Server Error">>}; error(508) -> {508, <<"Insufficient Capacity">>}; error(Int) -> {Int, <<"Undefined Error">>}. %%==================================================================== %% Internal functions %%==================================================================== decode(Type, Magic, TrID, Body) -> Method = ?STUN_METHOD(Type), Class = case ?STUN_CLASS(Type) of 0 -> request; 1 -> indication; 2 -> response; 3 -> error end, dec_attrs(Body, 20, #stun{class = Class, method = Method, magic = Magic, trid = TrID}). dec_attrs(<>, Bytes, Msg) -> PaddLen = padd_len(Len), <> = Rest, NewMsg = dec_attr(Type, Val, Msg), if Type == ?STUN_ATTR_MESSAGE_INTEGRITY -> {NewMsg, Bytes}; true -> NewBytes = Bytes + 4 + Len + (PaddLen div 8), dec_attrs(Tail, NewBytes, NewMsg) end; dec_attrs(<<>>, _Bytes, Msg) -> {Msg, 0}. enc_attrs(Msg) -> iolist_to_binary( [enc_attr(?STUN_ATTR_SOFTWARE, Msg#stun.'SOFTWARE'), enc_addr(?STUN_ATTR_MAPPED_ADDRESS, Msg#stun.'MAPPED-ADDRESS'), enc_xor_addr(?STUN_ATTR_XOR_MAPPED_ADDRESS, Msg#stun.magic, Msg#stun.trid, Msg#stun.'XOR-MAPPED-ADDRESS'), enc_xor_addr(?STUN_ATTR_XOR_RELAYED_ADDRESS, Msg#stun.magic, Msg#stun.trid, Msg#stun.'XOR-RELAYED-ADDRESS'), enc_xor_peer_addr(Msg#stun.magic, Msg#stun.trid, Msg#stun.'XOR-PEER-ADDRESS'), enc_req_trans(Msg#stun.'REQUESTED-TRANSPORT'), enc_attr(?STUN_ATTR_DATA, Msg#stun.'DATA'), enc_df(Msg#stun.'DONT-FRAGMENT'), enc_addr(?STUN_ATTR_ALTERNATE_SERVER, Msg#stun.'ALTERNATE-SERVER'), enc_attr(?STUN_ATTR_USERNAME, Msg#stun.'USERNAME'), enc_attr(?STUN_ATTR_REALM, Msg#stun.'REALM'), enc_attr(?STUN_ATTR_NONCE, Msg#stun.'NONCE'), enc_error_code(Msg#stun.'ERROR-CODE'), enc_uint32(?STUN_ATTR_LIFETIME, Msg#stun.'LIFETIME'), enc_chan(Msg#stun.'CHANNEL-NUMBER'), enc_unknown_attrs(Msg#stun.'UNKNOWN-ATTRIBUTES')]). dec_attr(?STUN_ATTR_MAPPED_ADDRESS, Val, Msg) -> <<_, Family, Port:16, AddrBin/binary>> = Val, Addr = dec_addr(Family, AddrBin), Msg#stun{'MAPPED-ADDRESS' = {Addr, Port}}; dec_attr(?STUN_ATTR_XOR_MAPPED_ADDRESS, Val, Msg) -> AddrPort = dec_xor_addr(Val, Msg), Msg#stun{'XOR-MAPPED-ADDRESS' = AddrPort}; dec_attr(?STUN_ATTR_SOFTWARE, Val, Msg) -> Msg#stun{'SOFTWARE' = Val}; dec_attr(?STUN_ATTR_USERNAME, Val, Msg) -> Msg#stun{'USERNAME' = Val}; dec_attr(?STUN_ATTR_REALM, Val, Msg) -> Msg#stun{'REALM' = Val}; dec_attr(?STUN_ATTR_NONCE, Val, Msg) -> Msg#stun{'NONCE' = Val}; dec_attr(?STUN_ATTR_MESSAGE_INTEGRITY, Val, Msg) -> Msg#stun{'MESSAGE-INTEGRITY' = Val}; dec_attr(?STUN_ATTR_ALTERNATE_SERVER, Val, Msg) -> <<_, Family, Port:16, Address/binary>> = Val, IP = dec_addr(Family, Address), Msg#stun{'ALTERNATE-SERVER' = {IP, Port}}; dec_attr(?STUN_ATTR_ERROR_CODE, Val, Msg) -> <<_:21, Class:3, Number:8, Reason/binary>> = Val, if Class >=3, Class =< 6, Number >=0, Number =< 99 -> Code = Class * 100 + Number, Msg#stun{'ERROR-CODE' = {Code, Reason}} end; dec_attr(?STUN_ATTR_UNKNOWN_ATTRIBUTES, Val, Msg) -> Attrs = dec_unknown_attrs(Val, []), Msg#stun{'UNKNOWN-ATTRIBUTES' = Attrs}; dec_attr(?STUN_ATTR_XOR_RELAYED_ADDRESS, Val, Msg) -> AddrPort = dec_xor_addr(Val, Msg), Msg#stun{'XOR-RELAYED-ADDRESS' = AddrPort}; dec_attr(?STUN_ATTR_XOR_PEER_ADDRESS, Val, Msg) -> AddrPort = dec_xor_addr(Val, Msg), Tail = Msg#stun.'XOR-PEER-ADDRESS', Msg#stun{'XOR-PEER-ADDRESS' = [AddrPort|Tail]}; dec_attr(?STUN_ATTR_REQUESTED_TRANSPORT, Val, Msg) -> <> = Val, Proto = case ProtoInt of 17 -> udp; _ -> unknown end, Msg#stun{'REQUESTED-TRANSPORT' = Proto}; dec_attr(?STUN_ATTR_DATA, Val, Msg) -> Msg#stun{'DATA' = Val}; dec_attr(?STUN_ATTR_LIFETIME, Val, Msg) -> <> = Val, Msg#stun{'LIFETIME' = Seconds}; dec_attr(?STUN_ATTR_DONT_FRAGMENT, _Val, Msg) -> Msg#stun{'DONT-FRAGMENT' = true}; dec_attr(?STUN_ATTR_CHANNEL_NUMBER, Val, Msg) -> <> = Val, Msg#stun{'CHANNEL-NUMBER' = Channel}; dec_attr(Attr, _Val, #stun{unsupported = Attrs} = Msg) when Attr < 16#8000 -> Msg#stun{unsupported = [Attr|Attrs]}; dec_attr(_Attr, _Val, Msg) -> Msg. dec_addr(1, <>) -> {A1, A2, A3, A4}; dec_addr(2, <>) -> {A1, A2, A3, A4, A5, A6, A7, A8}. dec_xor_addr(<<_, Family, XPort:16, XAddr/binary>>, Msg) -> Magic = Msg#stun.magic, Port = XPort bxor (Magic bsr 16), Addr = dec_xor_addr(Family, Magic, Msg#stun.trid, XAddr), {Addr, Port}. dec_xor_addr(1, Magic, _TrID, <>) -> Addr = XAddr bxor Magic, dec_addr(1, <>); dec_xor_addr(2, Magic, TrID, <>) -> Addr = XAddr bxor ((Magic bsl 96) bor TrID), dec_addr(2, <>). dec_unknown_attrs(<>, Acc) -> dec_unknown_attrs(Tail, [Attr|Acc]); dec_unknown_attrs(<<>>, Acc) -> lists:reverse(Acc). enc_attr(_Attr, undefined) -> <<>>; enc_attr(Attr, Val) -> Len = size(Val), PaddLen = padd_len(Len), <>. enc_addr(_Type, undefined) -> <<>>; enc_addr(Type, {{A1, A2, A3, A4}, Port}) -> enc_attr(Type, <<0, 1, Port:16, A1, A2, A3, A4>>); enc_addr(Type, {{A1, A2, A3, A4, A5, A6, A7, A8}, Port}) -> enc_attr(Type, <<0, 2, Port:16, A1:16, A2:16, A3:16, A4:16, A5:16, A6:16, A7:16, A8:16>>). enc_xor_addr(_Type, _Magic, _TrID, undefined) -> <<>>; enc_xor_addr(Type, Magic, _TrID, {{A1, A2, A3, A4}, Port}) -> XPort = Port bxor (Magic bsr 16), <> = <>, XAddr = Addr bxor Magic, enc_attr(Type, <<0, 1, XPort:16, XAddr:32>>); enc_xor_addr(Type, Magic, TrID, {{A1, A2, A3, A4, A5, A6, A7, A8}, Port}) -> XPort = Port bxor (Magic bsr 16), <> = <>, XAddr = Addr bxor ((Magic bsl 96) bor TrID), enc_attr(Type, <<0, 2, XPort:16, XAddr:128>>). enc_xor_peer_addr(Magic, TrID, AddrPortList) -> [enc_xor_addr(?STUN_ATTR_XOR_PEER_ADDRESS, Magic, TrID, AddrPort) || AddrPort <- AddrPortList]. enc_error_code(undefined) -> <<>>; enc_error_code({Code, Reason}) -> Class = Code div 100, Number = Code rem 100, enc_attr(?STUN_ATTR_ERROR_CODE, <<0:21, Class:3, Number:8, Reason/binary>>). enc_unknown_attrs([]) -> <<>>; enc_unknown_attrs(Attrs) -> enc_attr(?STUN_ATTR_UNKNOWN_ATTRIBUTES, iolist_to_binary([<> || Attr <- Attrs])). enc_uint32(_Type, undefined) -> <<>>; enc_uint32(Type, Seconds) -> enc_attr(Type, <>). enc_req_trans(undefined) -> <<>>; enc_req_trans(udp) -> enc_attr(?STUN_ATTR_REQUESTED_TRANSPORT, <<17, 0:24>>). enc_df(false) -> <<>>; enc_df(true) -> enc_attr(?STUN_ATTR_DONT_FRAGMENT, <<>>). enc_chan(undefined) -> <<>>; enc_chan(Channel) -> enc_attr(?STUN_ATTR_CHANNEL_NUMBER, <>). %%==================================================================== %% Auxiliary functions %%==================================================================== pp(Tag, N) -> try pp1(Tag, N) catch _:_ -> no end. pp1(stun, N) -> N = record_info(size, stun) - 1, record_info(fields, stun); pp1(turn, N) -> N = record_info(size, turn) - 1, record_info(fields, turn); pp1(_, _) -> no. add_raw(Msg, _Data, 0) -> Msg; add_raw(Msg, Data, Size) -> <> = Data, <> = Head, Raw = <>, Msg#stun{raw = Raw}. %% Workaround for stupid clients. -ifdef(NO_PADDING). padd_len(_Len) -> 0. -else. padd_len(Len) -> case Len rem 4 of 0 -> 0; N -> 8*(4-N) end. -endif. stun-0.9.1/src/stun_sup.erl0000644000175000017500000000452112650733700016250 0ustar debalancedebalance%%%---------------------------------------------------------------------- %%% File : stun_sup.erl %%% Author : Evgeniy Khramtsov %%% Purpose : stun supervisor %%% Created : 2 May 2013 by Evgeniy Khramtsov %%% %%% %%% stun, Copyright (C) 2002-2015 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., 59 Temple Place, Suite 330, Boston, MA %%% 02111-1307 USA %%% %%%---------------------------------------------------------------------- -module(stun_sup). -behaviour(supervisor). %% API -export([start_link/0]). %% Supervisor callbacks -export([init/1]). -define(SERVER, ?MODULE). %%%=================================================================== %%% API functions %%%=================================================================== start_link() -> supervisor:start_link({local, ?SERVER}, ?MODULE, []). %%%=================================================================== %%% Supervisor callbacks %%%=================================================================== init([]) -> StunTmpSup = {stun_tmp_sup, {stun_tmp_sup, start_link, []}, permanent, infinity, supervisor, [stun_tmp_sup]}, TurnTmpSup = {turn_tmp_sup, {turn_tmp_sup, start_link, []}, permanent, infinity, supervisor, [turn_tmp_sup]}, TurnSM = {turn_sm, {turn_sm, start_link, []}, permanent, 2000, worker, [turn_sm]}, StunListen = {stun_listener, {stun_listener, start_link, []}, permanent, 2000, worker, [stun_listener]}, {ok, {{one_for_one, 10, 1}, [TurnSM, StunTmpSup, TurnTmpSup, StunListen]}}. %%%=================================================================== %%% Internal functions %%%=================================================================== stun-0.9.1/src/turn_tmp_sup.erl0000644000175000017500000000530412650733700017127 0ustar debalancedebalance%%%---------------------------------------------------------------------- %%% File : turn_tmp_sup.erl %%% Author : Evgeniy Khramtsov %%% Purpose : %%% Created : 3 May 2014 by Evgeniy Khramtsov %%% %%% %%% stun, Copyright (C) 2002-2015 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., 59 Temple Place, Suite 330, Boston, MA %%% 02111-1307 USA %%% %%%---------------------------------------------------------------------- -module(turn_tmp_sup). -behaviour(supervisor). %% API -export([start_link/0]). %% Supervisor callbacks -export([init/1]). -define(SERVER, ?MODULE). %%%=================================================================== %%% API functions %%%=================================================================== %%-------------------------------------------------------------------- %% @doc %% Starts the supervisor %% %% @spec start_link() -> {ok, Pid} | ignore | {error, Error} %% @end %%-------------------------------------------------------------------- start_link() -> supervisor:start_link({local, ?SERVER}, ?MODULE, []). %%%=================================================================== %%% Supervisor callbacks %%%=================================================================== %%-------------------------------------------------------------------- %% @private %% @doc %% Whenever a supervisor is started using supervisor:start_link/[2,3], %% this function is called by the new process to find out about %% restart strategy, maximum restart frequency and child %% specifications. %% %% @spec init(Args) -> {ok, {SupFlags, [ChildSpec]}} | %% ignore | %% {error, Reason} %% @end %%-------------------------------------------------------------------- init([]) -> {ok, {{simple_one_for_one, 10, 1}, [{undefined, {turn, start_link, []}, temporary, brutal_kill, worker, [turn]}]}}. %%%=================================================================== %%% Internal functions %%%=================================================================== stun-0.9.1/src/stun_tmp_sup.erl0000644000175000017500000000530412650733700017130 0ustar debalancedebalance%%%---------------------------------------------------------------------- %%% File : stun_tmp_sup.erl %%% Author : Evgeniy Khramtsov %%% Purpose : %%% Created : 3 May 2014 by Evgeniy Khramtsov %%% %%% %%% stun, Copyright (C) 2002-2015 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., 59 Temple Place, Suite 330, Boston, MA %%% 02111-1307 USA %%% %%%---------------------------------------------------------------------- -module(stun_tmp_sup). -behaviour(supervisor). %% API -export([start_link/0]). %% Supervisor callbacks -export([init/1]). -define(SERVER, ?MODULE). %%%=================================================================== %%% API functions %%%=================================================================== %%-------------------------------------------------------------------- %% @doc %% Starts the supervisor %% %% @spec start_link() -> {ok, Pid} | ignore | {error, Error} %% @end %%-------------------------------------------------------------------- start_link() -> supervisor:start_link({local, ?SERVER}, ?MODULE, []). %%%=================================================================== %%% Supervisor callbacks %%%=================================================================== %%-------------------------------------------------------------------- %% @private %% @doc %% Whenever a supervisor is started using supervisor:start_link/[2,3], %% this function is called by the new process to find out about %% restart strategy, maximum restart frequency and child %% specifications. %% %% @spec init(Args) -> {ok, {SupFlags, [ChildSpec]}} | %% ignore | %% {error, Reason} %% @end %%-------------------------------------------------------------------- init([]) -> {ok, {{simple_one_for_one, 10, 1}, [{undefined, {stun, start_link, []}, temporary, brutal_kill, worker, [stun]}]}}. %%%=================================================================== %%% Internal functions %%%=================================================================== stun-0.9.1/COPYING0000644000175000017500000004325412650733700014136 0ustar debalancedebalance GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) 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. Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License.