stun-1.2.10/0000755000232200023220000000000014513201307013126 5ustar debalancedebalancestun-1.2.10/include/0000755000232200023220000000000014513201307014551 5ustar debalancedebalancestun-1.2.10/include/stun_logger.hrl0000644000232200023220000000360414513201307017613 0ustar debalancedebalance%%%---------------------------------------------------------------------- %%% File : stun_logger.hrl %%% Author : Holger Weiss %%% Purpose : Wrap OTP Logger for STUN/TURN logging %%% Created : 19 Jul 2020 by Holger Weiss %%% %%% %%% Copyright (C) 2020-2023 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. %%% %%%---------------------------------------------------------------------- -ifdef(USE_OLD_LOGGER). %%-define(debug, true). -ifdef(debug). -define(LOG_DEBUG(Str), stun_logger:log(info, Str)). -define(LOG_DEBUG(Str, Args), stun_logger:log(info, Str, Args)). -define(LOG_INFO(Str), stun_logger:log(info, Str)). -define(LOG_INFO(Str, Args), stun_logger:log(info, Str, Args)). -else. -define(LOG_DEBUG(Str), ok). -define(LOG_DEBUG(Str, Args), begin _ = Args end). -define(LOG_INFO(Str), ok). -define(LOG_INFO(Str, Args), begin _ = Args end). -endif. -define(LOG_NOTICE(Str), stun_logger:log(info, Str)). -define(LOG_NOTICE(Str, Args), stun_logger:log(info, Str, Args)). -define(LOG_WARNING(Str), stun_logger:log(warning, Str)). -define(LOG_WARNING(Str, Args), stun_logger:log(warning, Str, Args)). -define(LOG_ERROR(Str), stun_logger:log(error, Str)). -define(LOG_ERROR(Str, Args), stun_logger:log(error, Str, Args)). -else. % Use new logging API. -include_lib("kernel/include/logger.hrl"). -endif. stun-1.2.10/include/stun.hrl0000644000232200023220000000713314513201307016255 0ustar debalancedebalance%%%------------------------------------------------------------------- %%% File : stun.hrl %%% Author : Evgeniy Khramtsov %%% Description : STUN values %%% Created : 8 Aug 2009 by Evgeniy Khramtsov %%% %%% %%% Copyright (C) 2002-2023 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_REQUESTED_ADDRESS_FAMILY, 16#0017). -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-ADDRESS-FAMILY', 'REQUESTED-TRANSPORT', 'SOFTWARE', 'UNKNOWN-ATTRIBUTES' = [], 'USERNAME', 'XOR-MAPPED-ADDRESS', 'XOR-PEER-ADDRESS' = [], 'XOR-RELAYED-ADDRESS'}). -record(turn, {channel = 0 :: non_neg_integer(), data = <<>> :: binary()}). %% Workarounds. %%-define(NO_PADDING, true). stun-1.2.10/README.md0000644000232200023220000001223214513201307014405 0ustar debalancedebalance# STUN [![CI](https://github.com/processone/stun/actions/workflows/ci.yml/badge.svg?branch=master)](https://github.com/processone/stun/actions/workflows/ci.yml) [![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 media traffic. * 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 at 127.0.0.1: ``` 1> application:start(stun). ok 2> stun_listener:add_listener({127, 0, 0, 1}, 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.2.10/rebar.config0000644000232200023220000000365114513201307015415 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-2023 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, [{platform_define, "win32", 'USE_OLD_INET_BACKEND'}, {platform_define, "^(R|1|20|21|22)", 'USE_OLD_INET_BACKEND'}, {platform_define, "^(R|1|20|21|22)", 'USE_OLD_CRYPTO_HMAC'}, {platform_define, "^(R|1|20|21)", 'USE_OLD_LOGGER'}, debug_info, {i, "include"}]}. {deps, [{fast_tls, ".*", {git, "https://github.com/processone/fast_tls", {tag, "1.1.16"}}}, {p1_utils, ".*", {git, "https://github.com/processone/p1_utils", {tag, "1.0.25"}}}]}. {cover_enabled, true}. {cover_export_enabled, true}. {coveralls_coverdata , "_build/test/cover/eunit.coverdata"}. {coveralls_service_name , "github"}. {xref_checks, [undefined_function_calls, undefined_functions, deprecated_function_calls, deprecated_functions]}. {edoc_opts, [{preprocess, true}]}. {dialyzer, [{plt_extra_apps, [eunit]}]}. %% Local Variables: %% mode: erlang %% End: %% vim: set filetype=erlang tabstop=8: stun-1.2.10/CHANGELOG.md0000644000232200023220000001473114513201307014745 0ustar debalancedebalance# Version 1.2.10 * Improve dialyzer support # Version 1.2.9 * Allow for specifying white/blacklists for clients and peers separately. # Version 1.2.8 * Fix expiry of nonces. # Version 1.2.7 * Handle transport autodetection error gracefully * Remove unused error handling # Version 1.2.6 * Updating fast_tls to version 1.1.16. * Increase receive timeout # Version 1.2.5 * Hand over error events to callback function. * Improve TCP/TLS performance if no traffic shaper is configured. # Version 1.2.4 * Improve handling of invalid `REQUESTED-ADDRESS-FAMILY` value. * Apply minor logging improvements. * Reopen listener sockets if they were closed. # Version 1.2.3 * Don't complain about `proxy_protocol` option. * Gracefully handle errors while receiving UDP data. * Reduce log level of errors that may occur during normal operation. * Restart listeners on failure. # Version 1.2.2 * Updating fast_tls to version 1.1.15. * Updating p1_utils to version 1.0.25. # Version 1.2.1 * Updating fast_tls to version 1.1.14. * Updating p1_utils to version 1.0.23. * Include 'SOFTWARE' attribute in responses. * Use random session IDs. # Version 1.2.0 * Allow for whitelisting IP addresses/subnets. * Accept expired credentials for TURN session refreshes. * Accept additional TLS options/ciphers. # Version 1.1.0 * Support the HAproxy protocol (v1 and v2). * Don't close listener if accepting a connection fails. * Only use new 'socket' backend for multiplexing TCP/TLS listeners. # Version 1.0.47 * Disable new 'socket' backend for TCP/TLS connections on Windows. # Version 1.0.46 * Use new 'socket' backend for TCP/TLS connections (on Erlang/OTP 23+). * Support multiplexing TCP/TLS listeners (on Erlang/OTP 23+). # Version 1.0.45 * Improve UDP receive performance. * Reduce risk of UDP packet loss. * Support multiple passwords to facilitate rollover. # Version 1.0.44 * Updating fast_tls to version 1.1.13. * Updating p1_utils to version 1.0.23. * Switch from using Travis to Github Actions as CI # Version 1.0.43 * Updating p1_utils to version 1.0.22. * Updating fast_tls to version 1.1.12. * stun_test: Start up transitive dependencies # Version 1.0.42 * Updating fast_tls to version 1.1.11. # Version 1.0.41 * Never accept Teredo/6to4 addresses as TURN peers. * Never accept 0.0.0.0/:: addresses as TURN peers. # Version 1.0.40 * Updating fast_tls to version 1.1.10. * Updating p1_utils to version 1.0.21. # Version 1.0.39 * Updating fast_tls to version 1.1.9. * Exclude from Travis old OTP releases * Reduce log level for requests from incompatible clients. # Version 1.0.38 * Always log reason for TCP/TLS connection termination. * Log relay allocation refreshes at notice level. * Log duration of TURN sessions. * Log STUN queries at debug (rather than info) level. * Hand over more metadata to STUN callback. # Version 1.0.37 * Updating p1_utils to version 1.0.20. * Updating fast_tls to version 1.1.8. # Version 1.0.36 * Log relay (de)allocation rather than authentication at notice level. * Allow worker processes to perform cleanup tasks on shutdown. * Support event callbacks. # Version 1.0.35 * Updating fast_tls to version 1.1.7. * Add session ID, transport, username, and IP addresses to log output. * Log number of TURN-relayed bytes and packets. * Log plain STUN (Binding) responses. * Log all error responses. # Version 1.0.34 * Allow for binding listeners to specific IP addresses. * Use new logging API on Erlang/OTP 22+. # Version 1.0.33 * Updating fast_tls to version 1.1.6. * Updating p1_utils to version 1.0.19. * Fix compatibility issues with Erlang 23 * Add support for ipv6 clients * Improve compatibilty with clients # Version 1.0.32 * Updating fast_tls to version 1.1.5. * Make sure that 'turn\_ip' address is used for communicating with peer. * Make sure that opened socket uses ipv4. # Version 1.0.31 * Updating fast_tls to version 1.1.4. * Updating p1_utils to version 1.0.18. * Update copyright year # Version 1.0.30 * Updating fast_tls to version 1.1.3. * Updating p1_utils to version 1.0.17. # Version 1.0.29 * Updating fast_tls to version 1.1.2. * Updating p1_utils to version 1.0.16. # Version 1.0.28 * Updating fast_tls to version 1.1.1. * Updating p1_utils to version 1.0.15. # Version 1.0.27 * Updating fast_tls to version 1.1.0. * Updating p1_utils to version 1.0.14. * Add contribution guide # Version 1.0.26 * Updating fast_tls to version 1.0.26. # Version 1.0.25 * Updating p1_utils to version 1.0.13. * Updating fast_tls to version 1.0.25. # Version 1.0.24 * Updating fast_tls to version f36ea5b74526c2c1c9c38f8d473168d95804f59d. * Updating p1_utils to version 6ff85e8. # Version 1.0.23 * Updating fast_tls to version 1.0.23. * Updating p1_utils to version 1.0.12. * Use p1\_fsm instead of gen\_fsm * Remove unused dependency on port compiler # Version 1.0.22 * Updating fast_tls to version a166f0e. # Version 1.0.21 * Updating fast_tls to version 1.0.21. * Updating p1_utils to version 1.0.11. * Fix compilation with rebar3 * Fix warning about deprecated random * Fix typo in README # 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.2.10/LICENSE.txt0000644000232200023220000002613614513201307014761 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.2.10/Makefile0000644000232200023220000000033514513201307014567 0ustar debalancedebalanceREBAR ?= rebar all: 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.2.10/rebar.config.script0000644000232200023220000001036314513201307016716 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-2023 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|_] = string:tokens(VSN1, "."), (list_to_integer(Maj) >= 3); undefined -> lists:keymember(mix, 1, application:loaded_applications()) 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, code:ensure_loaded(rand), RandUniform = erlang:function_exported(rand, uniform, 1), GithubConfig = case {os:getenv("GITHUB_ACTIONS"), os:getenv("GITHUB_TOKEN")} of {"true", Token} when is_list(Token) -> CONFIG1 = [{coveralls_repo_token, Token}, {coveralls_service_job_id, os:getenv("GITHUB_RUN_ID")}, {coveralls_commit_sha, os:getenv("GITHUB_SHA")}, {coveralls_service_number, os:getenv("GITHUB_RUN_NUMBER")}], case os:getenv("GITHUB_EVENT_NAME") =:= "pull_request" andalso string:tokens(os:getenv("GITHUB_REF"), "/") of [_, "pull", PRNO, _] -> [{coveralls_service_pull_request, PRNO} | CONFIG1]; _ -> CONFIG1 end; _ -> [] end, Rules = [ {[deps], IsRebar3, Rebar3DepsFilter, []}, {[erl_opts], RandUniform, AppendList([{d, 'RAND_UNIFORM'}]), []}, {[plugins], os:getenv("COVERALLS") == "true", AppendList([{coveralls, {git, "https://github.com/processone/coveralls-erl.git", {branch, "addjsonfile"}}} ]), []}, {[deps], os:getenv("USE_GLOBAL_DEPS") /= false, GlobalDepsFilter, []} ], Config = FilterConfig(FilterConfig, CONFIG, Rules) ++ GithubConfig, %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.2.10/src/0000755000232200023220000000000014513201307013715 5ustar debalancedebalancestun-1.2.10/src/stun_codec.erl0000644000232200023220000003212714513201307016554 0ustar debalancedebalance%%%------------------------------------------------------------------- %%% File : stun_codec.erl %%% Author : Evgeniy Khramtsov %%% Description : STUN codec %%% Created : 7 Aug 2009 by Evgeniy Khramtsov %%% %%% %%% Copyright (C) 2002-2023 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"). -ifdef(USE_OLD_CRYPTO_HMAC). crypto_hmac(Type, Key, Data) -> crypto:hmac(Type, Key, Data). -else. crypto_hmac(Type, Key, Data) -> crypto:mac(hmac, Type, Key, Data). -endif. %%==================================================================== %% 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 = <>, Fingerprint = erlang:crc32(Data) bxor 16#5354554e, <>. 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(440) -> {440, <<"Address Family not Supported">>}; error(441) -> {441, <<"Wrong Credentials">>}; error(442) -> {442, <<"Unsupported Transport Protocol">>}; error(443) -> {443, <<"Peer Address Family Mismatch">>}; 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_family(Msg#stun.'REQUESTED-ADDRESS-FAMILY'), 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_ADDRESS_FAMILY, Val, Msg) -> <> = Val, Family = case FamilyInt of 1 -> ipv4; 2 -> ipv6; _ -> unknown end, Msg#stun{'REQUESTED-ADDRESS-FAMILY' = Family}; 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_family(undefined) -> <<>>; enc_req_family(ipv4) -> enc_attr(?STUN_ATTR_REQUESTED_ADDRESS_FAMILY, <<1, 0:24>>); enc_req_family(ipv6) -> enc_attr(?STUN_ATTR_REQUESTED_ADDRESS_FAMILY, <<2, 0:24>>). 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.2.10/src/stun_acceptor_sup.erl0000644000232200023220000000317614513201307020170 0ustar debalancedebalance%%%---------------------------------------------------------------------- %%% File : stun_acceptor_sup.erl %%% Author : Holger Weiss %%% Purpose : STUN/TURN listener (child) supervisor %%% Created : 3 Jul 2022 by Holger Weiss %%% %%% %%% Copyright (C) 2022 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_acceptor_sup). -behaviour(supervisor). -author('holger@zedat.fu-berlin.de'). -export([start_link/0]). -export([init/1]). -define(SERVER, ?MODULE). %% API. -spec start_link() -> {ok, pid()} | {error, term()}. start_link() -> supervisor:start_link({local, ?SERVER}, ?MODULE, []). %% Supervisor callbacks. -spec init([]) -> {ok, {supervisor:sup_flags(), [supervisor:child_spec()]}}. init([]) -> SupFlags = #{strategy => simple_one_for_one, intensity => 10, period => 1}, ChildSpecs = [#{id => stun_acceptor, shutdown => brutal_kill, start => {stun_acceptor, start_link, []}}], {ok, {SupFlags, ChildSpecs}}. stun-1.2.10/src/stun_test.erl0000644000232200023220000004333214513201307016456 0ustar debalancedebalance%%%------------------------------------------------------------------- %%% File : stun_test.erl %%% Author : Evgeniy Khramtsov %%% Description : STUN test suite %%% Created : 7 Aug 2009 by Evgeniy Khramtsov %%% %%% %%% Copyright (C) 2002-2023 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, bind_tls/2, allocate_udp/5]). -define(STUN_IP, {127,0,0,1}). -define(STUN_PORT, 34780). -define(AUTO_PORT, 34781). -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() -> ?assertMatch({ok, _}, application:ensure_all_started(p1_utils)), ?assertMatch({ok, _}, application:ensure_all_started(fast_tls)), ?assertMatch({ok, _}, application:ensure_all_started(stun)). mk_cert_test() -> ?assertEqual(ok, file:write_file("certfile.pem", get_cert())). add_udp_listener_test() -> ?assertEqual(ok, stun_listener:add_listener( ?STUN_IP, ?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_IP, ?STUN_PORT, tcp, [])). add_tls_listener_test() -> ?assertEqual(ok, stun_listener:add_listener( ?STUN_IP, ?STUNS_PORT, tcp, [tls, {certfile, "certfile.pem"}])). -ifndef(USE_OLD_INET_BACKEND). add_auto_listener_test() -> ?assertEqual(ok, stun_listener:add_listener( ?STUN_IP, ?AUTO_PORT, tcp, [{tls, optional}, {certfile, "certfile.pem"}])). -endif. bind_udp_test() -> TrID = mk_trid(), Msg = #stun{method = ?STUN_METHOD_BINDING, class = request, trid = TrID}, {ok, Socket} = gen_udp:open(0, [binary, {ip, ?STUN_IP}, {active, false}]), {ok, Addr} = inet:sockname(Socket), PktOut = stun_codec:encode(Msg), ?assertEqual(ok, gen_udp:send(Socket, ?STUN_IP, ?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(?STUN_IP, ?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(?STUN_IP, ?STUNS_PORT, [binary, {active, true}]), {ok, TLSSocket} = fast_tls:tcp_to_tls(Socket, [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)). -ifndef(USE_OLD_INET_BACKEND). bind_auto_test() -> %% TCP TrID1 = mk_trid(), Msg1 = #stun{method = ?STUN_METHOD_BINDING, class = request, trid = TrID1}, {ok, Socket1} = gen_tcp:connect(?STUN_IP, ?AUTO_PORT, [binary, {active, false}]), {ok, Addr1} = inet:sockname(Socket1), Pkt1 = stun_codec:encode(Msg1), ?assertEqual(ok, gen_tcp:send(Socket1, Pkt1)), ?assertMatch( {ok, #stun{trid = TrID1, 'XOR-MAPPED-ADDRESS' = Addr1}}, recv(Socket1, <<>>, false)), ?assertEqual(ok, gen_tcp:close(Socket1)), %% TLS TrID2 = mk_trid(), Msg2 = #stun{method = ?STUN_METHOD_BINDING, class = request, trid = TrID2}, {ok, Socket2} = gen_tcp:connect(?STUN_IP, ?AUTO_PORT, [binary, {active, true}]), {ok, TLSSocket} = fast_tls:tcp_to_tls(Socket2, [connect]), ?assertEqual({ok, <<>>}, fast_tls:recv_data(TLSSocket, <<>>)), {ok, Addr2} = fast_tls:sockname(TLSSocket), Pkt2 = stun_codec:encode(Msg2), recv(TLSSocket, <<>>, true), ?assertEqual(ok, fast_tls:send(TLSSocket, Pkt2)), ?assertMatch( {ok, #stun{trid = TrID2, 'XOR-MAPPED-ADDRESS' = Addr2}}, recv(TLSSocket, <<>>, true)), ?assertEqual(ok, gen_tcp:close(Socket2)). -endif. del_tcp_listener_test() -> ?assertEqual(ok, stun_listener:del_listener(?STUN_IP, ?STUN_PORT, tcp)). del_tls_listener_test() -> ?assertEqual(ok, stun_listener:del_listener(?STUN_IP, ?STUNS_PORT, tcp)). -ifndef(USE_OLD_INET_BACKEND). del_auto_listener_test() -> ?assertEqual(ok, stun_listener:del_listener(?STUN_IP, ?AUTO_PORT, tcp)). -endif. allocate_udp_test() -> {ok, Socket} = gen_udp:open(0, [binary, {ip, ?STUN_IP}, {active, false}]), {ok, PeerSocket} = gen_udp:open(0, [binary, {ip, ?STUN_IP}, {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, ?STUN_IP, ?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, ?STUN_IP, ?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, ?STUN_IP, ?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, ?STUN_IP, ?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, ?STUN_IP, ?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, ?STUN_IP, ?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, ?STUN_IP, ?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. bind_tls(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, true}]), {ok, TLSSocket} = fast_tls:tcp_to_tls(Socket, [connect]), {ok, <<>>} = fast_tls:recv_data(TLSSocket, <<>>), Pkt = stun_codec:encode(MsgOut), recv(TLSSocket, <<>>, true), ok = fast_tls:send(TLSSocket, Pkt), {ok, MsgIn = #stun{trid = TrID, 'XOR-MAPPED-ADDRESS' = _Addr}} = recv(TLSSocket, <<>>, true), 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 1000 -> ok end. mk_trid() -> stun:rand_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.2.10/src/stun_app.erl0000644000232200023220000000323114513201307016251 0ustar debalancedebalance%%%---------------------------------------------------------------------- %%% File : stun_app.erl %%% Author : Evgeniy Khramtsov %%% Purpose : stun application %%% Created : 2 May 2013 by Evgeniy Khramtsov %%% %%% %%% Copyright (C) 2002-2023 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 %%%=================================================================== start(_StartType, _StartArgs) -> stun_logger:start(), application:start(fast_tls), case stun_sup:start_link() of {ok, Pid} -> {ok, Pid}; Error -> Error end. stop(_State) -> stun_logger:stop(), ok. %%%=================================================================== %%% Internal functions %%%=================================================================== stun-1.2.10/src/stun.erl0000644000232200023220000007241414513201307015422 0ustar debalancedebalance%%%------------------------------------------------------------------- %%% File : stun.erl %%% Author : Evgeniy Khramtsov %%% Description : RFC5389/RFC5766 implementation. %%% Created : 8 Aug 2009 by Evgeniy Khramtsov %%% %%% %%% Copyright (C) 2002-2023 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, p1_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]). %% helper functions -export([rand_uniform/0, rand_uniform/1, rand_uniform/2, unmap_v4_addr/1]). -include("stun.hrl"). -include("stun_logger.hrl"). -define(MAX_BUF_SIZE, 64*1024). %% 64kb -define(TIMEOUT, 60000). %% 1 minute -define(TCP_ACTIVE, 500). -define(NONCE_LIFETIME, 60*1000*1000). %% 1 minute (in usec) -define(SERVER_NAME, <<"P1 STUN library">>). -type addr() :: {inet:ip_address(), inet:port_number()}. -record(state, {sock :: inet:socket() | fast_tls:tls_socket() | undefined, sock_mod = gen_tcp :: gen_udp | gen_tcp | fast_tls, peer = {{0,0,0,0}, 0} :: addr(), tref :: reference() | undefined, use_turn = false :: boolean(), relay_ipv4_ip = {127,0,0,1} :: inet:ip4_address(), relay_ipv6_ip :: inet:ip6_address() | undefined, 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, blacklist_clients = [] :: turn:accesslist(), whitelist_clients = [] :: turn:accesslist(), blacklist_peers = [] :: turn:accesslist(), whitelist_peers = [] :: turn:accesslist(), auth = user :: anonymous | user, nonces = treap:empty() :: treap:treap(), realm = <<"">> :: binary(), auth_fun :: function() | undefined, hook_fun :: function() | undefined, server_name = ?SERVER_NAME :: binary(), buf = <<>> :: binary(), session_id :: binary() | undefined}). %%==================================================================== %% 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) -> 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} -> ?LOG_DEBUG(#{verbatim => {"Received:~n~s", [stun_codec:pp(Msg)]}}), process(NewState, Msg); {error, Reason} -> ?LOG_DEBUG("Cannot parse packet: ~s", [Reason]), NewState end. %%==================================================================== %% gen_fsm callbacks %%==================================================================== init([Sock, Opts]) -> process_flag(trap_exit, true), case get_peername(Sock, Opts) of {ok, Addr} -> case get_sockmod(Opts, Sock) of {ok, SockMod} -> State = prepare_state(Opts, Sock, Addr, SockMod), case maybe_starttls(Sock, SockMod, Opts) of {ok, NewSock} -> TRef = erlang:start_timer(?TIMEOUT, self(), stop), NewState = State#state{sock = NewSock, tref = TRef}, activate_socket(NewState), {ok, session_established, NewState}; {error, Reason} -> {stop, Reason} end end; {error, Reason} -> {stop, Reason} end. session_established(Event, State) -> ?LOG_ERROR("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); {error, Reason} -> ?LOG_INFO("Connection failure: ~s", [Reason]), {stop, normal, NewState} end; handle_info({tcp, _Sock, Data}, StateName, State) -> NewState = update_shaper(State, Data), process_data(StateName, NewState, Data); handle_info({tcp_passive, _Sock}, StateName, State) -> activate_socket(State), {next_state, StateName, State}; handle_info({tcp_closed, _Sock}, _StateName, State) -> ?LOG_INFO("Connection reset by peer"), {stop, normal, State}; handle_info({tcp_error, _Sock, _Reason}, _StateName, State) -> ?LOG_INFO("Connection error: ~p", [_Reason]), {stop, normal, State}; handle_info({timeout, TRef, stop}, _StateName, #state{tref = TRef} = State) -> ?LOG_INFO("Connection timed out"), {stop, normal, State}; handle_info({timeout, _TRef, activate}, StateName, State) -> activate_socket(State), {next_state, StateName, State}; handle_info(Info, StateName, State) -> ?LOG_ERROR("Unexpected info in '~s': ~p", [StateName, 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 -> ?LOG_NOTICE("Rejecting request: Credentials provided for anonymous " "service"), Resp = prepare_response(State, Msg), R = Resp#stun{class = error, 'ERROR-CODE' = stun_codec:error(401)}, run_hook(protocol_error, State, R), 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 -> stun_logger:add_metadata(#{stun_user => User}), 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 <<"">> -> ?LOG_NOTICE("Failed long-term STUN/TURN authentication"), run_hook(protocol_error, State, R), send(NewState, R); Pass0 -> {Pass, IsExpired} = check_expired_tag(Pass0), case check_integrity(User, Realm, Msg, Pass) of {true, Key} -> ?LOG_INFO("Accepting long-term STUN/TURN " "authentication"), process(NewState, Msg, Key, IsExpired); false -> ?LOG_NOTICE("Failed long-term STUN/TURN " "authentication"), run_hook(protocol_error, State, R), send(NewState, R) end end; false -> ?LOG_NOTICE("Rejecting request: Nonexistent nonce"), {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}, run_hook(protocol_error, State, R), send(State#state{nonces = NewNonces}, R) end; process(State, #stun{class = request, 'USERNAME' = User, 'REALM' = undefined, 'NONCE' = undefined} = Msg) when User /= undefined -> ?LOG_NOTICE("Rejecting request: Missing realm and nonce"), Resp = prepare_response(State, Msg), R = Resp#stun{class = error, 'ERROR-CODE' = stun_codec:error(401)}, run_hook(protocol_error, State, R), send(State, R); process(State, #stun{class = request} = Msg) -> ?LOG_NOTICE("Rejecting malformed request"), Resp = prepare_response(State, Msg), R = Resp#stun{class = error, 'ERROR-CODE' = stun_codec:error(400)}, run_hook(protocol_error, State, R), 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, Msg, Secret) -> process(State, Msg, Secret, false). process(State, #stun{class = request, unsupported = [_|_] = Unsupported} = Msg, Secret, _IsExpired) -> ?LOG_DEBUG("Rejecting request with unknown attribute(s): ~p", [Unsupported]), Resp = prepare_response(State, Msg), R = Resp#stun{class = error, 'UNKNOWN-ATTRIBUTES' = Unsupported, 'ERROR-CODE' = stun_codec:error(420)}, run_hook(protocol_error, State, R), send(State, R, Secret); process(State, #stun{class = request, method = ?STUN_METHOD_BINDING} = Msg, Secret, _IsExpired) -> Resp = prepare_response(State, Msg), AddrPort = unmap_v4_addr(State#state.peer), R = case stun_codec:version(Msg) of old -> ?LOG_DEBUG("Responding to 'classic' STUN request"), Resp#stun{class = response, 'MAPPED-ADDRESS' = AddrPort}; new -> ?LOG_DEBUG("Responding to STUN request"), Resp#stun{class = response, 'XOR-MAPPED-ADDRESS' = AddrPort} end, run_hook(stun_query, State, Msg), send(State, R, Secret); process(#state{use_turn = false} = State, #stun{class = request} = Msg, Secret, _IsExpired) -> ?LOG_NOTICE("Rejecting TURN request: TURN is disabled"), Resp = prepare_response(State, Msg), R = Resp#stun{class = error, 'ERROR-CODE' = stun_codec:error(405)}, run_hook(protocol_error, State, R), send(State, R, Secret); process(State, #stun{class = request, method = ?STUN_METHOD_ALLOCATE} = Msg, Secret, IsExpired) -> 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; _ when IsExpired -> ?LOG_NOTICE("Rejecting request: credentials expired"), R = Resp#stun{class = error, 'ERROR-CODE' = stun_codec:error(401)}, run_hook(protocol_error, State, R), send(State, R); _ -> Opts = [{sock, State#state.sock}, {sock_mod, SockMod}, {username, Msg#stun.'USERNAME'}, {realm, State#state.realm}, {key, Secret}, {server_name, State#state.server_name}, {max_allocs, State#state.max_allocs}, {max_permissions, State#state.max_permissions}, {blacklist_clients, State#state.blacklist_clients}, {whitelist_clients, State#state.whitelist_clients}, {blacklist_peers, State#state.blacklist_peers}, {whitelist_peers, State#state.whitelist_peers}, {addr, AddrPort}, {relay_ipv4_ip, State#state.relay_ipv4_ip}, {relay_ipv6_ip, State#state.relay_ipv6_ip}, {min_port, State#state.min_port}, {max_port, State#state.max_port}, {hook_fun, State#state.hook_fun}, {session_id, State#state.session_id} | 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} -> ?LOG_NOTICE("Rejecting request: Allocation quota reached"), R = Resp#stun{class = error, 'ERROR-CODE' = stun_codec:error(486)}, run_hook(protocol_error, State, R), send(State, R, Secret); {error, stale} -> ?LOG_NOTICE("Rejecting request: Stale nonce"), R = Resp#stun{class = error, 'ERROR-CODE' = stun_codec:error(438)}, run_hook(protocol_error, State, R), send(State, R); {error, Reason} -> ?LOG_ERROR("Cannot start TURN session: ~s", [Reason]), R = Resp#stun{class = error, 'ERROR-CODE' = stun_codec:error(500)}, run_hook(protocol_error, State, R), send(State, R, Secret) end end; process(State, #stun{class = request, method = ?STUN_METHOD_REFRESH} = Msg, Secret, _IsExpired) -> route_on_turn(State, Msg, Secret); process(State, #stun{class = request, method = ?STUN_METHOD_CREATE_PERMISSION} = Msg, Secret, _IsExpired) -> route_on_turn(State, Msg, Secret); process(State, #stun{class = request, method = ?STUN_METHOD_CHANNEL_BIND} = Msg, Secret, _IsExpired) -> route_on_turn(State, Msg, Secret); process(State, #stun{class = request} = Msg, Secret, _IsExpired) -> ?LOG_NOTICE("Rejecting request: Method not allowed"), Resp = prepare_response(State, Msg), R = Resp#stun{class = error, 'ERROR-CODE' = stun_codec:error(405)}, run_hook(protocol_error, State, R), send(State, R, Secret). process_data(NextStateName, #state{buf = Buf} = State, Data) -> NewBuf = <>, case stun_codec:decode(NewBuf, stream) of {ok, Msg, Tail} -> ?LOG_DEBUG(#{verbatim => {"Received:~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}; {error, Reason} -> ?LOG_DEBUG("Cannot parse packet: ~p", [Reason]), {stop, normal, State} end. update_shaper(#state{shaper = none} = State, _Data) -> State; 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, Pass) -> ?LOG_DEBUG(#{verbatim => {"Sending:~n~s", [stun_codec:pp(Msg)]}}), send(State, stun_codec:encode(Msg, Pass)). route_on_turn(State, Msg) -> route_on_turn(State, Msg, undefined). 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} -> ?LOG_NOTICE("Rejecting request: Allocation mismatch"), Resp = prepare_response(State, Msg), R = Resp#stun{class = error, 'ERROR-CODE' = stun_codec:error(437)}, run_hook(protocol_error, State, R), send(State, R, Pass); _ -> State end end. prepare_state(Opts, Sock, Peer, SockMod) when is_list(Opts) -> ID = case proplists:get_value(session_id, Opts) of ID0 when is_binary(ID0) -> ID0; % Stick to listener's session ID. undefined -> stun_logger:make_id() end, stun_logger:set_metadata(stun, SockMod, ID, Peer), case proplists:get_bool(use_turn, Opts) of true -> lists:foldl( fun({turn_ip, IP}, State) -> case prepare_addr(IP) of {ok, Addr} -> ?LOG_WARNING("'turn_ip' is deprecated, specify " "'turn_ipv4_address' and optionally " "'turn_ipv6_address' instead"), State#state{relay_ipv4_ip = Addr}; {error, _} -> ?LOG_ERROR("Wrong 'turn_ip' value: ~p", [IP]), State end; ({turn_ipv4_address, IP}, State) -> case prepare_addr(IP) of {ok, Addr} -> State#state{relay_ipv4_ip = Addr}; {error, _} -> ?LOG_ERROR("Wrong 'turn_ipv4_address' value: ~p", [IP]), State end; ({turn_ipv6_address, IP}, State) -> case prepare_addr(IP) of {ok, Addr} -> State#state{relay_ipv6_ip = Addr}; {error, _} -> ?LOG_ERROR("Wrong 'turn_ipv6_address' 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) -> ?LOG_ERROR("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) -> ?LOG_ERROR("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) -> ?LOG_ERROR("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) -> ?LOG_ERROR("Wrong 'turn_max_permissions' value: ~p", [Wrong]), State; ({turn_blacklist_clients, B}, #state{blacklist_clients = B0} = State) -> case lists:all(fun is_valid_subnet/1, B) of true -> State#state{blacklist_clients = B0 ++ B}; false -> ?LOG_ERROR("Wrong 'turn_blacklist_clients' " "value: ~p", [B]), State end; ({turn_whitelist_clients, W}, #state{whitelist_clients = W0} = State) -> case lists:all(fun is_valid_subnet/1, W) of true -> State#state{whitelist_clients = W0 ++ W}; false -> ?LOG_ERROR("Wrong 'turn_whitelist_clients' " "value: ~p", [W]), State end; ({turn_blacklist_peers, B}, #state{blacklist_peers = B0} = State) -> case lists:all(fun is_valid_subnet/1, B) of true -> State#state{blacklist_peers = B0 ++ B}; false -> ?LOG_ERROR("Wrong 'turn_blacklist_peers' " "value: ~p", [B]), State end; ({turn_whitelist_peers, W}, #state{whitelist_peers = W0} = State) -> case lists:all(fun is_valid_subnet/1, W) of true -> State#state{whitelist_peers = W0 ++ W}; false -> ?LOG_ERROR("Wrong 'turn_whitelist_peers' " "value: ~p", [W]), State end; ({turn_blacklist, B}, #state{blacklist_clients = C, blacklist_peers = P} = State0) -> case lists:all(fun is_valid_subnet/1, B) of true -> State1 = State0#state{blacklist_clients = C ++ B}, State2 = State1#state{blacklist_peers = P ++ B}, State2; false -> ?LOG_ERROR("Wrong 'turn_blacklist' " "value: ~p", [B]), State0 end; ({turn_whitelist, W}, #state{whitelist_clients = C, whitelist_peers = P} = State0) -> case lists:all(fun is_valid_subnet/1, W) of true -> State1 = State0#state{whitelist_clients = C ++ W}, State2 = State1#state{whitelist_peers = P ++ W}, State2; false -> ?LOG_ERROR("Wrong 'turn_whitelist' " "value: ~p", [W]), State0 end; ({shaper, S}, State) when S == none orelse (is_integer(S) andalso (S > 0)) -> State#state{shaper = stun_shaper:new(S)}; ({shaper, Wrong}, State) -> ?LOG_ERROR("Wrong 'shaper' value: ~p", [Wrong]), State; ({server_name, S}, State) -> try State#state{server_name = iolist_to_binary(S)} catch _:_ -> ?LOG_ERROR("Wrong 'server_name' value: ~p", [S]), State end; ({auth_realm, R}, State) -> try State#state{realm = iolist_to_binary(R)} catch _:_ -> ?LOG_ERROR("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) -> ?LOG_ERROR("Wrong 'auth_fun' value: ~p", [Wrong]), State; ({hook_fun, F}, State) when is_function(F) -> State#state{hook_fun = F}; ({hook_fun, Wrong}, State) -> ?LOG_ERROR("Wrong 'hook_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) -> ?LOG_ERROR("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; ({dhfile, _}, State) -> State; ({ciphers, _}, State) -> State; ({protocol_options, _}, State) -> State; ({tls, _}, State) -> State; (tls, State) -> State; ({proxy_protocol, _}, State) -> State; (proxy_protocol, State) -> State; ({sock_peer_name, _}, State) -> State; ({session_id, _}, State) -> State; (Opt, State) -> ?LOG_ERROR("Ignoring unknown option '~p'", [Opt]), State end, #state{session_id = ID, peer = Peer, sock = Sock, sock_mod = SockMod, use_turn = true}, Opts); _ -> #state{session_id = ID, sock = Sock, sock_mod = SockMod, peer = Peer, hook_fun = proplists:get_value(hook_fun, Opts), auth = anonymous} end; prepare_state(State, _Sock, Peer, SockMod) -> ID = stun_logger:make_id(), stun_logger:set_metadata(stun, SockMod, ID, Peer), State#state{session_id = ID, 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 = gen_tcp, shaper = none}) -> inet:setopts(Sock, [{active, ?TCP_ACTIVE}]); activate_socket(#state{sock = Sock, sock_mod = SockMod, shaper = none}) -> SockMod:setopts(Sock, [{active, ?TCP_ACTIVE}]); activate_socket(#state{sock = Sock, sock_mod = gen_tcp}) -> inet:setopts(Sock, [{active, once}]); activate_socket(#state{sock = Sock, sock_mod = SockMod}) -> SockMod:setopts(Sock, [{active, once}]). 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 = integer_to_binary(rand_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. check_integrity(User, Realm, Msg, Pass) when is_binary(Pass) -> check_integrity(User, Realm, Msg, [Pass]); check_integrity(_User, _Realm, _Msg, []) -> false; check_integrity(User, Realm, Msg, [Pass | T]) -> Key = {User, Realm, Pass}, case stun_codec:check_integrity(Msg, Key) of true -> {true, Key}; false -> check_integrity(User, Realm, Msg, T) end. check_expired_tag({expired, Pass}) -> {Pass, true}; check_expired_tag(Pass) -> {Pass, false}. unmap_v4_addr({{0, 0, 0, 0, 0, 16#FFFF, D7, D8}, Port}) -> {{D7 bsr 8, D7 band 255, D8 bsr 8, D8 band 255}, Port}; unmap_v4_addr(AddrPort) -> AddrPort. is_valid_subnet({{IP1, IP2, IP3, IP4}, Mask}) -> (IP1 >= 0) and (IP1 =< 255) and (IP2 >= 0) and (IP2 =< 255) and (IP3 >= 0) and (IP3 =< 255) and (IP4 >= 0) and (IP4 =< 255) and (Mask >= 0) and (Mask =< 32); is_valid_subnet({{IP1, IP2, IP3, IP4, IP5, IP6, IP7, IP8}, Mask}) -> (IP1 >= 0) and (IP1 =< 65535) and (IP2 >= 0) and (IP2 =< 65535) and (IP3 >= 0) and (IP3 =< 65535) and (IP4 >= 0) and (IP4 =< 65535) and (IP5 >= 0) and (IP5 =< 65535) and (IP6 >= 0) and (IP6 =< 65535) and (IP7 >= 0) and (IP7 =< 65535) and (IP8 >= 0) and (IP8 =< 65535) and (Mask >= 0) and (Mask =< 128); is_valid_subnet(_) -> false. get_sockmod(Opts, Sock) -> case proplists:get_value(tls, Opts, false) of true -> {ok, fast_tls}; false -> {ok, gen_tcp}; optional -> case is_tls_handshake(Sock) of true -> {ok, fast_tls}; false -> {ok, gen_tcp} end end. get_peername(Sock, Opts) -> case proplists:get_value(sock_peer_name, Opts) of {_, Addr} -> {ok, Addr}; undefined -> inet:peername(Sock) end. -ifdef(USE_OLD_INET_BACKEND). -dialyzer({[no_match], [get_sockmod/2]}). is_tls_handshake(_Sock) -> ?LOG_ERROR("Multiplexing TCP and TLS requires a newer Erlang/OTP version"), {error, eprotonosupport}. -else. is_tls_handshake({_, _, {_, Socket}}) -> case socket:recvfrom(Socket, 10, [peek], ?TIMEOUT) of {ok, {_, <<22, 3, _:4/binary, 0, _:2/binary, 3>>}} -> ?LOG_DEBUG("Determined transport protocol: TLS"), true; {ok, {_, _}} -> ?LOG_DEBUG("Determined transport protocol: TCP"), false; {error, Reason} -> ?LOG_INFO("Cannot determine transport protocol: ~s", [Reason]), false end. -endif. maybe_starttls(Sock, fast_tls, Opts) -> case proplists:is_defined(certfile, Opts) of true -> TLSOpts = lists:filter( fun({certfile, _Val}) -> true; ({dhfile, _Val}) -> true; ({ciphers, _Val}) -> true; ({protocol_options, _Val}) -> true; (_Opt) -> false end, Opts), fast_tls:tcp_to_tls(Sock, [verify_none | TLSOpts]); false -> ?LOG_ERROR("Cannot accept TLS connection: " "option 'certfile' is not set"), {error, eprotonosupport} end; maybe_starttls(Sock, gen_tcp, _Opts) -> {ok, Sock}. prepare_response(State, Msg) -> #stun{method = Msg#stun.method, magic = Msg#stun.magic, trid = Msg#stun.trid, 'SOFTWARE' = State#state.server_name}. run_hook(HookName, #state{session_id = ID, peer = Client, sock_mod = SockMod, hook_fun = HookFun}, #stun{'USERNAME' = User, 'REALM' = Realm, 'ERROR-CODE' = Reason} = Msg) when is_function(HookFun) -> Info = #{id => ID, user => User, realm => Realm, client => Client, transport => stun_logger:encode_transport(SockMod), version => stun_codec:version(Msg), reason => Reason}, ?LOG_DEBUG("Running '~s' hook", [HookName]), try HookFun(HookName, Info) catch _:Err -> ?LOG_ERROR("Hook '~s' failed: ~p", [HookName, Err]) end; run_hook(HookName, _State, _Msg) -> ?LOG_DEBUG("No callback function specified for '~s' hook", [HookName]), ok. -define(THRESHOLD, 16#10000000000000000). -ifdef(RAND_UNIFORM). rand_uniform() -> rand:uniform(). rand_uniform(N) -> rand:uniform(N). rand_uniform(N, M) -> rand:uniform(M-N+1) + N-1. -else. rand_uniform() -> crypto:rand_uniform(0, ?THRESHOLD)/?THRESHOLD. rand_uniform(N) -> crypto:rand_uniform(1, N+1). rand_uniform(N, M) -> crypto:rand_uniform(N, M+1). -endif. stun-1.2.10/src/turn_sm.erl0000644000232200023220000000536214513201307016116 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-2023 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) -> % Catch the case where an allocation is deleted after turn_sm was terminated % during shutdown. try ets:delete(turn_allocs, AddrPort) catch _:badarg -> ok end, 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.2.10/src/stun_acceptor.erl0000644000232200023220000001522614513201307017300 0ustar debalancedebalance%%%---------------------------------------------------------------------- %%% File : stun_acceptor.erl %%% Author : Holger Weiss %%% Purpose : STUN/TURN acceptor %%% Created : 3 Jul 2022 by Holger Weiss %%% %%% %%% Copyright (C) 2022 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_acceptor). -author('holger@zedat.fu-berlin.de'). -export([start/4, stop/1]). -export([start_link/4]). -export([init/4]). -include("stun_logger.hrl"). -define(TCP_SEND_TIMEOUT, 10000). -define(UDP_READ_PACKETS, 100). -define(UDP_RECBUF, 1024 * 1024). % 1 MiB -type ip() :: inet:ip_address(). -type port_number() :: inet:port_number(). -type udp_socket() :: gen_udp:socket(). -type tcp_socket() :: gen_tcp:socket(). -type transport() :: udp | tcp | tls | auto. -type opts() :: proplists:proplist(). %% API. -spec start(ip(), port_number(), transport(), opts()) -> {ok, pid()} | {error, term()}. start(IP, Port, Transport, Opts) -> supervisor:start_child(stun_acceptor_sup, [IP, Port, Transport, Opts]). -spec stop(pid()) -> ok | {error, term()}. stop(Pid) -> supervisor:terminate_child(stun_acceptor_sup, Pid). -spec start_link(ip(), port_number(), transport(), opts()) -> {ok, pid()} | {error, term()}. start_link(IP, Port, Transport, Opts) -> proc_lib:start_link(?MODULE, init, [IP, Port, Transport, Opts]). -spec init(ip(), port_number(), transport(), opts()) -> no_return(). init(IP, Port, Transport0, Opts0) when Transport0 == tcp; Transport0 == tls; Transport0 == auto -> {Transport, Opts} = case {Transport0, proplists:get_value(tls, Opts0)} of {tcp, false} -> {tcp, Opts0}; {tcp, true} -> {tls, Opts0}; {tcp, optional} -> {auto, Opts0}; {tls, undefined} -> {tls, [tls | Opts0]}; {auto, undefined} -> {auto, [{tls, optional} | Opts0]}; {_Transport, _TLS} -> {Transport0, Opts0} end, case listen(Transport, Port, [binary, {ip, IP}, {packet, 0}, {active, false}, {reuseaddr, true}, {nodelay, true}, {keepalive, true}, {send_timeout, ?TCP_SEND_TIMEOUT}, {send_timeout_close, true}]) of {ok, ListenSocket} -> Opts1 = stun:tcp_init(ListenSocket, Opts), proc_lib:init_ack({ok, self()}), accept(Transport, ListenSocket, Opts1); {error, Reason} -> log_error(IP, Port, Transport, Opts, Reason), exit(Reason) end; init(IP, Port, udp, Opts) -> case gen_udp:open(Port, [binary, {ip, IP}, {active, false}, {recbuf, ?UDP_RECBUF}, {read_packets, ?UDP_READ_PACKETS}, {reuseaddr, true}]) of {ok, Socket} -> stun_logger:set_metadata(listener, udp), Opts1 = stun:udp_init(Socket, Opts), proc_lib:init_ack({ok, self()}), udp_recv(Socket, Opts1); {error, Reason} -> log_error(IP, Port, udp, Opts, Reason), exit(Reason) end. %% Internal functions. -spec listen(transport(), port_number(), opts()) -> {ok, tcp_socket()} | {error, term()}. -ifdef(USE_OLD_INET_BACKEND). listen(_Transport, Port, Opts) -> gen_tcp:listen(Port, Opts). -else. listen(auto, Port, Opts) -> gen_tcp:listen(Port, [{inet_backend, socket} | Opts]); listen(_Transport, Port, Opts) -> gen_tcp:listen(Port, Opts). -endif. -spec accept(transport(), tcp_socket(), opts()) -> no_return(). accept(Transport, ListenSocket, Opts) -> Proxy = proplists:get_bool(proxy_protocol, Opts), ID = stun_logger:make_id(), Opts1 = [{session_id, ID} | Opts], stun_logger:set_metadata(listener, Transport, ID), case gen_tcp:accept(ListenSocket) of {ok, Socket} when Proxy -> case p1_proxy_protocol:decode(gen_tcp, Socket, 10000) of {{Addr, Port}, {PeerAddr, PeerPort}} = SP -> Opts2 = [{sock_peer_name, SP} | Opts1], ?LOG_INFO("Accepting proxied connection: ~s -> ~s", [stun_logger:encode_addr({PeerAddr, PeerPort}), stun_logger:encode_addr({Addr, Port})]), case stun:start({gen_tcp, Socket}, Opts2) of {ok, Pid} -> gen_tcp:controlling_process(Socket, Pid); {error, Reason} -> ?LOG_NOTICE("Cannot start connection: ~s", [Reason]), gen_tcp:close(Socket) end; {error, Reason} -> ?LOG_ERROR("Cannot parse proxy protocol: ~s", [inet:format_error(Reason)]), gen_tcp:close(Socket); {undefined, undefined} -> ?LOG_ERROR("Cannot parse proxy protocol: unknown protocol"), gen_tcp:close(Socket) end; {ok, Socket} -> case {inet:peername(Socket), inet:sockname(Socket)} of {{ok, {PeerAddr, PeerPort}}, {ok, {Addr, Port}}} -> ?LOG_INFO("Accepting connection: ~s -> ~s", [stun_logger:encode_addr({PeerAddr, PeerPort}), stun_logger:encode_addr({Addr, Port})]), case stun:start({gen_tcp, Socket}, Opts1) of {ok, Pid} -> gen_tcp:controlling_process(Socket, Pid); {error, Reason} -> ?LOG_NOTICE("Cannot start connection: ~s", [Reason]), gen_tcp:close(Socket) end; Err -> ?LOG_NOTICE("Cannot fetch peername: ~p", [Err]), gen_tcp:close(Socket) end; {error, Reason} when Reason /= closed -> ?LOG_NOTICE("Cannot accept connection: ~s", [inet:format_error(Reason)]) end, accept(Transport, ListenSocket, Opts). -spec udp_recv(udp_socket(), opts()) -> no_return(). udp_recv(Socket, Opts) -> case gen_udp:recv(Socket, 0) of {ok, {Addr, Port, Packet}} -> NewOpts = stun:udp_recv(Socket, Addr, Port, Packet, Opts), udp_recv(Socket, NewOpts); {error, Reason} when Reason /= closed -> ?LOG_NOTICE("Cannot receive UDP packet: ~s", [inet:format_error(Reason)]), udp_recv(Socket, Opts) end. -spec log_error(ip(), port_number(), transport(), opts(), term()) -> any(). log_error(IP, Port, Transport, Opts, Reason) -> ?LOG_DEBUG("Cannot start listener:~n" "** IP: ~s~n" "** Port: ~B~n" "** Transport: ~s~n" "** Options: ~p~n" "** Reason: ~s", [stun_logger:encode_addr(IP), Port, stun_logger:encode_transport(Transport), Opts, inet:format_error(Reason)]). stun-1.2.10/src/turn.erl0000644000232200023220000006561714513201307015430 0ustar debalancedebalance%%%------------------------------------------------------------------- %%% File : turn.erl %%% Author : Evgeniy Khramtsov %%% Description : Handles TURN allocations, see RFC5766 %%% Created : 23 Aug 2009 by Evgeniy Khramtsov %%% %%% %%% Copyright (C) 2002-2023 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, p1_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"). -include("stun_logger.hrl"). -define(UDP_READ_PACKETS, 100). -define(UDP_ACTIVE, 500). -define(UDP_RECBUF, 1024 * 1024). % 1 MiB -define(MAX_LIFETIME, 3600000). %% 1 hour -define(DEFAULT_LIFETIME, 600000). %% 10 minutes -define(PERMISSION_LIFETIME, 300000). %% 5 minutes -define(CHANNEL_LIFETIME, 600000). %% 10 minutes -define(INITIAL_BLACKLIST, [ %% Could be used to circumvent blocking of loopback addresses: {{0, 0, 0, 0}, 8}, {{0, 0, 0, 0, 0, 0, 0, 0}, 128}, %% RFC 6156, 9.1: "a TURN relay MUST NOT accept Teredo or 6to4 addresses". {{8193, 0, 0, 0, 0, 0, 0, 0}, 32}, % 2001::/32 (Teredo). {{8194, 0, 0, 0, 0, 0, 0, 0}, 16}]). % 2002::/16 (6to4). -type addr() :: {inet:ip_address(), inet:port_number()}. -type subnet() :: {inet:ip4_address(), 0..32} | {inet:ip6_address(), 0..128}. -type accesslist() :: [subnet()]. -export_type([accesslist/0]). -record(state, {sock_mod = gen_udp :: gen_udp | gen_tcp | fast_tls, sock :: inet:socket() | fast_tls:tls_socket() | undefined, addr = {{0,0,0,0}, 0} :: addr(), owner = self() :: pid(), username = <<"">> :: binary(), realm = <<"">> :: binary(), key = {<<"">>, <<"">>, <<"">>} :: {binary(), binary(), binary()}, server_name = <<"">> :: binary(), peers = #{} :: map(), channels = #{} :: map(), permissions = #{} :: map(), max_permissions :: non_neg_integer() | atom() | undefined, relay_ipv4_ip = {127,0,0,1} :: inet:ip4_address(), relay_ipv6_ip :: inet:ip6_address() | undefined, min_port = 49152 :: non_neg_integer(), max_port = 65535 :: non_neg_integer(), relay_addr :: addr() | undefined, relay_sock :: inet:socket() | undefined, last_trid :: non_neg_integer() | undefined, last_pkt = <<>> :: binary(), seq = 1 :: non_neg_integer(), life_timer :: reference() | undefined, blacklist_clients = [] :: accesslist(), whitelist_clients = [] :: accesslist(), blacklist_peers = [] :: accesslist(), whitelist_peers = [] :: accesslist(), hook_fun :: function() | undefined, session_id :: binary(), rcvd_bytes = 0 :: non_neg_integer(), rcvd_pkts = 0 :: non_neg_integer(), sent_bytes = 0 :: non_neg_integer(), sent_pkts = 0 :: non_neg_integer(), start_timestamp = get_timestamp() :: integer()}). %%==================================================================== %% 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]) -> process_flag(trap_exit, true), ID = proplists:get_value(session_id, 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), SockMod = proplists:get_value(sock_mod, Opts), HookFun = proplists:get_value(hook_fun, Opts), BlacklistClients = proplists:get_value(blacklist_clients, Opts), WhitelistClients = proplists:get_value(whitelist_clients, Opts), BlacklistPeers = proplists:get_value(blacklist_peers, Opts), WhitelistPeers = proplists:get_value(whitelist_peers, Opts), State = #state{sock_mod = SockMod, sock = proplists:get_value(sock, Opts), key = proplists:get_value(key, Opts), relay_ipv4_ip = proplists:get_value(relay_ipv4_ip, Opts), relay_ipv6_ip = proplists:get_value(relay_ipv6_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), username = Username, realm = Realm, addr = AddrPort, session_id = ID, owner = Owner, hook_fun = HookFun, blacklist_clients = BlacklistClients ++ ?INITIAL_BLACKLIST, whitelist_clients = WhitelistClients, blacklist_peers = BlacklistPeers ++ ?INITIAL_BLACKLIST, whitelist_peers = WhitelistPeers}, stun_logger:set_metadata(turn, SockMod, ID, AddrPort, Username), 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), case turn_sm:add_allocation(AddrPort, Username, Realm, MaxAllocs, self()) of ok -> run_hook(turn_session_start, State), {ok, wait_for_allocate, State#state{life_timer = TRef}} %% %% turn_sm:add_allocation/5 currently doesn't return errors. %% %% {error, Reason} -> %% {stop, Reason} end. wait_for_allocate(#stun{class = request, method = ?STUN_METHOD_ALLOCATE} = Msg, State) -> Family = case Msg#stun.'REQUESTED-ADDRESS-FAMILY' of ipv4 -> inet; ipv6 -> inet6; undefined -> inet; unknown -> unknown end, IsBlacklisted = is_blacklisted_client(State), Resp = prepare_response(State, Msg), if Msg#stun.'REQUESTED-TRANSPORT' == undefined -> ?LOG_NOTICE("Rejecting allocation request: no transport requested"), R = Resp#stun{class = error, 'ERROR-CODE' = stun_codec:error(400)}, run_hook(protocol_error, State, R), {stop, normal, send(State, R)}; Msg#stun.'REQUESTED-TRANSPORT' == unknown -> ?LOG_NOTICE("Rejecting allocation request: unsupported transport"), R = Resp#stun{class = error, 'ERROR-CODE' = stun_codec:error(442)}, run_hook(protocol_error, State, R), {stop, normal, send(State, R)}; Msg#stun.'DONT-FRAGMENT' == true -> ?LOG_NOTICE("Rejecting allocation request: dont-fragment not " "supported"), R = Resp#stun{class = error, 'UNKNOWN-ATTRIBUTES' = [?STUN_ATTR_DONT_FRAGMENT], 'ERROR-CODE' = stun_codec:error(420)}, run_hook(protocol_error, State, R), {stop, normal, send(State, R)}; Family == unknown -> ?LOG_NOTICE("Rejecting allocation request: unknown address family"), R = Resp#stun{class = error, 'ERROR-CODE' = stun_codec:error(440)}, run_hook(protocol_error, State, R), {stop, normal, send(State, R)}; Family == inet6, State#state.relay_ipv6_ip == undefined -> ?LOG_NOTICE("Rejecting allocation request: IPv6 not supported"), R = Resp#stun{class = error, 'ERROR-CODE' = stun_codec:error(440)}, run_hook(protocol_error, State, R), {stop, normal, send(State, R)}; IsBlacklisted -> ?LOG_NOTICE("Rejecting allocation request: Client address is " "blacklisted"), R = Resp#stun{class = error, 'ERROR-CODE' = stun_codec:error(403)}, run_hook(protocol_error, State, R), {stop, normal, send(State, R)}; true -> RelayIP = case Family of inet -> State#state.relay_ipv4_ip; inet6 -> State#state.relay_ipv6_ip end, case allocate_addr(Family, RelayIP, {State#state.min_port, State#state.max_port}) of {ok, RelayPort, RelaySock} -> Lifetime = time_left(State#state.life_timer), AddrPort = stun:unmap_v4_addr(State#state.addr), RelayAddr = {RelayIP, RelayPort}, stun_logger:add_metadata( #{stun_relay => stun_logger:encode_addr(RelayAddr)}), ?LOG_NOTICE("Creating TURN allocation " "(lifetime: ~B seconds)", [Lifetime]), 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 -> ?LOG_ERROR("Cannot allocate TURN relay: ~s", [format_error(Err)]), R = Resp#stun{class = error, 'ERROR-CODE' = stun_codec:error(508)}, run_hook(protocol_error, State, R), {stop, normal, send(State, R)} end end; wait_for_allocate(Event, State) -> ?LOG_ERROR("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) -> ?LOG_NOTICE("Rejecting allocation request: Relay already allocated"), Resp = prepare_response(State, Msg), R = Resp#stun{class = error, 'ERROR-CODE' = stun_codec:error(437)}, run_hook(protocol_error, State, R), {next_state, active, send(State, R)}; active(#stun{class = request, 'REQUESTED-ADDRESS-FAMILY' = ipv4, method = ?STUN_METHOD_REFRESH} = Msg, #state{relay_addr = {{_, _, _, _, _, _, _, _}, _}} = State) -> ?LOG_NOTICE("Rejecting refresh request: IPv4 requested for IPv6 peer"), Resp = prepare_response(State, Msg), R = Resp#stun{class = error, 'ERROR-CODE' = stun_codec:error(443)}, run_hook(protocol_error, State, R), {next_state, active, send(State, R)}; active(#stun{class = request, 'REQUESTED-ADDRESS-FAMILY' = ipv6, method = ?STUN_METHOD_REFRESH} = Msg, #state{relay_addr = {{_, _, _, _}, _}} = State) -> ?LOG_NOTICE("Rejecting refresh request: IPv6 requested for IPv4 peer"), Resp = prepare_response(State, Msg), R = Resp#stun{class = error, 'ERROR-CODE' = stun_codec:error(443)}, run_hook(protocol_error, State, R), {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 -> ?LOG_INFO("Client requested closing the TURN session"), 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, ?LOG_NOTICE("Refreshing TURN allocation (lifetime: ~B seconds)", [MSecs div 1000]), 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) -> {Addrs, _Ports} = lists:unzip(XorPeerAddrs), Resp = prepare_response(State, Msg), case update_permissions(State, Addrs) of {ok, NewState} -> R = Resp#stun{class = response}, {next_state, active, send(NewState, R)}; {error, Code} -> Err = {_, Txt} = stun_codec:error(Code), ?LOG_NOTICE("Rejecting permission creation request: ~s", [Txt]), R = Resp#stun{class = error, 'ERROR-CODE' = Err}, run_hook(protocol_error, State, R), {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) -> State1 = case maps:find(Addr, State#state.permissions) of {ok, _} -> gen_udp:send(State#state.relay_sock, Addr, Port, Data), count_sent(State, Data); error -> State end, {next_state, active, State1}; active(#stun{class = request, 'CHANNEL-NUMBER' = Channel, 'XOR-PEER-ADDRESS' = [{Addr, _Port} = Peer], method = ?STUN_METHOD_CHANNEL_BIND} = Msg, State) when is_integer(Channel), Channel >= 16#4000, Channel =< 16#7ffe -> Resp = prepare_response(State, Msg), case {maps:find(Channel, State#state.channels), maps:find(Peer, State#state.peers)} of {_, {ok, OldChannel}} when Channel /= OldChannel -> ?LOG_NOTICE("Rejecting channel binding request: Peer already bound " "to a different channel (~.16B)", [OldChannel]), R = Resp#stun{class = error, 'ERROR-CODE' = stun_codec:error(400)}, run_hook(protocol_error, State, R), {next_state, active, send(State, R)}; {{ok, {OldPeer, _}}, _} when Peer /= OldPeer -> ?LOG_NOTICE("Rejecting channel binding request: Channel already " "bound to a different peer (~s)", [stun_logger:encode_addr(OldPeer)]), R = Resp#stun{class = error, 'ERROR-CODE' = stun_codec:error(400)}, run_hook(protocol_error, State, R), {next_state, active, send(State, R)}; {FindResult, _} -> case update_permissions(State, [Addr]) of {ok, NewState0} -> _Op = case FindResult of {ok, {_, OldTRef}} -> cancel_timer(OldTRef), maybe_log(<<"Refreshing">>); _ -> maybe_log(<<"Binding">>) end, TRef = erlang:start_timer(?CHANNEL_LIFETIME, self(), {channel_timeout, Channel}), Peers = maps:put(Peer, Channel, State#state.peers), Chans = maps:put(Channel, {Peer, TRef}, State#state.channels), NewState = NewState0#state{peers = Peers, channels = Chans}, ?LOG_INFO("~s TURN channel ~.16B for peer ~s", [_Op, Channel, stun_logger:encode_addr(Peer)]), R = Resp#stun{class = response}, {next_state, active, send(NewState, R)}; {error, Code} -> Err = {_, Txt} = stun_codec:error(Code), ?LOG_NOTICE("Rejecting channel binding request: ~s", [Txt]), R = Resp#stun{class = error, 'ERROR-CODE' = Err}, run_hook(protocol_error, State, R), {next_state, active, send(State, R)} end end; active(#stun{class = request, method = ?STUN_METHOD_CHANNEL_BIND} = Msg, State) -> ?LOG_NOTICE("Rejecting channel binding request: Missing channel number " "and/or peer address"), Resp = prepare_response(State, Msg), R = Resp#stun{class = error, 'ERROR-CODE' = stun_codec:error(400)}, run_hook(protocol_error, State, R), {next_state, active, send(State, R)}; active(#turn{channel = Channel, data = Data}, State) -> case maps:find(Channel, State#state.channels) of {ok, {{Addr, Port}, _}} -> gen_udp:send(State#state.relay_sock, Addr, Port, Data), State1 = count_sent(State, Data), {next_state, active, State1}; error -> {next_state, active, State} end; active(Event, State) -> ?LOG_ERROR("Unexpected event in 'active': ~p", [Event]), {next_state, active, State}. handle_event(stop, _StateName, State) -> {stop, normal, State}; handle_event(Event, StateName, State) -> ?LOG_ERROR("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) -> Peer = {Addr, Port}, case {maps:find(Addr, State#state.permissions), maps:find(Peer, State#state.peers)} of {{ok, _}, {ok, Channel}} -> TurnMsg = #turn{channel = Channel, data = Data}, State1 = count_rcvd(State, Data), {next_state, StateName, send(State1, TurnMsg)}; {{ok, _}, error} -> Seq = State#state.seq, Ind = #stun{class = indication, method = ?STUN_METHOD_DATA, trid = Seq, 'XOR-PEER-ADDRESS' = [Peer], 'DATA' = Data}, State1 = count_rcvd(State, Data), {next_state, StateName, send(State1#state{seq = Seq+1}, Ind)}; {error, _} -> {next_state, StateName, State} end; handle_info({udp_passive, Sock}, StateName, State) -> inet:setopts(Sock, [{active, ?UDP_ACTIVE}]), {next_state, StateName, State}; handle_info({timeout, _Tref, stop}, _StateName, State) -> {stop, normal, State}; handle_info({timeout, _Tref, {permission_timeout, Addr}}, StateName, State) -> ?LOG_INFO("TURN permission for ~s timed out", [stun_logger:encode_addr(Addr)]), case maps:find(Addr, State#state.permissions) of {ok, _} -> Perms = maps:remove(Addr, State#state.permissions), {next_state, StateName, State#state{permissions = Perms}}; error -> {next_state, StateName, State} end; handle_info({timeout, _Tref, {channel_timeout, Channel}}, StateName, State) -> case maps:find(Channel, State#state.channels) of {ok, {Peer, _}} -> ?LOG_INFO("TURN channel ~.16B for peer ~s timed out", [Channel, stun_logger:encode_addr(Peer)]), Chans = maps:remove(Channel, State#state.channels), Peers = maps:remove(Peer, State#state.peers), {next_state, StateName, State#state{channels = Chans, peers = Peers}}; error -> {next_state, StateName, State} end; handle_info({'DOWN', _Ref, _, _, _}, _StateName, State) -> {stop, normal, State}; handle_info(Info, StateName, State) -> ?LOG_ERROR("Unexpected info in '~s': ~p", [StateName, Info]), {next_state, StateName, State}. terminate(_Reason, _StateName, State) -> AddrPort = State#state.addr, Username = State#state.username, Realm = State#state.realm, RcvdBytes = State#state.rcvd_bytes, RcvdPkts = State#state.rcvd_pkts, SentBytes = State#state.sent_bytes, SentPkts = State#state.sent_pkts, case State#state.relay_addr of undefined -> ok; _RAddrPort -> ?LOG_INFO("Deleting TURN allocation") end, if is_pid(State#state.owner) -> stun:stop(State#state.owner); true -> ok end, ?LOG_NOTICE("Relayed ~B KiB (in ~B B / ~B packets, out ~B B / ~B packets), " "duration: ~B seconds", [round((RcvdBytes + SentBytes) / 1024), RcvdBytes, RcvdPkts, SentBytes, SentPkts, get_duration(State, second)]), run_hook(turn_session_stop, State), turn_sm:del_allocation(AddrPort, Username, Realm). code_change(_OldVsn, StateName, State, _Extra) -> {ok, StateName, State}. %%-------------------------------------------------------------------- %%% Internal functions %%-------------------------------------------------------------------- update_permissions(_State, []) -> {error, 400}; update_permissions(#state{permissions = Perms, max_permissions = Max}, Addrs) when map_size(Perms) + length(Addrs) > Max -> {error, 508}; update_permissions(#state{relay_addr = {IP, _}} = State, Addrs) -> case {families_match(IP, Addrs), is_blacklisted_peer(State, Addrs)} of {true, false} -> Perms = lists:foldl( fun(Addr, Acc) -> _Op = case maps:find(Addr, Acc) of {ok, OldTRef} -> cancel_timer(OldTRef), maybe_log(<<"Refreshing">>); error -> maybe_log(<<"Creating">>) end, TRef = erlang:start_timer( ?PERMISSION_LIFETIME, self(), {permission_timeout, Addr}), ?LOG_INFO("~s TURN permission for ~s", [_Op, stun_logger:encode_addr(Addr)]), maps:put(Addr, TRef, Acc) end, State#state.permissions, Addrs), {ok, State#state{permissions = Perms}}; {false, _} -> {error, 443}; {_, true} -> {error, 403} end. 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; _ -> ?LOG_INFO("Cannot respond to client: Connection closed"), exit(normal) end end; send(State, Msg) -> ?LOG_DEBUG(#{verbatim => {"Sending:~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(Family, Addr, {Min, Max}) -> Count = Max - Min + 1, Next = Min + stun:rand_uniform(Count) - 1, allocate_addr(Family, Addr, Min, Max, Next, Count). allocate_addr(_Family, _Addr, _Min, _Max, _Next, 0) -> {error, eaddrinuse}; allocate_addr(Family, Addr, Min, Max, Next, Count) -> case gen_udp:open(Next, [binary, Family, {ip, Addr}, {active, ?UDP_ACTIVE}, {recbuf, ?UDP_RECBUF}, {read_packets, ?UDP_READ_PACKETS}]) of {ok, Sock} -> case inet:sockname(Sock) of {ok, {_, Port}} -> {ok, Port, Sock}; Err -> Err end; {error, eaddrinuse} -> if Next == Max -> allocate_addr(Family, Addr, Min, Max, Min, Count-1); true -> allocate_addr(Family, Addr, Min, Max, Next+1, Count-1) end; {error, eaddrnotavail} when is_tuple(Addr) -> allocate_addr(Family, any, Min, Max, Next, Count); Err -> Err end. families_match(RelayAddr, Addrs) -> lists:all(fun(Addr) -> family_matches(RelayAddr, Addr) end, Addrs). family_matches({_, _, _, _}, {_, _, _, _}) -> true; family_matches({_, _, _, _, _, _, _, _}, {_, _, _, _, _, _, _, _}) -> true; family_matches(_Addr1, _Addr2) -> false. is_blacklisted_client(#state{addr = {IP, _Port}, blacklist_clients = Blacklist, whitelist_clients = Whitelist}) -> is_blacklisted(Blacklist, Whitelist, [IP]). is_blacklisted_peer(#state{blacklist_peers = Blacklist, whitelist_peers = Whitelist}, IPs) -> is_blacklisted(Blacklist, Whitelist, IPs). is_blacklisted(Blacklist, Whitelist, IPs) -> lists:any( fun(IP) -> lists:any( fun({Net, Mask}) -> match_subnet(IP, Net, Mask) end, Blacklist) end, IPs) andalso not lists:any( fun(IP) -> lists:any( fun({Net, Mask}) -> match_subnet(IP, Net, Mask) end, Whitelist) end, IPs). match_subnet({_, _, _, _} = IP, {_, _, _, _} = Net, Mask) -> IPInt = ip_to_integer(IP), NetInt = ip_to_integer(Net), M = bnot (1 bsl (32 - Mask) - 1), IPInt band M =:= NetInt band M; match_subnet({_, _, _, _, _, _, _, _} = IP, {_, _, _, _, _, _, _, _} = Net, Mask) -> IPInt = ip_to_integer(IP), NetInt = ip_to_integer(Net), M = bnot (1 bsl (128 - Mask) - 1), IPInt band M =:= NetInt band M; match_subnet({_, _, _, _} = IP, {0, 0, 0, 0, 0, 16#FFFF, _, _} = Net, Mask) -> IPInt = ip_to_integer({0, 0, 0, 0, 0, 16#FFFF, 0, 0}) + ip_to_integer(IP), NetInt = ip_to_integer(Net), M = bnot (1 bsl (128 - Mask) - 1), IPInt band M =:= NetInt band M; match_subnet({0, 0, 0, 0, 0, 16#FFFF, _, _} = IP, {_, _, _, _} = Net, Mask) -> IPInt = ip_to_integer(IP) - ip_to_integer({0, 0, 0, 0, 0, 16#FFFF, 0, 0}), NetInt = ip_to_integer(Net), M = bnot (1 bsl (32 - Mask) - 1), IPInt band M =:= NetInt band M; match_subnet(_, _, _) -> false. ip_to_integer({IP1, IP2, IP3, IP4}) -> IP1 bsl 8 bor IP2 bsl 8 bor IP3 bsl 8 bor IP4; ip_to_integer({IP1, IP2, IP3, IP4, IP5, IP6, IP7, IP8}) -> IP1 bsl 16 bor IP2 bsl 16 bor IP3 bsl 16 bor IP4 bsl 16 bor IP5 bsl 16 bor IP6 bsl 16 bor IP7 bsl 16 bor IP8. format_error({error, Reason}) -> case inet:format_error(Reason) of "unknown POSIX error" -> Reason; Res -> Res 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. get_timestamp() -> erlang:monotonic_time(). get_duration(State, Unit) -> erlang:convert_time_unit(get_duration(State), native, Unit). get_duration(#state{start_timestamp = Start}) -> get_timestamp() - Start. prepare_response(State, Msg) -> #stun{method = Msg#stun.method, magic = Msg#stun.magic, trid = Msg#stun.trid, 'SOFTWARE' = State#state.server_name}. count_sent(#state{sent_bytes = SentSize, sent_pkts = SentPkts} = State, Data) -> State#state{sent_bytes = SentSize + byte_size(Data), sent_pkts = SentPkts + 1}. count_rcvd(#state{rcvd_bytes = RcvdSize, rcvd_pkts = RcvdPkts} = State, Data) -> State#state{rcvd_bytes = RcvdSize + byte_size(Data), rcvd_pkts = RcvdPkts + 1}. run_hook(HookName, State) -> run_hook(HookName, State, #stun{}). run_hook(HookName, #state{session_id = ID, username = User, realm = Realm, addr = Client, sock_mod = SockMod, hook_fun = HookFun} = State, #stun{'ERROR-CODE' = Reason}) when is_function(HookFun) -> Info1 = #{id => ID, user => User, realm => Realm, client => Client, transport => stun_logger:encode_transport(SockMod), reason => Reason}, Info2 = case {HookName, State} of {turn_session_start, _State} -> Info1; {turn_session_stop, #state{sent_bytes = SentBytes, sent_pkts = SentPkts, rcvd_bytes = RcvdBytes, rcvd_pkts = RcvdPkts}} -> Info1#{sent_bytes => SentBytes, sent_pkts => SentPkts, rcvd_bytes => RcvdBytes, rcvd_pkts => RcvdPkts, duration => get_duration(State)}; {protocol_error, _State} -> Info1 end, ?LOG_DEBUG("Running '~s' hook", [HookName]), try HookFun(HookName, Info2) catch _:Err -> ?LOG_ERROR("Hook '~s' failed: ~p", [HookName, Err]) end; run_hook(HookName, _State, _Msg) -> ?LOG_DEBUG("No callback function specified for '~s' hook", [HookName]), ok. -ifdef(USE_OLD_LOGGER). -ifdef(debug). maybe_log(Term) -> Term. -else. maybe_log(_Term) -> ok. -endif. -else. maybe_log(Term) -> Term. -endif. stun-1.2.10/src/stun_listener_sup.erl0000644000232200023220000000320414513201307020205 0ustar debalancedebalance%%%---------------------------------------------------------------------- %%% Purpose : STUN/TURN listener (parent) supervisor %%% Created : 3 Jul 2022 by Holger Weiss %%% %%% %%% Copyright (C) 2022 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_sup). -behaviour(supervisor). -author('holger@zedat.fu-berlin.de'). -export([start_link/0]). -export([init/1]). -define(SERVER, ?MODULE). %% API. -spec start_link() -> {ok, pid()} | {error, term()}. start_link() -> supervisor:start_link({local, ?SERVER}, ?MODULE, []). %% Supervisor callbacks. -spec init([]) -> {ok, {supervisor:sup_flags(), [supervisor:child_spec()]}}. init([]) -> SupFlags = #{strategy => one_for_all, intensity => 10, period => 1}, ChildSpecs = [#{id => stun_acceptor_sup, type => supervisor, start => {stun_acceptor_sup, start_link, []}}, #{id => stun_listener, shutdown => 2000, start => {stun_listener, start_link, []}}], {ok, {SupFlags, ChildSpecs}}. stun-1.2.10/src/stun_listener.erl0000644000232200023220000000654414513201307017330 0ustar debalancedebalance%%%---------------------------------------------------------------------- %%% File : stun_listener.erl %%% Author : Evgeniy Khramtsov %%% Purpose : %%% Created : 9 Jan 2011 by Evgeniy Khramtsov %%% %%% %%% Copyright (C) 2002-2023 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/4, del_listener/3]). %% gen_server callbacks -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -include("stun_logger.hrl"). -record(state, {listeners = #{}}). %%%=================================================================== %%% API %%%=================================================================== start_link() -> gen_server:start_link({local, ?MODULE}, ?MODULE, [], []). add_listener(IP, Port, Transport, Opts) -> gen_server:call(?MODULE, {add_listener, IP, Port, Transport, Opts}). del_listener(IP, Port, Transport) -> gen_server:call(?MODULE, {del_listener, IP, Port, Transport}). %%%=================================================================== %%% gen_server callbacks %%%=================================================================== init([]) -> {ok, #state{}}. handle_call({add_listener, IP, Port, Transport, Opts}, _From, #state{listeners = Listeners} = State) -> Key = {IP, Port, Transport}, case Listeners of #{Key := _Pid} -> {reply, {error, already_started}, State}; #{} -> case stun_acceptor:start(IP, Port, Transport, Opts) of {ok, Pid} -> NewListeners = Listeners#{Key => Pid}, {reply, ok, State#state{listeners = NewListeners}}; {error, _Reason} = Err -> {reply, Err, State} end end; handle_call({del_listener, IP, Port, Transport}, _From, #state{listeners = Listeners} = State) -> Key = {IP, Port, Transport}, case Listeners of #{Key := Pid} -> case stun_acceptor:stop(Pid) of ok -> NewListeners = maps:remove(Key, Listeners), {reply, ok, State#state{listeners = NewListeners}}; {error, _Reason} = Err -> {reply, Err, State} end; #{} -> {reply, {error, not_found}, State} end; handle_call(Request, From, State) -> ?LOG_ERROR("Got unexpected request from ~p: ~p", [From, Request]), {reply, {error, badarg}, State}. handle_cast(Msg, State) -> ?LOG_ERROR("Got unexpected message: ~p", [Msg]), {noreply, State}. handle_info(Info, State) -> ?LOG_ERROR("Got unexpected info: ~p", [Info]), {noreply, State}. terminate(_Reason, #state{listeners = Listeners}) -> lists:foreach(fun(Pid) -> _ = stun_acceptor:stop(Pid) end, maps:values(Listeners)). code_change(_OldVsn, State, _Extra) -> {ok, State}. stun-1.2.10/src/stun_logger.erl0000644000232200023220000001551714513201307016762 0ustar debalancedebalance%%%---------------------------------------------------------------------- %%% File : stun_logger.erl %%% Author : Holger Weiss %%% Purpose : Wrap OTP Logger for STUN/TURN logging %%% Created : 19 Jul 2020 by Holger Weiss %%% %%% %%% Copyright (C) 2020-2023 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_logger). -author('holger@zedat.fu-berlin.de'). -export([start/0, stop/0, set_metadata/2, set_metadata/3, set_metadata/4, set_metadata/5, add_metadata/1, make_id/0, encode_addr/1, encode_transport/1]). -type sub_domain() :: listener | stun | turn. -type transport() :: udp | tcp | tls | auto. -type sock_mod() :: gen_udp | gen_tcp | fast_tls. %% API. -ifdef(USE_OLD_LOGGER). -export([log/2, log/3]). -spec start() -> ok. start() -> ok. -spec stop() -> ok. stop() -> ok. -spec set_metadata(sub_domain(), transport()) -> ok. set_metadata(SubDomain, Transport) -> put(?MODULE, #{domain => [stun, SubDomain], stun_transport => encode_transport(Transport)}), ok. -spec set_metadata(sub_domain(), transport(), binary()) -> ok. set_metadata(SubDomain, Transport, ID) -> put(?MODULE, #{domain => [stun, SubDomain], stun_transport => encode_transport(Transport), stun_session_id => ID}), ok. -spec set_metadata(sub_domain(), sock_mod(), binary(), {inet:ip_address(), inet:port_number()}, binary() | anonymous) -> ok. set_metadata(SubDomain, SockMod, ID, Addr, User) -> put(?MODULE, #{domain => [stun, SubDomain], stun_transport => encode_transport(SockMod), stun_session_id => ID, stun_client => encode_addr(Addr), stun_user => User}), ok. -spec add_metadata(logger:metadata()) -> ok. add_metadata(Meta) -> put(?MODULE, maps:merge(get(?MODULE), Meta)), ok. -spec log(info | warning | error, iodata() | atom() | map()) -> ok. log(Level, #{verbatim := {Format, Args}}) -> log(Level, Format, Args); log(Level, Text) -> {Format, Args} = format_msg(Text, get(?MODULE)), case Level of info -> error_logger:info_msg(Format, Args); warning -> error_logger:warning_msg(Format, Args); error -> error_logger:error_msg(Format, Args) end. -spec log(info | warning | error, io:format(), [term()]) -> ok. log(Level, Format, Args) -> Text = io_lib:format(Format, Args), log(Level, Text). -else. -export([filter/2]). -spec start() -> ok. start() -> case logger:add_primary_filter(stun, {fun ?MODULE:filter/2, none}) of ok -> ok; {error, {already_exist, _}} -> ok end. -spec stop() -> ok. stop() -> case logger:remove_primary_filter(stun) of ok -> ok; {error, {not_found, _}} -> ok end. -spec set_metadata(sub_domain(), transport()) -> ok. set_metadata(SubDomain, Transport) -> logger:set_process_metadata(#{ domain => [stun, SubDomain], stun_transport => encode_transport(Transport)}). -spec set_metadata(sub_domain(), transport(), binary()) -> ok. set_metadata(SubDomain, Transport, ID) -> logger:set_process_metadata( #{domain => [stun, SubDomain], stun_transport => encode_transport(Transport), stun_session_id => ID}). -spec set_metadata(sub_domain(), sock_mod(), binary(), {inet:ip_address(), inet:port_number()}, binary() | anonymous) -> ok. set_metadata(SubDomain, SockMod, ID, Addr, User) -> logger:set_process_metadata( #{domain => [stun, SubDomain], stun_transport => encode_transport(SockMod), stun_session_id => ID, stun_client => encode_addr(Addr), stun_user => User}). -spec add_metadata(logger:metadata()) -> ok. add_metadata(Meta) -> logger:update_process_metadata(Meta). -spec filter(logger:log_event(), logger:filter_arg()) -> logger:filter_return(). filter(#{meta := #{domain := [stun | _]}, msg := {report, #{verbatim := Msg}}} = Event, _Extra) -> Event#{msg := Msg}; filter(#{meta := #{domain := [stun | _], stun_transport := _Transport} = Meta, msg := {Format, Args}} = Event, _Extra) when Format =/= report -> Text = case Format of string -> Args; _ -> io_lib:format(Format, Args) end, Event#{msg := format_msg(Text, Meta)}; filter(_Event, _Extra) -> ignore. -endif. -spec set_metadata(sub_domain(), sock_mod(), binary(), {inet:ip_address(), inet:port_number()}) -> ok. set_metadata(SubDomain, SockMod, ID, Addr) -> set_metadata(SubDomain, SockMod, ID, Addr, anonymous). -spec make_id() -> binary(). make_id() -> iolist_to_binary( io_lib:format("~12.36.0b", [p1_rand:uniform(16#4000000000000000)])). -spec encode_addr({inet:ip_address(), inet:port_number()} | inet:ip_address()) -> iolist(). encode_addr({Addr, Port}) when is_tuple(Addr) -> [encode_addr(Addr), [ $: | integer_to_list(Port)]]; encode_addr({0, 0, 0, 0, 0, 16#FFFF, D7, D8}) -> encode_addr({D7 bsr 8, D7 band 255, D8 bsr 8, D8 band 255}); encode_addr({_, _, _, _, _, _, _, _} = Addr) -> [$[, inet:ntoa(Addr), $]]; encode_addr(Addr) -> inet:ntoa(Addr). -spec encode_transport(transport() | sock_mod()) -> binary(). encode_transport(udp) -> <<"UDP">>; encode_transport(tcp) -> <<"TCP">>; encode_transport(tls) -> <<"TLS">>; encode_transport(auto) -> <<"TCP|TLS">>; encode_transport(gen_udp) -> <<"UDP">>; encode_transport(gen_tcp) -> <<"TCP">>; encode_transport(fast_tls) -> <<"TLS">>. %% Internal functions. -spec format_msg(iodata() | atom(), map()) -> {io:format(), [term()]}. format_msg(Text, #{stun_transport := Transport, stun_session_id := ID, stun_user := User, stun_client := Client, stun_relay := Relay}) -> {"~s [~s, session ~s, ~s, client ~s, relay ~s]", [Text, Transport, ID, format_user(User), Client, Relay]}; format_msg(Text, #{stun_transport := Transport, stun_session_id := ID, stun_user := User, stun_client := Client}) -> {"~s [~s, session ~s, ~s, client ~s]", [Text, Transport, ID, format_user(User), Client]}; format_msg(Text, #{stun_transport := Transport, stun_session_id := ID}) -> {"~s [~s, session ~s]", [Text, Transport, ID]}; format_msg(Text, #{stun_transport := Transport}) -> {"~s [~s]", [Text, Transport]}. -spec format_user(anonymous | iodata()) -> iodata(). format_user(anonymous) -> <<"anonymous">>; format_user(User) -> [<<"user ">>, User]. stun-1.2.10/src/turn_tmp_sup.erl0000644000232200023220000000362014513201307017161 0ustar debalancedebalance%%%---------------------------------------------------------------------- %%% File : turn_tmp_sup.erl %%% Author : Evgeniy Khramtsov %%% Purpose : %%% Created : 3 May 2014 by Evgeniy Khramtsov %%% %%% %%% Copyright (C) 2002-2023 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 %%%=================================================================== start_link() -> supervisor:start_link({local, ?SERVER}, ?MODULE, []). %%%=================================================================== %%% Supervisor callbacks %%%=================================================================== init([]) -> SupFlags = #{strategy => simple_one_for_one, intensity => 10, period => 1}, ChildSpecs = [#{id => turn, restart => temporary, start => {turn, start_link, []}}], {ok, {SupFlags, ChildSpecs}}. %%%=================================================================== %%% Internal functions %%%=================================================================== stun-1.2.10/src/stun_sup.erl0000644000232200023220000000425214513201307016304 0ustar debalancedebalance%%%---------------------------------------------------------------------- %%% File : stun_sup.erl %%% Author : Evgeniy Khramtsov %%% Purpose : stun supervisor %%% Created : 2 May 2013 by Evgeniy Khramtsov %%% %%% %%% Copyright (C) 2002-2023 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([]) -> SupFlags = #{intensity => 10, period => 1}, ChildSpecs = [#{id => stun_listener_sup, type => supervisor, start => {stun_listener_sup, start_link, []}}, #{id => stun_tmp_sup, type => supervisor, start => {stun_tmp_sup, start_link, []}}, #{id => turn_tmp_sup, type => supervisor, start => {turn_tmp_sup, start_link, []}}, #{id => turn_sm, shutdown => 2000, start => {turn_sm, start_link, []}}], {ok, {SupFlags, ChildSpecs}}. %%%=================================================================== %%% Internal functions %%%=================================================================== stun-1.2.10/src/stun_tmp_sup.erl0000644000232200023220000000362014513201307017162 0ustar debalancedebalance%%%---------------------------------------------------------------------- %%% File : stun_tmp_sup.erl %%% Author : Evgeniy Khramtsov %%% Purpose : %%% Created : 3 May 2014 by Evgeniy Khramtsov %%% %%% %%% Copyright (C) 2002-2023 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 %%%=================================================================== start_link() -> supervisor:start_link({local, ?SERVER}, ?MODULE, []). %%%=================================================================== %%% Supervisor callbacks %%%=================================================================== init([]) -> SupFlags = #{strategy => simple_one_for_one, intensity => 10, period => 1}, ChildSpecs = [#{id => stun, restart => temporary, start => {stun, start_link, []}}], {ok, {SupFlags, ChildSpecs}}. %%%=================================================================== %%% Internal functions %%%=================================================================== stun-1.2.10/src/stun.app.src0000644000232200023220000000265614513201307016207 0ustar debalancedebalance%%%---------------------------------------------------------------------- %%% File : stun.app.src %%% Author : Evgeniy Khramtsov %%% Purpose : Application package description %%% Created : 4 Apr 2013 by Evgeniy Khramtsov %%% %%% %%% Copyright (C) 2002-2023 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.2.10"}, {modules, []}, {registered, []}, {applications, [kernel, stdlib, fast_tls, p1_utils]}, {mod, {stun_app,[]}}, %% hex.pm packaging: {licenses, ["Apache 2.0"]}, {links, [{"Github", "https://github.com/processone/stun"}]}]}. %% Local Variables: %% mode: erlang %% End: %% vim: set filetype=erlang tabstop=8: stun-1.2.10/src/stun_shaper.erl0000644000232200023220000000443714513201307016764 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-2023 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.2.10/CODE_OF_CONDUCT.md0000644000232200023220000000643314513201307015733 0ustar debalancedebalance# Contributor Covenant Code of Conduct ## Our Pledge In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation. ## Our Standards Examples of behavior that contributes to creating a positive environment include: * Using welcoming and inclusive language * Being respectful of differing viewpoints and experiences * Gracefully accepting constructive criticism * Focusing on what is best for the community * Showing empathy towards other community members Examples of unacceptable behavior by participants include: * The use of sexualized language or imagery and unwelcome sexual attention or advances * Trolling, insulting/derogatory comments, and personal or political attacks * Public or private harassment * Publishing others' private information, such as a physical or electronic address, without explicit permission * Other conduct which could reasonably be considered inappropriate in a professional setting ## Our Responsibilities Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. ## Scope This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at contact@process-one.net. All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. ## Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html [homepage]: https://www.contributor-covenant.org For answers to common questions about this code of conduct, see https://www.contributor-covenant.org/faq stun-1.2.10/CONTRIBUTING.md0000644000232200023220000001356514513201307015371 0ustar debalancedebalance# Contributing We'd love for you to contribute to our source code and to make our project even better than it is today! Here are the guidelines we'd like you to follow: * [Code of Conduct](#coc) * [Questions and Problems](#question) * [Issues and Bugs](#issue) * [Feature Requests](#feature) * [Issue Submission Guidelines](#submit) * [Pull Request Submission Guidelines](#submit-pr) * [Signing the CLA](#cla) ## Code of Conduct Help us keep our community open-minded and inclusive. Please read and follow our [Code of Conduct][coc]. ## Questions, Bugs, Features ### Got a Question or Problem? Do not open issues for general support questions as we want to keep GitHub issues for bug reports and feature requests. You've got much better chances of getting your question answered on dedicated support platforms, the best being [Stack Overflow][stackoverflow]. Stack Overflow is a much better place to ask questions since: - there are thousands of people willing to help on Stack Overflow - questions and answers stay available for public viewing so your question / answer might help someone else - Stack Overflow's voting system assures that the best answers are prominently visible. To save your and our time, we will systematically close all issues that are requests for general support and redirect people to the section you are reading right now. ### Found an Issue or Bug? If you find a bug in the source code, you can help us by submitting an issue to our [GitHub Repository][github]. Even better, you can submit a Pull Request with a fix. ### Missing a Feature? You can request a new feature by submitting an issue to our [GitHub Repository][github-issues]. If you would like to implement a new feature then consider what kind of change it is: * **Major Changes** that you wish to contribute to the project should be discussed first in an [GitHub issue][github-issues] that clearly outlines the changes and benefits of the feature. * **Small Changes** can directly be crafted and submitted to the [GitHub Repository][github] as a Pull Request. See the section about [Pull Request Submission Guidelines](#submit-pr). ## Issue Submission Guidelines Before you submit your issue search the archive, maybe your question was already answered. If your issue appears to be a bug, and hasn't been reported, open a new issue. Help us to maximize the effort we can spend fixing issues and adding new features, by not reporting duplicate issues. The "[new issue][github-new-issue]" form contains a number of prompts that you should fill out to make it easier to understand and categorize the issue. ## Pull Request Submission Guidelines By submitting a pull request for a code or doc contribution, you need to have the right to grant your contribution's copyright license to ProcessOne. Please check [ProcessOne CLA][cla] for details. Before you submit your pull request consider the following guidelines: * Search [GitHub][github-pr] for an open or closed Pull Request that relates to your submission. You don't want to duplicate effort. * Make your changes in a new git branch: ```shell git checkout -b my-fix-branch master ``` * Test your changes and, if relevant, expand the automated test suite. * Create your patch commit, including appropriate test cases. * If the changes affect public APIs, change or add relevant documentation. * Commit your changes using a descriptive commit message. ```shell git commit -a ``` Note: the optional commit `-a` command line option will automatically "add" and "rm" edited files. * Push your branch to GitHub: ```shell git push origin my-fix-branch ``` * In GitHub, send a pull request to `master` branch. This will trigger the continuous integration and run the test. We will also notify you if you have not yet signed the [contribution agreement][cla]. * If you find that the continunous integration has failed, look into the logs to find out if your changes caused test failures, the commit message was malformed etc. If you find that the tests failed or times out for unrelated reasons, you can ping a team member so that the build can be restarted. * If we suggest changes, then: * Make the required updates. * Test your changes and test cases. * Commit your changes to your branch (e.g. `my-fix-branch`). * Push the changes to your GitHub repository (this will update your Pull Request). You can also amend the initial commits and force push them to the branch. ```shell git rebase master -i git push origin my-fix-branch -f ``` This is generally easier to follow, but separate commits are useful if the Pull Request contains iterations that might be interesting to see side-by-side. That's it! Thank you for your contribution! ## Signing the Contributor License Agreement (CLA) Upon submitting a Pull Request, we will ask you to sign our CLA if you haven't done so before. It's a quick process, we promise, and you will be able to do it all online You can read [ProcessOne Contribution License Agreement][cla] in PDF. This is part of the legal framework of the open-source ecosystem that adds some red tape, but protects both the contributor and the company / foundation behind the project. It also gives us the option to relicense the code with a more permissive license in the future. [coc]: https://github.com/processone/stun/blob/master/CODE_OF_CONDUCT.md [stackoverflow]: https://stackoverflow.com/ [github]: https://github.com/processone/stun [github-issues]: https://github.com/processone/stun/issues [github-new-issue]: https://github.com/processone/stun/issues/new [github-pr]: https://github.com/processone/stun/pulls [cla]: https://www.process-one.net/resources/ejabberd-cla.pdf [license]: https://github.com/processone/stun/blob/master/LICENSE.txt