stun-1.0.20/0000755000232200023220000000000013225634002013126 5ustar debalancedebalancestun-1.0.20/LICENSE.txt0000644000232200023220000002613613225634002014761 0ustar debalancedebalance Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. stun-1.0.20/README.md0000644000232200023220000001212513225634002014406 0ustar debalancedebalance# STUN [![Build Status](https://travis-ci.org/processone/stun.svg?branch=master)](https://travis-ci.org/processone/stun) [![Coverage Status](https://coveralls.io/repos/processone/stun/badge.svg?branch=master&service=github)](https://coveralls.io/github/processone/stun?branch=master) [![Hex version](https://img.shields.io/hexpm/v/stun.svg "Hex version")](https://hex.pm/packages/stun) STUN and TURN library for Erlang / Elixir. Both [STUN](https://en.wikipedia.org/wiki/STUN) (Session Traversal Utilities for NAT) and [TURN](https://en.wikipedia.org/wiki/Traversal_Using_Relays_around_NAT) standards are used as technics to establish media connection between peers for VoIP (for example using [SIP](https://en.wikipedia.org/wiki/Session_Initiation_Protocol) or [Jingle](http://xmpp.org/about-xmpp/technology-overview/jingle/)) and [WebRTC](https://en.wikipedia.org/wiki/WebRTC). They are part of a more general negotiation technique know as [ICE](https://en.wikipedia.org/wiki/Interactive_Connectivity_Establishment) (Interactive Connectivity Establishment). To summarize: * A STUN server is used to get an external network address. It does not serve as a relay for the mediat raffic. * TURN servers are used to relay traffic if direct (peer to peer) connection fails. ## Build This is a pure Erlang implementation, so you do not need to have specific C libraries installed for the STUN, TURN, ICE code. However, this code depends on ProcessOne [Fast TLS](https://github.com/processone/fast_tls), which depends on OpenSSL 1.0.0+ library. ### Generic build You can trigger build with: make # Usage The following sequence describe a STUN establishment. First, start the application and stun listener: ``` 1> application:start(stun). ok 2> stun_listener:add_listener(3478, udp, []). ok ``` Then, you can form and send a BindRequest: ``` 3> rr(stun). [state,stun,turn] 4> random:seed(erlang:timestamp()). undefined ``` You can form a transaction id. Should be always 96 bit: ``` 5> TrID = random:uniform(1 bsl 96). 41809861624941132369239212033 ``` You then create a BindRequest message. `16#001` is `?STUN_METHOD_BINDING`, defined in `include/stun.hrl` ``` 6> Msg = #stun{method = 16#001, class = request, trid = TrID}. #stun{class = request,method = 1,magic = 554869826, trid = 41809861624941132369239212033,raw = <<>>, unsupported = [],'ALTERNATE-SERVER' = undefined, 'CHANNEL-NUMBER' = undefined,'DATA' = undefined, 'DONT-FRAGMENT' = false,'ERROR-CODE' = undefined, 'LIFETIME' = undefined,'MAPPED-ADDRESS' = undefined, 'MESSAGE-INTEGRITY' = undefined,'NONCE' = undefined, 'REALM' = undefined,'REQUESTED-TRANSPORT' = undefined, 'SOFTWARE' = undefined,'UNKNOWN-ATTRIBUTES' = [], 'USERNAME' = undefined,'XOR-MAPPED-ADDRESS' = undefined, 'XOR-PEER-ADDRESS' = [],'XOR-RELAYED-ADDRESS' = undefined} ``` You can then establish connection to running server: ``` 7> {ok, Socket} = gen_udp:open(0, [binary, {ip, 7> {127,0,0,1}},{active,false}]). {ok,#Port<0.1020>} 8> {ok, Addr} = inet:sockname(Socket). {ok,{{127,0,0,1},41906}} ``` The following call is for encoding BindRequest: ``` 9> PktOut = stun_codec:encode(Msg). <<0,1,0,0,33,18,164,66,135,24,78,148,65,4,128,0,0,0,0,1>> ``` The BindRequest can then be send: ``` 10> gen_udp:send(Socket, {127,0,0,1}, 3478, PktOut). ok ``` The follow code receives the BindResponse: ``` 11> {ok, {_, _, PktIn}} = gen_udp:recv(Socket, 0). {ok,{{127,0,0,1}, 3478, <<1,1,0,32,33,18,164,66,135,24,78,148,65,4,128,0,0,0,0, 1,128,34,0,15,...>>}} ``` You can then decode the BindResponse: ``` 12> {ok, Response} = stun_codec:decode(PktIn, datagram). {ok,#stun{class = response,method = 1,magic = 554869826, trid = 41809861624941132369239212033,raw = <<>>, unsupported = [],'ALTERNATE-SERVER' = undefined, 'CHANNEL-NUMBER' = undefined,'DATA' = undefined, 'DONT-FRAGMENT' = false,'ERROR-CODE' = undefined, 'LIFETIME' = undefined,'MAPPED-ADDRESS' = undefined, 'MESSAGE-INTEGRITY' = undefined,'NONCE' = undefined, 'REALM' = undefined,'REQUESTED-TRANSPORT' = undefined, 'SOFTWARE' = <<"P1 STUN library">>, 'UNKNOWN-ATTRIBUTES' = [],'USERNAME' = undefined, 'XOR-MAPPED-ADDRESS' = {{127,0,0,1},41906}, 'XOR-PEER-ADDRESS' = [],'XOR-RELAYED-ADDRESS' = undefined}} ``` Finally, checking 'XOR-MAPPED-ADDRESS' attribute, should be equal to locally binded address: ``` 13> Addr == Response#stun.'XOR-MAPPED-ADDRESS'. true ``` ## Development ### Test #### Unit test You can run eunit test with the command: make test # References You can refer to IETF specifications to learn more: * [RFC 5389](https://tools.ietf.org/html/rfc5389): Session Traversal Utilities for NAT (STUN). * [RFC 5766](https://tools.ietf.org/html/rfc5766): Traversal Using Relays around NAT (TURN): Relay Extensions to STUN. * [RFC 5245](https://tools.ietf.org/html/rfc5245): Interactive Connectivity Establishment (ICE): A Protocol for NAT Traversal for Offer/Answer Protocols. * [RFC 6544](https://tools.ietf.org/html/rfc6544): TCP Candidates with Interactive Connectivity Establishment (ICE) stun-1.0.20/rebar.config.script0000644000232200023220000000773313225634002016725 0ustar debalancedebalance%%%---------------------------------------------------------------------- %%% File : rebar.config.script %%% Author : Evgeniy Khramtsov %%% Purpose : Rebar build script. Compliant with rebar and rebar3. %%% Created : 8 May 2013 by Evgeniy Khramtsov %%% %%% Copyright (C) 2002-2017 ProcessOne, SARL. All Rights Reserved. %%% %%% Licensed under the Apache License, Version 2.0 (the "License"); %%% you may not use this file except in compliance with the License. %%% You may obtain a copy of the License at %%% %%% http://www.apache.org/licenses/LICENSE-2.0 %%% %%% Unless required by applicable law or agreed to in writing, software %%% distributed under the License is distributed on an "AS IS" BASIS, %%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %%% See the License for the specific language governing permissions and %%% limitations under the License. %%% %%%---------------------------------------------------------------------- IsRebar3 = case application:get_key(rebar, vsn) of {ok, VSN} -> [VSN1 | _] = string:tokens(VSN, "-"), [Maj, Min, Patch] = string:tokens(VSN1, "."), (list_to_integer(Maj) >= 3); undefined -> lists:keymember(mix, 1, application:loaded_applications()) end, JobId = case os:getenv("TRAVIS_JOB_ID") of false -> ""; V -> V end, ModCfg0 = fun(F, Cfg, [Key|Tail], Op, Default) -> {OldVal,PartCfg} = case lists:keytake(Key, 1, Cfg) of {value, {_, V1}, V2} -> {V1, V2}; false -> {if Tail == [] -> Default; true -> [] end, Cfg} end, case Tail of [] -> [{Key, Op(OldVal)} | PartCfg]; _ -> [{Key, F(F, OldVal, Tail, Op, Default)} | PartCfg] end end, ModCfg = fun(Cfg, Keys, Op, Default) -> ModCfg0(ModCfg0, Cfg, Keys, Op, Default) end, ModCfgS = fun(Cfg, Keys, Val) -> ModCfg0(ModCfg0, Cfg, Keys, fun(_V) -> Val end, "") end, FilterConfig = fun(F, Cfg, [{Path, true, ModFun, Default} | Tail]) -> F(F, ModCfg0(ModCfg0, Cfg, Path, ModFun, Default), Tail); (F, Cfg, [_ | Tail]) -> F(F, Cfg, Tail); (F, Cfg, []) -> Cfg end, AppendStr = fun(Append) -> fun("") -> Append; (Val) -> Val ++ " " ++ Append end end, AppendList = fun(Append) -> fun(Val) -> Val ++ Append end end, Rebar3DepsFilter = fun(DepsList) -> lists:map(fun({DepName,_, {git,_, {tag,Version}}}) -> {DepName, Version}; (Dep) -> Dep end, DepsList) end, GlobalDepsFilter = fun(Deps) -> DepNames = lists:map(fun({DepName, _, _}) -> DepName; ({DepName, _}) -> DepName end, Deps), lists:filtermap(fun(Dep) -> case code:lib_dir(Dep) of {error, _} -> {true,"Unable to locate dep '"++atom_to_list(Dep)++"' in system deps."}; _ -> false end end, DepNames) end, Rules = [ {[deps], IsRebar3, Rebar3DepsFilter, []}, {[plugins], IsRebar3, AppendList([rebar3_hex, pc]), []}, {[provider_hooks], IsRebar3, AppendList([{pre, [ {compile, {pc, compile}}, {clean, {pc, clean}} ]}]), []}, {[deps], os:getenv("TRAVIS") == "true", AppendList([{coveralls, ".*", {git, "https://github.com/markusn/coveralls-erl.git", "master"}}]), []}, {[post_hooks], os:getenv("TRAVIS") == "true", AppendList([{eunit, "echo '\n%%! -pa .eunit/ deps/coveralls/ebin\nmain(_)->{ok,F}=file:open(\"erlang.json\",[write]),io:fwrite(F,\"~s\",[coveralls:convert_file(\".eunit/cover.coverdata\", \""++JobId++"\", \"travis-ci\",\"\")]).' > getcover.erl"}, {eunit, "escript ./getcover.erl"}]), []}, {[deps], os:getenv("USE_GLOBAL_DEPS") /= false, GlobalDepsFilter, []} ], Config = FilterConfig(FilterConfig, CONFIG, Rules), %io:format("Rules:~n~p~n~nCONFIG:~n~p~n~nConfig:~n~p~n", [Rules, CONFIG, Config]), Config. %% Local Variables: %% mode: erlang %% End: %% vim: set filetype=erlang tabstop=8: stun-1.0.20/CHANGELOG.md0000644000232200023220000000276113225634002014745 0ustar debalancedebalance# Version 1.0.20 * Updating fast_tls to version 1.0.20. # Version 1.0.19 * Updating fast_tls to version 1.0.19. # Version 1.0.18 * Updating fast_tls to version 71250ae. * Fix compilation warnings # Version 1.0.17 * Updating fast_tls to version 1.0.18. # Version 1.0.16 * Updating fast_tls to version 1.0.17. # Version 1.0.15 * Updating fast_tls to version 1.0.16. * Updating p1_utils to version 1.0.10. # Version 1.0.14 * Updating fast_tls to version 1.0.15. # Version 1.0.13 * Updating fast_tls to version 1.0.14. * Make test not crash on R20 (Paweł Chmielowski) # Version 1.0.12 * Updating fast_tls to version 1.0.13. # Version 1.0.11 * Update Fast TLS and p1_utils (Christophe Romain) # Version 1.0.10 * Update Fast TLS and p1_utils (Christophe Romain) # Version 1.0.9 * Update Fast TLS (Mickaël Rémond) # Version 1.0.8 * Use p1_utils 1.0.6 (Christophe Romain) * Update Fast TLS (Mickaël Rémond) # Version 1.0.7 * Update Fast TLS and p1_utils (Mickaël Rémond) # Version 1.0.6 * Update Fast TLS (Mickaël Rémond) # Version 1.0.5 * Update Fast TLS and p1_utils (Mickaël Rémond) # Version 1.0.4 * Use Fast TLS 1.0.4 (Mickaël Rémond) # Version 1.0.3 * Use Fast TLS 1.0.3 (Mickaël Rémond) # Version 1.0.2 * Use Fast TLS 1.0.2 (Mickaël Rémond) # Version 1.0.1 * Use Fast TLS 1.0.1 (Mickaël Rémond) # Version 1.0.0 * Prepare release on Hex.pm (Mickaël Rémond) * Rename application to stun instead of p1_stun (Mickaël Rémond) * Document usage (Evgeny Khramtsov) stun-1.0.20/Makefile0000644000232200023220000000027613225634002014573 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-1.0.20/src/0000755000232200023220000000000013225634002013715 5ustar debalancedebalancestun-1.0.20/src/turn.erl0000644000232200023220000004121513225634002015414 0ustar debalancedebalance%%%------------------------------------------------------------------- %%% File : turn.erl %%% Author : Evgeniy Khramtsov %%% Description : Handles TURN allocations, see RFC5766 %%% Created : 23 Aug 2009 by Evgeniy Khramtsov %%% %%% %%% Copyright (C) 2002-2017 ProcessOne, SARL. All Rights Reserved. %%% %%% Licensed under the Apache License, Version 2.0 (the "License"); %%% you may not use this file except in compliance with the License. %%% You may obtain a copy of the License at %%% %%% http://www.apache.org/licenses/LICENSE-2.0 %%% %%% Unless required by applicable law or agreed to in writing, software %%% distributed under the License is distributed on an "AS IS" BASIS, %%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %%% See the License for the specific language governing permissions and %%% limitations under the License. %%% %%%------------------------------------------------------------------- -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 | fast_tls, sock :: inet:socket() | fast_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} = p1_time_compat:timestamp(), 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}, ?dbg("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}), ?dbg("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 -> ?dbg("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. -ifdef(debug). addr_to_str({Addr, Port}) -> [inet_parse:ntoa(Addr), $:, integer_to_list(Port)]; addr_to_str(Addr) -> inet_parse:ntoa(Addr). -endif. 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-1.0.20/src/turn_tmp_sup.erl0000644000232200023220000000506613225634002017167 0ustar debalancedebalance%%%---------------------------------------------------------------------- %%% File : turn_tmp_sup.erl %%% Author : Evgeniy Khramtsov %%% Purpose : %%% Created : 3 May 2014 by Evgeniy Khramtsov %%% %%% %%% Copyright (C) 2002-2017 ProcessOne, SARL. All Rights Reserved. %%% %%% Licensed under the Apache License, Version 2.0 (the "License"); %%% you may not use this file except in compliance with the License. %%% You may obtain a copy of the License at %%% %%% http://www.apache.org/licenses/LICENSE-2.0 %%% %%% Unless required by applicable law or agreed to in writing, software %%% distributed under the License is distributed on an "AS IS" BASIS, %%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %%% See the License for the specific language governing permissions and %%% limitations under the License. %%% %%%---------------------------------------------------------------------- -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-1.0.20/src/stun_tmp_sup.erl0000644000232200023220000000506613225634002017170 0ustar debalancedebalance%%%---------------------------------------------------------------------- %%% File : stun_tmp_sup.erl %%% Author : Evgeniy Khramtsov %%% Purpose : %%% Created : 3 May 2014 by Evgeniy Khramtsov %%% %%% %%% Copyright (C) 2002-2017 ProcessOne, SARL. All Rights Reserved. %%% %%% Licensed under the Apache License, Version 2.0 (the "License"); %%% you may not use this file except in compliance with the License. %%% You may obtain a copy of the License at %%% %%% http://www.apache.org/licenses/LICENSE-2.0 %%% %%% Unless required by applicable law or agreed to in writing, software %%% distributed under the License is distributed on an "AS IS" BASIS, %%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %%% See the License for the specific language governing permissions and %%% limitations under the License. %%% %%%---------------------------------------------------------------------- -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-1.0.20/src/stun_sup.erl0000644000232200023220000000430313225634002016301 0ustar debalancedebalance%%%---------------------------------------------------------------------- %%% File : stun_sup.erl %%% Author : Evgeniy Khramtsov %%% Purpose : stun supervisor %%% Created : 2 May 2013 by Evgeniy Khramtsov %%% %%% %%% Copyright (C) 2002-2017 ProcessOne, SARL. All Rights Reserved. %%% %%% Licensed under the Apache License, Version 2.0 (the "License"); %%% you may not use this file except in compliance with the License. %%% You may obtain a copy of the License at %%% %%% http://www.apache.org/licenses/LICENSE-2.0 %%% %%% Unless required by applicable law or agreed to in writing, software %%% distributed under the License is distributed on an "AS IS" BASIS, %%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %%% See the License for the specific language governing permissions and %%% limitations under the License. %%% %%%---------------------------------------------------------------------- -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-1.0.20/src/stun_codec.erl0000644000232200023220000003043513225634002016554 0ustar debalancedebalance%%%------------------------------------------------------------------- %%% File : stun_codec.erl %%% Author : Evgeniy Khramtsov %%% Description : STUN codec %%% Created : 7 Aug 2009 by Evgeniy Khramtsov %%% %%% %%% Copyright (C) 2002-2017 ProcessOne, SARL. All Rights Reserved. %%% %%% Licensed under the Apache License, Version 2.0 (the "License"); %%% you may not use this file except in compliance with the License. %%% You may obtain a copy of the License at %%% %%% http://www.apache.org/licenses/LICENSE-2.0 %%% %%% Unless required by applicable law or agreed to in writing, software %%% distributed under the License is distributed on an "AS IS" BASIS, %%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %%% See the License for the specific language governing permissions and %%% limitations under the License. %%% %%%------------------------------------------------------------------- -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-1.0.20/src/stun_listener.erl0000644000232200023220000001523213225634002017322 0ustar debalancedebalance%%%---------------------------------------------------------------------- %%% File : stun_listener.erl %%% Author : Evgeniy Khramtsov %%% Purpose : %%% Created : 9 Jan 2011 by Evgeniy Khramtsov %%% %%% %%% Copyright (C) 2002-2017 ProcessOne, SARL. All Rights Reserved. %%% %%% Licensed under the Apache License, Version 2.0 (the "License"); %%% you may not use this file except in compliance with the License. %%% You may obtain a copy of the License at %%% %%% http://www.apache.org/licenses/LICENSE-2.0 %%% %%% Unless required by applicable law or agreed to in writing, software %%% distributed under the License is distributed on an "AS IS" BASIS, %%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %%% See the License for the specific language governing permissions and %%% limitations under the License. %%% %%%---------------------------------------------------------------------- -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-1.0.20/src/stun.erl0000644000232200023220000005027513225634002015423 0ustar debalancedebalance%%%------------------------------------------------------------------- %%% File : stun.erl %%% Author : Evgeniy Khramtsov %%% Description : RFC5389/RFC5766 implementation. %%% Created : 8 Aug 2009 by Evgeniy Khramtsov %%% %%% %%% Copyright (C) 2002-2017 ProcessOne, SARL. All Rights Reserved. %%% %%% Licensed under the Apache License, Version 2.0 (the "License"); %%% you may not use this file except in compliance with the License. %%% You may obtain a copy of the License at %%% %%% http://www.apache.org/licenses/LICENSE-2.0 %%% %%% Unless required by applicable law or agreed to in writing, software %%% distributed under the License is distributed on an "AS IS" BASIS, %%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %%% See the License for the specific language governing permissions and %%% limitations under the License. %%% %%%------------------------------------------------------------------- -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() | fast_tls:tls_socket(), sock_mod = gen_tcp :: gen_udp | gen_tcp | fast_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 = fast_tls} = State) -> NewState = update_shaper(State, TLSData), case fast_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 -> ?dbg("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() -> {p1_time_compat:monotonic_time(micro_seconds), p1_time_compat:unique_integer([monotonic])}. clean_treap(Treap, CleanPriority) -> case treap:is_empty(Treap) of true -> Treap; false -> {_Key, {TS, _}, _Value} = treap:get_root(Treap), if TS > CleanPriority -> clean_treap(treap:delete_root(Treap), CleanPriority); true -> Treap end end. make_nonce(Addr, Nonces) -> Priority = now_priority(), {TS, _} = Priority, Nonce = list_to_binary(integer_to_list(random:uniform(1 bsl 32))), NewNonces = clean_treap(Nonces, TS + ?NONCE_LIFETIME), {Nonce, treap:insert(Nonce, Priority, Addr, NewNonces)}. have_nonce(Nonce, Nonces) -> TS = p1_time_compat:monotonic_time(micro_seconds), NewNonces = clean_treap(Nonces, TS + ?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 -> fast_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, fast_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, fast_tls, CertFile, _PeerAddr) -> fast_tls:tcp_to_tls(Sock, [{certfile, CertFile}]); maybe_starttls(Sock, gen_tcp, _CertFile, _PeerAddr) -> {ok, Sock}. seed() -> {A, B, C} = p1_time_compat:timestamp(), 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-1.0.20/src/turn_sm.erl0000644000232200023220000000514513225634002016115 0ustar debalancedebalance%%%------------------------------------------------------------------- %%% File : turn_sm.erl %%% Author : Evgeniy Khramtsov %%% Description : Registers TURN sessions and credentials %%% Created : 23 Aug 2009 by Evgeniy Khramtsov %%% %%% %%% Copyright (C) 2002-2017 ProcessOne, SARL. All Rights Reserved. %%% %%% Licensed under the Apache License, Version 2.0 (the "License"); %%% you may not use this file except in compliance with the License. %%% You may obtain a copy of the License at %%% %%% http://www.apache.org/licenses/LICENSE-2.0 %%% %%% Unless required by applicable law or agreed to in writing, software %%% distributed under the License is distributed on an "AS IS" BASIS, %%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %%% See the License for the specific language governing permissions and %%% limitations under the License. %%% %%%------------------------------------------------------------------- -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-1.0.20/src/stun_app.erl0000644000232200023220000000532313225634002016255 0ustar debalancedebalance%%%---------------------------------------------------------------------- %%% File : stun_app.erl %%% Author : Evgeniy Khramtsov %%% Purpose : stun application %%% Created : 2 May 2013 by Evgeniy Khramtsov %%% %%% %%% Copyright (C) 2002-2017 ProcessOne, SARL. All Rights Reserved. %%% %%% Licensed under the Apache License, Version 2.0 (the "License"); %%% you may not use this file except in compliance with the License. %%% You may obtain a copy of the License at %%% %%% http://www.apache.org/licenses/LICENSE-2.0 %%% %%% Unless required by applicable law or agreed to in writing, software %%% distributed under the License is distributed on an "AS IS" BASIS, %%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %%% See the License for the specific language governing permissions and %%% limitations under the License. %%% %%%---------------------------------------------------------------------- -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(fast_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-1.0.20/src/stun.app.src0000644000232200023220000000270513225634002016202 0ustar debalancedebalance%%%---------------------------------------------------------------------- %%% File : stun.app.src %%% Author : Evgeniy Khramtsov %%% Purpose : Application package description %%% Created : 4 Apr 2013 by Evgeniy Khramtsov %%% %%% %%% Copyright (C) 2002-2017 ProcessOne, SARL. All Rights Reserved. %%% %%% Licensed under the Apache License, Version 2.0 (the "License"); %%% you may not use this file except in compliance with the License. %%% You may obtain a copy of the License at %%% %%% http://www.apache.org/licenses/LICENSE-2.0 %%% %%% Unless required by applicable law or agreed to in writing, software %%% distributed under the License is distributed on an "AS IS" BASIS, %%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %%% See the License for the specific language governing permissions and %%% limitations under the License. %%% %%%---------------------------------------------------------------------- {application, stun, [{description, "STUN and TURN library for Erlang / Elixir"}, {vsn, "1.0.20"}, {modules, []}, {registered, []}, {applications, [kernel, stdlib, p1_utils]}, {mod, {stun_app,[]}}, %% hex.pm packaging: {licenses, ["Apache 2.0"]}, {maintainers, ["ProcessOne"]}, {links, [{"Github", "https://github.com/processone/stun"}]}]}. %% Local Variables: %% mode: erlang %% End: %% vim: set filetype=erlang tabstop=8: stun-1.0.20/src/stun_test.erl0000644000232200023220000003676513225634002016472 0ustar debalancedebalance%%%------------------------------------------------------------------- %%% File : stun_test.erl %%% Author : Evgeniy Khramtsov %%% Description : STUN test suite %%% Created : 7 Aug 2009 by Evgeniy Khramtsov %%% %%% %%% Copyright (C) 2002-2017 ProcessOne, SARL. All Rights Reserved. %%% %%% Licensed under the Apache License, Version 2.0 (the "License"); %%% you may not use this file except in compliance with the License. %%% You may obtain a copy of the License at %%% %%% http://www.apache.org/licenses/LICENSE-2.0 %%% %%% Unless required by applicable law or agreed to in writing, software %%% distributed under the License is distributed on an "AS IS" BASIS, %%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %%% See the License for the specific language governing permissions and %%% limitations under the License. %%% %%%------------------------------------------------------------------- -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(fast_tls)), ?assertEqual(ok, application:start(p1_utils)), ?assertEqual(ok, application:start(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} = fast_tls:tcp_to_tls( Socket, [{certfile, <<"certfile.pem">>}, connect]), ?assertEqual({ok, <<>>}, fast_tls:recv_data(TLSSocket, <<>>)), {ok, Addr} = fast_tls:sockname(TLSSocket), Pkt = stun_codec:encode(Msg), recv(TLSSocket, <<>>, true), ?assertEqual(ok, fast_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:strong_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:strong_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} = fast_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} = p1_time_compat:timestamp(), 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-1.0.20/src/stun_shaper.erl0000644000232200023220000000443713225634002016764 0ustar debalancedebalance%%%---------------------------------------------------------------------- %%% File : stun_shaper.erl %%% Author : Alexey Shchepin %%% Purpose : Functions to control connections traffic %%% Created : 9 Feb 2003 by Alexey Shchepin %%% %%% %%% Copyright (C) 2002-2017 ProcessOne, SARL. All Rights Reserved. %%% %%% Licensed under the Apache License, Version 2.0 (the "License"); %%% you may not use this file except in compliance with the License. %%% You may obtain a copy of the License at %%% %%% http://www.apache.org/licenses/LICENSE-2.0 %%% %%% Unless required by applicable law or agreed to in writing, software %%% distributed under the License is distributed on an "AS IS" BASIS, %%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %%% See the License for the specific language governing permissions and %%% limitations under the License. %%% %%%---------------------------------------------------------------------- -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 = p1_time_compat:monotonic_time(micro_seconds)}. -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 = (p1_time_compat:monotonic_time(micro_seconds) - State#maxrate.lasttime) / 1000, Pause = if MinInterv > Interv -> 1 + trunc(MinInterv - Interv); true -> 0 end, NextNow = p1_time_compat:monotonic_time(micro_seconds) + Pause * 1000, {State#maxrate{lastrate = (State#maxrate.lastrate + 1000000 * Size / (NextNow - State#maxrate.lasttime)) / 2, lasttime = NextNow}, Pause}. stun-1.0.20/rebar.config0000644000232200023220000000272613225634002015417 0ustar debalancedebalance%%%---------------------------------------------------------------------- %%% File : rebar.config.script %%% Author : Mickael Remond %%% Purpose : Rebar build script. Compliant with rebar and rebar3. %%% Created : 24 Nov 2015 by Mickael Remond %%% %%% Copyright (C) 2002-2017 ProcessOne, SARL. All Rights Reserved. %%% %%% Licensed under the Apache License, Version 2.0 (the "License"); %%% you may not use this file except in compliance with the License. %%% You may obtain a copy of the License at %%% %%% http://www.apache.org/licenses/LICENSE-2.0 %%% %%% Unless required by applicable law or agreed to in writing, software %%% distributed under the License is distributed on an "AS IS" BASIS, %%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %%% See the License for the specific language governing permissions and %%% limitations under the License. %%% %%%---------------------------------------------------------------------- {erl_opts, [debug_info, {i, "include"}]}. {deps, [{fast_tls, ".*", {git, "https://github.com/processone/fast_tls", {tag, "1.0.20"}}}, {p1_utils, ".*", {git, "https://github.com/processone/p1_utils", {tag, "1.0.10"}}}]}. {cover_enabled, true}. {cover_export_enabled, true}. {xref_checks, [undefined_function_calls, undefined_functions, deprecated_function_calls, deprecated_functions]}. %% Local Variables: %% mode: erlang %% End: %% vim: set filetype=erlang tabstop=8: stun-1.0.20/include/0000755000232200023220000000000013225634002014551 5ustar debalancedebalancestun-1.0.20/include/stun.hrl0000644000232200023220000000700113225634002016247 0ustar debalancedebalance%%%------------------------------------------------------------------- %%% File : stun.hrl %%% Author : Evgeniy Khramtsov %%% Description : STUN values %%% Created : 8 Aug 2009 by Evgeniy Khramtsov %%% %%% %%% Copyright (C) 2002-2017 ProcessOne, SARL. All Rights Reserved. %%% %%% Licensed under the Apache License, Version 2.0 (the "License"); %%% you may not use this file except in compliance with the License. %%% You may obtain a copy of the License at %%% %%% http://www.apache.org/licenses/LICENSE-2.0 %%% %%% Unless required by applicable law or agreed to in writing, software %%% distributed under the License is distributed on an "AS IS" BASIS, %%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %%% See the License for the specific language governing permissions and %%% limitations under the License. %%% %%%------------------------------------------------------------------- -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).