Compare commits

...

75 Commits
nlj ... master

Author SHA1 Message Date
bgrozev
d289f125a4
Expose AbstractUdpListener.localAddress. (#277) 2023-12-20 15:12:15 -08:00
Дамян Минков
0d8af275cd Update README.md forum link. 2023-11-20 16:32:27 -06:00
Jonathan Lennox
1c60acc59b
Update for ktlint 1.0.0 (ktlint-maven-plugin 3.0.0). (#273) 2023-10-03 11:20:28 -04:00
bgrozev
fd43e6c181
Fix consent checks (#272)
* fix: Fix sending consent checks (wrong property name).

* log: Log exceptions from PeriodicRunnable.
2023-10-02 07:38:14 -07:00
Jonathan Lennox
27ad37d1af
Update Kotlin to 1.9.10, and related Maven packages, and jitsi-utils and jicoco. (#271)
* Update Kotlin to 1.9.10, and related Maven packages, and jitsi-utils and jicoco.

* Update ktlint-maven-plugin.
2023-09-29 12:22:20 -04:00
bgrozev
9fe2d69cf1
Randomize consent check interval (follow rfc7675). (#270)
* Randomize consent check interval (follow rfc7675).
2023-08-23 14:38:31 -07:00
bgrozev
a947919f40
test: Use meet-jit-si-turnrelay.jitsi.net for STUN, do not use TURN in tests. (#269) 2023-03-06 08:58:41 -06:00
bgrozev
76e8a1968d
fix: Fix creating STUN harvesters when no local addresses are allowed. (#265) 2022-10-21 16:21:23 -05:00
Jonathan Lennox
28a23e1859
Update kotlin version. (#262) 2022-05-26 16:34:13 -04:00
Ingo Bauersachs
71e244dd67 Update dependencies 2022-05-16 09:24:32 -05:00
bgrozev
f41542dd7c
fix: Suppress stack trace log as intended in #257. (#260) 2022-05-12 12:10:52 -05:00
bgrozev
dec3a87d21
ref: Remove use of JMap. (#259)
* ref: Remove use of JMap and the guava dependency
* Update jitsi-utils
  * Remove the guava dependency (jitsi/jitsi-utils#119)
  * Don't use "jnilib" as the suffix for mac native libs; it's just "dylib". (jitsi/jitsi-utils#118)
  * Make BucketStats.toJson() overridable. (jitsi/jitsi-utils#117)
  * Move routeLoudestOnly filtering. (jitsi/jitsi-utils#116)
  * Add DominantSpeakerIdentification.isAmongLoudest (jitsi/jitsi-utils#115)
  * feat: Add an option to close the queue without interrupting the running task. (jitsi/jitsi-utils#114)
  * ref(EventEmitter): use error lvl for throwables  Pawel Domas
2022-05-02 15:20:20 -05:00
bgrozev
1f97cf2b26
log: Do not print stack trace (#257)
when ConnectivityCheckClient fails to send due to missing socket.

This condition happens when SinglePortUdpListener is used and hasn't
received packets from the destination address yet.
2022-04-21 14:27:33 -05:00
bgrozev
32a8aadae8
Port more config properties to AgentConfig (#254)
* test: Disable config caching for tests.

* feat: Port SOFTWARE to AgentConfig.

* feat: Port USE_COMPONENT_SOCKET to AgentConfig.
2022-03-04 10:41:07 -06:00
bgrozev
2baae57d53
ref: Use the HEADER_LENGTH constant. (#252) 2022-03-02 10:00:07 -06:00
bgrozev
f195378a3d
fix: Add a null check. (#253)
org.ice4j.stack.StunClientTransaction$Retransmitter.run: A client tran retransmission failed
java.lang.NullPointerException
        at org.ice4j.stack.Connector.sendMessage(Connector.java:329)
        at org.ice4j.stack.NetAccessManager.sendMessage(NetAccessManager.java:635)
2022-03-02 09:54:09 -06:00
bgrozev
a9ba80efb9
feat: Support harvesting with ephemeral ports. (#250) 2022-01-05 14:46:58 -06:00
Boris Grozev
86f1eaede2 fix: Fix gathering ipv6 addresses (broken in #214). 2022-01-05 12:40:22 -07:00
Jonathan Lennox
ddfc498d0b Squash: handle null reason phrase. 2021-12-29 14:47:12 -07:00
Jonathan Lennox
d825218ab7 Log the reason phrase of a STUN error response. 2021-12-29 14:47:12 -07:00
Boris Grozev
fc1498ef7e feat: Allow useDynamicPorts to be set per-Agent. 2021-12-29 14:46:58 -07:00
Jonathan Lennox
2e43ba1b3e
Log exceptions sending STUN requests when we can't find the socket. (#246) 2021-12-29 15:42:04 -05:00
Boris Grozev
64a7ca8c30 ref: Remove unused "transport" parameter. 2021-11-17 11:53:51 -07:00
Boris Grozev
f637413a98 ref: Clean up logger usage. 2021-11-17 11:53:51 -07:00
Ingo Bauersachs
15981cf5f3
Merge pull request #240 from jitsi/remove-private-jdk-api
Remove private jdk api
2021-11-09 21:57:49 +01:00
Ingo Bauersachs
0811007990 Improve test stability with wait/notify instead of sleeping 2021-11-09 21:18:02 +01:00
Ingo Bauersachs
cd2d21a8d0 Cleanup to make sure monotonic time is used, not wall-time
System.currentTimeMillis is not precise and may move backwards.
2021-11-09 21:02:27 +01:00
Ingo Bauersachs
626c35e460 Return unwrapped SocketOutputStream from PseudoTcpSocket
JDK17 introduced a wrapper around SocketOutputStream in
Socket.getOutputStream that doesn't forward flush. Directly return
our implementation in PseudoTcpSocket making sure that the original
intent of closing the socket when the stream is closed is still
followed.
2021-11-09 21:02:27 +01:00
Ingo Bauersachs
a1b3c9b503 Upgrade dependencies and build/test also on Java 17 2021-11-09 21:02:27 +01:00
Ingo Bauersachs
15d69b316c Remove ServerSocketChannel muxing that used private JDK api
Closes #239
2021-11-08 21:05:54 +01:00
bgrozev
d4a145374f
Add a log message when using StunMappingCandidateHarvester. (#238)
* log: Add a log message when using StunMappingCandidateHarvester.
* ref: Use lambda, fix formating.
2021-09-29 10:34:35 -05:00
Jonathan Lennox
d7c0e27a1c
Synchronize access to candidateSockets.get(). (#203)
* Synchronize access to candidateSockets.get().

* Remove XXX comment about synchronization.
2021-09-17 15:48:45 -05:00
Дамян Минков
9dc08bd299
feat: Adds checkstyle module. (#233)
* feat: Adds checkstyle module.
2021-09-02 12:54:33 -05:00
Jonathan Lennox
adca67b17f
Fix a race stopping a connectivity check client. (#237)
* Fix a race stopping a connectivity check client.

(This could result in the agent, and everything it references, staying reachable and so being leaked.)
2021-08-24 16:40:35 -05:00
bgrozev
076281c76b
Support mapping a single port in MappingCandidateHarvester. (#235)
* test: Add unit test for MappingCandidateHarvester.

* ref: Move MappingCandidateHarvester to kotlin.

* feat: Add the option to match the configured port.

* feat: Support statically mapping a specific port.

* feat: Add a name to MappingCandidateHarvester.

* doc: Add more docs to reference.conf.
2021-08-16 13:26:35 -05:00
bgrozev
311a495b21
Update kotlin to 1.5.20. (#232)
* ref: Remove unused code (stats never queried).

* chore: Update jitsi-utils.

* chore: Update kotlin to 1.5.20.

* chore: Update jitsi-utils
  * Update kotlin to 1.5.20.

* chore: Update jicoco.

* chore: Update jacoco to 0.8.7.
2021-07-14 14:58:07 -05:00
Nils Ohlmeier
10346acade
feat: Enable ephemeral port usage (#231)
* Port 0 allows to request ephemeral port
2021-07-13 15:24:12 -05:00
bgrozev
924f40c4e0
config: Fix static mapping property names (reported by @DoM1niC). (#230) 2021-06-08 12:06:56 +03:00
bgrozev
2586d8b2da
Port NAT harvester properties to new config (#229)
* feat: Port "nat harvester" to the new config.

* ref: Fix ktlint errors.
2021-05-26 18:01:12 +03:00
Ingo Bauersachs
3e0a9f97ef
Use ephemeral port for server socket (#228) 2021-05-03 23:21:29 +02:00
Ingo Bauersachs
f6550a80ac
Update Dokka to/and remove JCenter (#227) 2021-05-03 16:39:09 +02:00
George Politis
c829b3a766
feat: Adds a coverage profile and configures Codecov. (#225) 2021-04-12 16:17:55 +01:00
Ingo Bauersachs
f176d021f8
Replace static with random port in tests (#224) 2021-04-09 00:12:10 +02:00
Jonathan Lennox
5a299cd694
Shut down harvester thread pool when it's done. (#223)
* Shut down harvester thread pool when it's done.

* Use ExecutorService to create harvester threads; name thread pool threads to match other ice4j threads.
2021-04-08 15:51:51 -04:00
Ingo Bauersachs
34c2ce50ec
Migrate tests to JUnit 5 and release Maven Central (#221)
* Migrate test to JUnit 5 and prepare POM for Maven Central

* Use random ports for transaction tests

* Apply ktlint format

* Fix flaky tests

* Use jicoco from Maven Central

* Remove semver checks

* Add Kotlin linting check

* Use bnd-maven-plugin for OSGi to avoid confusing Kotlin

* Release to Maven Central

Closes #213
Closes #95

* Fix braces formatting that crept in with a regex
2021-01-04 21:34:02 +01:00
dependabot[bot]
a86c4be742
build(deps-dev): bump junit from 4.11 to 4.13.1 (#217)
Bumps [junit](https://github.com/junit-team/junit4) from 4.11 to 4.13.1.
- [Release notes](https://github.com/junit-team/junit4/releases)
- [Changelog](https://github.com/junit-team/junit4/blob/main/doc/ReleaseNotes4.11.md)
- [Commits](https://github.com/junit-team/junit4/compare/r4.11...r4.13.1)

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2020-10-13 13:54:10 -04:00
bgrozev
67ffceb81d
Port AWS harvester config. (#216) 2020-10-09 11:01:35 -05:00
bgrozev
3a55627ba0
ref: Port StunMappingHarvester config. (#215) 2020-09-25 11:39:13 -05:00
bgrozev
29ae8061ad
Port more config properties. (#214)
* ref: Port the "disable link-local addresses" property.

* ref: Port the receive buffer size property.

* ref: Port the "disable ipv6" property.

* ref: Port the "dynamic ports" propertty.

* ref: Port the timeout property.

* test: Add tests for the new properties.
2020-09-14 12:43:56 -05:00
bgrozev
f8a506ef70
Use metaconfig, port some properties. (#212)
* Use metaconfig, port some properties.

* ref: Use the typesource config to read system properties.

* fix: Fix a typo.

* Add tests for AgentConfig.
2020-08-24 11:36:22 -05:00
bgrozev
686164ffc4
ref: Rename variables. (#209) 2020-06-10 15:15:11 -05:00
bgrozev
ed63ae8e11
fix: Match the base when finding a local canidate for a remote address (fixes #205). (#208)
* fix: Match the base when finding a local canidate for a remote address (fixes #205).
2020-06-10 14:18:33 -05:00
bgrozev
9a580a9401
Remove unused code, fix typo and formatting (#207)
* Remove unused method.

* Fix typos and formatting.
2020-06-09 16:25:10 -05:00
Jonathan Lennox
8ffa9030f4
Log the real source port of STUN mapping requests. (#206) 2020-06-05 17:57:18 -04:00
Jonathan Lennox
7016902b21
Shut down STUN stack before removing streams from Agent. (#202)
Should fix NPEs being thrown during Agent.free().
2020-04-21 09:59:33 -04:00
Jonathan Lennox
e6e36856c6
Fix format of msgType in exception message. (#201) 2020-04-17 16:11:28 -04:00
Jonathan Lennox
e90c796d6d
Merge duplicate ICE candidate pairs. (#195)
This can happen if a remote candidate is discovered as peer-reflexive and later received over signaling.
2020-04-08 12:48:48 -04:00
Jonathan Lennox
ca3868ac26
Avoid double-nomination of ICE candidate pairs. (#198)
Nomination is blocked once something is nominated rather than waiting until something is selected.
2020-04-07 18:25:16 -04:00
Jonathan Lennox
982e78212b
Some helpers for adding an ICE nomination strategy config option. (#197)
* Add fromString method to NominationStrategy.

* Add getters for NominationStrategy.

This allows Kotlin to model Agent's nominationStrategy as a property.
2020-04-07 16:52:57 -04:00
Jonathan Lennox
35e149848e
Remove local ufrag from log messages. (#196)
Not needed now that we have logger2, which has it in the log context.
2020-04-07 16:33:35 -04:00
bgrozev
36f732ba1c
Initializes the harvesters array to non-null. (#193) 2020-04-03 14:34:06 -05:00
Ingo Bauersachs
e0fccdaf4d
Merge pull request #191 from mstyura/remove-unused-dep
Updated java-sdp-nist-bridge and removed explict jain-sip-ri-ossonly dependency.
2020-03-28 02:37:43 +01:00
Yura Yaroshevich
b504c2cc2e Updated java-sdp-nist-bridge to 1.2 2020-03-23 20:40:59 +03:00
Yura Yaroshevich
78e006cbac Remove unused dependency 2020-03-23 15:24:26 +03:00
bgrozev
fe30fe8a31
Adds the remote address and ufrag to a log message. (#190)
* Adds the remote address and ufrag to a log message.
2020-02-26 10:28:55 -06:00
Yury Yaroshevich
7989977e1e Added Message-Integrity attribute to Role Conflict message. (#187)
* Added missing attributes to Role Conflict message.

* Updated logs and fixed comments.

* Added unit test of role conflict recovery.

* Fixed long lines.
2019-09-30 13:27:07 -07:00
bbaldino
43a9f282d2
use classes in jitsi-utils (#188)
* use queuestatistics/ratestatistcs from jitsi-utils

* remove packetqueue (exists in jitsi-utils)

* use executorfactory in jitsi-utils

* use customizablethreadfactory on jitsi-utils

* remove asyncqueuehandler (exists in jitsi-utils)
2019-09-25 08:54:06 -07:00
bbaldino
e854e4efaf
use the jitsi-utils logger (#186)
* use new logger in agent

* use new logger in component, componentsocket, icemediastream, mergingdatagramsocket

* use new logger in localcandidate

* use new logger in checklist

* use new logger in defaultnominator

* use new logger in connectivitycheckclient, connectivitycheckserver

* fix typo, allow taking in a parent logger

* use jitsi-utils

* clean up uses of old logger and remove it
2019-09-19 08:11:18 -07:00
Brian Baldino
43fa07d9a5 increase major version number 2019-09-17 09:14:02 -07:00
damencho
0b052e8f85 Removes extra exception printed on initializing delegating channels. 2019-06-07 19:41:14 +01:00
Дамян Минков
c7c4719c45
Prepares for java 11. (#180)
* Prepares for java 11.

* Removes unused import.
2019-05-09 14:22:52 +01:00
Han Xu
59461c9d13 Clear system property at the end of test.
The current test is passing, but still I think it's better to clear
the system property it sets.
2019-04-24 09:44:02 +01:00
Han Xu
105a49749e Fix Retransmitter creation to take effect of originalWaitInterval config 2019-04-24 09:44:02 +01:00
Peter Sear
0ea60d85b3 Add unit tests for org.ice4j.ice.NetworkUtilsTest
These tests were written using Diffblue Cover.
2019-03-28 09:43:48 -07:00
Дамян Минков
17bbc9b97a Removes jitsi-universe dependency. (#177) 2019-03-27 16:01:44 +00:00
174 changed files with 4486 additions and 8163 deletions

17
.editorconfig Normal file
View File

@ -0,0 +1,17 @@
[*]
end_of_line = lf
insert_final_newline = true
charset = utf-8
[pom.xml]
indent_size = 2
indent_style = space
max_line_length = 120
[*.{kt,kts}]
max_line_length = 120
ktlint_code_style = intellij_idea
# I find trailing commas annoying
ktlint_standard_trailing-comma-on-call-site = disabled
ktlint_standard_trailing-comma-on-declaration-site = disabled

82
.github/workflows/maven.yml vendored Normal file
View File

@ -0,0 +1,82 @@
# This workflow will build a Java project with Maven
# For more information see: https://help.github.com/actions/language-and-framework-guides/building-and-testing-java-with-maven
name: Java CI with Maven
on:
push:
branches: [ master ]
pull_request:
branches: [ master ]
env:
# Java version to use for the release
RELEASE_JAVA_VERSION: 11
jobs:
test:
runs-on: ubuntu-latest
strategy:
matrix:
java: [ 11, 17 ]
name: Java ${{ matrix.java }}
steps:
- name: Checkout
uses: actions/checkout@v3
- name: Set up JDK ${{ matrix.java }}
uses: actions/setup-java@v3
with:
distribution: temurin
java-version: ${{ matrix.java }}
cache: maven
- name: Build and test with Maven
run: mvn -B -Dgpg.skip -Drelease=true -Pcoverage verify
- name: Upload coverage report
if: matrix.java == env.RELEASE_JAVA_VERSION
uses: codecov/codecov-action@v2
release:
if: github.ref == 'refs/heads/master'
needs: test
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v3
with:
fetch-depth: 0
- name: Set up JDK
uses: actions/setup-java@v3
with:
distribution: temurin
java-version: ${{ env.RELEASE_JAVA_VERSION }}
cache: maven
server-id: ossrh
server-username: SONATYPE_USER
server-password: SONATYPE_PW
- name: Set version
run: |
VERSION=`git describe --match "v[0-9\.]*" --long --dirty --always`
mvn -B versions:set -DnewVersion=${VERSION:1} -DgenerateBackupPoms=false
- name: Release to Maven Central
env:
SONATYPE_USER: ${{ secrets.SONATYPE_USER }}
SONATYPE_PW: ${{ secrets.SONATYPE_PW }}
run: |
cat <(echo -e "${{ secrets.GPG_KEY }}") | gpg --batch --import
gpg --list-secret-keys --keyid-format LONG
mvn \
--no-transfer-progress \
--batch-mode \
-Dgpg.passphrase="${{ secrets.GPG_PW }}" \
-Drelease=true \
-DskipTests \
deploy

4
.gitignore vendored
View File

@ -7,3 +7,7 @@
.project .project
.settings/ .settings/
bin/ bin/
# Ignore IntelliJ IDEA files
.idea
*.iml

View File

@ -4,7 +4,7 @@ The Interactive Connectivity Establishment (ICE) protocol combines various NAT t
This project provides a Java implementation of the ICE protocol that would be usable by both SIP and XMPP applications. The project also provides features such as socket sharing and support for Pseudo TCP. This project provides a Java implementation of the ICE protocol that would be usable by both SIP and XMPP applications. The project also provides features such as socket sharing and support for Pseudo TCP.
ice4j is maintained by the [Jitsi](https://jitsi.org/) community. Use Jitsi's [dev mailing list](https://jitsi.org/Development/MailingLists) for questions and discussions. ice4j is maintained by the [Jitsi](https://jitsi.org/) community. Use Jitsi's [community forum](https://community.jitsi.org) for questions and discussions.
Thanks Thanks
------ ------

6
bnd.bnd Normal file
View File

@ -0,0 +1,6 @@
Export-Package: org.ice4j.*
Import-Package: *;version=!
Bundle-SymbolicName: org.jitsi.ice4j
-noextraheaders: true
-snapshot: SNAPSHOT
-removeheaders: Require-Capability, Bundle-SCM

40
checkstyle.xml Normal file
View File

@ -0,0 +1,40 @@
<?xml version="1.0"?>
<!DOCTYPE module PUBLIC
"-//Checkstyle//DTD Checkstyle Configuration 1.3//EN"
"https://checkstyle.org/dtds/configuration_1_3.dtd">
<module name="Checker">
<module name="SuppressWithPlainTextCommentFilter"/>
<module name="LineLength">
<property name="fileExtensions" value="java"/>
<property name="max" value="120"/>
<property name="ignorePattern" value="http://|https://"/>
</module>
<module name="TreeWalker">
<module name="LeftCurly">
<property name="option" value="nl"/>
<property name="tokens" value="LITERAL_CATCH"/>
<property name="tokens" value="LITERAL_ELSE"/>
<property name="tokens" value="LITERAL_FINALLY"/>
<property name="tokens" value="LITERAL_IF"/>
<property name="tokens" value="LITERAL_TRY"/>
</module>
<!-- Skips empty blocks {}, to not skip them: value="alone" -->
<module name="RightCurly">
<property name="option" value="alone_or_singleline"/>
</module>
<module name="WhitespaceAfter">
<!-- Drops TYPECAST from default tokens -->
<property name="tokens" value="COMMA , SEMI , LITERAL_IF , LITERAL_ELSE , LITERAL_WHILE , LITERAL_DO , LITERAL_FOR , DO_WHILE"/>
</module>
</module>
<module name="FileTabCharacter">
<property name="eachLine" value="true"/>
</module>
</module>

412
pom.xml
View File

@ -1,42 +1,119 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<parent> <groupId>org.jitsi</groupId>
<groupId>org.jitsi</groupId>
<artifactId>jitsi-universe-public</artifactId>
<version>1.0</version>
</parent>
<artifactId>ice4j</artifactId> <artifactId>ice4j</artifactId>
<version>2.0.0-SNAPSHOT</version> <version>3.0-SNAPSHOT</version>
<packaging>bundle</packaging>
<name>ice4j</name> <name>ice4j</name>
<description>A Java implementation of the ICE protocol</description>
<url>https://github.com/jitsi/ice4j</url> <url>https://github.com/jitsi/ice4j</url>
<organization>
<name>jitsi.org</name>
<url>https://jitsi.org</url>
</organization>
<developers>
<developer>
<id>org.jitsi</id>
<name>Jitsi Team</name>
<email>dev@jitsi.org</email>
</developer>
</developers>
<scm> <scm>
<url>https://github.com/jitsi/ice4j</url> <url>https://github.com/jitsi/ice4j</url>
<connection>scm:git:https://github.com/jitsi/ice4j.git</connection> <connection>scm:git:https://github.com/jitsi/ice4j.git</connection>
<developerConnection>scm:git:https://github.com/jitsi/ice4j.git</developerConnection> <developerConnection>scm:git:https://github.com/jitsi/ice4j.git</developerConnection>
<tag>HEAD</tag>
</scm> </scm>
<licenses>
<license>
<name>Apache-2.0</name>
<url>https://github.com/jitsi/ice4j/blob/master/LICENSE</url>
<distribution>repo</distribution>
</license>
</licenses>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<jicoco.version>1.1-127-gf49982f</jicoco.version>
<kotlin.version>1.9.10</kotlin.version>
<dokka.version>1.9.0</dokka.version>
<kotest.version>5.7.2</kotest.version>
<junit.version>5.10.0</junit.version>
</properties>
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>org.opentelecoms.sdp</groupId> <groupId>org.opentelecoms.sdp</groupId>
<artifactId>java-sdp-nist-bridge</artifactId> <artifactId>java-sdp-nist-bridge</artifactId>
</dependency> <version>1.2</version>
<dependency>
<groupId>org.jitsi</groupId>
<artifactId>jain-sip-ri-ossonly</artifactId>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.bitlet</groupId> <groupId>org.bitlet</groupId>
<artifactId>weupnp</artifactId> <artifactId>weupnp</artifactId>
<version>0.1.4</version>
</dependency> </dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>jitsi-utils</artifactId>
<version>1.0-127-g6c65524</version>
</dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>jicoco-config</artifactId>
<version>${jicoco.version}</version>
</dependency>
<!-- test --> <!-- test -->
<dependency> <dependency>
<groupId>junit</groupId> <groupId>org.junit.platform</groupId>
<artifactId>junit</artifactId> <artifactId>junit-platform-launcher</artifactId>
<version>1.10.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.kotest</groupId>
<artifactId>kotest-assertions-core-jvm</artifactId>
<version>${kotest.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.kotest</groupId>
<artifactId>kotest-runner-junit5-jvm</artifactId>
<version>${kotest.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jitsi</groupId>
<artifactId>jicoco-test-kotlin</artifactId>
<version>${jicoco.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>4.5.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.mockk</groupId>
<artifactId>mockk-jvm</artifactId>
<version>1.13.8</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
</dependencies> </dependencies>
@ -44,66 +121,172 @@
<build> <build>
<plugins> <plugins>
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.jetbrains.kotlin</groupId>
<artifactId>maven-compiler-plugin</artifactId> <artifactId>kotlin-maven-plugin</artifactId>
<version>${kotlin.version}</version>
<executions>
<execution>
<id>compile</id>
<phase>compile</phase>
<goals>
<goal>compile</goal>
</goals>
<configuration>
<sourceDirs>
<sourceDir>${project.basedir}/src/main/kotlin</sourceDir>
<sourceDir>${project.basedir}/src/main/java</sourceDir>
</sourceDirs>
</configuration>
</execution>
<execution>
<id>test-compile</id>
<phase>test-compile</phase>
<goals>
<goal>test-compile</goal>
</goals>
<configuration>
<sourceDirs>
<sourceDir>${project.basedir}/src/test/kotlin</sourceDir>
<sourceDir>${project.basedir}/src/test/java</sourceDir>
</sourceDirs>
</configuration>
</execution>
</executions>
<configuration> <configuration>
<source>1.8</source> <jvmTarget>11</jvmTarget>
<target>1.8</target> <args>
<arg>-Xallow-result-return-type</arg>
</args>
</configuration> </configuration>
</plugin> </plugin>
<plugin> <plugin>
<groupId>org.apache.felix</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-bundle-plugin</artifactId> <artifactId>maven-compiler-plugin</artifactId>
<version>3.10.1</version>
<executions>
<!-- Replacing default-compile as it is treated specially by maven -->
<execution>
<id>default-compile</id>
<phase>none</phase>
</execution>
<!-- Replacing default-testCompile as it is treated specially by maven -->
<execution>
<id>default-testCompile</id>
<phase>none</phase>
</execution>
<execution>
<id>java-compile</id>
<phase>compile</phase>
<goals>
<goal>compile</goal>
</goals>
</execution>
<execution>
<id>java-test-compile</id>
<phase>test-compile</phase>
<goals>
<goal>testCompile</goal>
</goals>
</execution>
</executions>
<configuration>
<release>11</release>
<compilerArgs>
<arg>-Xlint:all</arg>
</compilerArgs>
</configuration>
</plugin> </plugin>
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId> <artifactId>maven-checkstyle-plugin</artifactId>
<version>2.10.4</version> <version>3.1.2</version>
<configuration> <configuration>
<show>private</show> <configLocation>checkstyle.xml</configLocation>
<nohelp>true</nohelp> </configuration>
<dependencies>
<dependency>
<groupId>com.puppycrawl.tools</groupId>
<artifactId>checkstyle</artifactId>
<version>10.1</version>
</dependency>
</dependencies>
<executions>
<execution>
<goals>
<goal>check</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>com.github.gantsign.maven</groupId>
<artifactId>ktlint-maven-plugin</artifactId>
<version>3.0.0</version>
<configuration>
<sourceRoots>
<sourceRoot>${project.basedir}/src/main/kotlin</sourceRoot>
</sourceRoots>
<testSourceRoots>
<testSourceRoot>${project.basedir}/src/test/kotlin</testSourceRoot>
</testSourceRoots>
</configuration>
<executions>
<execution>
<id>check</id>
<goals>
<goal>check</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>biz.aQute.bnd</groupId>
<artifactId>bnd-maven-plugin</artifactId>
<version>6.2.0</version>
<executions>
<execution>
<goals>
<goal>bnd-process</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>3.2.2</version>
<configuration>
<archive>
<manifestFile>${project.build.outputDirectory}/META-INF/MANIFEST.MF</manifestFile>
</archive>
</configuration> </configuration>
</plugin> </plugin>
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId> <artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M6</version>
<configuration> <configuration>
<includes> <includes>**/*</includes>
<include>**/*TestSuite.*</include> <systemPropertyVariables>
</includes> <java.util.logging.config.file>${project.build.testSourceDirectory}/../resources/logging.properties</java.util.logging.config.file>
</systemPropertyVariables>
</configuration> </configuration>
</plugin> </plugin>
<plugin> <plugin>
<groupId>com.github.siom79.japicmp</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>japicmp-maven-plugin</artifactId> <artifactId>maven-deploy-plugin</artifactId>
<version>0.10.0</version> <version>3.0.0-M2</version>
</plugin>
<plugin>
<groupId>org.sonatype.plugins</groupId>
<artifactId>nexus-staging-maven-plugin</artifactId>
<version>1.6.13</version>
<extensions>true</extensions>
<configuration> <configuration>
<newVersion> <serverId>ossrh</serverId>
<file> <nexusUrl>https://oss.sonatype.org/</nexusUrl>
<path>${project.build.directory}/${project.build.finalName}.jar</path> <autoReleaseAfterClose>true</autoReleaseAfterClose>
</file>
</newVersion>
<oldVersion>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>${project.artifactId}</artifactId>
<version>1.0.0</version>
</dependency>
</oldVersion>
<parameter>
<onlyModified>true</onlyModified>
<breakBuildBasedOnSemanticVersioning>true</breakBuildBasedOnSemanticVersioning>
<reportOnlyFilename>true</reportOnlyFilename>
</parameter>
</configuration> </configuration>
<executions>
<execution>
<phase>verify</phase>
<goals>
<goal>cmp</goal>
</goals>
</execution>
</executions>
</plugin> </plugin>
</plugins> </plugins>
@ -112,6 +295,7 @@
<plugin> <plugin>
<groupId>org.codehaus.mojo</groupId> <groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId> <artifactId>exec-maven-plugin</artifactId>
<version>3.0.0</version>
<executions> <executions>
<execution> <execution>
<goals> <goals>
@ -134,6 +318,32 @@
</build> </build>
<profiles> <profiles>
<profile>
<id>coverage</id>
<build>
<plugins>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.8.8</version>
<executions>
<execution>
<goals>
<goal>prepare-agent</goal>
</goals>
</execution>
<execution>
<id>report</id>
<phase>test</phase>
<goals>
<goal>report</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
<profile> <profile>
<id>run-sample</id> <id>run-sample</id>
<build> <build>
@ -238,5 +448,95 @@
</plugins> </plugins>
</build> </build>
</profile> </profile>
<profile>
<id>release</id>
<activation>
<property>
<name>release</name>
<value>true</value>
</property>
</activation>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
<version>3.3.0</version>
<executions>
<execution>
<phase>generate-sources</phase>
<goals>
<goal>add-source</goal>
</goals>
<configuration>
<sources>
<source>src/main/kotlin</source>
</sources>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<version>3.2.1</version>
<executions>
<execution>
<id>attach-sources</id>
<phase>verify</phase>
<goals>
<goal>jar-no-fork</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.jetbrains.dokka</groupId>
<artifactId>dokka-maven-plugin</artifactId>
<version>${dokka.version}</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>javadocJar</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-gpg-plugin</artifactId>
<version>3.0.1</version>
<executions>
<execution>
<id>sign-artifacts</id>
<phase>verify</phase>
<goals>
<goal>sign</goal>
</goals>
</execution>
</executions>
<configuration>
<gpgArguments>
<arg>--pinentry-mode</arg>
<arg>loopback</arg>
</gpgArguments>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles> </profiles>
<distributionManagement>
<snapshotRepository>
<id>ossrh</id>
<url>https://oss.sonatype.org/content/repositories/snapshots</url>
</snapshotRepository>
<repository>
<id>ossrh</id>
<url>https://oss.sonatype.org/service/local/staging/deploy/maven2/</url>
</repository>
</distributionManagement>
</project> </project>

View File

@ -59,43 +59,6 @@ public class StackProperties
*/ */
public static final String BIND_WILDCARD = "org.ice4j.BIND_WILDCARD"; public static final String BIND_WILDCARD = "org.ice4j.BIND_WILDCARD";
/**
* How often a STUN Binding request used for consent freshness check will be
* sent(value in milliseconds).
*/
public static final String CONSENT_FRESHNESS_INTERVAL
= "org.ice4j.ice.CONSENT_FRESHNESS_INTERVAL";
/**
* The maximum number of retransmissions of a STUN Binding request without
* a valid STUN Binding response after which consent freshness is to be
* considered unconfirmed according to &quot;STUN Usage for Consent
* Freshness&quot;.
*/
public static final String CONSENT_FRESHNESS_MAX_RETRANSMISSIONS
= "org.ice4j.ice.CONSENT_FRESHNESS_MAX_RETRANSMISSIONS";
/**
* The number of milliseconds without a valid STUN Binding response after
* which a STUN Binding request is to be retransmitted according to
* &quot;STUN Usage for Consent Freshness&quot;. This is the final value
* for the back-off strategy.
* {@link #CONSENT_FRESHNESS_ORIGINAL_WAIT_INTERVAL} defines the initial
* interval for the first request sent. Value in milliseconds.
*/
public static final String CONSENT_FRESHNESS_MAX_WAIT_INTERVAL
= "org.ice4j.ice.CONSENT_FRESHNESS_MAX_WAIT_INTERVAL";
/**
* The number of milliseconds without a valid STUN Binding response after
* which a STUN Binding request is to be retransmitted according to
* &quot;STUN Usage for Consent Freshness&quot;. This is the original value
* for back-off strategy. {@link #CONSENT_FRESHNESS_MAX_WAIT_INTERVAL} sets
* the upper limit. Value in milliseconds.
*/
public static final String CONSENT_FRESHNESS_ORIGINAL_WAIT_INTERVAL
= "org.ice4j.ice.CONSENT_FRESHNESS_WAIT_INTERVAL";
/** /**
* The number of milliseconds a client transaction should wait before * The number of milliseconds a client transaction should wait before
* retransmitting, after it has sent a request for the first time. * retransmitting, after it has sent a request for the first time.
@ -123,19 +86,6 @@ public class StackProperties
public static final String MAX_CTRAN_RETRANSMISSIONS public static final String MAX_CTRAN_RETRANSMISSIONS
= "org.ice4j.MAX_RETRANSMISSIONS"; = "org.ice4j.MAX_RETRANSMISSIONS";
/**
* The name of the System property that allows us to set a custom maximum
* for check list sizes.
*/
public static final String MAX_CHECK_LIST_SIZE
= "org.ice4j.MAX_CHECK_LIST_SIZE";
/**
* The value of the SOFTWARE attribute that ice4j should include in all
* outgoing messages.
*/
public static final String SOFTWARE = "org.ice4j.SOFTWARE";
/** /**
* The name of the property that tells the stack whether or not it should * The name of the property that tells the stack whether or not it should
* let the application see retransmissions of incoming requests. * let the application see retransmissions of incoming requests.
@ -164,14 +114,6 @@ public class StackProperties
public static final String REQUIRE_MESSAGE_INTEGRITY public static final String REQUIRE_MESSAGE_INTEGRITY
= "org.ice4j.REQUIRE_MESSAGE_INTEGRITY"; = "org.ice4j.REQUIRE_MESSAGE_INTEGRITY";
/**
* The name of the property that can be used to specify the number of
* milliseconds that we must wait after ICE processing enters a COMPLTED
* state and before we free candidates and move into the TERMINATED state.
*/
public static final String TERMINATION_DELAY
= "org.ice4j.TERMINATION_DELAY";
/** /**
* The name of the property that can be used to disable STUN keep alives. * The name of the property that can be used to disable STUN keep alives.
* Set to <tt>true</tt> to disable. * Set to <tt>true</tt> to disable.
@ -190,11 +132,6 @@ public class StackProperties
public static final String NOMINATION_TIMER public static final String NOMINATION_TIMER
= "org.ice4j.NOMINATION_TIMER"; = "org.ice4j.NOMINATION_TIMER";
/**
* The name of the property used to disabled IPv6 support.
*/
public static final String DISABLE_IPv6 = "org.ice4j.ipv6.DISABLED";
/** /**
* The name of the allowed interfaces property which specifies the allowed * The name of the allowed interfaces property which specifies the allowed
* interfaces for host candidate allocations. * interfaces for host candidate allocations.
@ -219,13 +156,6 @@ public class StackProperties
public static final String ALLOWED_ADDRESSES public static final String ALLOWED_ADDRESSES
= "org.ice4j.ice.harvest.ALLOWED_ADDRESSES"; = "org.ice4j.ice.harvest.ALLOWED_ADDRESSES";
/**
* The name of the property which, if set to true, specifies that
* link local addresses should not be used for candidate allocations.
*/
public static final String DISABLE_LINK_LOCAL_ADDRESSES
= "org.ice4j.ice.harvest.DISABLE_LINK_LOCAL_ADDRESSES";
/** /**
* The name of the property which specifies a ";"-separated list of IP * The name of the property which specifies a ";"-separated list of IP
* addresses that are not allowed to be used for host candidate allocations. * addresses that are not allowed to be used for host candidate allocations.
@ -236,31 +166,6 @@ public class StackProperties
public static final String BLOCKED_ADDRESSES public static final String BLOCKED_ADDRESSES
= "org.ice4j.ice.harvest.BLOCKED_ADDRESSES"; = "org.ice4j.ice.harvest.BLOCKED_ADDRESSES";
/**
* The name of the property which specifies whether the dynamic port UDP
* host harvester should be used by <tt>Agent</tt> instances.
*/
public static final String USE_DYNAMIC_HOST_HARVESTER
= "org.ice4j.ice.harvest.USE_DYNAMIC_HOST_HARVESTER";
/**
* Timeout, in seconds, of how long to wait for an individual harvest before timing out
*/
public static final String HARVESTING_TIMEOUT
= "org.ice4j.ice.harvest.HARVESTING_TIMEOUT";
/**
* The name of the property which specifies whether the per-component
* merging socket should be enabled by default (the default value can be
* overridden with {@link Agent#createComponent(IceMediaStream, Transport,
* int, int, int, KeepAliveStrategy, boolean)}.
* If enabled, the user of the library must use the socket instance provided
* by {@link Component#getSocket()}. Otherwise, the socket instance from the
* desired {@link CandidatePair} must be used.
*/
public static final String USE_COMPONENT_SOCKET
= "org.ice4j.ice.USE_COMPONENT_SOCKET";
/** /**
* Returns the String value of the specified property (minus all * Returns the String value of the specified property (minus all
* encompassing whitespaces)and null in case no property value was mapped * encompassing whitespaces)and null in case no property value was mapped

View File

@ -99,22 +99,22 @@ public enum Transport
public static Transport parse(String transportName) public static Transport parse(String transportName)
throws IllegalArgumentException throws IllegalArgumentException
{ {
if(UDP.toString().equals(transportName)) if (UDP.toString().equals(transportName))
return UDP; return UDP;
if(TCP.toString().equals(transportName)) if (TCP.toString().equals(transportName))
return TCP; return TCP;
if(TLS.toString().equals(transportName)) if (TLS.toString().equals(transportName))
return TLS; return TLS;
if(SCTP.toString().equals(transportName)) if (SCTP.toString().equals(transportName))
return SCTP; return SCTP;
if(DTLS.toString().equals(transportName)) if (DTLS.toString().equals(transportName))
return DTLS; return DTLS;
if(SSLTCP.toString().equals(transportName)) if (SSLTCP.toString().equals(transportName))
return SSLTCP; return SSLTCP;
throw new IllegalArgumentException( throw new IllegalArgumentException(

View File

@ -148,14 +148,14 @@ public class TransportAddress
public String toString() public String toString()
{ {
String hostAddress = getHostAddress(); String hostAddress = getHostAddress();
if(hostAddress == null) if (hostAddress == null)
{ {
hostAddress = getHostName(); hostAddress = getHostName();
} }
StringBuilder bldr = new StringBuilder(hostAddress); StringBuilder bldr = new StringBuilder(hostAddress);
if(isIPv6()) if (isIPv6())
bldr.insert(0, "[").append("]"); bldr.insert(0, "[").append("]");
bldr.append(":").append(getPort()); bldr.append(":").append(getPort());
@ -175,7 +175,7 @@ public class TransportAddress
String addressStr String addressStr
= addr != null ? addr.getHostAddress() : null; = addr != null ? addr.getHostAddress() : null;
if(addr instanceof Inet6Address) if (addr instanceof Inet6Address)
addressStr = NetworkUtils.stripScopeID(addressStr); addressStr = NetworkUtils.stripScopeID(addressStr);
return addressStr; return addressStr;
@ -258,7 +258,7 @@ public class TransportAddress
*/ */
public boolean canReach(TransportAddress dst) public boolean canReach(TransportAddress dst)
{ {
if( getTransport() != dst.getTransport() ) if ( getTransport() != dst.getTransport() )
return false; return false;
if (isIPv6() != dst.isIPv6()) if (isIPv6() != dst.isIPv6())
@ -269,7 +269,7 @@ public class TransportAddress
Inet6Address srcAddr = (Inet6Address)getAddress(); Inet6Address srcAddr = (Inet6Address)getAddress();
Inet6Address dstAddr = (Inet6Address)dst.getAddress(); Inet6Address dstAddr = (Inet6Address)dst.getAddress();
if(srcAddr.isLinkLocalAddress() != dstAddr.isLinkLocalAddress()) if (srcAddr.isLinkLocalAddress() != dstAddr.isLinkLocalAddress())
{ {
//this one may actually work if for example we are contacting //this one may actually work if for example we are contacting
//the public address of someone in our local network. however //the public address of someone in our local network. however

View File

@ -176,7 +176,7 @@ abstract class AddressAttribute extends Attribute
return false; return false;
//addresses //addresses
if( att.getAddress() == null && getAddress() == null) if ( att.getAddress() == null && getAddress() == null)
return true; return true;
return true; return true;
@ -221,10 +221,12 @@ abstract class AddressAttribute extends Attribute
binValue[7] = (byte)(getPort() & 0x00FF); binValue[7] = (byte)(getPort() & 0x00FF);
//address //address
if(getFamily() == ADDRESS_FAMILY_IPV6){ if (getFamily() == ADDRESS_FAMILY_IPV6)
{
System.arraycopy(getAddressBytes(), 0, binValue, 8, 16); System.arraycopy(getAddressBytes(), 0, binValue, 8, 16);
} }
else{ else
{
System.arraycopy(getAddressBytes(), 0, binValue, 8, 4); System.arraycopy(getAddressBytes(), 0, binValue, 8, 4);
} }
@ -307,7 +309,7 @@ abstract class AddressAttribute extends Attribute
//address //address
byte address[] = null; byte address[] = null;
if(family == ADDRESS_FAMILY_IPV6) if (family == ADDRESS_FAMILY_IPV6)
{ {
address = new byte[16]; address = new byte[16];
} }

View File

@ -43,11 +43,11 @@ public class AttributeDecoder
* @throws StunException if bytes is not a valid STUN attribute. * @throws StunException if bytes is not a valid STUN attribute.
*/ */
public static Attribute decode(byte[] bytes, public static Attribute decode(byte[] bytes,
char offset, int offset,
char length) int length)
throws StunException throws StunException
{ {
if(bytes == null || bytes.length < Attribute.HEADER_LENGTH) if (bytes == null || bytes.length < Attribute.HEADER_LENGTH)
{ {
throw new StunException( StunException.ILLEGAL_ARGUMENT, throw new StunException( StunException.ILLEGAL_ARGUMENT,
"Could not decode the specified binary array."); "Could not decode the specified binary array.");
@ -59,7 +59,7 @@ public class AttributeDecoder
char attributeLength = (char) char attributeLength = (char)
(((bytes[offset + 2] & 0xFF) << 8) | (bytes[offset + 3] & 0xFF)); (((bytes[offset + 2] & 0xFF) << 8) | (bytes[offset + 3] & 0xFF));
if(attributeLength > bytes.length - offset ) if (attributeLength > bytes.length - offset )
throw new StunException( StunException.ILLEGAL_ARGUMENT, throw new StunException( StunException.ILLEGAL_ARGUMENT,
"Could not decode the specified binary array."); "Could not decode the specified binary array.");
@ -130,9 +130,9 @@ public class AttributeDecoder
case Attribute.USE_CANDIDATE: case Attribute.USE_CANDIDATE:
decodedAttribute = new UseCandidateAttribute(); break; decodedAttribute = new UseCandidateAttribute(); break;
case Attribute.REQUESTED_ADDRESS_FAMILY: case Attribute.REQUESTED_ADDRESS_FAMILY:
decodedAttribute = new RequestedAddressFamilyAttribute(); break; decodedAttribute = new RequestedAddressFamilyAttribute(); break;
case Attribute.CONNECTION_ID: case Attribute.CONNECTION_ID:
decodedAttribute = new ConnectionIdAttribute(); break; decodedAttribute = new ConnectionIdAttribute(); break;
//According to rfc3489 we should silently ignore unknown attributes. //According to rfc3489 we should silently ignore unknown attributes.
default: decodedAttribute default: decodedAttribute
= new OptionalAttribute( Attribute.UNKNOWN_OPTIONAL_ATTRIBUTE); = new OptionalAttribute( Attribute.UNKNOWN_OPTIONAL_ATTRIBUTE);

View File

@ -624,14 +624,14 @@ public class AttributeFactory
public static RequestedAddressFamilyAttribute public static RequestedAddressFamilyAttribute
createRequestedAddressFamilyAttribute(char family) createRequestedAddressFamilyAttribute(char family)
{ {
RequestedAddressFamilyAttribute attribute RequestedAddressFamilyAttribute attribute
= new RequestedAddressFamilyAttribute(); = new RequestedAddressFamilyAttribute();
boolean isSet = attribute.setFamily(family); boolean isSet = attribute.setFamily(family);
if(!isSet) if (!isSet)
{ {
attribute = null; attribute = null;
} }
return attribute; return attribute;
} }
@ -644,8 +644,8 @@ public class AttributeFactory
*/ */
public static ConnectionIdAttribute createConnectionIdAttribute( public static ConnectionIdAttribute createConnectionIdAttribute(
int connectionIdValue) int connectionIdValue)
{ {
ConnectionIdAttribute attribute = new ConnectionIdAttribute(); ConnectionIdAttribute attribute = new ConnectionIdAttribute();
attribute.setConnectionIdValue(connectionIdValue); attribute.setConnectionIdValue(connectionIdValue);

View File

@ -137,7 +137,7 @@ public class ChannelNumberAttribute extends Attribute
void decodeAttributeBody(byte[] attributeValue, char offset, char length) void decodeAttributeBody(byte[] attributeValue, char offset, char length)
throws StunException throws StunException
{ {
if(length != 4) if (length != 4)
{ {
throw new StunException("length invalid"); throw new StunException("length invalid");
} }
@ -172,7 +172,7 @@ public class ChannelNumberAttribute extends Attribute
*/ */
public static boolean isValidRange(char channelNo) public static boolean isValidRange(char channelNo)
{ {
if(channelNo >= 0x4000) if (channelNo >= 0x4000)
{ {
return true; return true;
} }

View File

@ -48,7 +48,7 @@ public class ConnectionIdAttribute
*/ */
protected ConnectionIdAttribute() protected ConnectionIdAttribute()
{ {
super(CONNECTION_ID); super(CONNECTION_ID);
} }
/** /**
@ -58,7 +58,7 @@ public class ConnectionIdAttribute
@Override @Override
public char getDataLength() public char getDataLength()
{ {
return DATA_LENGTH; return DATA_LENGTH;
} }
/** /**
@ -70,7 +70,7 @@ public class ConnectionIdAttribute
@Override @Override
public String getName() public String getName()
{ {
return NAME; return NAME;
} }
/** /**
@ -82,7 +82,7 @@ public class ConnectionIdAttribute
@Override @Override
public boolean equals(Object obj) public boolean equals(Object obj)
{ {
if (! (obj instanceof ConnectionIdAttribute)) if (! (obj instanceof ConnectionIdAttribute))
return false; return false;
if (obj == this) if (obj == this)
@ -106,7 +106,7 @@ public class ConnectionIdAttribute
@Override @Override
public byte[] encode() public byte[] encode()
{ {
byte binValue[] = new byte[HEADER_LENGTH + DATA_LENGTH]; byte binValue[] = new byte[HEADER_LENGTH + DATA_LENGTH];
//Type //Type
binValue[0] = (byte)(getAttributeType() >> 8); binValue[0] = (byte)(getAttributeType() >> 8);
@ -135,9 +135,9 @@ public class ConnectionIdAttribute
*/ */
@Override @Override
void decodeAttributeBody(byte[] attributeValue, char offset, char length) void decodeAttributeBody(byte[] attributeValue, char offset, char length)
throws StunException throws StunException
{ {
if(length != DATA_LENGTH) if (length != DATA_LENGTH)
{ {
throw new StunException("length invalid: " + length); throw new StunException("length invalid: " + length);
} }
@ -168,8 +168,8 @@ public class ConnectionIdAttribute
* @param connectionIdValue the connection Id value. * @param connectionIdValue the connection Id value.
*/ */
public void setConnectionIdValue(int connectionIdValue) public void setConnectionIdValue(int connectionIdValue)
{ {
this.connectionIdValue = connectionIdValue; this.connectionIdValue = connectionIdValue;
} }
} }

View File

@ -112,7 +112,7 @@ public class DontFragmentAttribute extends Attribute
void decodeAttributeBody(byte[] attributeValue, char offset, char length) void decodeAttributeBody(byte[] attributeValue, char offset, char length)
throws StunException throws StunException
{ {
if(length != 0) if (length != 0)
{ {
throw new StunException("length invalid"); throw new StunException("length invalid");
} }

View File

@ -288,7 +288,7 @@ public class ErrorCodeAttribute extends Attribute
public void setErrorClass(byte errorClass) public void setErrorClass(byte errorClass)
throws IllegalArgumentException throws IllegalArgumentException
{ {
if(errorClass < 0 || errorClass > 99) if (errorClass < 0 || errorClass > 99)
throw new IllegalArgumentException( throw new IllegalArgumentException(
errorClass + " is not a valid error number!"); errorClass + " is not a valid error number!");
this.errorClass = errorClass; this.errorClass = errorClass;
@ -415,7 +415,7 @@ public class ErrorCodeAttribute extends Attribute
*/ */
public String getReasonPhrase() public String getReasonPhrase()
{ {
if(reasonPhrase == null) if (reasonPhrase == null)
return null; return null;
return new String(reasonPhrase); return new String(reasonPhrase);
@ -472,7 +472,7 @@ public class ErrorCodeAttribute extends Attribute
binValue[6] = getErrorClass(); binValue[6] = getErrorClass();
binValue[7] = getErrorNumber(); binValue[7] = getErrorNumber();
if(reasonPhrase != null) if (reasonPhrase != null)
System.arraycopy(reasonPhrase, 0, binValue, 8, reasonPhrase.length); System.arraycopy(reasonPhrase, 0, binValue, 8, reasonPhrase.length);
return binValue; return binValue;

View File

@ -132,7 +132,7 @@ public class EvenPortAttribute extends Attribute
void decodeAttributeBody(byte[] attributeValue, char offset, char length) void decodeAttributeBody(byte[] attributeValue, char offset, char length)
throws StunException throws StunException
{ {
if(length != 4) if (length != 4)
{ {
throw new StunException("length invalid"); throw new StunException("length invalid");
} }

View File

@ -212,7 +212,7 @@ public class FingerprintAttribute
char length) char length)
throws StunException throws StunException
{ {
if(length != 4) if (length != 4)
{ {
throw new StunException("length invalid"); throw new StunException("length invalid");
} }

View File

@ -125,14 +125,14 @@ public abstract class IceControlAttribute
*/ */
public boolean equals(Object obj) public boolean equals(Object obj)
{ {
if(!(obj instanceof IceControlAttribute)) if (!(obj instanceof IceControlAttribute))
return false; return false;
if(obj == this) if (obj == this)
return true; return true;
IceControlAttribute iceControlAtt = (IceControlAttribute)obj; IceControlAttribute iceControlAtt = (IceControlAttribute)obj;
if(iceControlAtt.getAttributeType() != getAttributeType() if (iceControlAtt.getAttributeType() != getAttributeType()
|| iceControlAtt.isControlling != isControlling || iceControlAtt.isControlling != isControlling
|| iceControlAtt.getDataLength() != DATA_LENGTH_ICE_CONTROL || iceControlAtt.getDataLength() != DATA_LENGTH_ICE_CONTROL
|| getTieBreaker() != iceControlAtt.getTieBreaker()) || getTieBreaker() != iceControlAtt.getTieBreaker())

View File

@ -138,7 +138,7 @@ public class LifetimeAttribute
void decodeAttributeBody(byte[] attributeValue, char offset, char length) void decodeAttributeBody(byte[] attributeValue, char offset, char length)
throws StunException throws StunException
{ {
if(length != 4) if (length != 4)
{ {
throw new StunException("length invalid"); throw new StunException("length invalid");
} }

View File

@ -138,7 +138,7 @@ public class MagicCookieAttribute
void decodeAttributeBody(byte[] attributeValue, char offset, char length) void decodeAttributeBody(byte[] attributeValue, char offset, char length)
throws StunException throws StunException
{ {
if(length != 4) if (length != 4)
{ {
throw new StunException("length invalid"); throw new StunException("length invalid");
} }

View File

@ -308,12 +308,12 @@ public class MessageIntegrityAttribute
logger.warning("Can not encode a message of type Indication."); logger.warning("Can not encode a message of type Indication.");
} }
Objects.requireNonNull(key, "key=null; msgType=" + msgType); Objects.requireNonNull(key, "key=null; msgType=" + String.format("%04X", (int)msgType));
//now calculate the HMAC-SHA1 //now calculate the HMAC-SHA1
this.hmacSha1Content = calculateHmacSha1(content, offset, length, key); this.hmacSha1Content = calculateHmacSha1(content, offset, length, key);
//username //username
System.arraycopy(hmacSha1Content, 0, binValue, 4, getDataLength()); System.arraycopy(hmacSha1Content, 0, binValue, HEADER_LENGTH, getDataLength());
return binValue; return binValue;
} }

View File

@ -134,7 +134,7 @@ public class OptionalAttribute
*/ */
public boolean equals(Object obj) public boolean equals(Object obj)
{ {
if(! (obj instanceof OptionalAttribute) ) if (! (obj instanceof OptionalAttribute) )
return false; return false;
return return

View File

@ -174,7 +174,7 @@ public class PriorityAttribute
throws IllegalArgumentException throws IllegalArgumentException
{ {
/* Priority must be between 1 and (2^31 - 1) */ /* Priority must be between 1 and (2^31 - 1) */
if(priority <= 0 || priority > 0x7FFFFFFFL) if (priority <= 0 || priority > 0x7FFFFFFFL)
{ {
throw new IllegalArgumentException("Priority must be " + throw new IllegalArgumentException("Priority must be " +
"between 0 and (2**31 - 1)"); "between 0 and (2**31 - 1)");

View File

@ -56,7 +56,7 @@ public class RequestedAddressFamilyAttribute extends Attribute
*/ */
protected RequestedAddressFamilyAttribute() protected RequestedAddressFamilyAttribute()
{ {
super(REQUESTED_ADDRESS_FAMILY); super(REQUESTED_ADDRESS_FAMILY);
} }
/** /**
@ -66,7 +66,7 @@ public class RequestedAddressFamilyAttribute extends Attribute
@Override @Override
public char getDataLength() public char getDataLength()
{ {
return DATA_LENGTH; return DATA_LENGTH;
} }
/** /**
@ -78,7 +78,7 @@ public class RequestedAddressFamilyAttribute extends Attribute
@Override @Override
public String getName() public String getName()
{ {
return NAME; return NAME;
} }
/** /**
@ -90,7 +90,7 @@ public class RequestedAddressFamilyAttribute extends Attribute
@Override @Override
public boolean equals(Object obj) public boolean equals(Object obj)
{ {
if (! (obj instanceof RequestedAddressFamilyAttribute)) if (! (obj instanceof RequestedAddressFamilyAttribute))
return false; return false;
if (obj == this) if (obj == this)
@ -142,16 +142,16 @@ public class RequestedAddressFamilyAttribute extends Attribute
*/ */
@Override @Override
void decodeAttributeBody(byte[] attributeValue, char offset, char length) void decodeAttributeBody(byte[] attributeValue, char offset, char length)
throws StunException throws StunException
{ {
if(length != DATA_LENGTH) if (length != DATA_LENGTH)
{ {
throw new StunException("length invalid: " + length); throw new StunException("length invalid: " + length);
} }
family = (char)(attributeValue[offset] & 0xff); family = (char)(attributeValue[offset] & 0xff);
if(family != IPv4 && family != IPv6) if (family != IPv4 && family != IPv6)
{ {
// instead throw TurnException // instead throw TurnException
throw new StunException("invalid family value: " + family); throw new StunException("invalid family value: " + family);
@ -173,8 +173,8 @@ public class RequestedAddressFamilyAttribute extends Attribute
* @return true if argument is IPv4 or IPv6 otherwise false * @return true if argument is IPv4 or IPv6 otherwise false
*/ */
public boolean setFamily(char family) public boolean setFamily(char family)
{ {
if(family == IPv4 || family == IPv6) if (family == IPv4 || family == IPv6)
{ {
this.family = family; this.family = family;
return true; return true;

View File

@ -147,7 +147,7 @@ public class RequestedTransportAttribute extends Attribute
void decodeAttributeBody(byte[] attributeValue, char offset, char length) void decodeAttributeBody(byte[] attributeValue, char offset, char length)
throws StunException throws StunException
{ {
if(length != 4) if (length != 4)
{ {
throw new StunException("length invalid"); throw new StunException("length invalid");
} }

View File

@ -75,7 +75,7 @@ public class ReservationTokenAttribute
void decodeAttributeBody(byte[] attributeValue, char offset, char length) void decodeAttributeBody(byte[] attributeValue, char offset, char length)
throws StunException throws StunException
{ {
if(length != 8) if (length != 8)
{ {
throw new StunException("Length mismatch!"); throw new StunException("Length mismatch!");
} }
@ -189,12 +189,12 @@ public class ReservationTokenAttribute
private static void generateReservationTokenAttribute( private static void generateReservationTokenAttribute(
ReservationTokenAttribute token, int nb) ReservationTokenAttribute token, int nb)
{ {
long left = System.currentTimeMillis();// the first nb/2 bytes of the long left = System.currentTimeMillis(); // the first nb/2 bytes of the
// token // token
long right = random.nextLong();// the last nb/2 bytes of the token long right = random.nextLong(); // the last nb/2 bytes of the token
int b = nb / 2; int b = nb / 2;
for(int i = 0; i < b; i++) for (int i = 0; i < b; i++)
{ {
token.reservationToken[i] = (byte)((left >> (i * 8)) & 0xFFL); token.reservationToken[i] = (byte)((left >> (i * 8)) & 0xFFL);
token.reservationToken[i + b] = (byte)((right >> (i * 8)) & 0xFFL); token.reservationToken[i + b] = (byte)((right >> (i * 8)) & 0xFFL);

View File

@ -84,7 +84,7 @@ public class UnknownAttributesAttribute extends Attribute
{ {
char len = (char)unknownAttributes.size(); char len = (char)unknownAttributes.size();
if( (len % 2 ) != 0 ) if ( (len % 2 ) != 0 )
len++; len++;
return (char)(len * 2); return (char)(len * 2);
@ -99,7 +99,7 @@ public class UnknownAttributesAttribute extends Attribute
{ {
//some attributes may be repeated for padding //some attributes may be repeated for padding
//(packet length should be divisable by 4) //(packet length should be divisable by 4)
if(!contains(attributeID)) if (!contains(attributeID))
unknownAttributes.add(attributeID); unknownAttributes.add(attributeID);
} }
@ -172,7 +172,7 @@ public class UnknownAttributesAttribute extends Attribute
// If the number of unknown attributes is an odd number, one of the // If the number of unknown attributes is an odd number, one of the
// attributes MUST be repeated in the list, so that the total length of // attributes MUST be repeated in the list, so that the total length of
// the list is a multiple of 4 bytes. // the list is a multiple of 4 bytes.
if(offset < binValue.length) if (offset < binValue.length)
{ {
char att = getAttribute(0); char att = getAttribute(0);
binValue[offset++] = (byte) (att >> 8); binValue[offset++] = (byte) (att >> 8);
@ -221,12 +221,12 @@ public class UnknownAttributesAttribute extends Attribute
void decodeAttributeBody(byte[] attributeValue, char offset, char length) void decodeAttributeBody(byte[] attributeValue, char offset, char length)
throws StunException throws StunException
{ {
if( (length % 2 ) != 0) if ( (length % 2 ) != 0)
throw new StunException("Attribute IDs are 2 bytes long and the " throw new StunException("Attribute IDs are 2 bytes long and the "
+ "passed binary array has an odd length " + + "passed binary array has an odd length " +
"value."); "value.");
char originalOffset = offset; char originalOffset = offset;
for(int i = offset; i < originalOffset + length; i += 2) for (int i = offset; i < originalOffset + length; i += 2)
{ {
char attributeID = (char) (((attributeValue[offset++] & 0xFF) << 8) char attributeID = (char) (((attributeValue[offset++] & 0xFF) << 8)
| (attributeValue[offset++] & 0xFF)); | (attributeValue[offset++] & 0xFF));

View File

@ -89,14 +89,14 @@ public class UseCandidateAttribute
*/ */
public boolean equals(Object obj) public boolean equals(Object obj)
{ {
if(!(obj instanceof UseCandidateAttribute)) if (!(obj instanceof UseCandidateAttribute))
return false; return false;
if(obj == this) if (obj == this)
return true; return true;
UseCandidateAttribute useCandidateAtt = (UseCandidateAttribute)obj; UseCandidateAttribute useCandidateAtt = (UseCandidateAttribute)obj;
if(useCandidateAtt.getAttributeType() != getAttributeType() if (useCandidateAtt.getAttributeType() != getAttributeType()
|| useCandidateAtt.getDataLength() != getDataLength()) || useCandidateAtt.getDataLength() != getDataLength())
return false; return false;

View File

@ -102,7 +102,7 @@ public class XorMappedAddressAttribute
port ^= portModifier; port ^= portModifier;
for(int i = 0; i < addressBytes.length; i++) for (int i = 0; i < addressBytes.length; i++)
addressBytes[i] ^= transactionID[i]; addressBytes[i] ^= transactionID[i];
TransportAddress xoredAdd; TransportAddress xoredAdd;

View File

@ -17,6 +17,14 @@
*/ */
package org.ice4j.ice; package org.ice4j.ice;
import org.ice4j.*;
import org.ice4j.ice.harvest.*;
import org.ice4j.stack.*;
import org.ice4j.util.PeriodicRunnable;
import org.jitsi.utils.concurrent.*;
import org.jitsi.utils.logging2.Logger;
import org.jitsi.utils.logging2.*;
import java.beans.*; import java.beans.*;
import java.io.*; import java.io.*;
import java.math.*; import java.math.*;
@ -27,11 +35,7 @@ import java.util.*;
import java.util.concurrent.*; import java.util.concurrent.*;
import java.util.logging.*; import java.util.logging.*;
import org.ice4j.*; import static org.ice4j.ice.AgentConfig.config;
import org.ice4j.ice.harvest.*;
import org.ice4j.stack.*;
import org.ice4j.util.*;
import org.ice4j.util.Logger; // Disambiguation.
/** /**
* An <tt>Agent</tt> could be described as the main class (i.e. the chef * An <tt>Agent</tt> could be described as the main class (i.e. the chef
@ -56,42 +60,6 @@ import org.ice4j.util.Logger; // Disambiguation.
*/ */
public class Agent public class Agent
{ {
/**
* Default value for {@link StackProperties#CONSENT_FRESHNESS_INTERVAL}.
*/
private static final int DEFAULT_CONSENT_FRESHNESS_INTERVAL = 15000;
/**
* Default value for
* {@link StackProperties#CONSENT_FRESHNESS_MAX_RETRANSMISSIONS}.
*/
private static final int DEFAULT_CONSENT_FRESHNESS_MAX_RETRANSMISSIONS = 30;
/**
* Default value for
* {@link StackProperties#CONSENT_FRESHNESS_MAX_WAIT_INTERVAL}.
*/
private static final int DEFAULT_CONSENT_FRESHNESS_MAX_WAIT_INTERVAL = 500;
/**
* Default value for
* {@link StackProperties#CONSENT_FRESHNESS_ORIGINAL_WAIT_INTERVAL}.
*/
private static final int DEFAULT_CONSENT_FRESHNESS_ORIGINAL_WAIT_INTERVAL
= 500;
/**
* The default maximum size for check lists.
*/
public static final int DEFAULT_MAX_CHECK_LIST_SIZE = 100;
/**
* The default number of milliseconds we should wait before moving from
* {@link IceProcessingState#COMPLETED} into {@link
* IceProcessingState#TERMINATED}.
*/
public static final int DEFAULT_TERMINATION_DELAY = 3000;
/** /**
* The constant which defines an empty array with element type * The constant which defines an empty array with element type
* <tt>PropertyChangeListener</tt> and represents the fact that there are no * <tt>PropertyChangeListener</tt> and represents the fact that there are no
@ -101,15 +69,6 @@ public class Agent
private static final PropertyChangeListener[] NO_STATE_CHANGE_LISTENERS private static final PropertyChangeListener[] NO_STATE_CHANGE_LISTENERS
= new PropertyChangeListener[0]; = new PropertyChangeListener[0];
/**
* The {@link Logger} used by the {@link Agent} class for logging output.
* Note that this shouldn't be used directly by instances of {@link Agent},
* because it doesn't take into account the per-instance log level.
* Instances should use {@link #logger} instead.
*/
private static final java.util.logging.Logger classLogger
= java.util.logging.Logger.getLogger(Agent.class.getName());
/** /**
* The name of the {@link PropertyChangeEvent} that we use to deliver * The name of the {@link PropertyChangeEvent} that we use to deliver
* events on changes in the state of ICE processing in this agent. * events on changes in the state of ICE processing in this agent.
@ -240,7 +199,7 @@ public class Agent
private long tieBreaker; private long tieBreaker;
/** /**
* Determines whether this is the controlling agent in a an ICE interaction. * Determines whether this agent has a controlling role in an ICE interaction.
*/ */
private boolean isControlling = true; private boolean isControlling = true;
@ -327,23 +286,27 @@ public class Agent
*/ */
private boolean performConsentFreshness = false; private boolean performConsentFreshness = false;
/**
* The flag which specifies whether {@link #hostCandidateHarvester} should
* be used or not.
*/
private Boolean useHostHarvester = null;
/** /**
* The {@link Logger} used by {@link Agent} instances. * The {@link Logger} used by {@link Agent} instances.
*/ */
private final Logger logger; private final Logger logger;
/**
* Whether this {@link Agent} should use dynamic ports. Can be overridden via {@link #setUseDynamicPorts(boolean)}.
*/
private boolean useDynamicPorts = HarvestConfig.config.useDynamicPorts();
/** /**
* Creates an empty <tt>Agent</tt> with no streams, and no address. * Creates an empty <tt>Agent</tt> with no streams, and no address.
*/ */
public Agent() public Agent()
{ {
this(Level.INFO, null); this(null, null);
}
public Agent(Logger parentLogger)
{
this(null, parentLogger);
} }
/** /**
@ -351,33 +314,27 @@ public class Agent
* @param ufragPrefix an optional prefix to the generated local ICE username * @param ufragPrefix an optional prefix to the generated local ICE username
* fragment. * fragment.
*/ */
public Agent(String ufragPrefix) public Agent(String ufragPrefix, Logger parentLogger)
{ {
this(Level.INFO, ufragPrefix);
}
/**
* Creates an empty <tt>Agent</tt> with no streams, and no address.
* @param loggingLevel the logging level to be used by the agent and all of
* its components.
*/
public Agent(Level loggingLevel)
{
this(loggingLevel, null);
}
/**
* Creates an empty <tt>Agent</tt> with no streams, and no address.
* @param loggingLevel the logging level to be used by the agent and all of
* its components.
* @param ufragPrefix an optional prefix to the generated local ICE username
* fragment.
*/
public Agent(Level loggingLevel, String ufragPrefix)
{
logger = new Logger(classLogger, loggingLevel);
SecureRandom random = new SecureRandom(); SecureRandom random = new SecureRandom();
String ufrag = ufragPrefix == null ? "" : ufragPrefix;
ufrag += new BigInteger(24, random).toString(32);
ufrag += BigInteger.valueOf(System.currentTimeMillis()).toString(32);
ufrag = ensureIceAttributeLength(ufrag, /* min */ 4, /* max */ 256);
this.ufrag = ufrag;
if (parentLogger != null)
{
logger = parentLogger.createChildLogger(
this.getClass().getName(),
Collections.singletonMap("ufrag", this.ufrag));
}
else
{
logger = new LoggerImpl(Agent.class.getName(), new LogContext("ufrag", this.ufrag));
}
connCheckServer = new ConnectivityCheckServer(this); connCheckServer = new ConnectivityCheckServer(this);
connCheckClient = new ConnectivityCheckClient( connCheckClient = new ConnectivityCheckClient(
this, agentTasksScheduler, agentTasksExecutor); this, agentTasksScheduler, agentTasksExecutor);
@ -385,16 +342,6 @@ public class Agent
//add the FINGERPRINT attribute to all messages. //add the FINGERPRINT attribute to all messages.
System.setProperty(StackProperties.ALWAYS_SIGN, "true"); System.setProperty(StackProperties.ALWAYS_SIGN, "true");
//add the software attribute to all messages
if (StackProperties.getString(StackProperties.SOFTWARE) == null)
System.setProperty(StackProperties.SOFTWARE, "ice4j.org");
String ufrag = ufragPrefix == null ? "" : ufragPrefix;
ufrag += new BigInteger(24, random).toString(32);
ufrag += BigInteger.valueOf(System.currentTimeMillis()).toString(32);
ufrag = ensureIceAttributeLength(ufrag, /* min */ 4, /* max */ 256);
this.ufrag = ufrag;
password password
= ensureIceAttributeLength( = ensureIceAttributeLength(
new BigInteger(128, random).toString(32), new BigInteger(128, random).toString(32),
@ -409,10 +356,8 @@ public class Agent
addCandidateHarvester(harvester); addCandidateHarvester(harvester);
} }
if (logger.isLoggable(Level.FINE)) logger.debug(() -> "Created a new Agent: " + this.toString() +
{ " with ICE controlling role = " + this.isControlling);
logger.fine("Created a new Agent, ufrag=" + ufrag);
}
} }
/** /**
@ -434,7 +379,7 @@ public class Agent
*/ */
public IceMediaStream createMediaStream(String mediaStreamName) public IceMediaStream createMediaStream(String mediaStreamName)
{ {
logger.debug("Create media stream for " + mediaStreamName); logger.debug(() -> "Create media stream for " + mediaStreamName);
IceMediaStream mediaStream IceMediaStream mediaStream
= new IceMediaStream(Agent.this, mediaStreamName); = new IceMediaStream(Agent.this, mediaStreamName);
@ -458,7 +403,6 @@ public class Agent
* *
* @param stream the {@link IceMediaStream} that the new {@link Component} * @param stream the {@link IceMediaStream} that the new {@link Component}
* should belong to. * should belong to.
* @param transport the transport protocol used by the component
* @param preferredPort the port number that should be tried first when * @param preferredPort the port number that should be tried first when
* binding local <tt>Candidate</tt> sockets for this <tt>Component</tt>. * binding local <tt>Candidate</tt> sockets for this <tt>Component</tt>.
* @param minPort the port number where we should first try to bind before * @param minPort the port number where we should first try to bind before
@ -478,21 +422,20 @@ public class Agent
* <tt>minPort</tt> and <tt>maxPort</tt> before reaching the maximum allowed * <tt>minPort</tt> and <tt>maxPort</tt> before reaching the maximum allowed
* number of retries. * number of retries.
*/ */
public Component createComponent( IceMediaStream stream, public Component createComponent(
Transport transport, IceMediaStream stream,
int preferredPort, int preferredPort,
int minPort, int minPort,
int maxPort) int maxPort)
throws IllegalArgumentException, throws IllegalArgumentException,
IOException, IOException,
BindException BindException
{ {
return createComponent( return createComponent(
stream, transport, stream,
preferredPort, minPort, maxPort, preferredPort, minPort, maxPort,
KeepAliveStrategy.SELECTED_ONLY, KeepAliveStrategy.SELECTED_ONLY,
StackProperties.getBoolean( config.getUseComponentSocket());
StackProperties.USE_COMPONENT_SOCKET, true));
} }
/** /**
@ -501,7 +444,6 @@ public class Agent
* *
* @param stream the {@link IceMediaStream} that the new {@link Component} * @param stream the {@link IceMediaStream} that the new {@link Component}
* should belong to. * should belong to.
* @param transport the transport protocol used by the component
* @param preferredPort the port number that should be tried first when * @param preferredPort the port number that should be tried first when
* binding local <tt>Candidate</tt> sockets for this <tt>Component</tt>. * binding local <tt>Candidate</tt> sockets for this <tt>Component</tt>.
* @param minPort the port number where we should first try to bind before * @param minPort the port number where we should first try to bind before
@ -525,7 +467,6 @@ public class Agent
*/ */
public Component createComponent( public Component createComponent(
IceMediaStream stream, IceMediaStream stream,
Transport transport,
int preferredPort, int preferredPort,
int minPort, int minPort,
int maxPort, int maxPort,
@ -536,7 +477,6 @@ public class Agent
{ {
return createComponent( return createComponent(
stream, stream,
transport,
preferredPort, preferredPort,
minPort, minPort,
maxPort, maxPort,
@ -548,9 +488,10 @@ public class Agent
* Creates a new {@link Component} for the specified <tt>stream</tt> and * Creates a new {@link Component} for the specified <tt>stream</tt> and
* allocates potentially all local candidates that should belong to it. * allocates potentially all local candidates that should belong to it.
* *
* If 0, 0, 0 are specified for preferred, min and max port, an ephemeral port will be used instead.
*
* @param stream the {@link IceMediaStream} that the new {@link Component} * @param stream the {@link IceMediaStream} that the new {@link Component}
* should belong to. * should belong to.
* @param transport the transport protocol used by the component
* @param preferredPort the port number that should be tried first when * @param preferredPort the port number that should be tried first when
* binding local <tt>Candidate</tt> sockets for this <tt>Component</tt>. * binding local <tt>Candidate</tt> sockets for this <tt>Component</tt>.
* @param minPort the port number where we should first try to bind before * @param minPort the port number where we should first try to bind before
@ -578,7 +519,6 @@ public class Agent
*/ */
public Component createComponent( public Component createComponent(
IceMediaStream stream, IceMediaStream stream,
Transport transport,
int preferredPort, int preferredPort,
int minPort, int minPort,
int maxPort, int maxPort,
@ -588,15 +528,7 @@ public class Agent
IOException, IOException,
BindException BindException
{ {
if (transport != Transport.UDP) Component component = stream.createComponent(keepAliveStrategy, useComponentSocket);
{
throw new IllegalArgumentException(
"This implementation does not currently support transport: "
+ transport);
}
Component component
= stream.createComponent(keepAliveStrategy, useComponentSocket);
gatherCandidates(component, preferredPort, minPort, maxPort); gatherCandidates(component, preferredPort, minPort, maxPort);
@ -615,6 +547,31 @@ public class Agent
return component; return component;
} }
/**
* Creates a new {@link Component} for the specified {@code stream} and allocates potentially all local
* candidates that should belong to it.
*
* If dynamic ports are enabled, an ephemeral port will be used.
*
* @param stream the {@link IceMediaStream} that the new {@link Component} should belong to.
* @param keepAliveStrategy the keep-alive strategy, which dictates which
* candidates pairs are going to be kept alive.
* @param useComponentSocket whether to use the component socket mode (in
* which case the socket is available through the {@link Component} directly),
* or not (in which case the socket is available through the selected {@link CandidatePair}).
*
* @return the newly created {@link Component} and with a list containing all and only local candidates.
* @throws IOException if an error occurs while the underlying resolver lib is using sockets.
*/
public Component createComponent(
IceMediaStream stream,
KeepAliveStrategy keepAliveStrategy,
boolean useComponentSocket)
throws IllegalArgumentException, IOException
{
return createComponent(stream, 0, 0, 0, keepAliveStrategy, useComponentSocket);
}
/** /**
* Initializes a new {@link CandidatePair} instance from a * Initializes a new {@link CandidatePair} instance from a
* {@link LocalCandidate} and a {@link RemoteCandidate}. The method * {@link LocalCandidate} and a {@link RemoteCandidate}. The method
@ -637,6 +594,14 @@ public class Agent
return new CandidatePair(local, remote); return new CandidatePair(local, remote);
} }
/**
* Sets the flag for whether this {@link Agent} instance should use dynamic ports.
*/
public void setUseDynamicPorts(boolean value)
{
useDynamicPorts = value;
}
/** /**
* Uses all <tt>CandidateHarvester</tt>s currently registered with this * Uses all <tt>CandidateHarvester</tt>s currently registered with this
* <tt>Agent</tt> to obtain whatever addresses they can discover. * <tt>Agent</tt> to obtain whatever addresses they can discover.
@ -645,6 +610,8 @@ public class Agent
* you've registered all harvesters that you would want to use before * you've registered all harvesters that you would want to use before
* calling it. * calling it.
* </p> * </p>
* If 0, 0, 0 are specified for preferred, min and max port, an ephemeral port will be used instead.
*
* @param component the <tt>Component</tt> that we'd like to gather * @param component the <tt>Component</tt> that we'd like to gather
* candidates for. * candidates for.
* @param preferredPort the port number that should be tried first when * @param preferredPort the port number that should be tried first when
@ -668,18 +635,16 @@ public class Agent
IOException IOException
{ {
logger.info("Gathering candidates for component " + logger.info("Gathering candidates for component " +
component.toShortString() +". Local ufrag " + getLocalUfrag()); component.toShortString() +".");
if (useHostHarvester()) if (useDynamicPorts)
{ {
hostCandidateHarvester.harvest( hostCandidateHarvester.harvest(component, preferredPort, minPort, maxPort, Transport.UDP);
component,
preferredPort, minPort, maxPort, Transport.UDP);
} }
else else
{ {
if (hostHarvesters.isEmpty()) if (hostHarvesters.isEmpty())
logger.warning("No host harvesters available!"); logger.warn("No host harvesters available!");
} }
for (CandidateHarvester harvester : hostHarvesters) for (CandidateHarvester harvester : hostHarvesters)
@ -688,7 +653,7 @@ public class Agent
} }
if (component.getLocalCandidateCount() == 0) if (component.getLocalCandidateCount() == 0)
logger.warning("Failed to gather any host candidates!"); logger.warn("Failed to gather any host candidates!");
//in case we are not trickling, apply other harvesters here //in case we are not trickling, apply other harvesters here
if (!isTrickling()) if (!isTrickling())
@ -697,7 +662,7 @@ public class Agent
harvesters.harvest(component); harvesters.harvest(component);
} }
logger.fine("Candidate count in first harvest: " + logger.debug(() -> "Candidate count in first harvest: " +
component.getLocalCandidateCount()); component.getLocalCandidateCount());
// Emil: Because of trickle, we now assign foundations, compute // Emil: Because of trickle, we now assign foundations, compute
@ -733,7 +698,7 @@ public class Agent
if (harvestingStarted) if (harvestingStarted)
{ {
logger.warning( logger.warn(
"Hmmm ... why are you harvesting twice? You shouldn't be!"); "Hmmm ... why are you harvesting twice? You shouldn't be!");
} }
@ -758,8 +723,7 @@ public class Agent
{ {
synchronized(startLock) synchronized(startLock)
{ {
logger.info("Start ICE connectivity establishment. Local ufrag " logger.info("Start ICE connectivity establishment.");
+ getLocalUfrag());
shutdown = false; shutdown = false;
pruneNonMatchedStreams(); pruneNonMatchedStreams();
@ -970,7 +934,7 @@ public class Agent
if (!oldState.equals(newState)) if (!oldState.equals(newState))
{ {
logger.info("ICE state changed from " + oldState + " to " logger.info("ICE state changed from " + oldState + " to "
+ newState + ". Local ufrag " + getLocalUfrag()); + newState + ".");
fireStateChange(oldState, newState); fireStateChange(oldState, newState);
return true; return true;
@ -985,31 +949,24 @@ public class Agent
*/ */
protected void initCheckLists() protected void initCheckLists()
{ {
//first init the check list. // First init the check list.
List<IceMediaStream> streams List<IceMediaStream> streams = getStreamsWithPendingConnectivityEstablishment();
= getStreamsWithPendingConnectivityEstablishment();
int streamCount = streams.size(); int streamCount = streams.size();
//init the maximum number of check list entries per stream.
int maxCheckListSize = Integer.getInteger(
StackProperties.MAX_CHECK_LIST_SIZE,
DEFAULT_MAX_CHECK_LIST_SIZE);
int maxPerStreamSize =
streamCount == 0
? 0
: maxCheckListSize / streamCount;
for (IceMediaStream stream : streams)
{
logger.info("Init checklist for stream " + stream.getName());
stream.setMaxCheckListSize(maxPerStreamSize);
stream.initCheckList();
}
//init the states of the first media stream as per 5245
if (streamCount > 0) if (streamCount > 0)
{
int maxCheckListSizePerStream = config.getMaxCheckListSize() / streamCount;
for (IceMediaStream stream : streams)
{
logger.info("Init checklist for stream " + stream.getName());
stream.setMaxCheckListSize(maxCheckListSizePerStream);
stream.initCheckList();
}
// Init the states of the first media stream as per 5245
streams.get(0).getCheckList().computeInitialCheckListPairStates(); streams.get(0).getCheckList().computeInitialCheckListPairStates();
}
} }
/** /**
@ -1102,7 +1059,7 @@ public class Agent
if (stream == null) if (stream == null)
{ {
ret = null; ret = null;
logger.warning( logger.warn(
"Agent contains no IceMediaStream with name " + media "Agent contains no IceMediaStream with name " + media
+ "!"); + "!");
} }
@ -1113,7 +1070,7 @@ public class Agent
if (remoteUfrag == null) if (remoteUfrag == null)
{ {
ret = null; ret = null;
logger.warning( logger.warn(
"Remote ufrag of IceMediaStream with name " + media "Remote ufrag of IceMediaStream with name " + media
+ " is null!"); + " is null!");
} }
@ -1417,6 +1374,13 @@ public class Agent
*/ */
public void setControlling(boolean isControlling) public void setControlling(boolean isControlling)
{ {
if (this.isControlling != isControlling)
{
this.logger.info(() -> "Changing agent " + this.toString() +
" role from controlling = " + this.isControlling +
" to controlling = " + isControlling);
}
this.isControlling = isControlling; this.isControlling = isControlling;
//in case we have already initialized our check lists we'd need to //in case we have already initialized our check lists we'd need to
@ -1468,57 +1432,45 @@ public class Agent
/** /**
* Returns the local <tt>LocalCandidate</tt> with the specified * Returns the local <tt>LocalCandidate</tt> with the specified
* <tt>localAddress</tt> if it belongs to any of this {@link Agent}'s * <tt>address</tt> if it belongs to any of this {@link Agent}'s
* streams or <tt>null</tt> if it doesn't. * streams or <tt>null</tt> if it doesn't.
* *
* @param localAddress the {@link TransportAddress} we are looking for. * @param address the {@link TransportAddress} we are looking for.
* *
* @return the local <tt>LocalCandidate</tt> with the specified * @return the local <tt>LocalCandidate</tt> with the specified
* <tt>localAddress</tt> if it belongs to any of this {@link Agent}'s * <tt>address</tt> if it belongs to any of this {@link Agent}'s
* streams or <tt>null</tt> if it doesn't. * streams or <tt>null</tt> if it doesn't.
*/ */
public LocalCandidate findLocalCandidate(TransportAddress localAddress) public LocalCandidate findLocalCandidate(TransportAddress address)
{ {
for (IceMediaStream stream : mediaStreams.values()) return findLocalCandidate(address, null);
{
LocalCandidate cnd = stream.findLocalCandidate(localAddress);
if (cnd != null)
{
return cnd;
}
}
return null;
} }
/** /**
* Returns the local <tt>LocalCandidate</tt> with the specified * Returns the local <tt>LocalCandidate</tt> with the specified
* <tt>localAddress</tt> if it belongs to any of this {@link Agent}'s * <tt>address</tt> if it belongs to any of this {@link Agent}'s
* streams or <tt>null</tt> if it doesn't. * streams or <tt>null</tt> if it doesn't. If {@code base} is also specified,
* tries to find a candidate whose base matches {@code base}.
*
* @param address the {@link TransportAddress} we are looking for.
* @param base an optional base to match.
* *
* @param localAddress the {@link TransportAddress} we are looking for.
* @param ufrag local ufrag
* @return the local <tt>LocalCandidate</tt> with the specified * @return the local <tt>LocalCandidate</tt> with the specified
* <tt>localAddress</tt> if it belongs to any of this {@link Agent}'s * <tt>address</tt> if it belongs to any of this {@link Agent}'s
* streams or <tt>null</tt> if it doesn't. * streams or <tt>null</tt> if it doesn't.
*/ */
public LocalCandidate findLocalCandidate( public LocalCandidate findLocalCandidate(
TransportAddress localAddress, TransportAddress address,
String ufrag) LocalCandidate base)
{ {
for (IceMediaStream stream : mediaStreams.values()) for (IceMediaStream stream : mediaStreams.values())
{ {
for (Component c : stream.getComponents()) LocalCandidate localCandidate
= stream.findLocalCandidate(address, base);
if (localCandidate != null)
{ {
for (LocalCandidate cnd : c.getLocalCandidates()) return localCandidate;
{
if (cnd != null
&& cnd.getUfrag() != null
&& cnd.getUfrag().equals(ufrag))
{
return cnd;
}
}
} }
} }
return null; return null;
@ -1660,7 +1612,7 @@ public class Agent
CandidatePair triggeredPair CandidatePair triggeredPair
= createCandidatePair(localCandidate, remoteCandidate); = createCandidatePair(localCandidate, remoteCandidate);
logger.fine("set use-candidate " + useCandidate + " for pair " + logger.debug(() -> "set use-candidate " + useCandidate + " for pair " +
triggeredPair.toShortString()); triggeredPair.toShortString());
if (useCandidate) if (useCandidate)
{ {
@ -1671,7 +1623,7 @@ public class Agent
{ {
if (state == IceProcessingState.WAITING) if (state == IceProcessingState.WAITING)
{ {
logger.fine("Receive STUN checks before our ICE has started"); logger.debug(() -> "Receive STUN checks before our ICE has started");
//we are not started yet so we'd better wait until we get the //we are not started yet so we'd better wait until we get the
//remote candidates in case we are holding to a new PR one. //remote candidates in case we are holding to a new PR one.
this.preDiscoveredPairsQueue.add(triggeredPair); this.preDiscoveredPairsQueue.add(triggeredPair);
@ -1682,12 +1634,8 @@ public class Agent
} }
else //Running, Connected or Terminated. else //Running, Connected or Terminated.
{ {
if (logger.isLoggable(Level.FINE)) logger.debug(() -> "Received check from "
{ + triggeredPair.toShortString() + " triggered a check.");
logger.debug("Received check from "
+ triggeredPair.toShortString() + " triggered a check. "
+ "Local ufrag " + getLocalUfrag());
}
// We have been started, and have not failed (yet). If this is // We have been started, and have not failed (yet). If this is
// a new pair, handle it (even if we have already completed). // a new pair, handle it (even if we have already completed).
@ -1735,7 +1683,7 @@ public class Agent
//7.2.1.5. Updating the Nominated Flag //7.2.1.5. Updating the Nominated Flag
if (!isControlling() && useCand) if (!isControlling() && useCand)
{ {
logger.fine("update nominated flag"); logger.debug(() -> "update nominated flag");
// If the Binding request received by the agent had the // If the Binding request received by the agent had the
// USE-CANDIDATE attribute set, and the agent is in the // USE-CANDIDATE attribute set, and the agent is in the
// controlled role, the agent looks at the state of the // controlled role, the agent looks at the state of the
@ -1855,6 +1803,18 @@ public class Agent
} }
} }
/**
* Returns the {@link NominationStrategy} that we use in order to
* decide if and when we should nominate valid pairs.
*
* @return the strategy that we are using for nominating
* valid {@link CandidatePair}s.
*/
public NominationStrategy getNominationStrategy()
{
return this.nominator.getStrategy();
}
/** /**
* Specifies the {@link NominationStrategy} that we should use in order to * Specifies the {@link NominationStrategy} that we should use in order to
* decide if and when we should nominate valid pairs. * decide if and when we should nominate valid pairs.
@ -1943,7 +1903,7 @@ public class Agent
if (!atLeastOneListSucceeded) if (!atLeastOneListSucceeded)
{ {
//all lists ended but none succeeded. No love today ;( //all lists ended but none succeeded. No love today ;(
if (logger.isLoggable(Level.INFO)) if (logger.isInfoEnabled())
{ {
if (connCheckClient.isAlive() if (connCheckClient.isAlive()
|| connCheckServer.isAlive()) || connCheckServer.isAlive())
@ -2003,8 +1963,7 @@ public class Agent
StringBuffer buf StringBuffer buf
= new StringBuffer( "Harvester used for selected pair for "); = new StringBuffer( "Harvester used for selected pair for ");
buf.append(component.toShortString()); buf.append(component.toShortString());
buf.append(" (local ufrag ").append(getLocalUfrag()); buf.append(": ");
buf.append("): ");
if (selectedPair == null) if (selectedPair == null)
{ {
@ -2197,10 +2156,7 @@ public class Agent
{ {
if (terminationFuture == null) if (terminationFuture == null)
{ {
long terminationDelay long terminationDelay = config.getTerminationDelay().toMillis();
= Integer.getInteger(
StackProperties.TERMINATION_DELAY,
DEFAULT_TERMINATION_DELAY);
if (terminationDelay > 0) if (terminationDelay > 0)
{ {
@ -2344,7 +2300,7 @@ public class Agent
*/ */
public void free() public void free()
{ {
logger.fine("Free ICE agent"); logger.debug(() -> "Free ICE agent");
shutdown = true; shutdown = true;
@ -2377,20 +2333,23 @@ public class Agent
terminate(IceProcessingState.TERMINATED); terminate(IceProcessingState.TERMINATED);
} }
/* Stop all outstanding transactions */
getStunStack().shutDown();
// Free its IceMediaStreams, Components and Candidates. // Free its IceMediaStreams, Components and Candidates.
boolean interrupted = false; boolean interrupted = false;
logger.fine("remove streams"); logger.debug(() -> "remove streams");
for (IceMediaStream stream : getStreams()) for (IceMediaStream stream : getStreams())
{ {
try try
{ {
removeStream(stream); removeStream(stream);
logger.fine("remove stream " + stream.getName()); logger.debug("remove stream " + stream.getName());
} }
catch (Throwable t) catch (Throwable t)
{ {
logger.fine( logger.debug(() ->
"remove stream " + stream.getName() + " failed: " + t); "remove stream " + stream.getName() + " failed: " + t);
if (t instanceof InterruptedException) if (t instanceof InterruptedException)
interrupted = true; interrupted = true;
@ -2401,9 +2360,7 @@ public class Agent
if (interrupted) if (interrupted)
Thread.currentThread().interrupt(); Thread.currentThread().interrupt();
getStunStack().shutDown(); logger.debug(() -> "ICE agent freed");
logger.fine("ICE agent freed");
} }
/** /**
@ -2638,34 +2595,6 @@ public class Agent
this.performConsentFreshness = performConsentFreshness; this.performConsentFreshness = performConsentFreshness;
} }
/**
* Checks whether the dynamic host harvester should be used or not.
* @return <tt>true</tt> if the dynamic host harvester should be used and
* <tt>false</tt> otherwise.
*/
public boolean useHostHarvester()
{
if (useHostHarvester == null)
{
useHostHarvester
= StackProperties.getBoolean(
StackProperties.USE_DYNAMIC_HOST_HARVESTER,
true);
}
return useHostHarvester;
}
/**
* Sets the flag which indicates whether the dynamic host harvester will
* be used or not by this <tt>Agent</tt>.
* @param useHostHarvester the value to set.
*/
public void setUseHostHarvester(boolean useHostHarvester)
{
this.useHostHarvester = useHostHarvester;
}
/** /**
* Sets the logging level for this {@link Agent} and its components. * Sets the logging level for this {@link Agent} and its components.
* @param level the level to set. * @param level the level to set.
@ -2696,21 +2625,14 @@ public class Agent
*/ */
private final class StunKeepAliveRunner extends PeriodicRunnable private final class StunKeepAliveRunner extends PeriodicRunnable
{ {
private final long consentFreshnessInterval = Long.getLong( private final long consentFreshnessInterval = config.getConsentFreshnessInterval().toMillis();
StackProperties.CONSENT_FRESHNESS_INTERVAL, private final int originalConsentFreshnessWaitInterval
DEFAULT_CONSENT_FRESHNESS_INTERVAL); = (int) config.getConsentFreshnessOriginalWaitInterval().toMillis();
private final int originalConsentFreshnessWaitInterval = Integer.getInteger( private final int maxConsentFreshnessWaitInterval
StackProperties.CONSENT_FRESHNESS_ORIGINAL_WAIT_INTERVAL, = (int) config.getConsentFreshnessMaxWaitInterval().toMillis();
DEFAULT_CONSENT_FRESHNESS_ORIGINAL_WAIT_INTERVAL);
private final int maxConsentFreshnessWaitInterval = Integer.getInteger( private final int consentFreshnessMaxRetransmissions = config.getMaxConsentFreshnessRetransmissions();
StackProperties.CONSENT_FRESHNESS_MAX_WAIT_INTERVAL,
DEFAULT_CONSENT_FRESHNESS_MAX_WAIT_INTERVAL);
private final int consentFreshnessMaxRetransmissions = Integer.getInteger(
StackProperties.CONSENT_FRESHNESS_MAX_RETRANSMISSIONS,
DEFAULT_CONSENT_FRESHNESS_MAX_RETRANSMISSIONS);
private int keepAliveSent = 0; private int keepAliveSent = 0;
@ -2724,7 +2646,19 @@ public class Agent
{ {
if (shouldRunStunKeepAlive()) if (shouldRunStunKeepAlive())
{ {
return Duration.ofMillis(keepAliveSent == 0 ? 0 : consentFreshnessInterval); if (keepAliveSent == 0)
{
return Duration.ZERO;
}
else
{
double r = 1;
if (config.getRandomizeConsentFreshnessInterval())
{
r = 0.8d + ThreadLocalRandom.current().nextDouble() * 0.4;
}
return Duration.ofMillis((long) (consentFreshnessInterval * r));
}
} }
return Duration.ofMillis(-1); return Duration.ofMillis(-1);
} }
@ -2738,7 +2672,7 @@ public class Agent
} }
catch (Exception e) catch (Exception e)
{ {
logger.log(Level.WARNING, "Error while sending keep alive", e); logger.warn("Error while sending keep alive", e);
} }
} }

View File

@ -438,17 +438,17 @@ public abstract class Candidate<T extends Candidate<?>>
/* Google Talk priority is in range 0 - 1, we multiply this by 1000 /* Google Talk priority is in range 0 - 1, we multiply this by 1000
* to have a long rather than float * to have a long rather than float
*/ */
if(candidateType == CandidateType.HOST_CANDIDATE) if (candidateType == CandidateType.HOST_CANDIDATE)
{ {
priority += 0.95 * 1000 - priority += 0.95 * 1000 -
(this.getBase().getTransport() == Transport.TCP ? 200 : 0); (this.getBase().getTransport() == Transport.TCP ? 200 : 0);
} }
else if(candidateType == CandidateType.PEER_REFLEXIVE_CANDIDATE) else if (candidateType == CandidateType.PEER_REFLEXIVE_CANDIDATE)
{ {
priority += (long)(0.9 * 1000) - priority += (long)(0.9 * 1000) -
(this.getBase().getTransport() == Transport.TCP ? 200 : 0); (this.getBase().getTransport() == Transport.TCP ? 200 : 0);
} }
else if(candidateType == CandidateType.SERVER_REFLEXIVE_CANDIDATE) else if (candidateType == CandidateType.SERVER_REFLEXIVE_CANDIDATE)
{ {
priority += (long)(0.9 * 1000); priority += (long)(0.9 * 1000);
} }
@ -462,9 +462,9 @@ public abstract class Candidate<T extends Candidate<?>>
InetAddress addr = getTransportAddress().getAddress(); InetAddress addr = getTransportAddress().getAddress();
// IPv6 has better priority than IPv4 // IPv6 has better priority than IPv4
if(addr instanceof Inet6Address) if (addr instanceof Inet6Address)
{ {
if(addr.isLinkLocalAddress()) if (addr.isLinkLocalAddress())
{ {
priority += 40; priority += 40;
} }
@ -499,15 +499,15 @@ public abstract class Candidate<T extends Candidate<?>>
{ {
int typePreference; int typePreference;
if(candidateType == CandidateType.HOST_CANDIDATE) if (candidateType == CandidateType.HOST_CANDIDATE)
{ {
typePreference = MAX_TYPE_PREFERENCE; // 126 typePreference = MAX_TYPE_PREFERENCE; // 126
} }
else if(candidateType == CandidateType.PEER_REFLEXIVE_CANDIDATE) else if (candidateType == CandidateType.PEER_REFLEXIVE_CANDIDATE)
{ {
typePreference = 110; typePreference = 110;
} }
else if(candidateType == CandidateType.SERVER_REFLEXIVE_CANDIDATE) else if (candidateType == CandidateType.SERVER_REFLEXIVE_CANDIDATE)
{ {
typePreference = 100; typePreference = 100;
} }
@ -540,13 +540,13 @@ public abstract class Candidate<T extends Candidate<?>>
{ {
//The ICE spec says: When there is only a single IP address, this value //The ICE spec says: When there is only a single IP address, this value
//SHOULD be set to. //SHOULD be set to.
if(getParentComponent().countLocalHostCandidates() < 2) if (getParentComponent().countLocalHostCandidates() < 2)
return MAX_LOCAL_PREFERENCE; return MAX_LOCAL_PREFERENCE;
//The ICE spec also says: Furthermore, if an agent is multi-homed and //The ICE spec also says: Furthermore, if an agent is multi-homed and
//has multiple IP addresses, the local preference for host candidates //has multiple IP addresses, the local preference for host candidates
//from a VPN interface SHOULD have a priority of 0. //from a VPN interface SHOULD have a priority of 0.
if(isVirtual()) if (isVirtual())
return MIN_LOCAL_PREFERENCE; return MIN_LOCAL_PREFERENCE;
InetAddress addr = getTransportAddress().getAddress(); InetAddress addr = getTransportAddress().getAddress();
@ -556,10 +556,10 @@ public abstract class Candidate<T extends Candidate<?>>
//Johnnie seems to think. //Johnnie seems to think.
//prefer IPv6 to IPv4 //prefer IPv6 to IPv4
if(addr instanceof Inet6Address) if (addr instanceof Inet6Address)
{ {
//prefer link local addresses to global ones //prefer link local addresses to global ones
if(addr.isLinkLocalAddress()) if (addr.isLinkLocalAddress())
return 30; return 30;
else else
return 40; return 40;
@ -719,7 +719,7 @@ public abstract class Candidate<T extends Candidate<?>>
*/ */
public TransportAddress getRelatedAddress() public TransportAddress getRelatedAddress()
{ {
if(getRelatedCandidate() != null) if (getRelatedCandidate() != null)
{ {
return getRelatedCandidate().getTransportAddress(); return getRelatedCandidate().getTransportAddress();
} }
@ -770,7 +770,7 @@ public abstract class Candidate<T extends Candidate<?>>
TransportAddress relAddr = getRelatedAddress(); TransportAddress relAddr = getRelatedAddress();
if(relAddr != null) if (relAddr != null)
{ {
buff.append(" raddr ").append(relAddr.getHostAddress()); buff.append(" raddr ").append(relAddr.getHostAddress());
buff.append(" rport ").append(relAddr.getPort()); buff.append(" rport ").append(relAddr.getPort());
@ -873,19 +873,19 @@ public abstract class Candidate<T extends Candidate<?>>
switch (getType()) switch (getType())
{ {
case SERVER_REFLEXIVE_CANDIDATE: case SERVER_REFLEXIVE_CANDIDATE:
if(getBase() != null) if (getBase() != null)
{ {
return getBase().getHostAddress(); return getBase().getHostAddress();
} }
break; break;
case PEER_REFLEXIVE_CANDIDATE: case PEER_REFLEXIVE_CANDIDATE:
if(getBase() != null) if (getBase() != null)
{ {
return getBase().getHostAddress(); return getBase().getHostAddress();
} }
break; break;
case RELAYED_CANDIDATE: case RELAYED_CANDIDATE:
if(getRelatedCandidate() != null) if (getRelatedCandidate() != null)
{ {
return getRelatedCandidate().getHostAddress(); return getRelatedCandidate().getHostAddress();
} }
@ -912,7 +912,7 @@ public abstract class Candidate<T extends Candidate<?>>
return getTransportAddress(); return getTransportAddress();
case RELAYED_CANDIDATE: case RELAYED_CANDIDATE:
// Corresponding to getMappedAddress(); // Corresponding to getMappedAddress();
if(getRelatedCandidate() != null) if (getRelatedCandidate() != null)
{ {
return getRelatedCandidate().getReflexiveAddress(); return getRelatedCandidate().getReflexiveAddress();
} }
@ -965,19 +965,19 @@ public abstract class Candidate<T extends Candidate<?>>
*/ */
public T getRelatedCandidate() public T getRelatedCandidate()
{ {
if(this.relatedCandidate == null) if (this.relatedCandidate == null)
{ {
TransportAddress relatedAddress = null; TransportAddress relatedAddress = null;
switch (getType()) switch (getType())
{ {
case SERVER_REFLEXIVE_CANDIDATE: case SERVER_REFLEXIVE_CANDIDATE:
if(getBase() != null) if (getBase() != null)
{ {
relatedAddress = getBase().getTransportAddress(); relatedAddress = getBase().getTransportAddress();
} }
break; break;
case PEER_REFLEXIVE_CANDIDATE: case PEER_REFLEXIVE_CANDIDATE:
if(getBase() != null) if (getBase() != null)
{ {
relatedAddress = getBase().getTransportAddress(); relatedAddress = getBase().getTransportAddress();
} }

View File

@ -122,25 +122,25 @@ public enum CandidateExtendedType
public static CandidateExtendedType parse(String extendedTypeName) public static CandidateExtendedType parse(String extendedTypeName)
throws IllegalArgumentException throws IllegalArgumentException
{ {
if(HOST_CANDIDATE.toString().equals(extendedTypeName)) if (HOST_CANDIDATE.toString().equals(extendedTypeName))
return HOST_CANDIDATE; return HOST_CANDIDATE;
else if(UPNP_CANDIDATE.toString().equals(extendedTypeName)) else if (UPNP_CANDIDATE.toString().equals(extendedTypeName))
return UPNP_CANDIDATE; return UPNP_CANDIDATE;
else if(STUN_PEER_REFLEXIVE_CANDIDATE.toString().equals( else if (STUN_PEER_REFLEXIVE_CANDIDATE.toString().equals(
extendedTypeName)) extendedTypeName))
return STUN_PEER_REFLEXIVE_CANDIDATE; return STUN_PEER_REFLEXIVE_CANDIDATE;
else if(STUN_SERVER_REFLEXIVE_CANDIDATE.toString().equals( else if (STUN_SERVER_REFLEXIVE_CANDIDATE.toString().equals(
extendedTypeName)) extendedTypeName))
return STUN_SERVER_REFLEXIVE_CANDIDATE; return STUN_SERVER_REFLEXIVE_CANDIDATE;
else if(TURN_RELAYED_CANDIDATE.toString().equals(extendedTypeName)) else if (TURN_RELAYED_CANDIDATE.toString().equals(extendedTypeName))
return TURN_RELAYED_CANDIDATE; return TURN_RELAYED_CANDIDATE;
else if(GOOGLE_TURN_RELAYED_CANDIDATE.toString().equals( else if (GOOGLE_TURN_RELAYED_CANDIDATE.toString().equals(
extendedTypeName)) extendedTypeName))
return GOOGLE_TURN_RELAYED_CANDIDATE; return GOOGLE_TURN_RELAYED_CANDIDATE;
else if(GOOGLE_TCP_TURN_RELAYED_CANDIDATE.toString().equals( else if (GOOGLE_TCP_TURN_RELAYED_CANDIDATE.toString().equals(
extendedTypeName)) extendedTypeName))
return GOOGLE_TCP_TURN_RELAYED_CANDIDATE; return GOOGLE_TCP_TURN_RELAYED_CANDIDATE;
else if(JINGLE_NODE_CANDIDATE.toString().equals(extendedTypeName)) else if (JINGLE_NODE_CANDIDATE.toString().equals(extendedTypeName))
return JINGLE_NODE_CANDIDATE; return JINGLE_NODE_CANDIDATE;
throw new IllegalArgumentException( throw new IllegalArgumentException(

View File

@ -172,7 +172,7 @@ public class CandidatePair
* @param localCnd the local <tt>Candidate</tt> of this * @param localCnd the local <tt>Candidate</tt> of this
* <tt>CandidatePair</tt>. * <tt>CandidatePair</tt>.
*/ */
protected void setLocalCandidate( LocalCandidate localCnd) protected void setLocalCandidate(LocalCandidate localCnd)
{ {
this.localCandidate = localCnd; this.localCandidate = localCnd;
} }

View File

@ -123,23 +123,23 @@ public enum CandidateType
public static CandidateType parse(String candidateTypeName) public static CandidateType parse(String candidateTypeName)
throws IllegalArgumentException throws IllegalArgumentException
{ {
if(PEER_REFLEXIVE_CANDIDATE.toString().equals(candidateTypeName)) if (PEER_REFLEXIVE_CANDIDATE.toString().equals(candidateTypeName))
return PEER_REFLEXIVE_CANDIDATE; return PEER_REFLEXIVE_CANDIDATE;
if(SERVER_REFLEXIVE_CANDIDATE.toString().equals(candidateTypeName)) if (SERVER_REFLEXIVE_CANDIDATE.toString().equals(candidateTypeName))
return SERVER_REFLEXIVE_CANDIDATE; return SERVER_REFLEXIVE_CANDIDATE;
if(RELAYED_CANDIDATE.toString().equals(candidateTypeName)) if (RELAYED_CANDIDATE.toString().equals(candidateTypeName))
return RELAYED_CANDIDATE; return RELAYED_CANDIDATE;
if(HOST_CANDIDATE.toString().equals(candidateTypeName)) if (HOST_CANDIDATE.toString().equals(candidateTypeName))
return HOST_CANDIDATE; return HOST_CANDIDATE;
// old name but returns the standard name // old name but returns the standard name
if(STUN_CANDIDATE.toString().equals(candidateTypeName)) if (STUN_CANDIDATE.toString().equals(candidateTypeName))
return SERVER_REFLEXIVE_CANDIDATE; return SERVER_REFLEXIVE_CANDIDATE;
if(LOCAL_CANDIDATE.toString().equals(candidateTypeName)) if (LOCAL_CANDIDATE.toString().equals(candidateTypeName))
return HOST_CANDIDATE; return HOST_CANDIDATE;
throw new IllegalArgumentException( throw new IllegalArgumentException(

View File

@ -17,11 +17,11 @@
*/ */
package org.ice4j.ice; package org.ice4j.ice;
import org.jitsi.utils.logging2.*;
import java.beans.*; import java.beans.*;
import java.util.*; import java.util.*;
import org.ice4j.util.Logger;
/** /**
* A check list is a list of <tt>CandidatePair</tt>s with a state (i.e. a * A check list is a list of <tt>CandidatePair</tt>s with a state (i.e. a
* <tt>CheckListState</tt>). The pairs in a check list are those that an ICE * <tt>CheckListState</tt>). The pairs in a check list are those that an ICE
@ -35,15 +35,6 @@ import org.ice4j.util.Logger;
public class CheckList public class CheckList
extends Vector<CandidatePair> extends Vector<CandidatePair>
{ {
/**
* The class logger.
* Note that this shouldn't be used directly by instances of
* {@link CheckList}, because it doesn't take into account the per-instance
* log level. Instances should use {@link #logger} instead.
*/
private static final java.util.logging.Logger classLogger
= java.util.logging.Logger.getLogger(CheckList.class.getName());
/** /**
* A dummy serialization id. * A dummy serialization id.
*/ */
@ -107,8 +98,7 @@ public class CheckList
protected CheckList(IceMediaStream parentStream) protected CheckList(IceMediaStream parentStream)
{ {
this.parentStream = parentStream; this.parentStream = parentStream;
logger logger = parentStream.getLogger().createChildLogger(this.getClass().getName());
= new Logger(classLogger, parentStream.getParentAgent().getLogger());
} }
/** /**
@ -145,7 +135,7 @@ public class CheckList
{ {
synchronized(triggeredCheckQueue) synchronized(triggeredCheckQueue)
{ {
if(!triggeredCheckQueue.contains(pair)) if (!triggeredCheckQueue.contains(pair))
{ {
triggeredCheckQueue.add(pair); triggeredCheckQueue.add(pair);
pair.setStateWaiting(); pair.setStateWaiting();
@ -164,7 +154,7 @@ public class CheckList
{ {
synchronized(triggeredCheckQueue) synchronized(triggeredCheckQueue)
{ {
if(triggeredCheckQueue.size() > 0) if (triggeredCheckQueue.size() > 0)
return triggeredCheckQueue.remove(0); return triggeredCheckQueue.remove(0);
} }
return null; return null;
@ -192,7 +182,7 @@ public class CheckList
{ {
if (pair.getState() == CandidatePairState.WAITING) if (pair.getState() == CandidatePairState.WAITING)
{ {
if(highestPriorityPair == null if (highestPriorityPair == null
|| pair.getPriority() > highestPriorityPair.getPriority()) || pair.getPriority() > highestPriorityPair.getPriority())
{ {
highestPriorityPair = pair; highestPriorityPair = pair;
@ -200,14 +190,14 @@ public class CheckList
} }
} }
if(highestPriorityPair != null) if (highestPriorityPair != null)
return highestPriorityPair; return highestPriorityPair;
for (CandidatePair pair : this) for (CandidatePair pair : this)
{ {
if (pair.getState() == CandidatePairState.FROZEN) if (pair.getState() == CandidatePairState.FROZEN)
{ {
if(highestPriorityPair == null if (highestPriorityPair == null
|| pair.getPriority() > highestPriorityPair.getPriority()) || pair.getPriority() > highestPriorityPair.getPriority())
{ {
highestPriorityPair = pair; highestPriorityPair = pair;
@ -219,6 +209,25 @@ public class CheckList
return highestPriorityPair; //return even if null return highestPriorityPair; //return even if null
} }
/**
* Returns a pair which matches the specified local and remote candidates'
* transport addresses, if any, otherwise null.
*/
public synchronized CandidatePair findPairMatching(LocalCandidate local, RemoteCandidate remote)
{
for (CandidatePair pair : this)
{
if (pair.getLocalCandidate() == local ||
pair.getLocalCandidate().getTransportAddress().equals(local.getTransportAddress()))
{
if (pair.getRemoteCandidate() == remote ||
pair.getRemoteCandidate().getTransportAddress().equals(remote.getTransportAddress()))
return pair;
}
}
return null;
}
/** /**
* Determines whether this <tt>CheckList</tt> can be considered active. * Determines whether this <tt>CheckList</tt> can be considered active.
* RFC 5245 says: A check list with at least one pair that is Waiting is * RFC 5245 says: A check list with at least one pair that is Waiting is
@ -310,14 +319,14 @@ public class CheckList
Map<String, CandidatePair> pairsToWait = new Hashtable<>(); Map<String, CandidatePair> pairsToWait = new Hashtable<>();
//first, determine the pairs that we'd need to put in the waiting state. //first, determine the pairs that we'd need to put in the waiting state.
for(CandidatePair pair : this) for (CandidatePair pair : this)
{ {
//we need to check whether the pair is already in the wait list. if //we need to check whether the pair is already in the wait list. if
//so we'll compare it with this one and determine which of the two //so we'll compare it with this one and determine which of the two
//needs to stay. //needs to stay.
CandidatePair prevPair = pairsToWait.get(pair.getFoundation()); CandidatePair prevPair = pairsToWait.get(pair.getFoundation());
if(prevPair == null) if (prevPair == null)
{ {
//first pair with this foundation. //first pair with this foundation.
pairsToWait.put(pair.getFoundation(), pair); pairsToWait.put(pair.getFoundation(), pair);
@ -327,9 +336,9 @@ public class CheckList
//we already have a pair with the same foundation. determine which //we already have a pair with the same foundation. determine which
//of the two has the lower component id and higher priority and //of the two has the lower component id and higher priority and
//keep that one in the list. //keep that one in the list.
if( prevPair.getParentComponent() == pair.getParentComponent()) if ( prevPair.getParentComponent() == pair.getParentComponent())
{ {
if(pair.getPriority() > prevPair.getPriority()) if (pair.getPriority() > prevPair.getPriority())
{ {
//need to replace the pair in the list. //need to replace the pair in the list.
pairsToWait.put(pair.getFoundation(), pair); pairsToWait.put(pair.getFoundation(), pair);
@ -337,7 +346,7 @@ public class CheckList
} }
else else
{ {
if(pair.getParentComponent().getComponentID() if (pair.getParentComponent().getComponentID()
< prevPair.getParentComponent().getComponentID()) < prevPair.getParentComponent().getComponentID())
{ {
//need to replace the pair in the list. //need to replace the pair in the list.
@ -359,7 +368,7 @@ public class CheckList
protected synchronized void recomputePairPriorities() protected synchronized void recomputePairPriorities()
{ {
//first, determine the pairs that we'd need to put in the waiting state. //first, determine the pairs that we'd need to put in the waiting state.
for(CandidatePair pair : this) for (CandidatePair pair : this)
pair.computePriority(); pair.computePriority();
} }
@ -389,7 +398,7 @@ public class CheckList
{ {
Component cmp = nominatedPair.getParentComponent(); Component cmp = nominatedPair.getParentComponent();
if(cmp.getSelectedPair() != null) if (cmp.getSelectedPair() != null)
{ {
return; return;
} }
@ -401,7 +410,7 @@ public class CheckList
cmp.setSelectedPair(nominatedPair); cmp.setSelectedPair(nominatedPair);
Iterator<CandidatePair> pairsIter = iterator(); Iterator<CandidatePair> pairsIter = iterator();
while(pairsIter.hasNext()) while (pairsIter.hasNext())
{ {
CandidatePair pair = pairsIter.next(); CandidatePair pair = pairsIter.next();
if (pair.getParentComponent() == cmp if (pair.getParentComponent() == cmp
@ -418,7 +427,7 @@ public class CheckList
{ {
Iterator<CandidatePair> triggeredPairsIter Iterator<CandidatePair> triggeredPairsIter
= triggeredCheckQueue.iterator(); = triggeredCheckQueue.iterator();
while(triggeredPairsIter.hasNext()) while (triggeredPairsIter.hasNext())
{ {
CandidatePair pair = triggeredPairsIter.next(); CandidatePair pair = triggeredPairsIter.next();
if (pair.getParentComponent() == cmp if (pair.getParentComponent() == cmp
@ -484,7 +493,7 @@ public class CheckList
{ {
synchronized(stateListeners) synchronized(stateListeners)
{ {
if(!stateListeners.contains(l)) if (!stateListeners.contains(l))
this.stateListeners.add(l); this.stateListeners.add(l);
} }
} }
@ -523,7 +532,7 @@ public class CheckList
PropertyChangeEvent evt = new PropertyChangeEvent( PropertyChangeEvent evt = new PropertyChangeEvent(
this, PROPERTY_CHECK_LIST_STATE, oldState, newState); this, PROPERTY_CHECK_LIST_STATE, oldState, newState);
for(PropertyChangeListener l : listenersCopy) for (PropertyChangeListener l : listenersCopy)
{ {
l.propertyChange(evt); l.propertyChange(evt);
} }
@ -539,7 +548,7 @@ public class CheckList
{ {
synchronized(checkListeners) synchronized(checkListeners)
{ {
if(!checkListeners.contains(l)) if (!checkListeners.contains(l))
{ {
checkListeners.add(l); checkListeners.add(l);
} }
@ -555,7 +564,7 @@ public class CheckList
{ {
synchronized(checkListeners) synchronized(checkListeners)
{ {
if(checkListeners.contains(l)) if (checkListeners.contains(l))
{ {
checkListeners.remove(l); checkListeners.remove(l);
} }
@ -578,7 +587,7 @@ public class CheckList
PropertyChangeEvent evt = new PropertyChangeEvent( PropertyChangeEvent evt = new PropertyChangeEvent(
this, PROPERTY_CHECK_LIST_CHECKS, false, true); this, PROPERTY_CHECK_LIST_CHECKS, false, true);
for(PropertyChangeListener l : listenersCopy) for (PropertyChangeListener l : listenersCopy)
{ {
l.propertyChange(evt); l.propertyChange(evt);
} }

View File

@ -18,15 +18,13 @@
package org.ice4j.ice; package org.ice4j.ice;
import java.beans.*; import java.beans.*;
import java.io.*;
import java.net.*; import java.net.*;
import java.util.*; import java.util.*;
import java.util.concurrent.*; import java.util.concurrent.*;
import java.util.logging.*;
import org.ice4j.*; import org.ice4j.*;
import org.ice4j.socket.*; import org.ice4j.socket.*;
import org.ice4j.util.Logger; //Disambiguation import org.jitsi.utils.logging2.*;
/** /**
* A component is a piece of a media stream requiring a single transport * A component is a piece of a media stream requiring a single transport
@ -43,15 +41,6 @@ import org.ice4j.util.Logger; //Disambiguation
public class Component public class Component
implements PropertyChangeListener implements PropertyChangeListener
{ {
/**
* Our class logger.
* Note that this shouldn't be used directly by instances of
* {@link IceMediaStream}, because it doesn't take into account the
* per-instance log level.updateRemoteCandidates Instances should use {@link #logger} instead.
*/
private static final java.util.logging.Logger classLogger
= java.util.logging.Logger.getLogger(Component.class.getName());
/** /**
* The component ID to use with RTP streams. * The component ID to use with RTP streams.
*/ */
@ -175,9 +164,10 @@ public class Component
*/ */
protected Component(int componentID, protected Component(int componentID,
IceMediaStream mediaStream, IceMediaStream mediaStream,
KeepAliveStrategy keepAliveStrategy) KeepAliveStrategy keepAliveStrategy,
Logger parentLogger)
{ {
this(componentID, mediaStream, keepAliveStrategy, true); this(componentID, mediaStream, keepAliveStrategy, true, parentLogger);
} }
/** /**
@ -192,21 +182,24 @@ public class Component
protected Component(int componentID, protected Component(int componentID,
IceMediaStream mediaStream, IceMediaStream mediaStream,
KeepAliveStrategy keepAliveStrategy, KeepAliveStrategy keepAliveStrategy,
boolean useComponentSocket) boolean useComponentSocket,
Logger parentLogger)
{ {
// the max value for componentID is 256 // the max value for componentID is 256
this.componentID = componentID; this.componentID = componentID;
this.parentStream = mediaStream; this.parentStream = mediaStream;
this.keepAliveStrategy this.keepAliveStrategy
= Objects.requireNonNull(keepAliveStrategy, "keepAliveStrategy"); = Objects.requireNonNull(keepAliveStrategy, "keepAliveStrategy");
this.logger = parentLogger.createChildLogger(
Logger agentLogger = mediaStream.getParentAgent().getLogger(); this.getClass().getName(),
Collections.singletonMap("componentId", Integer.toString(componentID))
);
if (useComponentSocket) if (useComponentSocket)
{ {
try try
{ {
componentSocket = new ComponentSocket(this, agentLogger); componentSocket = new ComponentSocket(this, logger);
socket = new MultiplexingDatagramSocket(componentSocket); socket = new MultiplexingDatagramSocket(componentSocket);
socketWrapper = new IceUdpSocketWrapper(socket); socketWrapper = new IceUdpSocketWrapper(socket);
} }
@ -223,7 +216,6 @@ public class Component
} }
mediaStream.addPairChangeListener(this); mediaStream.addPairChangeListener(this);
logger = new Logger(classLogger, agentLogger);
} }
/** /**
@ -443,9 +435,6 @@ public class Component
= getParentStream() = getParentStream()
.getParentAgent() .getParentAgent()
.createCandidatePair(localCnd, remoteCnd); .createCandidatePair(localCnd, remoteCnd);
logger.info("new Pair added: " + pair.toShortString()
+ ". Local ufrag "
+ parentStream.getParentAgent().getLocalUfrag());
checkList.add(pair); checkList.add(pair);
} }
} }
@ -472,7 +461,27 @@ public class Component
{ {
for (CandidatePair pair : checkList) for (CandidatePair pair : checkList)
{ {
streamCheckList.add(pair); /* Check whether the pair is already in the check list.
* (This can happen for pairs with remote peer-reflexive candidates,
* since those candidates aren't added to the candidate list even
* though the pair is added to the check list).
*/
CandidatePair existingPair
= streamCheckList.findPairMatching(pair.getLocalCandidate(), pair.getRemoteCandidate());
if (existingPair != null)
{
logger.info("existing Pair updated: " +
existingPair.toShortString() +
" to " + pair.toShortString() + ".");
existingPair.setRemoteCandidate(pair.getRemoteCandidate());
existingPair.computePriority();
}
else
{
streamCheckList.add(pair);
logger.info("new Pair added: " + pair.toShortString()
+ ".");
}
} }
} }
} }
@ -694,11 +703,7 @@ public class Component
&& (cand.getPriority() >= cand2.getPriority())) && (cand.getPriority() >= cand2.getPriority()))
{ {
localCandidates.remove(j); localCandidates.remove(j);
if (logger.isLoggable(Level.FINEST)) logger.trace(() -> "eliminating redundant cand: "+ cand2);
{
logger.finest(
"eliminating redundant cand: "+ cand2);
}
} }
else else
j++; j++;
@ -899,12 +904,7 @@ public class Component
*/ */
if (t instanceof ThreadDeath) if (t instanceof ThreadDeath)
throw (ThreadDeath) t; throw (ThreadDeath) t;
if (logger.isLoggable(Level.INFO)) logger.info(() -> "Failed to free LocalCandidate: " + localCandidate);
{
logger.log(
Level.INFO,
"Failed to free LocalCandidate: " + localCandidate);
}
} }
} }
@ -921,10 +921,47 @@ public class Component
*/ */
public LocalCandidate findLocalCandidate(TransportAddress localAddress) public LocalCandidate findLocalCandidate(TransportAddress localAddress)
{ {
for (LocalCandidate localCnd : localCandidates) return findLocalCandidate(localAddress, null);
}
/**
* Returns the local <tt>LocalCandidate</tt> with the specified
* <tt>address</tt> if it belongs to this component or <tt>null</tt>
* if it doesn't. If {@code base} is also specified, tries to find a
* candidate whose base matches {@code base}.
*
* @param address the {@link TransportAddress} we are looking for.
* @param base an optional base to match.
*
* @return the local <tt>LocalCandidate</tt> with the specified
* <tt>address</tt> if it belongs to this component or <tt>null</tt>
* if it doesn't.
*/
public LocalCandidate findLocalCandidate(TransportAddress address, LocalCandidate base)
{
for (LocalCandidate localCandidate : localCandidates)
{ {
if (localCnd.getTransportAddress().equals(localAddress)) if (localCandidate.getTransportAddress().equals(address))
return localCnd; {
if (base == null || base.equals(localCandidate.getBase()))
{
return localCandidate;
}
}
}
// In case the above loop failed to find a result because `base` was
// specified, fallback to the original behavior and return the first
// candidate matching `address` regardless of `base`.
for (LocalCandidate localCandidate : localCandidates)
{
if (localCandidate.getTransportAddress().equals(address))
{
logger.warn("Returning a candidate matching the address, "
+ "while no candidates match both address ("
+ address + ") and base (" + base +"): " + localCandidate
+ " with base " + localCandidate.getBase());
return localCandidate;
}
} }
return null; return null;
@ -1017,15 +1054,16 @@ public class Component
* parent of this component. * parent of this component.
* @return Component * @return Component
*/ */
public static Component build(int componentID, IceMediaStream mediaStream) public static Component build(int componentID, IceMediaStream mediaStream, Logger parentLogger)
{ {
return return
new Component( new Component(
componentID, componentID,
mediaStream, mediaStream,
KeepAliveStrategy.SELECTED_ONLY, KeepAliveStrategy.SELECTED_ONLY,
StackProperties.getBoolean( AgentConfig.config.getUseComponentSocket(),
StackProperties.USE_COMPONENT_SOCKET, true)); parentLogger
);
} }
/** /**
@ -1136,4 +1174,9 @@ public class Component
keepAlivePairs.add(pair); keepAlivePairs.add(pair);
} }
} }
public Logger getLogger()
{
return logger;
}
} }

View File

@ -33,14 +33,6 @@ public class ComponentSocket
extends MergingDatagramSocket extends MergingDatagramSocket
implements PropertyChangeListener implements PropertyChangeListener
{ {
/**
* The {@link Logger} used by the {@link MergingDatagramSocket} class and
* its instances for logging output.
*/
private static final java.util.logging.Logger classLogger
= java.util.logging.Logger.getLogger
(MergingDatagramSocket.class.getName());
/** /**
* Controls access to {@link #authorizedAddresses}. * Controls access to {@link #authorizedAddresses}.
*/ */
@ -68,22 +60,16 @@ public class ComponentSocket
*/ */
private final Object initializedActiveSyncRoot = new Object(); private final Object initializedActiveSyncRoot = new Object();
/**
* The {@link Logger} used by {@link MergingDatagramSocket} instances.
*/
private final Logger logger;
/** /**
* Initializes a new {@link MergingDatagramSocket} instance. * Initializes a new {@link MergingDatagramSocket} instance.
* @throws SocketException * @throws SocketException
*/ */
ComponentSocket(Component component, Logger levelDelegate) ComponentSocket(Component component, org.jitsi.utils.logging2.Logger parentLogger)
throws SocketException throws SocketException
{ {
super(levelDelegate); super(parentLogger);
this.component = component; this.component = component;
this.logger = new Logger(classLogger, levelDelegate);
component.getParentStream().addPairChangeListener(this); component.getParentStream().addPairChangeListener(this);
} }
@ -169,7 +155,9 @@ public class ComponentSocket
LocalCandidate localCandidate = pair.getLocalCandidate(); LocalCandidate localCandidate = pair.getLocalCandidate();
LocalCandidate base = localCandidate.getBase(); LocalCandidate base = localCandidate.getBase();
if (base != null) if (base != null)
{
localCandidate = base; localCandidate = base;
}
TransportAddress remoteAddress = null; TransportAddress remoteAddress = null;
RemoteCandidate remoteCandidate = pair.getRemoteCandidate(); RemoteCandidate remoteCandidate = pair.getRemoteCandidate();

View File

@ -21,7 +21,6 @@ import java.net.*;
import java.time.*; import java.time.*;
import java.util.*; import java.util.*;
import java.util.concurrent.*; import java.util.concurrent.*;
import java.util.logging.*;
import org.ice4j.*; import org.ice4j.*;
import org.ice4j.attribute.*; import org.ice4j.attribute.*;
@ -29,7 +28,7 @@ import org.ice4j.message.*;
import org.ice4j.socket.*; import org.ice4j.socket.*;
import org.ice4j.stack.*; import org.ice4j.stack.*;
import org.ice4j.util.*; import org.ice4j.util.*;
import org.ice4j.util.Logger; //Disambiguation import org.jitsi.utils.logging2.Logger;
/** /**
* The class that will be generating our outgoing connectivity checks and that * The class that will be generating our outgoing connectivity checks and that
@ -41,17 +40,6 @@ import org.ice4j.util.Logger; //Disambiguation
class ConnectivityCheckClient class ConnectivityCheckClient
implements ResponseCollector implements ResponseCollector
{ {
/**
* The <tt>Logger</tt> used by the <tt>ConnectivityCheckClient</tt>
* class for logging output.
* Note that this shouldn't be used directly by instances of
* {@link ConnectivityCheckClient}, because it doesn't take into account
* the per-instance log level. Instances should use {@link #logger} instead.
*/
private static final java.util.logging.Logger classLogger
= java.util.logging.Logger.getLogger(
ConnectivityCheckClient.class.getName());
/** /**
* The agent that created us. * The agent that created us.
*/ */
@ -78,6 +66,12 @@ class ConnectivityCheckClient
private final Queue<PaceMaker> paceMakers private final Queue<PaceMaker> paceMakers
= new ConcurrentLinkedQueue<>(); = new ConcurrentLinkedQueue<>();
/**
* Whether this {@link ConnectivityCheckClient} has been stopped.
* Synchronized by {@link #paceMakers}.
*/
private boolean stopped = false;
/** /**
* Timer that is used to let some seconds before a CheckList is considered * Timer that is used to let some seconds before a CheckList is considered
* as FAILED. * as FAILED.
@ -114,7 +108,7 @@ class ConnectivityCheckClient
this.parentAgent = parentAgent; this.parentAgent = parentAgent;
this.scheduledExecutorService = scheduledExecutorService; this.scheduledExecutorService = scheduledExecutorService;
this.executorService = executorService; this.executorService = executorService;
logger = new Logger(classLogger, parentAgent.getLogger()); logger = parentAgent.getLogger().createChildLogger(this.getClass().getName());
stunStack = this.parentAgent.getStunStack(); stunStack = this.parentAgent.getStunStack();
} }
@ -150,8 +144,7 @@ class ConnectivityCheckClient
if (streamsWithPendingConnectivityEstablishment.size() > 0) if (streamsWithPendingConnectivityEstablishment.size() > 0)
{ {
logger.info("Start connectivity checks. Local ufrag " logger.info("Start connectivity checks.");
+ parentAgent.getLocalUfrag());
startChecks( startChecks(
streamsWithPendingConnectivityEstablishment streamsWithPendingConnectivityEstablishment
.get(0).getCheckList()); .get(0).getCheckList());
@ -172,9 +165,16 @@ class ConnectivityCheckClient
*/ */
public void startChecks(CheckList checkList) public void startChecks(CheckList checkList)
{ {
PaceMaker paceMaker = new PaceMaker(checkList); synchronized (paceMakers)
paceMakers.add(paceMaker); {
paceMaker.schedule(); if (stopped)
{
return;
}
PaceMaker paceMaker = new PaceMaker(checkList);
paceMakers.add(paceMaker);
paceMaker.schedule();
}
} }
/** /**
@ -195,11 +195,8 @@ class ConnectivityCheckClient
indication, indication,
candidatePair.getRemoteCandidate().getTransportAddress(), candidatePair.getRemoteCandidate().getTransportAddress(),
localCandidate.getBase().getTransportAddress()); localCandidate.getBase().getTransportAddress());
if (logger.isLoggable(Level.FINEST)) logger.trace(() ->
{ "sending binding indication to pair " + candidatePair);
logger.finest(
"sending binding indication to pair " + candidatePair);
}
} }
catch (Exception ex) catch (Exception ex)
{ {
@ -207,11 +204,9 @@ class ConnectivityCheckClient
if (stunSocket != null) if (stunSocket != null)
{ {
logger.log( logger.info("Failed to send " + indication + " through "
Level.INFO, + stunSocket.getLocalSocketAddress() + "\n" +
"Failed to send " + indication + " through " ex.toString());
+ stunSocket.getLocalSocketAddress(),
ex);
} }
} }
} }
@ -282,7 +277,7 @@ class ConnectivityCheckClient
//nominated pairs. //nominated pairs.
if (candidatePair.isNominated()) if (candidatePair.isNominated())
{ {
logger.fine( logger.debug(() ->
"Add USE-CANDIDATE in check for: " "Add USE-CANDIDATE in check for: "
+ candidatePair.toShortString()); + candidatePair.toShortString());
request.putAttribute( request.putAttribute(
@ -326,9 +321,12 @@ class ConnectivityCheckClient
tran.setApplicationData(candidatePair); tran.setApplicationData(candidatePair);
logger.fine( if (logger.isDebugEnabled())
"start check for " + candidatePair.toShortString() + " tid " {
+ tran); logger.debug(
"start check for " + candidatePair.toShortString() + " tid "
+ tran);
}
try try
{ {
tran tran
@ -342,12 +340,15 @@ class ConnectivityCheckClient
originalWaitInterval, originalWaitInterval,
maxWaitInterval, maxWaitInterval,
maxRetransmissions); maxRetransmissions);
if (logger.isLoggable(Level.FINEST)) if (logger.isTraceEnabled())
{ {
logger.finest( logger.trace("checking pair " + candidatePair + " tid " + tran);
"checking pair " + candidatePair + " tid " + tran);
} }
} }
catch (NetAccessManager.SocketNotFoundException e)
{
logger.info("Could not start connectivity check: " + e.getMessage());
}
catch (Exception ex) catch (Exception ex)
{ {
tran = null; tran = null;
@ -367,7 +368,11 @@ class ConnectivityCheckClient
msg += " No route to host."; msg += " No route to host.";
ex = null; ex = null;
} }
logger.log(Level.INFO, msg, ex); logger.info(msg + (ex == null ? "" : "\n" + ex.toString()));
}
else
{
logger.warn("Failed to send " + request, ex);
} }
} }
@ -407,7 +412,7 @@ class ConnectivityCheckClient
{ {
if (!response.containsAttribute(Attribute.ERROR_CODE)) if (!response.containsAttribute(Attribute.ERROR_CODE))
{ {
logger.fine("Received a malformed error response."); logger.debug(() -> "Received a malformed error response.");
return; //malformed error response return; //malformed error response
} }
@ -528,11 +533,10 @@ class ConnectivityCheckClient
if (!response.containsAttribute(Attribute.XOR_MAPPED_ADDRESS)) if (!response.containsAttribute(Attribute.XOR_MAPPED_ADDRESS))
{ {
logger.fine("Received a success response with no " logger.debug(() -> "Received a success response with no "
+ "XOR_MAPPED_ADDRESS attribute."); + "XOR_MAPPED_ADDRESS attribute.");
logger.info("Pair failed (no XOR-MAPPED-ADDRESS): " logger.info("Pair failed (no XOR-MAPPED-ADDRESS): "
+ checkedPair.toShortString() + ". Local ufrag" + checkedPair.toShortString() + ".");
+ parentAgent.getLocalUfrag());
checkedPair.setStateFailed(); checkedPair.setStateFailed();
return; //malformed error response return; //malformed error response
} }
@ -554,9 +558,12 @@ class ConnectivityCheckClient
Transport.TCP); Transport.TCP);
} }
LocalCandidate validLocalCandidate = null; // In some situations we may have more than one local candidate matching
// the mapped address. In this case we want to find the that matches
validLocalCandidate = parentAgent.findLocalCandidate(mappedAddress); // the socket we received the response on.
LocalCandidate base = checkedPair.getLocalCandidate().getBase();
LocalCandidate validLocalCandidate
= parentAgent.findLocalCandidate(mappedAddress, base);
RemoteCandidate validRemoteCandidate = checkedPair.getRemoteCandidate(); RemoteCandidate validRemoteCandidate = checkedPair.getRemoteCandidate();
@ -602,7 +609,7 @@ class ConnectivityCheckClient
{ {
logger.info("Receive a peer-reflexive candidate: " logger.info("Receive a peer-reflexive candidate: "
+ peerReflexiveCandidate.getTransportAddress() + peerReflexiveCandidate.getTransportAddress()
+ ". Local ufrag " + parentAgent.getLocalUfrag()); + ".");
} }
} }
@ -640,8 +647,7 @@ class ConnectivityCheckClient
if (checkedPair.getParentComponent().getSelectedPair() == null) if (checkedPair.getParentComponent().getSelectedPair() == null)
{ {
logger.info("Pair succeeded: " + checkedPair.toShortString() logger.info("Pair succeeded: " + checkedPair.toShortString()
+ ". Local ufrag " + ".");
+ parentAgent.getLocalUfrag());
} }
checkedPair.setStateSucceeded(); checkedPair.setStateSucceeded();
} }
@ -650,7 +656,7 @@ class ConnectivityCheckClient
{ {
if (validPair.getParentComponent().getSelectedPair() == null) if (validPair.getParentComponent().getSelectedPair() == null)
logger.info("Pair validated: " + validPair.toShortString() logger.info("Pair validated: " + validPair.toShortString()
+ ". Local ufrag " + parentAgent.getLocalUfrag()); + ".");
parentAgent.validatePair(validPair); parentAgent.validatePair(validPair);
} }
@ -722,7 +728,7 @@ class ConnectivityCheckClient
" USE-CANDIDATE:" + " USE-CANDIDATE:" +
(request.containsAttribute(Attribute.USE_CANDIDATE) || (request.containsAttribute(Attribute.USE_CANDIDATE) ||
checkedPair.useCandidateSent()) checkedPair.useCandidateSent())
+ ". Local ufrag " + parentAgent.getLocalUfrag()); + ".");
} }
//If the agent was a controlling agent, and it had included a USE- //If the agent was a controlling agent, and it had included a USE-
@ -735,12 +741,12 @@ class ConnectivityCheckClient
{ {
logger.info("Nomination confirmed for pair: " logger.info("Nomination confirmed for pair: "
+ validPair.toShortString() + validPair.toShortString()
+ ". Loal ufrag " + parentAgent.getLocalUfrag()); + ".");
parentAgent.nominationConfirmed( validPair ); parentAgent.nominationConfirmed( validPair );
} }
else else
{ {
logger.fine( logger.debug(() ->
"Keep alive for pair: " + validPair.toShortString()); "Keep alive for pair: " + validPair.toShortString());
} }
} }
@ -762,7 +768,7 @@ class ConnectivityCheckClient
} }
else else
{ {
logger.fine( logger.debug(() ->
"Keep alive for pair: " + validPair.toShortString()); "Keep alive for pair: " + validPair.toShortString());
} }
} }
@ -832,7 +838,7 @@ class ConnectivityCheckClient
CandidatePair pair CandidatePair pair
= (CandidatePair) ev.getTransactionID().getApplicationData(); = (CandidatePair) ev.getTransactionID().getApplicationData();
logger.finer("Received error code " + ((int) errorCode)); logger.trace(() -> "Received error code " + ((int) errorCode));
//RESOLVE ROLE_CONFLICTS //RESOLVE ROLE_CONFLICTS
if (errorCode == ErrorCodeAttribute.ROLE_CONFLICT) if (errorCode == ErrorCodeAttribute.ROLE_CONFLICT)
@ -840,7 +846,7 @@ class ConnectivityCheckClient
boolean wasControlling boolean wasControlling
= originalRequest.containsAttribute(Attribute.ICE_CONTROLLING); = originalRequest.containsAttribute(Attribute.ICE_CONTROLLING);
logger.finer("Switching to isControlling=" + !wasControlling); logger.trace(() -> "Switching to isControlling=" + !wasControlling);
parentAgent.setControlling(!wasControlling); parentAgent.setControlling(!wasControlling);
pair.getParentComponent().getParentStream().getCheckList() pair.getParentComponent().getParentStream().getCheckList()
@ -849,10 +855,12 @@ class ConnectivityCheckClient
else else
{ {
int code = cl * 100 + co; int code = cl * 100 + co;
String reason = errorAttr.getReasonPhrase();
String trimmedReason = reason != null ? reason.trim() : null;
logger.info( logger.info(
"Error response for pair: " + pair.toShortString() + "Error response for pair: " + pair.toShortString() +
", failing. Code = " + code + ", failing. Code = " + code +
"(class=" + cl + "; number=" + co + ")"); "(class=" + cl + "; number=" + co + "): " + trimmedReason);
pair.setStateFailed(); pair.setStateFailed();
} }
} }
@ -950,7 +958,7 @@ class ConnectivityCheckClient
* its final state in either the processResponse(), * its final state in either the processResponse(),
* processTimeout() or processFailure() method. * processTimeout() or processFailure() method.
*/ */
logger.finest("will skip a check beat."); logger.trace(() -> "will skip a check beat.");
checkList.fireEndOfOrdinaryChecks(); checkList.fireEndOfOrdinaryChecks();
} }
} }
@ -982,14 +990,18 @@ class ConnectivityCheckClient
*/ */
public void stop() public void stop()
{ {
while (true) synchronized (paceMakers)
{ {
final PaceMaker paceMaker = paceMakers.poll(); stopped = true;
if (paceMaker == null) while (true)
{ {
break; final PaceMaker paceMaker = paceMakers.poll();
if (paceMaker == null)
{
break;
}
paceMaker.cancel();
} }
paceMaker.cancel();
} }
} }
} }

View File

@ -17,14 +17,12 @@
*/ */
package org.ice4j.ice; package org.ice4j.ice;
import java.util.logging.*;
import org.ice4j.*; import org.ice4j.*;
import org.ice4j.attribute.*; import org.ice4j.attribute.*;
import org.ice4j.message.*; import org.ice4j.message.*;
import org.ice4j.security.*; import org.ice4j.security.*;
import org.ice4j.stack.*; import org.ice4j.stack.*;
import org.ice4j.util.Logger; // Disambiguation. import org.jitsi.utils.logging2.*;
/** /**
* The class that would be handling and responding to incoming connectivity * The class that would be handling and responding to incoming connectivity
@ -37,34 +35,6 @@ class ConnectivityCheckServer
implements RequestListener, implements RequestListener,
CredentialsAuthority CredentialsAuthority
{ {
/**
* The <tt>Logger</tt> used by the <tt>ConnectivityCheckServer</tt>
* class and its instances for logging output.
* Note that this shouldn't be used directly by instances of
* {@link ConnectivityCheckServer}, because it doesn't take into account
* the per-instance log level. Instances should use {@link #logger} instead.
*/
private static final java.util.logging.Logger classLogger
= java.util.logging.Logger.getLogger(
ConnectivityCheckServer.class.getName());
/**
* Compares <tt>a</tt> and <tt>b</tt> as unsigned long values. Serves the
* same purpose as the <tt>Long.compareUnsigned</tt> method available in
* Java 1.8.
* @return <tt>-1</tt> if <tt>a</tt> is less than <tt>b</tt>, <tt>0</tt> if
* they are equal and <tt>1</tt> if <tt>a</tt> is bigger.
*/
private static int compareUnsignedLong(long a, long b)
{
if (a == b)
return 0;
else if ((a + Long.MIN_VALUE) < (b + Long.MIN_VALUE))
return -1;
else
return 1;
}
/** /**
* The agent that created us. * The agent that created us.
*/ */
@ -101,7 +71,7 @@ class ConnectivityCheckServer
public ConnectivityCheckServer(Agent parentAgent) public ConnectivityCheckServer(Agent parentAgent)
{ {
this.parentAgent = parentAgent; this.parentAgent = parentAgent;
logger = new Logger(classLogger, parentAgent.getLogger()); logger = parentAgent.getLogger().createChildLogger(this.getClass().getName());
stunStack = this.parentAgent.getStunStack(); stunStack = this.parentAgent.getStunStack();
stunStack.getCredentialsManager().registerAuthority(this); stunStack.getCredentialsManager().registerAuthority(this);
@ -141,8 +111,7 @@ class ConnectivityCheckServer
public void processRequest(StunMessageEvent evt) public void processRequest(StunMessageEvent evt)
throws IllegalArgumentException throws IllegalArgumentException
{ {
if(logger.isLoggable(Level.FINER)) logger.trace(() -> "Received request " + evt);
logger.finer("Received request " + evt);
alive = true; alive = true;
@ -155,14 +124,14 @@ class ConnectivityCheckServer
UsernameAttribute uname = (UsernameAttribute)request UsernameAttribute uname = (UsernameAttribute)request
.getAttribute(Attribute.USERNAME); .getAttribute(Attribute.USERNAME);
if( uname == null if ( uname == null
|| !checkLocalUserName(new String(uname.getUsername()))) || !checkLocalUserName(new String(uname.getUsername())))
{ {
return; return;
} }
//detect role conflicts //detect role conflicts
if( ( parentAgent.isControlling() if ( ( parentAgent.isControlling()
&& request.containsAttribute(Attribute.ICE_CONTROLLING)) && request.containsAttribute(Attribute.ICE_CONTROLLING))
|| ( ! parentAgent.isControlling() || ( ! parentAgent.isControlling()
&& request.containsAttribute(Attribute.ICE_CONTROLLED))) && request.containsAttribute(Attribute.ICE_CONTROLLED)))
@ -212,11 +181,9 @@ class ConnectivityCheckServer
} }
catch (Exception e) catch (Exception e)
{ {
logger.log( logger.info("Failed to send " + response
Level.INFO, + " through " + evt.getLocalAddress() + "\n" +
"Failed to send " + response e.toString());
+ " through " + evt.getLocalAddress(),
e);
//try to trigger a 500 response although if this one failed, //try to trigger a 500 response although if this one failed,
//then chances are the 500 will fail too. //then chances are the 500 will fail too.
throw new RuntimeException("Failed to send a response", e); throw new RuntimeException("Failed to send a response", e);
@ -247,13 +214,10 @@ class ConnectivityCheckServer
//apply tie-breaking //apply tie-breaking
//extract priority //extract priority
if(priorityAttr == null) if (priorityAttr == null)
{ {
if(logger.isLoggable(Level.FINE)) logger.debug(() -> "Received a connectivity check with"
{ + "no PRIORITY attribute. Discarding.");
logger.log(Level.FINE, "Received a connectivity check with"
+ "no PRIORITY attribute. Discarding.");
}
throw new IllegalArgumentException("Missing PRIORITY attribute!"); throw new IllegalArgumentException("Missing PRIORITY attribute!");
} }
@ -278,107 +242,79 @@ class ConnectivityCheckServer
*/ */
private boolean repairRoleConflict(StunMessageEvent evt) private boolean repairRoleConflict(StunMessageEvent evt)
{ {
Message req = evt.getMessage(); final Message req = evt.getMessage();
long ourTieBreaker = parentAgent.getTieBreaker(); final boolean selfIceControlling = parentAgent.isControlling();
// If the agent is in the controlling role, and the // If the agent is in the controlling role, and the
// ICE-CONTROLLING attribute is present in the request: // ICE-CONTROLLING attribute is present in the request:
if(parentAgent.isControlling() final boolean bothControllingConflict = selfIceControlling &&
&& req.containsAttribute(Attribute.ICE_CONTROLLING)) req.containsAttribute(Attribute.ICE_CONTROLLING);
{
IceControllingAttribute controlling = (IceControllingAttribute)
req.getAttribute(Attribute.ICE_CONTROLLING);
long theirTieBreaker = controlling.getTieBreaker();
// If the agent's tie-breaker is larger than or equal to the
// contents of the ICE-CONTROLLING attribute, the agent generates
// a Binding error response and includes an ERROR-CODE attribute
// with a value of 487 (Role Conflict) but retains its role.
if(compareUnsignedLong(ourTieBreaker, theirTieBreaker) >= 0)
{
Response response = MessageFactory.createBindingErrorResponse(
ErrorCodeAttribute.ROLE_CONFLICT);
try
{
stunStack.sendResponse(
evt.getTransactionID().getBytes(),
response,
evt.getLocalAddress(),
evt.getRemoteAddress());
return false;
}
catch(Exception exc)
{
//rethrow so that we would send a 500 response instead.
throw new RuntimeException("Failed to send a 487", exc);
}
}
//If the agent's tie-breaker is less than the contents of the
//ICE-CONTROLLING attribute, the agent switches to the controlled
//role.
else
{
logger.finer(
"Switching to controlled because theirTieBreaker="
+ theirTieBreaker + " and ourTieBreaker="
+ ourTieBreaker);
parentAgent.setControlling(false);
return true;
}
}
// If the agent is in the controlled role, and the ICE-CONTROLLED // If the agent is in the controlled role, and the ICE-CONTROLLED
// attribute is present in the request: // attribute is present in the request:
else if(!parentAgent.isControlling() final boolean bothControlledConflict = !selfIceControlling &&
&& req.containsAttribute(Attribute.ICE_CONTROLLED)) req.containsAttribute(Attribute.ICE_CONTROLLED);
if (!(bothControllingConflict || bothControlledConflict))
{ {
IceControlledAttribute controlled = (IceControlledAttribute) // we don't have a role conflict
req.getAttribute(Attribute.ICE_CONTROLLED); return true;
}
long theirTieBreaker = controlled.getTieBreaker(); final long selfTieBreaker = parentAgent.getTieBreaker();
//If the agent's tie-breaker is larger than or equal to the final IceControlAttribute theirIceControl = bothControllingConflict
//contents of the ICE-CONTROLLED attribute, the agent switches to ? (IceControlAttribute)req.getAttribute(Attribute.ICE_CONTROLLING)
//the controlling role. : (IceControlAttribute)req.getAttribute(Attribute.ICE_CONTROLLED);
if(compareUnsignedLong(ourTieBreaker, theirTieBreaker) >= 0)
final long theirTieBreaker = theirIceControl.getTieBreaker();
// If the agent's tie-breaker is larger than or equal to the
// contents of the ICE control attribute, the agent generates
// a Binding error response and includes an ERROR-CODE attribute
// with a value of 487 (Role Conflict) but retains its role.
if (Long.compareUnsigned(selfTieBreaker, theirTieBreaker) >= 0)
{
final UsernameAttribute requestUserName = (UsernameAttribute)req
.getAttribute(Attribute.USERNAME);
final Response response =
MessageFactory.createBindingErrorResponse(
ErrorCodeAttribute.ROLE_CONFLICT);
final Attribute messageIntegrityAttribute =
AttributeFactory.createMessageIntegrityAttribute(
new String(requestUserName.getUsername()));
response.putAttribute(messageIntegrityAttribute);
try
{ {
logger.finer( stunStack.sendResponse(
"Switching to controlling because theirTieBreaker=" evt.getTransactionID().getBytes(),
+ theirTieBreaker + " and ourTieBreaker=" response,
+ ourTieBreaker); evt.getLocalAddress(),
parentAgent.setControlling(true); evt.getRemoteAddress());
return true; return false;
} }
// If the agent's tie-breaker is less than the contents of the catch(Exception exc)
// ICE-CONTROLLED attribute, the agent generates a Binding error
// response and includes an ERROR-CODE attribute with a value of
// 487 (Role Conflict) but retains its role.
else
{ {
Response response = MessageFactory.createBindingErrorResponse( //rethrow so that we would send a 500 response instead.
ErrorCodeAttribute.ROLE_CONFLICT); throw new RuntimeException("Failed to send a 487", exc);
try
{
stunStack.sendResponse(
evt.getTransactionID().getBytes(),
response,
evt.getLocalAddress(),
evt.getRemoteAddress());
return false;
}
catch(Exception exc)
{
//rethrow so that we would send a 500 response instead.
throw new RuntimeException("Failed to send a 487", exc);
}
} }
} }
return true; // we don't have a role conflict //If the agent's tie-breaker is less than the contents of the
//ICE control attribute, the agent toggles its ICE control role.
else
{
final String selfNextControlState
= selfIceControlling ? "controlled" : "controlling";
logger.trace(() ->
"Switching to " + selfNextControlState + " because " +
" theirTieBreaker= " + theirTieBreaker + " and " +
"selfTieBreaker= " + selfTieBreaker);
parentAgent.setControlling(!selfIceControlling);
return true;
}
} }
/** /**
@ -444,7 +380,7 @@ class ConnectivityCheckServer
public byte[] getRemoteKey(String username, String media) public byte[] getRemoteKey(String username, String media)
{ {
IceMediaStream stream = parentAgent.getStream(media); IceMediaStream stream = parentAgent.getStream(media);
if(stream == null) if (stream == null)
{ {
return null; return null;
} }
@ -464,7 +400,7 @@ class ConnectivityCheckServer
//caller gave us the entire username. //caller gave us the entire username.
if (username.equals(parentAgent.generateLocalUserName(media))) if (username.equals(parentAgent.generateLocalUserName(media)))
{ {
if(stream.getRemotePassword() != null) if (stream.getRemotePassword() != null)
return stream.getRemotePassword().getBytes(); return stream.getRemotePassword().getBytes();
} }
} }

View File

@ -17,11 +17,11 @@
*/ */
package org.ice4j.ice; package org.ice4j.ice;
import org.jitsi.utils.logging2.*;
import java.beans.*; import java.beans.*;
import java.util.*; import java.util.*;
import org.ice4j.util.*;
/** /**
* Implements ice4j internal nomination strategies. * Implements ice4j internal nomination strategies.
* *
@ -30,15 +30,6 @@ import org.ice4j.util.*;
public class DefaultNominator public class DefaultNominator
implements PropertyChangeListener implements PropertyChangeListener
{ {
/**
* The class logger.
* Note that this shouldn't be used directly by instances of
* {@link DefaultNominator}, because it doesn't take into account the
* per-instance log level. Instances should use {@link #logger} instead.
*/
private static final java.util.logging.Logger classLogger
= java.util.logging.Logger.getLogger(DefaultNominator.class.getName());
/** /**
* The Agent that created us. * The Agent that created us.
*/ */
@ -71,7 +62,7 @@ public class DefaultNominator
public DefaultNominator(Agent parentAgent) public DefaultNominator(Agent parentAgent)
{ {
this.parentAgent = parentAgent; this.parentAgent = parentAgent;
logger = new Logger(classLogger, parentAgent.getLogger()); logger = parentAgent.getLogger().createChildLogger(this.getClass().getName());
parentAgent.addStateChangeListener(this); parentAgent.addStateChangeListener(this);
} }
@ -107,17 +98,20 @@ public class DefaultNominator
if (ev.getSource() instanceof CandidatePair) if (ev.getSource() instanceof CandidatePair)
{ {
// STUN Usage for Consent Freshness is of no concern here. // STUN Usage for Consent Freshness is of no concern here.
if (IceMediaStream.PROPERTY_PAIR_CONSENT_FRESHNESS_CHANGED.equals( if (IceMediaStream.PROPERTY_PAIR_CONSENT_FRESHNESS_CHANGED.equals(propertyName))
propertyName)) {
return; return;
}
CandidatePair validPair = (CandidatePair) ev.getSource(); CandidatePair validPair = (CandidatePair) ev.getSource();
Component parentComponent = validPair.getParentComponent();
IceMediaStream parentStream = parentComponent.getParentStream();
// do not nominate pair if there is currently a selected pair for // do not nominate pair if there is currently a nominated pair for
// the component // the component
if (validPair.getParentComponent().getSelectedPair() != null) if (parentStream.validListContainsNomineeForComponent(parentComponent))
{ {
logger.fine( logger.debug(() ->
"Keep-alive for pair: " + validPair.toShortString()); "Keep-alive for pair: " + validPair.toShortString());
return; return;
} }
@ -147,7 +141,7 @@ public class DefaultNominator
CandidatePair validPair = (CandidatePair)evt.getSource(); CandidatePair validPair = (CandidatePair)evt.getSource();
logger.info("Nominate (first valid): " + validPair.toShortString() logger.info("Nominate (first valid): " + validPair.toShortString()
+ ". Local ufrag " + parentAgent.getLocalUfrag()); + ".");
parentAgent.nominate(validPair); parentAgent.nominate(validPair);
} }
} }
@ -191,6 +185,18 @@ public class DefaultNominator
} }
} }
/**
* The {@link NominationStrategy} that this nominator is using when
* deciding whether or not a valid {@link CandidatePair} is suitable for
* nomination.
*
* @return the {@link NominationStrategy} we are using.
*/
public NominationStrategy getStrategy()
{
return strategy;
}
/** /**
* The {@link NominationStrategy} that this nominator should use when * The {@link NominationStrategy} that this nominator should use when
* deciding whether or not a valid {@link CandidatePair} is suitable for * deciding whether or not a valid {@link CandidatePair} is suitable for

View File

@ -83,7 +83,7 @@ public class FoundationsRegistry
StringBuffer foundationStringBuff = new StringBuffer(type); StringBuffer foundationStringBuff = new StringBuffer(type);
foundationStringBuff.append(base); foundationStringBuff.append(base);
if(server != null) if (server != null)
foundationStringBuff.append(server); foundationStringBuff.append(server);
foundationStringBuff.append(transport); foundationStringBuff.append(transport);
@ -97,7 +97,7 @@ public class FoundationsRegistry
//obtain a new foundation number if we don't have one for this kind //obtain a new foundation number if we don't have one for this kind
//of candidates. //of candidates.
if(foundationValue == null) if (foundationValue == null)
{ {
foundationValue = Integer.toString(++lastAssignedFoundation); foundationValue = Integer.toString(++lastAssignedFoundation);
foundations.put(foundationString, foundationValue); foundations.put(foundationString, foundationValue);

View File

@ -103,7 +103,7 @@ public class GoogleRelayedCandidate
turnCandidateHarvest.hostCandidate.getParentComponent() turnCandidateHarvest.hostCandidate.getParentComponent()
.findLocalCandidate(mappedAddress)); .findLocalCandidate(mappedAddress));
if(transportAddress.getTransport() == Transport.TCP) if (transportAddress.getTransport() == Transport.TCP)
{ {
super.setExtendedType( super.setExtendedType(
CandidateExtendedType.GOOGLE_TCP_TURN_RELAYED_CANDIDATE); CandidateExtendedType.GOOGLE_TCP_TURN_RELAYED_CANDIDATE);
@ -200,13 +200,13 @@ public class GoogleRelayedCandidate
{ {
try try
{ {
if(getTransport() == Transport.UDP) if (getTransport() == Transport.UDP)
{ {
socket socket
= new IceUdpSocketWrapper(new MultiplexingDatagramSocket( = new IceUdpSocketWrapper(new MultiplexingDatagramSocket(
getRelayedCandidateDatagramSocket())); getRelayedCandidateDatagramSocket()));
} }
else if(getTransport() == Transport.TCP) else if (getTransport() == Transport.TCP)
{ {
final Socket s = getRelayedCandidateSocket(); final Socket s = getRelayedCandidateSocket();
socket = new IceTcpSocketWrapper(new MultiplexingSocket(s)); socket = new IceTcpSocketWrapper(new MultiplexingSocket(s));

View File

@ -19,9 +19,12 @@ package org.ice4j.ice;
import java.beans.*; import java.beans.*;
import java.util.*; import java.util.*;
import java.util.logging.Logger;
import org.ice4j.*; import org.ice4j.*;
import org.jitsi.utils.collections.*;
import org.jitsi.utils.logging2.*;
import static org.ice4j.ice.AgentConfig.config;
/** /**
* The class represents a media stream from the ICE perspective, i.e. a * The class represents a media stream from the ICE perspective, i.e. a
@ -32,15 +35,6 @@ import org.ice4j.*;
*/ */
public class IceMediaStream public class IceMediaStream
{ {
/**
* Our class logger
* Note that this shouldn't be used directly by instances of
* {@link IceMediaStream}, because it doesn't take into account the
* per-instance log level. Instances should use {@link #logger} instead.
*/
private static final Logger classLogger =
Logger.getLogger(IceMediaStream.class.getName());
/** /**
* The property name that we use when delivering events notifying listeners * The property name that we use when delivering events notifying listeners
* that the consent freshness of a pair has changed. * that the consent freshness of a pair has changed.
@ -135,7 +129,7 @@ public class IceMediaStream
* across all check lists to a specific value, adn this value MUST be * across all check lists to a specific value, adn this value MUST be
* configurable. A default of 100 is RECOMMENDED. * configurable. A default of 100 is RECOMMENDED.
*/ */
private int maxCheckListSize = Agent.DEFAULT_MAX_CHECK_LIST_SIZE; private int maxCheckListSize = config.getMaxCheckListSize();
/** /**
* The user fragment that we received from the remote party. * The user fragment that we received from the remote party.
@ -150,7 +144,7 @@ public class IceMediaStream
/** /**
* The {@link Logger} used by {@link IceMediaStream} instances. * The {@link Logger} used by {@link IceMediaStream} instances.
*/ */
private org.ice4j.util.Logger logger; private Logger logger;
/** /**
* Initializes a new <tt>IceMediaStream</tt> object. * Initializes a new <tt>IceMediaStream</tt> object.
@ -161,7 +155,9 @@ public class IceMediaStream
*/ */
protected IceMediaStream(Agent parentAgent, String name) protected IceMediaStream(Agent parentAgent, String name)
{ {
logger = new org.ice4j.util.Logger(classLogger, parentAgent.getLogger()); logger = parentAgent.getLogger().createChildLogger(
IceMediaStream.class.getName(),
Collections.singletonMap("name", name));
this.name = name; this.name = name;
this.parentAgent = parentAgent; this.parentAgent = parentAgent;
checkList = new CheckList(this); checkList = new CheckList(this);
@ -176,14 +172,14 @@ public class IceMediaStream
* @param keepAliveStrategy the keep-alive strategy, which dictates which * @param keepAliveStrategy the keep-alive strategy, which dictates which
* candidates pairs are going to be kept alive. * candidates pairs are going to be kept alive.
* @param useComponentSocket whether the "component socket" should be used * @param useComponentSocket whether the "component socket" should be used
* or not. See {@link StackProperties#USE_COMPONENT_SOCKET}. * or not. See {@link AgentConfig#getUseComponentSocket()}.
* *
* @return the newly created stream <tt>Component</tt> after adding it to * @return the newly created stream <tt>Component</tt> after adding it to
* the stream first. * the stream first.
*/ */
protected Component createComponent( protected Component createComponent(
KeepAliveStrategy keepAliveStrategy, KeepAliveStrategy keepAliveStrategy,
boolean useComponentSocket) boolean useComponentSocket)
{ {
Component component; Component component;
@ -194,7 +190,8 @@ public class IceMediaStream
++lastComponentID, ++lastComponentID,
this, this,
keepAliveStrategy, keepAliveStrategy,
useComponentSocket); useComponentSocket,
logger);
components.put(component.getComponentID(), component); components.put(component.getComponentID(), component);
} }
@ -367,7 +364,7 @@ public class IceMediaStream
orderCheckList(); orderCheckList();
pruneCheckList(checkList); pruneCheckList(checkList);
logger.finest("Checklist initialized."); logger.trace(() -> "Checklist initialized.");
} }
} }
@ -379,7 +376,7 @@ public class IceMediaStream
*/ */
protected void createCheckList(List<CandidatePair> checkList) protected void createCheckList(List<CandidatePair> checkList)
{ {
for(Component cmp : getComponents()) for (Component cmp : getComponents())
createCheckList(cmp, checkList); createCheckList(cmp, checkList);
} }
@ -398,22 +395,22 @@ public class IceMediaStream
List<RemoteCandidate> remoteCnds = component.getRemoteCandidates(); List<RemoteCandidate> remoteCnds = component.getRemoteCandidates();
LocalCandidate upnpBase = null; LocalCandidate upnpBase = null;
for(LocalCandidate lc : localCnds) for (LocalCandidate lc : localCnds)
{ {
// XXX do we assume a single UPNPCandidate here? // XXX do we assume a single UPNPCandidate here?
if(lc instanceof UPNPCandidate) if (lc instanceof UPNPCandidate)
upnpBase = lc.getBase(); upnpBase = lc.getBase();
} }
for(LocalCandidate localCnd : localCnds) for (LocalCandidate localCnd : localCnds)
{ {
// Don't take into consideration UPnP base candidate // Don't take into consideration UPnP base candidate
if(localCnd == upnpBase) if (localCnd == upnpBase)
continue; continue;
for(RemoteCandidate remoteCnd : remoteCnds) for (RemoteCandidate remoteCnd : remoteCnds)
{ {
if(localCnd.canReach(remoteCnd) if (localCnd.canReach(remoteCnd)
&& remoteCnd.getTransportAddress().getPort() != 0) && remoteCnd.getTransportAddress().getPort() != 0)
{ {
CandidatePair pair CandidatePair pair
@ -459,12 +456,12 @@ public class IceMediaStream
Iterator<CandidatePair> ckListIter = checkList.iterator(); Iterator<CandidatePair> ckListIter = checkList.iterator();
while(ckListIter.hasNext()) while (ckListIter.hasNext())
{ {
CandidatePair pair = ckListIter.next(); CandidatePair pair = ckListIter.next();
//drop all pairs above MAX_CHECK_LIST_SIZE. //drop all pairs above MAX_CHECK_LIST_SIZE.
if(tmpCheckList.size() > maxCheckListSize) if (tmpCheckList.size() > maxCheckListSize)
{ {
ckListIter.remove(); ckListIter.remove();
continue; continue;
@ -472,14 +469,14 @@ public class IceMediaStream
//replace local server reflexive candidates with their base. //replace local server reflexive candidates with their base.
LocalCandidate localCnd = pair.getLocalCandidate(); LocalCandidate localCnd = pair.getLocalCandidate();
if( localCnd.getType() if ( localCnd.getType()
== CandidateType.SERVER_REFLEXIVE_CANDIDATE) == CandidateType.SERVER_REFLEXIVE_CANDIDATE)
{ {
pair.setLocalCandidate(localCnd.getBase()); pair.setLocalCandidate(localCnd.getBase());
//if the new pair corresponds to another one with a higher //if the new pair corresponds to another one with a higher
//priority, then remove it. //priority, then remove it.
if(tmpCheckList.contains(pair)) if (tmpCheckList.contains(pair))
{ {
ckListIter.remove(); ckListIter.remove();
continue; continue;
@ -514,23 +511,28 @@ public class IceMediaStream
/** /**
* Returns the local <tt>LocalCandidate</tt> with the specified * Returns the local <tt>LocalCandidate</tt> with the specified
* <tt>localAddress</tt> if it belongs to any of this stream's components * <tt>address</tt> if it belongs to any of this stream's components
* or <tt>null</tt> otherwise. * or <tt>null</tt> otherwise. If {@code base} is also specified, tries to
* find a candidate whose base matches {@code base}.
* *
* @param localAddress the {@link TransportAddress} we are looking for. * @param address the {@link TransportAddress} we are looking for.
* @param base an optional base to match.
* *
* @return the local <tt>LocalCandidate</tt> with the specified * @return the local <tt>LocalCandidate</tt> with the specified
* <tt>localAddress</tt> if it belongs to any of this stream's components * <tt>address</tt> if it belongs to any of this stream's components
* or <tt>null</tt> otherwise. * or <tt>null</tt> otherwise.
*/ */
public LocalCandidate findLocalCandidate(TransportAddress localAddress) public LocalCandidate findLocalCandidate(TransportAddress address, LocalCandidate base)
{ {
for( Component cmp : components.values()) for (Component component : components.values())
{ {
LocalCandidate cnd = cmp.findLocalCandidate(localAddress); LocalCandidate localCandidate
= component.findLocalCandidate(address, base);
if(cnd != null) if (localCandidate != null)
return cnd; {
return localCandidate;
}
} }
return null; return null;
@ -550,11 +552,11 @@ public class IceMediaStream
*/ */
public RemoteCandidate findRemoteCandidate(TransportAddress remoteAddress) public RemoteCandidate findRemoteCandidate(TransportAddress remoteAddress)
{ {
for( Component cmp : components.values()) for ( Component cmp : components.values())
{ {
RemoteCandidate cnd = cmp.findRemoteCandidate(remoteAddress); RemoteCandidate cnd = cmp.findRemoteCandidate(remoteAddress);
if(cnd != null) if (cnd != null)
return cnd; return cnd;
} }
@ -921,4 +923,9 @@ public class IceMediaStream
{ {
return remotePassword; return remotePassword;
} }
public Logger getLogger()
{
return logger;
}
} }

View File

@ -19,12 +19,11 @@ package org.ice4j.ice;
import java.io.*; import java.io.*;
import java.net.*; import java.net.*;
import java.util.logging.*;
import org.ice4j.*; import org.ice4j.*;
import org.ice4j.socket.*; import org.ice4j.socket.*;
import org.ice4j.stack.*; import org.ice4j.stack.*;
import org.ice4j.util.Logger; // Disambiguation. import org.jitsi.utils.logging2.*;
/** /**
* <tt>LocalCandidate</tt>s are obtained by an agent for every stream component * <tt>LocalCandidate</tt>s are obtained by an agent for every stream component
@ -66,7 +65,7 @@ public abstract class LocalCandidate
/** /**
* The {@link Logger} used by {@link LocalCandidate} instances. * The {@link Logger} used by {@link LocalCandidate} instances.
*/ */
private Logger logger; private final Logger logger;
/** /**
* Creates a <tt>LocalCandidate</tt> instance for the specified transport * Creates a <tt>LocalCandidate</tt> instance for the specified transport
@ -91,12 +90,10 @@ public abstract class LocalCandidate
CandidateType type, CandidateType type,
CandidateExtendedType extendedType, CandidateExtendedType extendedType,
LocalCandidate relatedCandidate) LocalCandidate relatedCandidate)
{ {
super(transportAddress, parentComponent, type, relatedCandidate); super(transportAddress, parentComponent, type, relatedCandidate);
logger logger = parentComponent.getLogger().createChildLogger(this.getClass().getName());
= new Logger(classLogger,
parentComponent.
getParentStream().getParentAgent().getLogger());
this.extendedType = extendedType; this.extendedType = extendedType;
} }
@ -205,8 +202,7 @@ public abstract class LocalCandidate
} }
catch (SocketException sex) //don't u just luv da name? ;) catch (SocketException sex) //don't u just luv da name? ;)
{ {
logger.log(Level.SEVERE, logger.error("Failed to acquire Socket"
"Failed to acquire Socket"
+ " specific to STUN communication.", + " specific to STUN communication.",
sex); sex);
exception = sex; exception = sex;
@ -262,8 +258,7 @@ public abstract class LocalCandidate
} }
catch (SocketException sex) //don't u just luv da name? ;) catch (SocketException sex) //don't u just luv da name? ;)
{ {
logger.log(Level.SEVERE, logger.error("Failed to acquire DatagramSocket"
"Failed to acquire DatagramSocket"
+ " specific to STUN communication.", + " specific to STUN communication.",
sex); sex);
exception = sex; exception = sex;

View File

@ -614,13 +614,13 @@ public class NetworkUtils
return IN4_ADDR_ANY; return IN4_ADDR_ANY;
} }
while(ifaces.hasMoreElements()) while (ifaces.hasMoreElements())
{ {
Enumeration<InetAddress> addrs Enumeration<InetAddress> addrs
= ifaces.nextElement().getInetAddresses(); = ifaces.nextElement().getInetAddresses();
while (addrs.hasMoreElements()) while (addrs.hasMoreElements())
{ {
if(addrs.nextElement() instanceof Inet6Address) if (addrs.nextElement() instanceof Inet6Address)
return IN6_ADDR_ANY; return IN6_ADDR_ANY;
} }
} }
@ -752,7 +752,7 @@ public class NetworkUtils
//in case this was an IPv6 literal and we remove the closing bracket, //in case this was an IPv6 literal and we remove the closing bracket,
//put it back in now. //put it back in now.
if(ipv6Address.charAt(0) == '[' if (ipv6Address.charAt(0) == '['
&& ipv6Address.charAt(ipv6Address.length()-1) != ']') && ipv6Address.charAt(ipv6Address.length()-1) != ']')
{ {
ipv6Address += ']'; ipv6Address += ']';

View File

@ -44,8 +44,11 @@ public enum NominationStrategy
NOMINATE_FIRST_VALID("NominateFirstValid"), NOMINATE_FIRST_VALID("NominateFirstValid"),
/** /**
* The strategy consists in nominating the highest priority valid pair once * The strategy consists in nominating the highest priority valid pair.
* all checks in a list have completed. * Once a pair is validated, if no higher-priority pairs remain outstanding,
* it is nominated; otherwise, a timer is armed, and if higher-priority
* pairs are still outstanding after the timeout, the highest-priority validated
* pair is nominated.
*/ */
NOMINATE_HIGHEST_PRIO("NominateHighestPriority"), NOMINATE_HIGHEST_PRIO("NominateHighestPriority"),
@ -90,4 +93,19 @@ public enum NominationStrategy
{ {
return strategyName; return strategyName;
} }
/**
* @return the {@link NominationStrategy} with name equal to the given
* string, or {@code null} if there is no such strategy.
* @param string the name of the strategy.
*/
public static NominationStrategy fromString(String string)
{
for (NominationStrategy strategy : NominationStrategy.values())
{
if (strategy.strategyName.equals(string))
return strategy;
}
return null;
}
} }

View File

@ -96,7 +96,7 @@ public class RemoteCandidate
String foundation, String foundation,
long priority, long priority,
RemoteCandidate relatedCandidate, RemoteCandidate relatedCandidate,
String ufrag) String ufrag)
{ {
super(transportAddress, parentComponent, type, relatedCandidate); super(transportAddress, parentComponent, type, relatedCandidate);
setFoundation(foundation); setFoundation(foundation);

View File

@ -123,7 +123,7 @@ public class ServerReflexiveCandidate
{ {
super.free(); super.free();
if(stunHarvest != null) if (stunHarvest != null)
stunHarvest.close(); stunHarvest.close();
} }
} }

View File

@ -80,7 +80,7 @@ public class UPNPCandidate
} }
IceSocketWrapper socket = getCandidateIceSocketWrapper(); IceSocketWrapper socket = getCandidateIceSocketWrapper();
if(socket != null) if (socket != null)
{ {
socket.close(); socket.close();
} }

View File

@ -19,7 +19,6 @@ package org.ice4j.ice.harvest;
import org.ice4j.*; import org.ice4j.*;
import org.ice4j.ice.*; import org.ice4j.ice.*;
import org.ice4j.message.*;
import org.ice4j.socket.*; import org.ice4j.socket.*;
import java.io.*; import java.io.*;
@ -29,6 +28,8 @@ import java.nio.channels.*;
import java.util.*; import java.util.*;
import java.util.logging.*; import java.util.logging.*;
import static org.ice4j.ice.harvest.HarvestConfig.config;
/** /**
* An abstract class that binds on a set of sockets and accepts sessions that * An abstract class that binds on a set of sockets and accepts sessions that
* start with a STUN Binding Request (preceded by an optional fake SSL * start with a STUN Binding Request (preceded by an optional fake SSL
@ -59,7 +60,15 @@ public abstract class AbstractTcpListener
*/ */
static void closeNoExceptions(Channel channel) static void closeNoExceptions(Channel channel)
{ {
MuxServerSocketChannelFactory.closeNoExceptions(channel); try
{
channel.close();
}
catch (IOException ioe)
{
// The whole idea of the method is to close a specific Channel
// without caring about any possible IOException.
}
} }
/** /**
@ -73,7 +82,6 @@ public abstract class AbstractTcpListener
private static List<TransportAddress> getLocalAddresses( private static List<TransportAddress> getLocalAddresses(
int port, int port,
List<NetworkInterface> interfaces) List<NetworkInterface> interfaces)
throws IOException
{ {
List<TransportAddress> addresses = new LinkedList<>(); List<TransportAddress> addresses = new LinkedList<>();
@ -89,7 +97,7 @@ public abstract class AbstractTcpListener
Enumeration<InetAddress> ifaceAddresses = iface.getInetAddresses(); Enumeration<InetAddress> ifaceAddresses = iface.getInetAddresses();
while(ifaceAddresses.hasMoreElements()) while (ifaceAddresses.hasMoreElements())
{ {
InetAddress addr = ifaceAddresses.nextElement(); InetAddress addr = ifaceAddresses.nextElement();
@ -99,83 +107,6 @@ public abstract class AbstractTcpListener
return addresses; return addresses;
} }
/**
* Determines whether a specific {@link DatagramPacket} is the first
* expected (i.e. supported) to be received from an accepted
* {@link SocketChannel} by this {@link AbstractTcpListener}. This is true
* if it is contains the hard-coded SSL client handshake (
* {@link GoogleTurnSSLCandidateHarvester#SSL_CLIENT_HANDSHAKE}), or
* a STUN Binding Request.
*
* @param p the {@code DatagramPacket} to examine
* @return {@code true} if {@code p} looks like the first
* {@code DatagramPacket} expected to be received from an accepted
* {@code SocketChannel} by this {@code TcpHarvester};
* otherwise, {@code false}
*/
private static boolean isFirstDatagramPacket(DatagramPacket p)
{
int len = p.getLength();
boolean b = false;
if (len > 0)
{
byte[] buf = p.getData();
int off = p.getOffset();
// Check for Google TURN SSLTCP
final byte[] googleTurnSslTcp
= GoogleTurnSSLCandidateHarvester.SSL_CLIENT_HANDSHAKE;
if (len >= googleTurnSslTcp.length)
{
b = true;
for (int i = 0, iEnd = googleTurnSslTcp.length, j = off;
i < iEnd;
i++, j++)
{
if (googleTurnSslTcp[i] != buf[j])
{
b = false;
break;
}
}
}
// nothing found, lets check for stun binding requests
if (!b)
{
// 2 bytes uint16 length
// STUN Binding request:
// 2 bits 00
// 14 bits STUN Messsage Type
// 2 bytes Message Length
// 4 bytes Magic Cookie
// RFC 5389: For example, a Binding request has class=0b00
// (request) and method=0b000000000001 (Binding) and is encoded
// into the first 16 bits as 0x0001.
if (len >= 10 && buf[off + 2] == 0 && buf[off + 3] == 1)
{
final byte[] magicCookie = Message.MAGIC_COOKIE;
b = true;
for (int i = 0, iEnd = magicCookie.length, j = off + 6;
i < iEnd;
i++, j++)
{
if (magicCookie[i] != buf[j])
{
b = false;
break;
}
}
}
}
}
return b;
}
/** /**
* The thread which <tt>accept</tt>s TCP connections from the sockets in * The thread which <tt>accept</tt>s TCP connections from the sockets in
* {@link #serverSocketChannels}. * {@link #serverSocketChannels}.
@ -216,12 +147,6 @@ public abstract class AbstractTcpListener
private final List<ServerSocketChannel> serverSocketChannels private final List<ServerSocketChannel> serverSocketChannels
= new LinkedList<>(); = new LinkedList<>();
/**
* The object used to synchronize access to the collection of sessions that
* the implementation of this class uses.
*/
protected final Object sessionsSyncRoot = new Object();
/** /**
* Initializes a new <tt>TcpHarvester</tt>, which is to * Initializes a new <tt>TcpHarvester</tt>, which is to
* listen on port number <tt>port</tt> on all IP addresses on all available * listen on port number <tt>port</tt> on all IP addresses on all available
@ -283,13 +208,6 @@ public abstract class AbstractTcpListener
protected void addLocalAddresses(List<TransportAddress> transportAddresses) protected void addLocalAddresses(List<TransportAddress> transportAddresses)
throws IOException throws IOException
{ {
boolean useIPv6 = !StackProperties.getBoolean(
StackProperties.DISABLE_IPv6,
false);
boolean useLinkLocalAddresses = !StackProperties.getBoolean(
StackProperties.DISABLE_LINK_LOCAL_ADDRESSES,
false);
// White list from the configuration // White list from the configuration
String[] allowedAddressesStr String[] allowedAddressesStr
= StackProperties.getStringArray(StackProperties.ALLOWED_ADDRESSES, = StackProperties.getStringArray(StackProperties.ALLOWED_ADDRESSES,
@ -301,8 +219,7 @@ public abstract class AbstractTcpListener
allowedAddresses = new InetAddress[allowedAddressesStr.length]; allowedAddresses = new InetAddress[allowedAddressesStr.length];
for (int i = 0; i < allowedAddressesStr.length; i++) for (int i = 0; i < allowedAddressesStr.length; i++)
{ {
allowedAddresses[i] allowedAddresses[i] = InetAddress.getByName(allowedAddressesStr[i]);
= InetAddress.getByName(allowedAddressesStr[i]);
} }
} }
@ -332,14 +249,12 @@ public abstract class AbstractTcpListener
continue; continue;
} }
if (!useIPv6 && (address instanceof Inet6Address)) if (!config.useIpv6() && (address instanceof Inet6Address))
continue; continue;
if (!useLinkLocalAddresses if (!config.useLinkLocalAddresses() && address.isLinkLocalAddress())
&& address.isLinkLocalAddress())
{ {
logger.info("Not using link-local address " + address +" for" logger.info("Not using link-local address " + address +" for TCP candidates.");
+ " TCP candidates.");
continue; continue;
} }
@ -440,21 +355,7 @@ public abstract class AbstractTcpListener
throws IOException throws IOException
{ {
ServerSocketChannel channel = MuxServerSocketChannelFactory ServerSocketChannel channel = MuxServerSocketChannelFactory
.openAndBindMuxServerSocketChannel( .openAndBindServerSocketChannel(null, address, 0);
/* properties */ null,
address,
/* backlog */ 0,
new DatagramPacketFilter()
{
/**
* {@inheritDoc}
*/
@Override
public boolean accept(DatagramPacket p)
{
return isFirstDatagramPacket(p);
}
});
serverSocketChannels.add(channel); serverSocketChannels.add(channel);
} }
@ -465,8 +366,6 @@ public abstract class AbstractTcpListener
* @param ufrag the local username fragment for the session. * @param ufrag the local username fragment for the session.
* @param pushback the first "datagram" (RFC4571-framed), already read from * @param pushback the first "datagram" (RFC4571-framed), already read from
* the socket's stream. * the socket's stream.
* @throws IllegalStateException
* @throws IOException
*/ */
protected abstract void acceptSession( protected abstract void acceptSession(
Socket socket, String ufrag, DatagramPacket pushback) Socket socket, String ufrag, DatagramPacket pushback)
@ -606,7 +505,9 @@ public abstract class AbstractTcpListener
selector.close(); selector.close();
} }
catch (IOException ioe) catch (IOException ioe)
{} {
// ignore
}
} }
} }
@ -621,11 +522,6 @@ public abstract class AbstractTcpListener
*/ */
public final SocketChannel channel; public final SocketChannel channel;
/**
* The time the channel was last found to be active.
*/
long lastActive = System.currentTimeMillis();
/** /**
* The buffer which stores the data so far read from the channel. * The buffer which stores the data so far read from the channel.
*/ */
@ -791,11 +687,8 @@ public abstract class AbstractTcpListener
{ {
/** /**
* Initializes a new <tt>ReadThread</tt>. * Initializes a new <tt>ReadThread</tt>.
*
* @throws IOException if the selector to be used fails to open.
*/ */
public ReadThread() public ReadThread()
throws IOException
{ {
setName("TcpHarvester ReadThread"); setName("TcpHarvester ReadThread");
setDaemon(true); setDaemon(true);
@ -829,50 +722,6 @@ public abstract class AbstractTcpListener
} }
} }
/**
* Closes any inactive channels registered with {@link #readSelector}.
* A channel is considered inactive if it hasn't been available for
* reading for
* {@link MuxServerSocketChannelFactory#SOCKET_CHANNEL_READ_TIMEOUT}
* milliseconds.
*/
private void cleanup()
{
long now = System.currentTimeMillis();
for (SelectionKey key : readSelector.keys())
{
// An invalid key specifies that either the channel was closed
// (in which case we do not have to do anything else to it) or
// that we no longer control the channel (i.e. we do not want to
// do anything else to it).
if (!key.isValid())
continue;
ChannelDesc channelDesc = (ChannelDesc) key.attachment();
if (channelDesc == null)
continue;
long lastActive = channelDesc.lastActive;
if (lastActive != -1
&& now - lastActive
> MuxServerSocketChannelFactory
.SOCKET_CHANNEL_READ_TIMEOUT)
{
// De-register from the Selector.
key.cancel();
SocketChannel channel = channelDesc.channel;
logger.info("Read timeout for socket: " + channel.socket());
closeNoExceptions(channel);
}
}
}
/** /**
* Tries to read, without blocking, from <tt>channel</tt> to its * Tries to read, without blocking, from <tt>channel</tt> to its
* buffer. If after reading the buffer is filled, handles the data in * buffer. If after reading the buffer is filled, handles the data in
@ -923,8 +772,6 @@ public abstract class AbstractTcpListener
if (read == -1) if (read == -1)
throw new IOException("End of stream!"); throw new IOException("End of stream!");
else if (read > 0)
channel.lastActive = System.currentTimeMillis();
if (!channel.buffer.hasRemaining()) if (!channel.buffer.hasRemaining())
{ {
@ -964,7 +811,7 @@ public abstract class AbstractTcpListener
bytesRead, 2, bytesRead.length); bytesRead, 2, bytesRead.length);
// if we had read enough data // if we had read enough data
if(channel.length <= bytesRead.length - 2) if (channel.length <= bytesRead.length - 2)
{ {
processFirstDatagram( processFirstDatagram(
preBuffered, channel, key); preBuffered, channel, key);
@ -999,7 +846,7 @@ public abstract class AbstractTcpListener
channel.buffer.flip(); channel.buffer.flip();
channel.buffer.get(bytesRead); channel.buffer.get(bytesRead);
if(channel.preBuffered != null) if (channel.preBuffered != null)
{ {
// will store preBuffered and currently read data // will store preBuffered and currently read data
byte[] newBytesRead = new byte[ byte[] newBytesRead = new byte[
@ -1110,9 +957,6 @@ public abstract class AbstractTcpListener
break; break;
} }
// clean up stale channels
cleanup();
checkForNewChannels(); checkForNewChannels();
for (SelectionKey key : readSelector.keys()) for (SelectionKey key : readSelector.keys())
@ -1172,7 +1016,9 @@ public abstract class AbstractTcpListener
readSelector.close(); readSelector.close();
} }
catch (IOException ioe) catch (IOException ioe)
{} {
// ignore
}
} }
} }
} }

View File

@ -20,15 +20,18 @@ package org.ice4j.ice.harvest;
import org.ice4j.*; import org.ice4j.*;
import org.ice4j.attribute.*; import org.ice4j.attribute.*;
import org.ice4j.message.*; import org.ice4j.message.*;
import org.ice4j.util.*; import org.jitsi.utils.queue.*;
import java.io.*; import java.io.*;
import java.net.*; import java.net.*;
import java.time.*;
import java.util.*; import java.util.*;
import java.util.concurrent.*; import java.util.concurrent.*;
import java.util.logging.*; import java.util.logging.*;
import java.util.logging.Logger; import java.util.logging.Logger;
import static org.ice4j.ice.harvest.HarvestConfig.config;
/** /**
* A class which holds a {@link DatagramSocket} and runs a thread * A class which holds a {@link DatagramSocket} and runs a thread
* ({@link #thread}) which perpetually reads from it. * ({@link #thread}) which perpetually reads from it.
@ -43,14 +46,6 @@ import java.util.logging.Logger;
*/ */
public abstract class AbstractUdpListener public abstract class AbstractUdpListener
{ {
/**
* The name of the property which controls the size of the receive buffer
* which {@link SinglePortUdpHarvester} will request for the sockets that
* it creates.
*/
public static final String SO_RCVBUF_PNAME
= AbstractUdpListener.class.getName() + ".SO_RCVBUF";
/** /**
* Our class logger. * Our class logger.
*/ */
@ -131,10 +126,7 @@ public abstract class AbstractUdpListener
try try
{ {
Message stunMessage Message stunMessage = Message.decode(buf, off, len);
= Message.decode(buf,
(char) off,
(char) len);
if (stunMessage.getMessageType() if (stunMessage.getMessageType()
!= Message.BINDING_REQUEST) != Message.BINDING_REQUEST)
@ -204,41 +196,51 @@ public abstract class AbstractUdpListener
/** /**
* Initializes a new <tt>SinglePortUdpHarvester</tt> instance which is to * Initializes a new <tt>SinglePortUdpHarvester</tt> instance which is to
* bind on the specified local address. * bind on the specified local address.
* @param localAddress the address to bind to. * @param localAddress the address to bind to. If the port is 0 an ephemeral port will be chosen by the OS and the
* AbstractUdpListener.localAddress will reflect the allocated port.
* @throws IOException if initialization fails. * @throws IOException if initialization fails.
*/ */
protected AbstractUdpListener(TransportAddress localAddress) protected AbstractUdpListener(TransportAddress localAddress)
throws IOException throws IOException
{ {
TransportAddress tempAddress = localAddress;
boolean bindWildcard = StackProperties.getBoolean( boolean bindWildcard = StackProperties.getBoolean(
StackProperties.BIND_WILDCARD, StackProperties.BIND_WILDCARD,
false); false);
if (bindWildcard) if (bindWildcard)
{ {
this.localAddress = new TransportAddress( tempAddress = new TransportAddress(
(InetAddress) null, (InetAddress) null,
localAddress.getPort(), localAddress.getPort(),
localAddress.getTransport() localAddress.getTransport()
); );
} }
else
{
this.localAddress = localAddress;
}
socket = new DatagramSocket( this.localAddress ); socket = new DatagramSocket( tempAddress );
int receiveBufferSize = StackProperties.getInt(SO_RCVBUF_PNAME, -1); Integer receiveBufferSize = config.udpReceiveBufferSize();
if (receiveBufferSize > 0) if (receiveBufferSize != null)
{ {
socket.setReceiveBufferSize(receiveBufferSize); socket.setReceiveBufferSize(receiveBufferSize);
} }
/* Update the port number if needed. */
if (localAddress.getPort() == 0)
{
tempAddress = new TransportAddress(
tempAddress.getAddress(),
socket.getLocalPort(),
tempAddress.getTransport()
);
}
this.localAddress = tempAddress;
String logMessage String logMessage
= "Initialized AbstractUdpListener with address " + this.localAddress; = "Initialized AbstractUdpListener with address " + this.localAddress;
logMessage += ". Receive buffer size " + socket.getReceiveBufferSize(); logMessage += ". Receive buffer size " + socket.getReceiveBufferSize();
if (receiveBufferSize > 0) if (receiveBufferSize != null)
{ {
logMessage += " (asked for " + receiveBufferSize + ")"; logMessage += " (asked for " + receiveBufferSize + ")";
} }
@ -253,12 +255,16 @@ public abstract class AbstractUdpListener
} }
}; };
thread.setName(AbstractUdpListener.class.getName() + " thread for " thread.setName(AbstractUdpListener.class.getName() + " thread for " + this.localAddress);
+ this.localAddress);
thread.setDaemon(true); thread.setDaemon(true);
thread.start(); thread.start();
} }
public TransportAddress getLocalAddress()
{
return localAddress;
}
/** /**
* Triggers the termination of the threads of this instance. * Triggers the termination of the threads of this instance.
*/ */
@ -391,12 +397,13 @@ public abstract class AbstractUdpListener
* *
* @param remoteAddress the remote address with which to associate the new * @param remoteAddress the remote address with which to associate the new
* socket instance. * socket instance.
* @param ufrag The username fragment associated with the socket.
* @return the created socket instance. * @return the created socket instance.
*/ */
protected MySocket addSocket(InetSocketAddress remoteAddress) protected MySocket addSocket(InetSocketAddress remoteAddress, String ufrag)
throws SocketException throws SocketException
{ {
MySocket newSocket = new MySocket(remoteAddress); MySocket newSocket = new MySocket(remoteAddress, ufrag);
sockets.put(remoteAddress, newSocket); sockets.put(remoteAddress, newSocket);
return newSocket; return newSocket;
} }
@ -440,6 +447,8 @@ public abstract class AbstractUdpListener
*/ */
private boolean closed = false; private boolean closed = false;
private final String ufrag;
/** /**
* Initializes a new <tt>MySocket</tt> instance with the given * Initializes a new <tt>MySocket</tt> instance with the given
* remote address. * remote address.
@ -447,17 +456,17 @@ public abstract class AbstractUdpListener
* new instance. * new instance.
* @throws SocketException * @throws SocketException
*/ */
MySocket(InetSocketAddress remoteAddress) MySocket(InetSocketAddress remoteAddress, String ufrag)
throws SocketException throws SocketException
{ {
// unbound // unbound
super((SocketAddress)null); super((SocketAddress)null);
this.ufrag = ufrag;
this.remoteAddress = remoteAddress; this.remoteAddress = remoteAddress;
if (logger.isLoggable(Level.FINEST)) if (logger.isLoggable(Level.FINEST))
{ {
queueStatistics = new QueueStatistics( queueStatistics = new QueueStatistics(QUEUE_SIZE, Clock.systemUTC());
"SinglePort" + remoteAddress.toString().replace('/', '-'));
} }
else else
{ {
@ -477,10 +486,12 @@ public abstract class AbstractUdpListener
// receivers can notice the loss earlier. // receivers can notice the loss earlier.
if (queue.size() == QUEUE_SIZE) if (queue.size() == QUEUE_SIZE)
{ {
logger.info("Dropping a packet because the queue is full."); logger.info(
"Dropping a packet because the queue is full. Remote address = "
+ remoteAddress + " ufrag=" + ufrag);
if (queueStatistics != null) if (queueStatistics != null)
{ {
queueStatistics.remove(System.currentTimeMillis()); queueStatistics.dropped();
} }
queue.poll(); queue.poll();
} }
@ -488,7 +499,7 @@ public abstract class AbstractUdpListener
queue.offer(buf); queue.offer(buf);
if (queueStatistics != null) if (queueStatistics != null)
{ {
queueStatistics.add(System.currentTimeMillis()); queueStatistics.added();
} }
queue.notify(); queue.notify();
@ -626,9 +637,9 @@ public abstract class AbstractUdpListener
} }
buf = queue.poll(); buf = queue.poll();
if (queueStatistics != null) if (buf != null && queueStatistics != null)
{ {
queueStatistics.remove(System.currentTimeMillis()); queueStatistics.removed(queue.size(), null);
} }
} }
} }

View File

@ -83,7 +83,7 @@ public class AwsCandidateHarvester
*/ */
public AwsCandidateHarvester() public AwsCandidateHarvester()
{ {
super(); super("aws");
} }
/** /**

View File

@ -198,7 +198,7 @@ public class CandidateHarvesterSet
{ {
try try
{ {
future.get(StackProperties.getInt(StackProperties.HARVESTING_TIMEOUT, 15), TimeUnit.SECONDS); future.get(HarvestConfig.config.timeout().toMillis(), TimeUnit.MILLISECONDS);
break; break;
} }
catch (TimeoutException te) catch (TimeoutException te)

View File

@ -96,7 +96,7 @@ class CandidateHarvesterSetElement
{ {
setEnabled(false); setEnabled(false);
} }
else if(trickleCallback != null) else if (trickleCallback != null)
{ {
trickleCallback.onIceCandidates(candidates); trickleCallback.onIceCandidates(candidates);
} }

View File

@ -105,7 +105,7 @@ public class GoogleTurnCandidateHarvest
Attribute attribute Attribute attribute
= response.getAttribute(Attribute.MAPPED_ADDRESS); = response.getAttribute(Attribute.MAPPED_ADDRESS);
if(attribute != null) if (attribute != null)
{ {
TransportAddress relayedAddress TransportAddress relayedAddress
= ((MappedAddressAttribute) attribute).getAddress(); = ((MappedAddressAttribute) attribute).getAddress();

View File

@ -279,7 +279,7 @@ public class GoogleTurnSSLCandidateHarvester
outputStream = null; outputStream = null;
inputStream = null; inputStream = null;
if(Arrays.equals(data, SSL_SERVER_HANDSHAKE)) if (Arrays.equals(data, SSL_SERVER_HANDSHAKE))
{ {
return true; return true;
} }

View File

@ -75,7 +75,7 @@ public class HarvestStatistics
protected void stopHarvestTiming(Collection<LocalCandidate> harvest) protected void stopHarvestTiming(Collection<LocalCandidate> harvest)
{ {
//count total candidates //count total candidates
if(harvest != null) if (harvest != null)
stopHarvestTiming(harvest.size()); stopHarvestTiming(harvest.size());
else else
stopHarvestTiming(0); stopHarvestTiming(0);
@ -108,13 +108,13 @@ public class HarvestStatistics
*/ */
public long getHarvestDuration() public long getHarvestDuration()
{ {
if(this.lastStartHarvestingTime != -1) if (this.lastStartHarvestingTime != -1)
{ {
long currentHarvestingTime long currentHarvestingTime
= System.currentTimeMillis() - lastStartHarvestingTime; = System.currentTimeMillis() - lastStartHarvestingTime;
// Retest here, while the harvesting may be end while computing the // Retest here, while the harvesting may be end while computing the
// harvesting time. // harvesting time.
if(this.lastStartHarvestingTime != -1) if (this.lastStartHarvestingTime != -1)
{ {
return this.lastHarvestingTime + currentHarvestingTime; return this.lastHarvestingTime + currentHarvestingTime;
} }

View File

@ -26,6 +26,8 @@ import org.ice4j.*;
import org.ice4j.ice.*; import org.ice4j.ice.*;
import org.ice4j.socket.*; import org.ice4j.socket.*;
import static org.ice4j.ice.harvest.HarvestConfig.config;
/** /**
* A <tt>HostCandidateHarvester</tt> gathers host <tt>Candidate</tt>s for a * A <tt>HostCandidateHarvester</tt> gathers host <tt>Candidate</tt>s for a
* specified {@link org.ice4j.ice.Component}. Most <tt>CandidateHarvester</tt>s * specified {@link org.ice4j.ice.Component}. Most <tt>CandidateHarvester</tt>s
@ -229,13 +231,6 @@ public class HostCandidateHarvester
public static List<InetAddress> getAllAllowedAddresses() public static List<InetAddress> getAllAllowedAddresses()
{ {
List<InetAddress> addresses = new LinkedList<>(); List<InetAddress> addresses = new LinkedList<>();
boolean isIPv6Disabled = StackProperties.getBoolean(
StackProperties.DISABLE_IPv6,
false);
boolean isLinkLocalAddressesDisabled = StackProperties.getBoolean(
StackProperties.DISABLE_LINK_LOCAL_ADDRESSES,
false);
try try
{ {
for (NetworkInterface iface for (NetworkInterface iface
@ -257,10 +252,9 @@ public class HostCandidateHarvester
if (!isAddressAllowed(address)) if (!isAddressAllowed(address))
continue; continue;
if (isIPv6Disabled && address instanceof Inet6Address) if (!config.useIpv6() && address instanceof Inet6Address)
continue; continue;
if (isLinkLocalAddressesDisabled if (!config.useLinkLocalAddresses() && address.isLinkLocalAddress())
&& address.isLinkLocalAddress())
continue; continue;
addresses.add(address); addresses.add(address);
@ -282,6 +276,8 @@ public class HostCandidateHarvester
* If that fails we will move through all ports between <tt>minPort</tt> and * If that fails we will move through all ports between <tt>minPort</tt> and
* <tt>maxPort</tt> and give up if still can't find a free port. * <tt>maxPort</tt> and give up if still can't find a free port.
* *
* If 0, 0, 0 are specified for preferred, min and max port, an ephemeral port will be used instead.
*
* @param component the {@link Component} that we'd like to gather candidate * @param component the {@link Component} that we'd like to gather candidate
* addresses for. * addresses for.
* @param preferredPort the port number that should be tried first when * @param preferredPort the port number that should be tried first when
@ -308,21 +304,11 @@ public class HostCandidateHarvester
{ {
harvestStatistics.startHarvestTiming(); harvestStatistics.startHarvestTiming();
Enumeration<NetworkInterface> interfaces Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
= NetworkInterface.getNetworkInterfaces();
boolean isIPv6Disabled = StackProperties.getBoolean( if (transport != Transport.UDP && transport != Transport.TCP)
StackProperties.DISABLE_IPv6,
false);
boolean isLinkLocalAddressesDisabled = StackProperties.getBoolean(
StackProperties.DISABLE_LINK_LOCAL_ADDRESSES,
false);
if(transport != Transport.UDP && transport != Transport.TCP)
{ {
throw new IllegalArgumentException( throw new IllegalArgumentException("Transport protocol not supported: " + transport);
"Transport protocol not supported: " + transport);
} }
boolean boundAtLeastOneSocket = false; boolean boundAtLeastOneSocket = false;
@ -343,7 +329,7 @@ public class HostCandidateHarvester
Enumeration<InetAddress> addresses = iface.getInetAddresses(); Enumeration<InetAddress> addresses = iface.getInetAddresses();
while(addresses.hasMoreElements()) while (addresses.hasMoreElements())
{ {
InetAddress addr = addresses.nextElement(); InetAddress addr = addresses.nextElement();
@ -352,27 +338,25 @@ public class HostCandidateHarvester
continue; continue;
} }
if (isLinkLocalAddressesDisabled if (!config.useLinkLocalAddresses() && addr.isLinkLocalAddress())
&& addr.isLinkLocalAddress())
{ {
continue; continue;
} }
foundAtLeastOneUsableAddress = true; foundAtLeastOneUsableAddress = true;
if((addr instanceof Inet4Address) || !isIPv6Disabled) if ((addr instanceof Inet4Address) || config.useIpv6())
{ {
IceSocketWrapper sock = null; IceSocketWrapper sock = null;
try try
{ {
if(transport == Transport.UDP) if (transport == Transport.UDP)
{ {
sock = createDatagramSocket( sock = createDatagramSocket(addr, preferredPort, minPort, maxPort);
addr, preferredPort, minPort, maxPort);
boundAtLeastOneSocket = true; boundAtLeastOneSocket = true;
} }
else if(transport == Transport.TCP) else if (transport == Transport.TCP)
{ {
if(addr instanceof Inet6Address) if (addr instanceof Inet6Address)
continue; continue;
sock = createServerSocket( sock = createServerSocket(
addr, addr,
@ -402,10 +386,8 @@ public class HostCandidateHarvester
continue; continue;
} }
HostCandidate candidate HostCandidate candidate = new HostCandidate(sock, component, transport);
= new HostCandidate(sock, component, transport); candidate.setVirtual(NetworkUtils.isInterfaceVirtual(iface));
candidate.setVirtual(
NetworkUtils.isInterfaceVirtual(iface));
component.addLocalCandidate(candidate); component.addLocalCandidate(candidate);
if (transport == Transport.TCP) if (transport == Transport.TCP)
@ -421,8 +403,7 @@ public class HostCandidateHarvester
// them as well while harvesting reflexive candidates. // them as well while harvesting reflexive candidates.
createAndRegisterStunSocket(candidate); createAndRegisterStunSocket(candidate);
ComponentSocket componentSocket ComponentSocket componentSocket = component.getComponentSocket();
= component.getComponentSocket();
if (componentSocket != null) if (componentSocket != null)
{ {
componentSocket.add(sock); componentSocket.add(sock);
@ -445,8 +426,7 @@ public class HostCandidateHarvester
+ foundAtLeastOneUsableAddress); + foundAtLeastOneUsableAddress);
} }
this.harvestStatistics this.harvestStatistics.stopHarvestTiming(component.getLocalCandidateCount());
.stopHarvestTiming(component.getLocalCandidateCount());
} }
/** /**
@ -461,7 +441,7 @@ public class HostCandidateHarvester
* <tt>org.ice4j.ice.harvest.BLOCKED_INTERFACES</tt> list. It returns * <tt>org.ice4j.ice.harvest.BLOCKED_INTERFACES</tt> list. It returns
* <tt>false</tt> otherwise. * <tt>false</tt> otherwise.
*/ */
static boolean isInterfaceAllowed(NetworkInterface iface) public static boolean isInterfaceAllowed(NetworkInterface iface)
{ {
if (iface == null) if (iface == null)
throw new IllegalArgumentException("iface cannot be null"); throw new IllegalArgumentException("iface cannot be null");
@ -541,6 +521,8 @@ public class HostCandidateHarvester
* <tt>localAddress</tt> and a port in the range specified by the * <tt>localAddress</tt> and a port in the range specified by the
* <tt>minPort</tt> and <tt>maxPort</tt> parameters. * <tt>minPort</tt> and <tt>maxPort</tt> parameters.
* *
* If 0, 0, 0 are specified for preferred, min and max port, an ephemeral port will be used instead.
*
* @param laddr the address that we'd like to bind the socket on. * @param laddr the address that we'd like to bind the socket on.
* @param preferredPort the port number that we should try to bind to first. * @param preferredPort the port number that we should try to bind to first.
* @param minPort the port number where we should first try to bind before * @param minPort the port number where we should first try to bind before
@ -567,7 +549,18 @@ public class HostCandidateHarvester
BindException BindException
{ {
// make sure port numbers are valid // make sure port numbers are valid
this.checkPorts(preferredPort, minPort, maxPort); boolean ephemeral = checkPorts(preferredPort, minPort, maxPort);
if (ephemeral)
{
ServerSocket socket = new ServerSocket();
socket.setReuseAddress(true);
socket.bind(new InetSocketAddress(laddr, 0));
if (logger.isLoggable(Level.FINEST))
{
logger.finest("Bound using an ephemeral port to " + socket.getLocalSocketAddress());
}
return new IceTcpServerSocketWrapper(new DelegatingServerSocket(socket), component);
}
int bindRetries = StackProperties.getInt( int bindRetries = StackProperties.getInt(
StackProperties.BIND_RETRIES, StackProperties.BIND_RETRIES,
@ -586,7 +579,7 @@ public class HostCandidateHarvester
new DelegatingServerSocket(sock), new DelegatingServerSocket(sock),
component); component);
if(logger.isLoggable(Level.FINEST)) if (logger.isLoggable(Level.FINEST))
{ {
logger.log( logger.log(
Level.FINEST, Level.FINEST,
@ -611,8 +604,7 @@ public class HostCandidateHarvester
port = minPort; port = minPort;
} }
throw new BindException("Could not bind to any port between " throw new BindException("Could not bind to any port between " + minPort + " and " + (port - 1));
+ minPort + " and " + (port - 1));
} }
/** /**
@ -627,6 +619,8 @@ public class HostCandidateHarvester
* start over again at <tt>minPort</tt> and keep going until we run out of * start over again at <tt>minPort</tt> and keep going until we run out of
* retries. * retries.
* *
* If 0, 0, 0 are specified for preferred, min and max port, an ephemeral port will be used instead.
*
* @param laddr the address that we'd like to bind the socket on. * @param laddr the address that we'd like to bind the socket on.
* @param preferredPort the port number that we should try to bind to first. * @param preferredPort the port number that we should try to bind to first.
* @param minPort the port number where we should first try to bind before * @param minPort the port number where we should first try to bind before
@ -654,7 +648,16 @@ public class HostCandidateHarvester
BindException BindException
{ {
// make sure port numbers are valid. // make sure port numbers are valid.
this.checkPorts(preferredPort, minPort, maxPort); boolean ephemeral = checkPorts(preferredPort, minPort, maxPort);
if (ephemeral)
{
DatagramSocket socket = new MultiplexingDatagramSocket(0, laddr);
if (logger.isLoggable(Level.FINEST))
{
logger.finest("Bound using ephemeral port to " + socket.getLocalSocketAddress());
}
return new IceUdpSocketWrapper(socket);
}
int bindRetries = StackProperties.getInt( int bindRetries = StackProperties.getInt(
StackProperties.BIND_RETRIES, StackProperties.BIND_RETRIES,
@ -669,7 +672,7 @@ public class HostCandidateHarvester
= new IceUdpSocketWrapper(new = new IceUdpSocketWrapper(new
MultiplexingDatagramSocket(port, laddr)); MultiplexingDatagramSocket(port, laddr));
if(logger.isLoggable(Level.FINEST)) if (logger.isLoggable(Level.FINEST))
{ {
logger.log( logger.log(
Level.FINEST, Level.FINEST,
@ -716,8 +719,10 @@ public class HostCandidateHarvester
} }
/** /**
* Checks if the different ports are correctly set. If not, throws an * Checks if the different ports are correctly set. If not, throws {@link IllegalArgumentException}. The
* IllegalArgumentException. * special values 0, 0, 0 for the parameters are interpreted as "use an ephemeral port".
*
* @return {@code true} if the params specify that an ephemeral port should be used, and {@code false} otherwise.
* *
* @param preferredPort the port number that we should try to bind to first. * @param preferredPort the port number that we should try to bind to first.
* @param minPort the port number where we should first try to bind before * @param minPort the port number where we should first try to bind before
@ -729,9 +734,14 @@ public class HostCandidateHarvester
* <tt>maxPort</tt> is not a valid port number or if <tt>minPort</tt> is * <tt>maxPort</tt> is not a valid port number or if <tt>minPort</tt> is
* greater than <tt>maxPort</tt>. * greater than <tt>maxPort</tt>.
*/ */
private void checkPorts(int preferredPort, int minPort, int maxPort) private static boolean checkPorts(int preferredPort, int minPort, int maxPort)
throws IllegalArgumentException throws IllegalArgumentException
{ {
if (preferredPort == 0 && minPort == 0 && maxPort == 0)
{
return true;
}
// make sure port numbers are valid // make sure port numbers are valid
if (!NetworkUtils.isValidPortNumber(minPort) if (!NetworkUtils.isValidPortNumber(minPort)
|| !NetworkUtils.isValidPortNumber(maxPort)) || !NetworkUtils.isValidPortNumber(maxPort))
@ -756,6 +766,8 @@ public class HostCandidateHarvester
+") must be between minPort (" + minPort +") must be between minPort (" + minPort
+ ") and maxPort (" + maxPort + ")"); + ") and maxPort (" + maxPort + ")");
} }
return false;
} }
/** /**

View File

@ -1,179 +0,0 @@
/*
* ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
*
* Copyright @ 2015 Atlassian Pty Ltd
*
* 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.
*/
package org.ice4j.ice.harvest;
import org.ice4j.*;
import org.ice4j.ice.*;
import java.util.*;
import java.util.logging.*;
/**
* Uses a list of addresses as a predefined static mask in order to generate
* {@link TransportAddress}es. This harvester is meant for use in situations
* where servers are deployed behind a NAT or in a DMZ with static port mapping.
* <p>
* Every time the {@link #harvest(Component)} method is called, the mapping
* harvester will return a list of candidates that provide masked alternatives
* for every host candidate in the component. Kind of like a STUN server.
* <p>
* Example: You run this on a server with address 192.168.0.1, that is behind
* a NAT with public IP: 93.184.216.119. You allocate a host candidate
* 192.168.0.1/UDP/5000. This harvester is going to then generate an address
* 93.184.216.119/UDP/5000
* <p>
* This harvester is instant and does not introduce any harvesting latency.
*
* @author Emil Ivov
*/
public class MappingCandidateHarvester
extends AbstractCandidateHarvester
{
/**
* The <tt>Logger</tt> used by the <tt>StunCandidateHarvester</tt> class and
* its instances for logging output.
*/
private static final Logger logger
= Logger.getLogger(StunCandidateHarvester.class.getName());
/**
* The addresses that we will use as a mask
*/
protected TransportAddress mask;
/**
* The addresses that we will be masking
*/
protected TransportAddress face;
/**
* Creates a mapping harvester with the specified <tt>mask</tt>
*
* @param mask the <tt>TransportAddress</tt>es that would be used as a mask.
* @param face the <tt>TransportAddress</tt>es that we will be masking.
*/
public MappingCandidateHarvester(TransportAddress mask,
TransportAddress face)
{
this.mask = Objects.requireNonNull(mask);
this.face = Objects.requireNonNull(face);
}
/**
* Initializes a {@link MappingCandidateHarvester} instance without
* specified addresses (only useful in subclasses which override
* {@link #getMask()} and {@link #getFace()}).
*/
protected MappingCandidateHarvester()
{
}
/**
* Maps all candidates to this harvester's mask and adds them to
* <tt>component</tt>.
*
* @param component the {@link Component} that we'd like to map candidates
* to.
* @return the <tt>LocalCandidate</tt>s gathered by this
* <tt>CandidateHarvester</tt> or <tt>null</tt> if no mask is specified.
*/
@Override
public Collection<LocalCandidate> harvest(Component component)
{
TransportAddress mask = getMask();
TransportAddress face = getFace();
if (face == null || mask == null)
{
logger.warning("Harvester not configured: face=" + face
+ ", mask=" + mask);
return null;
}
// Report the LocalCandidates gathered by this CandidateHarvester so
// that the harvest is sure to be considered successful.
Collection<LocalCandidate> candidates = new HashSet<>();
for (Candidate<?> cand : component.getLocalCandidates())
{
if (!(cand instanceof HostCandidate)
|| !cand.getTransportAddress().getHostAddress()
.equals(face.getHostAddress())
|| cand.getTransport() != face.getTransport())
{
continue;
}
HostCandidate hostCandidate = (HostCandidate) cand;
TransportAddress mappedAddress = new TransportAddress(
mask.getHostAddress(),
hostCandidate.getHostAddress().getPort(),
hostCandidate.getHostAddress().getTransport());
ServerReflexiveCandidate mappedCandidate
= new ServerReflexiveCandidate(
mappedAddress,
hostCandidate,
hostCandidate.getStunServerAddress(),
CandidateExtendedType.STATICALLY_MAPPED_CANDIDATE);
if (hostCandidate.isSSL())
mappedCandidate.setSSL(true);
//try to add the candidate to the component and then
//only add it to the harvest not redundant
if( !candidates.contains(mappedCandidate)
&& component.addLocalCandidate(mappedCandidate))
{
candidates.add(mappedCandidate);
}
}
return candidates;
}
/**
* Returns the public (mask) address, or null.
* @return the public (mask) address, or null.
*/
public TransportAddress getMask()
{
return mask;
}
/**
* Returns the local (face) address, or null.
* @return the local (face) address, or null.
*/
public TransportAddress getFace()
{
return face;
}
/**
* {@inheritDoc}
*/
@Override
public String toString()
{
TransportAddress face = getFace();
TransportAddress mask = getMask();
return
this.getClass().getName()
+ ", face=" + (face == null ? "null" : face.getAddress())
+ ", mask=" + (mask == null ? "null" : mask.getAddress());
}
}

View File

@ -16,12 +16,16 @@
package org.ice4j.ice.harvest; package org.ice4j.ice.harvest;
import org.ice4j.*; import org.ice4j.*;
import org.jetbrains.annotations.*;
import org.jitsi.utils.concurrent.*;
import java.net.*; import java.net.*;
import java.util.*; import java.util.*;
import java.util.concurrent.*; import java.util.concurrent.*;
import java.util.logging.*; import java.util.logging.*;
import static org.ice4j.ice.harvest.HarvestConfig.config;
/** /**
* Manages a static list of {@link MappingCandidateHarvester} instances, created * Manages a static list of {@link MappingCandidateHarvester} instances, created
* according to configuration provided as system properties. * according to configuration provided as system properties.
@ -37,44 +41,7 @@ public class MappingCandidateHarvesters
* The {@link Logger} used by the {@link MappingCandidateHarvesters} * The {@link Logger} used by the {@link MappingCandidateHarvesters}
* class for logging output. * class for logging output.
*/ */
private static final Logger logger private static final Logger logger = Logger.getLogger(MappingCandidateHarvesters.class.getName());
= Logger.getLogger(MappingCandidateHarvesters.class.getName());
/**
* The name of the property that specifies the local address, if any, for
* the pre-configured NAT harvester.
*/
public static final String NAT_HARVESTER_LOCAL_ADDRESS_PNAME
= "org.ice4j.ice.harvest.NAT_HARVESTER_LOCAL_ADDRESS";
/**
* The name of the property that specifies the public address, if any, for
* the pre-configured NAT harvester.
*/
public static final String NAT_HARVESTER_PUBLIC_ADDRESS_PNAME
= "org.ice4j.ice.harvest.NAT_HARVESTER_PUBLIC_ADDRESS";
/**
* The name of the property used to disable the AWS harvester.
*/
public static final String DISABLE_AWS_HARVESTER_PNAME
= "org.ice4j.ice.harvest.DISABLE_AWS_HARVESTER";
/**
* The name of the property which forces the use of the AWS harvester.
*/
public static final String FORCE_AWS_HARVESTER_PNAME
= "org.ice4j.ice.harvest.FORCE_AWS_HARVESTER";
/**
* The name of the property which contains the addresses of the STUN servers
* to use for the STUN mapping harvester. The property should contain a
* comma-separated list of addresses (pairs of IP address and port,
* separated by a colon). Example:
* {@code stun1.example.com:12345,stun2.example.com:23456}
*/
public static final String STUN_MAPPING_HARVESTER_ADDRESSES_PNAME
= "org.ice4j.ice.harvest.STUN_MAPPING_HARVESTER_ADDRESSES";
/** /**
* Whether {@link #harvesters} has been initialized. * Whether {@link #harvesters} has been initialized.
@ -84,7 +51,8 @@ public class MappingCandidateHarvesters
/** /**
* The list of already configured harvesters. * The list of already configured harvesters.
*/ */
private static MappingCandidateHarvester[] harvesters; private static MappingCandidateHarvester[] harvesters
= new MappingCandidateHarvester[0];
/** /**
* Whether the discovery of a public address via STUN has failed. * Whether the discovery of a public address via STUN has failed.
@ -104,6 +72,21 @@ public class MappingCandidateHarvesters
return harvesters; return harvesters;
} }
/**
* @return the (first) mapping harvester which matches a given public address, or {@code null} if none match it.
*/
public static MappingCandidateHarvester findHarvesterForAddress(TransportAddress publicAddress)
{
for (MappingCandidateHarvester harvester : harvesters)
{
if (harvester.publicAddressMatches(publicAddress))
{
return harvester;
}
}
return null;
}
/** /**
* Initializes {@link #harvesters}. * Initializes {@link #harvesters}.
* First it reads the configuration and instantiates harvesters accordingly, * First it reads the configuration and instantiates harvesters accordingly,
@ -123,64 +106,48 @@ public class MappingCandidateHarvesters
long start = System.currentTimeMillis(); long start = System.currentTimeMillis();
List<MappingCandidateHarvester> harvesterList = new LinkedList<>(); List<MappingCandidateHarvester> harvesterList = new LinkedList<>();
for (HarvestConfig.StaticMapping staticMapping : config.getStaticMappings())
// Pre-configured NAT harvester.
String localAddressStr
= StackProperties.getString(NAT_HARVESTER_LOCAL_ADDRESS_PNAME);
String publicAddressStr
= StackProperties.getString(NAT_HARVESTER_PUBLIC_ADDRESS_PNAME);
if (localAddressStr != null && publicAddressStr != null)
{ {
// the port number is unused, 9 is for "discard" logger.info("Adding a static mapping: " + staticMapping);
// If the configuration has no port, then the port value is not used in any way. We put 9 (for "discard")
// as a filler.
int localPort = staticMapping.getLocalPort() != null ? staticMapping.getLocalPort() : 9;
int publicPort = staticMapping.getPublicPort() != null ? staticMapping.getPublicPort() : 9;
TransportAddress localAddress TransportAddress localAddress
= new TransportAddress(localAddressStr, 9, Transport.UDP); = new TransportAddress(staticMapping.getLocalAddress(), localPort, Transport.UDP);
TransportAddress publicAddress TransportAddress publicAddress
= new TransportAddress(publicAddressStr, 9, Transport.UDP); = new TransportAddress(staticMapping.getPublicAddress(), publicPort, Transport.UDP);
harvesterList.add( harvesterList.add(new StaticMappingCandidateHarvester(
new MappingCandidateHarvester(publicAddress, localAddress)); publicAddress,
localAddress,
staticMapping.getName(),
staticMapping.getLocalPort() != null));
} }
// AWS harvester // AWS harvester
boolean disableAwsHarvester boolean enableAwsHarvester = config.enableAwsHarvester();
= StackProperties.getBoolean(DISABLE_AWS_HARVESTER_PNAME, false); if (enableAwsHarvester && (config.forceAwsHarvester() || AwsCandidateHarvester.smellsLikeAnEC2()))
boolean forceAwsHarvester
= StackProperties.getBoolean(FORCE_AWS_HARVESTER_PNAME, false);
if (logger.isLoggable(Level.FINE))
{
logger.fine("AWS configuration: disable=" + disableAwsHarvester
+ "; force=" + forceAwsHarvester);
}
if (!disableAwsHarvester &&
(forceAwsHarvester || AwsCandidateHarvester.smellsLikeAnEC2()))
{ {
logger.info("Using AwsCandidateHarvester.");
harvesterList.add(new AwsCandidateHarvester()); harvesterList.add(new AwsCandidateHarvester());
} }
// STUN harvesters // STUN harvesters
String stunServers List<String> stunServers = config.stunMappingCandidateHarvesterAddresses();
= StackProperties.getString(STUN_MAPPING_HARVESTER_ADDRESSES_PNAME); if (!stunServers.isEmpty())
if (stunServers != null && !stunServers.isEmpty())
{ {
// Create STUN harvesters (and wait for all of their discovery to // Create STUN harvesters (and wait for all of their discovery to finish).
// finish). List<StunMappingCandidateHarvester> stunHarvesters = createStunHarvesters(stunServers);
List<StunMappingCandidateHarvester> stunHarvesters
= createStunHarvesters(stunServers.split(","));
// We have STUN servers configured, so flag the failure if none of // We have STUN servers configured, so flag failure if none of them were able to discover an address.
// them were able to discover an address.
stunDiscoveryFailed = stunHarvesters.isEmpty(); stunDiscoveryFailed = stunHarvesters.isEmpty();
harvesterList.addAll(stunHarvesters); harvesterList.addAll(stunHarvesters);
} }
harvesterList = prune(harvesterList); harvesterList = prune(harvesterList);
harvesters harvesters = harvesterList.toArray(new MappingCandidateHarvester[harvesterList.size()]);
= harvesterList.toArray(
new MappingCandidateHarvester[harvesterList.size()]);
for (MappingCandidateHarvester harvester : harvesters) for (MappingCandidateHarvester harvester : harvesters)
{ {
@ -229,10 +196,10 @@ public class MappingCandidateHarvesters
for (MappingCandidateHarvester h : harvesters) for (MappingCandidateHarvester h : harvesters)
{ {
if (face.getAddress().equals(h.getFace().getAddress()) && mask.getAddress().equals(h.getMask().getAddress())) if (face.getAddress().equals(h.getFace().getAddress())
&& mask.getAddress().equals(h.getMask().getAddress()))
{ {
logger.info("Discarding a mapping harvester with duplicate " logger.info("Discarding a mapping harvester with duplicate addresses: " + harvester + ". Kept: " + h);
+ "addresses: " + harvester + ". Kept: " + h);
return; return;
} }
} }
@ -247,30 +214,20 @@ public class MappingCandidateHarvesters
* pairs). * pairs).
* @return the list of those who were successful in discovering an address. * @return the list of those who were successful in discovering an address.
*/ */
private static List<StunMappingCandidateHarvester> createStunHarvesters( private static List<StunMappingCandidateHarvester> createStunHarvesters(@NotNull List<String> stunServers)
String[] stunServers)
{ {
List<StunMappingCandidateHarvester> stunHarvesters = new LinkedList<>(); List<StunMappingCandidateHarvester> stunHarvesters = new LinkedList<>();
if (stunServers == null || stunServers.length == 0)
{
logger.severe("No STUN servers configured.");
return stunHarvesters;
}
List<Callable<StunMappingCandidateHarvester>> tasks = new LinkedList<>(); List<Callable<StunMappingCandidateHarvester>> tasks = new LinkedList<>();
// Create a StunMappingCandidateHarvester for each local:remote address // Create a StunMappingCandidateHarvester for each local:remote address pair.
// pair. List<InetAddress> localAddresses = HostCandidateHarvester.getAllAllowedAddresses();
List<InetAddress> localAddresses
= HostCandidateHarvester.getAllAllowedAddresses();
for (String stunServer : stunServers) for (String stunServer : stunServers)
{ {
String[] addressAndPort = stunServer.split(":"); String[] addressAndPort = stunServer.split(":");
if (addressAndPort.length < 2) if (addressAndPort.length < 2)
{ {
logger.severe("Failed to parse STUN server address: " logger.severe("Failed to parse STUN server address: " + stunServer);
+ stunServer);
continue; continue;
} }
int port; int port;
@ -299,67 +256,72 @@ public class MappingCandidateHarvesters
continue; continue;
} }
TransportAddress localAddress TransportAddress localAddress = new TransportAddress(localInetAddress, 0, Transport.UDP);
= new TransportAddress(localInetAddress, 0, Transport.UDP);
logger.info("Using " + remoteAddress + " for StunMappingCandidateHarvester (localAddress="
+ localAddress + ").");
final StunMappingCandidateHarvester stunHarvester final StunMappingCandidateHarvester stunHarvester
= new StunMappingCandidateHarvester( = new StunMappingCandidateHarvester(localAddress, remoteAddress);
localAddress,
remoteAddress);
Callable<StunMappingCandidateHarvester> task Callable<StunMappingCandidateHarvester> task = () ->
= new Callable<StunMappingCandidateHarvester>()
{ {
@Override stunHarvester.discover();
public StunMappingCandidateHarvester call() return stunHarvester;
throws Exception
{
stunHarvester.discover();
return stunHarvester;
}
}; };
tasks.add(task); tasks.add(task);
} }
} }
// Now run discover() on all created harvesters in parallel and pick if (tasks.isEmpty())
// the ones which succeeded.
ExecutorService es = Executors.newFixedThreadPool(tasks.size());
List<Future<StunMappingCandidateHarvester>> futures;
try
{ {
futures = es.invokeAll(tasks); logger.warning("STUN mapping harvesters are configured, but no allowed local addresses were found." +
} " Not using STUN.");
catch (InterruptedException ie)
{
Thread.currentThread().interrupt();
return stunHarvesters; return stunHarvesters;
} }
for (Future<StunMappingCandidateHarvester> future : futures) // Now run discover() on all created harvesters in parallel and pick the ones which succeeded.
ExecutorService es = ExecutorFactory.createFixedThreadPool(tasks.size(), "ice4j.Harvester-executor-");
try
{ {
List<Future<StunMappingCandidateHarvester>> futures;
try try
{ {
StunMappingCandidateHarvester harvester = future.get(); futures = es.invokeAll(tasks);
// The STUN server replied successfully.
if (harvester.getMask() != null)
{
stunHarvesters.add(harvester);
}
} }
catch (ExecutionException ee) catch (InterruptedException ie)
{
// The harvester failed for some reason, discard it.
}
catch(InterruptedException ie)
{ {
Thread.currentThread().interrupt(); Thread.currentThread().interrupt();
throw new RuntimeException(ie); return stunHarvesters;
}
for (Future<StunMappingCandidateHarvester> future : futures)
{
try
{
StunMappingCandidateHarvester harvester = future.get();
// The STUN server replied successfully.
if (harvester.getMask() != null)
{
stunHarvesters.add(harvester);
}
}
catch (ExecutionException ee)
{
// The harvester failed for some reason, discard it.
}
catch (InterruptedException ie)
{
Thread.currentThread().interrupt();
throw new RuntimeException(ie);
}
} }
} }
finally
{
es.shutdown();
}
return stunHarvesters; return stunHarvesters;
} }

View File

@ -101,7 +101,8 @@ public class SinglePortUdpHarvester
/** /**
* Initializes a new <tt>SinglePortUdpHarvester</tt> instance which is to * Initializes a new <tt>SinglePortUdpHarvester</tt> instance which is to
* bind on the specified local address. * bind on the specified local address.
* @param localAddress the address to bind to. * @param localAddress the address to bind to. If the port is 0 an ephemeral port is chosen by the OS and the
* SinglePortUdpHarvester.localAddress will reflect the allocated port number.
* @throws IOException if initialization fails. * @throws IOException if initialization fails.
*/ */
public SinglePortUdpHarvester(TransportAddress localAddress) public SinglePortUdpHarvester(TransportAddress localAddress)
@ -109,7 +110,7 @@ public class SinglePortUdpHarvester
{ {
super(localAddress); super(localAddress);
logger.info("Initialized SinglePortUdpHarvester with address " logger.info("Initialized SinglePortUdpHarvester with address "
+ localAddress); + this.localAddress);
} }
/** /**
@ -145,7 +146,7 @@ public class SinglePortUdpHarvester
// 1. Create a socket for this remote address // 1. Create a socket for this remote address
// 2. Set-up de-multiplexing for future datagrams // 2. Set-up de-multiplexing for future datagrams
// with this address to this socket. // with this address to this socket.
MySocket newSocket = addSocket(remoteAddress); MySocket newSocket = addSocket(remoteAddress, ufrag);
// 3. Let the candidate and its STUN stack no about the // 3. Let the candidate and its STUN stack no about the
// new socket. // new socket.
@ -378,7 +379,6 @@ public class SinglePortUdpHarvester
componentSocket.add(multiplexing); componentSocket.add(multiplexing);
} }
// XXX is this necessary?
synchronized (candidateSockets) synchronized (candidateSockets)
{ {
IceSocketWrapper oldSocket IceSocketWrapper oldSocket
@ -404,8 +404,10 @@ public class SinglePortUdpHarvester
protected IceSocketWrapper getCandidateIceSocketWrapper( protected IceSocketWrapper getCandidateIceSocketWrapper(
SocketAddress remoteAddress) SocketAddress remoteAddress)
{ {
return candidateSockets.get(remoteAddress); synchronized (candidateSockets)
{
return candidateSockets.get(remoteAddress);
}
} }
} }
} }

View File

@ -547,7 +547,7 @@ public class StunCandidateHarvest
Attribute attribute Attribute attribute
= response.getAttribute(Attribute.XOR_MAPPED_ADDRESS); = response.getAttribute(Attribute.XOR_MAPPED_ADDRESS);
if(attribute instanceof XorMappedAddressAttribute) if (attribute instanceof XorMappedAddressAttribute)
{ {
return return
((XorMappedAddressAttribute) attribute) ((XorMappedAddressAttribute) attribute)
@ -558,7 +558,7 @@ public class StunCandidateHarvest
attribute attribute
= response.getAttribute(Attribute.MAPPED_ADDRESS); = response.getAttribute(Attribute.MAPPED_ADDRESS);
if(attribute instanceof MappedAddressAttribute) if (attribute instanceof MappedAddressAttribute)
{ {
return return
((MappedAddressAttribute) attribute) ((MappedAddressAttribute) attribute)

View File

@ -111,9 +111,9 @@ public class StunCandidateHarvester
this.shortTermCredentialUsername = shortTermCredentialUsername; this.shortTermCredentialUsername = shortTermCredentialUsername;
//these should be configurable. //these should be configurable.
if(System.getProperty(StackProperties.MAX_CTRAN_RETRANS_TIMER) == null) if (System.getProperty(StackProperties.MAX_CTRAN_RETRANS_TIMER) == null)
System.setProperty(StackProperties.MAX_CTRAN_RETRANS_TIMER, "400"); System.setProperty(StackProperties.MAX_CTRAN_RETRANS_TIMER, "400");
if(System.getProperty(StackProperties.MAX_CTRAN_RETRANSMISSIONS) == null) if (System.getProperty(StackProperties.MAX_CTRAN_RETRANSMISSIONS) == null)
System.setProperty(StackProperties.MAX_CTRAN_RETRANSMISSIONS, "3"); System.setProperty(StackProperties.MAX_CTRAN_RETRANSMISSIONS, "3");
} }
@ -150,7 +150,7 @@ public class StunCandidateHarvester
synchronized(startedHarvests) synchronized(startedHarvests)
{ {
if(doNotify) if (doNotify)
startedHarvests.notify(); startedHarvests.notify();
} }
} }
@ -290,7 +290,7 @@ public class StunCandidateHarvester
private String listCandidates(Collection<? extends Candidate<?>> candidates) private String listCandidates(Collection<? extends Candidate<?>> candidates)
{ {
StringBuilder retval = new StringBuilder(); StringBuilder retval = new StringBuilder();
for(Candidate<?> candidate : candidates) for (Candidate<?> candidate : candidates)
{ {
retval.append(candidate.toShortString()); retval.append(candidate.toShortString());
} }
@ -313,7 +313,7 @@ public class StunCandidateHarvester
HostCandidate cand = getHostCandidate(hostCand); HostCandidate cand = getHostCandidate(hostCand);
if(cand == null) if (cand == null)
{ {
logger.info( logger.info(
"server/candidate address type mismatch," "server/candidate address type mismatch,"

View File

@ -20,13 +20,13 @@ package org.ice4j.ice.harvest;
import org.ice4j.*; import org.ice4j.*;
import org.ice4j.socket.*; import org.ice4j.socket.*;
import org.ice4j.stunclient.*; import org.ice4j.stunclient.*;
import org.jetbrains.annotations.*;
import java.net.*; import java.net.*;
import java.util.logging.*; import java.util.logging.*;
/** /**
* A {@link MappingCandidateHarvester} which uses a STUN servers to discover * A {@link MappingCandidateHarvester} which uses a STUN servers to discover its public IP address.
* its public IP address.
* *
* @author Damian Minkov * @author Damian Minkov
* @author Boris Grozev * @author Boris Grozev
@ -38,13 +38,24 @@ public class StunMappingCandidateHarvester
* The <tt>Logger</tt> used by the <tt>StunMappingCandidateHarvester</tt> * The <tt>Logger</tt> used by the <tt>StunMappingCandidateHarvester</tt>
* class and its instances for logging output. * class and its instances for logging output.
*/ */
private static final Logger logger private static final Logger logger = Logger.getLogger(StunMappingCandidateHarvester.class.getName());
= Logger.getLogger(StunMappingCandidateHarvester.class.getName());
/** /**
* The list of servers we will use to discover our public address. * The list of servers we will use to discover our public address.
*/ */
private TransportAddress stunServerAddress; private final TransportAddress stunServerAddress;
/**
* The local address this {@link StunMappingCandidateHarvester} was initialized with, and which will be used to
* communicate to STUN servers.
*/
@NotNull
private TransportAddress localAddress;
/**
* The public address discovered through STUN, if any.
*/
private TransportAddress publicAddress = null;
/** /**
* Initializes a new {@link StunMappingCandidateHarvester} instance with * Initializes a new {@link StunMappingCandidateHarvester} instance with
@ -55,10 +66,11 @@ public class StunMappingCandidateHarvester
* @param stunServerAddress The address of the STUN server. * @param stunServerAddress The address of the STUN server.
*/ */
public StunMappingCandidateHarvester( public StunMappingCandidateHarvester(
TransportAddress localAddress, @NotNull TransportAddress localAddress,
TransportAddress stunServerAddress) TransportAddress stunServerAddress)
{ {
face = localAddress; super("stun");
this.localAddress = localAddress;
this.stunServerAddress = stunServerAddress; this.stunServerAddress = stunServerAddress;
} }
@ -75,22 +87,48 @@ public class StunMappingCandidateHarvester
= new SimpleAddressDetector(stunServerAddress); = new SimpleAddressDetector(stunServerAddress);
sad.start(); sad.start();
IceSocketWrapper localSocket IceSocketWrapper localSocket = new IceUdpSocketWrapper(new DatagramSocket(localAddress));
= new IceUdpSocketWrapper(new DatagramSocket(face));
mask = sad.getMappingFor(localSocket); publicAddress = sad.getMappingFor(localSocket);
if (mask != null)
/* Record bound address as face. */
SocketAddress boundAddr = localSocket.getLocalSocketAddress();
if (boundAddr instanceof InetSocketAddress)
{ {
logger.info("Discovered public address " + mask localAddress = new TransportAddress((InetSocketAddress)boundAddr, localAddress.getTransport());
}
if (publicAddress != null)
{
logger.info("Discovered public address " + publicAddress
+ " from STUN server " + stunServerAddress + " from STUN server " + stunServerAddress
+ " using local address " + face); + " using local address " + localSocket);
} }
} }
catch (Exception exc) catch (Exception exc)
{ {
//whatever happens, we just log //whatever happens, we just log
logger.log(Level.INFO, "We failed to obtain addresses " logger.log(Level.INFO, "We failed to obtain addresses for the following reason: ", exc);
+ "for the following reason: ", exc);
} }
} }
/**
* {@inheritDoc}
*/
@Nullable
@Override
public TransportAddress getFace()
{
return localAddress;
}
/**
* {@inheritDoc}
*/
@Nullable
@Override
public TransportAddress getMask()
{
return publicAddress;
}
} }

View File

@ -93,10 +93,10 @@ public class UPNPHarvester
logger.fine("Begin UPnP harvesting"); logger.fine("Begin UPnP harvesting");
try try
{ {
if(device == null) if (device == null)
{ {
// do it only once // do it only once
if(finishThreads == 0) if (finishThreads == 0)
{ {
try try
{ {
@ -108,17 +108,17 @@ public class UPNPHarvester
synchronized(rootSync) synchronized(rootSync)
{ {
while(finishThreads != 2) while (finishThreads != 2)
{ {
rootSync.wait(); rootSync.wait();
} }
} }
if(wanIPThread.getDevice() != null) if (wanIPThread.getDevice() != null)
{ {
device = wanIPThread.getDevice(); device = wanIPThread.getDevice();
} }
else if(wanPPPThread.getDevice() != null) else if (wanPPPThread.getDevice() != null)
{ {
device = wanPPPThread.getDevice(); device = wanPPPThread.getDevice();
} }
@ -130,7 +130,7 @@ public class UPNPHarvester
} }
} }
if(device == null) if (device == null)
return candidates; return candidates;
} }
@ -143,12 +143,12 @@ public class UPNPHarvester
int port = socket.getLocalPort(); int port = socket.getLocalPort();
int externalPort = socket.getLocalPort(); int externalPort = socket.getLocalPort();
while(retries < MAX_RETRIES) while (retries < MAX_RETRIES)
{ {
if(!device.getSpecificPortMappingEntry(port, "UDP", if (!device.getSpecificPortMappingEntry(port, "UDP",
portMapping)) portMapping))
{ {
if(device.addPortMapping( if (device.addPortMapping(
externalPort, externalPort,
port, port,
localAddress.getHostAddress(), localAddress.getHostAddress(),
@ -165,11 +165,11 @@ public class UPNPHarvester
// if we don't add the base, we won't be able to add // if we don't add the base, we won't be able to add
// peer reflexive candidate if someone contact us on the // peer reflexive candidate if someone contact us on the
// UPNPCandidate // UPNPCandidate
for(LocalCandidate cand : cands) for (LocalCandidate cand : cands)
{ {
//try to add the candidate to the component and then //try to add the candidate to the component and then
//only add it to the harvest not redundant //only add it to the harvest not redundant
if(component.addLocalCandidate(cand)) if (component.addLocalCandidate(cand))
{ {
candidates.add(cand); candidates.add(cand);
} }
@ -280,7 +280,7 @@ public class UPNPHarvester
gd.discover(); gd.discover();
if(gd.getValidGateway() != null) if (gd.getValidGateway() != null)
{ {
device = gd.getValidGateway(); device = gd.getValidGateway();
} }
@ -294,7 +294,7 @@ public class UPNPHarvester
* a method, it is important that it be rethrown so that the * a method, it is important that it be rethrown so that the
* thread actually dies. * thread actually dies.
*/ */
if(e instanceof ThreadDeath) if (e instanceof ThreadDeath)
throw (ThreadDeath)e; throw (ThreadDeath)e;
} }
finally finally

View File

@ -151,15 +151,15 @@ public class IceSdpUtils
Component firstComponent = null; Component firstComponent = null;
//add candidates //add candidates
for(Component component : iceMediaStream.getComponents()) for (Component component : iceMediaStream.getComponents())
{ {
//if this is the first component, remember it so that we can //if this is the first component, remember it so that we can
//later use it for default candidates. //later use it for default candidates.
if(firstComponent == null) if (firstComponent == null)
firstComponent = component; firstComponent = component;
Vector attributes = mediaDescription.getAttributes(true); Vector attributes = mediaDescription.getAttributes(true);
for(Candidate<?> candidate : component.getLocalCandidates()) for (Candidate<?> candidate : component.getLocalCandidates())
{ {
attributes.add(new CandidateAttribute(candidate)); attributes.add(new CandidateAttribute(candidate));
} }
@ -184,12 +184,12 @@ public class IceSdpUtils
Component rtcpComponent Component rtcpComponent
= iceMediaStream.getComponent(Component.RTCP); = iceMediaStream.getComponent(Component.RTCP);
if( rtcpComponent != null ) if ( rtcpComponent != null )
{ {
TransportAddress defaultRtcpCandidate = rtcpComponent TransportAddress defaultRtcpCandidate = rtcpComponent
.getDefaultCandidate().getTransportAddress(); .getDefaultCandidate().getTransportAddress();
if(defaultRtcpCandidate.getPort() != defaultAddress.getPort()+1) if (defaultRtcpCandidate.getPort() != defaultAddress.getPort()+1)
{ {
mediaDescription.setAttribute( mediaDescription.setAttribute(
RTCP, Integer.toString(defaultRtcpCandidate.getPort())); RTCP, Integer.toString(defaultRtcpCandidate.getPort()));
@ -255,7 +255,7 @@ public class IceSdpUtils
//origin //origin
Origin o = sDes.getOrigin(); Origin o = sDes.getOrigin();
if( o == null || "user".equals(o.getUsername())) if ( o == null || "user".equals(o.getUsername()))
{ {
//looks like there wasn't any origin set: jain-sdp creates a //looks like there wasn't any origin set: jain-sdp creates a
//default origin that has "user" as the user name so we use this //default origin that has "user" as the user name so we use this
@ -277,7 +277,7 @@ public class IceSdpUtils
List<IceMediaStream> streams = agent.getStreams(); List<IceMediaStream> streams = agent.getStreams();
Vector<MediaDescription> mDescs Vector<MediaDescription> mDescs
= new Vector<>(agent.getStreamCount()); = new Vector<>(agent.getStreamCount());
for(IceMediaStream stream : streams) for (IceMediaStream stream : streams)
{ {
MediaDescription mLine = sdpFactory.createMediaDescription( MediaDescription mLine = sdpFactory.createMediaDescription(
stream.getName(), 0, //default port comes later stream.getName(), 0, //default port comes later
@ -320,7 +320,7 @@ public class IceSdpUtils
{ {
List<Attribute> trickleUpdate = null; List<Attribute> trickleUpdate = null;
if(localCandidates == null || localCandidates.size() == 0) if (localCandidates == null || localCandidates.size() == 0)
{ {
trickleUpdate = new ArrayList<>(1); trickleUpdate = new ArrayList<>(1);
trickleUpdate.add( trickleUpdate.add(
@ -333,7 +333,7 @@ public class IceSdpUtils
String streamName = null; String streamName = null;
for(LocalCandidate candidate : localCandidates) for (LocalCandidate candidate : localCandidates)
{ {
streamName = candidate.getParentComponent() streamName = candidate.getParentComponent()
.getParentStream().getName(); .getParentStream().getName();

View File

@ -106,7 +106,7 @@ public class ChannelData
*/ */
public char getDataLength() public char getDataLength()
{ {
if(data == null) if (data == null)
return 0; return 0;
return (char)data.length; return (char)data.length;
@ -159,7 +159,7 @@ public class ChannelData
byte binMsg[] = new byte[HEADER_LENGTH + dataLength]; byte binMsg[] = new byte[HEADER_LENGTH + dataLength];
int offset = 0; int offset = 0;
if(!validateChannelNumber(channelNumber)) if (!validateChannelNumber(channelNumber))
{ {
throw new StunException(StunException.ILLEGAL_ARGUMENT, "Channel number invalid"); throw new StunException(StunException.ILLEGAL_ARGUMENT, "Channel number invalid");
} }
@ -172,7 +172,7 @@ public class ChannelData
binMsg[offset++] = (byte)((data != null) ? data.length >> 8 : 0); binMsg[offset++] = (byte)((data != null) ? data.length >> 8 : 0);
binMsg[offset++] = (byte)((data != null) ? data.length & 0xff : 0); binMsg[offset++] = (byte)((data != null) ? data.length & 0xff : 0);
if(data != null) if (data != null)
{ {
System.arraycopy(data, 0, binMsg, offset, data.length); System.arraycopy(data, 0, binMsg, offset, data.length);
} }
@ -210,14 +210,14 @@ public class ChannelData
ChannelData channelData = null; ChannelData channelData = null;
byte data[] = null; byte data[] = null;
if((binMessage.length - offset) < HEADER_LENGTH) if ((binMessage.length - offset) < HEADER_LENGTH)
{ {
throw new StunException(StunException.ILLEGAL_ARGUMENT, "Size too short"); throw new StunException(StunException.ILLEGAL_ARGUMENT, "Size too short");
} }
channelNumber = (char)((binMessage[offset++]<<8) | (binMessage[offset++]&0xFF)); channelNumber = (char)((binMessage[offset++]<<8) | (binMessage[offset++]&0xFF));
if(!validateChannelNumber(channelNumber)) if (!validateChannelNumber(channelNumber))
{ {
throw new StunException(StunException.ILLEGAL_ARGUMENT, "Channel number invalid"); throw new StunException(StunException.ILLEGAL_ARGUMENT, "Channel number invalid");
} }

View File

@ -50,7 +50,7 @@ public class Indication
/* old TURN DATA indication type is an indication despite /* old TURN DATA indication type is an indication despite
* 0x0115 & 0x0110 indicates STUN error response type * 0x0115 & 0x0110 indicates STUN error response type
*/ */
if(!isIndicationType(indicationType) && if (!isIndicationType(indicationType) &&
indicationType != OLD_DATA_INDICATION) indicationType != OLD_DATA_INDICATION)
throw new IllegalArgumentException( throw new IllegalArgumentException(
(int)(indicationType) (int)(indicationType)

View File

@ -22,6 +22,7 @@ import java.util.logging.*;
import org.ice4j.*; import org.ice4j.*;
import org.ice4j.attribute.*; import org.ice4j.attribute.*;
import org.ice4j.ice.*;
import org.ice4j.stack.*; import org.ice4j.stack.*;
/** /**
@ -469,6 +470,7 @@ public abstract class Message
/* Old TURN attributes */ /* Old TURN attributes */
protected static final byte DESTINATION_ADDRESS_PRESENTITY_INDEX = 29; protected static final byte DESTINATION_ADDRESS_PRESENTITY_INDEX = 29;
// CHECKSTYLE:OFF
protected final static byte attributePresentities[][] = new byte[][]{ protected final static byte attributePresentities[][] = new byte[][]{
// Binding Shared Shared Shared Alloc Alloc Rfrsh Rfrsh ChnlBnd ChnlBnd Send Data // Binding Shared Shared Shared Alloc Alloc Rfrsh Rfrsh ChnlBnd ChnlBnd Send Data
// Binding Binding Error Secret Secret Secret Req. Resp. Req. Resp. Req. Resp. Indic. Indic. // Binding Binding Error Secret Secret Secret Req. Resp. Req. Resp. Req. Resp. Indic. Indic.
@ -509,6 +511,7 @@ public abstract class Message
/*USE-CANDIDATE*/ { O, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A}, /*USE-CANDIDATE*/ { O, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A},
/*DESTINATION-ADDRESS*/{N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, O, N_A, N_A, N_A, M, N_A}, /*DESTINATION-ADDRESS*/{N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, O, N_A, N_A, N_A, M, N_A},
}; };
// CHECKSTYLE:ON
/** /**
* Creates an empty STUN Message. * Creates an empty STUN Message.
@ -687,7 +690,7 @@ public abstract class Message
public void setTransactionID(byte[] tranID) public void setTransactionID(byte[] tranID)
throws StunException throws StunException
{ {
if(tranID == null if (tranID == null
|| (tranID.length != TRANSACTION_ID_LENGTH && || (tranID.length != TRANSACTION_ID_LENGTH &&
tranID.length != RFC3489_TRANSACTION_ID_LENGTH)) tranID.length != RFC3489_TRANSACTION_ID_LENGTH))
throw new StunException(StunException.ILLEGAL_ARGUMENT, throw new StunException(StunException.ILLEGAL_ARGUMENT,
@ -721,7 +724,7 @@ public abstract class Message
*/ */
protected byte getAttributePresentity(char attributeType) protected byte getAttributePresentity(char attributeType)
{ {
if(!rfc3489CompatibilityMode) if (!rfc3489CompatibilityMode)
return O; return O;
byte msgIndex = -1; byte msgIndex = -1;
@ -872,22 +875,22 @@ public abstract class Message
@Override @Override
public boolean equals(Object obj) public boolean equals(Object obj)
{ {
if(!(obj instanceof Message)) if (!(obj instanceof Message))
return false; return false;
if(obj == this) if (obj == this)
return true; return true;
Message msg = (Message) obj; Message msg = (Message) obj;
if( msg.getMessageType() != getMessageType()) if ( msg.getMessageType() != getMessageType())
return false; return false;
if(msg.getDataLength() != getDataLength()) if (msg.getDataLength() != getDataLength())
return false; return false;
//compare attributes //compare attributes
for (Attribute localAtt : attributes.values()) for (Attribute localAtt : attributes.values())
{ {
if(!localAtt.equals(msg.getAttribute(localAtt.getAttributeType()))) if (!localAtt.equals(msg.getAttribute(localAtt.getAttributeType())))
return false; return false;
} }
@ -930,7 +933,7 @@ public abstract class Message
byte tranID[] = getTransactionID(); byte tranID[] = getTransactionID();
if(tranID.length == 12) if (tranID.length == 12)
{ {
System.arraycopy(MAGIC_COOKIE, 0, binMsg, offset, 4); System.arraycopy(MAGIC_COOKIE, 0, binMsg, offset, 4);
offset += 4; offset += 4;
@ -1018,7 +1021,7 @@ public abstract class Message
//add a SOFTWARE attribute if the user said so, and unless they did it //add a SOFTWARE attribute if the user said so, and unless they did it
//themselves. //themselves.
String software = System.getProperty(StackProperties.SOFTWARE); String software = AgentConfig.config.getSoftware();
if (getAttribute(Attribute.SOFTWARE) == null if (getAttribute(Attribute.SOFTWARE) == null
&& software != null && software.length() > 0) && software != null && software.length() > 0)
@ -1057,13 +1060,13 @@ public abstract class Message
* @throws StunException <tt>ILLEGAL_ARGUMENT</tt> if one or more of the * @throws StunException <tt>ILLEGAL_ARGUMENT</tt> if one or more of the
* arguments have invalid values. * arguments have invalid values.
*/ */
public static Message decode(byte binMessage[], char offset, char arrayLen) public static Message decode(byte[] binMessage, int offset, int arrayLen)
throws StunException throws StunException
{ {
int originalOffset = offset; int originalOffset = offset;
arrayLen = (char)Math.min(binMessage.length, arrayLen); arrayLen = Math.min(binMessage.length, arrayLen);
if(arrayLen - offset < Message.HEADER_LENGTH) if (arrayLen - offset < Message.HEADER_LENGTH)
{ {
throw new StunException( StunException.ILLEGAL_ARGUMENT, throw new StunException( StunException.ILLEGAL_ARGUMENT,
"The given binary array is not a valid StunMessage"); "The given binary array is not a valid StunMessage");
@ -1077,7 +1080,7 @@ public abstract class Message
if (Message.isResponseType(messageType) && if (Message.isResponseType(messageType) &&
messageType != OLD_DATA_INDICATION) messageType != OLD_DATA_INDICATION)
message = new Response(); message = new Response();
else if(Message.isRequestType(messageType)) else if (Message.isRequestType(messageType))
message = new Request(); message = new Request();
else /* indication */ else /* indication */
message = new Indication(); message = new Indication();
@ -1088,38 +1091,38 @@ public abstract class Message
| (binMessage[offset++] & 0xFF)); | (binMessage[offset++] & 0xFF));
/* copy the cookie */ /* copy the cookie */
byte cookie[] = new byte[4]; byte[] cookie = new byte[4];
System.arraycopy(binMessage, offset, cookie, 0, 4); System.arraycopy(binMessage, offset, cookie, 0, 4);
offset += 4; offset += 4;
boolean rfc3489Compat = false; boolean rfc3489Compat = false;
if(!Arrays.equals(MAGIC_COOKIE, cookie)) if (!Arrays.equals(MAGIC_COOKIE, cookie))
{ {
rfc3489Compat = true; rfc3489Compat = true;
} }
if(arrayLen - offset - TRANSACTION_ID_LENGTH < length) if (arrayLen - offset - TRANSACTION_ID_LENGTH < length)
{ {
throw throw
new StunException( new StunException(
StunException.ILLEGAL_ARGUMENT, StunException.ILLEGAL_ARGUMENT,
"The given binary array does not seem to contain" "The given binary array does not seem to contain"
+ " a whole StunMessage: given " + " a whole StunMessage: given "
+ ((int) arrayLen) + arrayLen
+ " bytes of " + " bytes of "
+ message.getName() + message.getName()
+ " but expecting " + " but expecting "
+ (offset + TRANSACTION_ID_LENGTH + length)); + (offset + TRANSACTION_ID_LENGTH + length));
} }
byte tranID[] = new byte[TRANSACTION_ID_LENGTH]; byte[] tranID = new byte[TRANSACTION_ID_LENGTH];
System.arraycopy(binMessage, offset, tranID, 0, TRANSACTION_ID_LENGTH); System.arraycopy(binMessage, offset, tranID, 0, TRANSACTION_ID_LENGTH);
try try
{ {
if(rfc3489Compat) if (rfc3489Compat)
{ {
byte rfc3489TranID[] = new byte[TRANSACTION_ID_LENGTH + 4]; byte[] rfc3489TranID = new byte[TRANSACTION_ID_LENGTH + 4];
System.arraycopy(cookie, 0, rfc3489TranID, 0, 4); System.arraycopy(cookie, 0, rfc3489TranID, 0, 4);
System.arraycopy(tranID, 0, rfc3489TranID, 4, System.arraycopy(tranID, 0, rfc3489TranID, 4,
TRANSACTION_ID_LENGTH); TRANSACTION_ID_LENGTH);
@ -1139,7 +1142,7 @@ public abstract class Message
offset += TRANSACTION_ID_LENGTH; offset += TRANSACTION_ID_LENGTH;
while(offset - Message.HEADER_LENGTH < length) while (offset - Message.HEADER_LENGTH < length)
{ {
Attribute att = AttributeDecoder.decode( Attribute att = AttributeDecoder.decode(
binMessage, offset, (char)(length - offset)); binMessage, offset, (char)(length - offset));
@ -1152,7 +1155,7 @@ public abstract class Message
//now also skip any potential padding that might have come with //now also skip any potential padding that might have come with
//this attribute. //this attribute.
if((att.getDataLength() % 4) > 0) if ((att.getDataLength() % 4) > 0)
{ {
offset += (4 - (att.getDataLength() % 4)); offset += (4 - (att.getDataLength() % 4));
} }
@ -1249,11 +1252,11 @@ public abstract class Message
protected void validateAttributePresentity() protected void validateAttributePresentity()
throws IllegalStateException throws IllegalStateException
{ {
if(! rfc3489CompatibilityMode ) if (! rfc3489CompatibilityMode )
return; return;
for(char i = Attribute.MAPPED_ADDRESS; i < Attribute.REFLECTED_FROM;i++) for (char i = Attribute.MAPPED_ADDRESS; i < Attribute.REFLECTED_FROM; i++)
if(getAttributePresentity(i) == M && getAttribute(i) == null) if (getAttributePresentity(i) == M && getAttribute(i) == null)
throw new IllegalStateException( throw new IllegalStateException(
"A mandatory attribute (type=" + (int)i + ") is missing!"); "A mandatory attribute (type=" + (int)i + ") is missing!");
} }
@ -1275,7 +1278,7 @@ public abstract class Message
*/ */
public static boolean isSuccessResponseType(char type) public static boolean isSuccessResponseType(char type)
{ {
return ((type & MESSAGE_CLASS_MASK) == STUN_SUCCESS_RESP); return ((type & MESSAGE_CLASS_MASK) == STUN_SUCCESS_RESP);
} }
/** /**
@ -1286,8 +1289,8 @@ public abstract class Message
*/ */
public static boolean isResponseType(char type) public static boolean isResponseType(char type)
{ {
/* return (((type >> 8) & 1) != 0); */ /* return (((type >> 8) & 1) != 0); */
return (isSuccessResponseType(type) || isErrorResponseType(type)); return (isSuccessResponseType(type) || isErrorResponseType(type));
} }
/** /**
@ -1308,8 +1311,8 @@ public abstract class Message
*/ */
public static boolean isRequestType(char type) public static boolean isRequestType(char type)
{ {
/* return !isResponseType(type); */ /* return !isResponseType(type); */
return ((type & MESSAGE_CLASS_MASK) == STUN_REQUEST); return ((type & MESSAGE_CLASS_MASK) == STUN_REQUEST);
} }
/** /**

View File

@ -54,7 +54,8 @@ public class MessageFactory
try try
{ {
bindingRequest.setMessageType(Message.BINDING_REQUEST); bindingRequest.setMessageType(Message.BINDING_REQUEST);
} catch (IllegalArgumentException ex) }
catch (IllegalArgumentException ex)
{ {
// there should be no exc here since we're the creators. // there should be no exc here since we're the creators.
logger.log(Level.FINE, "Failed to set message type.", ex); logger.log(Level.FINE, "Failed to set message type.", ex);
@ -122,7 +123,8 @@ public class MessageFactory
IceControllingAttribute iceControllingAttribute = AttributeFactory IceControllingAttribute iceControllingAttribute = AttributeFactory
.createIceControllingAttribute(tieBreaker); .createIceControllingAttribute(tieBreaker);
bindingRequest.putAttribute(iceControllingAttribute); bindingRequest.putAttribute(iceControllingAttribute);
} else }
else
{ {
IceControlledAttribute iceControlledAttribute = AttributeFactory IceControlledAttribute iceControlledAttribute = AttributeFactory
.createIceControlledAttribute(tieBreaker); .createIceControlledAttribute(tieBreaker);
@ -356,7 +358,8 @@ public class MessageFactory
try try
{ {
allocateRequest.setMessageType(Message.ALLOCATE_REQUEST); allocateRequest.setMessageType(Message.ALLOCATE_REQUEST);
} catch (IllegalArgumentException ex) }
catch (IllegalArgumentException ex)
{ {
// there should be no exc here since we're the creators. // there should be no exc here since we're the creators.
logger.log(Level.FINE, "Failed to set message type.", ex); logger.log(Level.FINE, "Failed to set message type.", ex);
@ -428,8 +431,8 @@ public class MessageFactory
int lifetime ) int lifetime )
throws IllegalArgumentException throws IllegalArgumentException
{ {
return createAllocationResponse( return createAllocationResponse(
request, mappedAddress, relayedAddress, null ,lifetime); request, mappedAddress, relayedAddress, null , lifetime);
} }
/** /**
@ -473,8 +476,8 @@ public class MessageFactory
//xor relayed address //xor relayed address
XorRelayedAddressAttribute xorRelayedAddressAttribute XorRelayedAddressAttribute xorRelayedAddressAttribute
= AttributeFactory = AttributeFactory
.createXorRelayedAddressAttribute(relayedAddress, .createXorRelayedAddressAttribute(relayedAddress,
request.getTransactionID()); request.getTransactionID());
allocationSuccessResponse.putAttribute(xorRelayedAddressAttribute); allocationSuccessResponse.putAttribute(xorRelayedAddressAttribute);
@ -484,12 +487,12 @@ public class MessageFactory
allocationSuccessResponse.putAttribute(lifetimeAttribute); allocationSuccessResponse.putAttribute(lifetimeAttribute);
if(token != null) if (token != null)
{ {
//reservation token //reservation token
ReservationTokenAttribute reservationTokenAttribute ReservationTokenAttribute reservationTokenAttribute
= AttributeFactory = AttributeFactory
.createReservationTokenAttribute(token); .createReservationTokenAttribute(token);
allocationSuccessResponse.putAttribute(reservationTokenAttribute); allocationSuccessResponse.putAttribute(reservationTokenAttribute);
} }
@ -508,7 +511,7 @@ public class MessageFactory
*/ */
public static Response createAllocationErrorResponse(char errorCode) public static Response createAllocationErrorResponse(char errorCode)
{ {
return createAllocationErrorResponse(errorCode,null); return createAllocationErrorResponse(errorCode, null);
} }
/** /**
@ -524,7 +527,7 @@ public class MessageFactory
* @return a allocation error response message containing an error code. * @return a allocation error response message containing an error code.
*/ */
public static Response createAllocationErrorResponse(char errorCode, public static Response createAllocationErrorResponse(char errorCode,
String reasonPhrase) String reasonPhrase)
{ {
Response allocationErrorResponse = new Response(); Response allocationErrorResponse = new Response();
@ -669,7 +672,8 @@ public class MessageFactory
LifetimeAttribute lifetimeReq = AttributeFactory LifetimeAttribute lifetimeReq = AttributeFactory
.createLifetimeAttribute(lifetime); .createLifetimeAttribute(lifetime);
refreshRequest.putAttribute(lifetimeReq); refreshRequest.putAttribute(lifetimeReq);
} catch (IllegalArgumentException ex) }
catch (IllegalArgumentException ex)
{ {
logger.log(Level.FINE, "Failed to set message type.", ex); logger.log(Level.FINE, "Failed to set message type.", ex);
} }
@ -806,7 +810,7 @@ public class MessageFactory
*/ */
public static Response createChannelBindErrorResponse(char errorCode) public static Response createChannelBindErrorResponse(char errorCode)
{ {
return createChannelBindErrorResponse(errorCode, null); return createChannelBindErrorResponse(errorCode, null);
} }
/** /**
@ -826,7 +830,7 @@ public class MessageFactory
ErrorCodeAttribute errorCodeAttribute ErrorCodeAttribute errorCodeAttribute
= AttributeFactory = AttributeFactory
.createErrorCodeAttribute(errorCode,reasonPhrase); .createErrorCodeAttribute(errorCode, reasonPhrase);
channelBindErrorResponse.putAttribute(errorCodeAttribute); channelBindErrorResponse.putAttribute(errorCodeAttribute);
@ -912,7 +916,7 @@ public class MessageFactory
ErrorCodeAttribute errorCodeAttribute ErrorCodeAttribute errorCodeAttribute
= AttributeFactory = AttributeFactory
.createErrorCodeAttribute( .createErrorCodeAttribute(
errorCode,reasonPhrase); errorCode, reasonPhrase);
createPermissionErrorResponse.putAttribute(errorCodeAttribute); createPermissionErrorResponse.putAttribute(errorCodeAttribute);
@ -949,7 +953,8 @@ public class MessageFactory
.createDataAttribute(data); .createDataAttribute(data);
sendIndication.putAttribute(dataAttribute); sendIndication.putAttribute(dataAttribute);
} }
} catch (IllegalArgumentException ex) }
catch (IllegalArgumentException ex)
{ {
logger.log(Level.FINE, "Failed to set message type.", ex); logger.log(Level.FINE, "Failed to set message type.", ex);
} }
@ -1180,7 +1185,7 @@ public class MessageFactory
public static Response createConnectErrorResponse(char errorCode) public static Response createConnectErrorResponse(char errorCode)
throws IllegalArgumentException throws IllegalArgumentException
{ {
return createConnectErrorResponse(errorCode, null); return createConnectErrorResponse(errorCode, null);
} }
/** /**
@ -1270,7 +1275,7 @@ public class MessageFactory
public static Response createConnectionBindErrorResponse(char errorCode) public static Response createConnectionBindErrorResponse(char errorCode)
throws IllegalArgumentException throws IllegalArgumentException
{ {
return createConnectionBindErrorResponse(errorCode,null); return createConnectionBindErrorResponse(errorCode, null);
} }
/** /**

View File

@ -44,7 +44,7 @@ public class Request extends Message
public void setMessageType(char requestType) public void setMessageType(char requestType)
throws IllegalArgumentException throws IllegalArgumentException
{ {
if(!isRequestType(requestType)) if (!isRequestType(requestType))
throw new IllegalArgumentException( throw new IllegalArgumentException(
(int)(requestType) (int)(requestType)
+ " - is not a valid request type."); + " - is not a valid request type.");

View File

@ -68,7 +68,7 @@ public class Response
public void setMessageType(char responseType) public void setMessageType(char responseType)
throws IllegalArgumentException throws IllegalArgumentException
{ {
if(!isResponseType(responseType)) if (!isResponseType(responseType))
throw new IllegalArgumentException( throw new IllegalArgumentException(
Integer.toString(responseType) Integer.toString(responseType)
+ " is not a valid response type."); + " is not a valid response type.");

View File

@ -387,12 +387,11 @@ public class PseudoTCPBase
} }
/** /**
*
* @return current timestamp limited to 32 bits * @return current timestamp limited to 32 bits
*/ */
public static long now() public static long now()
{ {
return System.currentTimeMillis() & 0xFFFFFFFFL; return (System.nanoTime() / 1000000) & 0xFFFFFFFFL;
} }
/** /**
@ -445,7 +444,8 @@ public class PseudoTCPBase
long nInFlight = m_snd_nxt - m_snd_una; long nInFlight = m_snd_nxt - m_snd_una;
m_ssthresh = Math.max(nInFlight / 2, 2 * m_mss); m_ssthresh = Math.max(nInFlight / 2, 2 * m_mss);
//Logger.Log(LS_INFO) << "m_ssthresh: " << m_ssthresh << " nInFlight: " << nInFlight << " m_mss: " << m_mss; //Logger.Log(LS_INFO)
// << "m_ssthresh: " << m_ssthresh << " nInFlight: " << nInFlight << " m_mss: " << m_mss;
m_cwnd = m_mss; m_cwnd = m_mss;
// Back off retransmit timer. Note: the limit is lower when connecting. // Back off retransmit timer. Note: the limit is lower when connecting.
@ -914,7 +914,7 @@ public class PseudoTCPBase
public static String segToStr(Segment seg) public static String segToStr(Segment seg)
{ {
String data="data: "; String data="data: ";
for(byte b : seg.data) for (byte b : seg.data)
{ {
data += b; data += b;
} }
@ -1064,7 +1064,7 @@ public class PseudoTCPBase
bConnect = true; bConnect = true;
// TCP options are in the remainder of the payload after CTL_CONNECT. // TCP options are in the remainder of the payload after CTL_CONNECT.
if(!parseOptions(seg.data, 1, seg.len - 1)) if (!parseOptions(seg.data, 1, seg.len - 1))
{ {
return false; return false;
} }
@ -1252,7 +1252,8 @@ public class PseudoTCPBase
m_recover = m_snd_nxt; m_recover = m_snd_nxt;
long nInFlight = m_snd_nxt - m_snd_una; long nInFlight = m_snd_nxt - m_snd_una;
m_ssthresh = Math.max(nInFlight / 2, 2 * m_mss); m_ssthresh = Math.max(nInFlight / 2, 2 * m_mss);
//Logger.Log(LS_INFO) << "m_ssthresh: " << m_ssthresh << " nInFlight: " << nInFlight << " m_mss: " << m_mss; //Logger.Log(LS_INFO)
// << "m_ssthresh: " << m_ssthresh << " nInFlight: " << nInFlight << " m_mss: " << m_mss;
m_cwnd = m_ssthresh + 3 * m_mss; m_cwnd = m_ssthresh + 3 * m_mss;
} }
else else
@ -1757,11 +1758,11 @@ public class PseudoTCPBase
else else
{ {
m_t_ack = now(); m_t_ack = now();
if (logger.isLoggable(Level.FINER)) if (logger.isLoggable(Level.FINER))
{ {
logger.log( logger.log(
Level.FINER, "Delayed ack, m_t_ack: " + m_t_ack); Level.FINER, "Delayed ack, m_t_ack: " + m_t_ack);
} }
} }
return; return;
} }
@ -1958,7 +1959,7 @@ public class PseudoTCPBase
options_specified.add(kind); options_specified.add(kind);
} }
if (options_specified.indexOf(TCP_OPT_WND_SCALE) == -1)//options_specified.size() - 1) if (!options_specified.contains(TCP_OPT_WND_SCALE))
{ {
logger.log(Level.WARNING, "Peer doesn't support window scaling"); logger.log(Level.WARNING, "Peer doesn't support window scaling");
if (getM_rwnd_scale() > 0) if (getM_rwnd_scale() > 0)
@ -2123,7 +2124,7 @@ public class PseudoTCPBase
void setConversationID(long convID) void setConversationID(long convID)
{ {
if(m_state != PseudoTcpState.TCP_LISTEN) if (m_state != PseudoTcpState.TCP_LISTEN)
throw new IllegalStateException(); throw new IllegalStateException();
this.m_conv = convID; this.m_conv = convID;
} }

View File

@ -24,13 +24,13 @@ import java.net.*;
* @author Pawel Domas * @author Pawel Domas
*/ */
public class PseudoTcpJavaSocket extends Socket { public class PseudoTcpJavaSocket extends Socket {
public PseudoTcpJavaSocket(long conv_id) throws SocketException { public PseudoTcpJavaSocket(long conv_id) throws SocketException {
super(new PseudoTcpSocketImpl(conv_id)); super(new PseudoTcpSocketImpl(conv_id));
} }
public PseudoTcpJavaSocket(long conv_id, DatagramSocket socket) public PseudoTcpJavaSocket(long conv_id, DatagramSocket socket)
throws SocketException { throws SocketException {
super(new PseudoTcpSocketImpl(conv_id, socket)); super(new PseudoTcpSocketImpl(conv_id, socket));
} }
} }

View File

@ -34,10 +34,10 @@ public class PseudoTcpSocket extends Socket
PseudoTcpSocket(PseudoTcpSocketImpl socketImpl) PseudoTcpSocket(PseudoTcpSocketImpl socketImpl)
throws SocketException throws SocketException
{ {
super(socketImpl); super(socketImpl);
this.socketImpl = socketImpl; this.socketImpl = socketImpl;
} }
/** /**
* *
@ -60,62 +60,62 @@ public class PseudoTcpSocket extends Socket
{ {
socketImpl.setConversationID(convID); socketImpl.setConversationID(convID);
} }
/** /**
* Sets MTU (maximum transmission unit) value * Sets MTU (maximum transmission unit) value
* @param mtu the MTU value * @param mtu the MTU value
*/ */
public void setMTU(int mtu) public void setMTU(int mtu)
{ {
socketImpl.setMTU(mtu); socketImpl.setMTU(mtu);
} }
/** /**
* Gets MTU (maximum transmission unit) value * Gets MTU (maximum transmission unit) value
* @return MTU value * @return MTU value
*/ */
public int getMTU() public int getMTU()
{ {
return socketImpl.getMTU(); return socketImpl.getMTU();
} }
/** /**
* Sets an {@link Option} on this socket. * Sets an {@link Option} on this socket.
* @return PseudoTCP option value * @return PseudoTCP option value
* *
* @param option the option to set on this socket. * @param option the option to set on this socket.
* @see Option * @see Option
*/ */
public long getOption(Option option) public long getOption(Option option)
{ {
return socketImpl.getPTCPOption(option); return socketImpl.getPTCPOption(option);
} }
/** /**
* *
* @param option PseudoTCP option to set * @param option PseudoTCP option to set
* @param optValue option's value * @param optValue option's value
* *
* @see Option * @see Option
*/ */
public void setOption(Option option, long optValue) public void setOption(Option option, long optValue)
{ {
socketImpl.setPTCPOption(option, optValue); socketImpl.setPTCPOption(option, optValue);
} }
/** /**
* Blocking method waits for connection. * Blocking method waits for connection.
* *
* @param timeout for this operation in ms * @param timeout for this operation in ms
* @throws IOException If socket gets closed or timeout expires * @throws IOException If socket gets closed or timeout expires
*/ */
public void accept(int timeout) public void accept(int timeout)
throws IOException throws IOException
{ {
socketImpl.accept(timeout); socketImpl.accept(timeout);
} }
/** /**
* Sets debug name that will be displayed in log messages for this socket * Sets debug name that will be displayed in log messages for this socket
* @param debugName the name of this socket for debug messages * @param debugName the name of this socket for debug messages
*/ */
@ -245,6 +245,7 @@ public class PseudoTcpSocket extends Socket
/** /**
* {@inheritDoc} * {@inheritDoc}
*/ */
@Override
public synchronized void close() public synchronized void close()
throws IOException throws IOException
{ {
@ -256,6 +257,12 @@ public class PseudoTcpSocket extends Socket
} }
} }
@Override
public OutputStream getOutputStream() throws IOException
{
return socketImpl.getOutputStream();
}
/** /**
* Allows to set up the remote address directly. * Allows to set up the remote address directly.
* Otherwise, when using the other <tt>accept</tt> methods, * Otherwise, when using the other <tt>accept</tt> methods,

View File

@ -78,17 +78,10 @@ class PseudoTcpSocketImpl
*/ */
private long readTimeout; private long readTimeout;
/**
*
*/
private PseudoTcpInputStream inputStream; private PseudoTcpInputStream inputStream;
/**
*
*/
private PseudoTcpOutputStream outputstream; private PseudoTcpOutputStream outputstream;
/** /**
* *
* @param conv_id conversation id, must be the same on both sides * @param conv_id conversation id, must be the same on both sides
@ -196,6 +189,7 @@ class PseudoTcpSocketImpl
* @param stream if true, create a stream socket; otherwise, create a datagram socket. * @param stream if true, create a stream socket; otherwise, create a datagram socket.
* @throws IOException if an I/O error occurs while creating the socket. * @throws IOException if an I/O error occurs while creating the socket.
*/ */
@Override
protected void create(boolean stream) protected void create(boolean stream)
throws IOException throws IOException
{ {
@ -208,6 +202,7 @@ class PseudoTcpSocketImpl
* @param port the port number. * @param port the port number.
* @throws IOException * @throws IOException
*/ */
@Override
protected void connect(String host, int port) protected void connect(String host, int port)
throws IOException throws IOException
{ {
@ -220,6 +215,7 @@ class PseudoTcpSocketImpl
* @param port the port number. * @param port the port number.
* @throws IOException if an I/O error occurs when attempting a connection. * @throws IOException if an I/O error occurs when attempting a connection.
*/ */
@Override
protected void connect(InetAddress address, int port) protected void connect(InetAddress address, int port)
throws IOException throws IOException
{ {
@ -234,6 +230,7 @@ class PseudoTcpSocketImpl
* @param timeout the timeout value, in milliseconds, or zero for no timeout. * @param timeout the timeout value, in milliseconds, or zero for no timeout.
* @throws IOException if an I/O error occurs when attempting a connection. * @throws IOException if an I/O error occurs when attempting a connection.
*/ */
@Override
protected void connect(SocketAddress address, int timeout) protected void connect(SocketAddress address, int timeout)
throws IOException throws IOException
{ {
@ -247,12 +244,13 @@ class PseudoTcpSocketImpl
* @param port the port number. * @param port the port number.
* @throws IOException * @throws IOException
*/ */
@Override
public void bind(InetAddress host, int port) public void bind(InetAddress host, int port)
throws IOException throws IOException
{ {
if(socket != null) if (socket != null)
socket.close(); socket.close();
InetSocketAddress newAddr = new InetSocketAddress(host.getHostAddress(),port); InetSocketAddress newAddr = new InetSocketAddress(host.getHostAddress(), port);
this.socket = new DatagramSocket(newAddr); this.socket = new DatagramSocket(newAddr);
} }
@ -264,6 +262,7 @@ class PseudoTcpSocketImpl
* @param backlog the maximum length of the queue. * @param backlog the maximum length of the queue.
* @throws IOException if an I/O error occurs when creating the queue. * @throws IOException if an I/O error occurs when creating the queue.
*/ */
@Override
protected void listen(int backlog) protected void listen(int backlog)
throws IOException throws IOException
{ {
@ -271,6 +270,7 @@ class PseudoTcpSocketImpl
} }
private Map<Integer, Object> options = new HashMap<>(); private Map<Integer, Object> options = new HashMap<>();
@Override
public void setOption(int optID, Object value) public void setOption(int optID, Object value)
throws SocketException throws SocketException
{ {
@ -278,31 +278,32 @@ class PseudoTcpSocketImpl
options.put(optID, value); options.put(optID, value);
} }
@Override
public Object getOption(int optID) public Object getOption(int optID)
throws SocketException throws SocketException
{ {
//TODO: map options to PTCP options/method calls //TODO: map options to PTCP options/method calls
if(optID == SocketOptions.TCP_NODELAY) if (optID == SocketOptions.TCP_NODELAY)
{ {
Object ret = options.get(Option.OPT_NODELAY.ordinal()); Object ret = options.get(Option.OPT_NODELAY.ordinal());
return ret != null; return ret != null;
} }
Object option = options.get(optID); Object option = options.get(optID);
if(option == null) if (option == null)
{ {
logger.warning("Asked for unknown optID" + optID); logger.warning("Asked for unknown optID" + optID);
} }
return option; return option;
} }
public long getPTCPOption(Option opt) public long getPTCPOption(Option opt)
{ {
if(Option.OPT_READ_TIMEOUT == opt) if (Option.OPT_READ_TIMEOUT == opt)
{ {
return this.readTimeout; return this.readTimeout;
} }
else if(Option.OPT_WRITE_TIMEOUT == opt) else if (Option.OPT_WRITE_TIMEOUT == opt)
{ {
return this.writeTimeout; return this.writeTimeout;
} }
@ -314,11 +315,11 @@ class PseudoTcpSocketImpl
public void setPTCPOption(Option opt, long optValue) public void setPTCPOption(Option opt, long optValue)
{ {
if(Option.OPT_WRITE_TIMEOUT == opt) if (Option.OPT_WRITE_TIMEOUT == opt)
{ {
this.writeTimeout = optValue >= 0 ? optValue : 0; this.writeTimeout = optValue >= 0 ? optValue : 0;
} }
else if(Option.OPT_READ_TIMEOUT == opt) else if (Option.OPT_READ_TIMEOUT == opt)
{ {
this.readTimeout = optValue >= 0 ? optValue : 0; this.readTimeout = optValue >= 0 ? optValue : 0;
} }
@ -334,7 +335,6 @@ class PseudoTcpSocketImpl
* *
* @param remoteAddress to which this socket connects to * @param remoteAddress to which this socket connects to
* @param timeout for this operation in ms * @param timeout for this operation in ms
* @throws IOException
*/ */
void doConnect(InetSocketAddress remoteAddress, long timeout) void doConnect(InetSocketAddress remoteAddress, long timeout)
throws IOException throws IOException
@ -355,10 +355,9 @@ class PseudoTcpSocketImpl
while (pseudoTcp.getState() != PseudoTcpState.TCP_ESTABLISHED while (pseudoTcp.getState() != PseudoTcpState.TCP_ESTABLISHED
&& (noTimeout || (elapsed < timeout)) ) && (noTimeout || (elapsed < timeout)) )
{ {
long start = System.currentTimeMillis(); long start = System.nanoTime();
state_notify.wait(timeout); state_notify.wait(timeout);
long end = System.currentTimeMillis(); elapsed += TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start);
elapsed += end - start;
} }
if (pseudoTcp.getState() != PseudoTcpState.TCP_ESTABLISHED) if (pseudoTcp.getState() != PseudoTcpState.TCP_ESTABLISHED)
{ {
@ -431,6 +430,7 @@ class PseudoTcpSocketImpl
* @param s the accepted connection. * @param s the accepted connection.
* @throws IOException if an I/O error occurs when accepting the connection. * @throws IOException if an I/O error occurs when accepting the connection.
*/ */
@Override
protected void accept(SocketImpl s) protected void accept(SocketImpl s)
throws IOException throws IOException
{ {
@ -453,7 +453,7 @@ class PseudoTcpSocketImpl
*/ */
private void updateClock() private void updateClock()
{ {
scheduleClockTask(0); scheduleClockTask(0);
} }
/** /**
@ -464,6 +464,7 @@ class PseudoTcpSocketImpl
pseudoTcp.notifyClock(PseudoTCPBase.now()); pseudoTcp.notifyClock(PseudoTCPBase.now());
receiveThread = new Thread(new Runnable() receiveThread = new Thread(new Runnable()
{ {
@Override
public void run() public void run()
{ {
receivePackets(); receivePackets();
@ -483,6 +484,7 @@ class PseudoTcpSocketImpl
* @param tcp the {@link PseudoTCPBase} that caused an event * @param tcp the {@link PseudoTCPBase} that caused an event
* @see PseudoTcpNotify#onTcpOpen(PseudoTCPBase) * @see PseudoTcpNotify#onTcpOpen(PseudoTCPBase)
*/ */
@Override
public void onTcpOpen(PseudoTCPBase tcp) public void onTcpOpen(PseudoTCPBase tcp)
{ {
logger.log(Level.FINE, "tcp opened"); logger.log(Level.FINE, "tcp opened");
@ -501,9 +503,10 @@ class PseudoTcpSocketImpl
* @param tcp the {@link PseudoTCPBase} that caused an event * @param tcp the {@link PseudoTCPBase} that caused an event
* @see PseudoTcpNotify#onTcpReadable(PseudoTCPBase) * @see PseudoTcpNotify#onTcpReadable(PseudoTCPBase)
*/ */
@Override
public void onTcpReadable(PseudoTCPBase tcp) public void onTcpReadable(PseudoTCPBase tcp)
{ {
if(logger.isLoggable(Level.FINER)) if (logger.isLoggable(Level.FINER))
{ {
logger.log( logger.log(
Level.FINER, Level.FINER,
@ -522,6 +525,7 @@ class PseudoTcpSocketImpl
* @param tcp the {@link PseudoTCPBase} that caused an event * @param tcp the {@link PseudoTCPBase} that caused an event
* @see PseudoTcpNotify#onTcpWriteable(PseudoTCPBase) * @see PseudoTcpNotify#onTcpWriteable(PseudoTCPBase)
*/ */
@Override
public void onTcpWriteable(PseudoTCPBase tcp) public void onTcpWriteable(PseudoTCPBase tcp)
{ {
@ -545,6 +549,7 @@ class PseudoTcpSocketImpl
* *
* @see PseudoTcpNotify#onTcpClosed(PseudoTCPBase, IOException) * @see PseudoTcpNotify#onTcpClosed(PseudoTCPBase, IOException)
*/ */
@Override
public void onTcpClosed(PseudoTCPBase tcp, IOException e) public void onTcpClosed(PseudoTCPBase tcp, IOException e)
{ {
if (e != null) if (e != null)
@ -560,7 +565,7 @@ class PseudoTcpSocketImpl
runClock = false; runClock = false;
this.exception = e; this.exception = e;
releaseAllLocks(); releaseAllLocks();
cancelClockTask(true); cancelClockTask(true);
} }
@ -606,6 +611,7 @@ class PseudoTcpSocketImpl
* *
* @see PseudoTcpNotify#tcpWritePacket(PseudoTCPBase, byte[], int) * @see PseudoTcpNotify#tcpWritePacket(PseudoTCPBase, byte[], int)
*/ */
@Override
public WriteResult tcpWritePacket(PseudoTCPBase tcp, byte[] buffer, int len) public WriteResult tcpWritePacket(PseudoTCPBase tcp, byte[] buffer, int len)
{ {
if (logger.isLoggable(Level.FINEST)) if (logger.isLoggable(Level.FINEST))
@ -709,74 +715,69 @@ class PseudoTcpSocketImpl
*/ */
private void runClock() private void runClock()
{ {
if(!runClock) if (!runClock)
{ {
return; return;
} }
long sleep; long sleep;
synchronized (pseudoTcp) synchronized (pseudoTcp)
{ {
pseudoTcp.notifyClock(PseudoTCPBase.now()); pseudoTcp.notifyClock(PseudoTCPBase.now());
sleep = pseudoTcp.getNextClock(PseudoTCPBase.now()); sleep = pseudoTcp.getNextClock(PseudoTCPBase.now());
} }
//there might be negative interval even if there's no error //there might be negative interval even if there's no error
if (sleep == -1) if (sleep == -1)
{ {
releaseAllLocks(); releaseAllLocks();
if (exception != null) if (exception != null)
{ {
logger.log(Level.SEVERE, logger.log(Level.SEVERE,
"STATE: " + pseudoTcp.getState() "STATE: " + pseudoTcp.getState()
+ " ERROR: " + exception.getMessage()); + " ERROR: " + exception.getMessage());
} }
} }
else else
{ {
//logger.log(Level.FINEST, "Clock sleep for " + sleep); //logger.log(Level.FINEST, "Clock sleep for " + sleep);
scheduleClockTask(sleep); scheduleClockTask(sleep);
} }
} }
private Runnable clockTaskRunner = new Runnable() private final Runnable clockTaskRunner = this::runClock;
{
@Override
public void run() {
runClock();
}
};
private void scheduleClockTask(long sleep) private void scheduleClockTask(long sleep)
{ {
synchronized (clockTaskRunner) synchronized (clockTaskRunner)
{ {
// Cancel any existing tasks, to make sure we don't run duplicates. // Cancel any existing tasks, to make sure we don't run duplicates.
cancelClockTask(false); cancelClockTask(false);
if(runClock) if (runClock)
{ {
currentlyScheduledClockTask currentlyScheduledClockTask
= clockExecutor.schedule( = clockExecutor.schedule(
clockTaskRunner, sleep, TimeUnit.MILLISECONDS); clockTaskRunner, sleep, TimeUnit.MILLISECONDS);
} }
} }
} }
private void cancelClockTask(boolean interruptIfRunning) private void cancelClockTask(boolean interruptIfRunning)
{ {
// Copy the reference, in case it changes. // Copy the reference, in case it changes.
ScheduledFuture<?> taskToCancel = this.currentlyScheduledClockTask; ScheduledFuture<?> taskToCancel = this.currentlyScheduledClockTask;
if(taskToCancel != null) if (taskToCancel != null)
{ {
taskToCancel.cancel(interruptIfRunning); taskToCancel.cancel(interruptIfRunning);
} }
} }
/** /**
* Returns an output stream for this socket. * Returns an output stream for this socket.
* @return an output stream for writing to this socket. * @return an output stream for writing to this socket.
* @throws IOException if an I/O error occurs when creating the output stream. * @throws IOException if an I/O error occurs when creating the output stream.
*/ */
@Override
public OutputStream getOutputStream() public OutputStream getOutputStream()
throws IOException throws IOException
{ {
@ -793,6 +794,7 @@ class PseudoTcpSocketImpl
* @return a stream for reading from this socket. * @return a stream for reading from this socket.
* @throws IOException * @throws IOException
*/ */
@Override
public InputStream getInputStream() public InputStream getInputStream()
throws IOException throws IOException
{ {
@ -808,6 +810,7 @@ class PseudoTcpSocketImpl
* @return the number of bytes that can be read from this socket without blocking. * @return the number of bytes that can be read from this socket without blocking.
* @throws IOException if an I/O error occurs when determining the number of bytes available. * @throws IOException if an I/O error occurs when determining the number of bytes available.
*/ */
@Override
protected int available() protected int available()
throws IOException throws IOException
{ {
@ -816,16 +819,16 @@ class PseudoTcpSocketImpl
/** /**
* Closes this socket. * Closes this socket.
* @throws IOException
*/ */
@Override
public void close() public void close()
throws IOException throws IOException
{ {
try try
{ {
pseudoTcp.close(true); pseudoTcp.close(true);
//System.out.println("ON CLOSE: in flight "+pseudoTcp.GetBytesInFlight()); //System.out.println("ON CLOSE: in flight "+pseudoTcp.getBytesInFlight());
//System.out.println("ON CLOSE: buff not sent "+pseudoTcp.GetBytesBufferedNotSent()); //System.out.println("ON CLOSE: buff not sent "+pseudoTcp.getBytesBufferedNotSent());
onTcpClosed(pseudoTcp, null); onTcpClosed(pseudoTcp, null);
socket.close(); socket.close();
joinAllThreads(); joinAllThreads();
@ -851,6 +854,7 @@ class PseudoTcpSocketImpl
* @param data The byte of data to send * @param data The byte of data to send
* @throws IOException if there is an error sending the data. * @throws IOException if there is an error sending the data.
*/ */
@Override
protected void sendUrgentData(int data) protected void sendUrgentData(int data)
throws IOException throws IOException
{ {
@ -908,7 +912,7 @@ class PseudoTcpSocketImpl
public int read(byte[] buffer, int offset, int length) public int read(byte[] buffer, int offset, int length)
throws IOException throws IOException
{ {
long start = System.currentTimeMillis(); long start = System.nanoTime();
int read; int read;
while (true) while (true)
{ {
@ -926,12 +930,12 @@ class PseudoTcpSocketImpl
return read; return read;
} }
logger.log(Level.FINER, "Read wait for data available"); logger.log(Level.FINER, "Read wait for data available");
if(readTimeout > 0) if (readTimeout > 0)
{ {
//Check for timeout //Check for timeout
long elapsed = System.currentTimeMillis() - start; long elapsed = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start);
long left = readTimeout - elapsed; long left = readTimeout - elapsed;
if(left <= 0) if (left <= 0)
{ {
IOException exc = IOException exc =
new IOException("Read operation timeout"); new IOException("Read operation timeout");
@ -940,7 +944,7 @@ class PseudoTcpSocketImpl
} }
synchronized (read_notify) synchronized (read_notify)
{ {
if(pseudoTcp.getAvailable() == 0) if (pseudoTcp.getAvailable() == 0)
{ {
read_notify.wait(left); read_notify.wait(left);
} }
@ -950,7 +954,7 @@ class PseudoTcpSocketImpl
{ {
synchronized (read_notify) synchronized (read_notify)
{ {
if(pseudoTcp.getAvailable() == 0) if (pseudoTcp.getAvailable() == 0)
{ {
read_notify.wait(); read_notify.wait();
} }
@ -1033,12 +1037,6 @@ class PseudoTcpSocketImpl
write(bytes); write(bytes);
} }
@Override
public void write(byte[] bytes) throws IOException
{
write(bytes, 0, bytes.length);
}
/** /**
* This method blocks until all data has been written. * This method blocks until all data has been written.
* *
@ -1053,7 +1051,7 @@ class PseudoTcpSocketImpl
{ {
int toSend = length; int toSend = length;
int sent; int sent;
long start = System.currentTimeMillis(); long start = System.nanoTime();
while (toSend > 0) while (toSend > 0)
{ {
synchronized (pseudoTcp) synchronized (pseudoTcp)
@ -1071,11 +1069,11 @@ class PseudoTcpSocketImpl
logger.log(Level.FINER, "Write wait for notify"); logger.log(Level.FINER, "Write wait for notify");
synchronized (write_notify) synchronized (write_notify)
{ {
if(writeTimeout > 0) if (writeTimeout > 0)
{ {
long elapsed = System.currentTimeMillis() - start; long elapsed = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start);
long left = writeTimeout - elapsed; long left = writeTimeout - elapsed;
if(left <= 0) if (left <= 0)
{ {
IOException exc = IOException exc =
new IOException("Write operation timeout"); new IOException("Write operation timeout");
@ -1121,7 +1119,7 @@ class PseudoTcpSocketImpl
public synchronized void flush() throws IOException public synchronized void flush() throws IOException
{ {
logger.log(Level.FINE, "Flushing..."); logger.log(Level.FINE, "Flushing...");
long start = System.currentTimeMillis(); long start = System.nanoTime();
final Object ackNotify = pseudoTcp.getAckNotify(); final Object ackNotify = pseudoTcp.getAckNotify();
synchronized (ackNotify) synchronized (ackNotify)
{ {
@ -1129,12 +1127,12 @@ class PseudoTcpSocketImpl
{ {
try try
{ {
if(writeTimeout > 0) if (writeTimeout > 0)
{ {
//Check write timeout //Check write timeout
long elapsed = System.currentTimeMillis() - start; long elapsed = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start);
long left = writeTimeout - elapsed; long left = writeTimeout - elapsed;
if(left <= 0) if (left <= 0)
{ {
IOException e = IOException e =
new IOException("Flush operation timeout"); new IOException("Flush operation timeout");
@ -1151,7 +1149,7 @@ class PseudoTcpSocketImpl
catch (InterruptedException ex) catch (InterruptedException ex)
{ {
throw new IOException("Flush stream interrupted", ex); throw new IOException("Flush stream interrupted", ex);
} }
} }
} }
logger.log(Level.FINE, "Flushing completed"); logger.log(Level.FINE, "Flushing completed");
@ -1160,6 +1158,7 @@ class PseudoTcpSocketImpl
@Override @Override
public void close() throws IOException public void close() throws IOException
{ {
PseudoTcpSocketImpl.this.close();
} }
} }

View File

@ -26,23 +26,23 @@ public enum PseudoTcpState
/** /**
* Initial state, can accept connection * Initial state, can accept connection
*/ */
TCP_LISTEN,// = 0, TCP_LISTEN, // = 0,
/** /**
* SYN sent to remote peer, wits for SYN * SYN sent to remote peer, wits for SYN
*/ */
TCP_SYN_SENT,// = 1, TCP_SYN_SENT, // = 1,
/** /**
* SYN received from remote peer, sends back SYN * SYN received from remote peer, sends back SYN
*/ */
TCP_SYN_RECEIVED,// = 2; TCP_SYN_RECEIVED, // = 2;
/** /**
* SYN sent and received - connection established * SYN sent and received - connection established
*/ */
TCP_ESTABLISHED,// = 3; TCP_ESTABLISHED, // = 3;
/** /**
* Closed state. In current implementation reached on error * Closed state. In current implementation reached on error
* or explicite by close method with force option * or explicite by close method with force option
* TODO: closing procedure * TODO: closing procedure
*/ */
TCP_CLOSED// = 4; TCP_CLOSED // = 4;
} }

View File

@ -225,7 +225,7 @@ public class DelegatingDatagramSocket
// Delegates the DatagramSocket functionality to the DatagramSocket // Delegates the DatagramSocket functionality to the DatagramSocket
// given in parameter. // given in parameter.
if(delegate != null) if (delegate != null)
{ {
this.delegate = delegate; this.delegate = delegate;
} }
@ -233,7 +233,7 @@ public class DelegatingDatagramSocket
{ {
// Creates a custom DatagramSocket to replace classical "java" // Creates a custom DatagramSocket to replace classical "java"
// DatagramSocket and set it as a delegate Socket // DatagramSocket and set it as a delegate Socket
if(delegateFactory != null) if (delegateFactory != null)
{ {
this.delegate = delegateFactory.createUnboundDatagramSocket(); this.delegate = delegateFactory.createUnboundDatagramSocket();
} }
@ -741,7 +741,7 @@ public class DelegatingDatagramSocket
catch(Exception ex) catch(Exception ex)
{ {
InetAddress tmpAddr = p.getAddress(); InetAddress tmpAddr = p.getAddress();
if(((ex instanceof NoRouteToHostException) if (((ex instanceof NoRouteToHostException)
|| (ex.getMessage() != null || (ex.getMessage() != null
&& ex.getMessage().equals("No route to host"))) && ex.getMessage().equals("No route to host")))
&& (tmpAddr instanceof Inet6Address) && (tmpAddr instanceof Inet6Address)
@ -755,9 +755,10 @@ public class DelegatingDatagramSocket
p.setAddress(newAddr); p.setAddress(newAddr);
super.send(p); super.send(p);
}
} else if (ex instanceof IOException) { else if (ex instanceof IOException)
throw((IOException)ex); {
throw((IOException)ex);
} }
} }
@ -940,7 +941,7 @@ public class DelegatingDatagramSocket
throws SocketException throws SocketException
{ {
// Only change the buffer size on the real underlying DatagramSocket. // Only change the buffer size on the real underlying DatagramSocket.
if(delegate == null && defaultReceiveBufferSize > 0) if (delegate == null && defaultReceiveBufferSize > 0)
{ {
super.setReceiveBufferSize(defaultReceiveBufferSize); super.setReceiveBufferSize(defaultReceiveBufferSize);
} }

View File

@ -796,7 +796,7 @@ public class DelegatingSocket
*/ */
public void setOriginalInputStream(InputStream inputStream) public void setOriginalInputStream(InputStream inputStream)
{ {
if(this.inputStream == null && inputStream != null) if (this.inputStream == null && inputStream != null)
this.inputStream = inputStream; this.inputStream = inputStream;
} }

View File

@ -250,12 +250,12 @@ public class GoogleRelayedCandidateSocket
public OutputStream getOutputStream() public OutputStream getOutputStream()
throws IOException throws IOException
{ {
if(outputStream == null) if (outputStream == null)
{ {
CandidatePair pair = CandidatePair pair =
relayedCandidate.getParentComponent().getSelectedPair(); relayedCandidate.getParentComponent().getSelectedPair();
if(pair.getLocalCandidate() == relayedCandidate) if (pair.getLocalCandidate() == relayedCandidate)
{ {
TransportAddress target = pair.getRemoteCandidate(). TransportAddress target = pair.getRemoteCandidate().
getTransportAddress(); getTransportAddress();

View File

@ -107,7 +107,7 @@ public class IceTcpServerSocketWrapper
{ {
isRun = false; isRun = false;
serverSocket.close(); serverSocket.close();
for(Socket s : sockets) for (Socket s : sockets)
{ {
s.close(); s.close();
} }
@ -150,7 +150,7 @@ public class IceTcpServerSocketWrapper
@Override @Override
public Socket getTCPSocket() public Socket getTCPSocket()
{ {
if(sockets.size() > 0) if (sockets.size() > 0)
{ {
return sockets.get(0); return sockets.get(0);
} }
@ -182,13 +182,13 @@ public class IceTcpServerSocketWrapper
{ {
isRun = true; isRun = true;
while(isRun) while (isRun)
{ {
try try
{ {
Socket tcpSocket = serverSocket.accept(); Socket tcpSocket = serverSocket.accept();
if(tcpSocket != null) if (tcpSocket != null)
{ {
MultiplexingSocket multiplexingSocket = MultiplexingSocket multiplexingSocket =
new MultiplexingSocket(tcpSocket); new MultiplexingSocket(tcpSocket);

View File

@ -18,13 +18,12 @@
package org.ice4j.socket; package org.ice4j.socket;
import org.ice4j.*; import org.ice4j.*;
import org.jitsi.utils.logging2.*;
import java.io.*; import java.io.*;
import java.net.*; import java.net.*;
import java.util.*; import java.util.*;
import java.util.concurrent.*; import java.util.concurrent.*;
import java.util.logging.*;
import org.ice4j.util.Logger; //Disambiguation
/** /**
* A {@link DatagramSocket} implementation which merges a set of sockets. * A {@link DatagramSocket} implementation which merges a set of sockets.
@ -44,14 +43,6 @@ import org.ice4j.util.Logger; //Disambiguation
public class MergingDatagramSocket public class MergingDatagramSocket
extends DatagramSocket extends DatagramSocket
{ {
/**
* The {@link Logger} used by the {@link MergingDatagramSocket} class and
* its instances for logging output.
*/
private static final java.util.logging.Logger classLogger
= java.util.logging.Logger.getLogger(
MergingDatagramSocket.class.getName());
/** /**
* Used to control access to {@link #socketContainers}. * Used to control access to {@link #socketContainers}.
*/ */
@ -97,7 +88,7 @@ public class MergingDatagramSocket
/** /**
* The {@link Logger} used by {@link MergingDatagramSocket} instances. * The {@link Logger} used by {@link MergingDatagramSocket} instances.
*/ */
private final Logger logger; protected final Logger logger;
/** /**
* Initializes a new {@link MergingDatagramSocket} instance. * Initializes a new {@link MergingDatagramSocket} instance.
@ -111,14 +102,14 @@ public class MergingDatagramSocket
/** /**
* Initializes a new {@link MergingDatagramSocket} instance. * Initializes a new {@link MergingDatagramSocket} instance.
* @param levelDelegate the {@link Logger} instance which dictates the * @param parentLogger the {@link Logger} parent logger from which we'll
* logging level for the new {@link MergingDatagramSocket} instance. * derive this class' logger instance
* @throws SocketException * @throws SocketException
*/ */
public MergingDatagramSocket(Logger levelDelegate) public MergingDatagramSocket(Logger parentLogger)
throws SocketException throws SocketException
{ {
logger = new Logger(classLogger, levelDelegate); logger = parentLogger.createChildLogger(this.getClass().getName());
} }
/** /**
@ -220,11 +211,8 @@ public class MergingDatagramSocket
public void add(DelegatingSocket socket) public void add(DelegatingSocket socket)
{ {
Objects.requireNonNull(socket, "socket"); Objects.requireNonNull(socket, "socket");
if (logger.isLoggable(Level.FINE)) logger.debug(() -> "Adding a DelegatingSocket instance: "
{ + socket.getLocalAddress());
logger.fine("Adding a DelegatingSocket instance: "
+ socket.getLocalAddress());
}
doAdd(socket); doAdd(socket);
} }
@ -251,11 +239,8 @@ public class MergingDatagramSocket
public void add(DatagramSocket socket) public void add(DatagramSocket socket)
{ {
Objects.requireNonNull(socket, "socket"); Objects.requireNonNull(socket, "socket");
if (logger.isLoggable(Level.FINE)) logger.debug(() -> "Adding a DatagramSocket instance: "
{ + socket.getLocalAddress());
logger.fine("Adding a DatagramSocket instance: "
+ socket.getLocalAddress());
}
doAdd(socket); doAdd(socket);
} }
@ -280,7 +265,7 @@ public class MergingDatagramSocket
{ {
if (indexOf(socketContainers, socket) != -1) if (indexOf(socketContainers, socket) != -1)
{ {
logger.warning("Socket already added."); logger.warn("Socket already added.");
return; return;
} }
@ -361,7 +346,7 @@ public class MergingDatagramSocket
if (socketContainer == active) if (socketContainer == active)
{ {
// TODO: proper selection of a new active socket // TODO: proper selection of a new active socket
logger.warning( logger.warn(
"Removing the active socket. Won't be able to send " "Removing the active socket. Won't be able to send "
+ "until a new one is elected."); + "until a new one is elected.");
active = null; active = null;
@ -369,13 +354,13 @@ public class MergingDatagramSocket
} }
else else
{ {
logger.severe("Cannot find socket to remove."); logger.error("Cannot find socket to remove.");
} }
} }
if (logger.isLoggable(Level.FINE)) if (logger.isDebugEnabled())
{ {
logger.fine("Removed: " + socketContainer); logger.debug("Removed: " + socketContainer);
} }
if (socketContainer != null) if (socketContainer != null)
{ {
@ -595,10 +580,10 @@ public class MergingDatagramSocket
socket = socketWrapper.getUDPSocket(); socket = socketWrapper.getUDPSocket();
} }
if (logger.isLoggable(Level.FINE)) if (logger.isDebugEnabled())
{ {
logger.fine("Initializing the active container, socket=" + socket logger.debug("Initializing the active container, socket=" + socket
+ "; remote address=" + remoteAddress); + "; remote address=" + remoteAddress);
} }
synchronized (socketContainersSyncRoot) synchronized (socketContainersSyncRoot)
@ -611,7 +596,7 @@ public class MergingDatagramSocket
// is not necessarily incorrect. // is not necessarily incorrect.
// Still, go on and replace the active socket with whatever // Still, go on and replace the active socket with whatever
// ICE selected. // ICE selected.
logger.warning("Active socket already initialized."); logger.warn("Active socket already initialized.");
} }
SocketContainer newActive = null; SocketContainer newActive = null;
@ -627,7 +612,7 @@ public class MergingDatagramSocket
if (newActive == null) if (newActive == null)
{ {
logger.severe("No SocketContainer found!"); logger.error("No SocketContainer found!");
return; return;
} }
@ -742,12 +727,9 @@ public class MergingDatagramSocket
+ getLocalSocketAddress() + " -> " + getLocalSocketAddress() + " -> "
+ getRemoteSocketAddress()); + getRemoteSocketAddress());
if (logger.isLoggable(Level.FINE)) logger.debug(() -> "Starting the thread for socket "
{ + getLocalSocketAddress() + " -> "
logger.fine("Starting the thread for socket " + getRemoteSocketAddress());
+ getLocalSocketAddress() + " -> "
+ getRemoteSocketAddress());
}
thread.start(); thread.start();
} }
@ -810,10 +792,7 @@ public class MergingDatagramSocket
// container anymore. // container anymore.
close(true); close(true);
if (logger.isLoggable(Level.FINE)) logger.debug(() -> "Finished: " + toString());
{
logger.fine("Finished: " + toString());
}
} }
/** /**
@ -874,11 +853,7 @@ public class MergingDatagramSocket
synchronized (socketContainersSyncRoot) synchronized (socketContainersSyncRoot)
{ {
MergingDatagramSocket.this.active = this; MergingDatagramSocket.this.active = this;
if (logger.isLoggable(Level.FINE)) logger.debug(() -> "Switching to new active socket: " + this);
{
logger.fine("Switching to new active socket: "
+ this);
}
} }
} }
} }

View File

@ -276,7 +276,7 @@ public class MultiplexedSocket
public void reset() public void reset()
throws IOException throws IOException
{ {
if(!markSupported()) if (!markSupported())
{ {
throw new IOException( throw new IOException(
"InputStreamImpl does not support reset()"); "InputStreamImpl does not support reset()");

View File

@ -322,7 +322,7 @@ public class MultiplexingSocket
@Override @Override
public int getSoTimeout() public int getSoTimeout()
{ {
return soTimeout; return soTimeout;
} }
/** /**
@ -427,10 +427,10 @@ public class MultiplexingSocket
*/ */
@Override @Override
public void setSoTimeout(int timeout) public void setSoTimeout(int timeout)
throws SocketException throws SocketException
{ {
super.setSoTimeout(timeout); super.setSoTimeout(timeout);
soTimeout = timeout; soTimeout = timeout;
} }
} }

View File

@ -18,11 +18,9 @@
package org.ice4j.socket; package org.ice4j.socket;
import java.io.*; import java.io.*;
import java.lang.reflect.*;
import java.net.*; import java.net.*;
import java.nio.channels.*; import java.nio.channels.*;
import java.util.*; import java.util.*;
import java.util.logging.*;
/** /**
* If supported by the runtime, initializes {@link ServerSocketChannel}s which * If supported by the runtime, initializes {@link ServerSocketChannel}s which
@ -33,19 +31,6 @@ import java.util.logging.*;
*/ */
public class MuxServerSocketChannelFactory public class MuxServerSocketChannelFactory
{ {
/**
* The {@code Logger} used by the {@code MuxServerSocketChannelFactory}
* class (and its instances) to print debug information.
*/
private static final Logger logger
= Logger.getLogger(MuxServerSocketChannelFactory.class.getName());
/**
* The reflection of the {@code openAndBind} method of the
* {@code MuxServerSocketChannel} class.
*/
private static final Method OPEN_AND_BIND_METHOD;
/** /**
* The maximum number of milliseconds to wait for an accepted * The maximum number of milliseconds to wait for an accepted
* {@code SocketChannel} to provide incoming/readable data before it is * {@code SocketChannel} to provide incoming/readable data before it is
@ -56,158 +41,12 @@ public class MuxServerSocketChannelFactory
/** /**
* The name of the {@code boolean} property of the {@code socket} property * The name of the {@code boolean} property of the {@code socket} property
* of the {@code ServerSocketChannel} returned by * of the {@code ServerSocketChannel} returned by
* {@link #openAndBindMuxServerSocketChannel(Map, SocketAddress, int, * {@link #openAndBindServerSocketChannel(Map, SocketAddress, int)} which
* DatagramPacketFilter)} which specifies the value of the * specifies the value of the {@code SO_REUSEADDR} socket option.
* {@code SO_REUSEADDR} socket option.
*/ */
public static final String SOCKET_REUSE_ADDRESS_PROPERTY_NAME public static final String SOCKET_REUSE_ADDRESS_PROPERTY_NAME
= "socket.reuseAddress"; = "socket.reuseAddress";
static
{
Class<?> clazz;
try
{
clazz
= Class.forName("org.ice4j.socket.jdk8.MuxServerSocketChannel");
}
catch (ClassNotFoundException cnfex)
{
// The class cannot be located probably because ICE4J was not built
// on JDK 8.
clazz = null;
logger.warning(
"ICE4J does not support sharing of listening endpoints"
+ " (probably because it was not built on JDK 8).");
}
catch (LinkageError lerr)
{
// The linkage fails probably because ICE4J was built on JDK 8 but
// is not run on JDK 8.
clazz = null;
logger.warning(
"ICE4J does not support sharing of listening endpoints"
+ " (probably because it is not running on JDK 8).");
}
Method method;
if (clazz == null)
{
method = null;
}
else
{
try
{
method
= clazz.getDeclaredMethod(
"openAndBind",
Map.class,
SocketAddress.class,
int.class,
DatagramPacketFilter.class);
}
catch (NoSuchMethodException nsmex)
{
throw new RuntimeException(nsmex);
}
}
OPEN_AND_BIND_METHOD = method;
}
/**
* Closes a {@code Channel} and swallows any {@link IOException}.
*
* @param channel the {@code Channel} to close
*/
public static void closeNoExceptions(Channel channel)
{
try
{
channel.close();
}
catch (IOException ioe)
{
// The whole idea of the method is to close a specific Channel
// without caring about any possible IOException.
}
}
/**
* Opens and binds a new {@code MuxServerSocketChannel} instance if
* supported by the runtime. If there are other (existing)
* {@code MuxServerSocketChannel} open and bound on the specified listening
* {@code endpoint}, the new instance will share it with them. If the
* sharing of listening endpoints is not supported by the runtime, falls
* back to {@link #openAndBindServerSocketChannel(Map, SocketAddress, int)}.
*
* @param properties a {@code Map} of the values to be assigned to
* properties of the underlying {@link ServerSocketChannel} which is to
* actually listen on the specified {@code endpoint}. If the new instance is
* not the first to open and bind the specified {@code endpoint}, the
* {@code properties} and their respective values may not be used.
* @param endpoint the IP and port the new instance is to bind to
* @param backlog the requested maximum number of pending incoming
* connections to be queued. If the new instance is not the first to open
* and bind the specified {@code endpoint}, the value may not be used.
* @param filter the {@code DatagramPacketFilter} to demultiplex (i.e.
* recognize) the content meant for the new instance
* @return a new {@code MuxServerSocketChannel} instance open and bound on
* the specified listening {@code endpoint}
* @throws IOException if an I/O error occurs
*/
public static ServerSocketChannel openAndBindMuxServerSocketChannel(
Map<String,Object> properties,
SocketAddress endpoint,
int backlog,
DatagramPacketFilter filter)
throws IOException
{
Method method = OPEN_AND_BIND_METHOD;
if (method == null)
{
return
openAndBindServerSocketChannel(properties, endpoint, backlog);
}
else
{
try
{
return
(ServerSocketChannel)
method.invoke(
null,
properties, endpoint, backlog, filter);
}
catch (IllegalAccessException iaex)
{
IllegalAccessError iaerr
= new IllegalAccessError(iaex.getMessage());
iaerr.initCause(iaex);
throw iaerr;
}
catch (InvocationTargetException itex)
{
Throwable cause = itex.getCause();
if (cause == null)
throw new RuntimeException(itex);
else if (cause instanceof Error)
throw (Error) cause;
else if (cause instanceof IOException)
throw (IOException) cause;
else if (cause instanceof RuntimeException)
throw (RuntimeException) cause;
else
throw new RuntimeException(cause);
}
}
}
/** /**
* Opens and binds a new {@code ServerSocketChannel} instance. * Opens and binds a new {@code ServerSocketChannel} instance.
* *
@ -225,7 +64,7 @@ public class MuxServerSocketChannelFactory
* @throws IOException if an I/O error occurs * @throws IOException if an I/O error occurs
*/ */
public static ServerSocketChannel openAndBindServerSocketChannel( public static ServerSocketChannel openAndBindServerSocketChannel(
Map<String,Object> properties, Map<String, Object> properties,
SocketAddress endpoint, SocketAddress endpoint,
int backlog) int backlog)
throws IOException throws IOException
@ -236,7 +75,7 @@ public class MuxServerSocketChannelFactory
if (properties != null && !properties.isEmpty()) if (properties != null && !properties.isEmpty())
{ {
for (Map.Entry<String,Object> property for (Map.Entry<String, Object> property
: properties.entrySet()) : properties.entrySet())
{ {
String name = property.getKey(); String name = property.getKey();
@ -251,7 +90,7 @@ public class MuxServerSocketChannelFactory
else if (value instanceof Boolean) else if (value instanceof Boolean)
on = (Boolean) value; on = (Boolean) value;
else else
on = Boolean.valueOf(value.toString()); on = Boolean.parseBoolean(value.toString());
socket.setReuseAddress(on); socket.setReuseAddress(on);
} }

View File

@ -296,7 +296,7 @@ public class RelayedCandidateDatagramSocket
* DatagramPacket. * DatagramPacket.
*/ */
return length == pLength - padding - CHANNELDATA_LENGTH_LENGTH return length == pLength - padding - CHANNELDATA_LENGTH_LENGTH
|| length == pLength - CHANNELDATA_LENGTH_LENGTH; || length == pLength - CHANNELDATA_LENGTH_LENGTH;
} }
} }
} }
@ -1162,7 +1162,7 @@ public class RelayedCandidateDatagramSocket
} }
} }
/** /**
* Represents a channel which relays data sent through this * Represents a channel which relays data sent through this
* <tt>RelayedCandidateDatagramSocket</tt> to a specific * <tt>RelayedCandidateDatagramSocket</tt> to a specific
* <tt>TransportAddress</tt> via the TURN server associated with this * <tt>TransportAddress</tt> via the TURN server associated with this

View File

@ -184,11 +184,11 @@ public class StunDatagramPacketFilter
// All STUN messages MUST start with a 20-byte header followed by zero // All STUN messages MUST start with a 20-byte header followed by zero
// or more Attributes. // or more Attributes.
if(length >= 20) if (length >= 20)
{ {
// If the MAGIC COOKIE is present this is a STUN packet (RFC5389 // If the MAGIC COOKIE is present this is a STUN packet (RFC5389
// compliant). // compliant).
if(data[offset + 4] == Message.MAGIC_COOKIE[0] if (data[offset + 4] == Message.MAGIC_COOKIE[0]
&& data[offset + 5] == Message.MAGIC_COOKIE[1] && data[offset + 5] == Message.MAGIC_COOKIE[1]
&& data[offset + 6] == Message.MAGIC_COOKIE[2] && data[offset + 6] == Message.MAGIC_COOKIE[2]
&& data[offset + 7] == Message.MAGIC_COOKIE[3]) && data[offset + 7] == Message.MAGIC_COOKIE[3])

View File

@ -1,79 +0,0 @@
/*
* ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
*
* Copyright @ 2015 Atlassian Pty Ltd
*
* 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.
*/
package org.ice4j.socket.jdk8;
import java.net.*;
import java.nio.*;
/**
* Associates a {@link ByteBuffer} with a {@link DatagramPacket} so that the
* {@code ByteBuffer} may be used for writing into a {@code byte} array and the
* {@code DatagramPacket} may be used for reading from the same {@code byte}
* array.
*
* @author Lyubomir Marinov
*/
class DatagramBuffer
extends Timestamped<ByteBuffer>
{
/**
* The {@code DatagramPacket} which is associated with the
* {@link ByteBuffer} {@link #o} and shares its {@code data} with.
*/
private final DatagramPacket datagramPacket;
/**
* Initializes a new {@code DatagramBuffer} instance with a specific
* capacity of {@code byte}s shared between a {@code ByteBuffer} and a
* {@code DatagramPacket}.
*
* @param capacity the maximum number of {@code byte}s to be written into
* and read from the new instance
*/
public DatagramBuffer(int capacity)
{
super(ByteBuffer.allocate(capacity));
datagramPacket
= new DatagramPacket(o.array(), /* offset */ 0, /* length */ 0);
}
/**
* Gets the {@code ByteBuffer} (view) of this instance.
*
* @return the {@code ByteBuffer} (view) of this instance
*/
public ByteBuffer getByteBuffer()
{
return o;
}
/**
* Gets the {@code DatagramPacket} (view) of this instance. The
* {@code length} of the {@code DatagramPacket} equals the {@code position}
* of the {@code ByteBuffer} so that the {@code byte}s written into the
* {@code ByteBuffer} may be read from the {@code DatagramPacket}.
*
* @return the {@code DatagramPacket} (view) of this instance
*/
public DatagramPacket getDatagramPacket()
{
datagramPacket.setLength(getByteBuffer().position());
return datagramPacket;
}
}

View File

@ -1,125 +0,0 @@
/*
* ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
*
* Copyright @ 2015 Atlassian Pty Ltd
*
* 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.
*/
package org.ice4j.socket.jdk8;
import java.io.*;
import java.nio.channels.*;
import org.ice4j.socket.*;
import sun.nio.ch.*;
/**
* Implements a {@code ServerSocketChannel} which delegates (its method calls)
* to another {@code ServerSocketChannel}. In other words, the former wraps the
* latter.
*
* @author Lyubomir Marinov
*/
class DelegatingServerSocketChannel<T extends ServerSocketChannel>
extends BaseDelegatingServerSocketChannel<T>
implements SelChImpl
{
/**
* The view of {@link #delegate} as a <tt>SelChImpl</tt> interface instance
* required by {@link Selector} and related functionality.
*/
protected final SelChImpl delegateAsSelChImpl;
/**
* Initializes a new {@code DelegatingServerSocketChannel} instance which is
* to delegate (its method calls) to a specific {@code ServerSocketChannel}.
*
* @param delegate the {@code ServerSocketChannel} the new instance is to
* delegate (its method calls) to
*/
public DelegatingServerSocketChannel(T delegate)
{
super(delegate);
delegateAsSelChImpl
= (delegate instanceof SelChImpl) ? (SelChImpl) delegate : null;
}
/**
* {@inheritDoc}
*
* Forwards to {@link #delegate}.
*/
@Override
public FileDescriptor getFD()
{
return delegateAsSelChImpl.getFD();
}
/**
* {@inheritDoc}
*
* Forwards to {@link #delegate}.
*/
@Override
public int getFDVal()
{
return delegateAsSelChImpl.getFDVal();
}
/**
* {@inheritDoc}
*
* Forwards to {@link #delegate}.
*/
@Override
public void kill()
throws IOException
{
delegateAsSelChImpl.kill();
}
/**
* {@inheritDoc}
*
* Forwards to {@link #delegate}.
*/
@Override
public void translateAndSetInterestOps(int ops, SelectionKeyImpl sk)
{
delegateAsSelChImpl.translateAndSetInterestOps(ops, sk);
}
/**
* {@inheritDoc}
*
* Forwards to {@link #delegate}.
*/
@Override
public boolean translateAndSetReadyOps(int ops, SelectionKeyImpl sk)
{
return delegateAsSelChImpl.translateAndSetReadyOps(ops, sk);
}
/**
* {@inheritDoc}
*
* Forwards to {@link #delegate}.
*/
@Override
public boolean translateAndUpdateReadyOps(int ops, SelectionKeyImpl sk)
{
return delegateAsSelChImpl.translateAndUpdateReadyOps(ops, sk);
}
}

View File

@ -1,124 +0,0 @@
/*
* ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
*
* Copyright @ 2015 Atlassian Pty Ltd
*
* 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.
*/
package org.ice4j.socket.jdk8;
import java.io.*;
import java.nio.channels.*;
import org.ice4j.socket.*;
import sun.nio.ch.*;
/**
* Implements a {@code SocketChannel} which delegates (its method calls) to
* another {@code SocketChannel}. In other words, the former wraps the latter.
*
* @author Lyubomir Marinov
*/
class DelegatingSocketChannel<T extends SocketChannel>
extends BaseDelegatingSocketChannel<T>
implements SelChImpl
{
/**
* The view of {@link #delegate} as a <tt>SelChImpl</tt> interface instance
* required by {@link Selector} and related functionality.
*/
protected final SelChImpl delegateAsSelChImpl;
/**
* Initializes a new {@code DelegatingSocketChannel} instance which is to
* delegate (its method calls) to a specific {@code SocketChannel}.
*
* @param delegate the {@code SocketChannel} the new instance is to delegate
* (its method calls) to
*/
public DelegatingSocketChannel(T delegate)
{
super(delegate);
delegateAsSelChImpl
= (delegate instanceof SelChImpl) ? (SelChImpl) delegate : null;
}
/**
* {@inheritDoc}
*
* Forwards to {@link #delegate}.
*/
@Override
public FileDescriptor getFD()
{
return delegateAsSelChImpl.getFD();
}
/**
* {@inheritDoc}
*
* Forwards to {@link #delegate}.
*/
@Override
public int getFDVal()
{
return delegateAsSelChImpl.getFDVal();
}
/**
* {@inheritDoc}
*
* Forwards to {@link #delegate}.
*/
@Override
public void kill()
throws IOException
{
delegateAsSelChImpl.kill();
}
/**
* {@inheritDoc}
*
* Forwards to {@link #delegate}.
*/
@Override
public void translateAndSetInterestOps(int ops, SelectionKeyImpl sk)
{
delegateAsSelChImpl.translateAndSetInterestOps(ops, sk);
}
/**
* {@inheritDoc}
*
* Forwards to {@link #delegate}.
*/
@Override
public boolean translateAndSetReadyOps(int ops, SelectionKeyImpl sk)
{
return delegateAsSelChImpl.translateAndSetReadyOps(ops, sk);
}
/**
* {@inheritDoc}
*
* Forwards to {@link #delegate}.
*/
@Override
public boolean translateAndUpdateReadyOps(int ops, SelectionKeyImpl sk)
{
return delegateAsSelChImpl.translateAndUpdateReadyOps(ops, sk);
}
}

View File

@ -1,56 +0,0 @@
/*
* ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
*
* Copyright @ 2015 Atlassian Pty Ltd
*
* 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.
*/
package org.ice4j.socket.jdk8;
import java.io.*;
import java.net.*;
import java.util.*;
import org.ice4j.socket.*;
/**
* Represents a {@link ServerSocket} associated with a
* {@code MuxServerSocketChannel}.
*
* @author Lyubomir Marinov
*/
class MuxServerSocket
extends DelegatingServerSocket
{
/**
* Initializes a new {@code MuxServerSocket} instance which delegates (its
* method calls) to a specific {@code MuxingServerSocket} and is associated
* with a specific {@code MuxServerSocketChannel}.
*
* @param delegate the {@code MuxingServerSocket} the new instance is to
* delegate (its method calls) to. Technically, it is the {@code socket} of
* the {@code delegate} of {@code channel}.
* @param channel the {@code MuxServerSocketChannel} associated with the new
* instance
* @throws IOException if an I/O error occurs
*/
public MuxServerSocket(
MuxingServerSocket delegate,
MuxServerSocketChannel channel)
throws IOException
{
super(
Objects.requireNonNull(delegate, "delegate"),
Objects.requireNonNull(channel, "channel"));
}
}

View File

@ -1,298 +0,0 @@
/*
* ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
*
* Copyright @ 2015 Atlassian Pty Ltd
*
* 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.
*/
package org.ice4j.socket.jdk8;
import java.io.*;
import java.net.*;
import java.nio.channels.*;
import java.util.*;
import org.ice4j.socket.*;
/**
* Implements a {@link ServerSocketChannel} which is capable of sharing its
* listening endpoint with multiple others like it.
*
* @author Lyubomir Marinov
*/
public class MuxServerSocketChannel
extends DelegatingServerSocketChannel<MuxingServerSocketChannel>
{
/**
* Opens and binds a new {@code MuxServerSocketChannel} instance. If there
* are other (existing) {@code MuxServerSocketChannel} open and bound on the
* specified listening {@code endpoint}, the new instance will share it with
* them.
*
* @param properties a {@code Map} of the values to be assigned to
* properties of the underlying {@link ServerSocketChannel} which is to
* actually listen on the specified {@code endpoint}. If the new instance is
* not the first to open and bind the specified {@code endpoint}, the
* {@code properties} and their respective values may not be used.
* @param endpoint the IP and port the new instance is to bind to
* @param backlog the requested maximum number of pending incoming
* connections to be queued. If the new instance is not the first to open
* and bind the specified {@code endpoint}, the value may not be used.
* @param filter the {@code DatagramPacketFilter} to demultiplex (i.e.
* recognize) the content meant for the new instance
* @return a new {@code MuxServerSocketChannel} instance open and bound on
* the specified listening {@code endpoint}
* @throws IOException if an I/O error occurs
*/
public static MuxServerSocketChannel openAndBind(
Map<String,Object> properties,
SocketAddress endpoint,
int backlog,
DatagramPacketFilter filter)
throws IOException
{
return
MuxingServerSocketChannel.openAndBind(
properties,
endpoint,
backlog,
filter);
}
/**
* The (ordered) list (i.e. queue) of <tt>SocketChannel</tt>s to be returned
* by {@link #accept()}.
*/
private final Queue<Timestamped<SocketChannel>> acceptQ
= new LinkedList<>();
/**
* The {@code DatagramPacketFilter} which demultiplexes
* {@code SocketChannel}s accepted by the associated
* {@code MuxingServerSocketChannel}.
*/
protected final DatagramPacketFilter filter;
/**
* The <tt>Object</tt> which synchronizes the access to the state of this
* <tt>MuxServerSocketChannel</tt> such as {@link #acceptQ}.
*/
private final Object syncRoot = new Object();
/**
* Initializes a new {@code MuxServerSocketChannel} instance which is to
* demultiplex {@link SocketChannel}s accepted by a specific
* {@link MuxingServerSocketChannel} using a specific
* {@link DatagramPacketFilter}. The new instance shares the listening
* endpoint of {@code delegate} with any other associated
* {@code MuxServerSocketChannel}s.
*
* @param delegate the {@code MuxingServerSocketChannel} which is actually
* open and bound to a listening endpoint and accepts {@code SocketChannel}s
* to be filtered by associated
* {@code MuxServerSocketChannel}s
* @param filter the {@code DatagramPacketFilter} which is to demultiplex
* {@code SocketChannel}s accepted by {@code delegate}
*/
protected MuxServerSocketChannel(
MuxingServerSocketChannel delegate,
DatagramPacketFilter filter)
{
super(Objects.requireNonNull(delegate, "delegate"));
this.filter = Objects.requireNonNull(filter, "filter");
}
/**
* {@inheritDoc}
*/
@Override
public SocketChannel accept()
throws IOException
{
SocketChannel accepted = null;
boolean interrupted = false;
// Pop a SocketChannel from acceptQ.
try
{
do
{
if (!isOpen())
{
throw new ClosedChannelException();
}
else if (!isBound())
{
throw new NotYetBoundException();
}
else
{
synchronized (syncRoot)
{
Timestamped<SocketChannel> timestamped = acceptQ.poll();
if (timestamped == null)
{
if (isBlocking())
{
try
{
syncRoot.wait();
}
catch (InterruptedException ie)
{
interrupted = true;
}
}
else
{
break;
}
}
else if ((accepted = timestamped.o).isOpen())
{
// Allow the MuxServerSocketChannel class and/or its
// super(s) to have a final say on the accepted
// SocketChannel such as wrapping it into a suitable
// specialization of DelegatingSocketChannel.
accepted = implAccept(accepted);
if (accepted != null)
break;
}
}
}
}
while (true);
}
finally
{
// Restore the interrupted state of the current thread if we've
// cleared it in the loop above.
if (interrupted)
Thread.currentThread().interrupt();
}
return accepted;
}
/**
* Weeds out abandoned {@code SocketChannels} from {@link #acceptQ} i.e.
* which were classified/filtered into this {@code MuxServerSocketChannel}
* but were not accepted (out of it) for a long time.
*
* @param now the (system) time in milliseconds at which the method is
* invoked
*/
void closeAbandonedSocketChannels(long now)
{
synchronized (syncRoot)
{
Collection<Timestamped<SocketChannel>> chs = acceptQ;
if (!chs.isEmpty())
{
for (Iterator<Timestamped<SocketChannel>> i = chs.iterator();
i.hasNext();)
{
Timestamped<SocketChannel> ch = i.next();
if (now - ch.timestamp
>= MuxingServerSocketChannel
.SOCKET_CHANNEL_READ_TIMEOUT)
{
i.remove();
MuxingServerSocketChannel.closeNoExceptions(ch.o);
}
}
}
}
}
/**
* Determines whether the {@link #filter} of this instance accepts a
* specific {@code SocketChannel} from which a specific
* {@code DatagramPacket} has been read and, if it does, queues the
* {@code channel} to be accepted through this instance.
*
* @param p the {@code DatagramPacket} which has been read from
* {@code channel} and which is to be analyzed by the {@code filter} of this
* instance
* @param channel the {@code SocketChannel} from which {@code p} has been
* read and which is to be queued for acceptance through this instance if
* the {@code filter} accepts {@code p}
* @return {@code true} if the {@code filter} of this instance accepts
* {@code p} and {@code channel} was queued for acceptance through this
* instance; otherwise, {@code false}
*/
protected boolean filterAccept(DatagramPacket p, SocketChannel channel)
{
return
filter.accept(p) && qAccept(new PreReadSocketChannel(p, channel));
}
/**
* {@inheritDoc}
*
* Adjusts the blocking mode of {@link #delegate}.
*/
@Override
protected void implConfigureBlocking(boolean block)
throws IOException
{
// If at least one MuxServerSocketChannel is configured as non-blocking,
// then MuxingServerSocketChannel has to be configured as non-blocking
// as well.
if (!block)
delegate.configureBlocking(block);
}
/**
* {@inheritDoc}
*
* Associates a {@link MuxServerSocket} with this
* {@code MuxServerSocketChannel}.
*/
@Override
protected MuxServerSocket implSocket(ServerSocket socket)
throws IOException
{
return new MuxServerSocket((MuxingServerSocket) socket, this);
}
/**
* Queues a {@link SocketChannel} for acceptance through this instance.
*
* @param channel the {@code SocketChannel} to queue for acceptance through
* this instance
* @return {@code true} if {@code channel} was queued for acceptance through
* this instance; otherwise, {@code false}
*/
boolean qAccept(SocketChannel channel)
{
boolean b;
synchronized (syncRoot)
{
if (acceptQ.offer(
new Timestamped<>(channel, System.currentTimeMillis())))
{
syncRoot.notifyAll();
b = true;
}
else
{
b = false;
}
}
return b;
}
}

View File

@ -1,56 +0,0 @@
/*
* ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
*
* Copyright @ 2015 Atlassian Pty Ltd
*
* 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.
*/
package org.ice4j.socket.jdk8;
import java.io.*;
import java.net.*;
import java.util.*;
import org.ice4j.socket.*;
/**
* Represents a {@link ServerSocket} associated with a
* {@code MuxingServerSocketChannel}.
*
* @author Lyubomir Marinov
*/
class MuxingServerSocket
extends DelegatingServerSocket
{
/**
* Initializes a new {@code MuxingServerSocket} instance which delegates
* (its method calls) to a specific {@code ServerSocket} and is associated
* with a specific {@code MuxingServerSocketChannel}.
*
* @param delegate the {@code ServerSocket} the new instance is to delegate
* (its method calls) to. Technically, it is the {@code socket} of the
* {@code delegate} of {@code channel}.
* @param channel the {@code MuxingServerSocketChannel} associated with the
* new instance
* @throws IOException if an I/O error occurs
*/
public MuxingServerSocket(
ServerSocket delegate,
MuxingServerSocketChannel channel)
throws IOException
{
super(
Objects.requireNonNull(delegate, "delegate"),
Objects.requireNonNull(channel, "channel"));
}
}

View File

@ -1,108 +0,0 @@
/*
* ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
*
* Copyright @ 2015 Atlassian Pty Ltd
*
* 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.
*/
package org.ice4j.socket.jdk8;
import java.io.*;
import java.net.*;
import java.nio.*;
import java.nio.channels.*;
/**
* Prepends a {@link DatagramPacket} to a {@link SocketChannel}. In other words,
* enables looking ahead at the {@code byte}s of a {@code SocketChannel}.
*
* @author Lyubomir Marinov
*/
class PreReadSocketChannel
extends DelegatingSocketChannel<SocketChannel>
{
/**
* The {@link DatagramPacket} which is to be prepended to the
* {@link SocketChannel} which is the {@link #delegate} of this
* {@link DelegatingSocketChannel}.
*/
private final DatagramPacket preRead;
/**
* Initializes a new {@code PreReadSocketChannel} instance which is to
* prepend a specific {@link DatagramPacket} to a specific
* {@link SocketChannel}.
*
* @param preRead the {@code DatagramPacket} to prepend to {@code delegate}
* @param delegate the {@code SocketChannel} to prepend {@code preRead} to
*/
public PreReadSocketChannel(DatagramPacket preRead, SocketChannel delegate)
{
super(delegate);
this.preRead = preRead;
}
/**
* {@inheritDoc}
*
* Reads from {@link #preRead} first (until it is fully read) and then
* continues with the {@code super} implementation.
*/
@Override
public int read(ByteBuffer dst)
throws IOException
{
synchronized (preRead)
{
int len = preRead.getLength();
int read;
if (len > 0)
{
int toRead = Math.min(len, dst.remaining());
if (toRead > 0)
{
byte[] buf = preRead.getData();
int off = preRead.getOffset();
dst.put(buf, off, toRead);
read = toRead;
preRead.setData(buf, off + read, len - read);
}
else
{
read = 0;
}
}
else
{
read = 0;
}
if (read == 0)
{
read = super.read(dst);
}
else if (dst.hasRemaining())
{
int superRead = super.read(dst);
if (superRead > 0)
read += superRead;
}
return read;
}
}
}

View File

@ -1,66 +0,0 @@
/*
* ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
*
* Copyright @ 2015 Atlassian Pty Ltd
*
* 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.
*/
package org.ice4j.socket.jdk8;
/**
* Represents an {@code Object} with a timestamp.
*
* @param <T> the type of the {@code Object} which has a timestamp (associated)
* @author Lyubomir Marinov
*/
class Timestamped<T>
{
/**
* The {@code Object} associated with {@link #timestamp}.
*/
final T o;
/**
* The timestamp (in milliseconds) associated with {@link #o}.
*/
long timestamp;
/**
* Initializes a new {@code Timestamped} instance with a specific
* {@code Object} and a default timestamp (value).
*
* @param o the {@code Object} to associate with a timestamp
*/
public Timestamped(T o)
{
this(o, -1);
}
/**
* Initializes a new {@code Timestamped} instance with a specific
* {@code Object} and a specific timestamp (value).
*
* @param o the {@code Object} to associate with {@code timestamp}
* @param timestamp the timestamp (in milliseconds) to associate with
* {@code o}
*/
public Timestamped(T o, long timestamp)
{
// It makes no sense to associate a timestamp with a null.
if (o == null)
throw new NullPointerException("o");
this.o = o;
this.timestamp = timestamp;
}
}

View File

@ -210,7 +210,8 @@ class Connector
if (!running) if (!running)
return; return;
if (logger.isLoggable(Level.FINEST)){ if (logger.isLoggable(Level.FINEST))
{
logger.finest("received datagram packet - addr: " logger.finest("received datagram packet - addr: "
+ packet.getAddress() + " port: " + packet.getPort()); + packet.getAddress() + " port: " + packet.getPort());
} }
@ -325,7 +326,15 @@ class Connector
DatagramPacket datagramPacket DatagramPacket datagramPacket
= new DatagramPacket(message, 0, message.length, address); = new DatagramPacket(message, 0, message.length, address);
sock.send(datagramPacket); IceSocketWrapper sock = this.sock;
if (sock != null)
{
sock.send(datagramPacket);
}
else
{
logger.warning("Can not send message, Connector stopped.");
}
} }
/** /**

View File

@ -109,7 +109,7 @@ public class EventDispatcher
{ {
synchronized(messageListeners) synchronized(messageListeners)
{ {
if(!messageListeners.contains(messageListener)) if (!messageListeners.contains(messageListener))
messageListeners.add(messageListener); messageListeners.add(messageListener);
} }
} }
@ -289,7 +289,7 @@ public class EventDispatcher
{ {
synchronized(messageListeners) synchronized(messageListeners)
{ {
if(!messageListeners.isEmpty()) if (!messageListeners.isEmpty())
{ {
// there is a generic listener // there is a generic listener
return true; return true;

Some files were not shown because too many files have changed in this diff Show More