Compare commits
94 Commits
stable/jit
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d289f125a4 | ||
|
|
0d8af275cd | ||
|
|
1c60acc59b | ||
|
|
fd43e6c181 | ||
|
|
27ad37d1af | ||
|
|
9fe2d69cf1 | ||
|
|
a947919f40 | ||
|
|
76e8a1968d | ||
|
|
28a23e1859 | ||
|
|
71e244dd67 | ||
|
|
f41542dd7c | ||
|
|
dec3a87d21 | ||
|
|
1f97cf2b26 | ||
|
|
32a8aadae8 | ||
|
|
2baae57d53 | ||
|
|
f195378a3d | ||
|
|
a9ba80efb9 | ||
|
|
86f1eaede2 | ||
|
|
ddfc498d0b | ||
|
|
d825218ab7 | ||
|
|
fc1498ef7e | ||
|
|
2e43ba1b3e | ||
|
|
64a7ca8c30 | ||
|
|
f637413a98 | ||
|
|
15981cf5f3 | ||
|
|
0811007990 | ||
|
|
cd2d21a8d0 | ||
|
|
626c35e460 | ||
|
|
a1b3c9b503 | ||
|
|
15d69b316c | ||
|
|
d4a145374f | ||
|
|
d7c0e27a1c | ||
|
|
9dc08bd299 | ||
|
|
adca67b17f | ||
|
|
076281c76b | ||
|
|
311a495b21 | ||
|
|
10346acade | ||
|
|
924f40c4e0 | ||
|
|
2586d8b2da | ||
|
|
3e0a9f97ef | ||
|
|
f6550a80ac | ||
|
|
c829b3a766 | ||
|
|
f176d021f8 | ||
|
|
5a299cd694 | ||
|
|
34c2ce50ec | ||
|
|
a86c4be742 | ||
|
|
67ffceb81d | ||
|
|
3a55627ba0 | ||
|
|
29ae8061ad | ||
|
|
f8a506ef70 | ||
|
|
686164ffc4 | ||
|
|
ed63ae8e11 | ||
|
|
9a580a9401 | ||
|
|
8ffa9030f4 | ||
|
|
7016902b21 | ||
|
|
e6e36856c6 | ||
|
|
e90c796d6d | ||
|
|
ca3868ac26 | ||
|
|
982e78212b | ||
|
|
35e149848e | ||
|
|
36f732ba1c | ||
|
|
e0fccdaf4d | ||
|
|
b504c2cc2e | ||
|
|
78e006cbac | ||
|
|
fe30fe8a31 | ||
|
|
7989977e1e | ||
|
|
43a9f282d2 | ||
|
|
e854e4efaf | ||
|
|
43fa07d9a5 | ||
|
|
0b052e8f85 | ||
|
|
c7c4719c45 | ||
|
|
59461c9d13 | ||
|
|
105a49749e | ||
|
|
0ea60d85b3 | ||
|
|
17bbc9b97a | ||
|
|
80471b751a | ||
|
|
5aec41fc02 | ||
|
|
f9a357ec17 | ||
|
|
0be8f1aae7 | ||
|
|
e87d331e57 | ||
|
|
e3e78dcda3 | ||
|
|
ce42c77b82 | ||
|
|
4027cf429d | ||
|
|
c56fcc3a3f | ||
|
|
8b43209b8d | ||
|
|
6beca2903c | ||
|
|
c325421927 | ||
|
|
17b9bd9c17 | ||
|
|
ee4e8c9452 | ||
|
|
3239ed12fc | ||
|
|
513fb588d6 | ||
|
|
3fe34dcb97 | ||
|
|
6bed63795f | ||
|
|
ba7e30c189 |
17
.editorconfig
Normal file
17
.editorconfig
Normal 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
82
.github/workflows/maven.yml
vendored
Normal 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
4
.gitignore
vendored
@ -7,3 +7,7 @@
|
|||||||
.project
|
.project
|
||||||
.settings/
|
.settings/
|
||||||
bin/
|
bin/
|
||||||
|
|
||||||
|
# Ignore IntelliJ IDEA files
|
||||||
|
.idea
|
||||||
|
*.iml
|
||||||
|
|||||||
@ -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
6
bnd.bnd
Normal 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
40
checkstyle.xml
Normal 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>
|
||||||
414
pom.xml
414
pom.xml
@ -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,58 +121,172 @@
|
|||||||
<build>
|
<build>
|
||||||
<plugins>
|
<plugins>
|
||||||
<plugin>
|
<plugin>
|
||||||
<groupId>org.apache.felix</groupId>
|
<groupId>org.jetbrains.kotlin</groupId>
|
||||||
<artifactId>maven-bundle-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>
|
||||||
|
<jvmTarget>11</jvmTarget>
|
||||||
|
<args>
|
||||||
|
<arg>-Xallow-result-return-type</arg>
|
||||||
|
</args>
|
||||||
|
</configuration>
|
||||||
</plugin>
|
</plugin>
|
||||||
<plugin>
|
<plugin>
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
<artifactId>maven-javadoc-plugin</artifactId>
|
<artifactId>maven-compiler-plugin</artifactId>
|
||||||
<version>2.10.4</version>
|
<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>
|
<configuration>
|
||||||
<show>private</show>
|
<release>11</release>
|
||||||
<nohelp>true</nohelp>
|
<compilerArgs>
|
||||||
|
<arg>-Xlint:all</arg>
|
||||||
|
</compilerArgs>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-checkstyle-plugin</artifactId>
|
||||||
|
<version>3.1.2</version>
|
||||||
|
<configuration>
|
||||||
|
<configLocation>checkstyle.xml</configLocation>
|
||||||
|
</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>
|
||||||
|
|
||||||
@ -104,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>
|
||||||
@ -127,25 +319,31 @@
|
|||||||
|
|
||||||
<profiles>
|
<profiles>
|
||||||
<profile>
|
<profile>
|
||||||
<id>skip-pre-jdk8</id>
|
<id>coverage</id>
|
||||||
<activation>
|
|
||||||
<jdk>(,1.8)</jdk>
|
|
||||||
</activation>
|
|
||||||
<build>
|
<build>
|
||||||
<plugins>
|
<plugins>
|
||||||
<plugin>
|
<plugin>
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
<groupId>org.jacoco</groupId>
|
||||||
<artifactId>maven-compiler-plugin</artifactId>
|
<artifactId>jacoco-maven-plugin</artifactId>
|
||||||
<configuration>
|
<version>0.8.8</version>
|
||||||
<excludes>
|
<executions>
|
||||||
<exclude>**/jdk8/**</exclude>
|
<execution>
|
||||||
</excludes>
|
<goals>
|
||||||
</configuration>
|
<goal>prepare-agent</goal>
|
||||||
|
</goals>
|
||||||
|
</execution>
|
||||||
|
<execution>
|
||||||
|
<id>report</id>
|
||||||
|
<phase>test</phase>
|
||||||
|
<goals>
|
||||||
|
<goal>report</goal>
|
||||||
|
</goals>
|
||||||
|
</execution>
|
||||||
|
</executions>
|
||||||
</plugin>
|
</plugin>
|
||||||
</plugins>
|
</plugins>
|
||||||
</build>
|
</build>
|
||||||
</profile>
|
</profile>
|
||||||
|
|
||||||
<profile>
|
<profile>
|
||||||
<id>run-sample</id>
|
<id>run-sample</id>
|
||||||
<build>
|
<build>
|
||||||
@ -250,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>
|
||||||
|
|||||||
@ -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 "STUN Usage for Consent
|
|
||||||
* Freshness".
|
|
||||||
*/
|
|
||||||
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
|
|
||||||
* "STUN Usage for Consent Freshness". 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
|
|
||||||
* "STUN Usage for Consent Freshness". 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 IPv6
|
|
||||||
* 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
|
||||||
|
|||||||
@ -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);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -43,8 +43,8 @@ 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)
|
||||||
|
|||||||
@ -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;
|
||||||
}
|
}
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@ -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());
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -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
|
||||||
|
|||||||
@ -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);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -471,8 +460,28 @@ public class Component
|
|||||||
synchronized(streamCheckList)
|
synchronized(streamCheckList)
|
||||||
{
|
{
|
||||||
for (CandidatePair pair : checkList)
|
for (CandidatePair pair : checkList)
|
||||||
|
{
|
||||||
|
/* 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);
|
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)
|
||||||
{
|
{
|
||||||
if (localCnd.getTransportAddress().equals(localAddress))
|
for (LocalCandidate localCandidate : localCandidates)
|
||||||
return localCnd;
|
{
|
||||||
|
if (localCandidate.getTransportAddress().equals(address))
|
||||||
|
{
|
||||||
|
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;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -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();
|
||||||
|
|||||||
@ -18,15 +18,17 @@
|
|||||||
package org.ice4j.ice;
|
package org.ice4j.ice;
|
||||||
|
|
||||||
import java.net.*;
|
import java.net.*;
|
||||||
|
import java.time.*;
|
||||||
import java.util.*;
|
import java.util.*;
|
||||||
import java.util.logging.*;
|
import java.util.concurrent.*;
|
||||||
|
|
||||||
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.socket.*;
|
import org.ice4j.socket.*;
|
||||||
import org.ice4j.stack.*;
|
import org.ice4j.stack.*;
|
||||||
import org.ice4j.util.Logger; //Disambiguation
|
import org.ice4j.util.*;
|
||||||
|
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
|
||||||
@ -38,22 +40,21 @@ 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.
|
||||||
*/
|
*/
|
||||||
private final Agent parentAgent;
|
private final Agent parentAgent;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A scheduled executor service to perform periodic tasks of the client
|
||||||
|
*/
|
||||||
|
private final ScheduledExecutorService scheduledExecutorService;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* An executor service to perform background tasks of the client
|
||||||
|
*/
|
||||||
|
private final ExecutorService executorService;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The <tt>StunStack</tt> that we will use for connectivity checks.
|
* The <tt>StunStack</tt> that we will use for connectivity checks.
|
||||||
*/
|
*/
|
||||||
@ -62,13 +63,21 @@ class ConnectivityCheckClient
|
|||||||
/**
|
/**
|
||||||
* The {@link PaceMaker}s that are currently running checks in this client.
|
* The {@link PaceMaker}s that are currently running checks in this client.
|
||||||
*/
|
*/
|
||||||
private final List<PaceMaker> paceMakers = new LinkedList<>();
|
private final Queue<PaceMaker> paceMakers
|
||||||
|
= 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.
|
||||||
*/
|
*/
|
||||||
private Map<String, Timer> timers = new HashMap<>();
|
private ConcurrentMap<String, ScheduledFuture<?>>
|
||||||
|
checkListCompletionCheckers = new ConcurrentHashMap<>();
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* A flag that determines whether we have received a STUN response or not.
|
* A flag that determines whether we have received a STUN response or not.
|
||||||
@ -86,11 +95,20 @@ class ConnectivityCheckClient
|
|||||||
* information such as user fragments for example.
|
* information such as user fragments for example.
|
||||||
*
|
*
|
||||||
* @param parentAgent the <tt>Agent</tt> that is creating this instance.
|
* @param parentAgent the <tt>Agent</tt> that is creating this instance.
|
||||||
|
* @param scheduledExecutorService the <tt>ScheduledExecutorService</tt>
|
||||||
|
* to execute clients tasks
|
||||||
|
* @param executorService the <tt>ExecutorService</tt> to execute
|
||||||
|
* background tasks of connectivity check client
|
||||||
*/
|
*/
|
||||||
public ConnectivityCheckClient(Agent parentAgent)
|
public ConnectivityCheckClient(
|
||||||
|
Agent parentAgent,
|
||||||
|
ScheduledExecutorService scheduledExecutorService,
|
||||||
|
ExecutorService executorService)
|
||||||
{
|
{
|
||||||
this.parentAgent = parentAgent;
|
this.parentAgent = parentAgent;
|
||||||
logger = new Logger(classLogger, parentAgent.getLogger());
|
this.scheduledExecutorService = scheduledExecutorService;
|
||||||
|
this.executorService = executorService;
|
||||||
|
logger = parentAgent.getLogger().createChildLogger(this.getClass().getName());
|
||||||
|
|
||||||
stunStack = this.parentAgent.getStunStack();
|
stunStack = this.parentAgent.getStunStack();
|
||||||
}
|
}
|
||||||
@ -126,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());
|
||||||
@ -148,13 +165,16 @@ class ConnectivityCheckClient
|
|||||||
*/
|
*/
|
||||||
public void startChecks(CheckList checkList)
|
public void startChecks(CheckList checkList)
|
||||||
{
|
{
|
||||||
PaceMaker paceMaker = new PaceMaker(checkList);
|
|
||||||
|
|
||||||
synchronized (paceMakers)
|
synchronized (paceMakers)
|
||||||
{
|
{
|
||||||
paceMakers.add(paceMaker);
|
if (stopped)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
PaceMaker paceMaker = new PaceMaker(checkList);
|
||||||
|
paceMakers.add(paceMaker);
|
||||||
|
paceMaker.schedule();
|
||||||
}
|
}
|
||||||
paceMaker.start();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -175,23 +195,18 @@ class ConnectivityCheckClient
|
|||||||
indication,
|
indication,
|
||||||
candidatePair.getRemoteCandidate().getTransportAddress(),
|
candidatePair.getRemoteCandidate().getTransportAddress(),
|
||||||
localCandidate.getBase().getTransportAddress());
|
localCandidate.getBase().getTransportAddress());
|
||||||
if (logger.isLoggable(Level.FINEST))
|
logger.trace(() ->
|
||||||
{
|
|
||||||
logger.finest(
|
|
||||||
"sending binding indication to pair " + candidatePair);
|
"sending binding indication to pair " + candidatePair);
|
||||||
}
|
}
|
||||||
}
|
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
IceSocketWrapper stunSocket = localCandidate.getStunSocket(null);
|
IceSocketWrapper stunSocket = localCandidate.getStunSocket(null);
|
||||||
|
|
||||||
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);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -262,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(
|
||||||
@ -306,9 +321,12 @@ class ConnectivityCheckClient
|
|||||||
|
|
||||||
tran.setApplicationData(candidatePair);
|
tran.setApplicationData(candidatePair);
|
||||||
|
|
||||||
logger.fine(
|
if (logger.isDebugEnabled())
|
||||||
|
{
|
||||||
|
logger.debug(
|
||||||
"start check for " + candidatePair.toShortString() + " tid "
|
"start check for " + candidatePair.toShortString() + " tid "
|
||||||
+ tran);
|
+ tran);
|
||||||
|
}
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
tran
|
tran
|
||||||
@ -322,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;
|
||||||
@ -347,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);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -387,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
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -431,14 +456,12 @@ class ConnectivityCheckClient
|
|||||||
if ( !stream.validListContainsAllComponents())
|
if ( !stream.validListContainsAllComponents())
|
||||||
{
|
{
|
||||||
final String streamName = stream.getName();
|
final String streamName = stream.getName();
|
||||||
Timer timer = timers.get(streamName);
|
if (!checkListCompletionCheckers.containsKey(streamName))
|
||||||
|
|
||||||
if (timer == null)
|
|
||||||
{
|
{
|
||||||
logger.info("CheckList will failed in a few seconds if no" +
|
logger.info("CheckList will failed in a few seconds" +
|
||||||
"succeeded checks come");
|
" if no succeeded checks come");
|
||||||
|
|
||||||
TimerTask task = new TimerTask()
|
Runnable checkLickCompletedChecker = new Runnable()
|
||||||
{
|
{
|
||||||
@Override
|
@Override
|
||||||
public void run()
|
public void run()
|
||||||
@ -453,9 +476,20 @@ class ConnectivityCheckClient
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
timer = new Timer();
|
|
||||||
timers.put(streamName, timer);
|
final ScheduledFuture<?> scheduledCheckerFuture
|
||||||
timer.schedule(task, 5000);
|
= scheduledExecutorService.schedule(
|
||||||
|
checkLickCompletedChecker,
|
||||||
|
5000,
|
||||||
|
TimeUnit.MILLISECONDS);
|
||||||
|
|
||||||
|
final ScheduledFuture<?> existingCheckerFuture
|
||||||
|
= checkListCompletionCheckers
|
||||||
|
.putIfAbsent(streamName, scheduledCheckerFuture);
|
||||||
|
if (existingCheckerFuture != null)
|
||||||
|
{
|
||||||
|
scheduledCheckerFuture.cancel(false);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -499,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
|
||||||
}
|
}
|
||||||
@ -525,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();
|
||||||
|
|
||||||
@ -573,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());
|
+ ".");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -611,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();
|
||||||
}
|
}
|
||||||
@ -621,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);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -693,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-
|
||||||
@ -706,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());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -733,7 +768,7 @@ class ConnectivityCheckClient
|
|||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
logger.fine(
|
logger.debug(() ->
|
||||||
"Keep alive for pair: " + validPair.toShortString());
|
"Keep alive for pair: " + validPair.toShortString());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -803,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)
|
||||||
@ -811,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()
|
||||||
@ -820,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();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -847,17 +884,11 @@ class ConnectivityCheckClient
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The thread that actually sends the checks for a particular check list
|
* A class to control periodically scheduled runnable that actually sends
|
||||||
* in the pace defined in RFC 5245.
|
* the checks for a particular check list in the pace defined in RFC 5245.
|
||||||
*/
|
*/
|
||||||
private class PaceMaker
|
private final class PaceMaker extends PeriodicRunnable
|
||||||
extends Thread
|
|
||||||
{
|
{
|
||||||
/**
|
|
||||||
* Indicates whether this <tt>Thread</tt> should still be running.
|
|
||||||
*/
|
|
||||||
boolean running = true;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The {@link CheckList} that this <tt>PaceMaker</tt> will be running
|
* The {@link CheckList} that this <tt>PaceMaker</tt> will be running
|
||||||
* checks for.
|
* checks for.
|
||||||
@ -873,39 +904,8 @@ class ConnectivityCheckClient
|
|||||||
*/
|
*/
|
||||||
public PaceMaker(CheckList checkList)
|
public PaceMaker(CheckList checkList)
|
||||||
{
|
{
|
||||||
super("ICE PaceMaker: " + parentAgent.getLocalUfrag());
|
super(scheduledExecutorService, executorService);
|
||||||
|
|
||||||
this.checkList = checkList;
|
this.checkList = checkList;
|
||||||
|
|
||||||
/*
|
|
||||||
* Because PaceMaker does not seem to be a daemon at least on Ubuntu
|
|
||||||
* in the run-sample target and it looks like it should be from the
|
|
||||||
* standpoint of the application, explicitly tell it to be a daemon.
|
|
||||||
* Otherwise, it could prevent the application from exiting because
|
|
||||||
* of a problem in the ICE implementation.
|
|
||||||
*/
|
|
||||||
setDaemon(true);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns the number milliseconds to wait before we send the next
|
|
||||||
* check.
|
|
||||||
*
|
|
||||||
* @return the number milliseconds to wait before we send the next
|
|
||||||
* check.
|
|
||||||
*/
|
|
||||||
private long getNextWaitInterval()
|
|
||||||
{
|
|
||||||
int activeCheckLists = parentAgent.getActiveCheckListCount();
|
|
||||||
|
|
||||||
if (activeCheckLists < 1)
|
|
||||||
{
|
|
||||||
//don't multiply by 0. even when we no longer have active check
|
|
||||||
//lists we may still have nomination checks to
|
|
||||||
activeCheckLists = 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
return parentAgent.calculateTa() * activeCheckLists;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -914,39 +914,15 @@ class ConnectivityCheckClient
|
|||||||
* or the regular check lists.
|
* or the regular check lists.
|
||||||
*/
|
*/
|
||||||
@Override
|
@Override
|
||||||
public synchronized void run()
|
protected void run()
|
||||||
{
|
{
|
||||||
try
|
|
||||||
{
|
|
||||||
while(running)
|
|
||||||
{
|
|
||||||
long waitFor = getNextWaitInterval();
|
|
||||||
|
|
||||||
if (waitFor > 0)
|
|
||||||
{
|
|
||||||
/*
|
|
||||||
* waitFor will be 0 for the first check since we won't
|
|
||||||
* have any active check lists at that point yet.
|
|
||||||
*/
|
|
||||||
try
|
|
||||||
{
|
|
||||||
wait(waitFor);
|
|
||||||
}
|
|
||||||
catch (InterruptedException e)
|
|
||||||
{
|
|
||||||
logger.log(Level.FINER, "PaceMaker got interrupted",
|
|
||||||
e);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!running)
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
CandidatePair pairToCheck = checkList.popTriggeredCheck();
|
CandidatePair pairToCheck = checkList.popTriggeredCheck();
|
||||||
|
|
||||||
//if there are no triggered checks, go for an ordinary one.
|
//if there are no triggered checks, go for an ordinary one.
|
||||||
if (pairToCheck == null)
|
if (pairToCheck == null)
|
||||||
|
{
|
||||||
pairToCheck = checkList.getNextOrdinaryPairToCheck();
|
pairToCheck = checkList.getNextOrdinaryPairToCheck();
|
||||||
|
}
|
||||||
|
|
||||||
if (pairToCheck != null)
|
if (pairToCheck != null)
|
||||||
{
|
{
|
||||||
@ -970,9 +946,11 @@ class ConnectivityCheckClient
|
|||||||
pairToCheck.setStateFailed();
|
pairToCheck.setStateFailed();
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
|
{
|
||||||
pairToCheck.setStateInProgress(transactionID);
|
pairToCheck.setStateInProgress(transactionID);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
/*
|
/*
|
||||||
@ -980,21 +958,30 @@ 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();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
finally
|
/**
|
||||||
|
* Returns the number milliseconds to wait before we send the next
|
||||||
|
* check.
|
||||||
|
*
|
||||||
|
* @return the number milliseconds to wait before we send the next
|
||||||
|
* check.
|
||||||
|
*/
|
||||||
|
protected Duration getDelayUntilNextRun()
|
||||||
{
|
{
|
||||||
synchronized (paceMakers)
|
int activeCheckLists = parentAgent.getActiveCheckListCount();
|
||||||
|
|
||||||
|
if (activeCheckLists < 1)
|
||||||
{
|
{
|
||||||
synchronized (this)
|
//don't multiply by 0. even when we no longer have active check
|
||||||
{
|
//lists we may still have nomination checks to
|
||||||
paceMakers.remove(this);
|
activeCheckLists = 1;
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return Duration.ofMillis(parentAgent.calculateTa() * activeCheckLists);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -1005,19 +992,15 @@ class ConnectivityCheckClient
|
|||||||
{
|
{
|
||||||
synchronized (paceMakers)
|
synchronized (paceMakers)
|
||||||
{
|
{
|
||||||
Iterator<PaceMaker> paceMakersIter = paceMakers.iterator();
|
stopped = true;
|
||||||
|
while (true)
|
||||||
while(paceMakersIter.hasNext())
|
|
||||||
{
|
{
|
||||||
PaceMaker paceMaker = paceMakersIter.next();
|
final PaceMaker paceMaker = paceMakers.poll();
|
||||||
|
if (paceMaker == null)
|
||||||
synchronized (paceMaker)
|
|
||||||
{
|
{
|
||||||
paceMaker.running = false;
|
break;
|
||||||
paceMaker.notify();
|
|
||||||
}
|
}
|
||||||
|
paceMaker.cancel();
|
||||||
paceMakersIter.remove();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -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;
|
||||||
|
|
||||||
@ -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);
|
||||||
@ -249,11 +216,8 @@ class ConnectivityCheckServer
|
|||||||
//extract priority
|
//extract priority
|
||||||
if (priorityAttr == null)
|
if (priorityAttr == null)
|
||||||
{
|
{
|
||||||
if(logger.isLoggable(Level.FINE))
|
logger.debug(() -> "Received a connectivity check with"
|
||||||
{
|
|
||||||
logger.log(Level.FINE, "Received a connectivity check with"
|
|
||||||
+ "no PRIORITY attribute. Discarding.");
|
+ "no PRIORITY attribute. Discarding.");
|
||||||
}
|
|
||||||
|
|
||||||
throw new IllegalArgumentException("Missing PRIORITY attribute!");
|
throw new IllegalArgumentException("Missing PRIORITY attribute!");
|
||||||
}
|
}
|
||||||
@ -278,89 +242,51 @@ 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);
|
||||||
{
|
|
||||||
IceControlledAttribute controlled = (IceControlledAttribute)
|
|
||||||
req.getAttribute(Attribute.ICE_CONTROLLED);
|
|
||||||
|
|
||||||
long theirTieBreaker = controlled.getTieBreaker();
|
if (!(bothControllingConflict || bothControlledConflict))
|
||||||
|
|
||||||
//If the agent's tie-breaker is larger than or equal to the
|
|
||||||
//contents of the ICE-CONTROLLED attribute, the agent switches to
|
|
||||||
//the controlling role.
|
|
||||||
if(compareUnsignedLong(ourTieBreaker, theirTieBreaker) >= 0)
|
|
||||||
{
|
{
|
||||||
logger.finer(
|
// we don't have a role conflict
|
||||||
"Switching to controlling because theirTieBreaker="
|
|
||||||
+ theirTieBreaker + " and ourTieBreaker="
|
|
||||||
+ ourTieBreaker);
|
|
||||||
parentAgent.setControlling(true);
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
// If the agent's tie-breaker is less than the contents of the
|
|
||||||
// ICE-CONTROLLED attribute, the agent generates a Binding error
|
final long selfTieBreaker = parentAgent.getTieBreaker();
|
||||||
// response and includes an ERROR-CODE attribute with a value of
|
|
||||||
// 487 (Role Conflict) but retains its role.
|
final IceControlAttribute theirIceControl = bothControllingConflict
|
||||||
else
|
? (IceControlAttribute)req.getAttribute(Attribute.ICE_CONTROLLING)
|
||||||
|
: (IceControlAttribute)req.getAttribute(Attribute.ICE_CONTROLLED);
|
||||||
|
|
||||||
|
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)
|
||||||
{
|
{
|
||||||
Response response = MessageFactory.createBindingErrorResponse(
|
final UsernameAttribute requestUserName = (UsernameAttribute)req
|
||||||
|
.getAttribute(Attribute.USERNAME);
|
||||||
|
|
||||||
|
final Response response =
|
||||||
|
MessageFactory.createBindingErrorResponse(
|
||||||
ErrorCodeAttribute.ROLE_CONFLICT);
|
ErrorCodeAttribute.ROLE_CONFLICT);
|
||||||
|
|
||||||
|
final Attribute messageIntegrityAttribute =
|
||||||
|
AttributeFactory.createMessageIntegrityAttribute(
|
||||||
|
new String(requestUserName.getUsername()));
|
||||||
|
response.putAttribute(messageIntegrityAttribute);
|
||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
stunStack.sendResponse(
|
stunStack.sendResponse(
|
||||||
@ -368,7 +294,6 @@ class ConnectivityCheckServer
|
|||||||
response,
|
response,
|
||||||
evt.getLocalAddress(),
|
evt.getLocalAddress(),
|
||||||
evt.getRemoteAddress());
|
evt.getRemoteAddress());
|
||||||
|
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
catch(Exception exc)
|
catch(Exception exc)
|
||||||
@ -377,8 +302,19 @@ class ConnectivityCheckServer
|
|||||||
throw new RuntimeException("Failed to send a 487", exc);
|
throw new RuntimeException("Failed to send a 487", exc);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
//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;
|
||||||
}
|
}
|
||||||
return true; // we don't have a role conflict
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@ -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
|
||||||
|
|||||||
@ -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,7 +172,7 @@ 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.
|
||||||
@ -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.");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -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;
|
||||||
@ -921,4 +923,9 @@ public class IceMediaStream
|
|||||||
{
|
{
|
||||||
return remotePassword;
|
return remotePassword;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public Logger getLogger()
|
||||||
|
{
|
||||||
|
return logger;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -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;
|
||||||
|
|||||||
@ -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;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -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<>();
|
||||||
|
|
||||||
@ -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 useIPv6LinkLocal = !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,15 +249,12 @@ public abstract class AbstractTcpListener
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!useIPv6 && (address instanceof Inet6Address))
|
if (!config.useIpv6() && (address instanceof Inet6Address))
|
||||||
continue;
|
continue;
|
||||||
|
|
||||||
if (!useIPv6LinkLocal
|
if (!config.useLinkLocalAddresses() && address.isLinkLocalAddress())
|
||||||
&& (address instanceof Inet6Address)
|
|
||||||
&& 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;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -441,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);
|
||||||
}
|
}
|
||||||
@ -466,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)
|
||||||
@ -607,7 +505,9 @@ public abstract class AbstractTcpListener
|
|||||||
selector.close();
|
selector.close();
|
||||||
}
|
}
|
||||||
catch (IOException ioe)
|
catch (IOException ioe)
|
||||||
{}
|
{
|
||||||
|
// ignore
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -622,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.
|
||||||
*/
|
*/
|
||||||
@ -792,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);
|
||||||
@ -830,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
|
||||||
@ -924,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())
|
||||||
{
|
{
|
||||||
@ -1111,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())
|
||||||
@ -1173,7 +1016,9 @@ public abstract class AbstractTcpListener
|
|||||||
readSelector.close();
|
readSelector.close();
|
||||||
}
|
}
|
||||||
catch (IOException ioe)
|
catch (IOException ioe)
|
||||||
{}
|
{
|
||||||
|
// ignore
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -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,10 +499,10 @@ public abstract class AbstractUdpListener
|
|||||||
queue.offer(buf);
|
queue.offer(buf);
|
||||||
if (queueStatistics != null)
|
if (queueStatistics != null)
|
||||||
{
|
{
|
||||||
queueStatistics.add(System.currentTimeMillis());
|
queueStatistics.added();
|
||||||
}
|
}
|
||||||
|
|
||||||
queue.notifyAll();
|
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);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -83,7 +83,7 @@ public class AwsCandidateHarvester
|
|||||||
*/
|
*/
|
||||||
public AwsCandidateHarvester()
|
public AwsCandidateHarvester()
|
||||||
{
|
{
|
||||||
super();
|
super("aws");
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@ -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)
|
||||||
|
|||||||
@ -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 isIPv6LinkLocalDisabled = StackProperties.getBoolean(
|
|
||||||
StackProperties.DISABLE_LINK_LOCAL_ADDRESSES,
|
|
||||||
false);
|
|
||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
for (NetworkInterface iface
|
for (NetworkInterface iface
|
||||||
@ -257,11 +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 (isIPv6LinkLocalDisabled
|
if (!config.useLinkLocalAddresses() && address.isLinkLocalAddress())
|
||||||
&& address instanceof Inet6Address
|
|
||||||
&& address.isLinkLocalAddress())
|
|
||||||
continue;
|
continue;
|
||||||
|
|
||||||
addresses.add(address);
|
addresses.add(address);
|
||||||
@ -283,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
|
||||||
@ -309,21 +304,11 @@ public class HostCandidateHarvester
|
|||||||
{
|
{
|
||||||
harvestStatistics.startHarvestTiming();
|
harvestStatistics.startHarvestTiming();
|
||||||
|
|
||||||
Enumeration<NetworkInterface> interfaces
|
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
|
||||||
= NetworkInterface.getNetworkInterfaces();
|
|
||||||
|
|
||||||
boolean isIPv6Disabled = StackProperties.getBoolean(
|
|
||||||
StackProperties.DISABLE_IPv6,
|
|
||||||
false);
|
|
||||||
|
|
||||||
boolean isIPv6LinkLocalDisabled = StackProperties.getBoolean(
|
|
||||||
StackProperties.DISABLE_LINK_LOCAL_ADDRESSES,
|
|
||||||
false);
|
|
||||||
|
|
||||||
if (transport != Transport.UDP && transport != Transport.TCP)
|
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;
|
||||||
@ -353,23 +338,20 @@ public class HostCandidateHarvester
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (isIPv6LinkLocalDisabled
|
if (!config.useLinkLocalAddresses() && addr.isLinkLocalAddress())
|
||||||
&& (addr instanceof Inet6Address)
|
|
||||||
&& 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)
|
||||||
@ -404,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)
|
||||||
@ -423,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);
|
||||||
@ -447,8 +426,7 @@ public class HostCandidateHarvester
|
|||||||
+ foundAtLeastOneUsableAddress);
|
+ foundAtLeastOneUsableAddress);
|
||||||
}
|
}
|
||||||
|
|
||||||
this.harvestStatistics
|
this.harvestStatistics.stopHarvestTiming(component.getLocalCandidateCount());
|
||||||
.stopHarvestTiming(component.getLocalCandidateCount());
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -463,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");
|
||||||
@ -543,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
|
||||||
@ -569,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,
|
||||||
@ -613,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));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -629,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
|
||||||
@ -656,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,
|
||||||
@ -718,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
|
||||||
@ -731,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))
|
||||||
@ -758,6 +766,8 @@ public class HostCandidateHarvester
|
|||||||
+") must be between minPort (" + minPort
|
+") must be between minPort (" + minPort
|
||||||
+ ") and maxPort (" + maxPort + ")");
|
+ ") and maxPort (" + maxPort + ")");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@ -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());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -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,33 +256,34 @@ 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
|
|
||||||
public StunMappingCandidateHarvester call()
|
|
||||||
throws Exception
|
|
||||||
{
|
{
|
||||||
stunHarvester.discover();
|
stunHarvester.discover();
|
||||||
return stunHarvester;
|
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());
|
logger.warning("STUN mapping harvesters are configured, but no allowed local addresses were found." +
|
||||||
|
" Not using STUN.");
|
||||||
|
return stunHarvesters;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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;
|
List<Future<StunMappingCandidateHarvester>> futures;
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
@ -359,7 +317,11 @@ public class MappingCandidateHarvesters
|
|||||||
throw new RuntimeException(ie);
|
throw new RuntimeException(ie);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
es.shutdown();
|
||||||
|
}
|
||||||
return stunHarvesters;
|
return stunHarvesters;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -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
|
||||||
@ -403,9 +403,11 @@ public class SinglePortUdpHarvester
|
|||||||
@Override
|
@Override
|
||||||
protected IceSocketWrapper getCandidateIceSocketWrapper(
|
protected IceSocketWrapper getCandidateIceSocketWrapper(
|
||||||
SocketAddress remoteAddress)
|
SocketAddress remoteAddress)
|
||||||
|
{
|
||||||
|
synchronized (candidateSockets)
|
||||||
{
|
{
|
||||||
return candidateSockets.get(remoteAddress);
|
return candidateSockets.get(remoteAddress);
|
||||||
}
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -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;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -177,7 +177,7 @@ public class IceSdpUtils
|
|||||||
: Connection.IP4;
|
: Connection.IP4;
|
||||||
|
|
||||||
mediaDescription.setConnection(sdpFactory.createConnection(
|
mediaDescription.setConnection(sdpFactory.createConnection(
|
||||||
"IN", defaultAddress.getHostAddress(), addressFamily));
|
"IN", addressFamily, defaultAddress.getHostAddress()));
|
||||||
|
|
||||||
//now check if the RTCP port for the default candidate is different
|
//now check if the RTCP port for the default candidate is different
|
||||||
//than RTP.port +1, in which case we need to mention it.
|
//than RTP.port +1, in which case we need to mention it.
|
||||||
|
|||||||
@ -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.
|
||||||
@ -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,11 +1060,11 @@ 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)
|
||||||
{
|
{
|
||||||
@ -1088,7 +1091,7 @@ 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;
|
||||||
|
|
||||||
@ -1106,20 +1109,20 @@ public abstract class Message
|
|||||||
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);
|
||||||
|
|||||||
@ -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);
|
||||||
@ -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);
|
||||||
}
|
}
|
||||||
@ -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);
|
||||||
}
|
}
|
||||||
|
|||||||
@ -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.
|
||||||
@ -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
|
||||||
@ -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)
|
||||||
|
|||||||
@ -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,
|
||||||
|
|||||||
@ -78,15 +78,8 @@ class PseudoTcpSocketImpl
|
|||||||
*/
|
*/
|
||||||
private long readTimeout;
|
private long readTimeout;
|
||||||
|
|
||||||
|
|
||||||
/**
|
|
||||||
*
|
|
||||||
*/
|
|
||||||
private PseudoTcpInputStream inputStream;
|
private PseudoTcpInputStream inputStream;
|
||||||
|
|
||||||
/**
|
|
||||||
*
|
|
||||||
*/
|
|
||||||
private PseudoTcpOutputStream outputstream;
|
private PseudoTcpOutputStream outputstream;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -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,6 +244,7 @@ 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
|
||||||
{
|
{
|
||||||
@ -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,6 +278,7 @@ 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
|
||||||
{
|
{
|
||||||
@ -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
|
||||||
{
|
{
|
||||||
@ -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,6 +503,7 @@ 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))
|
||||||
@ -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)
|
||||||
@ -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))
|
||||||
@ -739,13 +745,7 @@ class PseudoTcpSocketImpl
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
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)
|
||||||
{
|
{
|
||||||
@ -777,6 +777,7 @@ class PseudoTcpSocketImpl
|
|||||||
* @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)
|
||||||
{
|
{
|
||||||
@ -929,7 +933,7 @@ class PseudoTcpSocketImpl
|
|||||||
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)
|
||||||
{
|
{
|
||||||
@ -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)
|
||||||
@ -1073,7 +1071,7 @@ class PseudoTcpSocketImpl
|
|||||||
{
|
{
|
||||||
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)
|
||||||
{
|
{
|
||||||
@ -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)
|
||||||
{
|
{
|
||||||
@ -1132,7 +1130,7 @@ class PseudoTcpSocketImpl
|
|||||||
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)
|
||||||
{
|
{
|
||||||
@ -1160,6 +1158,7 @@ class PseudoTcpSocketImpl
|
|||||||
@Override
|
@Override
|
||||||
public void close() throws IOException
|
public void close() throws IOException
|
||||||
{
|
{
|
||||||
|
PseudoTcpSocketImpl.this.close();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -755,8 +755,9 @@ 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);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -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: "
|
||||||
{
|
|
||||||
logger.fine("Adding a DelegatingSocket instance: "
|
|
||||||
+ socket.getLocalAddress());
|
+ 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: "
|
||||||
{
|
|
||||||
logger.fine("Adding a DatagramSocket instance: "
|
|
||||||
+ socket.getLocalAddress());
|
+ 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;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -337,7 +322,7 @@ public class MergingDatagramSocket
|
|||||||
synchronized (socketContainersSyncRoot)
|
synchronized (socketContainersSyncRoot)
|
||||||
{
|
{
|
||||||
int i = indexOf(socketContainers, socket);
|
int i = indexOf(socketContainers, socket);
|
||||||
if (i > 0)
|
if (i >= 0)
|
||||||
{
|
{
|
||||||
socketContainer = socketContainers[i];
|
socketContainer = socketContainers[i];
|
||||||
|
|
||||||
@ -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,9 +580,9 @@ 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);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -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 "
|
||||||
{
|
|
||||||
logger.fine("Starting the thread for socket "
|
|
||||||
+ getLocalSocketAddress() + " -> "
|
+ getLocalSocketAddress() + " -> "
|
||||||
+ getRemoteSocketAddress());
|
+ getRemoteSocketAddress());
|
||||||
}
|
|
||||||
thread.start();
|
thread.start();
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -797,7 +779,7 @@ public class MergingDatagramSocket
|
|||||||
queue.put(buffer);
|
queue.put(buffer);
|
||||||
synchronized (receiveLock)
|
synchronized (receiveLock)
|
||||||
{
|
{
|
||||||
receiveLock.notifyAll();
|
receiveLock.notify();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
catch (InterruptedException ie)
|
catch (InterruptedException ie)
|
||||||
@ -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);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -55,19 +55,8 @@ public class MultiplexedDatagramSocket
|
|||||||
* The list of <tt>DatagramPacket</tt>s to be received through this
|
* The list of <tt>DatagramPacket</tt>s to be received through this
|
||||||
* <tt>DatagramSocket</tt> i.e. accepted by {@link #filter}.
|
* <tt>DatagramSocket</tt> i.e. accepted by {@link #filter}.
|
||||||
*/
|
*/
|
||||||
final List<DatagramPacket> received
|
final SocketReceiveBuffer received
|
||||||
= new SocketReceiveBuffer()
|
= new SocketReceiveBuffer(this::getReceiveBufferSize);
|
||||||
{
|
|
||||||
private static final long serialVersionUID
|
|
||||||
= -5763976093759762087L;
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public int getReceiveBufferSize()
|
|
||||||
throws SocketException
|
|
||||||
{
|
|
||||||
return MultiplexedDatagramSocket.this.getReceiveBufferSize();
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Initializes a new <tt>MultiplexedDatagramSocket</tt> which is unbound and
|
* Initializes a new <tt>MultiplexedDatagramSocket</tt> which is unbound and
|
||||||
|
|||||||
@ -67,19 +67,8 @@ public class MultiplexedSocket
|
|||||||
* The list of <tt>DatagramPacket</tt>s to be received through this
|
* The list of <tt>DatagramPacket</tt>s to be received through this
|
||||||
* <tt>Socket</tt> i.e. accepted by {@link #filter}.
|
* <tt>Socket</tt> i.e. accepted by {@link #filter}.
|
||||||
*/
|
*/
|
||||||
final List<DatagramPacket> received
|
final SocketReceiveBuffer received
|
||||||
= new SocketReceiveBuffer()
|
= new SocketReceiveBuffer(this::getReceiveBufferSize);
|
||||||
{
|
|
||||||
private static final long serialVersionUID
|
|
||||||
= 678744096057601141L;
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public int getReceiveBufferSize()
|
|
||||||
throws SocketException
|
|
||||||
{
|
|
||||||
return MultiplexedSocket.this.getReceiveBufferSize();
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Initializes a new <tt>MultiplexedSocket</tt> which is unbound and filters
|
* Initializes a new <tt>MultiplexedSocket</tt> which is unbound and filters
|
||||||
|
|||||||
@ -81,7 +81,7 @@ public class MultiplexingDatagramSocket
|
|||||||
* {@inheritDoc}
|
* {@inheritDoc}
|
||||||
*/
|
*/
|
||||||
@Override
|
@Override
|
||||||
protected List<DatagramPacket> getReceived()
|
protected SocketReceiveBuffer getReceived()
|
||||||
{
|
{
|
||||||
return received;
|
return received;
|
||||||
}
|
}
|
||||||
@ -90,7 +90,7 @@ public class MultiplexingDatagramSocket
|
|||||||
* {@inheritDoc}
|
* {@inheritDoc}
|
||||||
*/
|
*/
|
||||||
@Override
|
@Override
|
||||||
protected List<DatagramPacket> getReceived(
|
protected SocketReceiveBuffer getReceived(
|
||||||
MultiplexedDatagramSocket socket)
|
MultiplexedDatagramSocket socket)
|
||||||
{
|
{
|
||||||
return socket.received;
|
return socket.received;
|
||||||
@ -103,19 +103,8 @@ public class MultiplexingDatagramSocket
|
|||||||
* {@link MultiplexedDatagramSocket} of this instance at the time of the
|
* {@link MultiplexedDatagramSocket} of this instance at the time of the
|
||||||
* reading from the network.
|
* reading from the network.
|
||||||
*/
|
*/
|
||||||
private final List<DatagramPacket> received
|
private final SocketReceiveBuffer received
|
||||||
= new SocketReceiveBuffer()
|
= new SocketReceiveBuffer(this::getReceiveBufferSize);
|
||||||
{
|
|
||||||
private static final long serialVersionUID
|
|
||||||
= 3125772367019091216L;
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public int getReceiveBufferSize()
|
|
||||||
throws SocketException
|
|
||||||
{
|
|
||||||
return MultiplexingDatagramSocket.this.getReceiveBufferSize();
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Buffer variable for storing the SO_TIMEOUT value set by the
|
* Buffer variable for storing the SO_TIMEOUT value set by the
|
||||||
|
|||||||
@ -92,7 +92,7 @@ public class MultiplexingSocket
|
|||||||
* {@inheritDoc}
|
* {@inheritDoc}
|
||||||
*/
|
*/
|
||||||
@Override
|
@Override
|
||||||
protected List<DatagramPacket> getReceived()
|
protected SocketReceiveBuffer getReceived()
|
||||||
{
|
{
|
||||||
return received;
|
return received;
|
||||||
}
|
}
|
||||||
@ -101,7 +101,7 @@ public class MultiplexingSocket
|
|||||||
* {@inheritDoc}
|
* {@inheritDoc}
|
||||||
*/
|
*/
|
||||||
@Override
|
@Override
|
||||||
protected List<DatagramPacket> getReceived(
|
protected SocketReceiveBuffer getReceived(
|
||||||
MultiplexedSocket socket)
|
MultiplexedSocket socket)
|
||||||
{
|
{
|
||||||
return socket.received;
|
return socket.received;
|
||||||
@ -118,19 +118,8 @@ public class MultiplexingSocket
|
|||||||
* <tt>Socket</tt> i.e. not accepted by the <tt>DatagramFilter</tt>s of
|
* <tt>Socket</tt> i.e. not accepted by the <tt>DatagramFilter</tt>s of
|
||||||
* {@link #sockets} at the time of the reading from the network.
|
* {@link #sockets} at the time of the reading from the network.
|
||||||
*/
|
*/
|
||||||
private final List<DatagramPacket> received
|
private final SocketReceiveBuffer received
|
||||||
= new SocketReceiveBuffer()
|
= new SocketReceiveBuffer(this::getReceiveBufferSize);
|
||||||
{
|
|
||||||
private static final long serialVersionUID
|
|
||||||
= 4097024214973676873L;
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public int getReceiveBufferSize()
|
|
||||||
throws SocketException
|
|
||||||
{
|
|
||||||
return MultiplexingSocket.this.getReceiveBufferSize();
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Buffer variable for storing the SO_TIMEOUT value set by the last
|
* Buffer variable for storing the SO_TIMEOUT value set by the last
|
||||||
|
|||||||
@ -18,9 +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.util.*;
|
import java.util.*;
|
||||||
|
import java.util.concurrent.*;
|
||||||
import java.util.logging.*;
|
import java.util.logging.*;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -188,6 +188,24 @@ abstract class MultiplexingXXXSocketSupport
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The max number of {@link DatagramPacket}'s stored in the receive pool.
|
||||||
|
*/
|
||||||
|
private static final int RECEIVE_DATAGRAM_PACKETS_POOL_SIZE = 64;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The buffer size of pooled datagram packet used to read from
|
||||||
|
* underlying socket.
|
||||||
|
*/
|
||||||
|
private static final int POOLED_DATAGRAM_PACKET_SIZE = 1500;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A pool of {@link DatagramPacket}s used to receive data from unrelying
|
||||||
|
* socket.
|
||||||
|
*/
|
||||||
|
private final BlockingQueue<DatagramPacket> receiveDatagramPacketsPool
|
||||||
|
= new ArrayBlockingQueue<>(RECEIVE_DATAGRAM_PACKETS_POOL_SIZE);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The indicator which determines whether this <tt>DatagramSocket</tt> is
|
* The indicator which determines whether this <tt>DatagramSocket</tt> is
|
||||||
* currently reading from the network using
|
* currently reading from the network using
|
||||||
@ -247,7 +265,7 @@ abstract class MultiplexingXXXSocketSupport
|
|||||||
{
|
{
|
||||||
if (getFilter(socket).accept(p))
|
if (getFilter(socket).accept(p))
|
||||||
{
|
{
|
||||||
List<DatagramPacket> socketReceived = getReceived(socket);
|
SocketReceiveBuffer socketReceived = getReceived(socket);
|
||||||
|
|
||||||
synchronized (socketReceived)
|
synchronized (socketReceived)
|
||||||
{
|
{
|
||||||
@ -263,7 +281,7 @@ abstract class MultiplexingXXXSocketSupport
|
|||||||
}
|
}
|
||||||
if (!accepted)
|
if (!accepted)
|
||||||
{
|
{
|
||||||
List<DatagramPacket> thisReceived = getReceived();
|
SocketReceiveBuffer thisReceived = getReceived();
|
||||||
|
|
||||||
synchronized (thisReceived)
|
synchronized (thisReceived)
|
||||||
{
|
{
|
||||||
@ -352,7 +370,7 @@ abstract class MultiplexingXXXSocketSupport
|
|||||||
* not accepted by any (existing) {@code DatagramPacketFilter} at the time of
|
* not accepted by any (existing) {@code DatagramPacketFilter} at the time of
|
||||||
* receipt
|
* receipt
|
||||||
*/
|
*/
|
||||||
protected abstract List<DatagramPacket> getReceived();
|
protected abstract SocketReceiveBuffer getReceived();
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Gets the list of {@code DatagramPacket}s received by this multiplexing
|
* Gets the list of {@code DatagramPacket}s received by this multiplexing
|
||||||
@ -365,7 +383,7 @@ abstract class MultiplexingXXXSocketSupport
|
|||||||
* socket and accepted by the {@code DatagramPacketFilter} of the
|
* socket and accepted by the {@code DatagramPacketFilter} of the
|
||||||
* multiplexed {@code socket} at the time of receipt
|
* multiplexed {@code socket} at the time of receipt
|
||||||
*/
|
*/
|
||||||
protected abstract List<DatagramPacket> getReceived(
|
protected abstract SocketReceiveBuffer getReceived(
|
||||||
MultiplexedXXXSocketT socket);
|
MultiplexedXXXSocketT socket);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -470,47 +488,27 @@ abstract class MultiplexingXXXSocketSupport
|
|||||||
{
|
{
|
||||||
// Pull the packets which have been received already and are accepted by
|
// Pull the packets which have been received already and are accepted by
|
||||||
// the specified multiplexed socket out of the multiplexing socket.
|
// the specified multiplexed socket out of the multiplexing socket.
|
||||||
List<DatagramPacket> thisReceived = getReceived();
|
final SocketReceiveBuffer thisReceived = getReceived();
|
||||||
DatagramPacketFilter socketFilter = getFilter(socket);
|
final DatagramPacketFilter socketFilter = getFilter(socket);
|
||||||
List<DatagramPacket> toMove = null;
|
final List<DatagramPacket> toMove;
|
||||||
|
|
||||||
synchronized (thisReceived)
|
synchronized (thisReceived)
|
||||||
{
|
{
|
||||||
if (thisReceived.isEmpty())
|
toMove = thisReceived.scan(socketFilter);
|
||||||
{
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
for (Iterator<DatagramPacket> i = thisReceived.iterator();
|
|
||||||
i.hasNext();)
|
|
||||||
{
|
|
||||||
DatagramPacket p = i.next();
|
|
||||||
|
|
||||||
if (socketFilter.accept(p))
|
|
||||||
{
|
|
||||||
if (toMove == null)
|
|
||||||
toMove = new LinkedList<>();
|
|
||||||
toMove.add(p);
|
|
||||||
|
|
||||||
// XXX In the method receive, we allow multiple filters
|
|
||||||
// to accept one and the same packet.
|
|
||||||
i.remove();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Push the packets which have been accepted already and are accepted by
|
// Push the packets which have been accepted already and are accepted by
|
||||||
// the specified multiplexed socket into the multiplexed socket in
|
// the specified multiplexed socket into the multiplexed socket in
|
||||||
// question.
|
// question.
|
||||||
if (toMove != null)
|
if (!toMove.isEmpty())
|
||||||
{
|
{
|
||||||
List<DatagramPacket> socketReceived = getReceived(socket);
|
final SocketReceiveBuffer socketReceived = getReceived(socket);
|
||||||
|
|
||||||
synchronized (socketReceived)
|
synchronized (socketReceived)
|
||||||
{
|
{
|
||||||
socketReceived.addAll(toMove);
|
for (DatagramPacket datagramPacket : toMove) {
|
||||||
|
socketReceived.add(datagramPacket);
|
||||||
|
}
|
||||||
// The notifyAll will practically likely be unnecessary because
|
// The notifyAll will practically likely be unnecessary because
|
||||||
// the specified socket will likely be a newly-created one to
|
// the specified socket will likely be a newly-created one to
|
||||||
// which noone else has a reference. Anyway, dp the invocation
|
// which noone else has a reference. Anyway, dp the invocation
|
||||||
@ -539,11 +537,11 @@ abstract class MultiplexingXXXSocketSupport
|
|||||||
* @throws SocketTimeoutException if <tt>timeout</tt> is positive and has
|
* @throws SocketTimeoutException if <tt>timeout</tt> is positive and has
|
||||||
* expired
|
* expired
|
||||||
*/
|
*/
|
||||||
void receive(List<DatagramPacket> received, DatagramPacket p, int timeout)
|
void receive(SocketReceiveBuffer received, DatagramPacket p, int timeout)
|
||||||
throws IOException
|
throws IOException
|
||||||
{
|
{
|
||||||
long startTime = System.currentTimeMillis();
|
long startTime = System.currentTimeMillis();
|
||||||
DatagramPacket r = null;
|
DatagramPacket receivedPacket;
|
||||||
|
|
||||||
do
|
do
|
||||||
{
|
{
|
||||||
@ -555,13 +553,10 @@ abstract class MultiplexingXXXSocketSupport
|
|||||||
// SocketTimeoutException.
|
// SocketTimeoutException.
|
||||||
synchronized (received)
|
synchronized (received)
|
||||||
{
|
{
|
||||||
if (!received.isEmpty())
|
receivedPacket = received.poll();
|
||||||
{
|
if (receivedPacket != null)
|
||||||
r = received.remove(0);
|
|
||||||
if (r != null)
|
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
// Throw a SocketTimeoutException if the timeout is over/up.
|
// Throw a SocketTimeoutException if the timeout is over/up.
|
||||||
long remainingTimeout;
|
long remainingTimeout;
|
||||||
@ -622,8 +617,18 @@ abstract class MultiplexingXXXSocketSupport
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
// The caller will receive from the network.
|
// The pooled datagram packet instance will be used to receive
|
||||||
DatagramPacket c = clone(p, /* arraycopy */ false);
|
// from the network.
|
||||||
|
DatagramPacket receivePacket
|
||||||
|
= receiveDatagramPacketsPool.poll();
|
||||||
|
if (receivePacket == null)
|
||||||
|
{
|
||||||
|
receivePacket = new DatagramPacket(
|
||||||
|
new byte[POOLED_DATAGRAM_PACKET_SIZE],
|
||||||
|
POOLED_DATAGRAM_PACKET_SIZE);
|
||||||
|
}
|
||||||
|
|
||||||
|
receivePacket.setLength(POOLED_DATAGRAM_PACKET_SIZE);
|
||||||
|
|
||||||
synchronized (receiveSyncRoot)
|
synchronized (receiveSyncRoot)
|
||||||
{
|
{
|
||||||
@ -641,11 +646,11 @@ abstract class MultiplexingXXXSocketSupport
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
doReceive(c);
|
doReceive(receivePacket);
|
||||||
|
|
||||||
// The caller received from the network. Copy/add the packet to
|
// The caller received from the network. Copy/add the packet to
|
||||||
// the receive list of the sockets which accept it.
|
// the receive list of the sockets which accept it.
|
||||||
acceptBySocketsOrThis(c);
|
acceptBySocketsOrThis(receivePacket);
|
||||||
}
|
}
|
||||||
finally
|
finally
|
||||||
{
|
{
|
||||||
@ -658,7 +663,12 @@ abstract class MultiplexingXXXSocketSupport
|
|||||||
}
|
}
|
||||||
while (true);
|
while (true);
|
||||||
|
|
||||||
copy(r, p);
|
copy(receivedPacket, p);
|
||||||
|
|
||||||
|
// receivePacket is a datagram packet retrieved from SocketReceiveBuffer
|
||||||
|
// SocketReceiveBuffers only store datagrams borrowed from pool,
|
||||||
|
// so return datagram back to pool.
|
||||||
|
receiveDatagramPacketsPool.offer(receivedPacket);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@ -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.
|
||||||
*
|
*
|
||||||
@ -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);
|
||||||
}
|
}
|
||||||
|
|||||||
@ -19,6 +19,7 @@ package org.ice4j.socket;
|
|||||||
|
|
||||||
import java.io.*;
|
import java.io.*;
|
||||||
import java.net.*;
|
import java.net.*;
|
||||||
|
import java.util.concurrent.locks.*;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Represents a <tt>DatagramSocket</tt> which fixes the following problem: when
|
* Represents a <tt>DatagramSocket</tt> which fixes the following problem: when
|
||||||
@ -29,22 +30,17 @@ import java.net.*;
|
|||||||
* returns.
|
* returns.
|
||||||
*
|
*
|
||||||
* @author Lubomir Marinov
|
* @author Lubomir Marinov
|
||||||
|
* @author Yura Yaroshevich
|
||||||
*/
|
*/
|
||||||
public class SafeCloseDatagramSocket
|
public class SafeCloseDatagramSocket
|
||||||
extends DelegatingDatagramSocket
|
extends DelegatingDatagramSocket
|
||||||
{
|
{
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The number of {@link #receive(DatagramPacket)} calls that have to return
|
* A reader-writer lock to prevent {@link #close()} completion if any thread
|
||||||
* before {@link #close()} returns.
|
* is blocked within {@link #receive(DatagramPacket)}.
|
||||||
*/
|
*/
|
||||||
private int inReceive = 0;
|
private final ReadWriteLock receiveCloseLock
|
||||||
|
= new ReentrantReadWriteLock();
|
||||||
/**
|
|
||||||
* The <tt>Object</tt> which synchronizes the access to {@link #inReceive}
|
|
||||||
* and implements the related inter-thread communication.
|
|
||||||
*/
|
|
||||||
private final Object inReceiveSyncRoot = new Object();
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Initializes a new <tt>SafeCloseDatagramSocket</tt> instance and binds it
|
* Initializes a new <tt>SafeCloseDatagramSocket</tt> instance and binds it
|
||||||
@ -143,22 +139,10 @@ public class SafeCloseDatagramSocket
|
|||||||
{
|
{
|
||||||
super.close();
|
super.close();
|
||||||
|
|
||||||
synchronized (inReceiveSyncRoot)
|
final Lock closeLock = receiveCloseLock.writeLock();
|
||||||
{
|
closeLock.lock();
|
||||||
boolean interrupted = false;
|
// we now know all read threads have finished
|
||||||
|
closeLock.unlock();
|
||||||
while (inReceive > 0)
|
|
||||||
try
|
|
||||||
{
|
|
||||||
inReceiveSyncRoot.wait();
|
|
||||||
}
|
|
||||||
catch (InterruptedException iex)
|
|
||||||
{
|
|
||||||
interrupted = true;
|
|
||||||
}
|
|
||||||
if (interrupted)
|
|
||||||
Thread.currentThread().interrupt();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -182,21 +166,15 @@ public class SafeCloseDatagramSocket
|
|||||||
public void receive(DatagramPacket p)
|
public void receive(DatagramPacket p)
|
||||||
throws IOException
|
throws IOException
|
||||||
{
|
{
|
||||||
synchronized (inReceiveSyncRoot)
|
final Lock receiveLock = receiveCloseLock.readLock();
|
||||||
{
|
receiveLock.lock();
|
||||||
inReceive++;
|
|
||||||
}
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
super.receive(p);
|
super.receive(p);
|
||||||
}
|
}
|
||||||
finally
|
finally
|
||||||
{
|
{
|
||||||
synchronized (inReceiveSyncRoot)
|
receiveLock.unlock();
|
||||||
{
|
|
||||||
inReceive--;
|
|
||||||
inReceiveSyncRoot.notifyAll();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -19,70 +19,228 @@ package org.ice4j.socket;
|
|||||||
|
|
||||||
import java.net.*;
|
import java.net.*;
|
||||||
import java.util.*;
|
import java.util.*;
|
||||||
|
import java.util.concurrent.*;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Implements a list of <tt>DatagramPacket</tt>s received by a
|
* Implements a buffer of <tt>DatagramPacket</tt>s received by a
|
||||||
* <tt>DatagramSocket</tt> or a <tt>Socket</tt>. The list enforces the
|
* <tt>DatagramSocket</tt> or a <tt>Socket</tt>. The list enforces the
|
||||||
* <tt>SO_RCVBUF</tt> option for the associated <tt>DatagramSocket</tt> or
|
* <tt>SO_RCVBUF</tt> option for the associated <tt>DatagramSocket</tt> or
|
||||||
* <tt>Socket</tt>.
|
* <tt>Socket</tt>.
|
||||||
*
|
*
|
||||||
* @author Lyubomir Marinov
|
* @author Lyubomir Marinov
|
||||||
|
* @author Yura Yaroshevich
|
||||||
*/
|
*/
|
||||||
abstract class SocketReceiveBuffer
|
class SocketReceiveBuffer
|
||||||
extends LinkedList<DatagramPacket>
|
|
||||||
{
|
{
|
||||||
|
/**
|
||||||
|
* Default size in bytes of socket receive buffer.
|
||||||
|
*/
|
||||||
private static final int DEFAULT_RECEIVE_BUFFER_SIZE = 1024 * 1024;
|
private static final int DEFAULT_RECEIVE_BUFFER_SIZE = 1024 * 1024;
|
||||||
|
|
||||||
private static final long serialVersionUID = 2804762379509257652L;
|
/**
|
||||||
|
* Maxumum number of datagrams buffer is capable to store regardless
|
||||||
|
* of total datagram size in bytes.
|
||||||
|
*/
|
||||||
|
private static final int DATAGRAMS_BUFFER_CAPACITY = 10000;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Queue to store received datagrams.
|
||||||
|
*/
|
||||||
|
private final BlockingQueue<DatagramPacket> buffer
|
||||||
|
= new ArrayBlockingQueue<>(DATAGRAMS_BUFFER_CAPACITY);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* An instance of datagram size tracker to compute total number of bytes
|
||||||
|
* stored in datagrams witin {@link #buffer}.
|
||||||
|
*/
|
||||||
|
private final DatagramSizeTracker tracker;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Constructs {@link SocketReceiveBuffer} with user-provided
|
||||||
|
* @param receiveBufferSizeSupplier a function to obtain receive buffer
|
||||||
|
* size from associated socket.
|
||||||
|
*/
|
||||||
|
public SocketReceiveBuffer(Callable<Integer> receiveBufferSizeSupplier)
|
||||||
|
{
|
||||||
|
this.tracker = new DatagramSizeTracker(receiveBufferSizeSupplier);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check if receive buffer is empty
|
||||||
|
* @return true if buffer is empty, false - otherwise.
|
||||||
|
*/
|
||||||
|
public boolean isEmpty()
|
||||||
|
{
|
||||||
|
return buffer.isEmpty();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Adds {@link DatagramPacket} at the end of the socket receive buffer.
|
||||||
|
* @param p datagram to add into receive buffer
|
||||||
|
*/
|
||||||
|
public void add(DatagramPacket p)
|
||||||
|
{
|
||||||
|
while (!buffer.offer(p))
|
||||||
|
{
|
||||||
|
// ensure buffer capacity restriction enforced
|
||||||
|
poll();
|
||||||
|
}
|
||||||
|
|
||||||
|
tracker.trackDatagramAdded(p);
|
||||||
|
|
||||||
|
while (tracker.isExceedReceiveBufferSize() && buffer.size() > 1)
|
||||||
|
{
|
||||||
|
// enforce SO_RCVBUF restriction
|
||||||
|
poll();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Polls socket receive buffer for already stored {@link DatagramPacket}
|
||||||
|
* @return the first datagram in the buffer, or {@code null} if buffer
|
||||||
|
* is empty.
|
||||||
|
*/
|
||||||
|
public DatagramPacket poll()
|
||||||
|
{
|
||||||
|
DatagramPacket p = buffer.poll();
|
||||||
|
|
||||||
|
// Keep track of the (total) size in bytes of this receive buffer in
|
||||||
|
// order to be able to enforce SO_RCVBUF restriction.
|
||||||
|
if (p != null)
|
||||||
|
{
|
||||||
|
tracker.trackDatagramRemoved(p);
|
||||||
|
}
|
||||||
|
|
||||||
|
return p;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Scans buffer of received {@link DatagramPacket}s and move
|
||||||
|
* datagrams which matches the {@code filter} into returned list.
|
||||||
|
* @param filter a predicate to filter {@link DatagramPacket} stored
|
||||||
|
* in receive buffer.
|
||||||
|
* @return list of datagrams matched to {@code filter}.
|
||||||
|
*/
|
||||||
|
public List<DatagramPacket> scan(DatagramPacketFilter filter)
|
||||||
|
{
|
||||||
|
List<DatagramPacket> matchedDatagrams = null;
|
||||||
|
final Iterator<DatagramPacket> it = buffer.iterator();
|
||||||
|
|
||||||
|
while (it.hasNext())
|
||||||
|
{
|
||||||
|
final DatagramPacket p = it.next();
|
||||||
|
|
||||||
|
if (filter.accept(p))
|
||||||
|
{
|
||||||
|
if (matchedDatagrams == null)
|
||||||
|
{
|
||||||
|
matchedDatagrams = new ArrayList<>();
|
||||||
|
}
|
||||||
|
matchedDatagrams.add(p);
|
||||||
|
|
||||||
|
it.remove();
|
||||||
|
|
||||||
|
tracker.trackDatagramRemoved(p);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (matchedDatagrams != null)
|
||||||
|
{
|
||||||
|
return matchedDatagrams;
|
||||||
|
}
|
||||||
|
return Collections.emptyList();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A helper class to keep track of total size in bytes of all
|
||||||
|
* {@link DatagramPacket} instances stored in {@link #buffer} to
|
||||||
|
* be able to enforce SO_RCVBUF.
|
||||||
|
*/
|
||||||
|
private final class DatagramSizeTracker
|
||||||
|
{
|
||||||
/**
|
/**
|
||||||
* The value of the <tt>SO_RCVBUF</tt> option for the associated
|
* The value of the <tt>SO_RCVBUF</tt> option for the associated
|
||||||
* <tt>DatagramSocket</tt> or <tt>Socket</tt>. Cached for the sake of
|
* <tt>DatagramSocket</tt> or <tt>Socket</tt>. Cached for the sake of
|
||||||
* performance.
|
* performance.
|
||||||
*/
|
*/
|
||||||
private int receiveBufferSize;
|
private int cachedReceiveBufferSize;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The (total) size in bytes of this receive buffer.
|
* The (total) size in bytes of this receive buffer.
|
||||||
*/
|
*/
|
||||||
private int size;
|
private int totalBuffersByteSize;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* {@inheritDoc}
|
* Counts total number of datagrams added to buffer.
|
||||||
*/
|
*/
|
||||||
@Override
|
private int totalDatagramsAdded;
|
||||||
public boolean add(DatagramPacket p)
|
|
||||||
{
|
|
||||||
boolean added = super.add(p);
|
|
||||||
|
|
||||||
// Keep track of the (total) size in bytes of this receive buffer in
|
/**
|
||||||
// order to be able to enforce SO_RCVBUF.
|
* A user provided getter of receive buffer size, might
|
||||||
if (added && (p != null))
|
* fail with {@link Exception} when called.
|
||||||
{
|
*/
|
||||||
int pSize = p.getLength();
|
private final Callable<Integer> receiveBufferSizeSupplier;
|
||||||
|
|
||||||
if (pSize > 0)
|
/**
|
||||||
|
* Create a tracker of datagram packet size stored in buffer.
|
||||||
|
* @param receiveBufferSizeSupplier a function to obtain receive buffer
|
||||||
|
* size from associated socket.
|
||||||
|
*/
|
||||||
|
public DatagramSizeTracker(
|
||||||
|
Callable<Integer> receiveBufferSizeSupplier)
|
||||||
{
|
{
|
||||||
size += pSize;
|
this.receiveBufferSizeSupplier = receiveBufferSizeSupplier;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check if total bytes stored in {@link #buffer} exceeds socket's
|
||||||
|
* receive buffer size.
|
||||||
|
* @return true if size exceeded, false - otherwise
|
||||||
|
*/
|
||||||
|
boolean isExceedReceiveBufferSize()
|
||||||
|
{
|
||||||
|
return totalBuffersByteSize > cachedReceiveBufferSize;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Updates computed value of total datagrams size in bytes
|
||||||
|
* stored in {@link #buffer} with datagram just added to buffer.
|
||||||
|
* @param p datagram packed added to {@link #buffer}
|
||||||
|
*/
|
||||||
|
void trackDatagramAdded(DatagramPacket p)
|
||||||
|
{
|
||||||
|
++totalDatagramsAdded;
|
||||||
|
|
||||||
|
final int pSize = p.getLength();
|
||||||
|
if (pSize <= 0)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
totalBuffersByteSize += pSize;
|
||||||
|
|
||||||
// If the added packet is the only element of this list, do not
|
// If the added packet is the only element of this list, do not
|
||||||
// drop it because of the enforcement of SO_RCVBUF.
|
// drop it because of the enforcement of SO_RCVBUF.
|
||||||
if (size() > 1)
|
if (buffer.size() > 1)
|
||||||
{
|
{
|
||||||
// For the sake of performance, do not invoke the method
|
// For the sake of performance, do not invoke the method
|
||||||
// getReceiveBufferSize() of DatagramSocket or Socket on
|
// getReceiveBufferSize() of DatagramSocket or Socket on
|
||||||
// every packet added to this buffer.
|
// every packet added to this buffer.
|
||||||
int receiveBufferSize = this.receiveBufferSize;
|
int receiveBufferSize = this.cachedReceiveBufferSize;
|
||||||
|
|
||||||
if ((receiveBufferSize <= 0) || (modCount % 1000 == 0))
|
if ((receiveBufferSize <= 0)
|
||||||
|
|| (totalDatagramsAdded % 1000 == 0))
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
receiveBufferSize = getReceiveBufferSize();
|
receiveBufferSize
|
||||||
|
= this.receiveBufferSizeSupplier.call();
|
||||||
}
|
}
|
||||||
catch (SocketException sex)
|
catch (Exception e)
|
||||||
{
|
{
|
||||||
|
// nothing to do
|
||||||
}
|
}
|
||||||
|
|
||||||
if (receiveBufferSize <= 0)
|
if (receiveBufferSize <= 0)
|
||||||
{
|
{
|
||||||
receiveBufferSize = DEFAULT_RECEIVE_BUFFER_SIZE;
|
receiveBufferSize = DEFAULT_RECEIVE_BUFFER_SIZE;
|
||||||
@ -101,50 +259,29 @@ abstract class SocketReceiveBuffer
|
|||||||
= DEFAULT_RECEIVE_BUFFER_SIZE;
|
= DEFAULT_RECEIVE_BUFFER_SIZE;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
this.receiveBufferSize = receiveBufferSize;
|
this.cachedReceiveBufferSize = receiveBufferSize;
|
||||||
}
|
|
||||||
if (size > receiveBufferSize)
|
|
||||||
remove(0);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return added;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Gets the value of the <tt>SO_RCVBUF</tt> option for the associated
|
* Updates computed value of total datagrams size in bytes
|
||||||
* <tt>DatagramSocket</tt> or <tt>Socket</tt> which is the buffer size used
|
* stored in {@link #buffer} with datagram just removed from buffer.
|
||||||
* by the platform for input on the <tt>DatagramSocket</tt> or
|
* @param p datagram packed removed from {@link #buffer}
|
||||||
* <tt>Socket</tt>.
|
|
||||||
*
|
|
||||||
* @return the value of the <tt>SO_RCVBUF</tt> option for the associated
|
|
||||||
* <tt>DatagramSocket</tt> or <tt>Socket</tt>
|
|
||||||
* @throws SocketException if there is an error in the underlying protocol
|
|
||||||
*/
|
*/
|
||||||
public abstract int getReceiveBufferSize()
|
void trackDatagramRemoved(DatagramPacket p)
|
||||||
throws SocketException;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* {@inheritDoc}
|
|
||||||
*/
|
|
||||||
@Override
|
|
||||||
public DatagramPacket remove(int index)
|
|
||||||
{
|
{
|
||||||
DatagramPacket p = super.remove(index);
|
final int pSize = p.getLength();
|
||||||
|
if (pSize <= 0)
|
||||||
// Keep track of the (total) size in bytes of this receive buffer in
|
|
||||||
// order to be able to enforce SO_RCVBUF.
|
|
||||||
if (p != null)
|
|
||||||
{
|
{
|
||||||
int pSize = p.getLength();
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
if (pSize > 0)
|
totalBuffersByteSize -= pSize;
|
||||||
|
if (totalBuffersByteSize < 0)
|
||||||
{
|
{
|
||||||
size -= pSize;
|
totalBuffersByteSize = 0;
|
||||||
if (size < 0)
|
|
||||||
size = 0;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return p;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -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;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -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);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -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);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -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"));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -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;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -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"));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
File diff suppressed because it is too large
Load Diff
@ -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;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -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;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -20,7 +20,7 @@ package org.ice4j.stack;
|
|||||||
import java.io.*;
|
import java.io.*;
|
||||||
import java.net.*;
|
import java.net.*;
|
||||||
import java.nio.channels.*;
|
import java.nio.channels.*;
|
||||||
import java.util.concurrent.*;
|
import java.util.function.*;
|
||||||
import java.util.logging.*;
|
import java.util.logging.*;
|
||||||
|
|
||||||
import org.ice4j.*;
|
import org.ice4j.*;
|
||||||
@ -29,8 +29,9 @@ import org.ice4j.socket.*;
|
|||||||
/**
|
/**
|
||||||
* The Network Access Point is the most outward part of the stack. It is
|
* The Network Access Point is the most outward part of the stack. It is
|
||||||
* constructed around a datagram socket and takes care of forwarding incoming
|
* constructed around a datagram socket and takes care of forwarding incoming
|
||||||
* messages to the MessageProcessor as well as sending datagrams to the STUN
|
* messages to the provided {@link #messageConsumer} as well as sending
|
||||||
* server specified by the original NetAccessPointDescriptor.
|
* datagrams to the STUN server specified by the
|
||||||
|
* original NetAccessPointDescriptor.
|
||||||
*
|
*
|
||||||
* @author Emil Ivov
|
* @author Emil Ivov
|
||||||
*/
|
*/
|
||||||
@ -44,9 +45,9 @@ class Connector
|
|||||||
= Logger.getLogger(Connector.class.getName());
|
= Logger.getLogger(Connector.class.getName());
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The message queue is where incoming messages are added.
|
* The consumer of incoming <tt>RawMessage</tt>s
|
||||||
*/
|
*/
|
||||||
private final BlockingQueue<RawMessage> messageQueue;
|
private final Consumer<RawMessage> messageConsumer;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The socket object that used by this access point to access the network.
|
* The socket object that used by this access point to access the network.
|
||||||
@ -87,16 +88,16 @@ class Connector
|
|||||||
* communication.
|
* communication.
|
||||||
* @param remoteAddress the remote address of the socket of this
|
* @param remoteAddress the remote address of the socket of this
|
||||||
* {@link Connector} if it is a TCP socket, or null if it is UDP.
|
* {@link Connector} if it is a TCP socket, or null if it is UDP.
|
||||||
* @param messageQueue the Queue where incoming messages should be queued
|
* @param messageConsumer the incoming messages consumer
|
||||||
* @param errorHandler the instance to notify when errors occur.
|
* @param errorHandler the instance to notify when errors occur.
|
||||||
*/
|
*/
|
||||||
protected Connector(IceSocketWrapper socket,
|
protected Connector(IceSocketWrapper socket,
|
||||||
TransportAddress remoteAddress,
|
TransportAddress remoteAddress,
|
||||||
BlockingQueue<RawMessage> messageQueue,
|
Consumer<RawMessage> messageConsumer,
|
||||||
ErrorHandler errorHandler)
|
ErrorHandler errorHandler)
|
||||||
{
|
{
|
||||||
this.sock = socket;
|
this.sock = socket;
|
||||||
this.messageQueue = messageQueue;
|
this.messageConsumer = messageConsumer;
|
||||||
this.errorHandler = errorHandler;
|
this.errorHandler = errorHandler;
|
||||||
this.remoteAddress = remoteAddress;
|
this.remoteAddress = remoteAddress;
|
||||||
|
|
||||||
@ -209,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());
|
||||||
}
|
}
|
||||||
@ -230,7 +232,7 @@ class Connector
|
|||||||
listenAddress.getTransport()),
|
listenAddress.getTransport()),
|
||||||
listenAddress);
|
listenAddress);
|
||||||
|
|
||||||
messageQueue.add(rawMessage);
|
messageConsumer.accept(rawMessage);
|
||||||
}
|
}
|
||||||
catch (SocketException ex)
|
catch (SocketException ex)
|
||||||
{
|
{
|
||||||
@ -324,8 +326,16 @@ class Connector
|
|||||||
DatagramPacket datagramPacket
|
DatagramPacket datagramPacket
|
||||||
= new DatagramPacket(message, 0, message.length, address);
|
= new DatagramPacket(message, 0, message.length, address);
|
||||||
|
|
||||||
|
IceSocketWrapper sock = this.sock;
|
||||||
|
if (sock != null)
|
||||||
|
{
|
||||||
sock.send(datagramPacket);
|
sock.send(datagramPacket);
|
||||||
}
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
logger.warning("Can not send message, Connector stopped.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Returns a String representation of the object.
|
* Returns a String representation of the object.
|
||||||
|
|||||||
216
src/main/java/org/ice4j/stack/MessageProcessingTask.java
Normal file
216
src/main/java/org/ice4j/stack/MessageProcessingTask.java
Normal file
@ -0,0 +1,216 @@
|
|||||||
|
/*
|
||||||
|
* 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.stack;
|
||||||
|
|
||||||
|
import java.util.concurrent.atomic.*;
|
||||||
|
import java.util.function.*;
|
||||||
|
import java.util.logging.*;
|
||||||
|
|
||||||
|
import org.ice4j.*;
|
||||||
|
import org.ice4j.message.*;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The class is used to parse and dispatch incoming messages by being
|
||||||
|
* executed by concurrent {@link java.util.concurrent.ExecutorService}.
|
||||||
|
* To reduce memory allocation this class is designed to be suitable for
|
||||||
|
* usage with pooling, the instance of this type is mutable such that
|
||||||
|
* <tt>RawMessage</tt> can be updated and instance can be reused and
|
||||||
|
* scheduled with new <tt>RawMessage</tt>
|
||||||
|
*
|
||||||
|
* @author Emil Ivov
|
||||||
|
* @author Yura Yaroshevich
|
||||||
|
*/
|
||||||
|
class MessageProcessingTask
|
||||||
|
implements Runnable
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Our class logger.
|
||||||
|
*/
|
||||||
|
private static final Logger logger
|
||||||
|
= Logger.getLogger(MessageProcessingTask.class.getName());
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Indicates that <tt>MessageProcessingTask</tt> is cancelled and should not
|
||||||
|
* process <tt>RawMessage</tt> anymore.
|
||||||
|
*/
|
||||||
|
private final AtomicBoolean cancelled = new AtomicBoolean(false);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The <tt>NetAccessManager</tt> which has created this instance and which
|
||||||
|
* is its owner.
|
||||||
|
*/
|
||||||
|
private final NetAccessManager netAccessManager;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The listener that will be collecting error notifications.
|
||||||
|
*/
|
||||||
|
private final ErrorHandler errorHandler;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The listener that will be retrieving <tt>MessageEvent</tt>s
|
||||||
|
*/
|
||||||
|
private final MessageEventHandler messageEventHandler;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Raw message which is being processed
|
||||||
|
*/
|
||||||
|
private RawMessage rawMessage;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Callback which is invoked when this <tt>MessageProcessingTask</tt>
|
||||||
|
* processed it's {@link #rawMessage}
|
||||||
|
*/
|
||||||
|
private Consumer<MessageProcessingTask> rawMessageProcessedHandler;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Creates a Message processor.
|
||||||
|
*
|
||||||
|
* @param netAccessManager the <tt>NetAccessManager</tt> which is creating
|
||||||
|
* the new instance, is going to be its owner, specifies the
|
||||||
|
* <tt>MessageEventHandler</tt> and represents the <tt>ErrorHandler</tt> to
|
||||||
|
* handle exceptions in the new instance
|
||||||
|
* @throws IllegalArgumentException if any of the mentioned properties of
|
||||||
|
* <tt>netAccessManager</tt> are <tt>null</tt>
|
||||||
|
*/
|
||||||
|
MessageProcessingTask(NetAccessManager netAccessManager)
|
||||||
|
throws IllegalArgumentException
|
||||||
|
{
|
||||||
|
if (netAccessManager == null)
|
||||||
|
{
|
||||||
|
throw new NullPointerException("netAccessManager");
|
||||||
|
}
|
||||||
|
|
||||||
|
MessageEventHandler messageEventHandler
|
||||||
|
= netAccessManager.getMessageEventHandler();
|
||||||
|
|
||||||
|
if (messageEventHandler == null)
|
||||||
|
{
|
||||||
|
throw new IllegalArgumentException(
|
||||||
|
"The message event handler may not be null");
|
||||||
|
}
|
||||||
|
|
||||||
|
this.netAccessManager = netAccessManager;
|
||||||
|
this.messageEventHandler = messageEventHandler;
|
||||||
|
this.errorHandler = netAccessManager;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Assigns the <tt>RawMessage</tt> that will be processed
|
||||||
|
* by this <tt>MessageProcessingTask</tt> on executor's thread.
|
||||||
|
* @param message RawMessage to be processed
|
||||||
|
* @param onProcessed callback which will be invoked when processing
|
||||||
|
* of {@link #rawMessage} is completed
|
||||||
|
*/
|
||||||
|
void setMessage(
|
||||||
|
RawMessage message,
|
||||||
|
Consumer<MessageProcessingTask> onProcessed)
|
||||||
|
{
|
||||||
|
if (message == null)
|
||||||
|
{
|
||||||
|
throw new IllegalArgumentException("The message may not be null");
|
||||||
|
}
|
||||||
|
rawMessage = message;
|
||||||
|
rawMessageProcessedHandler = onProcessed;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Performs proper reset of internal state of pooled instance.
|
||||||
|
*/
|
||||||
|
void resetState()
|
||||||
|
{
|
||||||
|
cancelled.set(false);
|
||||||
|
rawMessage = null;
|
||||||
|
rawMessageProcessedHandler = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Attempts to cancel processing of {@link #rawMessage}
|
||||||
|
*/
|
||||||
|
public void cancel()
|
||||||
|
{
|
||||||
|
cancelled.set(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Does the message parsing.
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
public void run()
|
||||||
|
{
|
||||||
|
final Consumer<MessageProcessingTask> onProcessed
|
||||||
|
= rawMessageProcessedHandler;
|
||||||
|
final RawMessage message = rawMessage;
|
||||||
|
//add an extra try/catch block that handles uncatched errors
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (message == null)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
rawMessage = null;
|
||||||
|
rawMessageProcessedHandler = null;
|
||||||
|
|
||||||
|
if (cancelled.get())
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
StunStack stunStack = netAccessManager.getStunStack();
|
||||||
|
|
||||||
|
Message stunMessage;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
stunMessage
|
||||||
|
= Message.decode(message.getBytes(),
|
||||||
|
0,
|
||||||
|
message.getMessageLength());
|
||||||
|
}
|
||||||
|
catch (StunException ex)
|
||||||
|
{
|
||||||
|
errorHandler.handleError(
|
||||||
|
"Failed to decode a stun message!",
|
||||||
|
ex);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.finest("Dispatching a StunMessageEvent.");
|
||||||
|
|
||||||
|
StunMessageEvent stunMessageEvent
|
||||||
|
= new StunMessageEvent(stunStack, message, stunMessage);
|
||||||
|
|
||||||
|
messageEventHandler.handleMessageEvent(stunMessageEvent);
|
||||||
|
}
|
||||||
|
catch (Throwable err)
|
||||||
|
{
|
||||||
|
errorHandler.handleFatalError(
|
||||||
|
Thread.currentThread(),
|
||||||
|
"Unexpected Error!", err);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
// On processed callback must be invoked in all cases, even when
|
||||||
|
// cancellation or early exist happen, otherwise
|
||||||
|
// NetAccessManager internal tracking of pooled and active
|
||||||
|
// message processors will misbehave.
|
||||||
|
if (onProcessed != null)
|
||||||
|
{
|
||||||
|
onProcessed.accept(this);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -1,212 +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.stack;
|
|
||||||
|
|
||||||
import java.util.concurrent.*;
|
|
||||||
import java.util.logging.*;
|
|
||||||
|
|
||||||
import org.ice4j.*;
|
|
||||||
import org.ice4j.message.*;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The class is used to parse and dispatch incoming messages in a multi-thread
|
|
||||||
* manner.
|
|
||||||
*
|
|
||||||
* @author Emil Ivov
|
|
||||||
*/
|
|
||||||
class MessageProcessor
|
|
||||||
implements Runnable
|
|
||||||
{
|
|
||||||
/**
|
|
||||||
* Our class logger.
|
|
||||||
*/
|
|
||||||
private static final Logger logger
|
|
||||||
= Logger.getLogger(MessageProcessor.class.getName());
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The listener that will be collecting error notifications.
|
|
||||||
*/
|
|
||||||
private final ErrorHandler errorHandler;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The queue where we store incoming messages until they are collected.
|
|
||||||
*/
|
|
||||||
private final BlockingQueue<RawMessage> messageQueue;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The listener that will be retrieving <tt>MessageEvent</tt>s
|
|
||||||
*/
|
|
||||||
private final MessageEventHandler messageEventHandler;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The <tt>NetAccessManager</tt> which has created this instance and which
|
|
||||||
* is its owner.
|
|
||||||
*/
|
|
||||||
private final NetAccessManager netAccessManager;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The flag that indicates whether we are still running.
|
|
||||||
*/
|
|
||||||
private boolean running = false;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* A reference to the thread that we use to execute ourselves.
|
|
||||||
*/
|
|
||||||
private Thread runningThread = null;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Creates a Message processor.
|
|
||||||
*
|
|
||||||
* @param netAccessManager the <tt>NetAccessManager</tt> which is creating
|
|
||||||
* the new instance, is going to be its owner, specifies the
|
|
||||||
* <tt>BlockingQueue</tt> which is to store incoming messages, specifies the
|
|
||||||
* <tt>MessageEventHandler</tt> and represents the <tt>ErrorHandler</tt> to
|
|
||||||
* handle exceptions in the new instance
|
|
||||||
* @throws IllegalArgumentException if any of the mentioned properties of
|
|
||||||
* <tt>netAccessManager</tt> are <tt>null</tt>
|
|
||||||
*/
|
|
||||||
MessageProcessor(NetAccessManager netAccessManager)
|
|
||||||
throws IllegalArgumentException
|
|
||||||
{
|
|
||||||
if (netAccessManager == null)
|
|
||||||
throw new NullPointerException("netAccessManager");
|
|
||||||
|
|
||||||
BlockingQueue<RawMessage> messageQueue = netAccessManager.getMessageQueue();
|
|
||||||
|
|
||||||
if (messageQueue == null)
|
|
||||||
{
|
|
||||||
throw new IllegalArgumentException(
|
|
||||||
"The message queue may not be null");
|
|
||||||
}
|
|
||||||
|
|
||||||
MessageEventHandler messageEventHandler
|
|
||||||
= netAccessManager.getMessageEventHandler();
|
|
||||||
|
|
||||||
if(messageEventHandler == null)
|
|
||||||
{
|
|
||||||
throw new IllegalArgumentException(
|
|
||||||
"The message event handler may not be null");
|
|
||||||
}
|
|
||||||
|
|
||||||
this.netAccessManager = netAccessManager;
|
|
||||||
this.messageQueue = messageQueue;
|
|
||||||
this.messageEventHandler = messageEventHandler;
|
|
||||||
this.errorHandler = netAccessManager;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Does the message parsing.
|
|
||||||
*/
|
|
||||||
public void run()
|
|
||||||
{
|
|
||||||
//add an extra try/catch block that handles uncatched errors and helps
|
|
||||||
//avoid having dead threads in our pools.
|
|
||||||
try
|
|
||||||
{
|
|
||||||
StunStack stunStack = netAccessManager.getStunStack();
|
|
||||||
|
|
||||||
while (running)
|
|
||||||
{
|
|
||||||
RawMessage rawMessage;
|
|
||||||
|
|
||||||
try
|
|
||||||
{
|
|
||||||
rawMessage = messageQueue.take();
|
|
||||||
}
|
|
||||||
catch (InterruptedException ex)
|
|
||||||
{
|
|
||||||
if(isRunning())
|
|
||||||
logger.log(Level.WARNING,
|
|
||||||
"A net access point has gone useless: ", ex);
|
|
||||||
//nothing to do here since we test whether we are running
|
|
||||||
//just beneath ...
|
|
||||||
rawMessage = null;
|
|
||||||
}
|
|
||||||
|
|
||||||
// were we asked to stop?
|
|
||||||
if (!isRunning())
|
|
||||||
return;
|
|
||||||
//anything to parse?
|
|
||||||
if (rawMessage == null)
|
|
||||||
continue;
|
|
||||||
|
|
||||||
Message stunMessage = null;
|
|
||||||
try
|
|
||||||
{
|
|
||||||
stunMessage
|
|
||||||
= Message.decode(rawMessage.getBytes(),
|
|
||||||
(char) 0,
|
|
||||||
(char) rawMessage.getMessageLength());
|
|
||||||
}
|
|
||||||
catch (StunException ex)
|
|
||||||
{
|
|
||||||
errorHandler.handleError(
|
|
||||||
"Failed to decode a stun message!",
|
|
||||||
ex);
|
|
||||||
|
|
||||||
continue; //let this one go and for better luck next time.
|
|
||||||
}
|
|
||||||
|
|
||||||
logger.finest("Dispatching a StunMessageEvent.");
|
|
||||||
|
|
||||||
StunMessageEvent stunMessageEvent
|
|
||||||
= new StunMessageEvent(stunStack, rawMessage,
|
|
||||||
stunMessage);
|
|
||||||
|
|
||||||
messageEventHandler.handleMessageEvent(stunMessageEvent);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
catch(Throwable err)
|
|
||||||
{
|
|
||||||
//notify and bail
|
|
||||||
errorHandler.handleFatalError(this, "Unexpected Error!", err);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Start the message processing thread.
|
|
||||||
*/
|
|
||||||
void start()
|
|
||||||
{
|
|
||||||
this.running = true;
|
|
||||||
|
|
||||||
runningThread = new Thread(this, "Stun4J Message Processor");
|
|
||||||
runningThread.setDaemon(true);
|
|
||||||
runningThread.start();
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Shut down the message processor.
|
|
||||||
*/
|
|
||||||
void stop()
|
|
||||||
{
|
|
||||||
this.running = false;
|
|
||||||
runningThread.interrupt();
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Determines whether the processor is still running;
|
|
||||||
*
|
|
||||||
* @return true if the processor is still authorized to run, and false
|
|
||||||
* otherwise.
|
|
||||||
*/
|
|
||||||
boolean isRunning()
|
|
||||||
{
|
|
||||||
return running;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -17,28 +17,32 @@
|
|||||||
*/
|
*/
|
||||||
package org.ice4j.stack;
|
package org.ice4j.stack;
|
||||||
|
|
||||||
|
import org.ice4j.*;
|
||||||
|
import org.ice4j.message.*;
|
||||||
|
import org.ice4j.socket.*;
|
||||||
|
import org.jitsi.utils.concurrent.*;
|
||||||
|
|
||||||
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.concurrent.atomic.*;
|
||||||
|
import java.util.function.*;
|
||||||
import java.util.logging.*;
|
import java.util.logging.*;
|
||||||
|
|
||||||
import org.ice4j.*;
|
|
||||||
import org.ice4j.message.*;
|
|
||||||
import org.ice4j.socket.*;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Manages <tt>Connector</tt>s and <tt>MessageProcessor</tt> pooling. This class
|
* Manages <tt>Connector</tt>s and <tt>MessageProcessingTask</tt> execution and
|
||||||
* serves as a layer that masks network primitives and provides equivalent STUN
|
* pooling. This class serves as a layer that masks network primitives and
|
||||||
* abstractions. Instances that operate with the NetAccessManager are only
|
* provides equivalent STUN abstractions. Instances that operate with
|
||||||
* supposed to understand STUN talk and shouldn't be aware of datagrams sockets,
|
* the NetAccessManager are only supposed to understand STUN talk and
|
||||||
* and etc.
|
* shouldn't be aware of datagrams sockets, and etc.
|
||||||
*
|
*
|
||||||
* @author Emil Ivov
|
* @author Emil Ivov
|
||||||
* @author Aakash Garg
|
* @author Aakash Garg
|
||||||
* @author Boris Grozev
|
* @author Boris Grozev
|
||||||
|
* @author Yura Yaroshevich
|
||||||
*/
|
*/
|
||||||
class NetAccessManager
|
public class NetAccessManager
|
||||||
implements ErrorHandler
|
implements ErrorHandler
|
||||||
{
|
{
|
||||||
/**
|
/**
|
||||||
@ -47,6 +51,35 @@ class NetAccessManager
|
|||||||
private static final Logger logger
|
private static final Logger logger
|
||||||
= Logger.getLogger(NetAccessManager.class.getName());
|
= Logger.getLogger(NetAccessManager.class.getName());
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Thread pool to execute {@link MessageProcessingTask}s across all
|
||||||
|
* {@link NetAccessManager}s.
|
||||||
|
*/
|
||||||
|
private static ExecutorService messageProcessingExecutor
|
||||||
|
= ExecutorFactory.createCachedThreadPool("ice4j.NetAccessManager-");
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Maximum number of {@link MessageProcessingTask} to keep in object pool.
|
||||||
|
* Each {@link NetAccessManager} has it's own pool, small pool size is
|
||||||
|
* enough to save allocations.
|
||||||
|
*/
|
||||||
|
private static final int TASK_POOL_SIZE = 8;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Pool of <tt>MessageProcessingTask</tt> objects to avoid extra-allocations
|
||||||
|
* of processor object per <tt>RawMessage</tt> needed to process.
|
||||||
|
*/
|
||||||
|
private final ArrayBlockingQueue<MessageProcessingTask> taskPool
|
||||||
|
= new ArrayBlockingQueue<>(TASK_POOL_SIZE);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The set of {@link MessageProcessingTask}'s which are not yet finished
|
||||||
|
* it's, processing, tracking of active tasks is necessary to properly
|
||||||
|
* cancel pending tasks in case {@link #stop()} is called.
|
||||||
|
*/
|
||||||
|
private final ConcurrentHashMap.KeySetView<MessageProcessingTask, Boolean>
|
||||||
|
activeTasks = ConcurrentHashMap.newKeySet();
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* All <tt>Connectors</tt> currently in use with UDP. The table maps a local
|
* All <tt>Connectors</tt> currently in use with UDP. The table maps a local
|
||||||
* <tt>TransportAddress</tt> and and a remote <tt>TransportAddress</tt> to
|
* <tt>TransportAddress</tt> and and a remote <tt>TransportAddress</tt> to
|
||||||
@ -77,16 +110,6 @@ class NetAccessManager
|
|||||||
tcpConnectors
|
tcpConnectors
|
||||||
= new HashMap<>();
|
= new HashMap<>();
|
||||||
|
|
||||||
/**
|
|
||||||
* A synchronized FIFO where incoming messages are stocked for processing.
|
|
||||||
*/
|
|
||||||
private final BlockingQueue<RawMessage> messageQueue = new LinkedBlockingQueue<>();
|
|
||||||
|
|
||||||
/**
|
|
||||||
* A thread pool of message processors.
|
|
||||||
*/
|
|
||||||
private final Vector<MessageProcessor> messageProcessors = new Vector<>();
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The instance that should be notified when an incoming message has been
|
* The instance that should be notified when an incoming message has been
|
||||||
* processed and ready for delivery
|
* processed and ready for delivery
|
||||||
@ -105,17 +128,34 @@ class NetAccessManager
|
|||||||
*/
|
*/
|
||||||
private final ChannelDataEventHandler channelDataEventHandler;
|
private final ChannelDataEventHandler channelDataEventHandler;
|
||||||
|
|
||||||
/**
|
|
||||||
* The size of the thread pool to start with.
|
|
||||||
*/
|
|
||||||
private int initialThreadPoolSize = StunStack.DEFAULT_THREAD_POOL_SIZE;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The <tt>StunStack</tt> which has created this instance, is its owner and
|
* The <tt>StunStack</tt> which has created this instance, is its owner and
|
||||||
* is the handler that incoming message requests should be passed to.
|
* is the handler that incoming message requests should be passed to.
|
||||||
*/
|
*/
|
||||||
private final StunStack stunStack;
|
private final StunStack stunStack;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Indicates if this <tt>NetAccessManager</tt> is stopped
|
||||||
|
*/
|
||||||
|
private final AtomicBoolean isStopped = new AtomicBoolean(false);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Callback to be called when scheduled <tt>MessageProcessingTask</tt>
|
||||||
|
* completes processing it's <tt>RawMessage</tt>.
|
||||||
|
*/
|
||||||
|
private final Consumer<MessageProcessingTask> onRawMessageProcessed
|
||||||
|
= messageProcessingTask -> {
|
||||||
|
|
||||||
|
activeTasks.remove(messageProcessingTask);
|
||||||
|
|
||||||
|
final boolean isAdded = taskPool.offer(messageProcessingTask);
|
||||||
|
if (!isAdded && logger.isLoggable(Level.FINEST))
|
||||||
|
{
|
||||||
|
logger.finest("Dropping MessageProcessingTask for "
|
||||||
|
+ this + " because pool is full, max pool size is " + TASK_POOL_SIZE);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Constructs a NetAccessManager.
|
* Constructs a NetAccessManager.
|
||||||
*
|
*
|
||||||
@ -150,7 +190,6 @@ class NetAccessManager
|
|||||||
this.messageEventHandler = stunStack;
|
this.messageEventHandler = stunStack;
|
||||||
this.peerUdpMessageEventHandler = peerUdpMessageEventHandler;
|
this.peerUdpMessageEventHandler = peerUdpMessageEventHandler;
|
||||||
this.channelDataEventHandler = channelDataEventHandler;
|
this.channelDataEventHandler = channelDataEventHandler;
|
||||||
initThreadPool();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -196,17 +235,6 @@ class NetAccessManager
|
|||||||
return channelDataEventHandler;
|
return channelDataEventHandler;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Gets the <tt>BlockingQueue</tt> of this <tt>NetAccessManager</tt> in which
|
|
||||||
* incoming messages are stocked for processing.
|
|
||||||
*
|
|
||||||
* @return the <tt>BlockingQueue</tt> of this <tt>NetAccessManager</tt> in
|
|
||||||
* which incoming messages are stocked for processing
|
|
||||||
*/
|
|
||||||
BlockingQueue<RawMessage> getMessageQueue()
|
|
||||||
{
|
|
||||||
return messageQueue;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Gets the <tt>StunStack</tt> which has created this instance and is its
|
* Gets the <tt>StunStack</tt> which has created this instance and is its
|
||||||
@ -228,6 +256,12 @@ class NetAccessManager
|
|||||||
@Override
|
@Override
|
||||||
public void handleError(String message, Throwable error)
|
public void handleError(String message, Throwable error)
|
||||||
{
|
{
|
||||||
|
if (isStopped.get())
|
||||||
|
{
|
||||||
|
logger.log(Level.WARNING,
|
||||||
|
"Got error when stopped, ignoring: " + message, error);
|
||||||
|
return;
|
||||||
|
}
|
||||||
/**
|
/**
|
||||||
* apart from logging, i am not sure what else we could do here.
|
* apart from logging, i am not sure what else we could do here.
|
||||||
*/
|
*/
|
||||||
@ -249,6 +283,13 @@ class NetAccessManager
|
|||||||
String message,
|
String message,
|
||||||
Throwable error)
|
Throwable error)
|
||||||
{
|
{
|
||||||
|
if (isStopped.get())
|
||||||
|
{
|
||||||
|
logger.log(Level.WARNING,
|
||||||
|
"Got fatal error when stopped, ignoring: " + message, error);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
if (callingThread instanceof Connector)
|
if (callingThread instanceof Connector)
|
||||||
{
|
{
|
||||||
Connector connector = (Connector)callingThread;
|
Connector connector = (Connector)callingThread;
|
||||||
@ -260,25 +301,15 @@ class NetAccessManager
|
|||||||
{
|
{
|
||||||
logger.log(Level.WARNING, "Removing connector:" + connector,
|
logger.log(Level.WARNING, "Removing connector:" + connector,
|
||||||
error);
|
error);
|
||||||
} else if (logger.isLoggable(Level.FINE))
|
}
|
||||||
|
else if (logger.isLoggable(Level.FINE))
|
||||||
{
|
{
|
||||||
logger.fine("Removing connector " + connector);
|
logger.fine("Removing connector " + connector);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
else if( callingThread instanceof MessageProcessor )
|
else
|
||||||
{
|
{
|
||||||
MessageProcessor mp = (MessageProcessor)callingThread;
|
logger.log(Level.SEVERE, message, error);
|
||||||
logger.log( Level.WARNING, "A message processor has unexpectedly "
|
|
||||||
+ "stopped. AP:" + mp, error);
|
|
||||||
|
|
||||||
//make sure the guy's dead.
|
|
||||||
mp.stop();
|
|
||||||
messageProcessors.remove(mp);
|
|
||||||
|
|
||||||
mp = new MessageProcessor(this);
|
|
||||||
mp.start();
|
|
||||||
logger.fine("A message processor has been relaunched because "
|
|
||||||
+ "of an error.");
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -349,7 +380,11 @@ class NetAccessManager
|
|||||||
if (!connectorsForLocalAddress.containsKey(remoteAddress))
|
if (!connectorsForLocalAddress.containsKey(remoteAddress))
|
||||||
{
|
{
|
||||||
Connector connector
|
Connector connector
|
||||||
= new Connector(socket, remoteAddress, messageQueue, this);
|
= new Connector(
|
||||||
|
socket,
|
||||||
|
remoteAddress,
|
||||||
|
this::onIncomingRawMessage,
|
||||||
|
this);
|
||||||
|
|
||||||
connectorsForLocalAddress.put(remoteAddress, connector);
|
connectorsForLocalAddress.put(remoteAddress, connector);
|
||||||
connector.start();
|
connector.start();
|
||||||
@ -405,15 +440,24 @@ class NetAccessManager
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Stops <tt>NetAccessManager</tt> and all of its <tt>MessageProcessor</tt>.
|
* Stops <tt>NetAccessManager</tt> and all of its active
|
||||||
|
* <tt>MessageProcessingTask</tt>.
|
||||||
*/
|
*/
|
||||||
@SuppressWarnings("unchecked")
|
@SuppressWarnings("unchecked")
|
||||||
public void stop()
|
public void stop()
|
||||||
{
|
{
|
||||||
for(MessageProcessor mp : messageProcessors)
|
// Mark NetAccessManager as stopped, it will immediately result in
|
||||||
|
// ignoring of all concurrent requests to handle messages
|
||||||
|
isStopped.set(true);
|
||||||
|
|
||||||
|
// no item can be added to {@link #activeTasks} when
|
||||||
|
// NetAccessManager is stopped, so it is safe to iterate without
|
||||||
|
// removing item in-place.
|
||||||
|
for (MessageProcessingTask messageProcessingTask : activeTasks)
|
||||||
{
|
{
|
||||||
mp.stop();
|
messageProcessingTask.cancel();
|
||||||
}
|
}
|
||||||
|
activeTasks.clear();
|
||||||
|
|
||||||
for (Object o : new Object[]{udpConnectors, tcpConnectors})
|
for (Object o : new Object[]{udpConnectors, tcpConnectors})
|
||||||
{
|
{
|
||||||
@ -475,81 +519,43 @@ class NetAccessManager
|
|||||||
return connector;
|
return connector;
|
||||||
}
|
}
|
||||||
|
|
||||||
//---------------thread pool implementation --------------------------------
|
|
||||||
/**
|
/**
|
||||||
* Adjusts the number of concurrently running MessageProcessors.
|
* Enqueues incoming {@link RawMessage} for asynchronous
|
||||||
* If the number is smaller or bigger than the number of threads
|
* processing by {@link #messageProcessingExecutor}
|
||||||
* currently running, then message processors are created/deleted so that
|
* @param message <tt>RawMessage</tt> to process
|
||||||
* their count matches the new value.
|
|
||||||
*
|
|
||||||
* @param threadPoolSize the number of MessageProcessors that should be
|
|
||||||
* running concurrently
|
|
||||||
* @throws IllegalArgumentException if threadPoolSize is not a valid size.
|
|
||||||
*/
|
*/
|
||||||
void setThreadPoolSize(int threadPoolSize)
|
private void onIncomingRawMessage(final RawMessage message)
|
||||||
throws IllegalArgumentException
|
|
||||||
{
|
{
|
||||||
if(threadPoolSize < 1)
|
if (isStopped.get())
|
||||||
{
|
{
|
||||||
throw new IllegalArgumentException(
|
logger.fine("Got RawMessage when stopped, ignore it.");
|
||||||
threadPoolSize + " is not a legal thread pool size value.");
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
//if we are not running just record the size
|
MessageProcessingTask messageProcessingTask
|
||||||
//so that we could init later.
|
= taskPool.poll();
|
||||||
if(messageProcessors.size() < threadPoolSize)
|
if (messageProcessingTask == null)
|
||||||
{
|
{
|
||||||
//create additional processors
|
messageProcessingTask
|
||||||
fillUpThreadPool(threadPoolSize);
|
= new MessageProcessingTask(this);
|
||||||
|
if (logger.isLoggable(Level.FINEST))
|
||||||
|
{
|
||||||
|
logger.finest("Allocated new MessageProcessingTask for "
|
||||||
|
+ this + " due to absence of available pooled instances");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
//delete extra processors
|
messageProcessingTask.resetState();
|
||||||
shrinkThreadPool(threadPoolSize);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
messageProcessingTask.setMessage(message, onRawMessageProcessed);
|
||||||
* Fills the thread pool with the initially specified number of message
|
|
||||||
* processors.
|
|
||||||
*/
|
|
||||||
private void initThreadPool()
|
|
||||||
{
|
|
||||||
//create additional processors
|
|
||||||
fillUpThreadPool(initialThreadPoolSize);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
activeTasks.add(messageProcessingTask);
|
||||||
* Starts all message processors
|
|
||||||
*
|
|
||||||
* @param newSize the new thread pool size
|
|
||||||
*/
|
|
||||||
private void fillUpThreadPool(int newSize)
|
|
||||||
{
|
|
||||||
//make sure we don't resize more than once
|
|
||||||
messageProcessors.ensureCapacity(newSize);
|
|
||||||
|
|
||||||
for (int i = messageProcessors.size(); i < newSize; i++)
|
// Use overload which does not return Future object to avoid
|
||||||
{
|
// unnecessary allocation
|
||||||
MessageProcessor mp = new MessageProcessor(this);
|
messageProcessingExecutor.execute(messageProcessingTask);
|
||||||
|
|
||||||
messageProcessors.add(mp);
|
|
||||||
mp.start();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Stops message processors until processors count equals newSize.
|
|
||||||
*
|
|
||||||
* @param newSize the new thread pool size
|
|
||||||
*/
|
|
||||||
private void shrinkThreadPool(int newSize)
|
|
||||||
{
|
|
||||||
while(messageProcessors.size() > newSize)
|
|
||||||
{
|
|
||||||
MessageProcessor mp = messageProcessors.remove(0);
|
|
||||||
mp.stop();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
//--------------- SENDING MESSAGES -----------------------------------------
|
//--------------- SENDING MESSAGES -----------------------------------------
|
||||||
@ -622,10 +628,17 @@ class NetAccessManager
|
|||||||
Connector ap = getConnector(srcAddr, remoteAddr);
|
Connector ap = getConnector(srcAddr, remoteAddr);
|
||||||
if (ap == null)
|
if (ap == null)
|
||||||
{
|
{
|
||||||
throw new IllegalArgumentException(
|
throw new SocketNotFoundException("No socket found for " + srcAddr + "->" + remoteAddr);
|
||||||
"No socket found for " + srcAddr + "->" + remoteAddr);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
ap.sendMessage(bytes, remoteAddr);
|
ap.sendMessage(bytes, remoteAddr);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public class SocketNotFoundException extends IllegalArgumentException
|
||||||
|
{
|
||||||
|
private SocketNotFoundException(String message)
|
||||||
|
{
|
||||||
|
super(message);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -17,13 +17,16 @@
|
|||||||
*/
|
*/
|
||||||
package org.ice4j.stack;
|
package org.ice4j.stack;
|
||||||
|
|
||||||
import java.io.*;
|
|
||||||
import java.util.concurrent.*;
|
|
||||||
import java.util.concurrent.locks.*;
|
|
||||||
import java.util.logging.*;
|
|
||||||
|
|
||||||
import org.ice4j.*;
|
import org.ice4j.*;
|
||||||
import org.ice4j.message.*;
|
import org.ice4j.message.*;
|
||||||
|
import org.ice4j.util.PeriodicRunnable;
|
||||||
|
import org.jitsi.utils.concurrent.*;
|
||||||
|
|
||||||
|
import java.io.*;
|
||||||
|
import java.time.*;
|
||||||
|
import java.util.concurrent.*;
|
||||||
|
import java.util.concurrent.atomic.*;
|
||||||
|
import java.util.logging.*;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The {@code StunClientTransaction} class retransmits requests as specified by
|
* The {@code StunClientTransaction} class retransmits requests as specified by
|
||||||
@ -46,13 +49,12 @@ import org.ice4j.message.*;
|
|||||||
* @author Lyubomir Marinov
|
* @author Lyubomir Marinov
|
||||||
*/
|
*/
|
||||||
public class StunClientTransaction
|
public class StunClientTransaction
|
||||||
implements Runnable
|
|
||||||
{
|
{
|
||||||
/**
|
/**
|
||||||
* Our class logger.
|
* Our class logger.
|
||||||
*/
|
*/
|
||||||
private static final Logger logger
|
private static final java.util.logging.Logger logger
|
||||||
= Logger.getLogger(StunClientTransaction.class.getName());
|
= java.util.logging.Logger.getLogger(StunClientTransaction.class.getName());
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The number of times to retransmit a request if no explicit value has been
|
* The number of times to retransmit a request if no explicit value has been
|
||||||
@ -74,43 +76,21 @@ public class StunClientTransaction
|
|||||||
public static final int DEFAULT_ORIGINAL_WAIT_INTERVAL = 100;
|
public static final int DEFAULT_ORIGINAL_WAIT_INTERVAL = 100;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The pool of <tt>Thread</tt>s which retransmit
|
* The pool of <tt>Thread</tt>s which schedules retransmission of
|
||||||
* <tt>StunClientTransaction</tt>s.
|
* <tt>StunClientTransaction</tt>s.
|
||||||
*/
|
*/
|
||||||
private static final ExecutorService retransmissionThreadPool
|
private static final ScheduledExecutorService retransmissionTimer
|
||||||
= Executors.newCachedThreadPool(
|
= ExecutorFactory.createSingleThreadScheduledExecutor(
|
||||||
new ThreadFactory()
|
"ice4j.StunClientTransaction-timer-", 60, TimeUnit.SECONDS);
|
||||||
{
|
|
||||||
/**
|
/**
|
||||||
* The default {@code ThreadFactory} implementation which is
|
* The pool of <tt>Thread</tt>s which retransmits
|
||||||
* augmented by this instance to create daemon
|
* <tt>StunClientTransaction</tt>s.
|
||||||
* {@code Thread}s.
|
|
||||||
*/
|
*/
|
||||||
private final ThreadFactory defaultThreadFactory
|
private static final ExecutorService retransmissionExecutor
|
||||||
= Executors.defaultThreadFactory();
|
= ExecutorFactory.createCachedThreadPool(
|
||||||
|
"ice4j.StunClientTransaction-executor-");
|
||||||
|
|
||||||
@Override
|
|
||||||
public Thread newThread(Runnable r)
|
|
||||||
{
|
|
||||||
Thread t = defaultThreadFactory.newThread(r);
|
|
||||||
|
|
||||||
if (t != null)
|
|
||||||
{
|
|
||||||
t.setDaemon(true);
|
|
||||||
|
|
||||||
// Additionally, make it known through the name of
|
|
||||||
// the Thread that it is associated with the
|
|
||||||
// StunClientTransaction class for
|
|
||||||
// debugging/informational purposes.
|
|
||||||
String name = t.getName();
|
|
||||||
|
|
||||||
if (name == null)
|
|
||||||
name = "";
|
|
||||||
t.setName("StunClientTransaction-" + name);
|
|
||||||
}
|
|
||||||
return t;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Maximum number of retransmissions. Once this number is reached and if no
|
* Maximum number of retransmissions. Once this number is reached and if no
|
||||||
@ -166,25 +146,12 @@ public class StunClientTransaction
|
|||||||
/**
|
/**
|
||||||
* Determines whether the transaction is active or not.
|
* Determines whether the transaction is active or not.
|
||||||
*/
|
*/
|
||||||
private boolean cancelled = false;
|
private final AtomicBoolean cancelled = new AtomicBoolean(false);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The <tt>Lock</tt> which synchronizes the access to the state of this
|
* A transaction request retransmitter
|
||||||
* instance. Introduced along with {@link #lockCondition} in order to allow
|
|
||||||
* the invocation of {@link #cancel(boolean)} without a requirement to
|
|
||||||
* acquire the synchronization root. Otherwise, callers of
|
|
||||||
* <tt>cancel(boolean)</tt> may (and have be reported multiple times to)
|
|
||||||
* fall into a deadlock merely because they want to cancel this
|
|
||||||
* <tt>StunClientTransaction</tt>.
|
|
||||||
*/
|
*/
|
||||||
private final Lock lock = new ReentrantLock();
|
private final Retransmitter retransmitter;
|
||||||
|
|
||||||
/**
|
|
||||||
* The <tt>Condition</tt> of {@link #lock} which this instance uses to wait
|
|
||||||
* for either the next retransmission interval or the cancellation of this
|
|
||||||
* <tt>StunClientTransaction</tt>.
|
|
||||||
*/
|
|
||||||
private final Condition lockCondition = lock.newCondition();
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Creates a client transaction.
|
* Creates a client transaction.
|
||||||
@ -240,6 +207,8 @@ public class StunClientTransaction
|
|||||||
|
|
||||||
initTransactionConfiguration();
|
initTransactionConfiguration();
|
||||||
|
|
||||||
|
retransmitter = new Retransmitter(); // create it here to support 'originalWaitInterval' configuration
|
||||||
|
|
||||||
this.transactionID = transactionID;
|
this.transactionID = transactionID;
|
||||||
|
|
||||||
try
|
try
|
||||||
@ -256,102 +225,6 @@ public class StunClientTransaction
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Implements the retransmissions algorithm. Retransmits the request
|
|
||||||
* starting with an interval of 100ms, doubling every retransmit until the
|
|
||||||
* interval reaches 1.6s. Retransmissions continue with intervals of 1.6s
|
|
||||||
* until a response is received, or a total of 7 requests have been sent.
|
|
||||||
* If no response is received by 1.6 seconds after the last request has been
|
|
||||||
* sent, we consider the transaction to have failed.
|
|
||||||
* <p>
|
|
||||||
* The method acquires {@link #lock} and invokes {@link #runLocked()}.
|
|
||||||
* </p>
|
|
||||||
*/
|
|
||||||
@Override
|
|
||||||
public void run()
|
|
||||||
{
|
|
||||||
lock.lock();
|
|
||||||
try
|
|
||||||
{
|
|
||||||
runLocked();
|
|
||||||
}
|
|
||||||
finally
|
|
||||||
{
|
|
||||||
lock.unlock();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Implements the retransmissions algorithm. Retransmits the request
|
|
||||||
* starting with an interval of 100ms, doubling every retransmit until the
|
|
||||||
* interval reaches 1.6s. Retransmissions continue with intervals of 1.6s
|
|
||||||
* until a response is received, or a total of 7 requests have been sent.
|
|
||||||
* If no response is received by 1.6 seconds after the last request has been
|
|
||||||
* sent, we consider the transaction to have failed.
|
|
||||||
* <p>
|
|
||||||
* The method assumes that the current thread has already acquired
|
|
||||||
* {@link #lock}.
|
|
||||||
* </p>
|
|
||||||
*/
|
|
||||||
private void runLocked()
|
|
||||||
{
|
|
||||||
// Indicates how many times we have retransmitted so far.
|
|
||||||
int retransmissionCounter = 0;
|
|
||||||
// How much did we wait after our last retransmission?
|
|
||||||
int nextWaitInterval = originalWaitInterval;
|
|
||||||
|
|
||||||
for (retransmissionCounter = 0;
|
|
||||||
retransmissionCounter < maxRetransmissions;
|
|
||||||
retransmissionCounter ++)
|
|
||||||
{
|
|
||||||
waitFor(nextWaitInterval);
|
|
||||||
|
|
||||||
//did someone tell us to get lost?
|
|
||||||
if(cancelled)
|
|
||||||
return;
|
|
||||||
|
|
||||||
int curWaitInterval = nextWaitInterval;
|
|
||||||
if(nextWaitInterval < maxWaitInterval)
|
|
||||||
nextWaitInterval *= 2;
|
|
||||||
|
|
||||||
try
|
|
||||||
{
|
|
||||||
logger.fine(
|
|
||||||
"retrying STUN tid " + transactionID + " from "
|
|
||||||
+ localAddress + " to " + requestDestination
|
|
||||||
+ " waited " + curWaitInterval + " ms retrans "
|
|
||||||
+ (retransmissionCounter + 1) + " of "
|
|
||||||
+ maxRetransmissions);
|
|
||||||
sendRequest0();
|
|
||||||
}
|
|
||||||
catch (Exception ex)
|
|
||||||
{
|
|
||||||
//I wonder whether we should notify anyone that a retransmission
|
|
||||||
// has failed
|
|
||||||
logger.log(
|
|
||||||
Level.INFO,
|
|
||||||
"A client tran retransmission failed",
|
|
||||||
ex);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
//before stating that a transaction has timeout-ed we should first wait
|
|
||||||
//for a reception of the response
|
|
||||||
if(nextWaitInterval < maxWaitInterval)
|
|
||||||
nextWaitInterval *= 2;
|
|
||||||
|
|
||||||
waitFor(nextWaitInterval);
|
|
||||||
|
|
||||||
if(cancelled)
|
|
||||||
return;
|
|
||||||
|
|
||||||
stackCallback.removeClientTransaction(this);
|
|
||||||
responseCollector.processTimeout(
|
|
||||||
new StunTimeoutEvent(
|
|
||||||
stackCallback,
|
|
||||||
this.request, getLocalAddress(), transactionID));
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Sends the request and schedules the first retransmission for after
|
* Sends the request and schedules the first retransmission for after
|
||||||
* {@link #originalWaitInterval} and thus starts the retransmission
|
* {@link #originalWaitInterval} and thus starts the retransmission
|
||||||
@ -371,7 +244,7 @@ public class StunClientTransaction
|
|||||||
+ localAddress + " to " + requestDestination);
|
+ localAddress + " to " + requestDestination);
|
||||||
sendRequest0();
|
sendRequest0();
|
||||||
|
|
||||||
retransmissionThreadPool.execute(this);
|
this.retransmitter.schedule();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -385,7 +258,7 @@ public class StunClientTransaction
|
|||||||
private void sendRequest0()
|
private void sendRequest0()
|
||||||
throws IllegalArgumentException, IOException
|
throws IllegalArgumentException, IOException
|
||||||
{
|
{
|
||||||
if(cancelled)
|
if (cancelled.get())
|
||||||
{
|
{
|
||||||
logger.finer("Trying to resend a cancelled transaction.");
|
logger.finer("Trying to resend a cancelled transaction.");
|
||||||
}
|
}
|
||||||
@ -408,74 +281,18 @@ public class StunClientTransaction
|
|||||||
return this.request;
|
return this.request;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Waits until next retransmission is due or until the transaction is
|
|
||||||
* cancelled (whichever comes first).
|
|
||||||
*
|
|
||||||
* @param millis the number of milliseconds to wait for.
|
|
||||||
*/
|
|
||||||
void waitFor(long millis)
|
|
||||||
{
|
|
||||||
lock.lock();
|
|
||||||
try
|
|
||||||
{
|
|
||||||
lockCondition.await(millis, TimeUnit.MILLISECONDS);
|
|
||||||
}
|
|
||||||
catch (InterruptedException ex)
|
|
||||||
{
|
|
||||||
throw new RuntimeException(ex);
|
|
||||||
}
|
|
||||||
finally
|
|
||||||
{
|
|
||||||
lock.unlock();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Cancels the transaction. Once this method is called the transaction is
|
|
||||||
* considered terminated and will stop retransmissions.
|
|
||||||
*
|
|
||||||
* @param waitForResponse indicates whether we should wait for the current
|
|
||||||
* RTO to expire before ending the transaction or immediately terminate.
|
|
||||||
*/
|
|
||||||
void cancel(boolean waitForResponse)
|
|
||||||
{
|
|
||||||
// XXX The cancelled field is initialized to false and then the one and
|
|
||||||
// only write access to it is here to set it to true. The rest of the
|
|
||||||
// code just checks whether it has become true. Consequently, there
|
|
||||||
// shouldn't be a problem if the set is outside a synchronized block.
|
|
||||||
// However, it being outside a synchronized block will decrease the risk
|
|
||||||
// of deadlocks.
|
|
||||||
cancelled = true;
|
|
||||||
|
|
||||||
if(!waitForResponse)
|
|
||||||
{
|
|
||||||
// Try to interrupt #waitFor(long) if possible. But don't risk a
|
|
||||||
// deadlock. It is not a problem if it is not possible to interrupt
|
|
||||||
// #waitFor(long) here because it will complete in finite time and
|
|
||||||
// this StunClientTransaction will eventually notice that it has
|
|
||||||
// been cancelled.
|
|
||||||
if (lock.tryLock())
|
|
||||||
{
|
|
||||||
try
|
|
||||||
{
|
|
||||||
lockCondition.signal();
|
|
||||||
}
|
|
||||||
finally
|
|
||||||
{
|
|
||||||
lock.unlock();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Cancels the transaction. Once this method is called the transaction is
|
* Cancels the transaction. Once this method is called the transaction is
|
||||||
* considered terminated and will stop retransmissions.
|
* considered terminated and will stop retransmissions.
|
||||||
*/
|
*/
|
||||||
void cancel()
|
void cancel()
|
||||||
{
|
{
|
||||||
cancel(false);
|
// The cancelled field is initialized to false and then the one and
|
||||||
|
// only write access to it is here to set it to true. The rest of the
|
||||||
|
// code just checks whether it has become true.
|
||||||
|
cancelled.set(true);
|
||||||
|
|
||||||
|
this.retransmitter.cancel();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -485,15 +302,14 @@ public class StunClientTransaction
|
|||||||
* @param evt the event that contains the newly received message
|
* @param evt the event that contains the newly received message
|
||||||
*/
|
*/
|
||||||
public void handleResponse(StunMessageEvent evt)
|
public void handleResponse(StunMessageEvent evt)
|
||||||
{
|
|
||||||
lock.lock();
|
|
||||||
try
|
|
||||||
{
|
{
|
||||||
TransactionID transactionID = getTransactionID();
|
TransactionID transactionID = getTransactionID();
|
||||||
|
|
||||||
logger.log(Level.FINE, "handleResponse tid " + transactionID);
|
logger.fine("handleResponse tid " + transactionID);
|
||||||
if (!Boolean.getBoolean(StackProperties.KEEP_CRANS_AFTER_A_RESPONSE))
|
if (!Boolean.getBoolean(StackProperties.KEEP_CRANS_AFTER_A_RESPONSE))
|
||||||
|
{
|
||||||
cancel();
|
cancel();
|
||||||
|
}
|
||||||
|
|
||||||
responseCollector.processResponse(
|
responseCollector.processResponse(
|
||||||
new StunResponseEvent(
|
new StunResponseEvent(
|
||||||
@ -503,11 +319,6 @@ public class StunClientTransaction
|
|||||||
request,
|
request,
|
||||||
transactionID));
|
transactionID));
|
||||||
}
|
}
|
||||||
finally
|
|
||||||
{
|
|
||||||
lock.unlock();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Returns the ID of the current transaction.
|
* Returns the ID of the current transaction.
|
||||||
@ -608,4 +419,81 @@ public class StunClientTransaction
|
|||||||
{
|
{
|
||||||
return requestDestination;
|
return requestDestination;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Implements the retransmissions algorithm. Retransmits the request
|
||||||
|
* starting with an interval of 100ms, doubling every retransmit until the
|
||||||
|
* interval reaches 1.6s. Retransmissions continue with intervals of 1.6s
|
||||||
|
* until a response is received, or a total of 7 requests have been sent.
|
||||||
|
* If no response is received by 1.6 seconds after the last request has been
|
||||||
|
* sent, we consider the transaction to have failed.
|
||||||
|
*/
|
||||||
|
private final class Retransmitter extends PeriodicRunnable
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Current number of retransmission attempts
|
||||||
|
*/
|
||||||
|
private int retransmissionCounter = 0;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Delay before attempting next retransmission
|
||||||
|
*/
|
||||||
|
private int nextRetransmissionDelay = originalWaitInterval;
|
||||||
|
|
||||||
|
protected Retransmitter()
|
||||||
|
{
|
||||||
|
super(retransmissionTimer, retransmissionExecutor);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected Duration getDelayUntilNextRun()
|
||||||
|
{
|
||||||
|
return Duration.ofMillis(nextRetransmissionDelay);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected void run()
|
||||||
|
{
|
||||||
|
retransmissionCounter++;
|
||||||
|
|
||||||
|
int curWaitInterval = nextRetransmissionDelay;
|
||||||
|
nextRetransmissionDelay
|
||||||
|
= Math.min(maxWaitInterval, 2 * nextRetransmissionDelay);
|
||||||
|
|
||||||
|
if (retransmissionCounter <= maxRetransmissions)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
logger.fine(
|
||||||
|
"retrying STUN tid " + transactionID + " from "
|
||||||
|
+ localAddress + " to " + requestDestination
|
||||||
|
+ " waited " + curWaitInterval + " ms retrans "
|
||||||
|
+ retransmissionCounter + " of "
|
||||||
|
+ maxRetransmissions);
|
||||||
|
sendRequest0();
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
//I wonder whether we should notify anyone that a retransmission
|
||||||
|
// has failed
|
||||||
|
logger.log(
|
||||||
|
Level.INFO,
|
||||||
|
"A client tran retransmission failed",
|
||||||
|
ex);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
stackCallback.removeClientTransaction(
|
||||||
|
StunClientTransaction.this);
|
||||||
|
|
||||||
|
responseCollector.processTimeout(
|
||||||
|
new StunTimeoutEvent(
|
||||||
|
stackCallback,
|
||||||
|
getRequest(), getLocalAddress(), getTransactionID()));
|
||||||
|
|
||||||
|
nextRetransmissionDelay = -1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -165,7 +165,8 @@ public class StunServerTransaction
|
|||||||
IOException,
|
IOException,
|
||||||
IllegalArgumentException
|
IllegalArgumentException
|
||||||
{
|
{
|
||||||
if(!isRetransmitting){
|
if (!isRetransmitting)
|
||||||
|
{
|
||||||
this.response = response;
|
this.response = response;
|
||||||
//the transaction id might already have been set, but its our job
|
//the transaction id might already have been set, but its our job
|
||||||
//to make sure of that
|
//to make sure of that
|
||||||
|
|||||||
@ -17,19 +17,20 @@
|
|||||||
*/
|
*/
|
||||||
package org.ice4j.stack;
|
package org.ice4j.stack;
|
||||||
|
|
||||||
import java.io.*;
|
|
||||||
import java.net.*;
|
|
||||||
import java.security.*;
|
|
||||||
import java.util.*;
|
|
||||||
import java.util.logging.*;
|
|
||||||
|
|
||||||
import javax.crypto.*;
|
|
||||||
|
|
||||||
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.socket.*;
|
import org.ice4j.socket.*;
|
||||||
|
import org.jitsi.utils.concurrent.*;
|
||||||
|
|
||||||
|
import javax.crypto.*;
|
||||||
|
import java.io.*;
|
||||||
|
import java.net.*;
|
||||||
|
import java.security.*;
|
||||||
|
import java.util.*;
|
||||||
|
import java.util.concurrent.*;
|
||||||
|
import java.util.logging.*;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The entry point to the Stun4J stack. The class is used to start, stop and
|
* The entry point to the Stun4J stack. The class is used to start, stop and
|
||||||
@ -42,18 +43,12 @@ import org.ice4j.socket.*;
|
|||||||
public class StunStack
|
public class StunStack
|
||||||
implements MessageEventHandler
|
implements MessageEventHandler
|
||||||
{
|
{
|
||||||
|
|
||||||
/**
|
|
||||||
* The number of threads to split our flow in.
|
|
||||||
*/
|
|
||||||
public static final int DEFAULT_THREAD_POOL_SIZE = 3;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The <tt>Logger</tt> used by the <tt>StunStack</tt> class and its
|
* The <tt>Logger</tt> used by the <tt>StunStack</tt> class and its
|
||||||
* instances for logging output.
|
* instances for logging output.
|
||||||
*/
|
*/
|
||||||
private static final Logger logger
|
private static final java.util.logging.Logger logger
|
||||||
= Logger.getLogger(StunStack.class.getName());
|
= java.util.logging.Logger.getLogger(StunStack.class.getName());
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The indicator which determines whether
|
* The indicator which determines whether
|
||||||
@ -64,6 +59,14 @@ public class StunStack
|
|||||||
*/
|
*/
|
||||||
private static Mac mac;
|
private static Mac mac;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The ScheduledExecutorService to execute StunStack scheduled tasks,
|
||||||
|
* in particular - expired server transactions collector.
|
||||||
|
*/
|
||||||
|
private static final ScheduledExecutorService tasksScheduler
|
||||||
|
= ExecutorFactory.createSingleThreadScheduledExecutor(
|
||||||
|
"ice4j.StunStack-", 60, TimeUnit.SECONDS);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Our network gateway.
|
* Our network gateway.
|
||||||
*/
|
*/
|
||||||
@ -84,11 +87,12 @@ public class StunStack
|
|||||||
= new Hashtable<>();
|
= new Hashtable<>();
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The <tt>Thread</tt> which expires the <tt>StunServerTransaction</tt>s of
|
* The <tt>ExpiredServerTransactionsCollector</tt> which expires
|
||||||
* this <tt>StunStack</tt> and removes them from
|
* the <tt>StunServerTransaction</tt>s of this <tt>StunStack</tt> and
|
||||||
* {@link #serverTransactions}.
|
* removes them from {@link #serverTransactions}.
|
||||||
*/
|
*/
|
||||||
private Thread serverTransactionExpireThread;
|
private ExpiredServerTransactionsCollector expiredTransactionsCollector
|
||||||
|
= new ExpiredServerTransactionsCollector();
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Currently open server transactions. The vector contains transaction ids
|
* Currently open server transactions. The vector contains transaction ids
|
||||||
@ -108,18 +112,6 @@ public class StunStack
|
|||||||
*/
|
*/
|
||||||
private static PacketLogger packetLogger;
|
private static PacketLogger packetLogger;
|
||||||
|
|
||||||
/**
|
|
||||||
* Sets the number of Message processors running in the same time.
|
|
||||||
*
|
|
||||||
* @param threadPoolSize the number of message process threads to run.
|
|
||||||
* @throws IllegalArgumentException if threadPoolSize is not a valid size.
|
|
||||||
*/
|
|
||||||
public void setThreadPoolSize(int threadPoolSize)
|
|
||||||
throws IllegalArgumentException
|
|
||||||
{
|
|
||||||
netAccessManager.setThreadPoolSize(threadPoolSize);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Creates and starts a Network Access Point (Connector) based on the
|
* Creates and starts a Network Access Point (Connector) based on the
|
||||||
* specified socket.
|
* specified socket.
|
||||||
@ -408,7 +400,6 @@ public class StunStack
|
|||||||
new NetAccessManager(this, peerUdpMessageEventHandler,
|
new NetAccessManager(this, peerUdpMessageEventHandler,
|
||||||
channelDataEventHandler);
|
channelDataEventHandler);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Initializes a new <tt>StunStack</tt> instance.
|
* Initializes a new <tt>StunStack</tt> instance.
|
||||||
*/
|
*/
|
||||||
@ -950,10 +941,7 @@ public class StunStack
|
|||||||
ev.getLocalAddress(),
|
ev.getLocalAddress(),
|
||||||
ev.getRemoteAddress());
|
ev.getRemoteAddress());
|
||||||
|
|
||||||
// if there is an OOM error here, it will lead to
|
// if there is an OOM error here, stop here right now
|
||||||
// NetAccessManager.handleFatalError that will stop the
|
|
||||||
// MessageProcessor thread and restart it that will lead again
|
|
||||||
// to an OOM error and so on... So stop here right now
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
sTran.start();
|
sTran.start();
|
||||||
@ -966,7 +954,7 @@ public class StunStack
|
|||||||
synchronized (serverTransactions)
|
synchronized (serverTransactions)
|
||||||
{
|
{
|
||||||
serverTransactions.put(serverTid, sTran);
|
serverTransactions.put(serverTid, sTran);
|
||||||
maybeStartServerTransactionExpireThread();
|
expiredTransactionsCollector.schedule();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -1106,6 +1094,8 @@ public class StunStack
|
|||||||
// serverTransactions
|
// serverTransactions
|
||||||
Collection<StunServerTransaction> serverTransactionsToExpire;
|
Collection<StunServerTransaction> serverTransactionsToExpire;
|
||||||
|
|
||||||
|
expiredTransactionsCollector.cancel();
|
||||||
|
|
||||||
synchronized (serverTransactions)
|
synchronized (serverTransactions)
|
||||||
{
|
{
|
||||||
serverTransactionsToExpire
|
serverTransactionsToExpire
|
||||||
@ -1442,135 +1432,6 @@ public class StunStack
|
|||||||
return packetLogger != null && packetLogger.isEnabled();
|
return packetLogger != null && packetLogger.isEnabled();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Initializes and starts {@link #serverTransactionExpireThread} if
|
|
||||||
* necessary.
|
|
||||||
*/
|
|
||||||
private void maybeStartServerTransactionExpireThread()
|
|
||||||
{
|
|
||||||
synchronized (serverTransactions)
|
|
||||||
{
|
|
||||||
if (!serverTransactions.isEmpty()
|
|
||||||
&& (serverTransactionExpireThread == null))
|
|
||||||
{
|
|
||||||
Thread t
|
|
||||||
= new Thread()
|
|
||||||
{
|
|
||||||
@Override
|
|
||||||
public void run()
|
|
||||||
{
|
|
||||||
runInServerTransactionExpireThread();
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
t.setDaemon(true);
|
|
||||||
t.setName(
|
|
||||||
getClass().getName()
|
|
||||||
+ ".serverTransactionExpireThread");
|
|
||||||
|
|
||||||
boolean started = false;
|
|
||||||
|
|
||||||
serverTransactionExpireThread = t;
|
|
||||||
try
|
|
||||||
{
|
|
||||||
t.start();
|
|
||||||
started = true;
|
|
||||||
}
|
|
||||||
finally
|
|
||||||
{
|
|
||||||
if (!started && (serverTransactionExpireThread == t))
|
|
||||||
serverTransactionExpireThread = null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Runs in {@link #serverTransactionExpireThread} and expires the
|
|
||||||
* <tt>StunServerTransaction</tt>s of this <tt>StunStack</tt> and removes
|
|
||||||
* them from {@link #serverTransactions}.
|
|
||||||
*/
|
|
||||||
private void runInServerTransactionExpireThread()
|
|
||||||
{
|
|
||||||
try
|
|
||||||
{
|
|
||||||
long idleStartTime = -1;
|
|
||||||
|
|
||||||
do
|
|
||||||
{
|
|
||||||
synchronized (serverTransactions)
|
|
||||||
{
|
|
||||||
try
|
|
||||||
{
|
|
||||||
serverTransactions.wait(StunServerTransaction.LIFETIME);
|
|
||||||
}
|
|
||||||
catch (InterruptedException ie)
|
|
||||||
{
|
|
||||||
}
|
|
||||||
|
|
||||||
/*
|
|
||||||
* Is the current Thread still designated to expire the
|
|
||||||
* StunServerTransactions of this StunStack?
|
|
||||||
*/
|
|
||||||
if (Thread.currentThread() != serverTransactionExpireThread)
|
|
||||||
break;
|
|
||||||
|
|
||||||
long now = System.currentTimeMillis();
|
|
||||||
|
|
||||||
/*
|
|
||||||
* Has the current Thread been idle long enough to merit
|
|
||||||
* disposing of it?
|
|
||||||
*/
|
|
||||||
if (serverTransactions.isEmpty())
|
|
||||||
{
|
|
||||||
if (idleStartTime == -1)
|
|
||||||
idleStartTime = now;
|
|
||||||
else if (now - idleStartTime > 60 * 1000)
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
// Expire the StunServerTransactions of this StunStack.
|
|
||||||
|
|
||||||
idleStartTime = -1;
|
|
||||||
|
|
||||||
for (Iterator<StunServerTransaction> i
|
|
||||||
= serverTransactions.values().iterator();
|
|
||||||
i.hasNext();)
|
|
||||||
{
|
|
||||||
StunServerTransaction serverTransaction = i.next();
|
|
||||||
|
|
||||||
if (serverTransaction == null)
|
|
||||||
{
|
|
||||||
i.remove();
|
|
||||||
}
|
|
||||||
else if (serverTransaction.isExpired(now))
|
|
||||||
{
|
|
||||||
i.remove();
|
|
||||||
serverTransaction.expire();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
while (true);
|
|
||||||
}
|
|
||||||
finally
|
|
||||||
{
|
|
||||||
synchronized (serverTransactions)
|
|
||||||
{
|
|
||||||
if (serverTransactionExpireThread == Thread.currentThread())
|
|
||||||
serverTransactionExpireThread = null;
|
|
||||||
/*
|
|
||||||
* If serverTransactionExpireThread dies unexpectedly and yet it
|
|
||||||
* is still necessary, resurrect it.
|
|
||||||
*/
|
|
||||||
if (serverTransactionExpireThread == null)
|
|
||||||
maybeStartServerTransactionExpireThread();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Returns the Error Response object with specified errorCode and
|
* Returns the Error Response object with specified errorCode and
|
||||||
* reasonPhrase corresponding to input type.
|
* reasonPhrase corresponding to input type.
|
||||||
@ -1639,4 +1500,117 @@ public class StunStack
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Class which performs periodic collection of expired transactions.
|
||||||
|
* It's execution is controlled outside by {@link #schedule()}
|
||||||
|
* and {@link #cancel()} methods. Whenever expired transactions collector
|
||||||
|
* is scheduled it does self reschedule with fixed delay
|
||||||
|
* of StunServerTransaction.LIFETIME_MILLIS,
|
||||||
|
* until {@link #serverTransactions} is empty, in that case it self-cancel
|
||||||
|
* further execution and need to be scheduled again when new item added
|
||||||
|
* to {@link #serverTransactions} container.
|
||||||
|
*/
|
||||||
|
private final class ExpiredServerTransactionsCollector
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Runnable which walks {@link #serverTransactions}, check if
|
||||||
|
* transaction is expired and if so - remove it
|
||||||
|
* from {@link #serverTransactions}.
|
||||||
|
* Self-cancels when {@link #serverTransactions} is empty
|
||||||
|
*/
|
||||||
|
private final Runnable collector = new Runnable()
|
||||||
|
{
|
||||||
|
@Override
|
||||||
|
public void run()
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
synchronized (serverTransactions)
|
||||||
|
{
|
||||||
|
final int transactionsBeforeCollection
|
||||||
|
= serverTransactions.size();
|
||||||
|
|
||||||
|
long now = System.currentTimeMillis();
|
||||||
|
|
||||||
|
for (Iterator<StunServerTransaction> i
|
||||||
|
= serverTransactions.values().iterator();
|
||||||
|
i.hasNext();)
|
||||||
|
{
|
||||||
|
StunServerTransaction serverTransaction = i.next();
|
||||||
|
|
||||||
|
if (serverTransaction == null)
|
||||||
|
{
|
||||||
|
i.remove();
|
||||||
|
}
|
||||||
|
else if (serverTransaction.isExpired(now))
|
||||||
|
{
|
||||||
|
i.remove();
|
||||||
|
serverTransaction.expire();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.fine("Non-expired server transactions "
|
||||||
|
+ "count " + serverTransactions.size()
|
||||||
|
+ ", transactions before collection "
|
||||||
|
+ transactionsBeforeCollection);
|
||||||
|
|
||||||
|
if (serverTransactions.isEmpty())
|
||||||
|
{
|
||||||
|
cancel();
|
||||||
|
logger.finest("Cancel expired collector "
|
||||||
|
+ "due to no more server transactions");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (Throwable t)
|
||||||
|
{
|
||||||
|
logger.log(Level.FINE,
|
||||||
|
"Failed to expire server transactions", t);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Scheduled execution of {@link #collector} runnable.
|
||||||
|
* Access synchronized via {@link #serverTransactions}.
|
||||||
|
*/
|
||||||
|
private ScheduledFuture<?> scheduledCollectorFuture;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Schedules repeated collector execution in background
|
||||||
|
* task executor. If collector is already scheduled - do nothing
|
||||||
|
*/
|
||||||
|
void schedule()
|
||||||
|
{
|
||||||
|
synchronized (serverTransactions)
|
||||||
|
{
|
||||||
|
if (scheduledCollectorFuture == null ||
|
||||||
|
scheduledCollectorFuture.isDone())
|
||||||
|
{
|
||||||
|
scheduledCollectorFuture
|
||||||
|
= tasksScheduler.scheduleWithFixedDelay(
|
||||||
|
collector,
|
||||||
|
StunServerTransaction.LIFETIME,
|
||||||
|
StunServerTransaction.LIFETIME,
|
||||||
|
TimeUnit.MILLISECONDS);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Cancels execution of scheduled expired transactions collector if
|
||||||
|
* it is running
|
||||||
|
*/
|
||||||
|
void cancel()
|
||||||
|
{
|
||||||
|
synchronized (serverTransactions)
|
||||||
|
{
|
||||||
|
if (scheduledCollectorFuture != null)
|
||||||
|
{
|
||||||
|
scheduledCollectorFuture.cancel(false);
|
||||||
|
scheduledCollectorFuture = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -409,7 +409,8 @@ public class NetworkConfigurationDiscoveryProcess
|
|||||||
{
|
{
|
||||||
Request request = MessageFactory.createBindingRequest();
|
Request request = MessageFactory.createBindingRequest();
|
||||||
|
|
||||||
/* ChangeRequestAttribute changeRequest = (ChangeRequestAttribute)request.getAttribute(Attribute.CHANGE_REQUEST); */
|
/* ChangeRequestAttribute changeRequest
|
||||||
|
= (ChangeRequestAttribute)request.getAttribute(Attribute.CHANGE_REQUEST); */
|
||||||
/* add a change request attribute */
|
/* add a change request attribute */
|
||||||
ChangeRequestAttribute changeRequest = AttributeFactory.createChangeRequestAttribute();
|
ChangeRequestAttribute changeRequest = AttributeFactory.createChangeRequestAttribute();
|
||||||
changeRequest.setChangeIpFlag(false);
|
changeRequest.setChangeIpFlag(false);
|
||||||
|
|||||||
@ -1,234 +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.util;
|
|
||||||
|
|
||||||
import java.util.logging.*;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Implements a logger, which delegates to a {@link java.util.logging.Logger}
|
|
||||||
* instance, but maintains its own logging level.
|
|
||||||
*
|
|
||||||
* @author Boris Grozev
|
|
||||||
*/
|
|
||||||
public class Logger
|
|
||||||
{
|
|
||||||
/**
|
|
||||||
* The level of this logger.
|
|
||||||
*/
|
|
||||||
private Level level;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The underlying {@link java.util.logging.Logger} instance to which logging
|
|
||||||
* is delegated.
|
|
||||||
*/
|
|
||||||
private java.util.logging.Logger delegate;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The {@link Logger} instance (if any) which provides the log level of this
|
|
||||||
* instance.
|
|
||||||
*/
|
|
||||||
private Logger levelDelegate;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Initializes a new {@link Logger} instance with a given delegate and a
|
|
||||||
* given log level.
|
|
||||||
* @param delegate the delegate.
|
|
||||||
* @param level the log level.
|
|
||||||
*/
|
|
||||||
public Logger(java.util.logging.Logger delegate, Level level)
|
|
||||||
{
|
|
||||||
this.delegate = delegate;
|
|
||||||
this.level = level;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Initializes a new {@link Logger} instance with a given delegate and which
|
|
||||||
* uses the log level from another {@link Logger} instance.
|
|
||||||
* @param delegate the delegate.
|
|
||||||
* @param levelDelegate the {@link Logger} instance whose log level will be
|
|
||||||
* used.
|
|
||||||
*/
|
|
||||||
public Logger(java.util.logging.Logger delegate, Logger levelDelegate)
|
|
||||||
{
|
|
||||||
this.delegate = delegate;
|
|
||||||
this.levelDelegate = levelDelegate;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Sets the logging {@link Level} for this {@link Logger}.
|
|
||||||
* @param level the level to set.
|
|
||||||
*/
|
|
||||||
public void setLevel(Level level)
|
|
||||||
{
|
|
||||||
this.level = level;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @return the logging {@link Level} configured for this {@link Logger}.
|
|
||||||
*/
|
|
||||||
public Level getLevel()
|
|
||||||
{
|
|
||||||
return levelDelegate != null ? levelDelegate.getLevel() : level;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Checks whether messages with a particular level should be logged
|
|
||||||
* according to the log level configured for this {@link Logger}.
|
|
||||||
* @param level the log level.
|
|
||||||
*/
|
|
||||||
public boolean isLoggable(Level level)
|
|
||||||
{
|
|
||||||
Level currentLevel
|
|
||||||
= levelDelegate != null ? levelDelegate.getLevel() : this.level;
|
|
||||||
int levelValue = currentLevel.intValue();
|
|
||||||
|
|
||||||
return level.intValue() >= levelValue
|
|
||||||
&& levelValue != Level.OFF.intValue();
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Logs a message at a given level, if that level is loggable according to
|
|
||||||
* the log level configured by this instance.
|
|
||||||
* @param level the level at which to log the message.
|
|
||||||
* @param msg the message to log.
|
|
||||||
*/
|
|
||||||
public void log(Level level, String msg)
|
|
||||||
{
|
|
||||||
if (isLoggable(level))
|
|
||||||
{
|
|
||||||
delegate.log(level, msg);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Logs a message at a given level, if that level is loggable according to
|
|
||||||
* the log level configured by this instance.
|
|
||||||
* @param level the level at which to log the message.
|
|
||||||
* @param msg the message to log.
|
|
||||||
* @param thrown a {@link Throwable} associated with log message.
|
|
||||||
*/
|
|
||||||
public void log(Level level, String msg, Throwable thrown)
|
|
||||||
{
|
|
||||||
if (isLoggable(level))
|
|
||||||
{
|
|
||||||
delegate.log(level, msg, thrown);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Logs a message with level {@link Level#SEVERE}, if that level is
|
|
||||||
* loggable according to the log level configured for this {@link Logger}.
|
|
||||||
* @param msg the message to log.
|
|
||||||
*/
|
|
||||||
public void severe(String msg)
|
|
||||||
{
|
|
||||||
log(Level.SEVERE, msg);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Logs a message with level {@link Level#WARNING}, if that level is
|
|
||||||
* loggable according to the log level configured for this {@link Logger}.
|
|
||||||
* @param msg the message to log.
|
|
||||||
*/
|
|
||||||
public void warning(String msg)
|
|
||||||
{
|
|
||||||
log(Level.WARNING, msg);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Logs a message with level {@link Level#INFO}, if that level is
|
|
||||||
* loggable according to the log level configured for this {@link Logger}.
|
|
||||||
* @param msg the message to log.
|
|
||||||
*/
|
|
||||||
public void info(String msg)
|
|
||||||
{
|
|
||||||
log(Level.INFO, msg);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Logs a message with level {@link Level#CONFIG}, if that level is
|
|
||||||
* loggable according to the log level configured for this {@link Logger}.
|
|
||||||
* @param msg the message to log.
|
|
||||||
*/
|
|
||||||
public void config(String msg)
|
|
||||||
{
|
|
||||||
log(Level.CONFIG, msg);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Logs a message with level {@link Level#FINE}, if that level is
|
|
||||||
* loggable according to the log level configured for this {@link Logger}.
|
|
||||||
* @param msg the message to log.
|
|
||||||
*/
|
|
||||||
public void fine(String msg)
|
|
||||||
{
|
|
||||||
log(Level.FINE, msg);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Logs a message with level {@link Level#FINER}, if that level is
|
|
||||||
* loggable according to the log level configured for this {@link Logger}.
|
|
||||||
* @param msg the message to log.
|
|
||||||
*/
|
|
||||||
public void finer(String msg)
|
|
||||||
{
|
|
||||||
log(Level.FINER, msg);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Logs a message with level {@link Level#FINEST}, if that level is
|
|
||||||
* loggable according to the log level configured for this {@link Logger}.
|
|
||||||
* @param msg the message to log.
|
|
||||||
*/
|
|
||||||
public void finest(String msg)
|
|
||||||
{
|
|
||||||
log(Level.FINEST, msg);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* An alias for {@link #fine(String)}.
|
|
||||||
*/
|
|
||||||
public void debug(String msg)
|
|
||||||
{
|
|
||||||
fine(msg);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* An alias for {@link #warning(String)}.
|
|
||||||
*/
|
|
||||||
public void warn(String msg)
|
|
||||||
{
|
|
||||||
warning(msg);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* An alias for {@link #severe(String)}.
|
|
||||||
*/
|
|
||||||
public void error(String msg)
|
|
||||||
{
|
|
||||||
severe(msg);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* An alias for {@link #finest(String)}.
|
|
||||||
*/
|
|
||||||
public void trace(String msg)
|
|
||||||
{
|
|
||||||
finest(msg);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,498 +0,0 @@
|
|||||||
/*
|
|
||||||
* 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.util;
|
|
||||||
|
|
||||||
import java.util.*;
|
|
||||||
import java.util.concurrent.*;
|
|
||||||
import java.util.logging.Logger; // Disambiguation.
|
|
||||||
|
|
||||||
/**
|
|
||||||
* An abstract queue of packets. This is meant to eventually be able to be used
|
|
||||||
* in the following classes (in ice4j and libjitsi) in place of their ad-hoc
|
|
||||||
* queue implementations (which is the reason the class is parameterized):
|
|
||||||
* <br> RTPConnectorOutputStream.Queue
|
|
||||||
* <br> PushSourceStreamImpl#readQ
|
|
||||||
* <br> OutputDataStreamImpl#writeQ
|
|
||||||
* <br> SinglePortHarvester.MySocket#queue
|
|
||||||
* <br> MultiplexingSocket#received (and the rest of Multiplex* classes).
|
|
||||||
*
|
|
||||||
* @author Boris Grozev
|
|
||||||
*/
|
|
||||||
public abstract class PacketQueue<T>
|
|
||||||
{
|
|
||||||
/**
|
|
||||||
* The {@link Logger} used by the {@link PacketQueue} class and its
|
|
||||||
* instances for logging output.
|
|
||||||
*/
|
|
||||||
private static final Logger logger
|
|
||||||
= Logger.getLogger(PacketQueue.class.getName());
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The default capacity of a {@link PacketQueue}.
|
|
||||||
*/
|
|
||||||
private final static int DEFAULT_CAPACITY = 256;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The capacity of the {@code byte[]} cache, if it is enabled.
|
|
||||||
*/
|
|
||||||
private final static int CACHE_CAPACITY = 100;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns true if a warning should be logged after a queue has dropped
|
|
||||||
* {@code numDroppedPackets} packets.
|
|
||||||
* @param numDroppedPackets the number of dropped packets.
|
|
||||||
* @return {@code true} if a warning should be logged.
|
|
||||||
*/
|
|
||||||
public static boolean logDroppedPacket(int numDroppedPackets)
|
|
||||||
{
|
|
||||||
return
|
|
||||||
numDroppedPackets == 1 ||
|
|
||||||
(numDroppedPackets <= 1000 && numDroppedPackets % 100 == 0) ||
|
|
||||||
numDroppedPackets % 1000 == 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The underlying {@link Queue} which holds packets.
|
|
||||||
*/
|
|
||||||
private final Queue<T> queue;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Whether this {@link PacketQueue} should store the {@code byte[]} or
|
|
||||||
* {@code T} instances added to it via one of the {@code add} methods (if
|
|
||||||
* {@code false}), or create and store a copy (if {@code true}).
|
|
||||||
*/
|
|
||||||
private final boolean copy;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The capacity of this {@link PacketQueue}. If one of the {@code add}
|
|
||||||
* methods is called while the queue holds this many packets, the first
|
|
||||||
* packet in the queue will be dropped.
|
|
||||||
*/
|
|
||||||
private final int capacity;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The {@link QueueStatistics} instance optionally used to collect and print
|
|
||||||
* detailed statistics about this queue.
|
|
||||||
*/
|
|
||||||
private final QueueStatistics queueStatistics;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The {@link Thread} optionally used to perpetually read packets from this
|
|
||||||
* queue and handle them using {@link #handler}.
|
|
||||||
*/
|
|
||||||
private final Thread thread;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The {@link org.ice4j.util.PacketQueue.PacketHandler} optionally used to
|
|
||||||
* handle packets read from this queue by {@link #thread}.
|
|
||||||
*/
|
|
||||||
private final PacketHandler<T> handler;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* A string used to identify this {@link PacketQueue} for logging purposes.
|
|
||||||
*/
|
|
||||||
private final String id;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Whether this queue has been closed.
|
|
||||||
*/
|
|
||||||
private boolean closed = false;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The number of packets which were dropped from this {@link PacketQueue} as
|
|
||||||
* a result of a packet being added while the queue is at full capacity.
|
|
||||||
*/
|
|
||||||
private int numDroppedPackets = 0;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Initializes a new {@link PacketQueue} instance.
|
|
||||||
*/
|
|
||||||
public PacketQueue()
|
|
||||||
{
|
|
||||||
this(false, "PacketQueue", null);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Initializes a new {@link PacketQueue} instance.
|
|
||||||
* @param enableStatistics whether detailed statistics should be calculated
|
|
||||||
* and printed. WARNING: this will produce copious output (one line per
|
|
||||||
* packet added or removed).
|
|
||||||
* @param id the ID of the packet queue, to be used for logging.
|
|
||||||
* @param packetHandler An optional handler to be used by the queue for
|
|
||||||
* packets read from it. If a non-null value is passed the queue will
|
|
||||||
* start its own thread, which will read packets from the queue and execute
|
|
||||||
* {@code handler.handlePacket} on them. If set to null, no thread will be
|
|
||||||
* created, and the queue will provide access to the head element via
|
|
||||||
* {@link #get()} and {@link #poll()}.
|
|
||||||
*/
|
|
||||||
public PacketQueue(
|
|
||||||
boolean enableStatistics, String id, PacketHandler<T> packetHandler)
|
|
||||||
{
|
|
||||||
this(DEFAULT_CAPACITY, true, enableStatistics, id, packetHandler);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Initializes a new {@link PacketQueue} instance.
|
|
||||||
* @param capacity the capacity of the queue.
|
|
||||||
* @param copy whether the queue is to store the instances it is given via
|
|
||||||
* the various {@code add} methods, or create a copy.
|
|
||||||
* @param enableStatistics whether detailed statistics should be calculated
|
|
||||||
* and printed. WARNING: this will produce copious output (one line per
|
|
||||||
* packet added or removed).
|
|
||||||
* @param id the ID of the packet queue, to be used for logging.
|
|
||||||
* @param packetHandler An optional handler to be used by the queue for
|
|
||||||
* packets read from it. If a non-null value is passed the queue will
|
|
||||||
* start its own thread, which will read packets from the queue and execute
|
|
||||||
* {@code handler.handlePacket} on them. If set to null, no thread will be
|
|
||||||
* created, and the queue will provide access to the head element via
|
|
||||||
* {@link #get()} and {@link #poll()}.
|
|
||||||
*/
|
|
||||||
public PacketQueue(int capacity, boolean copy,
|
|
||||||
boolean enableStatistics, String id,
|
|
||||||
PacketHandler<T> packetHandler)
|
|
||||||
{
|
|
||||||
this.copy = copy;
|
|
||||||
this.capacity = capacity;
|
|
||||||
this.id = id;
|
|
||||||
queue = new ArrayBlockingQueue<>(capacity);
|
|
||||||
|
|
||||||
queueStatistics
|
|
||||||
= enableStatistics ? new QueueStatistics(id) : null;
|
|
||||||
|
|
||||||
if (packetHandler != null)
|
|
||||||
{
|
|
||||||
handler = packetHandler;
|
|
||||||
|
|
||||||
thread = new Thread(){
|
|
||||||
@Override
|
|
||||||
public void run()
|
|
||||||
{
|
|
||||||
runInReadingThread();
|
|
||||||
}
|
|
||||||
};
|
|
||||||
thread.setName(getClass().getName() + "-" + id);
|
|
||||||
thread.setDaemon(true);
|
|
||||||
thread.start();
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
thread = null;
|
|
||||||
handler = null;
|
|
||||||
}
|
|
||||||
|
|
||||||
logger.fine("Initialized a PacketQueue instance with ID " + id);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Perpetually reads packets from this {@link PacketQueue} and uses
|
|
||||||
* {@link #handler} on each of them.
|
|
||||||
*/
|
|
||||||
private void runInReadingThread()
|
|
||||||
{
|
|
||||||
if (Thread.currentThread() != thread)
|
|
||||||
{
|
|
||||||
logger.warning("runInReadingThread executing in "
|
|
||||||
+ Thread.currentThread());
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (handler == null)
|
|
||||||
{
|
|
||||||
logger.warning("No handler set, the reading thread will be stopped.");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
while (!closed)
|
|
||||||
{
|
|
||||||
T pkt;
|
|
||||||
|
|
||||||
synchronized (queue)
|
|
||||||
{
|
|
||||||
pkt = queue.poll();
|
|
||||||
if (pkt == null)
|
|
||||||
{
|
|
||||||
try
|
|
||||||
{
|
|
||||||
queue.wait(100);
|
|
||||||
}
|
|
||||||
catch (InterruptedException ie)
|
|
||||||
{
|
|
||||||
}
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (queueStatistics != null)
|
|
||||||
{
|
|
||||||
queueStatistics.remove(System.currentTimeMillis());
|
|
||||||
}
|
|
||||||
|
|
||||||
try
|
|
||||||
{
|
|
||||||
handler.handlePacket(pkt);
|
|
||||||
}
|
|
||||||
catch (Exception e)
|
|
||||||
{
|
|
||||||
logger.warning("Failed to handle packet: " + e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Adds a packet represented by a {@code byte[]} with a corresponding
|
|
||||||
* offset and length to this queue.
|
|
||||||
* @param buf the {@code byte[]} to add.
|
|
||||||
* @param off the offset into {@code byte[]} where data begins.
|
|
||||||
* @param len the length of the data.
|
|
||||||
*/
|
|
||||||
public void add(byte[] buf, int off, int len)
|
|
||||||
{
|
|
||||||
add(buf, off, len, null);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Adds a packet represented by a {@code byte[]} with a corresponding
|
|
||||||
* offset and length, and a context object to this queue.
|
|
||||||
* @param buf the {@code byte[]} to add.
|
|
||||||
* @param off the offset into {@code byte[]} where data begins.
|
|
||||||
* @param len the length of the data.
|
|
||||||
* @param context an object which will be added to the queue as part of the
|
|
||||||
* packet.
|
|
||||||
*/
|
|
||||||
public void add(byte[] buf, int off, int len, Object context)
|
|
||||||
{
|
|
||||||
if (copy)
|
|
||||||
{
|
|
||||||
byte[] newBuf = getByteArray(len);
|
|
||||||
System.arraycopy(buf, off, newBuf, 0, len);
|
|
||||||
doAdd(createPacket(newBuf, 0, len, context));
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
doAdd(createPacket(buf, off, len, context));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Adds a specific packet ({@code T}) instance to the queue.
|
|
||||||
* @param pkt the packet to add.
|
|
||||||
*/
|
|
||||||
public void add(T pkt)
|
|
||||||
{
|
|
||||||
if (copy)
|
|
||||||
{
|
|
||||||
// create a new instance
|
|
||||||
add(getBuffer(pkt), getOffset(pkt), getLength(pkt), getContext(pkt));
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
doAdd(pkt);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Get an unused {@link byte[]} instance with length at least {@code len}.
|
|
||||||
* @param len the minimum length of the returned instance.
|
|
||||||
* @return a {@link byte[]} instance with length at least {@code len}.
|
|
||||||
*/
|
|
||||||
private byte[] getByteArray(int len)
|
|
||||||
{
|
|
||||||
return new byte[len];
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Adds a specific packet ({@code T}) instance to the queue.
|
|
||||||
* @param pkt the packet to add.
|
|
||||||
*/
|
|
||||||
private void doAdd(T pkt)
|
|
||||||
{
|
|
||||||
if (closed)
|
|
||||||
return;
|
|
||||||
|
|
||||||
synchronized (queue)
|
|
||||||
{
|
|
||||||
if (queue.size() >= capacity)
|
|
||||||
{
|
|
||||||
// Drop from the head of the queue.
|
|
||||||
T p = queue.poll();
|
|
||||||
if (p != null)
|
|
||||||
{
|
|
||||||
if (queueStatistics != null)
|
|
||||||
{
|
|
||||||
queueStatistics.remove(System.currentTimeMillis());
|
|
||||||
}
|
|
||||||
if (logDroppedPacket(++numDroppedPackets))
|
|
||||||
{
|
|
||||||
logger.warning(
|
|
||||||
"Packets dropped (id=" + id + "): " + numDroppedPackets);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (queueStatistics != null)
|
|
||||||
{
|
|
||||||
queueStatistics.add(System.currentTimeMillis());
|
|
||||||
}
|
|
||||||
queue.offer(pkt);
|
|
||||||
|
|
||||||
queue.notifyAll();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Removes and returns the packet ({@code T}) at the head of this queue.
|
|
||||||
* Blocks until there is a packet in the queue. Returns {@code null} if
|
|
||||||
* the queue is closed or gets closed while waiting for a packet to be added.
|
|
||||||
* @return the packet at the head of this queue.
|
|
||||||
*/
|
|
||||||
public T get()
|
|
||||||
{
|
|
||||||
if (handler != null)
|
|
||||||
{
|
|
||||||
// If the queue was configured with a handler, it is running its
|
|
||||||
// own reading thread, and reading from it via this interface would
|
|
||||||
// not provide consistent results.
|
|
||||||
throw new IllegalStateException(
|
|
||||||
"Trying to read from a queue with a configured handler.");
|
|
||||||
}
|
|
||||||
|
|
||||||
while (true)
|
|
||||||
{
|
|
||||||
if (closed)
|
|
||||||
return null;
|
|
||||||
synchronized (queue)
|
|
||||||
{
|
|
||||||
T pkt = queue.poll();
|
|
||||||
if (pkt != null)
|
|
||||||
{
|
|
||||||
if (queueStatistics != null)
|
|
||||||
{
|
|
||||||
queueStatistics.remove(System.currentTimeMillis());
|
|
||||||
}
|
|
||||||
return pkt;
|
|
||||||
}
|
|
||||||
|
|
||||||
try
|
|
||||||
{
|
|
||||||
queue.wait();
|
|
||||||
}
|
|
||||||
catch (InterruptedException ie)
|
|
||||||
{}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Removes and returns the packet ({@code T}) at the head of this queue, if
|
|
||||||
* the queue is non-empty. If the queue is closed or empty, returns null
|
|
||||||
* without blocking.
|
|
||||||
* @return the packet at the head of this queue, or null if the queue is
|
|
||||||
* empty.
|
|
||||||
*/
|
|
||||||
public T poll()
|
|
||||||
{
|
|
||||||
if (closed)
|
|
||||||
return null;
|
|
||||||
|
|
||||||
if (handler != null)
|
|
||||||
{
|
|
||||||
// If the queue was configured with a handler, it is running its
|
|
||||||
// own reading thread, and reading from it via this interface would
|
|
||||||
// not provide consistent results.
|
|
||||||
throw new IllegalStateException(
|
|
||||||
"Trying to read from a queue with a configured handler.");
|
|
||||||
}
|
|
||||||
|
|
||||||
synchronized (queue)
|
|
||||||
{
|
|
||||||
T pkt = queue.poll();
|
|
||||||
if (pkt != null && queueStatistics != null)
|
|
||||||
{
|
|
||||||
queueStatistics.remove(System.currentTimeMillis());
|
|
||||||
}
|
|
||||||
|
|
||||||
return pkt;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public void close()
|
|
||||||
{
|
|
||||||
if (!closed)
|
|
||||||
{
|
|
||||||
closed = true;
|
|
||||||
|
|
||||||
synchronized (queue)
|
|
||||||
{
|
|
||||||
queue.notifyAll();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Extracts the underlying {@code byte[]} from a packet.
|
|
||||||
* @param pkt the packet to get the {@code byte[]} from.
|
|
||||||
* @return the underlying {@code byte[]} of {@code pkt}.
|
|
||||||
*/
|
|
||||||
public abstract byte[] getBuffer(T pkt);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Extracts the offset of a packet.
|
|
||||||
* @param pkt the packet to get the offset of.
|
|
||||||
* @return the offset of {@code pkt}.
|
|
||||||
*/
|
|
||||||
public abstract int getOffset(T pkt);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Extracts the length of a packet.
|
|
||||||
* @param pkt the packet to get the length of.
|
|
||||||
* @return the length of {@code pkt}.
|
|
||||||
*/
|
|
||||||
public abstract int getLength(T pkt);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Extracts the context of a packet.
|
|
||||||
* @param pkt the packet to get the context of.
|
|
||||||
* @return the context of {@code pkt}.
|
|
||||||
*/
|
|
||||||
public abstract Object getContext(T pkt);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Creates a new packet ({@link T} instance) with the given {@code byte[]},
|
|
||||||
* offset, length and context.
|
|
||||||
* @param buf the {@code byte[]} of the new instance.
|
|
||||||
* @param off the offset of the new instance.
|
|
||||||
* @param len the length of the new instance.
|
|
||||||
* @param context the context of the new instance.
|
|
||||||
* @return a new packet ({@link T} instance).
|
|
||||||
*/
|
|
||||||
protected abstract T createPacket(
|
|
||||||
byte[] buf, int off, int len, Object context);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* A simple interface to handle packets.
|
|
||||||
* @param <T> the type of the packets.
|
|
||||||
*/
|
|
||||||
public interface PacketHandler<T>
|
|
||||||
{
|
|
||||||
/**
|
|
||||||
* Does something with a packet.
|
|
||||||
* @param pkt the packet to do something with.
|
|
||||||
* @return {@code true} if the operation was successful, and
|
|
||||||
* {@code false} otherwise.
|
|
||||||
*/
|
|
||||||
boolean handlePacket(T pkt);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
263
src/main/java/org/ice4j/util/PeriodicRunnable.java
Normal file
263
src/main/java/org/ice4j/util/PeriodicRunnable.java
Normal file
@ -0,0 +1,263 @@
|
|||||||
|
package org.ice4j.util;
|
||||||
|
|
||||||
|
import org.jitsi.utils.logging2.*;
|
||||||
|
|
||||||
|
import java.time.*;
|
||||||
|
import java.util.concurrent.*;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A base class for runnables which should be periodically executed on
|
||||||
|
* specified executor service.
|
||||||
|
*
|
||||||
|
* @author Yura Yaroshevich
|
||||||
|
*/
|
||||||
|
public abstract class PeriodicRunnable
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* The {@link Logger} used by the {@link PeriodicRunnable} class for logging output.
|
||||||
|
*/
|
||||||
|
private final static Logger logger = new LoggerImpl(PeriodicRunnable.class.getName());
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A timer to perform periodic scheduling of {@link #run()} execution
|
||||||
|
* on {@link #executor}'s thread.
|
||||||
|
*/
|
||||||
|
private final ScheduledExecutorService timer;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* An executor service to perform actual execution of {@link #run()}.
|
||||||
|
*/
|
||||||
|
private final ExecutorService executor;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A synchronization object to synchronize scheduling, execution and
|
||||||
|
* cancellation of {@link #run()}.
|
||||||
|
*/
|
||||||
|
private final Object syncRoot = new Object();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Indicates if execution of {@link #run()} scheduled and should
|
||||||
|
* be further continued.
|
||||||
|
*/
|
||||||
|
private volatile boolean running = false;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Store a reference to last runnable submitted to {@link #timer}
|
||||||
|
*/
|
||||||
|
private ScheduledFuture<?> scheduledSubmit;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Store a reference to last runnable submitted to {@link #executor}
|
||||||
|
*/
|
||||||
|
private Future<?> submittedExecute;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create instance of {@link PeriodicRunnable} with specified timer and
|
||||||
|
* executor.
|
||||||
|
* @param timer an {@link ScheduledExecutorService} which is used to
|
||||||
|
* periodic triggering of {@link #run()} execution.
|
||||||
|
* @param executor an {@link ExecutorService} to perform actual execution
|
||||||
|
* of {@link #run()}.
|
||||||
|
*/
|
||||||
|
protected PeriodicRunnable(
|
||||||
|
ScheduledExecutorService timer,
|
||||||
|
ExecutorService executor)
|
||||||
|
{
|
||||||
|
if (timer == null)
|
||||||
|
{
|
||||||
|
throw new IllegalArgumentException("timer is null");
|
||||||
|
}
|
||||||
|
if (executor == null)
|
||||||
|
{
|
||||||
|
throw new IllegalArgumentException("executor is null");
|
||||||
|
}
|
||||||
|
this.timer = timer;
|
||||||
|
this.executor = executor;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get delay before next execution of {@link #run()}.
|
||||||
|
* @return non-negative value if execution of {@link #run()} should be
|
||||||
|
* performed with specified delay, negative value if execution should not
|
||||||
|
* be done.
|
||||||
|
*/
|
||||||
|
protected abstract Duration getDelayUntilNextRun();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Periodically executed method on {@link #executor}'s thread.
|
||||||
|
*/
|
||||||
|
protected abstract void run();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Schedules periodic execution of {@link #run()} on {@link #executor}'s
|
||||||
|
* thread.
|
||||||
|
*/
|
||||||
|
public void schedule()
|
||||||
|
{
|
||||||
|
if (running)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
final Duration delay =
|
||||||
|
getDelayUntilNextRun();
|
||||||
|
|
||||||
|
scheduleNextRun(delay);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Cancels periodic execution of {@link #run()} on {@link #executor}'s
|
||||||
|
* thread.
|
||||||
|
*/
|
||||||
|
public void cancel()
|
||||||
|
{
|
||||||
|
if (!running)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
synchronized (syncRoot)
|
||||||
|
{
|
||||||
|
if (running)
|
||||||
|
{
|
||||||
|
running = false;
|
||||||
|
|
||||||
|
if (scheduledSubmit != null)
|
||||||
|
{
|
||||||
|
scheduledSubmit.cancel(true);
|
||||||
|
scheduledSubmit = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (submittedExecute != null)
|
||||||
|
{
|
||||||
|
submittedExecute.cancel(true);
|
||||||
|
submittedExecute = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Perform either cancellation or actual scheduling based on delay until
|
||||||
|
* next run.
|
||||||
|
* @param delay delay before next execution of {@link #run()}.
|
||||||
|
*/
|
||||||
|
private void scheduleNextRun(Duration delay)
|
||||||
|
{
|
||||||
|
synchronized (syncRoot)
|
||||||
|
{
|
||||||
|
final boolean isRecurrentRun = submittedExecute != null;
|
||||||
|
if (isRecurrentRun && !running)
|
||||||
|
{
|
||||||
|
// was cancelled
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (delay.isNegative())
|
||||||
|
{
|
||||||
|
running = false;
|
||||||
|
scheduledSubmit = null;
|
||||||
|
submittedExecute = null;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
running = true;
|
||||||
|
|
||||||
|
if (delay.isZero())
|
||||||
|
{
|
||||||
|
submitExecuteRun();
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
scheduledSubmit = timer.schedule(
|
||||||
|
this::submitExecuteRun,
|
||||||
|
delay.toNanos(),
|
||||||
|
TimeUnit.NANOSECONDS);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Submit execution of {@link #run()} into {@link #executor}'s thread
|
||||||
|
* if not cancelled.
|
||||||
|
*/
|
||||||
|
private void submitExecuteRun()
|
||||||
|
{
|
||||||
|
if (!running)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
synchronized (syncRoot)
|
||||||
|
{
|
||||||
|
if (!running)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
submittedExecute = this.executor.submit(this::executeRun);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Perform execution of {@link #run()} with further re-schedule of
|
||||||
|
* execution if not cancelled
|
||||||
|
*/
|
||||||
|
private void executeRun()
|
||||||
|
{
|
||||||
|
if (!running)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
this.run();
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
logger.warn("Exception in run(), will retry.", e);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
if (running)
|
||||||
|
{
|
||||||
|
final Duration delayMillis =
|
||||||
|
getDelayUntilNextRun();
|
||||||
|
|
||||||
|
scheduleNextRun(delayMillis);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Constructs {@link PeriodicRunnable} for {@link Runnable} with provided
|
||||||
|
* timer, executor and fixed delay.
|
||||||
|
* fixed delay.
|
||||||
|
* @param timer {@link ScheduledExecutorService} to be used as timer
|
||||||
|
* @param executor {@link ExecutorService} to execute provided runnable
|
||||||
|
* @param period delay between subsequent execution of runnable
|
||||||
|
* @param r {@link Runnable} to for periodic execution.
|
||||||
|
* @return {@link PeriodicRunnable} instance constructed with provided
|
||||||
|
* arguments
|
||||||
|
*/
|
||||||
|
static PeriodicRunnable create(
|
||||||
|
ScheduledExecutorService timer,
|
||||||
|
ExecutorService executor,
|
||||||
|
Duration period,
|
||||||
|
Runnable r)
|
||||||
|
{
|
||||||
|
return new PeriodicRunnable(timer, executor)
|
||||||
|
{
|
||||||
|
@Override
|
||||||
|
protected Duration getDelayUntilNextRun()
|
||||||
|
{
|
||||||
|
return period;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected void run()
|
||||||
|
{
|
||||||
|
r.run();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -1,131 +0,0 @@
|
|||||||
/*
|
|
||||||
* 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.util;
|
|
||||||
|
|
||||||
import java.util.logging.*;
|
|
||||||
import java.util.logging.Logger; // Disambiguation.
|
|
||||||
|
|
||||||
public class QueueStatistics
|
|
||||||
{
|
|
||||||
/**
|
|
||||||
* The scale to use for {@link RateStatistics}. This makes their output in
|
|
||||||
* units (e.g. packets) per second.
|
|
||||||
*/
|
|
||||||
private static final int SCALE = 1000;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The interval (in number of calls to {@link #add(long)} or
|
|
||||||
* {@link #remove(long)}) at which the gathered statistics will be printed.
|
|
||||||
*/
|
|
||||||
private static final int DEFAULT_PRINT_INTERVAL = 500;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Calculate the average rate of addition of packets in a 200ms window.
|
|
||||||
*/
|
|
||||||
private final RateStatistics addRateStatistics = new RateStatistics(200, SCALE);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Calculate the average rate of removal of packets in a 200ms window.
|
|
||||||
*/
|
|
||||||
private final RateStatistics removeRateStatistics = new RateStatistics(200, SCALE);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The {@link Logger} instance used for logging output.
|
|
||||||
*/
|
|
||||||
private final Logger logger;
|
|
||||||
|
|
||||||
private int head = 0;
|
|
||||||
private int size = 0;
|
|
||||||
private int[] sizes = new int[DEFAULT_PRINT_INTERVAL];
|
|
||||||
private long[] timestamps = new long[DEFAULT_PRINT_INTERVAL];
|
|
||||||
private long[] addRates = new long[DEFAULT_PRINT_INTERVAL];
|
|
||||||
private long[] removeRates = new long[DEFAULT_PRINT_INTERVAL];
|
|
||||||
private int[] totalPacketsAddedHistory = new int[DEFAULT_PRINT_INTERVAL];
|
|
||||||
private int totalPacketsAdded = 0;
|
|
||||||
private String logHeader;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Initializes a new {@link QueueStatistics} instance.
|
|
||||||
*
|
|
||||||
* @param id Identifier to distinguish the log output of multiple
|
|
||||||
* {@link QueueStatistics} instances.
|
|
||||||
*/
|
|
||||||
public QueueStatistics(String id)
|
|
||||||
{
|
|
||||||
logger = Logger.getLogger("QueueStatistics-" + id);
|
|
||||||
logHeader = "QueueStatistics-" + id + ": ";
|
|
||||||
|
|
||||||
// We let the users of this class decide whether to enable logging (by
|
|
||||||
// creating a QueueStatistic instance) or not.
|
|
||||||
logger.setLevel(Level.ALL);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Registers the addition of a packet to the corresponding queue.
|
|
||||||
* @param now the time (in milliseconds since the epoch) at which the
|
|
||||||
* packet was added.
|
|
||||||
*/
|
|
||||||
public synchronized void add(long now)
|
|
||||||
{
|
|
||||||
addRateStatistics.update(1, now);
|
|
||||||
size++;
|
|
||||||
totalPacketsAdded++;
|
|
||||||
update(now);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Registers the removal of a packet from the corresponding queue.
|
|
||||||
* @param now the time (in milliseconds since the epoch) at which the
|
|
||||||
* packet was removed.
|
|
||||||
*/
|
|
||||||
public synchronized void remove(long now)
|
|
||||||
{
|
|
||||||
removeRateStatistics.update(1, now);
|
|
||||||
size--;
|
|
||||||
update(now);
|
|
||||||
}
|
|
||||||
|
|
||||||
private synchronized void update(long now)
|
|
||||||
{
|
|
||||||
if (head == sizes.length)
|
|
||||||
{
|
|
||||||
print();
|
|
||||||
head = 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
sizes[head] = size;
|
|
||||||
timestamps[head] = now;
|
|
||||||
addRates[head] = addRateStatistics.getRate(now);
|
|
||||||
removeRates[head] = removeRateStatistics.getRate(now);
|
|
||||||
totalPacketsAddedHistory[head] = totalPacketsAdded;
|
|
||||||
head++;
|
|
||||||
}
|
|
||||||
|
|
||||||
private void print()
|
|
||||||
{
|
|
||||||
StringBuilder s = new StringBuilder();
|
|
||||||
for (int i =0; i<sizes.length; i++)
|
|
||||||
{
|
|
||||||
s.append(logHeader).
|
|
||||||
append(timestamps[i]).append(' ').
|
|
||||||
append(sizes[i]).append(' ').
|
|
||||||
append(addRates[i]).append(' ').
|
|
||||||
append(removeRates[i]).append(' ').
|
|
||||||
append(totalPacketsAddedHistory[i]).append('\n');
|
|
||||||
}
|
|
||||||
logger.fine(s.toString());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,146 +0,0 @@
|
|||||||
/*
|
|
||||||
* 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.util;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* This originally comes from webrtc.org but has been moved here so that it can
|
|
||||||
* be reused more easily.
|
|
||||||
*
|
|
||||||
* webrtc/modules/remote_bitrate_estimator/rate_statistics.cc
|
|
||||||
* webrtc/modules/remote_bitrate_estimator/rate_statistics.h
|
|
||||||
*
|
|
||||||
* @author Lyubomir Marinov
|
|
||||||
*/
|
|
||||||
public class RateStatistics
|
|
||||||
{
|
|
||||||
/**
|
|
||||||
* Total count recorded in buckets.
|
|
||||||
*/
|
|
||||||
private long accumulatedCount;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Counters are kept in buckets (circular buffer), with one bucket per
|
|
||||||
* millisecond.
|
|
||||||
*/
|
|
||||||
private final long[] buckets;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Bucket index of oldest counter recorded in buckets.
|
|
||||||
*/
|
|
||||||
private int oldestIndex;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Oldest time recorded in buckets.
|
|
||||||
*/
|
|
||||||
private long oldestTime;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* To convert counts/ms to desired units.
|
|
||||||
*/
|
|
||||||
private final float scale;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Initializes a new {@link RateStatistics} instance with a default scale
|
|
||||||
* of 8000 (i.e. if the input is in bytes, the result will be in bits per
|
|
||||||
* second).
|
|
||||||
* @param windowSizeMs window size in ms for the rate estimation
|
|
||||||
*/
|
|
||||||
public RateStatistics(int windowSizeMs)
|
|
||||||
{
|
|
||||||
this(windowSizeMs, 8000F);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @param windowSizeMs window size in ms for the rate estimation
|
|
||||||
* @param scale coefficient to convert counts/ms to desired units. For
|
|
||||||
* example, if counts represents bytes, use <tt>8*1000</tt> to go to bits/s.
|
|
||||||
*/
|
|
||||||
public RateStatistics(int windowSizeMs, float scale)
|
|
||||||
{
|
|
||||||
buckets = new long[windowSizeMs + 1]; // N ms in (N+1) buckets.
|
|
||||||
this.scale = scale / (buckets.length - 1);
|
|
||||||
}
|
|
||||||
|
|
||||||
private synchronized void eraseOld(long nowMs)
|
|
||||||
{
|
|
||||||
long newOldestTime = nowMs - buckets.length + 1;
|
|
||||||
|
|
||||||
if (newOldestTime <= oldestTime)
|
|
||||||
return;
|
|
||||||
|
|
||||||
while (oldestTime < newOldestTime)
|
|
||||||
{
|
|
||||||
long countInOldestBucket = buckets[oldestIndex];
|
|
||||||
|
|
||||||
accumulatedCount -= countInOldestBucket;
|
|
||||||
buckets[oldestIndex] = 0L;
|
|
||||||
if (++oldestIndex >= buckets.length)
|
|
||||||
{
|
|
||||||
oldestIndex = 0;
|
|
||||||
}
|
|
||||||
++oldestTime;
|
|
||||||
if (accumulatedCount == 0L)
|
|
||||||
{
|
|
||||||
// This guarantees we go through all the buckets at most once,
|
|
||||||
// even if newOldestTime is far greater than oldestTime.
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
oldestTime = newOldestTime;
|
|
||||||
}
|
|
||||||
|
|
||||||
public long getRate()
|
|
||||||
{
|
|
||||||
return getRate(System.currentTimeMillis());
|
|
||||||
}
|
|
||||||
|
|
||||||
public long getRate(long nowMs)
|
|
||||||
{
|
|
||||||
eraseOld(nowMs);
|
|
||||||
return (long) (accumulatedCount * scale + 0.5F);
|
|
||||||
}
|
|
||||||
|
|
||||||
public long getAccumulatedCount()
|
|
||||||
{
|
|
||||||
return getAccumulatedCount(System.currentTimeMillis());
|
|
||||||
}
|
|
||||||
|
|
||||||
public long getAccumulatedCount(long nowMs)
|
|
||||||
{
|
|
||||||
eraseOld(nowMs);
|
|
||||||
return accumulatedCount;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
public void update(int count, long nowMs)
|
|
||||||
{
|
|
||||||
if (nowMs < oldestTime) // Too old data is ignored.
|
|
||||||
return;
|
|
||||||
|
|
||||||
synchronized (this)
|
|
||||||
{
|
|
||||||
eraseOld(nowMs);
|
|
||||||
|
|
||||||
int nowOffset = (int) (nowMs - oldestTime);
|
|
||||||
int index = oldestIndex + nowOffset;
|
|
||||||
|
|
||||||
if (index >= buckets.length)
|
|
||||||
index -= buckets.length;
|
|
||||||
buckets[index] += count;
|
|
||||||
accumulatedCount += count;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
83
src/main/kotlin/org/ice4j/ice/AgentConfig.kt
Normal file
83
src/main/kotlin/org/ice4j/ice/AgentConfig.kt
Normal file
@ -0,0 +1,83 @@
|
|||||||
|
/*
|
||||||
|
* Copyright @ 2020 - Present, 8x8 Inc
|
||||||
|
*
|
||||||
|
* 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
|
||||||
|
|
||||||
|
import org.jitsi.metaconfig.config
|
||||||
|
import java.time.Duration
|
||||||
|
import org.jitsi.config.JitsiConfig.Companion.newConfig as configSource
|
||||||
|
|
||||||
|
class AgentConfig {
|
||||||
|
val consentFreshnessInterval: Duration by config {
|
||||||
|
"org.ice4j.ice.CONSENT_FRESHNESS_INTERVAL".from(configSource)
|
||||||
|
.convertFrom<Long> { Duration.ofMillis(it) }
|
||||||
|
"ice4j.consent-freshness.interval".from(configSource)
|
||||||
|
}
|
||||||
|
|
||||||
|
val randomizeConsentFreshnessInterval: Boolean by config {
|
||||||
|
"ice4j.consent-freshness.randomize-interval".from(configSource)
|
||||||
|
}
|
||||||
|
|
||||||
|
val consentFreshnessOriginalWaitInterval: Duration by config {
|
||||||
|
"org.ice4j.ice.CONSENT_FRESHNESS_WAIT_INTERVAL".from(configSource)
|
||||||
|
.convertFrom<Long> { Duration.ofMillis(it) }
|
||||||
|
"ice4j.consent-freshness.original-wait-interval".from(configSource)
|
||||||
|
}
|
||||||
|
|
||||||
|
val consentFreshnessMaxWaitInterval: Duration by config {
|
||||||
|
"org.ice4j.ice.CONSENT_FRESHNESS_MAX_WAIT_INTERVAL".from(configSource)
|
||||||
|
.convertFrom<Long> { Duration.ofMillis(it) }
|
||||||
|
"ice4j.consent-freshness.max-wait-interval".from(configSource)
|
||||||
|
}
|
||||||
|
|
||||||
|
val maxConsentFreshnessRetransmissions: Int by config {
|
||||||
|
"org.ice4j.ice.CONSENT_FRESHNESS_MAX_RETRANSMISSIONS".from(configSource)
|
||||||
|
"ice4j.consent-freshness.max-retransmissions".from(configSource)
|
||||||
|
}
|
||||||
|
|
||||||
|
val terminationDelay: Duration by config {
|
||||||
|
"org.ice4j.TERMINATION_DELAY".from(configSource)
|
||||||
|
.convertFrom<Long> { Duration.ofMillis(it) }
|
||||||
|
"ice4j.ice.termination-delay".from(configSource)
|
||||||
|
}
|
||||||
|
|
||||||
|
val maxCheckListSize: Int by config {
|
||||||
|
"org.ice4j.MAX_CHECK_LIST_SIZE".from(configSource)
|
||||||
|
"ice4j.ice.max-check-list-size".from(configSource)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The value of the SOFTWARE attribute that ice4j should include in all outgoing messages. */
|
||||||
|
val software: String? by config {
|
||||||
|
"org.ice4j.SOFTWARE".from(configSource)
|
||||||
|
"ice4j.software".from(configSource)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Whether the per-component merging socket should be enabled by default (the default value can be
|
||||||
|
* overridden with the [Agent] API).
|
||||||
|
* If enabled, the user of the library must use the socket instance provided by [Component.getSocket]. Otherwise,
|
||||||
|
* the socket instance from the desired [CandidatePair] must be used.
|
||||||
|
*/
|
||||||
|
val useComponentSocket: Boolean by config {
|
||||||
|
"org.ice4j.ice.USE_COMPONENT_SOCKET".from(configSource)
|
||||||
|
"ice4j.use-component-socket".from(configSource)
|
||||||
|
}
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
@JvmField
|
||||||
|
val config = AgentConfig()
|
||||||
|
}
|
||||||
|
}
|
||||||
132
src/main/kotlin/org/ice4j/ice/harvest/HarvestConfig.kt
Normal file
132
src/main/kotlin/org/ice4j/ice/harvest/HarvestConfig.kt
Normal file
@ -0,0 +1,132 @@
|
|||||||
|
/*
|
||||||
|
* Copyright @ 2020 - Present, 8x8 Inc
|
||||||
|
*
|
||||||
|
* 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 com.typesafe.config.Config
|
||||||
|
import org.jitsi.metaconfig.ConfigException
|
||||||
|
import org.jitsi.metaconfig.config
|
||||||
|
import org.jitsi.metaconfig.optionalconfig
|
||||||
|
import java.time.Duration
|
||||||
|
import org.jitsi.config.JitsiConfig.Companion.newConfig as configSource
|
||||||
|
|
||||||
|
class HarvestConfig {
|
||||||
|
val useLinkLocalAddresses: Boolean by config {
|
||||||
|
"org.ice4j.ice.harvest.DISABLE_LINK_LOCAL_ADDRESSES".from(configSource)
|
||||||
|
.transformedBy { !it }
|
||||||
|
"ice4j.harvest.use-link-local-addresses".from(configSource)
|
||||||
|
}
|
||||||
|
fun useLinkLocalAddresses() = useLinkLocalAddresses
|
||||||
|
|
||||||
|
val udpReceiveBufferSize: Int? by optionalconfig {
|
||||||
|
"org.ice4j.ice.harvest.AbstractUdpListener.SO_RCVBUF".from(configSource)
|
||||||
|
"ice4j.harvest.udp.receive-buffer-size".from(configSource)
|
||||||
|
}
|
||||||
|
fun udpReceiveBufferSize() = udpReceiveBufferSize
|
||||||
|
|
||||||
|
val useIpv6: Boolean by config {
|
||||||
|
"org.ice4j.ipv6.DISABLED".from(configSource)
|
||||||
|
.transformedBy { !it }
|
||||||
|
"ice4j.harvest.use-ipv6".from(configSource)
|
||||||
|
}
|
||||||
|
fun useIpv6() = useIpv6
|
||||||
|
|
||||||
|
val useDynamicPorts: Boolean by config {
|
||||||
|
"org.ice4j.ice.harvest.USE_DYNAMIC_HOST_HARVESTER".from(configSource)
|
||||||
|
"ice4j.harvest.udp.use-dynamic-ports".from(configSource)
|
||||||
|
}
|
||||||
|
fun useDynamicPorts() = useDynamicPorts
|
||||||
|
|
||||||
|
val timeout: Duration by config {
|
||||||
|
"org.ice4j.ice.harvest.HARVESTING_TIMEOUT".from(configSource)
|
||||||
|
.convertFrom<Long> { Duration.ofSeconds(it) }
|
||||||
|
"ice4j.harvest.timeout".from(configSource)
|
||||||
|
}
|
||||||
|
fun timeout() = timeout
|
||||||
|
|
||||||
|
val stunMappingCandidateHarvesterAddresses: List<String> by config {
|
||||||
|
"org.ice4j.ice.harvest.STUN_MAPPING_HARVESTER_ADDRESSES".from(configSource)
|
||||||
|
.convertFrom<String> { it.split(",") }
|
||||||
|
"ice4j.harvest.mapping.stun.addresses".from(configSource)
|
||||||
|
}
|
||||||
|
fun stunMappingCandidateHarvesterAddresses() = stunMappingCandidateHarvesterAddresses
|
||||||
|
|
||||||
|
val enableAwsHarvester: Boolean by config {
|
||||||
|
"org.ice4j.ice.harvest.DISABLE_AWS_HARVESTER".from(configSource).transformedBy { !it }
|
||||||
|
"ice4j.harvest.mapping.aws.enabled".from(configSource)
|
||||||
|
}
|
||||||
|
fun enableAwsHarvester() = enableAwsHarvester
|
||||||
|
|
||||||
|
val forceAwsHarvester: Boolean by config {
|
||||||
|
"org.ice4j.ice.harvest.FORCE_AWS_HARVESTER".from(configSource).transformedBy { !it }
|
||||||
|
"ice4j.harvest.mapping.aws.force".from(configSource)
|
||||||
|
}
|
||||||
|
fun forceAwsHarvester() = enableAwsHarvester
|
||||||
|
|
||||||
|
private val legacyNatHarvesterLocalAddress: String? by optionalconfig {
|
||||||
|
"org.ice4j.ice.harvest.NAT_HARVESTER_LOCAL_ADDRESS".from(configSource)
|
||||||
|
}
|
||||||
|
|
||||||
|
private val legacyNatHarvesterPublicAddress: String? by optionalconfig {
|
||||||
|
"org.ice4j.ice.harvest.NAT_HARVESTER_PUBLIC_ADDRESS".from(configSource)
|
||||||
|
}
|
||||||
|
|
||||||
|
private val staticMappingsFromNewConfig: Set<StaticMapping> by config {
|
||||||
|
"ice4j.harvest.mapping.static-mappings".from(configSource)
|
||||||
|
.convertFrom<List<Config>> { cfg ->
|
||||||
|
cfg.map {
|
||||||
|
val localPort = if (it.hasPath("local-port")) it.getInt("local-port") else null
|
||||||
|
val publicPort = if (it.hasPath("public-port")) it.getInt("public-port") else null
|
||||||
|
if ((localPort == null || publicPort == null) && localPort != publicPort) {
|
||||||
|
throw ConfigException.UnableToRetrieve.ConditionNotMet(
|
||||||
|
"Inconsistent value for local-port and public-port, both must be present or both missing."
|
||||||
|
)
|
||||||
|
}
|
||||||
|
StaticMapping(
|
||||||
|
localAddress = it.getString("local-address"),
|
||||||
|
publicAddress = it.getString("public-address"),
|
||||||
|
localPort = localPort,
|
||||||
|
publicPort = publicPort,
|
||||||
|
name = if (it.hasPath("name")) it.getString("name") else null
|
||||||
|
)
|
||||||
|
}.toSet()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
val staticMappings: Set<StaticMapping> = let {
|
||||||
|
if (legacyNatHarvesterLocalAddress != null && legacyNatHarvesterPublicAddress != null) {
|
||||||
|
setOf(
|
||||||
|
StaticMapping(legacyNatHarvesterLocalAddress!!, legacyNatHarvesterPublicAddress!!),
|
||||||
|
*staticMappingsFromNewConfig.toTypedArray()
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
staticMappingsFromNewConfig
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
data class StaticMapping(
|
||||||
|
val localAddress: String,
|
||||||
|
val publicAddress: String,
|
||||||
|
val localPort: Int? = null,
|
||||||
|
val publicPort: Int? = null,
|
||||||
|
val name: String? = null
|
||||||
|
)
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
@JvmField
|
||||||
|
val config = HarvestConfig()
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,104 @@
|
|||||||
|
/*
|
||||||
|
* 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.TransportAddress
|
||||||
|
import org.ice4j.ice.CandidateExtendedType
|
||||||
|
import org.ice4j.ice.Component
|
||||||
|
import org.ice4j.ice.HostCandidate
|
||||||
|
import org.ice4j.ice.LocalCandidate
|
||||||
|
import org.ice4j.ice.ServerReflexiveCandidate
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A [CandidateHarvester] which maps existing local [HostCandidate]s to new candidates.
|
||||||
|
*/
|
||||||
|
abstract class MappingCandidateHarvester @JvmOverloads constructor(
|
||||||
|
val name: String,
|
||||||
|
/**
|
||||||
|
* Whether this harvester should match the port of the public address.
|
||||||
|
*
|
||||||
|
* When [matchPort] is enabled, mapping candidates will be added only when the local host candidate's address and
|
||||||
|
* port match the public (mask) address, and the public (mask) address's port will be used.
|
||||||
|
*
|
||||||
|
* When [matchPort] is disabled, mapping candidates will be added whenever the local host candidate's inet address
|
||||||
|
* matches the public (mask) address, and the host candidate port will be preserved.
|
||||||
|
*/
|
||||||
|
val matchPort: Boolean = false
|
||||||
|
) : AbstractCandidateHarvester() {
|
||||||
|
abstract val face: TransportAddress?
|
||||||
|
abstract val mask: TransportAddress?
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Checks whether the given [address] matches the public address of this harvester.
|
||||||
|
* only compares the inet address (since by default the port is not matched in [harvest]), but other implementations
|
||||||
|
* may chose to also compare the port.
|
||||||
|
*/
|
||||||
|
fun publicAddressMatches(address: TransportAddress): Boolean {
|
||||||
|
val mask = this.mask
|
||||||
|
return if (mask == null) {
|
||||||
|
false
|
||||||
|
} else {
|
||||||
|
mask.address == address.address && (!matchPort || mask.port == address.port)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Looks for existing [HostCandidate]s in [component] which match our local address ([face]) and creates
|
||||||
|
* associated [ServerReflexiveCandidate]s substituting [mask] for the address.
|
||||||
|
*
|
||||||
|
* @param component the [Component] that we'd like to harvest candidates for.
|
||||||
|
* @return the [LocalCandidate]s created and added to [component].
|
||||||
|
*/
|
||||||
|
override fun harvest(component: Component): Collection<LocalCandidate> {
|
||||||
|
val localAddress = face ?: return emptyList()
|
||||||
|
val publicAddress = mask ?: return emptyList()
|
||||||
|
|
||||||
|
// Report the LocalCandidates gathered by this CandidateHarvester so
|
||||||
|
// that the harvest is sure to be considered successful.
|
||||||
|
val candidates = mutableSetOf<LocalCandidate>()
|
||||||
|
component.localCandidates
|
||||||
|
.filter {
|
||||||
|
it is HostCandidate &&
|
||||||
|
it.transportAddress.hostAddress == localAddress.hostAddress &&
|
||||||
|
it.transport == localAddress.transport &&
|
||||||
|
(!matchPort || it.transportAddress.port == localAddress.port)
|
||||||
|
}.forEach { hostCandidate ->
|
||||||
|
hostCandidate as HostCandidate
|
||||||
|
|
||||||
|
val mappedAddress = TransportAddress(
|
||||||
|
publicAddress.hostAddress,
|
||||||
|
if (matchPort) publicAddress.port else hostCandidate.hostAddress.port,
|
||||||
|
hostCandidate.hostAddress.transport
|
||||||
|
)
|
||||||
|
val mappedCandidate = ServerReflexiveCandidate(
|
||||||
|
mappedAddress,
|
||||||
|
hostCandidate,
|
||||||
|
hostCandidate.stunServerAddress,
|
||||||
|
CandidateExtendedType.STATICALLY_MAPPED_CANDIDATE
|
||||||
|
)
|
||||||
|
if (hostCandidate.isSSL) mappedCandidate.isSSL = true
|
||||||
|
|
||||||
|
// Try to add the candidate to the component and only then add it to the harvest.
|
||||||
|
if (!candidates.contains(mappedCandidate) && component.addLocalCandidate(mappedCandidate)) {
|
||||||
|
candidates.add(mappedCandidate)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return candidates
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,29 @@
|
|||||||
|
package org.ice4j.ice.harvest
|
||||||
|
|
||||||
|
import org.ice4j.TransportAddress
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Uses a predefined static mask in order to generate [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.
|
||||||
|
*
|
||||||
|
* Every time the [.harvest] 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.
|
||||||
|
*
|
||||||
|
* 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.
|
||||||
|
*
|
||||||
|
* This harvester is instant and does not introduce any harvesting latency.
|
||||||
|
*
|
||||||
|
* @author Emil Ivov
|
||||||
|
*/
|
||||||
|
class StaticMappingCandidateHarvester @JvmOverloads constructor(
|
||||||
|
/** The public address (aka mask) */
|
||||||
|
override val mask: TransportAddress,
|
||||||
|
/** The local address (aka face) */
|
||||||
|
override val face: TransportAddress,
|
||||||
|
name: String? = null,
|
||||||
|
matchPort: Boolean = false
|
||||||
|
) : MappingCandidateHarvester(name ?: "static_mapping", matchPort) {
|
||||||
|
override fun toString() = "${javaClass.name}(face=$face, mask=$mask)"
|
||||||
|
}
|
||||||
94
src/main/resources/reference.conf
Normal file
94
src/main/resources/reference.conf
Normal file
@ -0,0 +1,94 @@
|
|||||||
|
ice4j {
|
||||||
|
ice {
|
||||||
|
max-check-list-size = 100
|
||||||
|
// The amount of time that we must wait after ICE processing enters a COMPLETED state before we free candidates
|
||||||
|
// and move into the TERMINATED state.
|
||||||
|
termination-delay = 3 seconds
|
||||||
|
}
|
||||||
|
|
||||||
|
// The value of the SOFTWARE attribute that ice4j should include in all outgoing messages. Set to the empty string to
|
||||||
|
// not include a SOFTWARE attribute.
|
||||||
|
software = "ice4j.org"
|
||||||
|
|
||||||
|
// Whether the per-component merging socket should be enabled by default (the default value can be
|
||||||
|
// overridden with the [Agent] API).
|
||||||
|
// If enabled, the user of the library must use the socket instance provided by [Component.getSocket]. Otherwise,
|
||||||
|
// the socket instance from the desired [CandidatePair] must be used.
|
||||||
|
use-component-socket = true
|
||||||
|
|
||||||
|
consent-freshness {
|
||||||
|
// How often a STUN Binding request used for consent freshness check will be sent.
|
||||||
|
interval = 15 seconds
|
||||||
|
// The amount of time without a valid STUN Binding response after which a STUN Binding request is to be
|
||||||
|
// retransmitted according to `STUN Usage for Consent Freshness` (RFC7675).
|
||||||
|
// This is the original value for back-off strategy, while `max-wait-interval` sets the upper limit.
|
||||||
|
original-wait-interval = 500 milliseconds
|
||||||
|
// The amount of time without a valid STUN Binding response after which a STUN Binding request is to be
|
||||||
|
// retransmitted according to `STUN Usage for Consent Freshness` (RFC7675).
|
||||||
|
// This is the final value for the back-off strategy, while `original-wait-interval` defines the initial interval for
|
||||||
|
// the first request sent.
|
||||||
|
max-wait-interval = 500 milliseconds
|
||||||
|
// 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 `STUN Usage for Consent Freshness` (RFC7675).
|
||||||
|
max-retransmissions = 30
|
||||||
|
// Whether to randomize the period between any two checks between 0.8 and 1.2 of the configured interval as
|
||||||
|
// recommended in RFC7675 Section 5.1. We keep this configurable in case the previous behavior is desired.
|
||||||
|
randomize-interval = true
|
||||||
|
}
|
||||||
|
|
||||||
|
// Configuration related to harvesting (aka gathering) of local candidates.
|
||||||
|
harvest {
|
||||||
|
// Whether to harvest IPv6 addresses.
|
||||||
|
use-ipv6 = true
|
||||||
|
// Whether to use link-local addresses when harvesting candidates.
|
||||||
|
use-link-local-addresses = true
|
||||||
|
|
||||||
|
// How long to wait for an individual harvest before timing out.
|
||||||
|
timeout = 15 seconds
|
||||||
|
|
||||||
|
// Configuration for the "single port" UDP harvester.
|
||||||
|
udp {
|
||||||
|
// The size in bytes to set on the UDP socket (SO_RCVBUF). If not specified, the default from the OS will be used.
|
||||||
|
#receive-buffer-size = 10485760
|
||||||
|
|
||||||
|
// Whether to allocate ephemeral ports for local candidates. This is the default value, and can be overridden
|
||||||
|
// for Agent instances.
|
||||||
|
use-dynamic-ports = true
|
||||||
|
}
|
||||||
|
|
||||||
|
// Configuration for the set of "mapping" harvesters.
|
||||||
|
mapping {
|
||||||
|
aws {
|
||||||
|
enabled = true
|
||||||
|
// Whether to use the AWS harvester even when the automatic detection indicates that we are not running in AWS.
|
||||||
|
force = false
|
||||||
|
}
|
||||||
|
stun {
|
||||||
|
addresses = [ ]
|
||||||
|
# addresses = [ "stun1.example.com:5379", "stun2.example.com:443" ]
|
||||||
|
}
|
||||||
|
// Pre-configured mappings
|
||||||
|
static-mappings = [
|
||||||
|
#{
|
||||||
|
# // This results in a candidate for 1.2.3.4:20000 being added whenever a host candidate for
|
||||||
|
# // 10.10.0.123:10000 exists.
|
||||||
|
# local-address = "10.10.0.123"
|
||||||
|
# public-address = "1.2.3.4"
|
||||||
|
# // The ports are optional, but need to either both be provided or both not provided.
|
||||||
|
# local-port = 10000
|
||||||
|
# public-port = 20000
|
||||||
|
# // Optional name
|
||||||
|
# name = "my-mapping-for-a-specific-port"
|
||||||
|
#},
|
||||||
|
#{
|
||||||
|
# // This results in a candidate for 1.2.3.4:PORT being added whenever a host candidate for 10.10.0.123
|
||||||
|
# // exists, where the PORT is the port of the existing host candidate.
|
||||||
|
# local-address = "10.10.0.123"
|
||||||
|
# public-address = "1.2.3.4"
|
||||||
|
# // Optional name
|
||||||
|
# name = "my-mapping-for-all-ports"
|
||||||
|
#}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -19,18 +19,18 @@ package org.ice4j;
|
|||||||
|
|
||||||
import java.util.*;
|
import java.util.*;
|
||||||
|
|
||||||
import junit.framework.*;
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
import org.ice4j.message.*;
|
import org.ice4j.message.*;
|
||||||
import org.ice4j.socket.*;
|
import org.ice4j.socket.*;
|
||||||
import org.ice4j.stack.*;
|
import org.ice4j.stack.*;
|
||||||
|
import org.junit.jupiter.api.*;
|
||||||
/**
|
/**
|
||||||
* Test event dispatching for both client and server.
|
* Test event dispatching for both client and server.
|
||||||
*`
|
*`
|
||||||
* @author Emil Ivov
|
* @author Emil Ivov
|
||||||
*/
|
*/
|
||||||
public class MessageEventDispatchingTest extends TestCase
|
public class MessageEventDispatchingTest
|
||||||
{
|
{
|
||||||
/**
|
/**
|
||||||
* The stack that we are using for the tests.
|
* The stack that we are using for the tests.
|
||||||
@ -95,10 +95,9 @@ public class MessageEventDispatchingTest extends TestCase
|
|||||||
*
|
*
|
||||||
* @throws Exception if anything goes wrong.
|
* @throws Exception if anything goes wrong.
|
||||||
*/
|
*/
|
||||||
protected void setUp() throws Exception
|
@BeforeEach
|
||||||
|
public void setUp() throws Exception
|
||||||
{
|
{
|
||||||
super.setUp();
|
|
||||||
|
|
||||||
stunStack = new StunStack();
|
stunStack = new StunStack();
|
||||||
|
|
||||||
clientSock = new IceUdpSocketWrapper(
|
clientSock = new IceUdpSocketWrapper(
|
||||||
@ -126,7 +125,8 @@ public class MessageEventDispatchingTest extends TestCase
|
|||||||
*
|
*
|
||||||
* @throws Exception if anything goes wrong.
|
* @throws Exception if anything goes wrong.
|
||||||
*/
|
*/
|
||||||
protected void tearDown() throws Exception
|
@AfterEach
|
||||||
|
public void tearDown() throws Exception
|
||||||
{
|
{
|
||||||
stunStack.removeSocket(clientAddress);
|
stunStack.removeSocket(clientAddress);
|
||||||
stunStack.removeSocket(serverAddress);
|
stunStack.removeSocket(serverAddress);
|
||||||
@ -138,8 +138,6 @@ public class MessageEventDispatchingTest extends TestCase
|
|||||||
|
|
||||||
requestCollector = null;
|
requestCollector = null;
|
||||||
responseCollector = null;
|
responseCollector = null;
|
||||||
|
|
||||||
super.tearDown();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -147,6 +145,7 @@ public class MessageEventDispatchingTest extends TestCase
|
|||||||
*
|
*
|
||||||
* @throws Exception upon a stun failure
|
* @throws Exception upon a stun failure
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testClientTransactionTimeouts() throws Exception
|
public void testClientTransactionTimeouts() throws Exception
|
||||||
{
|
{
|
||||||
String oldRetransValue = System.getProperty(
|
String oldRetransValue = System.getProperty(
|
||||||
@ -156,13 +155,11 @@ public class MessageEventDispatchingTest extends TestCase
|
|||||||
responseCollector);
|
responseCollector);
|
||||||
responseCollector.waitForTimeout();
|
responseCollector.waitForTimeout();
|
||||||
|
|
||||||
assertEquals(
|
assertEquals(1, responseCollector.receivedResponses.size(),
|
||||||
"No timeout was produced upon expiration of a client transaction",
|
"No timeout was produced upon expiration of a client transaction");
|
||||||
responseCollector.receivedResponses.size(), 1);
|
|
||||||
|
|
||||||
assertEquals(
|
assertEquals("timeout", responseCollector.receivedResponses.get(0),
|
||||||
"No timeout was produced upon expiration of a client transaction",
|
"No timeout was produced upon expiration of a client transaction");
|
||||||
responseCollector.receivedResponses.get(0), "timeout");
|
|
||||||
|
|
||||||
//restore the retransmissions prop in case others are counting on
|
//restore the retransmissions prop in case others are counting on
|
||||||
//defaults.
|
//defaults.
|
||||||
@ -178,6 +175,7 @@ public class MessageEventDispatchingTest extends TestCase
|
|||||||
*
|
*
|
||||||
* @throws java.lang.Exception upon any failure
|
* @throws java.lang.Exception upon any failure
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testEventDispatchingUponIncomingRequests() throws Exception
|
public void testEventDispatchingUponIncomingRequests() throws Exception
|
||||||
{
|
{
|
||||||
//prepare to listen
|
//prepare to listen
|
||||||
@ -189,8 +187,8 @@ public class MessageEventDispatchingTest extends TestCase
|
|||||||
requestCollector.waitForRequest();
|
requestCollector.waitForRequest();
|
||||||
|
|
||||||
//verify
|
//verify
|
||||||
assertTrue("No MessageEvents have been dispatched",
|
assertEquals(1, requestCollector.receivedRequests.size(),
|
||||||
requestCollector.receivedRequests.size() == 1);
|
"No MessageEvents have been dispatched");
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -199,6 +197,7 @@ public class MessageEventDispatchingTest extends TestCase
|
|||||||
*
|
*
|
||||||
* @throws java.lang.Exception upon any failure
|
* @throws java.lang.Exception upon any failure
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testSelectiveEventDispatchingUponIncomingRequests()
|
public void testSelectiveEventDispatchingUponIncomingRequests()
|
||||||
throws Exception
|
throws Exception
|
||||||
{
|
{
|
||||||
@ -216,19 +215,17 @@ public class MessageEventDispatchingTest extends TestCase
|
|||||||
requestCollector2.waitForRequest();
|
requestCollector2.waitForRequest();
|
||||||
|
|
||||||
//verify
|
//verify
|
||||||
assertTrue(
|
assertEquals(0, requestCollector.receivedRequests.size(),
|
||||||
"A MessageEvent was received by a non-interested selective listener",
|
"A MessageEvent was received by a non-interested selective listener");
|
||||||
requestCollector.receivedRequests.size() == 0);
|
assertEquals(1, requestCollector2.receivedRequests.size(),
|
||||||
assertTrue(
|
"No MessageEvents have been dispatched for a selective listener");
|
||||||
"No MessageEvents have been dispatched for a selective listener",
|
|
||||||
requestCollector2.receivedRequests.size() == 1);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Makes sure that we receive response events.
|
* Makes sure that we receive response events.
|
||||||
* @throws Exception if we screw up.
|
* @throws Exception if we screw up.
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testServerResponseRetransmissions() throws Exception
|
public void testServerResponseRetransmissions() throws Exception
|
||||||
{
|
{
|
||||||
//prepare to listen
|
//prepare to listen
|
||||||
@ -249,15 +246,14 @@ public class MessageEventDispatchingTest extends TestCase
|
|||||||
responseCollector.waitForResponse();
|
responseCollector.waitForResponse();
|
||||||
|
|
||||||
//verify that we got the response.
|
//verify that we got the response.
|
||||||
assertTrue(
|
assertEquals(1, responseCollector.receivedResponses.size(),
|
||||||
"There were no retransmissions of a binding response",
|
"There were no retransmissions of a binding response");
|
||||||
responseCollector.receivedResponses.size() == 1 );
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* A utility class we use to collect incoming requests.
|
* A utility class we use to collect incoming requests.
|
||||||
*/
|
*/
|
||||||
private class PlainRequestCollector implements RequestListener
|
private static class PlainRequestCollector implements RequestListener
|
||||||
{
|
{
|
||||||
/** all requests we've received so far. */
|
/** all requests we've received so far. */
|
||||||
public final Vector<StunMessageEvent> receivedRequests = new Vector<>();
|
public final Vector<StunMessageEvent> receivedRequests = new Vector<>();
|
||||||
|
|||||||
@ -243,20 +243,4 @@ public class MsgFixture
|
|||||||
0x00, 0x20, 0x00, 0x21,
|
0x00, 0x20, 0x00, 0x21,
|
||||||
0x00, 0x22, 0x00, 0x22
|
0x00, 0x22, 0x00, 0x22
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
public MsgFixture()
|
|
||||||
{
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setUp()
|
|
||||||
{
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
public void tearDown()
|
|
||||||
{
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,62 +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;
|
|
||||||
|
|
||||||
import junit.framework.*;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Contains pseudo TCP tests.
|
|
||||||
*
|
|
||||||
* @author Pawel Domas
|
|
||||||
*/
|
|
||||||
public class PseudoTcpTestSuite
|
|
||||||
extends TestCase
|
|
||||||
{
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Creates a new instance of the suite
|
|
||||||
*
|
|
||||||
* @param s test name
|
|
||||||
*/
|
|
||||||
public PseudoTcpTestSuite(String s)
|
|
||||||
{
|
|
||||||
super(s);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns the suite of tests to run.
|
|
||||||
* @return the suite of tests to run.
|
|
||||||
*/
|
|
||||||
public static Test suite()
|
|
||||||
{
|
|
||||||
TestSuite suite = new TestSuite();
|
|
||||||
|
|
||||||
// byte fifo buffer
|
|
||||||
suite.addTestSuite(org.ice4j.pseudotcp.util.ByteFifoBufferTest.class);
|
|
||||||
// transfer
|
|
||||||
suite.addTestSuite(org.ice4j.pseudotcp.PseudoTcpTestTransfer.class);
|
|
||||||
// ping pong
|
|
||||||
suite.addTestSuite(org.ice4j.pseudotcp.PseudoTcpTestPingPong.class);
|
|
||||||
// receive window
|
|
||||||
suite.addTestSuite(org.ice4j.pseudotcp.PseudoTcpTestRecvWindow.class);
|
|
||||||
// stream
|
|
||||||
suite.addTestSuite(org.ice4j.pseudotcp.PseudoTcpStreamTest.class);
|
|
||||||
|
|
||||||
return suite;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,94 +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;
|
|
||||||
|
|
||||||
import junit.framework.*;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Contains all tests in the ice4j project.
|
|
||||||
*
|
|
||||||
* @author Emil Ivov
|
|
||||||
*/
|
|
||||||
public class StunTestSuite
|
|
||||||
extends TestCase
|
|
||||||
{
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Creates a new instance of the suite
|
|
||||||
*
|
|
||||||
* @param s test name
|
|
||||||
*/
|
|
||||||
public StunTestSuite(String s)
|
|
||||||
{
|
|
||||||
super(s);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns the suite of tests to run.
|
|
||||||
* @return the suite of tests to run.
|
|
||||||
*/
|
|
||||||
public static Test suite()
|
|
||||||
{
|
|
||||||
TestSuite suite = new TestSuite();
|
|
||||||
|
|
||||||
//attributes
|
|
||||||
suite.addTestSuite(org.ice4j.attribute.
|
|
||||||
AddressAttributeTest.class);
|
|
||||||
suite.addTestSuite(org.ice4j.attribute.
|
|
||||||
XorOnlyTest.class);
|
|
||||||
suite.addTestSuite(org.ice4j.attribute.
|
|
||||||
AttributeDecoderTest.class);
|
|
||||||
suite.addTestSuite(org.ice4j.attribute.
|
|
||||||
ChangeRequestAttributeTest.class);
|
|
||||||
suite.addTestSuite(org.ice4j.attribute.
|
|
||||||
ErrorCodeAttributeTest.class);
|
|
||||||
suite.addTestSuite(org.ice4j.attribute.
|
|
||||||
UnknownAttributesAttributeTest.class);
|
|
||||||
suite.addTestSuite(org.ice4j.attribute.
|
|
||||||
SoftwareAttributeTest.class);
|
|
||||||
suite.addTestSuite(org.ice4j.attribute.
|
|
||||||
OptionalAttributeAttributeTest.class);
|
|
||||||
suite.addTestSuite(org.ice4j.attribute.
|
|
||||||
ConnectionIdAttributeTest.class);
|
|
||||||
suite.addTestSuite(org.ice4j.attribute.
|
|
||||||
RequestedAddressFamilyAttributeTest.class);
|
|
||||||
suite.addTestSuite(org.ice4j.attribute.UsernameAttributeTest.class);
|
|
||||||
suite.addTestSuite(org.ice4j.attribute.NonceAttributeTest.class);
|
|
||||||
suite.addTestSuite(org.ice4j.attribute.RealmAttributeTest.class);
|
|
||||||
|
|
||||||
//messages
|
|
||||||
suite.addTestSuite(org.ice4j.message.MessageFactoryTest.class);
|
|
||||||
suite.addTestSuite(org.ice4j.message.MessageTest.class);
|
|
||||||
|
|
||||||
//stack
|
|
||||||
suite.addTestSuite(org.ice4j.stack.ShallowStackTest.class);
|
|
||||||
|
|
||||||
//event dispatching
|
|
||||||
suite.addTestSuite(org.ice4j.MessageEventDispatchingTest.class);
|
|
||||||
|
|
||||||
//transactions
|
|
||||||
suite.addTestSuite(org.ice4j.TransactionSupportTests.class);
|
|
||||||
|
|
||||||
//client
|
|
||||||
suite.addTestSuite(org.ice4j.stunclient.StunAddressDiscovererTest.class);
|
|
||||||
suite.addTestSuite(org.ice4j.stunclient.StunAddressDiscovererTest_v6.class);
|
|
||||||
suite.addTestSuite(org.ice4j.stunclient.StunAddressDiscovererTest_v4v6.class);
|
|
||||||
|
|
||||||
return suite;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
47
src/test/java/org/ice4j/TestExecutionListener.java
Normal file
47
src/test/java/org/ice4j/TestExecutionListener.java
Normal file
@ -0,0 +1,47 @@
|
|||||||
|
/*
|
||||||
|
* 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;
|
||||||
|
|
||||||
|
import org.jitsi.metaconfig.*;
|
||||||
|
import org.junit.platform.launcher.*;
|
||||||
|
|
||||||
|
public class TestExecutionListener implements org.junit.platform.launcher.TestExecutionListener {
|
||||||
|
private static boolean initialized = false;
|
||||||
|
|
||||||
|
private static void beforeAll()
|
||||||
|
{
|
||||||
|
// Disable config caching.
|
||||||
|
MetaconfigSettings.Companion.setCacheEnabled(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
public TestExecutionListener()
|
||||||
|
{}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void executionStarted(TestIdentifier testIdentifier)
|
||||||
|
{
|
||||||
|
synchronized (TestExecutionListener.class)
|
||||||
|
{
|
||||||
|
if (!initialized)
|
||||||
|
{
|
||||||
|
beforeAll();
|
||||||
|
initialized = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -17,14 +17,15 @@
|
|||||||
*/
|
*/
|
||||||
package org.ice4j;
|
package org.ice4j;
|
||||||
|
|
||||||
|
import java.net.*;
|
||||||
import java.util.*;
|
import java.util.*;
|
||||||
|
|
||||||
import junit.framework.*;
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
import org.ice4j.message.*;
|
import org.ice4j.message.*;
|
||||||
import org.ice4j.socket.*;
|
import org.ice4j.socket.*;
|
||||||
import org.ice4j.stack.*;
|
import org.ice4j.stack.*;
|
||||||
|
import org.junit.jupiter.api.*;
|
||||||
/**
|
/**
|
||||||
* Test how client and server behave, how they recognize/adopt messages and
|
* Test how client and server behave, how they recognize/adopt messages and
|
||||||
* how they both handle retransmissions (i.e. client transactions should make
|
* how they both handle retransmissions (i.e. client transactions should make
|
||||||
@ -32,19 +33,17 @@ import org.ice4j.stack.*;
|
|||||||
*
|
*
|
||||||
* @author Emil Ivov
|
* @author Emil Ivov
|
||||||
*/
|
*/
|
||||||
public class TransactionSupportTests extends TestCase
|
public class TransactionSupportTests
|
||||||
{
|
{
|
||||||
/**
|
/**
|
||||||
* The client address we use for this test.
|
* The client address we use for this test.
|
||||||
*/
|
*/
|
||||||
TransportAddress clientAddress
|
TransportAddress clientAddress;
|
||||||
= new TransportAddress("127.0.0.1", 5216, Transport.UDP);
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The client address we use for this test.
|
* The client address we use for this test.
|
||||||
*/
|
*/
|
||||||
TransportAddress serverAddress
|
TransportAddress serverAddress;
|
||||||
= new TransportAddress("127.0.0.1", 5255, Transport.UDP);
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The socket the client uses in this test.
|
* The socket the client uses in this test.
|
||||||
@ -86,15 +85,19 @@ public class TransactionSupportTests extends TestCase
|
|||||||
*
|
*
|
||||||
* @throws Exception if something goes bad.
|
* @throws Exception if something goes bad.
|
||||||
*/
|
*/
|
||||||
protected void setUp()
|
@BeforeEach
|
||||||
|
public void setUp()
|
||||||
throws Exception
|
throws Exception
|
||||||
{
|
{
|
||||||
super.setUp();
|
|
||||||
|
|
||||||
clientSock = new IceUdpSocketWrapper(
|
clientSock = new IceUdpSocketWrapper(
|
||||||
new SafeCloseDatagramSocket(clientAddress));
|
new SafeCloseDatagramSocket(new InetSocketAddress("127.0.0.1", 0)));
|
||||||
serverSock = new IceUdpSocketWrapper(
|
serverSock = new IceUdpSocketWrapper(
|
||||||
new SafeCloseDatagramSocket(serverAddress));
|
new SafeCloseDatagramSocket(new InetSocketAddress("127.0.0.1", 0)));
|
||||||
|
|
||||||
|
clientAddress
|
||||||
|
= new TransportAddress("127.0.0.1", clientSock.getLocalPort(), Transport.UDP);
|
||||||
|
serverAddress
|
||||||
|
= new TransportAddress("127.0.0.1", serverSock.getLocalPort(), Transport.UDP);
|
||||||
|
|
||||||
stunStack = new StunStack();
|
stunStack = new StunStack();
|
||||||
stunStack.addSocket(clientSock);
|
stunStack.addSocket(clientSock);
|
||||||
@ -129,7 +132,8 @@ public class TransactionSupportTests extends TestCase
|
|||||||
*
|
*
|
||||||
* @throws Exception if something does not go as planned.
|
* @throws Exception if something does not go as planned.
|
||||||
*/
|
*/
|
||||||
protected void tearDown()
|
@AfterEach
|
||||||
|
public void tearDown()
|
||||||
throws Exception
|
throws Exception
|
||||||
{
|
{
|
||||||
stunStack.removeSocket(clientAddress);
|
stunStack.removeSocket(clientAddress);
|
||||||
@ -156,8 +160,6 @@ public class TransactionSupportTests extends TestCase
|
|||||||
System.setProperty(
|
System.setProperty(
|
||||||
StackProperties.FIRST_CTRAN_RETRANS_AFTER,
|
StackProperties.FIRST_CTRAN_RETRANS_AFTER,
|
||||||
"");
|
"");
|
||||||
|
|
||||||
super.tearDown();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -165,6 +167,7 @@ public class TransactionSupportTests extends TestCase
|
|||||||
*
|
*
|
||||||
* @throws java.lang.Exception upon any failure
|
* @throws java.lang.Exception upon any failure
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testClientRetransmissions() throws Exception
|
public void testClientRetransmissions() throws Exception
|
||||||
{
|
{
|
||||||
String oldRetransValue = System.getProperty(
|
String oldRetransValue = System.getProperty(
|
||||||
@ -195,11 +198,10 @@ public class TransactionSupportTests extends TestCase
|
|||||||
= requestCollector.getRequestsForTransaction(
|
= requestCollector.getRequestsForTransaction(
|
||||||
bindingRequest.getTransactionID());
|
bindingRequest.getTransactionID());
|
||||||
|
|
||||||
assertTrue("No retransmissions of the request have been received",
|
assertTrue(reqs.size() > 1,
|
||||||
reqs.size() > 1);
|
"No retransmissions of the request have been received");
|
||||||
assertTrue("The binding request has been retransmitted more than it "
|
assertTrue(reqs.size() >= 3,
|
||||||
+"should have!",
|
"The binding request has been retransmitted more than it should have!");
|
||||||
reqs.size() >= 3);
|
|
||||||
|
|
||||||
//restore the retransmissions prop in case others are counting on
|
//restore the retransmissions prop in case others are counting on
|
||||||
//defaults.
|
//defaults.
|
||||||
@ -222,6 +224,7 @@ public class TransactionSupportTests extends TestCase
|
|||||||
*
|
*
|
||||||
* @throws Exception if anything goes wrong.
|
* @throws Exception if anything goes wrong.
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testServerRetransmissionHiding() throws Exception
|
public void testServerRetransmissionHiding() throws Exception
|
||||||
{
|
{
|
||||||
String oldRetransValue = System.getProperty(
|
String oldRetransValue = System.getProperty(
|
||||||
@ -244,9 +247,8 @@ public class TransactionSupportTests extends TestCase
|
|||||||
= requestCollector.getRequestsForTransaction(
|
= requestCollector.getRequestsForTransaction(
|
||||||
bindingRequest.getTransactionID());
|
bindingRequest.getTransactionID());
|
||||||
|
|
||||||
assertTrue(
|
assertTrue(reqs.size() <= 1,
|
||||||
"Retransmissions of a binding request were propagated "
|
"Retransmissions of a binding request were propagated to the server");
|
||||||
+ "to the server", reqs.size() <= 1 );
|
|
||||||
|
|
||||||
//restore the retransmissions prop in case others are counting on
|
//restore the retransmissions prop in case others are counting on
|
||||||
//defaults.
|
//defaults.
|
||||||
@ -264,6 +266,7 @@ public class TransactionSupportTests extends TestCase
|
|||||||
*
|
*
|
||||||
* @throws Exception if we screw up.
|
* @throws Exception if we screw up.
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testServerResponseRetransmissions() throws Exception
|
public void testServerResponseRetransmissions() throws Exception
|
||||||
{
|
{
|
||||||
String oldRetransValue = System.getProperty(
|
String oldRetransValue = System.getProperty(
|
||||||
@ -303,10 +306,9 @@ public class TransactionSupportTests extends TestCase
|
|||||||
Thread.sleep(500);
|
Thread.sleep(500);
|
||||||
|
|
||||||
//verify that we received a fair number of retransmitted responses.
|
//verify that we received a fair number of retransmitted responses.
|
||||||
assertTrue(
|
assertTrue(responseCollector.receivedResponses.size() < 3,
|
||||||
"There were too few retransmissions of a binding response: "
|
"There were too few retransmissions of a binding response: "
|
||||||
+responseCollector.receivedResponses.size(),
|
+responseCollector.receivedResponses.size());
|
||||||
responseCollector.receivedResponses.size() < 3 );
|
|
||||||
|
|
||||||
//restore the retransmissions prop in case others are counting on
|
//restore the retransmissions prop in case others are counting on
|
||||||
//defaults.
|
//defaults.
|
||||||
@ -323,6 +325,7 @@ public class TransactionSupportTests extends TestCase
|
|||||||
* A (very) weak test, verifying that transaction IDs are unique.
|
* A (very) weak test, verifying that transaction IDs are unique.
|
||||||
* @throws Exception in case we feel like it.
|
* @throws Exception in case we feel like it.
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testUniqueIDs() throws Exception
|
public void testUniqueIDs() throws Exception
|
||||||
{
|
{
|
||||||
stunStack.addRequestListener(serverAddress, requestCollector);
|
stunStack.addRequestListener(serverAddress, requestCollector);
|
||||||
@ -366,10 +369,11 @@ public class TransactionSupportTests extends TestCase
|
|||||||
|
|
||||||
StunMessageEvent evt2 = reqs2.get(0);
|
StunMessageEvent evt2 = reqs2.get(0);
|
||||||
|
|
||||||
assertFalse(
|
assertFalse(Arrays.equals(
|
||||||
"Consecutive requests were assigned the same transaction id",
|
evt1.getMessage().getTransactionID(),
|
||||||
Arrays.equals( evt1.getMessage().getTransactionID(),
|
evt2.getMessage().getTransactionID()),
|
||||||
evt2.getMessage().getTransactionID()));
|
"Consecutive requests were assigned the same transaction id"
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -378,6 +382,7 @@ public class TransactionSupportTests extends TestCase
|
|||||||
*
|
*
|
||||||
* @throws Exception if the gods so decide.
|
* @throws Exception if the gods so decide.
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testClientTransactionMaxRetransmisssionsConfigurationParameter()
|
public void testClientTransactionMaxRetransmisssionsConfigurationParameter()
|
||||||
throws Exception
|
throws Exception
|
||||||
{
|
{
|
||||||
@ -404,13 +409,10 @@ public class TransactionSupportTests extends TestCase
|
|||||||
= requestCollector.getRequestsForTransaction(
|
= requestCollector.getRequestsForTransaction(
|
||||||
bindingRequest.getTransactionID());
|
bindingRequest.getTransactionID());
|
||||||
|
|
||||||
assertTrue("No retransmissions of the request have been received",
|
assertTrue(reqs.size() > 1,
|
||||||
reqs.size() > 1);
|
"No retransmissions of the request have been received");
|
||||||
assertEquals(
|
assertEquals(3, reqs.size(),
|
||||||
"The MAX_RETRANSMISSIONS param was not taken into account!",
|
"The MAX_RETRANSMISSIONS param was not taken into account!");
|
||||||
reqs.size(),
|
|
||||||
3);
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -419,6 +421,7 @@ public class TransactionSupportTests extends TestCase
|
|||||||
*
|
*
|
||||||
* @throws Exception if we are having a bad day.
|
* @throws Exception if we are having a bad day.
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testMinWaitIntervalConfigurationParameter()
|
public void testMinWaitIntervalConfigurationParameter()
|
||||||
throws Exception
|
throws Exception
|
||||||
{
|
{
|
||||||
@ -442,8 +445,8 @@ public class TransactionSupportTests extends TestCase
|
|||||||
//verify
|
//verify
|
||||||
Vector<?> reqs = requestCollector.getRequestsForTransaction(
|
Vector<?> reqs = requestCollector.getRequestsForTransaction(
|
||||||
bindingRequest.getTransactionID());
|
bindingRequest.getTransactionID());
|
||||||
assertTrue("A retransmissions of the request was sent too early",
|
assertTrue(reqs.size() < 2,
|
||||||
reqs.size() < 2);
|
"A retransmissions of the request was sent too early");
|
||||||
|
|
||||||
//wait for a send
|
//wait for a send
|
||||||
Thread.sleep(110);
|
Thread.sleep(110);
|
||||||
@ -452,8 +455,8 @@ public class TransactionSupportTests extends TestCase
|
|||||||
bindingRequest.getTransactionID());
|
bindingRequest.getTransactionID());
|
||||||
|
|
||||||
//verify
|
//verify
|
||||||
assertEquals("A retransmissions of the request was not sent",
|
assertEquals(2, reqs.size(),
|
||||||
2, reqs.size());
|
"A retransmissions of the request was not sent");
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -462,6 +465,7 @@ public class TransactionSupportTests extends TestCase
|
|||||||
*
|
*
|
||||||
* @throws Exception if the gods so decide.
|
* @throws Exception if the gods so decide.
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testMaxWaitIntervalConfigurationParameter()
|
public void testMaxWaitIntervalConfigurationParameter()
|
||||||
throws Exception
|
throws Exception
|
||||||
{
|
{
|
||||||
@ -481,40 +485,39 @@ public class TransactionSupportTests extends TestCase
|
|||||||
clientAddress,
|
clientAddress,
|
||||||
responseCollector);
|
responseCollector);
|
||||||
|
|
||||||
//wait a while
|
//wait until a response arrives
|
||||||
Thread.sleep(1200);
|
synchronized (responseCollector)
|
||||||
|
{
|
||||||
|
responseCollector.wait(5000);
|
||||||
|
}
|
||||||
|
|
||||||
//verify
|
//verify
|
||||||
Vector<StunMessageEvent> reqs
|
Vector<StunMessageEvent> reqs
|
||||||
= requestCollector.getRequestsForTransaction(
|
= requestCollector.getRequestsForTransaction(
|
||||||
bindingRequest.getTransactionID());
|
bindingRequest.getTransactionID());
|
||||||
assertEquals("Not all retransmissions were made for the expected period "
|
assertEquals(12, reqs.size(),
|
||||||
+"of time",
|
"Not all retransmissions were made for the expected period of time");
|
||||||
12,
|
|
||||||
reqs.size());
|
|
||||||
|
|
||||||
//wait for a send
|
//wait for a send
|
||||||
Thread.sleep(1800);
|
requestCollector.waitForRequest(1800);
|
||||||
|
|
||||||
//verify
|
//verify
|
||||||
reqs = requestCollector.getRequestsForTransaction(
|
reqs = requestCollector.getRequestsForTransaction(
|
||||||
bindingRequest.getTransactionID());
|
bindingRequest.getTransactionID());
|
||||||
assertEquals("A retransmissions of the request was sent, while not "
|
assertEquals(12, reqs.size(),
|
||||||
+"supposed to",
|
"A retransmissions of the request was sent, while not supposed to");
|
||||||
12,
|
|
||||||
reqs.size());
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* A simply utility for asynchronous collection of requests.
|
* A simply utility for asynchronous collection of requests.
|
||||||
*/
|
*/
|
||||||
private class PlainRequestCollector
|
private static class PlainRequestCollector
|
||||||
implements RequestListener
|
implements RequestListener
|
||||||
{
|
{
|
||||||
/**
|
/**
|
||||||
*
|
*
|
||||||
*/
|
*/
|
||||||
private Vector<StunMessageEvent> receivedRequestsVector
|
private final Vector<StunMessageEvent> receivedRequestsVector
|
||||||
= new Vector<>();
|
= new Vector<>();
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -559,15 +562,25 @@ public class TransactionSupportTests extends TestCase
|
|||||||
* Blocks until a request arrives or 50 ms pass.
|
* Blocks until a request arrives or 50 ms pass.
|
||||||
*/
|
*/
|
||||||
public void waitForRequest()
|
public void waitForRequest()
|
||||||
|
{
|
||||||
|
waitForRequest(50);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Blocks until a request arrives or the timeout passes.
|
||||||
|
*/
|
||||||
|
public void waitForRequest(long timeoutMillis)
|
||||||
{
|
{
|
||||||
synchronized(this)
|
synchronized(this)
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
wait(50);
|
wait(timeoutMillis);
|
||||||
}
|
}
|
||||||
catch (InterruptedException e)
|
catch (InterruptedException e)
|
||||||
{}
|
{
|
||||||
|
Thread.currentThread().interrupt();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -592,7 +605,7 @@ public class TransactionSupportTests extends TestCase
|
|||||||
* transaction and the runtime type of which specifies the failure reason
|
* transaction and the runtime type of which specifies the failure reason
|
||||||
* @see AbstractResponseCollector#processFailure(BaseStunMessageEvent)
|
* @see AbstractResponseCollector#processFailure(BaseStunMessageEvent)
|
||||||
*/
|
*/
|
||||||
protected void processFailure(BaseStunMessageEvent event)
|
protected synchronized void processFailure(BaseStunMessageEvent event)
|
||||||
{
|
{
|
||||||
String receivedResponse;
|
String receivedResponse;
|
||||||
|
|
||||||
@ -603,6 +616,7 @@ public class TransactionSupportTests extends TestCase
|
|||||||
else
|
else
|
||||||
receivedResponse = "failure";
|
receivedResponse = "failure";
|
||||||
receivedResponses.add(receivedResponse);
|
receivedResponses.add(receivedResponse);
|
||||||
|
notifyAll();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -610,9 +624,10 @@ public class TransactionSupportTests extends TestCase
|
|||||||
*
|
*
|
||||||
* @param response the event to log.
|
* @param response the event to log.
|
||||||
*/
|
*/
|
||||||
public void processResponse(StunResponseEvent response)
|
public synchronized void processResponse(StunResponseEvent response)
|
||||||
{
|
{
|
||||||
receivedResponses.add(response);
|
receivedResponses.add(response);
|
||||||
|
notifyAll();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -17,46 +17,40 @@
|
|||||||
*/
|
*/
|
||||||
package org.ice4j.attribute;
|
package org.ice4j.attribute;
|
||||||
|
|
||||||
import java.util.*;
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
import junit.framework.*;
|
|
||||||
|
|
||||||
import org.ice4j.*;
|
import org.ice4j.*;
|
||||||
|
import org.junit.jupiter.api.*;
|
||||||
/**
|
/**
|
||||||
*
|
*
|
||||||
* @author Emil Ivov
|
* @author Emil Ivov
|
||||||
*/
|
*/
|
||||||
public class AddressAttributeTest extends TestCase {
|
public class AddressAttributeTest
|
||||||
|
{
|
||||||
private AddressAttribute addressAttribute = null;
|
private AddressAttribute addressAttribute = null;
|
||||||
private MsgFixture msgFixture;
|
private MsgFixture msgFixture;
|
||||||
|
|
||||||
public AddressAttributeTest(String name) {
|
@BeforeEach
|
||||||
super(name);
|
public void setUp() throws Exception
|
||||||
}
|
{
|
||||||
|
|
||||||
protected void setUp() throws Exception {
|
|
||||||
super.setUp();
|
|
||||||
|
|
||||||
addressAttribute = new MappedAddressAttribute();
|
addressAttribute = new MappedAddressAttribute();
|
||||||
msgFixture = new MsgFixture();
|
msgFixture = new MsgFixture();
|
||||||
|
|
||||||
msgFixture.setUp();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
protected void tearDown() throws Exception {
|
@AfterEach
|
||||||
|
public void tearDown() throws Exception
|
||||||
|
{
|
||||||
addressAttribute = null;
|
addressAttribute = null;
|
||||||
msgFixture.tearDown();
|
|
||||||
|
|
||||||
msgFixture = null;
|
msgFixture = null;
|
||||||
super.tearDown();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Verify that AddressAttribute descendants have correctly set types and
|
* Verify that AddressAttribute descendants have correctly set types and
|
||||||
* names.
|
* names.
|
||||||
*/
|
*/
|
||||||
public void testAddressAttributeDescendants() {
|
@Test
|
||||||
|
public void testAddressAttributeDescendants()
|
||||||
|
{
|
||||||
char expectedType;
|
char expectedType;
|
||||||
char actualType;
|
char actualType;
|
||||||
String expectedName;
|
String expectedName;
|
||||||
@ -71,10 +65,10 @@ public class AddressAttributeTest extends TestCase {
|
|||||||
expectedName = "MAPPED-ADDRESS";
|
expectedName = "MAPPED-ADDRESS";
|
||||||
actualName = addressAttribute.getName();
|
actualName = addressAttribute.getName();
|
||||||
|
|
||||||
assertEquals("MappedAddressAttribute does not the right type.",
|
assertEquals(expectedType, actualType,
|
||||||
expectedType, actualType);
|
"MappedAddressAttribute does not the right type.");
|
||||||
assertEquals("MappedAddressAttribute does not the right name.",
|
assertEquals(expectedName, actualName,
|
||||||
expectedName, actualName);
|
"MappedAddressAttribute does not the right name.");
|
||||||
|
|
||||||
|
|
||||||
//SOURCE-ADDRESS
|
//SOURCE-ADDRESS
|
||||||
@ -86,10 +80,10 @@ public class AddressAttributeTest extends TestCase {
|
|||||||
expectedName = "SOURCE-ADDRESS";
|
expectedName = "SOURCE-ADDRESS";
|
||||||
actualName = addressAttribute.getName();
|
actualName = addressAttribute.getName();
|
||||||
|
|
||||||
assertEquals("SourceAddressAttribute does not the right type.",
|
assertEquals(expectedType, actualType,
|
||||||
expectedType, actualType);
|
"SourceAddressAttribute does not the right type.");
|
||||||
assertEquals("SourceAddressAttribute does not the right name.",
|
assertEquals(expectedName, actualName,
|
||||||
expectedName, actualName);
|
"SourceAddressAttribute does not the right name.");
|
||||||
|
|
||||||
|
|
||||||
//CHANGED-ADDRESS
|
//CHANGED-ADDRESS
|
||||||
@ -101,10 +95,10 @@ public class AddressAttributeTest extends TestCase {
|
|||||||
expectedName = "CHANGED-ADDRESS";
|
expectedName = "CHANGED-ADDRESS";
|
||||||
actualName = addressAttribute.getName();
|
actualName = addressAttribute.getName();
|
||||||
|
|
||||||
assertEquals("ChangedAddressAttribute does not the right type.",
|
assertEquals(expectedType, actualType,
|
||||||
expectedType, actualType);
|
"ChangedAddressAttribute does not the right type.");
|
||||||
assertEquals("ChangedAddressAttribute does not the right name.",
|
assertEquals(expectedName, actualName,
|
||||||
expectedName, actualName);
|
"ChangedAddressAttribute does not the right name.");
|
||||||
|
|
||||||
|
|
||||||
//RESPONSE-ADDRESS
|
//RESPONSE-ADDRESS
|
||||||
@ -116,10 +110,10 @@ public class AddressAttributeTest extends TestCase {
|
|||||||
expectedName = "RESPONSE-ADDRESS";
|
expectedName = "RESPONSE-ADDRESS";
|
||||||
actualName = addressAttribute.getName();
|
actualName = addressAttribute.getName();
|
||||||
|
|
||||||
assertEquals("ResponseAddressAttribute does not the right type.",
|
assertEquals(expectedType, actualType,
|
||||||
expectedType, actualType);
|
"ResponseAddressAttribute does not the right type.");
|
||||||
assertEquals("ResponseAddressAttribute does not the right name.",
|
assertEquals(expectedName, actualName,
|
||||||
expectedName, actualName);
|
"ResponseAddressAttribute does not the right name.");
|
||||||
|
|
||||||
|
|
||||||
//REFLECTED-FROM
|
//REFLECTED-FROM
|
||||||
@ -131,10 +125,10 @@ public class AddressAttributeTest extends TestCase {
|
|||||||
expectedName = "REFLECTED-FROM";
|
expectedName = "REFLECTED-FROM";
|
||||||
actualName = addressAttribute.getName();
|
actualName = addressAttribute.getName();
|
||||||
|
|
||||||
assertEquals("ReflectedFromAttribute does not the right type.",
|
assertEquals(expectedType, actualType,
|
||||||
expectedType, actualType);
|
"ReflectedFromAttribute does not the right type.");
|
||||||
assertEquals("ReflectedFromAttribute does not the right name.",
|
assertEquals(expectedName, actualName,
|
||||||
expectedName, actualName);
|
"ReflectedFromAttribute does not the right name.");
|
||||||
|
|
||||||
//REFLECTED-FROM
|
//REFLECTED-FROM
|
||||||
addressAttribute = new ReflectedFromAttribute();
|
addressAttribute = new ReflectedFromAttribute();
|
||||||
@ -145,10 +139,10 @@ public class AddressAttributeTest extends TestCase {
|
|||||||
expectedName = "REFLECTED-FROM";
|
expectedName = "REFLECTED-FROM";
|
||||||
actualName = addressAttribute.getName();
|
actualName = addressAttribute.getName();
|
||||||
|
|
||||||
assertEquals("ReflectedFromAttribute does not the right type.",
|
assertEquals(expectedType, actualType,
|
||||||
expectedType, actualType);
|
"ReflectedFromAttribute does not the right type.");
|
||||||
assertEquals("ReflectedFromAttribute does not the right name.",
|
assertEquals(expectedName, actualName,
|
||||||
expectedName, actualName);
|
"ReflectedFromAttribute does not the right name.");
|
||||||
|
|
||||||
//XOR-MAPPED-ADDRESS
|
//XOR-MAPPED-ADDRESS
|
||||||
addressAttribute = new XorMappedAddressAttribute();
|
addressAttribute = new XorMappedAddressAttribute();
|
||||||
@ -159,10 +153,10 @@ public class AddressAttributeTest extends TestCase {
|
|||||||
expectedName = "XOR-MAPPED-ADDRESS";
|
expectedName = "XOR-MAPPED-ADDRESS";
|
||||||
actualName = addressAttribute.getName();
|
actualName = addressAttribute.getName();
|
||||||
|
|
||||||
assertEquals("XorMappedAddressAttribute does not the right type.",
|
assertEquals(expectedType, actualType,
|
||||||
expectedType, actualType);
|
"XorMappedAddressAttribute does not the right type.");
|
||||||
assertEquals("XorMappedAddressAttribute does not the right name.",
|
assertEquals(expectedName, actualName,
|
||||||
expectedName, actualName);
|
"XorMappedAddressAttribute does not the right name.");
|
||||||
|
|
||||||
/* ALTERNATE-SERVER */
|
/* ALTERNATE-SERVER */
|
||||||
addressAttribute = new AlternateServerAttribute();
|
addressAttribute = new AlternateServerAttribute();
|
||||||
@ -173,10 +167,10 @@ public class AddressAttributeTest extends TestCase {
|
|||||||
expectedName = "ALTERNATE-SERVER";
|
expectedName = "ALTERNATE-SERVER";
|
||||||
actualName = addressAttribute.getName();
|
actualName = addressAttribute.getName();
|
||||||
|
|
||||||
assertEquals("AlternateServerAttribute does not the right type.",
|
assertEquals(expectedType, actualType,
|
||||||
expectedType, actualType);
|
"AlternateServerAttribute does not the right type.");
|
||||||
assertEquals("AlternateAttribute does not the right name.",
|
assertEquals(expectedName, actualName,
|
||||||
expectedName, actualName);
|
"AlternateAttribute does not the right name.");
|
||||||
|
|
||||||
|
|
||||||
/* XOR-PEER-ADDRESS */
|
/* XOR-PEER-ADDRESS */
|
||||||
@ -188,10 +182,10 @@ public class AddressAttributeTest extends TestCase {
|
|||||||
expectedName = "XOR-PEER-ADDRESS";
|
expectedName = "XOR-PEER-ADDRESS";
|
||||||
actualName = addressAttribute.getName();
|
actualName = addressAttribute.getName();
|
||||||
|
|
||||||
assertEquals("XorPeerAddressAttribute does not the right type.",
|
assertEquals(expectedType, actualType,
|
||||||
expectedType, actualType);
|
"XorPeerAddressAttribute does not the right type.");
|
||||||
assertEquals("XorPeerAddressAttribute does not the right name.",
|
assertEquals(expectedName, actualName,
|
||||||
expectedName, actualName);
|
"XorPeerAddressAttribute does not the right name.");
|
||||||
|
|
||||||
/* XOR-RELAYED-ADDRESS */
|
/* XOR-RELAYED-ADDRESS */
|
||||||
addressAttribute = new XorRelayedAddressAttribute();
|
addressAttribute = new XorRelayedAddressAttribute();
|
||||||
@ -202,15 +196,16 @@ public class AddressAttributeTest extends TestCase {
|
|||||||
expectedName = "XOR-RELAYED-ADDRESS";
|
expectedName = "XOR-RELAYED-ADDRESS";
|
||||||
actualName = addressAttribute.getName();
|
actualName = addressAttribute.getName();
|
||||||
|
|
||||||
assertEquals("XorRelayedAddressAttribute does not the right type.",
|
assertEquals(expectedType, actualType,
|
||||||
expectedType, actualType);
|
"XorRelayedAddressAttribute does not the right type.");
|
||||||
assertEquals("XorRelayedAddressAttribute does not the right name.",
|
assertEquals(expectedName, actualName,
|
||||||
expectedName, actualName);
|
"XorRelayedAddressAttribute does not the right name.");
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Verifies that xorred address-es are properly xor-ed for IPv4 addresses.
|
* Verifies that xorred address-es are properly xor-ed for IPv4 addresses.
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testXorMappedAddressXoring_v4()
|
public void testXorMappedAddressXoring_v4()
|
||||||
{
|
{
|
||||||
XorMappedAddressAttribute addressAttribute = new XorMappedAddressAttribute();
|
XorMappedAddressAttribute addressAttribute = new XorMappedAddressAttribute();
|
||||||
@ -223,11 +218,12 @@ public class AddressAttributeTest extends TestCase {
|
|||||||
TransportAddress xorredAddr = addressAttribute.applyXor(
|
TransportAddress xorredAddr = addressAttribute.applyXor(
|
||||||
new byte[]{(byte)130,79,95,53,0,0,0,0,0,0,0,0,0,0,0,0,0});
|
new byte[]{(byte)130,79,95,53,0,0,0,0,0,0,0,0,0,0,0,0,0});
|
||||||
|
|
||||||
assertTrue("Xorring the address with itself didn't return 00000...",
|
assertArrayEquals(
|
||||||
Arrays.equals(xorredAddr.getAddressBytes(), new byte[]{0,0,0,0}));
|
xorredAddr.getAddressBytes(), new byte[] { 0, 0, 0, 0 },
|
||||||
|
"Xorring the address with itself didn't return 00000...");
|
||||||
|
|
||||||
assertTrue("Port was not xorred",
|
assertNotEquals(xorredAddr.getPort(), testAddress.getPort(),
|
||||||
testAddress.getPort() != xorredAddr.getPort());
|
"Port was not xorred");
|
||||||
|
|
||||||
//Test xor-ing the original with the xored - should get the xor code
|
//Test xor-ing the original with the xored - should get the xor code
|
||||||
addressAttribute.setAddress(testAddress);
|
addressAttribute.setAddress(testAddress);
|
||||||
@ -237,13 +233,11 @@ public class AddressAttributeTest extends TestCase {
|
|||||||
xorredAddr =
|
xorredAddr =
|
||||||
addressAttribute.applyXor(xorredAddr.getAddressBytes());
|
addressAttribute.applyXor(xorredAddr.getAddressBytes());
|
||||||
|
|
||||||
assertTrue("Xorring the original with the xor-ed didn't "
|
assertArrayEquals(
|
||||||
+"return the code..",
|
xorredAddr.getAddressBytes(), new byte[] { 21, 22, 23, 24 },
|
||||||
Arrays.equals( xorredAddr.getAddressBytes(),
|
"Xorring the original with the xor-ed didn't return the code.");
|
||||||
new byte[]{21,22,23,24}));
|
|
||||||
|
|
||||||
assertTrue("Port was not xorred",
|
assertNotEquals(0xFFFF, testAddress.getPort(), "Port was not xorred");
|
||||||
testAddress.getPort() != 0xFFFF);
|
|
||||||
|
|
||||||
//Test double xor-ing - should get the original
|
//Test double xor-ing - should get the original
|
||||||
addressAttribute.setAddress(testAddress);
|
addressAttribute.setAddress(testAddress);
|
||||||
@ -254,13 +248,14 @@ public class AddressAttributeTest extends TestCase {
|
|||||||
xorredAddr = addressAttribute.applyXor(
|
xorredAddr = addressAttribute.applyXor(
|
||||||
new byte[]{21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36});
|
new byte[]{21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36});
|
||||||
|
|
||||||
assertEquals("Double xorring didn't give the original ...",
|
assertEquals(testAddress, xorredAddr,
|
||||||
testAddress, xorredAddr);
|
"Double xorring didn't give the original");
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Verifies that xorred address-es are properly xor-ed for IPv6 addresses.
|
* Verifies that xorred address-es are properly xor-ed for IPv6 addresses.
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testXorMappedAddressXoring_v6()
|
public void testXorMappedAddressXoring_v6()
|
||||||
{
|
{
|
||||||
XorMappedAddressAttribute addressAttribute
|
XorMappedAddressAttribute addressAttribute
|
||||||
@ -278,15 +273,15 @@ public class AddressAttributeTest extends TestCase {
|
|||||||
(byte)0x02, (byte)0x02, (byte)0x8a, (byte)0xff,
|
(byte)0x02, (byte)0x02, (byte)0x8a, (byte)0xff,
|
||||||
(byte)0xfe, (byte)0xbe, (byte)0x13, (byte)0x0b});
|
(byte)0xfe, (byte)0xbe, (byte)0x13, (byte)0x0b});
|
||||||
|
|
||||||
assertTrue("Xorring the address with itself didn't return 00000...",
|
assertArrayEquals(
|
||||||
Arrays.equals(xorredAddr.getAddressBytes(),
|
xorredAddr.getAddressBytes(), new byte[] { 0, 0, 0, 0,
|
||||||
new byte[]{0,0,0,0,
|
|
||||||
0, 0, 0, 0,
|
0, 0, 0, 0,
|
||||||
0, 0, 0, 0,
|
0, 0, 0, 0,
|
||||||
0,0,0,0}));
|
0, 0, 0, 0 },
|
||||||
|
"Xorring the address with itself didn't return 00000...");
|
||||||
|
|
||||||
assertTrue("Port was not xorred",
|
assertNotEquals(testAddress.getPort(), xorredAddr.getPort(),
|
||||||
testAddress.getPort() != xorredAddr.getPort());
|
"Port was not xorred");
|
||||||
|
|
||||||
//Test xor-ing the original with the xored - should get the xor code
|
//Test xor-ing the original with the xored - should get the xor code
|
||||||
addressAttribute.setAddress(testAddress);
|
addressAttribute.setAddress(testAddress);
|
||||||
@ -295,13 +290,13 @@ public class AddressAttributeTest extends TestCase {
|
|||||||
|
|
||||||
xorredAddr = addressAttribute.applyXor(xorredAddr.getAddressBytes());
|
xorredAddr = addressAttribute.applyXor(xorredAddr.getAddressBytes());
|
||||||
|
|
||||||
assertTrue("Xorring the original with the xor-ed didn't return the code..",
|
assertArrayEquals(
|
||||||
Arrays.equals(
|
|
||||||
xorredAddr.getAddressBytes(),
|
xorredAddr.getAddressBytes(),
|
||||||
new byte[]{21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36}));
|
new byte[] { 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34,
|
||||||
|
35, 36 },
|
||||||
|
"Xorring the original with the xor-ed didn't return the code.");
|
||||||
|
|
||||||
assertTrue("Port was not xorred",
|
assertNotEquals(0xFFFF, testAddress.getPort(), "Port was not xorred");
|
||||||
testAddress.getPort() != 0xFFFF);
|
|
||||||
|
|
||||||
//Test double xor-ing - should get the original
|
//Test double xor-ing - should get the original
|
||||||
addressAttribute.setAddress(testAddress);
|
addressAttribute.setAddress(testAddress);
|
||||||
@ -312,8 +307,8 @@ public class AddressAttributeTest extends TestCase {
|
|||||||
xorredAddr = addressAttribute.applyXor(
|
xorredAddr = addressAttribute.applyXor(
|
||||||
new byte[]{21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36});
|
new byte[]{21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36});
|
||||||
|
|
||||||
assertEquals("Double xorring didn't give the original ...",
|
assertEquals(testAddress, xorredAddr,
|
||||||
testAddress, xorredAddr);
|
"Double xorring didn't give the original");
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -321,6 +316,7 @@ public class AddressAttributeTest extends TestCase {
|
|||||||
*
|
*
|
||||||
* @throws StunException if something goes wrong
|
* @throws StunException if something goes wrong
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testDecodeAttributeBody() throws StunException {
|
public void testDecodeAttributeBody() throws StunException {
|
||||||
byte[] attributeValue = msgFixture.mappedAddress;
|
byte[] attributeValue = msgFixture.mappedAddress;
|
||||||
char offset = Attribute.HEADER_LENGTH;
|
char offset = Attribute.HEADER_LENGTH;
|
||||||
@ -330,12 +326,12 @@ public class AddressAttributeTest extends TestCase {
|
|||||||
|
|
||||||
|
|
||||||
assertEquals(
|
assertEquals(
|
||||||
"AddressAttribute.decode() did not properly decode the port field.",
|
MsgFixture.ADDRESS_ATTRIBUTE_PORT, addressAttribute.getPort(),
|
||||||
MsgFixture.ADDRESS_ATTRIBUTE_PORT, addressAttribute.getPort());
|
"AddressAttribute.decode() did not properly decode the port field.");
|
||||||
assertTrue(
|
assertArrayEquals(
|
||||||
"AddressAttribute.decode() did not properly decode the address field.",
|
MsgFixture.ADDRESS_ATTRIBUTE_ADDRESS,
|
||||||
Arrays.equals( MsgFixture.ADDRESS_ATTRIBUTE_ADDRESS,
|
addressAttribute.getAddressBytes(),
|
||||||
addressAttribute.getAddressBytes()));
|
"AddressAttribute.decode() did not properly decode the address field.");
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
@ -344,6 +340,7 @@ public class AddressAttributeTest extends TestCase {
|
|||||||
* Test whetner sample binary arrays are correctly decoded.
|
* Test whetner sample binary arrays are correctly decoded.
|
||||||
* @throws StunException if something goes wrong
|
* @throws StunException if something goes wrong
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testDecodeAttributeBodyv6() throws StunException {
|
public void testDecodeAttributeBodyv6() throws StunException {
|
||||||
byte[] attributeValue = msgFixture.mappedAddressv6;
|
byte[] attributeValue = msgFixture.mappedAddressv6;
|
||||||
char offset = Attribute.HEADER_LENGTH;
|
char offset = Attribute.HEADER_LENGTH;
|
||||||
@ -352,14 +349,13 @@ public class AddressAttributeTest extends TestCase {
|
|||||||
addressAttribute.decodeAttributeBody(attributeValue, offset, length);
|
addressAttribute.decodeAttributeBody(attributeValue, offset, length);
|
||||||
|
|
||||||
|
|
||||||
assertEquals("decode() failed for an IPv6 Addr's port.",
|
assertEquals(MsgFixture.ADDRESS_ATTRIBUTE_PORT,
|
||||||
MsgFixture.ADDRESS_ATTRIBUTE_PORT,
|
addressAttribute.getPort(),
|
||||||
addressAttribute.getPort());
|
"decode() failed for an IPv6 Addr's port.");
|
||||||
assertTrue("AddressAttribute.decode() failed for an IPv6 address.",
|
assertArrayEquals(
|
||||||
Arrays.equals( MsgFixture.ADDRESS_ATTRIBUTE_ADDRESS_V6,
|
MsgFixture.ADDRESS_ATTRIBUTE_ADDRESS_V6,
|
||||||
addressAttribute.getAddressBytes()));
|
addressAttribute.getAddressBytes(),
|
||||||
|
"AddressAttribute.decode() failed for an IPv6 address.");
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -367,6 +363,7 @@ public class AddressAttributeTest extends TestCase {
|
|||||||
*
|
*
|
||||||
* @throws Exception java.lang.Exception if we fail
|
* @throws Exception java.lang.Exception if we fail
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testEncode()
|
public void testEncode()
|
||||||
throws Exception
|
throws Exception
|
||||||
{
|
{
|
||||||
@ -378,9 +375,8 @@ public class AddressAttributeTest extends TestCase {
|
|||||||
Transport.UDP));
|
Transport.UDP));
|
||||||
|
|
||||||
byte[] actualReturn = addressAttribute.encode();
|
byte[] actualReturn = addressAttribute.encode();
|
||||||
assertTrue("AddressAttribute.encode() did not "
|
assertArrayEquals(expectedReturn, actualReturn,
|
||||||
+"properly encode a sample attribute",
|
"AddressAttribute.encode() did not properly encode a sample attribute");
|
||||||
Arrays.equals( expectedReturn, actualReturn));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -388,6 +384,7 @@ public class AddressAttributeTest extends TestCase {
|
|||||||
*
|
*
|
||||||
* @throws Exception java.lang.Exception if we fail
|
* @throws Exception java.lang.Exception if we fail
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testEncodev6()
|
public void testEncodev6()
|
||||||
throws Exception
|
throws Exception
|
||||||
{
|
{
|
||||||
@ -398,8 +395,8 @@ public class AddressAttributeTest extends TestCase {
|
|||||||
MsgFixture.ADDRESS_ATTRIBUTE_PORT, Transport.UDP));
|
MsgFixture.ADDRESS_ATTRIBUTE_PORT, Transport.UDP));
|
||||||
|
|
||||||
byte[] actualReturn = addressAttribute.encode();
|
byte[] actualReturn = addressAttribute.encode();
|
||||||
assertTrue("An AddressAttribute did not properly encode an IPv6 addr.",
|
assertArrayEquals(expectedReturn, actualReturn,
|
||||||
Arrays.equals( expectedReturn, actualReturn));
|
"An AddressAttribute did not properly encode an IPv6 addr.");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@ -409,6 +406,7 @@ public class AddressAttributeTest extends TestCase {
|
|||||||
*
|
*
|
||||||
* @throws Exception java.lang.Exception if we fail
|
* @throws Exception java.lang.Exception if we fail
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testEquals()
|
public void testEquals()
|
||||||
throws Exception
|
throws Exception
|
||||||
{
|
{
|
||||||
@ -417,8 +415,8 @@ public class AddressAttributeTest extends TestCase {
|
|||||||
boolean expectedReturn = false;
|
boolean expectedReturn = false;
|
||||||
boolean actualReturn = addressAttribute.equals(target);
|
boolean actualReturn = addressAttribute.equals(target);
|
||||||
|
|
||||||
assertEquals("AddressAttribute.equals() failed against a null target.",
|
assertEquals(expectedReturn, actualReturn,
|
||||||
expectedReturn, actualReturn);
|
"AddressAttribute.equals() failed against a null target.");
|
||||||
|
|
||||||
//difference test
|
//difference test
|
||||||
target = new MappedAddressAttribute();
|
target = new MappedAddressAttribute();
|
||||||
@ -434,9 +432,8 @@ public class AddressAttributeTest extends TestCase {
|
|||||||
|
|
||||||
expectedReturn = false;
|
expectedReturn = false;
|
||||||
actualReturn = addressAttribute.equals(target);
|
actualReturn = addressAttribute.equals(target);
|
||||||
assertEquals(
|
assertEquals(expectedReturn, actualReturn,
|
||||||
"AddressAttribute.equals() failed against a different target.",
|
"AddressAttribute.equals() failed against a different target.");
|
||||||
expectedReturn, actualReturn);
|
|
||||||
|
|
||||||
//equality test
|
//equality test
|
||||||
target.setAddress( new TransportAddress(
|
target.setAddress( new TransportAddress(
|
||||||
@ -445,9 +442,8 @@ public class AddressAttributeTest extends TestCase {
|
|||||||
|
|
||||||
expectedReturn = true;
|
expectedReturn = true;
|
||||||
actualReturn = addressAttribute.equals(target);
|
actualReturn = addressAttribute.equals(target);
|
||||||
assertEquals(
|
assertEquals(expectedReturn, actualReturn,
|
||||||
"AddressAttribute.equals() failed against an equal target.",
|
"AddressAttribute.equals() failed against an equal target.");
|
||||||
expectedReturn, actualReturn);
|
|
||||||
|
|
||||||
//ipv6 equality test
|
//ipv6 equality test
|
||||||
target.setAddress( new TransportAddress(
|
target.setAddress( new TransportAddress(
|
||||||
@ -461,8 +457,8 @@ public class AddressAttributeTest extends TestCase {
|
|||||||
|
|
||||||
expectedReturn = true;
|
expectedReturn = true;
|
||||||
actualReturn = addressAttribute.equals(target);
|
actualReturn = addressAttribute.equals(target);
|
||||||
assertEquals("AddressAttribute.equals() failed for IPv6 addresses.",
|
assertEquals(expectedReturn, actualReturn,
|
||||||
expectedReturn, actualReturn);
|
"AddressAttribute.equals() failed for IPv6 addresses.");
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -470,6 +466,7 @@ public class AddressAttributeTest extends TestCase {
|
|||||||
*
|
*
|
||||||
* @throws Exception java.lang.Exception if we fail
|
* @throws Exception java.lang.Exception if we fail
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testGetDataLength()
|
public void testGetDataLength()
|
||||||
throws Exception
|
throws Exception
|
||||||
{
|
{
|
||||||
@ -482,8 +479,8 @@ public class AddressAttributeTest extends TestCase {
|
|||||||
|
|
||||||
char actualReturn = addressAttribute.getDataLength();
|
char actualReturn = addressAttribute.getDataLength();
|
||||||
|
|
||||||
assertEquals("Datalength is not propoerly calculated",
|
assertEquals(expectedReturn, actualReturn,
|
||||||
expectedReturn, actualReturn);
|
"Datalength is not propoerly calculated");
|
||||||
|
|
||||||
expectedReturn = 20;//1-padding + 1-family + 2-port + 16-address
|
expectedReturn = 20;//1-padding + 1-family + 2-port + 16-address
|
||||||
addressAttribute.setAddress( new TransportAddress(
|
addressAttribute.setAddress( new TransportAddress(
|
||||||
@ -492,8 +489,8 @@ public class AddressAttributeTest extends TestCase {
|
|||||||
|
|
||||||
actualReturn = addressAttribute.getDataLength();
|
actualReturn = addressAttribute.getDataLength();
|
||||||
|
|
||||||
assertEquals("Datalength is not propoerly calculated",
|
assertEquals(expectedReturn, actualReturn,
|
||||||
expectedReturn, actualReturn);
|
"Datalength is not propoerly calculated");
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -501,6 +498,7 @@ public class AddressAttributeTest extends TestCase {
|
|||||||
*
|
*
|
||||||
* @throws Exception java.lang.Exception if we fail
|
* @throws Exception java.lang.Exception if we fail
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testGetFamily()
|
public void testGetFamily()
|
||||||
throws Exception
|
throws Exception
|
||||||
{
|
{
|
||||||
@ -509,8 +507,8 @@ public class AddressAttributeTest extends TestCase {
|
|||||||
MsgFixture.ADDRESS_ATTRIBUTE_ADDRESS,
|
MsgFixture.ADDRESS_ATTRIBUTE_ADDRESS,
|
||||||
MsgFixture.ADDRESS_ATTRIBUTE_PORT, Transport.UDP));
|
MsgFixture.ADDRESS_ATTRIBUTE_PORT, Transport.UDP));
|
||||||
byte actualReturn = addressAttribute.getFamily();
|
byte actualReturn = addressAttribute.getFamily();
|
||||||
assertEquals("Address family was not 1 for an IPv4",
|
assertEquals(expectedReturn, actualReturn,
|
||||||
expectedReturn, actualReturn);
|
"Address family was not 1 for an IPv4");
|
||||||
|
|
||||||
//ipv6
|
//ipv6
|
||||||
expectedReturn = 2;
|
expectedReturn = 2;
|
||||||
@ -518,9 +516,7 @@ public class AddressAttributeTest extends TestCase {
|
|||||||
MsgFixture.ADDRESS_ATTRIBUTE_ADDRESS_V6,
|
MsgFixture.ADDRESS_ATTRIBUTE_ADDRESS_V6,
|
||||||
MsgFixture.ADDRESS_ATTRIBUTE_PORT, Transport.UDP));
|
MsgFixture.ADDRESS_ATTRIBUTE_PORT, Transport.UDP));
|
||||||
actualReturn = addressAttribute.getFamily();
|
actualReturn = addressAttribute.getFamily();
|
||||||
assertEquals("Address family was not 2 for an IPv6 address",
|
assertEquals(expectedReturn, actualReturn,
|
||||||
expectedReturn, actualReturn);
|
"Address family was not 2 for an IPv6 address");
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@ -17,28 +17,23 @@
|
|||||||
*/
|
*/
|
||||||
package org.ice4j.attribute;
|
package org.ice4j.attribute;
|
||||||
|
|
||||||
|
|
||||||
import org.ice4j.*;
|
import org.ice4j.*;
|
||||||
|
|
||||||
import junit.framework.*;
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.*;
|
||||||
/**
|
/**
|
||||||
* We have already tested individual decode methods, so our job here
|
* We have already tested individual decode methods, so our job here
|
||||||
* is to verify that that AttributeDecoder.decode distributes the right way.
|
* is to verify that that AttributeDecoder.decode distributes the right way.
|
||||||
*/
|
*/
|
||||||
public class AttributeDecoderTest extends TestCase
|
public class AttributeDecoderTest {
|
||||||
{
|
|
||||||
private MsgFixture msgFixture;
|
private MsgFixture msgFixture;
|
||||||
private byte[] expectedAttributeValue = null;
|
private byte[] expectedAttributeValue = null;
|
||||||
|
|
||||||
public AttributeDecoderTest(String name)
|
@BeforeEach
|
||||||
|
public void setUp() throws Exception
|
||||||
{
|
{
|
||||||
super(name);
|
|
||||||
}
|
|
||||||
|
|
||||||
protected void setUp() throws Exception
|
|
||||||
{
|
|
||||||
super.setUp();
|
|
||||||
|
|
||||||
msgFixture = new MsgFixture();
|
msgFixture = new MsgFixture();
|
||||||
|
|
||||||
//init a sample body
|
//init a sample body
|
||||||
@ -48,18 +43,15 @@ public class AttributeDecoderTest extends TestCase
|
|||||||
System.arraycopy(msgFixture.unknownOptionalAttribute, offset,
|
System.arraycopy(msgFixture.unknownOptionalAttribute, offset,
|
||||||
expectedAttributeValue, 0,
|
expectedAttributeValue, 0,
|
||||||
expectedAttributeValue.length);
|
expectedAttributeValue.length);
|
||||||
|
|
||||||
msgFixture.setUp();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
protected void tearDown() throws Exception
|
@AfterEach
|
||||||
|
public void tearDown() throws Exception
|
||||||
{
|
{
|
||||||
msgFixture.tearDown();
|
|
||||||
|
|
||||||
msgFixture = null;
|
msgFixture = null;
|
||||||
super.tearDown();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testDecodeMappedAddress()
|
public void testDecodeMappedAddress()
|
||||||
throws Exception
|
throws Exception
|
||||||
{
|
{
|
||||||
@ -79,11 +71,11 @@ public class AttributeDecoderTest extends TestCase
|
|||||||
Attribute actualReturn = AttributeDecoder.decode(
|
Attribute actualReturn = AttributeDecoder.decode(
|
||||||
bytes, offset, length);
|
bytes, offset, length);
|
||||||
|
|
||||||
assertEquals(
|
assertEquals(expectedReturn, actualReturn,
|
||||||
"AttributeDecoder.decode() failed for a MAPPED-ADDRESS attribute",
|
"AttributeDecoder.decode() failed for a MAPPED-ADDRESS attribute");
|
||||||
expectedReturn, actualReturn);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testDecodeMappedAddress_v6()
|
public void testDecodeMappedAddress_v6()
|
||||||
throws Exception
|
throws Exception
|
||||||
{
|
{
|
||||||
@ -104,10 +96,12 @@ public class AttributeDecoderTest extends TestCase
|
|||||||
bytes, offset, length);
|
bytes, offset, length);
|
||||||
|
|
||||||
assertEquals(
|
assertEquals(
|
||||||
"AttributeDecoder.decode() failed for a MAPPED-ADDRESS attribute",
|
expectedReturn, actualReturn,
|
||||||
expectedReturn, actualReturn);
|
"AttributeDecoder.decode() failed for a MAPPED-ADDRESS attribute"
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testDecodeChangeRequest()
|
public void testDecodeChangeRequest()
|
||||||
throws Exception
|
throws Exception
|
||||||
{
|
{
|
||||||
@ -123,11 +117,12 @@ public class AttributeDecoderTest extends TestCase
|
|||||||
|
|
||||||
Attribute actualReturn = AttributeDecoder.decode(
|
Attribute actualReturn = AttributeDecoder.decode(
|
||||||
bytes, offset, length);
|
bytes, offset, length);
|
||||||
assertEquals("AttributeDecoder.decode() failed for a CHANGE-REQUEST attribute",
|
assertEquals(expectedReturn, actualReturn,
|
||||||
expectedReturn, actualReturn);
|
"AttributeDecoder.decode() failed for a CHANGE-REQUEST attribute"
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testDecodeErrorCode()
|
public void testDecodeErrorCode()
|
||||||
throws Exception
|
throws Exception
|
||||||
{
|
{
|
||||||
@ -144,12 +139,11 @@ public class AttributeDecoderTest extends TestCase
|
|||||||
|
|
||||||
Attribute actualReturn = AttributeDecoder.decode(
|
Attribute actualReturn = AttributeDecoder.decode(
|
||||||
bytes, offset, length);
|
bytes, offset, length);
|
||||||
assertEquals(
|
assertEquals(expectedReturn, actualReturn,
|
||||||
"AttributeDecoder.decode() failed for a ERROR-CODE attribute",
|
"AttributeDecoder.decode() failed for a ERROR-CODE attribute");
|
||||||
expectedReturn, actualReturn);
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testDecodeUnknownAttributes()
|
public void testDecodeUnknownAttributes()
|
||||||
throws Exception
|
throws Exception
|
||||||
{
|
{
|
||||||
@ -168,12 +162,11 @@ public class AttributeDecoderTest extends TestCase
|
|||||||
Attribute actualReturn = AttributeDecoder.decode(
|
Attribute actualReturn = AttributeDecoder.decode(
|
||||||
bytes, offset, length);
|
bytes, offset, length);
|
||||||
|
|
||||||
assertEquals(
|
assertEquals(expectedReturn, actualReturn,
|
||||||
"AttributeDecoder.decode() failed for a ERROR-CODE attribute",
|
"AttributeDecoder.decode() failed for a ERROR-CODE attribute");
|
||||||
expectedReturn, actualReturn);
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testDecodeUnknownOptionalAttribute()
|
public void testDecodeUnknownOptionalAttribute()
|
||||||
throws Exception
|
throws Exception
|
||||||
{
|
{
|
||||||
@ -190,9 +183,8 @@ public class AttributeDecoderTest extends TestCase
|
|||||||
|
|
||||||
Attribute actualReturn = AttributeDecoder.decode(
|
Attribute actualReturn = AttributeDecoder.decode(
|
||||||
bytes, offset, length);
|
bytes, offset, length);
|
||||||
assertEquals(
|
assertEquals(expectedReturn, actualReturn,
|
||||||
"AttributeDecoder.decode() failed for a UNKNOWN_OPTIONAL attribute",
|
"AttributeDecoder.decode() failed for a UNKNOWN_OPTIONAL attribute");
|
||||||
expectedReturn, actualReturn);
|
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -17,57 +17,47 @@
|
|||||||
*/
|
*/
|
||||||
package org.ice4j.attribute;
|
package org.ice4j.attribute;
|
||||||
|
|
||||||
import junit.framework.*;
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
import java.util.Arrays;
|
|
||||||
|
|
||||||
import org.ice4j.*;
|
import org.ice4j.*;
|
||||||
|
import org.junit.jupiter.api.*;
|
||||||
/**
|
/**
|
||||||
* Tests the CHANGE-REQUEST attribute class.
|
* Tests the CHANGE-REQUEST attribute class.
|
||||||
*
|
*
|
||||||
* @author Emil Ivov
|
* @author Emil Ivov
|
||||||
*/
|
*/
|
||||||
public class ChangeRequestAttributeTest extends TestCase
|
public class ChangeRequestAttributeTest
|
||||||
{
|
{
|
||||||
private ChangeRequestAttribute changeRequestAttribute = null;
|
private ChangeRequestAttribute changeRequestAttribute = null;
|
||||||
private MsgFixture binMessagesFixture;
|
private MsgFixture binMessagesFixture;
|
||||||
|
|
||||||
public ChangeRequestAttributeTest(String name)
|
@BeforeEach
|
||||||
|
public void setUp() throws Exception
|
||||||
{
|
{
|
||||||
super(name);
|
|
||||||
}
|
|
||||||
|
|
||||||
protected void setUp() throws Exception
|
|
||||||
{
|
|
||||||
super.setUp();
|
|
||||||
changeRequestAttribute = new ChangeRequestAttribute();
|
changeRequestAttribute = new ChangeRequestAttribute();
|
||||||
binMessagesFixture = new MsgFixture();
|
binMessagesFixture = new MsgFixture();
|
||||||
|
|
||||||
binMessagesFixture.setUp();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
protected void tearDown() throws Exception
|
@AfterEach
|
||||||
|
public void tearDown() throws Exception
|
||||||
{
|
{
|
||||||
changeRequestAttribute = null;
|
changeRequestAttribute = null;
|
||||||
binMessagesFixture.tearDown();
|
|
||||||
|
|
||||||
binMessagesFixture = null;
|
binMessagesFixture = null;
|
||||||
super.tearDown();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Test whether the constructed object has the proper type.
|
* Test whether the constructed object has the proper type.
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testChangeRequestAttribute()
|
public void testChangeRequestAttribute()
|
||||||
{
|
{
|
||||||
changeRequestAttribute = new ChangeRequestAttribute();
|
changeRequestAttribute = new ChangeRequestAttribute();
|
||||||
|
|
||||||
assertEquals(
|
assertEquals(
|
||||||
"ChangeRequestAttribute did not construct an attribute with the "
|
|
||||||
+"correct type.",
|
|
||||||
changeRequestAttribute.getAttributeType(),
|
changeRequestAttribute.getAttributeType(),
|
||||||
Attribute.CHANGE_REQUEST);
|
Attribute.CHANGE_REQUEST,
|
||||||
|
"ChangeRequestAttribute did not construct an attribute with the correct type."
|
||||||
|
);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -76,6 +66,7 @@ public class ChangeRequestAttributeTest extends TestCase
|
|||||||
*
|
*
|
||||||
* @throws StunException java.lang.Exception if we fail
|
* @throws StunException java.lang.Exception if we fail
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testDecodeAttributeBody()
|
public void testDecodeAttributeBody()
|
||||||
throws StunException
|
throws StunException
|
||||||
{
|
{
|
||||||
@ -84,34 +75,39 @@ public class ChangeRequestAttributeTest extends TestCase
|
|||||||
char length = (char)(attributeValue.length - offset);
|
char length = (char)(attributeValue.length - offset);
|
||||||
changeRequestAttribute.decodeAttributeBody(attributeValue, offset, length);
|
changeRequestAttribute.decodeAttributeBody(attributeValue, offset, length);
|
||||||
|
|
||||||
assertEquals("decodeAttributeBody() did not properly decode the changeIpFlag",
|
assertEquals(
|
||||||
MsgFixture.CHANGE_IP_FLAG_1,
|
MsgFixture.CHANGE_IP_FLAG_1,
|
||||||
changeRequestAttribute.getChangeIpFlag()
|
changeRequestAttribute.getChangeIpFlag(),
|
||||||
|
"decodeAttributeBody() did not properly decode the changeIpFlag"
|
||||||
);
|
);
|
||||||
assertEquals("decodeAttributeBody() did not properly decode the changePortFlag",
|
assertEquals(
|
||||||
MsgFixture.CHANGE_PORT_FLAG_1,
|
MsgFixture.CHANGE_PORT_FLAG_1,
|
||||||
changeRequestAttribute.getChangePortFlag()
|
changeRequestAttribute.getChangePortFlag(),
|
||||||
|
"decodeAttributeBody() did not properly decode the changePortFlag"
|
||||||
);
|
);
|
||||||
|
|
||||||
//2nd sample
|
//2nd sample
|
||||||
attributeValue = binMessagesFixture.chngReqTestValue2;
|
attributeValue = binMessagesFixture.chngReqTestValue2;
|
||||||
changeRequestAttribute.decodeAttributeBody(attributeValue, offset, length);
|
changeRequestAttribute
|
||||||
assertEquals("decodeAttributeBody() did not properly decode the changeIpFlag",
|
.decodeAttributeBody(attributeValue, offset, length);
|
||||||
|
assertEquals(
|
||||||
MsgFixture.CHANGE_IP_FLAG_2,
|
MsgFixture.CHANGE_IP_FLAG_2,
|
||||||
changeRequestAttribute.getChangeIpFlag()
|
changeRequestAttribute.getChangeIpFlag(),
|
||||||
|
"decodeAttributeBody() did not properly decode the changeIpFlag"
|
||||||
);
|
);
|
||||||
assertEquals("decodeAttributeBody() did not properly decode the changePortFlag",
|
assertEquals(
|
||||||
MsgFixture.CHANGE_PORT_FLAG_2,
|
MsgFixture.CHANGE_PORT_FLAG_2,
|
||||||
changeRequestAttribute.getChangePortFlag()
|
changeRequestAttribute.getChangePortFlag(),
|
||||||
|
"decodeAttributeBody() did not properly decode the changePortFlag"
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|
||||||
changeRequestAttribute.getChangePortFlag();
|
changeRequestAttribute.getChangePortFlag();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Create sample objects and test whether they encode properly.
|
* Create sample objects and test whether they encode properly.
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testEncode()
|
public void testEncode()
|
||||||
{
|
{
|
||||||
byte[] expectedReturn = binMessagesFixture.chngReqTestValue1;
|
byte[] expectedReturn = binMessagesFixture.chngReqTestValue1;
|
||||||
@ -122,8 +118,8 @@ public class ChangeRequestAttributeTest extends TestCase
|
|||||||
changeRequestAttribute.setChangePortFlag(MsgFixture.CHANGE_PORT_FLAG_1);
|
changeRequestAttribute.setChangePortFlag(MsgFixture.CHANGE_PORT_FLAG_1);
|
||||||
|
|
||||||
byte[] actualReturn = changeRequestAttribute.encode();
|
byte[] actualReturn = changeRequestAttribute.encode();
|
||||||
assertTrue("Object did not encode properly.",
|
assertArrayEquals(expectedReturn, actualReturn,
|
||||||
Arrays.equals(expectedReturn, actualReturn));
|
"Object did not encode properly.");
|
||||||
|
|
||||||
//2nd test
|
//2nd test
|
||||||
expectedReturn = binMessagesFixture.chngReqTestValue2;
|
expectedReturn = binMessagesFixture.chngReqTestValue2;
|
||||||
@ -133,27 +129,22 @@ public class ChangeRequestAttributeTest extends TestCase
|
|||||||
changeRequestAttribute.setChangePortFlag(MsgFixture.CHANGE_PORT_FLAG_2);
|
changeRequestAttribute.setChangePortFlag(MsgFixture.CHANGE_PORT_FLAG_2);
|
||||||
|
|
||||||
actualReturn = changeRequestAttribute.encode();
|
actualReturn = changeRequestAttribute.encode();
|
||||||
assertTrue("Object did not encode properly.",
|
assertArrayEquals(expectedReturn, actualReturn,
|
||||||
Arrays.equals(expectedReturn, actualReturn));
|
"Object did not encode properly.");
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Tests the equals method against a null, a different and an identical
|
* Tests the equals method against a null, a different and an identical
|
||||||
* object.
|
* object.
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testEquals()
|
public void testEquals()
|
||||||
{
|
{
|
||||||
ChangeRequestAttribute target = null;
|
|
||||||
boolean expectedReturn = false;
|
|
||||||
|
|
||||||
//null test
|
//null test
|
||||||
boolean actualReturn = changeRequestAttribute.equals(target);
|
assertNotEquals(changeRequestAttribute, null);
|
||||||
assertEquals("Null value test failed", expectedReturn, actualReturn);
|
|
||||||
|
|
||||||
//test against a different object.
|
//test against a different object.
|
||||||
target = new ChangeRequestAttribute();
|
ChangeRequestAttribute target = new ChangeRequestAttribute();
|
||||||
|
|
||||||
changeRequestAttribute.setChangeIpFlag(true);
|
changeRequestAttribute.setChangeIpFlag(true);
|
||||||
changeRequestAttribute.setChangePortFlag(false);
|
changeRequestAttribute.setChangePortFlag(false);
|
||||||
@ -161,9 +152,7 @@ public class ChangeRequestAttributeTest extends TestCase
|
|||||||
target.setChangeIpFlag(false);
|
target.setChangeIpFlag(false);
|
||||||
target.setChangePortFlag(true);
|
target.setChangePortFlag(true);
|
||||||
|
|
||||||
actualReturn = changeRequestAttribute.equals(target);
|
assertNotEquals(changeRequestAttribute, target);
|
||||||
assertEquals("Test against a different value failed",
|
|
||||||
expectedReturn, actualReturn);
|
|
||||||
|
|
||||||
//test against an equal value
|
//test against an equal value
|
||||||
target = new ChangeRequestAttribute();
|
target = new ChangeRequestAttribute();
|
||||||
@ -173,33 +162,27 @@ public class ChangeRequestAttributeTest extends TestCase
|
|||||||
|
|
||||||
target.setChangeIpFlag(true);
|
target.setChangeIpFlag(true);
|
||||||
target.setChangePortFlag(false);
|
target.setChangePortFlag(false);
|
||||||
|
assertEquals(changeRequestAttribute, target);
|
||||||
expectedReturn = true;
|
|
||||||
actualReturn = changeRequestAttribute.equals(target);
|
|
||||||
assertEquals("Test against an equals value failed",
|
|
||||||
expectedReturn, actualReturn);
|
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Test whether the returned value is always 4.
|
* Test whether the returned value is always 4.
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testGetDataLength()
|
public void testGetDataLength()
|
||||||
{
|
{
|
||||||
char expectedReturn = 4; // constant 4 bytes of data
|
char expectedReturn = 4; // constant 4 bytes of data
|
||||||
char actualReturn = changeRequestAttribute.getDataLength();
|
char actualReturn = changeRequestAttribute.getDataLength();
|
||||||
assertEquals("data length returned an invalid value",
|
assertEquals(expectedReturn, actualReturn,
|
||||||
expectedReturn, actualReturn);
|
"data length returned an invalid value");
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Test whether we get a relevant name.
|
* Test whether we get a relevant name.
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testGetName()
|
public void testGetName()
|
||||||
{
|
{
|
||||||
String expectedReturn = "CHANGE-REQUEST";
|
assertEquals("CHANGE-REQUEST", changeRequestAttribute.getName());
|
||||||
String actualReturn = changeRequestAttribute.getName();
|
|
||||||
assertEquals("Invalid name", expectedReturn, actualReturn);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@ -19,10 +19,9 @@ package org.ice4j.attribute;
|
|||||||
|
|
||||||
import org.ice4j.*;
|
import org.ice4j.*;
|
||||||
|
|
||||||
import java.util.*;
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
import junit.framework.*;
|
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.*;
|
||||||
/**
|
/**
|
||||||
* Class to test the ConnectionIdAttribute class.
|
* Class to test the ConnectionIdAttribute class.
|
||||||
*
|
*
|
||||||
@ -30,108 +29,86 @@ import junit.framework.*;
|
|||||||
*
|
*
|
||||||
*/
|
*/
|
||||||
public class ConnectionIdAttributeTest
|
public class ConnectionIdAttributeTest
|
||||||
extends TestCase
|
|
||||||
{
|
{
|
||||||
private ConnectionIdAttribute connectionIdAttribute = null;
|
private ConnectionIdAttribute connectionIdAttribute = null;
|
||||||
|
|
||||||
private MsgFixture msgFixture;
|
private MsgFixture msgFixture;
|
||||||
|
|
||||||
@Override
|
@BeforeEach
|
||||||
protected void setUp() throws Exception
|
public void setUp() throws Exception
|
||||||
{
|
{
|
||||||
super.setUp();
|
|
||||||
this.connectionIdAttribute = new ConnectionIdAttribute();
|
this.connectionIdAttribute = new ConnectionIdAttribute();
|
||||||
this.msgFixture = new MsgFixture();
|
this.msgFixture = new MsgFixture();
|
||||||
|
|
||||||
msgFixture.setUp();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@AfterEach
|
||||||
protected void tearDown() throws Exception
|
public void tearDown() throws Exception
|
||||||
{
|
{
|
||||||
this.connectionIdAttribute = null;
|
this.connectionIdAttribute = null;
|
||||||
this.msgFixture.tearDown();
|
|
||||||
|
|
||||||
this.msgFixture = null;
|
this.msgFixture = null;
|
||||||
super.tearDown();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Tests whether data length is properly calculated.
|
* Tests whether data length is properly calculated.
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testGetDataLength()
|
public void testGetDataLength()
|
||||||
{
|
{
|
||||||
char expectedReturn = 4;
|
char expectedReturn = 4;
|
||||||
this.connectionIdAttribute
|
this.connectionIdAttribute
|
||||||
.setConnectionIdValue(MsgFixture.CONNECTION_ID);
|
.setConnectionIdValue(MsgFixture.CONNECTION_ID);
|
||||||
char actualReturn = this.connectionIdAttribute.getDataLength();
|
char actualReturn = this.connectionIdAttribute.getDataLength();
|
||||||
assertEquals(
|
assertEquals(expectedReturn, actualReturn,
|
||||||
"Datalength is not properly calculated", expectedReturn,
|
"Datalength is not properly calculated");
|
||||||
actualReturn);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Tests getting the name.
|
* Tests getting the name.
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testGetName()
|
public void testGetName()
|
||||||
{
|
{
|
||||||
String expectedReturn = "CONNECTION-ID";
|
assertEquals("CONNECTION-ID", connectionIdAttribute.getName());
|
||||||
String actualReturn = connectionIdAttribute.getName();
|
|
||||||
assertEquals(
|
|
||||||
"getting name failed", expectedReturn, actualReturn);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Tests the equals method against a null, a different and an identical
|
* Tests the equals method against a null, a different and an identical
|
||||||
* object.
|
* object.
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testEqualsObject()
|
public void testEqualsObject()
|
||||||
{
|
{
|
||||||
// null test
|
// null test
|
||||||
ConnectionIdAttribute target = null;
|
assertNotEquals(connectionIdAttribute, null);
|
||||||
boolean expectedReturn = false;
|
|
||||||
boolean actualReturn = connectionIdAttribute.equals(target);
|
|
||||||
|
|
||||||
assertEquals(
|
|
||||||
"ConnectionIdAttribute.equals() failed against a null target.",
|
|
||||||
expectedReturn, actualReturn);
|
|
||||||
|
|
||||||
// difference test
|
// difference test
|
||||||
target = new ConnectionIdAttribute();
|
ConnectionIdAttribute target = new ConnectionIdAttribute();
|
||||||
|
|
||||||
int connectionId = MsgFixture.CONNECTION_ID_2;
|
int connectionId = MsgFixture.CONNECTION_ID_2;
|
||||||
target.setConnectionIdValue(connectionId);
|
target.setConnectionIdValue(connectionId);
|
||||||
|
|
||||||
connectionIdAttribute.setConnectionIdValue(MsgFixture.CONNECTION_ID);
|
connectionIdAttribute.setConnectionIdValue(MsgFixture.CONNECTION_ID);
|
||||||
expectedReturn = false;
|
assertNotEquals(connectionIdAttribute, target,
|
||||||
actualReturn = connectionIdAttribute.equals(target);
|
"ConnectionIdAttribute.equals() failed against a different target.");
|
||||||
assertEquals(
|
|
||||||
"ConnectionIdAttribute.equals() failed against a different target.",
|
|
||||||
expectedReturn, actualReturn);
|
|
||||||
|
|
||||||
// equality test
|
// equality test
|
||||||
target.setConnectionIdValue(MsgFixture.CONNECTION_ID);
|
target.setConnectionIdValue(MsgFixture.CONNECTION_ID);
|
||||||
|
assertEquals(connectionIdAttribute, target,
|
||||||
expectedReturn = true;
|
"ConnectionIdAttribute.equals() failed against an equal target.");
|
||||||
actualReturn = connectionIdAttribute.equals(target);
|
|
||||||
assertEquals(
|
|
||||||
"ConnectionIdAttribute.equals() failed against an equal target.",
|
|
||||||
expectedReturn, actualReturn);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Test whether attributes are properly encoded.
|
* Test whether attributes are properly encoded.
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testEncode()
|
public void testEncode()
|
||||||
{
|
{
|
||||||
byte[] expectedReturn = msgFixture.connectionId;
|
byte[] expectedReturn = msgFixture.connectionId;
|
||||||
connectionIdAttribute.setConnectionIdValue(MsgFixture.CONNECTION_ID);
|
connectionIdAttribute.setConnectionIdValue(MsgFixture.CONNECTION_ID);
|
||||||
byte[] actualReturn = connectionIdAttribute.encode();
|
byte[] actualReturn = connectionIdAttribute.encode();
|
||||||
|
|
||||||
assertTrue(
|
assertArrayEquals(expectedReturn, actualReturn,
|
||||||
"ConnectionIdAttribute.encode() did not "
|
"ConnectionIdAttribute.encode() did not properly encode a sample attribute");
|
||||||
+ "properly encode a sample attribute", Arrays.equals(
|
|
||||||
expectedReturn, actualReturn));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -140,6 +117,7 @@ public class ConnectionIdAttributeTest
|
|||||||
* @throws StunException if something goes wrong while decoding
|
* @throws StunException if something goes wrong while decoding
|
||||||
* Attribute Body.
|
* Attribute Body.
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testDecodeAttributeBody() throws StunException
|
public void testDecodeAttributeBody() throws StunException
|
||||||
{
|
{
|
||||||
byte[] attributeValue = msgFixture.connectionId;
|
byte[] attributeValue = msgFixture.connectionId;
|
||||||
@ -150,31 +128,31 @@ public class ConnectionIdAttributeTest
|
|||||||
attributeValue, offset, length);
|
attributeValue, offset, length);
|
||||||
|
|
||||||
assertEquals(
|
assertEquals(
|
||||||
"ConnectionIdAttribute.decode() did not properly decode the "
|
MsgFixture.CONNECTION_ID,
|
||||||
+ "connection id field.", MsgFixture.CONNECTION_ID,
|
connectionIdAttribute.getConnectionIdValue(),
|
||||||
connectionIdAttribute.getConnectionIdValue());
|
"ConnectionIdAttribute.decode() did not properly decode the connection id field."
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Tests that the connection Id is always integer.
|
* Tests that the connection Id is always integer.
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testGetConnectionIdValue()
|
public void testGetConnectionIdValue()
|
||||||
{
|
{
|
||||||
int expectedReturn = 0x5555;
|
int expectedReturn = 0x5555;
|
||||||
this.connectionIdAttribute
|
this.connectionIdAttribute
|
||||||
.setConnectionIdValue(MsgFixture.CONNECTION_ID);
|
.setConnectionIdValue(MsgFixture.CONNECTION_ID);
|
||||||
int actualReturn = this.connectionIdAttribute.getConnectionIdValue();
|
int actualReturn = this.connectionIdAttribute.getConnectionIdValue();
|
||||||
assertEquals(
|
assertEquals(expectedReturn, actualReturn,
|
||||||
"ConnectionId is not properly calculated", expectedReturn,
|
"ConnectionId is not properly calculated");
|
||||||
actualReturn);
|
|
||||||
|
|
||||||
expectedReturn = 0x2222;
|
expectedReturn = 0x2222;
|
||||||
this.connectionIdAttribute
|
this.connectionIdAttribute
|
||||||
.setConnectionIdValue(MsgFixture.CONNECTION_ID_2);
|
.setConnectionIdValue(MsgFixture.CONNECTION_ID_2);
|
||||||
actualReturn = this.connectionIdAttribute.getConnectionIdValue();
|
actualReturn = this.connectionIdAttribute.getConnectionIdValue();
|
||||||
assertEquals(
|
assertEquals(expectedReturn, actualReturn,
|
||||||
"ConnectionId is not properly calculated", expectedReturn,
|
"ConnectionId is not properly calculated");
|
||||||
actualReturn);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@ -17,51 +17,44 @@
|
|||||||
*/
|
*/
|
||||||
package org.ice4j.attribute;
|
package org.ice4j.attribute;
|
||||||
|
|
||||||
import junit.framework.*;
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
import java.util.Arrays;
|
|
||||||
|
|
||||||
import org.ice4j.*;
|
import org.ice4j.*;
|
||||||
|
import org.junit.jupiter.api.*;
|
||||||
/**
|
/**
|
||||||
*
|
*
|
||||||
* @author Emil Ivov
|
* @author Emil Ivov
|
||||||
*/
|
*/
|
||||||
public class ErrorCodeAttributeTest extends TestCase {
|
public class ErrorCodeAttributeTest
|
||||||
|
{
|
||||||
private ErrorCodeAttribute errorCodeAttribute = null;
|
private ErrorCodeAttribute errorCodeAttribute = null;
|
||||||
private MsgFixture msgFixture;
|
private MsgFixture msgFixture;
|
||||||
|
|
||||||
public ErrorCodeAttributeTest(String name) {
|
@BeforeEach
|
||||||
super(name);
|
public void setUp() throws Exception
|
||||||
}
|
{
|
||||||
|
|
||||||
protected void setUp() throws Exception {
|
|
||||||
super.setUp();
|
|
||||||
errorCodeAttribute = new ErrorCodeAttribute();
|
errorCodeAttribute = new ErrorCodeAttribute();
|
||||||
msgFixture = new MsgFixture();
|
msgFixture = new MsgFixture();
|
||||||
|
|
||||||
msgFixture.setUp();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
protected void tearDown() throws Exception {
|
@AfterEach
|
||||||
|
public void tearDown() throws Exception {
|
||||||
errorCodeAttribute = null;
|
errorCodeAttribute = null;
|
||||||
msgFixture.tearDown();
|
|
||||||
|
|
||||||
msgFixture = null;
|
msgFixture = null;
|
||||||
super.tearDown();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Test Attribute type
|
* Test Attribute type
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testErrorCodeAttribute()
|
public void testErrorCodeAttribute()
|
||||||
{
|
{
|
||||||
|
|
||||||
errorCodeAttribute = new ErrorCodeAttribute();
|
errorCodeAttribute = new ErrorCodeAttribute();
|
||||||
|
assertEquals(
|
||||||
assertEquals("ErrorCodeAttribute() constructed an attribute with an invalid type",
|
|
||||||
Attribute.ERROR_CODE,
|
Attribute.ERROR_CODE,
|
||||||
errorCodeAttribute.getAttributeType());
|
errorCodeAttribute.getAttributeType(),
|
||||||
|
"ErrorCodeAttribute() constructed an attribute with an invalid type"
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -69,6 +62,7 @@ public class ErrorCodeAttributeTest extends TestCase {
|
|||||||
*
|
*
|
||||||
* @throws StunException java.lang.Exception if we fail
|
* @throws StunException java.lang.Exception if we fail
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testDecodeAttributeBody()
|
public void testDecodeAttributeBody()
|
||||||
throws StunException {
|
throws StunException {
|
||||||
byte[] attributeValue = msgFixture.errCodeTestValue;
|
byte[] attributeValue = msgFixture.errCodeTestValue;
|
||||||
@ -76,18 +70,22 @@ public class ErrorCodeAttributeTest extends TestCase {
|
|||||||
char length = (char)(attributeValue.length - Attribute.HEADER_LENGTH);
|
char length = (char)(attributeValue.length - Attribute.HEADER_LENGTH);
|
||||||
errorCodeAttribute.decodeAttributeBody(attributeValue, offset, length);
|
errorCodeAttribute.decodeAttributeBody(attributeValue, offset, length);
|
||||||
|
|
||||||
assertEquals("Error Class was not correctly decoded",
|
assertEquals(
|
||||||
MsgFixture.ERROR_CLASS,
|
MsgFixture.ERROR_CLASS,
|
||||||
errorCodeAttribute.getErrorClass());
|
errorCodeAttribute.getErrorClass(),
|
||||||
|
"Error Class was not correctly decoded"
|
||||||
|
);
|
||||||
|
|
||||||
assertEquals("Error Number was not correctly decoded",
|
assertEquals(
|
||||||
MsgFixture.ERROR_NUMBER,
|
MsgFixture.ERROR_NUMBER,
|
||||||
errorCodeAttribute.getErrorNumber());
|
errorCodeAttribute.getErrorNumber(),
|
||||||
|
"Error Number was not correctly decoded"
|
||||||
|
);
|
||||||
|
|
||||||
assertEquals("Reason phrase was not correctly decoded",
|
assertEquals(
|
||||||
MsgFixture.REASON_PHRASE.trim(),
|
MsgFixture.REASON_PHRASE.trim(),
|
||||||
errorCodeAttribute.getReasonPhrase().trim());
|
errorCodeAttribute.getReasonPhrase().trim(),
|
||||||
|
"Reason phrase was not correctly decoded");
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -96,6 +94,7 @@ public class ErrorCodeAttributeTest extends TestCase {
|
|||||||
*
|
*
|
||||||
* @throws StunException java.lang.Exception if we fail
|
* @throws StunException java.lang.Exception if we fail
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testEncode()
|
public void testEncode()
|
||||||
throws StunException
|
throws StunException
|
||||||
{
|
{
|
||||||
@ -108,8 +107,8 @@ public class ErrorCodeAttributeTest extends TestCase {
|
|||||||
|
|
||||||
byte[] actualReturn = errorCodeAttribute.encode();
|
byte[] actualReturn = errorCodeAttribute.encode();
|
||||||
|
|
||||||
assertTrue("encode() did not return the expected binary array.",
|
assertArrayEquals(expectedReturn, actualReturn,
|
||||||
Arrays.equals( expectedReturn, actualReturn));
|
"encode() did not return the expected binary array.");
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -118,20 +117,17 @@ public class ErrorCodeAttributeTest extends TestCase {
|
|||||||
*
|
*
|
||||||
* @throws StunException java.lang.Exception if we fail
|
* @throws StunException java.lang.Exception if we fail
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testEquals()
|
public void testEquals()
|
||||||
throws StunException
|
throws StunException
|
||||||
{
|
{
|
||||||
|
|
||||||
//null value test
|
//null value test
|
||||||
ErrorCodeAttribute target = null;
|
assertNotEquals(errorCodeAttribute, null,
|
||||||
boolean expectedReturn = false;
|
"equals() failed against a null value target.");
|
||||||
boolean actualReturn = errorCodeAttribute.equals(target);
|
|
||||||
assertEquals("equals() failed against a null value target.",
|
|
||||||
expectedReturn, actualReturn);
|
|
||||||
|
|
||||||
//different objects
|
//different objects
|
||||||
|
ErrorCodeAttribute target;
|
||||||
target = new ErrorCodeAttribute();
|
target = new ErrorCodeAttribute();
|
||||||
expectedReturn = false;
|
|
||||||
|
|
||||||
target.setErrorClass(MsgFixture.ERROR_CLASS);
|
target.setErrorClass(MsgFixture.ERROR_CLASS);
|
||||||
target.setErrorNumber(MsgFixture.ERROR_NUMBER);
|
target.setErrorNumber(MsgFixture.ERROR_NUMBER);
|
||||||
@ -139,14 +135,12 @@ public class ErrorCodeAttributeTest extends TestCase {
|
|||||||
errorCodeAttribute.setErrorClass((byte)(MsgFixture.ERROR_CLASS+1));
|
errorCodeAttribute.setErrorClass((byte)(MsgFixture.ERROR_CLASS+1));
|
||||||
errorCodeAttribute.setErrorNumber((byte)(MsgFixture.ERROR_NUMBER+1));
|
errorCodeAttribute.setErrorNumber((byte)(MsgFixture.ERROR_NUMBER+1));
|
||||||
|
|
||||||
actualReturn = errorCodeAttribute.equals(target);
|
assertNotEquals(errorCodeAttribute, target,
|
||||||
assertEquals("equals() failed against a not equal target.",
|
"equals() failed against a not equal target.");
|
||||||
expectedReturn, actualReturn);
|
|
||||||
|
|
||||||
//different objects
|
//equal objects
|
||||||
target = new ErrorCodeAttribute();
|
target = new ErrorCodeAttribute();
|
||||||
errorCodeAttribute = new ErrorCodeAttribute();
|
errorCodeAttribute = new ErrorCodeAttribute();
|
||||||
expectedReturn = true;
|
|
||||||
|
|
||||||
target.setErrorClass(MsgFixture.ERROR_CLASS);
|
target.setErrorClass(MsgFixture.ERROR_CLASS);
|
||||||
target.setErrorNumber(MsgFixture.ERROR_NUMBER);
|
target.setErrorNumber(MsgFixture.ERROR_NUMBER);
|
||||||
@ -154,11 +148,8 @@ public class ErrorCodeAttributeTest extends TestCase {
|
|||||||
errorCodeAttribute.setErrorClass(MsgFixture.ERROR_CLASS);
|
errorCodeAttribute.setErrorClass(MsgFixture.ERROR_CLASS);
|
||||||
errorCodeAttribute.setErrorNumber(MsgFixture.ERROR_NUMBER);
|
errorCodeAttribute.setErrorNumber(MsgFixture.ERROR_NUMBER);
|
||||||
|
|
||||||
actualReturn = errorCodeAttribute.equals(target);
|
assertEquals(errorCodeAttribute, target,
|
||||||
assertEquals("equals() failed against a not equal target.",
|
"equals() failed against an equal target.");
|
||||||
expectedReturn, actualReturn);
|
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -166,6 +157,7 @@ public class ErrorCodeAttributeTest extends TestCase {
|
|||||||
*
|
*
|
||||||
* @throws StunException java.lang.Exception if we fail
|
* @throws StunException java.lang.Exception if we fail
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testGetDataLength()
|
public void testGetDataLength()
|
||||||
throws StunException
|
throws StunException
|
||||||
{
|
{
|
||||||
@ -177,16 +169,14 @@ public class ErrorCodeAttributeTest extends TestCase {
|
|||||||
errorCodeAttribute.setReasonPhrase(MsgFixture.REASON_PHRASE);
|
errorCodeAttribute.setReasonPhrase(MsgFixture.REASON_PHRASE);
|
||||||
|
|
||||||
char actualReturn = errorCodeAttribute.getDataLength();
|
char actualReturn = errorCodeAttribute.getDataLength();
|
||||||
assertEquals("data length1", expectedReturn, actualReturn);
|
assertEquals(expectedReturn, actualReturn, "data length1");
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Test whether error code is properly calculated from error class and number
|
* Test whether error code is properly calculated from error class and number
|
||||||
*
|
|
||||||
* @throws StunException java.lang.Exception if we fail
|
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testGetErrorCode()
|
public void testGetErrorCode()
|
||||||
throws StunException
|
|
||||||
{
|
{
|
||||||
char expectedReturn = (char)(100*MsgFixture.ERROR_CLASS
|
char expectedReturn = (char)(100*MsgFixture.ERROR_CLASS
|
||||||
+ MsgFixture.ERROR_NUMBER);
|
+ MsgFixture.ERROR_NUMBER);
|
||||||
@ -195,35 +185,36 @@ public class ErrorCodeAttributeTest extends TestCase {
|
|||||||
errorCodeAttribute.setErrorNumber(MsgFixture.ERROR_NUMBER);
|
errorCodeAttribute.setErrorNumber(MsgFixture.ERROR_NUMBER);
|
||||||
|
|
||||||
char actualReturn = errorCodeAttribute.getErrorCode();
|
char actualReturn = errorCodeAttribute.getErrorCode();
|
||||||
assertEquals("return value", expectedReturn, actualReturn);
|
assertEquals(expectedReturn, actualReturn);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Test whether we get a proper name for that attribute.
|
* Test whether we get a proper name for that attribute.
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testGetName() {
|
public void testGetName() {
|
||||||
String expectedReturn = "ERROR-CODE";
|
assertEquals("ERROR-CODE", errorCodeAttribute.getName());
|
||||||
String actualReturn = errorCodeAttribute.getName();
|
|
||||||
assertEquals("return value", expectedReturn, actualReturn);
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Test whether error code is properly calculated from error class and number
|
* Test whether error code is properly calculated from error class and number
|
||||||
*
|
*
|
||||||
* @throws StunException java.lang.Exception if we fail
|
|
||||||
*/
|
*/
|
||||||
public void testSetErrorCode() throws StunException {
|
@Test
|
||||||
|
public void testSetErrorCode()
|
||||||
|
{
|
||||||
char errorCode = (char)(MsgFixture.ERROR_CLASS*100 + MsgFixture.ERROR_NUMBER);
|
char errorCode = (char)(MsgFixture.ERROR_CLASS*100 + MsgFixture.ERROR_NUMBER);
|
||||||
errorCodeAttribute.setErrorCode(errorCode);
|
errorCodeAttribute.setErrorCode(errorCode);
|
||||||
|
|
||||||
assertEquals("An error class was not properly set after decoding an error code.",
|
assertEquals(
|
||||||
(int)MsgFixture.ERROR_CLASS,
|
MsgFixture.ERROR_CLASS,
|
||||||
(int)errorCodeAttribute.getErrorClass());
|
(int) errorCodeAttribute.getErrorClass(),
|
||||||
assertEquals("An error number was not properly set after decoding an error code.",
|
"An error class was not properly set after decoding an error code."
|
||||||
(int)MsgFixture.ERROR_NUMBER,
|
);
|
||||||
(int)errorCodeAttribute.getErrorNumber());
|
assertEquals(
|
||||||
|
MsgFixture.ERROR_NUMBER,
|
||||||
|
(int) errorCodeAttribute.getErrorNumber(),
|
||||||
|
"An error number was not properly set after decoding an error code."
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@ -17,19 +17,17 @@
|
|||||||
*/
|
*/
|
||||||
package org.ice4j.attribute;
|
package org.ice4j.attribute;
|
||||||
|
|
||||||
import junit.framework.*;
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
import java.util.*;
|
|
||||||
|
|
||||||
import org.ice4j.*;
|
import org.ice4j.*;
|
||||||
|
import org.junit.jupiter.api.*;
|
||||||
/**
|
/**
|
||||||
* Tests the nonce attribute class.
|
* Tests the nonce attribute class.
|
||||||
*
|
*
|
||||||
* @author Emil Ivov
|
* @author Emil Ivov
|
||||||
* @author Sebastien Vincent
|
* @author Sebastien Vincent
|
||||||
*/
|
*/
|
||||||
public class NonceAttributeTest extends TestCase
|
public class NonceAttributeTest
|
||||||
{
|
{
|
||||||
private NonceAttribute nonceAttribute = null;
|
private NonceAttribute nonceAttribute = null;
|
||||||
MsgFixture msgFixture = null;
|
MsgFixture msgFixture = null;
|
||||||
@ -40,30 +38,26 @@ public class NonceAttributeTest extends TestCase
|
|||||||
0, (byte)nonceValue.length(),
|
0, (byte)nonceValue.length(),
|
||||||
'0', '1', '2', '3', '4', '5', '6','7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
|
'0', '1', '2', '3', '4', '5', '6','7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
|
||||||
|
|
||||||
protected void setUp() throws Exception
|
@BeforeEach
|
||||||
|
public void setUp() throws Exception
|
||||||
{
|
{
|
||||||
super.setUp();
|
|
||||||
msgFixture = new MsgFixture();
|
msgFixture = new MsgFixture();
|
||||||
|
|
||||||
nonceAttribute = new NonceAttribute();
|
nonceAttribute = new NonceAttribute();
|
||||||
nonceAttribute.setNonce(nonceValue.getBytes());
|
nonceAttribute.setNonce(nonceValue.getBytes());
|
||||||
|
|
||||||
msgFixture.setUp();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
protected void tearDown() throws Exception
|
@AfterEach
|
||||||
|
public void tearDown() throws Exception
|
||||||
{
|
{
|
||||||
nonceAttribute = null;
|
nonceAttribute = null;
|
||||||
msgFixture.tearDown();
|
|
||||||
|
|
||||||
msgFixture = null;
|
msgFixture = null;
|
||||||
super.tearDown();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Tests decoding of the nonce attribute.
|
* Tests decoding of the nonce attribute.
|
||||||
* @throws StunException upon a failure
|
* @throws StunException upon a failure
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testDecodeAttributeBody() throws StunException
|
public void testDecodeAttributeBody() throws StunException
|
||||||
{
|
{
|
||||||
char offset = 0;
|
char offset = 0;
|
||||||
@ -72,63 +66,63 @@ public class NonceAttributeTest extends TestCase
|
|||||||
decoded.decodeAttributeBody(nonceValue.getBytes(), offset, length);
|
decoded.decodeAttributeBody(nonceValue.getBytes(), offset, length);
|
||||||
|
|
||||||
//nonce value
|
//nonce value
|
||||||
assertEquals( "decode failed", nonceAttribute, decoded);
|
assertEquals(nonceAttribute, decoded, "decode failed");
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Tests the encode method
|
* Tests the encode method
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testEncode()
|
public void testEncode()
|
||||||
{
|
{
|
||||||
assertTrue("encode failed",
|
assertArrayEquals(nonceAttribute.encode(), attributeBinValue,
|
||||||
Arrays.equals(nonceAttribute.encode(),
|
"encode failed");
|
||||||
attributeBinValue));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Test Equals
|
* Test Equals
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testEquals()
|
public void testEquals()
|
||||||
{
|
{
|
||||||
NonceAttribute nonceAttribute2 = new NonceAttribute();
|
NonceAttribute nonceAttribute2 = new NonceAttribute();
|
||||||
nonceAttribute2.setNonce(nonceValue.getBytes());
|
nonceAttribute2.setNonce(nonceValue.getBytes());
|
||||||
|
|
||||||
//test positive equals
|
//test positive equals
|
||||||
assertEquals("testequals failed", nonceAttribute, nonceAttribute2);
|
assertEquals(nonceAttribute, nonceAttribute2);
|
||||||
|
|
||||||
//test negative equals
|
//test negative equals
|
||||||
nonceAttribute2 = new NonceAttribute();
|
nonceAttribute2 = new NonceAttribute();
|
||||||
nonceAttribute2.setNonce("some other nonce".getBytes());
|
nonceAttribute2.setNonce("some other nonce".getBytes());
|
||||||
|
|
||||||
//test positive equals
|
//test positive equals
|
||||||
assertFalse("testequals failed",
|
assertNotEquals(nonceAttribute2, nonceAttribute);
|
||||||
nonceAttribute.equals(nonceAttribute2));
|
|
||||||
|
|
||||||
//test null equals
|
//test null equals
|
||||||
assertFalse("testequals failed",
|
assertNotEquals(nonceAttribute, null);
|
||||||
nonceAttribute.equals(null));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Tests extracting data length
|
* Tests extracting data length
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testGetDataLength()
|
public void testGetDataLength()
|
||||||
{
|
{
|
||||||
char expectedReturn = (char)nonceValue.length();
|
char expectedReturn = (char)nonceValue.length();
|
||||||
char actualReturn = nonceAttribute.getDataLength();
|
char actualReturn = nonceAttribute.getDataLength();
|
||||||
assertEquals("getDataLength - failed", expectedReturn, actualReturn);
|
assertEquals(expectedReturn, actualReturn);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Tests getting the name
|
* Tests getting the name
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testGetName()
|
public void testGetName()
|
||||||
{
|
{
|
||||||
String expectedReturn = "NONCE";
|
assertEquals("NONCE", nonceAttribute.getName());
|
||||||
String actualReturn = nonceAttribute.getName();
|
|
||||||
assertEquals("getting name failed", expectedReturn, actualReturn);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testSetGetNonce()
|
public void testSetGetNonce()
|
||||||
{
|
{
|
||||||
byte[] expectedReturn = nonceValue.getBytes();
|
byte[] expectedReturn = nonceValue.getBytes();
|
||||||
@ -137,8 +131,7 @@ public class NonceAttributeTest extends TestCase
|
|||||||
att.setNonce(expectedReturn);
|
att.setNonce(expectedReturn);
|
||||||
|
|
||||||
byte[] actualReturn = att.getNonce();
|
byte[] actualReturn = att.getNonce();
|
||||||
assertTrue("nonce setter or getter failed",
|
assertArrayEquals(expectedReturn, actualReturn,
|
||||||
Arrays.equals( expectedReturn,
|
"nonce setter or getter failed");
|
||||||
actualReturn));
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -17,25 +17,22 @@
|
|||||||
*/
|
*/
|
||||||
package org.ice4j.attribute;
|
package org.ice4j.attribute;
|
||||||
|
|
||||||
import junit.framework.*;
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
import java.util.Arrays;
|
|
||||||
|
|
||||||
import org.ice4j.*;
|
import org.ice4j.*;
|
||||||
|
import org.junit.jupiter.api.*;
|
||||||
/**
|
/**
|
||||||
* @author Emil Ivov
|
* @author Emil Ivov
|
||||||
*/
|
*/
|
||||||
public class OptionalAttributeAttributeTest extends TestCase
|
public class OptionalAttributeAttributeTest
|
||||||
{
|
{
|
||||||
private OptionalAttribute optionalAttribute = null;
|
private OptionalAttribute optionalAttribute = null;
|
||||||
private MsgFixture msgFixture = null;
|
private MsgFixture msgFixture = null;
|
||||||
byte[] expectedAttributeValue = null;
|
byte[] expectedAttributeValue = null;
|
||||||
|
|
||||||
protected void setUp() throws Exception
|
@BeforeEach
|
||||||
|
public void setUp() throws Exception
|
||||||
{
|
{
|
||||||
super.setUp();
|
|
||||||
|
|
||||||
msgFixture = new MsgFixture();
|
msgFixture = new MsgFixture();
|
||||||
int offset = Attribute.HEADER_LENGTH;
|
int offset = Attribute.HEADER_LENGTH;
|
||||||
|
|
||||||
@ -51,17 +48,18 @@ public class OptionalAttributeAttributeTest extends TestCase
|
|||||||
msgFixture.optionalAttributeType);
|
msgFixture.optionalAttributeType);
|
||||||
}
|
}
|
||||||
|
|
||||||
protected void tearDown() throws Exception
|
@AfterEach
|
||||||
|
public void tearDown() throws Exception
|
||||||
{
|
{
|
||||||
optionalAttribute = null;
|
optionalAttribute = null;
|
||||||
expectedAttributeValue = null;
|
expectedAttributeValue = null;
|
||||||
super.tearDown();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Test whether sample binary arrays are correctly decoded.
|
* Test whether sample binary arrays are correctly decoded.
|
||||||
* @throws StunException if anything goes wrong.
|
* @throws StunException if anything goes wrong.
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testDecodeAttributeBody() throws StunException {
|
public void testDecodeAttributeBody() throws StunException {
|
||||||
|
|
||||||
char offset = Attribute.HEADER_LENGTH;
|
char offset = Attribute.HEADER_LENGTH;
|
||||||
@ -70,60 +68,52 @@ public class OptionalAttributeAttributeTest extends TestCase
|
|||||||
optionalAttribute.decodeAttributeBody(msgFixture.unknownOptionalAttribute,
|
optionalAttribute.decodeAttributeBody(msgFixture.unknownOptionalAttribute,
|
||||||
offset, length);
|
offset, length);
|
||||||
|
|
||||||
|
assertArrayEquals(
|
||||||
|
expectedAttributeValue, optionalAttribute.getBody(),
|
||||||
|
"OptionalAttribute did not decode properly.");
|
||||||
|
|
||||||
assertTrue("OptionalAttribute did not decode properly.",
|
assertEquals(length, optionalAttribute.getDataLength(),
|
||||||
Arrays.equals( expectedAttributeValue,
|
"Length was not properly decoded");
|
||||||
optionalAttribute.getBody()));
|
|
||||||
|
|
||||||
assertEquals("Lenght was not properly decoded", length,
|
|
||||||
optionalAttribute.getDataLength());
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Test whether attributes are properly encoded
|
* Test whether attributes are properly encoded
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testEncode()
|
public void testEncode()
|
||||||
{
|
{
|
||||||
optionalAttribute.setBody(expectedAttributeValue, 0,
|
optionalAttribute.setBody(expectedAttributeValue, 0,
|
||||||
expectedAttributeValue.length);
|
expectedAttributeValue.length);
|
||||||
|
|
||||||
byte[] actualReturn = optionalAttribute.encode();
|
byte[] actualReturn = optionalAttribute.encode();
|
||||||
|
assertArrayEquals(msgFixture.unknownOptionalAttribute, actualReturn);
|
||||||
assertTrue("encode failed",
|
|
||||||
Arrays.equals( msgFixture.unknownOptionalAttribute, actualReturn) );
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Test whether the equals method works ok
|
* Test whether the equals method works ok
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testEquals()
|
public void testEquals()
|
||||||
{
|
{
|
||||||
//null comparison
|
//null comparison
|
||||||
Object obj = null;
|
|
||||||
boolean expectedReturn = false;
|
|
||||||
optionalAttribute.setBody( expectedAttributeValue, 0,
|
optionalAttribute.setBody( expectedAttributeValue, 0,
|
||||||
expectedAttributeValue.length);
|
expectedAttributeValue.length);
|
||||||
|
|
||||||
boolean actualReturn = optionalAttribute.equals(obj);
|
assertNotEquals(optionalAttribute, null);
|
||||||
assertEquals("failed null comparison", expectedReturn, actualReturn);
|
|
||||||
|
|
||||||
//wrong type comparison
|
//wrong type comparison
|
||||||
obj = "hehe :)";
|
assertNotEquals(optionalAttribute, "hehe :)");
|
||||||
actualReturn = optionalAttribute.equals(obj);
|
|
||||||
assertEquals("failed wrong type comparison", expectedReturn,
|
|
||||||
actualReturn);
|
|
||||||
|
|
||||||
//succesful comparison
|
//succesful comparison
|
||||||
obj = new OptionalAttribute(msgFixture.optionalAttributeType);
|
OptionalAttribute obj =
|
||||||
|
new OptionalAttribute(msgFixture.optionalAttributeType);
|
||||||
|
|
||||||
((OptionalAttribute)obj).setBody( expectedAttributeValue, 0,
|
obj.setBody( expectedAttributeValue, 0,
|
||||||
expectedAttributeValue.length);
|
expectedAttributeValue.length);
|
||||||
expectedReturn = true;
|
assertEquals(obj, optionalAttribute);
|
||||||
actualReturn = optionalAttribute.equals(obj);
|
|
||||||
assertEquals("failed null comparison", expectedReturn, actualReturn);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testGetDataLength()
|
public void testGetDataLength()
|
||||||
{
|
{
|
||||||
char expectedReturn = (char)expectedAttributeValue.length;
|
char expectedReturn = (char)expectedAttributeValue.length;
|
||||||
@ -132,7 +122,7 @@ public class OptionalAttributeAttributeTest extends TestCase
|
|||||||
expectedAttributeValue.length);
|
expectedAttributeValue.length);
|
||||||
|
|
||||||
char actualReturn = optionalAttribute.getDataLength();
|
char actualReturn = optionalAttribute.getDataLength();
|
||||||
assertEquals("return value", expectedReturn, actualReturn);
|
assertEquals(expectedReturn, actualReturn);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@ -17,19 +17,17 @@
|
|||||||
*/
|
*/
|
||||||
package org.ice4j.attribute;
|
package org.ice4j.attribute;
|
||||||
|
|
||||||
import junit.framework.*;
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
import java.util.*;
|
|
||||||
|
|
||||||
import org.ice4j.*;
|
import org.ice4j.*;
|
||||||
|
import org.junit.jupiter.api.*;
|
||||||
/**
|
/**
|
||||||
* Tests the realm attribute class.
|
* Tests the realm attribute class.
|
||||||
*
|
*
|
||||||
* @author Emil Ivov
|
* @author Emil Ivov
|
||||||
* @author Sebastien Vincent
|
* @author Sebastien Vincent
|
||||||
*/
|
*/
|
||||||
public class RealmAttributeTest extends TestCase
|
public class RealmAttributeTest
|
||||||
{
|
{
|
||||||
private RealmAttribute realmAttribute = null;
|
private RealmAttribute realmAttribute = null;
|
||||||
MsgFixture msgFixture = null;
|
MsgFixture msgFixture = null;
|
||||||
@ -40,30 +38,27 @@ public class RealmAttributeTest extends TestCase
|
|||||||
0, (byte)realmValue.length(),
|
0, (byte)realmValue.length(),
|
||||||
'd', 'o', 'm', 'a', 'i', 'n', '.', 'o', 'r', 'g', 0x00, 0x00};
|
'd', 'o', 'm', 'a', 'i', 'n', '.', 'o', 'r', 'g', 0x00, 0x00};
|
||||||
|
|
||||||
protected void setUp() throws Exception
|
@BeforeEach
|
||||||
|
public void setUp() throws Exception
|
||||||
{
|
{
|
||||||
super.setUp();
|
|
||||||
msgFixture = new MsgFixture();
|
msgFixture = new MsgFixture();
|
||||||
|
|
||||||
realmAttribute = new RealmAttribute();
|
realmAttribute = new RealmAttribute();
|
||||||
realmAttribute.setRealm(realmValue.getBytes());
|
realmAttribute.setRealm(realmValue.getBytes());
|
||||||
|
|
||||||
msgFixture.setUp();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
protected void tearDown() throws Exception
|
@AfterEach
|
||||||
|
public void tearDown() throws Exception
|
||||||
{
|
{
|
||||||
realmAttribute = null;
|
realmAttribute = null;
|
||||||
msgFixture.tearDown();
|
|
||||||
|
|
||||||
msgFixture = null;
|
msgFixture = null;
|
||||||
super.tearDown();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Tests decoding of the realm attribute.
|
* Tests decoding of the realm attribute.
|
||||||
* @throws StunException upon a failure
|
* @throws StunException upon a failure
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testDecodeAttributeBody() throws StunException
|
public void testDecodeAttributeBody() throws StunException
|
||||||
{
|
{
|
||||||
char offset = 0;
|
char offset = 0;
|
||||||
@ -72,63 +67,62 @@ public class RealmAttributeTest extends TestCase
|
|||||||
decoded.decodeAttributeBody(realmValue.getBytes(), offset, length);
|
decoded.decodeAttributeBody(realmValue.getBytes(), offset, length);
|
||||||
|
|
||||||
//realm value
|
//realm value
|
||||||
assertEquals( "decode failed", realmAttribute, decoded);
|
assertEquals(realmAttribute, decoded);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Tests the encode method
|
* Tests the encode method
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testEncode()
|
public void testEncode()
|
||||||
{
|
{
|
||||||
assertTrue("encode failed",
|
assertArrayEquals(realmAttribute.encode(), attributeBinValue);
|
||||||
Arrays.equals(realmAttribute.encode(),
|
|
||||||
attributeBinValue));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Test Equals
|
* Test Equals
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testEquals()
|
public void testEquals()
|
||||||
{
|
{
|
||||||
RealmAttribute realmAttribute2 = new RealmAttribute();
|
RealmAttribute realmAttribute2 = new RealmAttribute();
|
||||||
realmAttribute2.setRealm(realmValue.getBytes());
|
realmAttribute2.setRealm(realmValue.getBytes());
|
||||||
|
|
||||||
//test positive equals
|
//test positive equals
|
||||||
assertEquals("testequals failed", realmAttribute, realmAttribute2);
|
assertEquals(realmAttribute, realmAttribute2);
|
||||||
|
|
||||||
//test negative equals
|
//test negative equals
|
||||||
realmAttribute2 = new RealmAttribute();
|
realmAttribute2 = new RealmAttribute();
|
||||||
realmAttribute2.setRealm("some other realm".getBytes());
|
realmAttribute2.setRealm("some other realm".getBytes());
|
||||||
|
|
||||||
//test positive equals
|
//test positive equals
|
||||||
assertFalse("testequals failed",
|
assertNotEquals(realmAttribute2, realmAttribute);
|
||||||
realmAttribute.equals(realmAttribute2));
|
|
||||||
|
|
||||||
//test null equals
|
//test null equals
|
||||||
assertFalse("testequals failed",
|
assertNotEquals(realmAttribute, null);
|
||||||
realmAttribute.equals(null));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Tests extracting data length
|
* Tests extracting data length
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testGetDataLength()
|
public void testGetDataLength()
|
||||||
{
|
{
|
||||||
char expectedReturn = (char)realmValue.length();
|
char expectedReturn = (char)realmValue.length();
|
||||||
char actualReturn = realmAttribute.getDataLength();
|
char actualReturn = realmAttribute.getDataLength();
|
||||||
assertEquals("getDataLength - failed", expectedReturn, actualReturn);
|
assertEquals(expectedReturn, actualReturn);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Tests getting the name
|
* Tests getting the name
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testGetName()
|
public void testGetName()
|
||||||
{
|
{
|
||||||
String expectedReturn = "REALM";
|
assertEquals("REALM", realmAttribute.getName());
|
||||||
String actualReturn = realmAttribute.getName();
|
|
||||||
assertEquals("getting name failed", expectedReturn, actualReturn);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testSetGetRealm()
|
public void testSetGetRealm()
|
||||||
{
|
{
|
||||||
byte[] expectedReturn = realmValue.getBytes();
|
byte[] expectedReturn = realmValue.getBytes();
|
||||||
@ -137,8 +131,7 @@ public class RealmAttributeTest extends TestCase
|
|||||||
att.setRealm(expectedReturn);
|
att.setRealm(expectedReturn);
|
||||||
|
|
||||||
byte[] actualReturn = att.getRealm();
|
byte[] actualReturn = att.getRealm();
|
||||||
assertTrue("realm setter or getter failed",
|
assertArrayEquals(expectedReturn, actualReturn,
|
||||||
Arrays.equals( expectedReturn,
|
"realm setter or getter failed");
|
||||||
actualReturn));
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -17,12 +17,10 @@
|
|||||||
*/
|
*/
|
||||||
package org.ice4j.attribute;
|
package org.ice4j.attribute;
|
||||||
|
|
||||||
import java.util.*;
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
import junit.framework.*;
|
|
||||||
|
|
||||||
import org.ice4j.*;
|
import org.ice4j.*;
|
||||||
|
import org.junit.jupiter.api.*;
|
||||||
/**
|
/**
|
||||||
* Class to test the RequestedAddressFamilyAttribute class.
|
* Class to test the RequestedAddressFamilyAttribute class.
|
||||||
*
|
*
|
||||||
@ -30,42 +28,31 @@ import org.ice4j.*;
|
|||||||
*
|
*
|
||||||
*/
|
*/
|
||||||
public class RequestedAddressFamilyAttributeTest
|
public class RequestedAddressFamilyAttributeTest
|
||||||
extends TestCase
|
|
||||||
{
|
{
|
||||||
private RequestedAddressFamilyAttribute requestedAddressFamilyAttribute =
|
private RequestedAddressFamilyAttribute requestedAddressFamilyAttribute =
|
||||||
null;
|
null;
|
||||||
|
|
||||||
private MsgFixture msgFixture;
|
private MsgFixture msgFixture;
|
||||||
|
|
||||||
@Override
|
@BeforeEach
|
||||||
protected void setUp() throws Exception
|
public void setUp() throws Exception
|
||||||
{
|
{
|
||||||
super.setUp();
|
|
||||||
this.requestedAddressFamilyAttribute =
|
this.requestedAddressFamilyAttribute =
|
||||||
new RequestedAddressFamilyAttribute();
|
new RequestedAddressFamilyAttribute();
|
||||||
this.msgFixture = new MsgFixture();
|
this.msgFixture = new MsgFixture();
|
||||||
|
|
||||||
msgFixture.setUp();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public RequestedAddressFamilyAttributeTest(String name)
|
@AfterEach
|
||||||
{
|
public void tearDown() throws Exception
|
||||||
super(name);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
protected void tearDown() throws Exception
|
|
||||||
{
|
{
|
||||||
this.requestedAddressFamilyAttribute = null;
|
this.requestedAddressFamilyAttribute = null;
|
||||||
this.msgFixture.tearDown();
|
|
||||||
|
|
||||||
this.msgFixture = null;
|
this.msgFixture = null;
|
||||||
super.tearDown();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Tests whether data length is properly calculated.
|
* Tests whether data length is properly calculated.
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testGetDataLength()
|
public void testGetDataLength()
|
||||||
{
|
{
|
||||||
char expectedReturn = 1;
|
char expectedReturn = 1;
|
||||||
@ -73,47 +60,39 @@ public class RequestedAddressFamilyAttributeTest
|
|||||||
.setFamily(MsgFixture.REQUESTED_ADDRESS_FAMILY_ATTRIBUTE_V4);
|
.setFamily(MsgFixture.REQUESTED_ADDRESS_FAMILY_ATTRIBUTE_V4);
|
||||||
char actualReturn =
|
char actualReturn =
|
||||||
this.requestedAddressFamilyAttribute.getDataLength();
|
this.requestedAddressFamilyAttribute.getDataLength();
|
||||||
assertEquals(
|
assertEquals(expectedReturn, actualReturn,
|
||||||
"Datalength is not properly calculated", expectedReturn,
|
"Datalength is not properly calculated");
|
||||||
actualReturn);
|
|
||||||
|
|
||||||
expectedReturn = 1;
|
expectedReturn = 1;
|
||||||
this.requestedAddressFamilyAttribute
|
this.requestedAddressFamilyAttribute
|
||||||
.setFamily(MsgFixture.REQUESTED_ADDRESS_FAMILY_ATTRIBUTE_V6);
|
.setFamily(MsgFixture.REQUESTED_ADDRESS_FAMILY_ATTRIBUTE_V6);
|
||||||
actualReturn = this.requestedAddressFamilyAttribute.getDataLength();
|
actualReturn = this.requestedAddressFamilyAttribute.getDataLength();
|
||||||
assertEquals(
|
assertEquals(expectedReturn, actualReturn,
|
||||||
"Datalength is not properly calculated", expectedReturn,
|
"Datalength is not properly calculated");
|
||||||
actualReturn);
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Tests getting the name.
|
* Tests getting the name.
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testGetName()
|
public void testGetName()
|
||||||
{
|
{
|
||||||
String expectedReturn = "REQUESTED-ADDRESS-FAMILY";
|
assertEquals("REQUESTED-ADDRESS-FAMILY", requestedAddressFamilyAttribute.getName());
|
||||||
String actualReturn = requestedAddressFamilyAttribute.getName();
|
|
||||||
assertEquals(
|
|
||||||
"getting name failed", expectedReturn, actualReturn);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Tests the equals method against a null, a different and an identical
|
* Tests the equals method against a null, a different and an identical
|
||||||
* object.
|
* object.
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testEqualsObject()
|
public void testEqualsObject()
|
||||||
{
|
{
|
||||||
// null test
|
// null test
|
||||||
RequestedAddressFamilyAttribute target = null;
|
assertNotEquals(requestedAddressFamilyAttribute, null);
|
||||||
boolean expectedReturn = false;
|
|
||||||
boolean actualReturn = requestedAddressFamilyAttribute.equals(target);
|
|
||||||
|
|
||||||
assertEquals(
|
|
||||||
"RequestedAddressFamilyAttribute.equals() failed against a null "
|
|
||||||
+ "target.", expectedReturn, actualReturn);
|
|
||||||
|
|
||||||
// difference test
|
// difference test
|
||||||
|
RequestedAddressFamilyAttribute target;
|
||||||
target = new RequestedAddressFamilyAttribute();
|
target = new RequestedAddressFamilyAttribute();
|
||||||
|
|
||||||
char family = MsgFixture.REQUESTED_ADDRESS_FAMILY_ATTRIBUTE_V6;
|
char family = MsgFixture.REQUESTED_ADDRESS_FAMILY_ATTRIBUTE_V6;
|
||||||
@ -122,20 +101,12 @@ public class RequestedAddressFamilyAttributeTest
|
|||||||
requestedAddressFamilyAttribute
|
requestedAddressFamilyAttribute
|
||||||
.setFamily(MsgFixture.REQUESTED_ADDRESS_FAMILY_ATTRIBUTE_V4);
|
.setFamily(MsgFixture.REQUESTED_ADDRESS_FAMILY_ATTRIBUTE_V4);
|
||||||
|
|
||||||
expectedReturn = false;
|
assertNotEquals(requestedAddressFamilyAttribute, target);
|
||||||
actualReturn = requestedAddressFamilyAttribute.equals(target);
|
|
||||||
assertEquals(
|
|
||||||
"RequestedAddressFamilyAttribute.equals() failed against a "
|
|
||||||
+ "different target.", expectedReturn, actualReturn);
|
|
||||||
|
|
||||||
// equality test
|
// equality test
|
||||||
target.setFamily(MsgFixture.REQUESTED_ADDRESS_FAMILY_ATTRIBUTE_V4);
|
target.setFamily(MsgFixture.REQUESTED_ADDRESS_FAMILY_ATTRIBUTE_V4);
|
||||||
|
|
||||||
expectedReturn = true;
|
assertEquals(requestedAddressFamilyAttribute, target);
|
||||||
actualReturn = requestedAddressFamilyAttribute.equals(target);
|
|
||||||
assertEquals(
|
|
||||||
"RequestedAddressFamilyAttribute.equals() failed against an equal "
|
|
||||||
+ "target.", expectedReturn, actualReturn);
|
|
||||||
|
|
||||||
// ipv6 equality test
|
// ipv6 equality test
|
||||||
target.setFamily(MsgFixture.REQUESTED_ADDRESS_FAMILY_ATTRIBUTE_V6);
|
target.setFamily(MsgFixture.REQUESTED_ADDRESS_FAMILY_ATTRIBUTE_V6);
|
||||||
@ -143,11 +114,7 @@ public class RequestedAddressFamilyAttributeTest
|
|||||||
requestedAddressFamilyAttribute
|
requestedAddressFamilyAttribute
|
||||||
.setFamily(MsgFixture.REQUESTED_ADDRESS_FAMILY_ATTRIBUTE_V6);
|
.setFamily(MsgFixture.REQUESTED_ADDRESS_FAMILY_ATTRIBUTE_V6);
|
||||||
|
|
||||||
expectedReturn = true;
|
assertEquals(requestedAddressFamilyAttribute, target);
|
||||||
actualReturn = requestedAddressFamilyAttribute.equals(target);
|
|
||||||
assertEquals(
|
|
||||||
"RequestedAddressFamilyAttribute.equals() failed for IPv6 address.",
|
|
||||||
expectedReturn, actualReturn);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -156,6 +123,7 @@ public class RequestedAddressFamilyAttributeTest
|
|||||||
* @throws StunException if something goes wrong while decoding
|
* @throws StunException if something goes wrong while decoding
|
||||||
* Attribute Body.
|
* Attribute Body.
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testDecodeAttributeBodyV4() throws StunException
|
public void testDecodeAttributeBodyV4() throws StunException
|
||||||
{
|
{
|
||||||
byte[] attributeValue = msgFixture.requestedAddressFamilyV4;
|
byte[] attributeValue = msgFixture.requestedAddressFamilyV4;
|
||||||
@ -166,10 +134,10 @@ public class RequestedAddressFamilyAttributeTest
|
|||||||
attributeValue, offset, length);
|
attributeValue, offset, length);
|
||||||
|
|
||||||
assertEquals(
|
assertEquals(
|
||||||
"RequestedAddressFamilyAttribute.decode() did not properly decode "
|
|
||||||
+ "the family field.",
|
|
||||||
MsgFixture.REQUESTED_ADDRESS_FAMILY_ATTRIBUTE_V4,
|
MsgFixture.REQUESTED_ADDRESS_FAMILY_ATTRIBUTE_V4,
|
||||||
requestedAddressFamilyAttribute.getFamily());
|
requestedAddressFamilyAttribute.getFamily(),
|
||||||
|
"RequestedAddressFamilyAttribute.decode() did not properly decode the family field."
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -178,6 +146,7 @@ public class RequestedAddressFamilyAttributeTest
|
|||||||
* @throws StunException if something goes wrong while decoding
|
* @throws StunException if something goes wrong while decoding
|
||||||
* Attribute Body.
|
* Attribute Body.
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testDecodeAttributeBodyV6() throws StunException
|
public void testDecodeAttributeBodyV6() throws StunException
|
||||||
{
|
{
|
||||||
byte[] attributeValue = msgFixture.requestedAddressFamilyV6;
|
byte[] attributeValue = msgFixture.requestedAddressFamilyV6;
|
||||||
@ -188,63 +157,62 @@ public class RequestedAddressFamilyAttributeTest
|
|||||||
attributeValue, offset, length);
|
attributeValue, offset, length);
|
||||||
|
|
||||||
assertEquals(
|
assertEquals(
|
||||||
"RequestedAddressFamilyAttribute.decode() did not properly decode.",
|
|
||||||
MsgFixture.REQUESTED_ADDRESS_FAMILY_ATTRIBUTE_V6,
|
MsgFixture.REQUESTED_ADDRESS_FAMILY_ATTRIBUTE_V6,
|
||||||
requestedAddressFamilyAttribute.getFamily());
|
requestedAddressFamilyAttribute.getFamily(),
|
||||||
|
"RequestedAddressFamilyAttribute.decode() did not properly decode."
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Test whether attributes are properly encoded.
|
* Test whether attributes are properly encoded.
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testEncodeV4()
|
public void testEncodeV4()
|
||||||
{
|
{
|
||||||
byte[] expectedReturn = msgFixture.requestedAddressFamilyV4;
|
byte[] expectedReturn = msgFixture.requestedAddressFamilyV4;
|
||||||
requestedAddressFamilyAttribute
|
requestedAddressFamilyAttribute
|
||||||
.setFamily(MsgFixture.REQUESTED_ADDRESS_FAMILY_ATTRIBUTE_V4);
|
.setFamily(MsgFixture.REQUESTED_ADDRESS_FAMILY_ATTRIBUTE_V4);
|
||||||
byte[] actualReturn = requestedAddressFamilyAttribute.encode();
|
byte[] actualReturn = requestedAddressFamilyAttribute.encode();
|
||||||
assertTrue(
|
assertArrayEquals(
|
||||||
"RequestedAddressFamilyAttribute.encode() did not "
|
expectedReturn, actualReturn,
|
||||||
+ "properly encode a sample attribute for IPv4 family",
|
"RequestedAddressFamilyAttribute.encode() did not properly encode a sample attribute for IPv4 family"
|
||||||
Arrays.equals(
|
);
|
||||||
expectedReturn, actualReturn));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Test whether attributes are properly encoded.
|
* Test whether attributes are properly encoded.
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testEncodeV6()
|
public void testEncodeV6()
|
||||||
{
|
{
|
||||||
byte[] expectedReturn = msgFixture.requestedAddressFamilyV6;
|
byte[] expectedReturn = msgFixture.requestedAddressFamilyV6;
|
||||||
requestedAddressFamilyAttribute
|
requestedAddressFamilyAttribute
|
||||||
.setFamily(MsgFixture.REQUESTED_ADDRESS_FAMILY_ATTRIBUTE_V6);
|
.setFamily(MsgFixture.REQUESTED_ADDRESS_FAMILY_ATTRIBUTE_V6);
|
||||||
byte[] actualReturn = requestedAddressFamilyAttribute.encode();
|
byte[] actualReturn = requestedAddressFamilyAttribute.encode();
|
||||||
assertTrue(
|
assertArrayEquals(
|
||||||
"RequestedAddressFamilyAttribute.encode() did not "
|
expectedReturn, actualReturn,
|
||||||
+ "properly encode a sample attribute for IPv6 family",
|
"RequestedAddressFamilyAttribute.encode() did not properly encode a sample attribute for IPv6 family"
|
||||||
Arrays.equals(
|
);
|
||||||
expectedReturn, actualReturn));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Tests that the address family is always 0x01 or 0x02.
|
* Tests that the address family is always 0x01 or 0x02.
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testGetFamily()
|
public void testGetFamily()
|
||||||
{
|
{
|
||||||
char expectedReturn = 0x01;
|
char expectedReturn = 0x01;
|
||||||
this.requestedAddressFamilyAttribute
|
this.requestedAddressFamilyAttribute
|
||||||
.setFamily(MsgFixture.REQUESTED_ADDRESS_FAMILY_ATTRIBUTE_V4);
|
.setFamily(MsgFixture.REQUESTED_ADDRESS_FAMILY_ATTRIBUTE_V4);
|
||||||
char actualReturn = this.requestedAddressFamilyAttribute.getFamily();
|
char actualReturn = this.requestedAddressFamilyAttribute.getFamily();
|
||||||
assertEquals(
|
assertEquals(expectedReturn, actualReturn,
|
||||||
"Family is not properly calculated", expectedReturn,
|
"Family is not properly calculated");
|
||||||
actualReturn);
|
|
||||||
|
|
||||||
expectedReturn = 0x02;
|
expectedReturn = 0x02;
|
||||||
this.requestedAddressFamilyAttribute
|
this.requestedAddressFamilyAttribute
|
||||||
.setFamily(MsgFixture.REQUESTED_ADDRESS_FAMILY_ATTRIBUTE_V6);
|
.setFamily(MsgFixture.REQUESTED_ADDRESS_FAMILY_ATTRIBUTE_V6);
|
||||||
actualReturn = this.requestedAddressFamilyAttribute.getFamily();
|
actualReturn = this.requestedAddressFamilyAttribute.getFamily();
|
||||||
assertEquals(
|
assertEquals(expectedReturn, actualReturn,
|
||||||
"Family is not properly calculated", expectedReturn,
|
"Family is not properly calculated");
|
||||||
actualReturn);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@ -17,18 +17,16 @@
|
|||||||
*/
|
*/
|
||||||
package org.ice4j.attribute;
|
package org.ice4j.attribute;
|
||||||
|
|
||||||
import junit.framework.*;
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
import java.util.*;
|
|
||||||
|
|
||||||
import org.ice4j.*;
|
import org.ice4j.*;
|
||||||
|
import org.junit.jupiter.api.*;
|
||||||
/**
|
/**
|
||||||
* Tests the software attribute class.
|
* Tests the software attribute class.
|
||||||
*
|
*
|
||||||
* @author Emil Ivov
|
* @author Emil Ivov
|
||||||
*/
|
*/
|
||||||
public class SoftwareAttributeTest extends TestCase
|
public class SoftwareAttributeTest
|
||||||
{
|
{
|
||||||
private SoftwareAttribute softwareAttribute = null;
|
private SoftwareAttribute softwareAttribute = null;
|
||||||
MsgFixture msgFixture = null;
|
MsgFixture msgFixture = null;
|
||||||
@ -40,30 +38,27 @@ public class SoftwareAttributeTest extends TestCase
|
|||||||
't', 'u', 'r', 'n', 's', 'e', 'r','v', 'e', 'r', '.', 'o', 'r', 'g',
|
't', 'u', 'r', 'n', 's', 'e', 'r','v', 'e', 'r', '.', 'o', 'r', 'g',
|
||||||
0x00, 0x00};
|
0x00, 0x00};
|
||||||
|
|
||||||
protected void setUp() throws Exception
|
@BeforeEach
|
||||||
|
public void setUp() throws Exception
|
||||||
{
|
{
|
||||||
super.setUp();
|
|
||||||
msgFixture = new MsgFixture();
|
msgFixture = new MsgFixture();
|
||||||
|
|
||||||
softwareAttribute = new SoftwareAttribute();
|
softwareAttribute = new SoftwareAttribute();
|
||||||
softwareAttribute.setSoftware(softwareValue.getBytes());
|
softwareAttribute.setSoftware(softwareValue.getBytes());
|
||||||
|
|
||||||
msgFixture.setUp();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
protected void tearDown() throws Exception
|
@AfterEach
|
||||||
|
public void tearDown() throws Exception
|
||||||
{
|
{
|
||||||
softwareAttribute = null;
|
softwareAttribute = null;
|
||||||
msgFixture.tearDown();
|
|
||||||
|
|
||||||
msgFixture = null;
|
msgFixture = null;
|
||||||
super.tearDown();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Tests decoding of the software attribute.
|
* Tests decoding of the software attribute.
|
||||||
* @throws StunException upon a failure
|
* @throws StunException upon a failure
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testDecodeAttributeBody() throws StunException
|
public void testDecodeAttributeBody() throws StunException
|
||||||
{
|
{
|
||||||
char offset = 0;
|
char offset = 0;
|
||||||
@ -72,63 +67,62 @@ public class SoftwareAttributeTest extends TestCase
|
|||||||
decoded.decodeAttributeBody(softwareValue.getBytes(), offset, length);
|
decoded.decodeAttributeBody(softwareValue.getBytes(), offset, length);
|
||||||
|
|
||||||
//software value
|
//software value
|
||||||
assertEquals( "decode failed", softwareAttribute, decoded);
|
assertEquals(softwareAttribute, decoded);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Tests the encode method
|
* Tests the encode method
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testEncode()
|
public void testEncode()
|
||||||
{
|
{
|
||||||
assertTrue("encode failed",
|
assertArrayEquals(softwareAttribute.encode(), attributeBinValue);
|
||||||
Arrays.equals(softwareAttribute.encode(),
|
|
||||||
attributeBinValue));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Test Equals
|
* Test Equals
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testEquals()
|
public void testEquals()
|
||||||
{
|
{
|
||||||
SoftwareAttribute softwareAttribute2 = new SoftwareAttribute();
|
SoftwareAttribute softwareAttribute2 = new SoftwareAttribute();
|
||||||
softwareAttribute2.setSoftware(softwareValue.getBytes());
|
softwareAttribute2.setSoftware(softwareValue.getBytes());
|
||||||
|
|
||||||
//test positive equals
|
//test positive equals
|
||||||
assertEquals("testequals failed", softwareAttribute, softwareAttribute2);
|
assertEquals(softwareAttribute, softwareAttribute2);
|
||||||
|
|
||||||
//test negative equals
|
//test negative equals
|
||||||
softwareAttribute2 = new SoftwareAttribute();
|
softwareAttribute2 = new SoftwareAttribute();
|
||||||
softwareAttribute2.setSoftware("some other software".getBytes());
|
softwareAttribute2.setSoftware("some other software".getBytes());
|
||||||
|
|
||||||
//test positive equals
|
//test positive equals
|
||||||
assertFalse("testequals failed",
|
assertNotEquals(softwareAttribute2, softwareAttribute);
|
||||||
softwareAttribute.equals(softwareAttribute2));
|
|
||||||
|
|
||||||
//test null equals
|
//test null equals
|
||||||
assertFalse("testequals failed",
|
assertNotEquals(softwareAttribute, null);
|
||||||
softwareAttribute.equals(null));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Tests extracting data length
|
* Tests extracting data length
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testGetDataLength()
|
public void testGetDataLength()
|
||||||
{
|
{
|
||||||
char expectedReturn = (char)softwareValue.length();
|
char expectedReturn = (char)softwareValue.length();
|
||||||
char actualReturn = softwareAttribute.getDataLength();
|
char actualReturn = softwareAttribute.getDataLength();
|
||||||
assertEquals("getDataLength - failed", expectedReturn, actualReturn);
|
assertEquals(expectedReturn, actualReturn);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Tests getting the name
|
* Tests getting the name
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testGetName()
|
public void testGetName()
|
||||||
{
|
{
|
||||||
String expectedReturn = "SOFTWARE";
|
assertEquals("SOFTWARE", softwareAttribute.getName());
|
||||||
String actualReturn = softwareAttribute.getName();
|
|
||||||
assertEquals("getting name failed", expectedReturn, actualReturn);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testSetGetSoftware()
|
public void testSetGetSoftware()
|
||||||
{
|
{
|
||||||
byte[] expectedReturn = softwareValue.getBytes();
|
byte[] expectedReturn = softwareValue.getBytes();
|
||||||
@ -137,8 +131,7 @@ public class SoftwareAttributeTest extends TestCase
|
|||||||
att.setSoftware(expectedReturn);
|
att.setSoftware(expectedReturn);
|
||||||
|
|
||||||
byte[] actualReturn = att.getSoftware();
|
byte[] actualReturn = att.getSoftware();
|
||||||
assertTrue("software setter or getter failed",
|
assertArrayEquals(expectedReturn, actualReturn,
|
||||||
Arrays.equals( expectedReturn,
|
"software setter or getter failed");
|
||||||
actualReturn));
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -17,57 +17,48 @@
|
|||||||
*/
|
*/
|
||||||
package org.ice4j.attribute;
|
package org.ice4j.attribute;
|
||||||
|
|
||||||
import junit.framework.*;
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
import java.util.*;
|
import java.util.*;
|
||||||
|
|
||||||
import org.ice4j.*;
|
import org.ice4j.*;
|
||||||
|
import org.junit.jupiter.api.*;
|
||||||
/**
|
/**
|
||||||
* Tests the UNKNOWN attribute class.
|
* Tests the UNKNOWN attribute class.
|
||||||
*
|
*
|
||||||
* @author Emil Ivov
|
* @author Emil Ivov
|
||||||
*/
|
*/
|
||||||
public class UnknownAttributesAttributeTest extends TestCase
|
public class UnknownAttributesAttributeTest
|
||||||
{
|
{
|
||||||
private UnknownAttributesAttribute unknownAttributesAttribute = null;
|
private UnknownAttributesAttribute unknownAttributesAttribute = null;
|
||||||
private MsgFixture binMessagesFixture;
|
private MsgFixture binMessagesFixture;
|
||||||
|
|
||||||
public UnknownAttributesAttributeTest(String name)
|
@BeforeEach
|
||||||
|
public void setUp() throws Exception
|
||||||
{
|
{
|
||||||
super(name);
|
|
||||||
}
|
|
||||||
|
|
||||||
protected void setUp() throws Exception
|
|
||||||
{
|
|
||||||
super.setUp();
|
|
||||||
unknownAttributesAttribute = new UnknownAttributesAttribute();
|
unknownAttributesAttribute = new UnknownAttributesAttribute();
|
||||||
binMessagesFixture = new MsgFixture();
|
binMessagesFixture = new MsgFixture();
|
||||||
|
|
||||||
binMessagesFixture.setUp();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
protected void tearDown() throws Exception
|
@AfterEach
|
||||||
|
public void tearDown() throws Exception
|
||||||
{
|
{
|
||||||
unknownAttributesAttribute = null;
|
unknownAttributesAttribute = null;
|
||||||
binMessagesFixture.tearDown();
|
|
||||||
|
|
||||||
binMessagesFixture = null;
|
binMessagesFixture = null;
|
||||||
super.tearDown();
|
|
||||||
}
|
}
|
||||||
//-------------------------------- TESTS ---------------------------------------
|
//-------------------------------- TESTS ---------------------------------------
|
||||||
/**
|
/**
|
||||||
* Verify the the constructed object has the correct (UNKNOWN-ATTRIBUTES)
|
* Verify the the constructed object has the correct (UNKNOWN-ATTRIBUTES)
|
||||||
* type.
|
* type.
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testUnknownAttributesAttribute()
|
public void testUnknownAttributesAttribute()
|
||||||
{
|
{
|
||||||
unknownAttributesAttribute = new UnknownAttributesAttribute();
|
unknownAttributesAttribute = new UnknownAttributesAttribute();
|
||||||
|
assertEquals(
|
||||||
assertEquals("UnknownAttributesAttribute() did not properly set the "
|
Attribute.UNKNOWN_ATTRIBUTES,
|
||||||
+"Attribute's type field!",
|
(int) unknownAttributesAttribute.getAttributeType(),
|
||||||
(int)Attribute.UNKNOWN_ATTRIBUTES,
|
"UnknownAttributesAttribute() did not properly set the Attribute's type field!"
|
||||||
(int)unknownAttributesAttribute.getAttributeType()
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -76,37 +67,40 @@ public class UnknownAttributesAttributeTest extends TestCase
|
|||||||
* and that a second addition of the same id would not augment the attribute
|
* and that a second addition of the same id would not augment the attribute
|
||||||
* count.
|
* count.
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testAddAttributeID()
|
public void testAddAttributeID()
|
||||||
{
|
{
|
||||||
char attributeID = 0x22; // unknown attribute id
|
char attributeID = 0x22; // unknown attribute id
|
||||||
|
|
||||||
unknownAttributesAttribute.addAttributeID(attributeID);
|
unknownAttributesAttribute.addAttributeID(attributeID);
|
||||||
|
|
||||||
assertEquals("addAttributeID does not seem to properly add the attribute ID",
|
assertEquals(
|
||||||
(int) attributeID,
|
(int) attributeID,
|
||||||
(int)unknownAttributesAttribute.getAttribute(0)
|
(int) unknownAttributesAttribute.getAttribute(0),
|
||||||
|
"addAttributeID does not seem to properly add the attribute ID"
|
||||||
);
|
);
|
||||||
|
|
||||||
assertEquals("addAttributeID does not seem to properly add the attribute ID",
|
assertEquals(
|
||||||
1,
|
1,
|
||||||
unknownAttributesAttribute.getAttributeCount()
|
unknownAttributesAttribute.getAttributeCount(),
|
||||||
|
"addAttributeID does not seem to properly add the attribute ID"
|
||||||
);
|
);
|
||||||
|
|
||||||
//add a second one
|
//add a second one
|
||||||
unknownAttributesAttribute.addAttributeID(attributeID);
|
unknownAttributesAttribute.addAttributeID(attributeID);
|
||||||
|
|
||||||
assertEquals("Adding a 2nd time the same attributeID should not change "
|
assertEquals(
|
||||||
+"the number of attributes",
|
|
||||||
1,
|
1,
|
||||||
unknownAttributesAttribute.getAttributeCount()
|
unknownAttributesAttribute.getAttributeCount(),
|
||||||
|
"Adding a 2nd time the same attributeID should not change the number of attributes"
|
||||||
);
|
);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Tests whether a sample binary array is properly decoded.
|
* Tests whether a sample binary array is properly decoded.
|
||||||
* @throws StunException if anything goes wrong.
|
* @throws StunException if anything goes wrong.
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testDecodeAttributeBody() throws StunException
|
public void testDecodeAttributeBody() throws StunException
|
||||||
{
|
{
|
||||||
//a copy of the array in the fixture:
|
//a copy of the array in the fixture:
|
||||||
@ -118,30 +112,36 @@ public class UnknownAttributesAttributeTest extends TestCase
|
|||||||
- Attribute.HEADER_LENGTH));
|
- Attribute.HEADER_LENGTH));
|
||||||
//is every one there?
|
//is every one there?
|
||||||
assertTrue(
|
assertTrue(
|
||||||
"The " + (int)MsgFixture.UNKNOWN_ATTRIBUTES_1ST_ATT +" attribute id "
|
|
||||||
+ "was not found after decoding a binary array that contained it.",
|
|
||||||
unknownAttributesAttribute.contains(
|
unknownAttributesAttribute.contains(
|
||||||
MsgFixture.UNKNOWN_ATTRIBUTES_1ST_ATT));
|
MsgFixture.UNKNOWN_ATTRIBUTES_1ST_ATT),
|
||||||
|
"The " + (int) MsgFixture.UNKNOWN_ATTRIBUTES_1ST_ATT
|
||||||
|
+ " attribute id "
|
||||||
|
+ "was not found after decoding a binary array that contained it."
|
||||||
|
);
|
||||||
|
|
||||||
assertTrue(
|
assertTrue(
|
||||||
"The " + (int)MsgFixture.UNKNOWN_ATTRIBUTES_2ND_ATT +" attribute id "
|
|
||||||
+ "was not found after decoding a binary array that contained it.",
|
|
||||||
unknownAttributesAttribute.contains(
|
unknownAttributesAttribute.contains(
|
||||||
MsgFixture.UNKNOWN_ATTRIBUTES_2ND_ATT));
|
MsgFixture.UNKNOWN_ATTRIBUTES_2ND_ATT),
|
||||||
|
"The " + (int) MsgFixture.UNKNOWN_ATTRIBUTES_2ND_ATT
|
||||||
|
+ " attribute id "
|
||||||
|
+ "was not found after decoding a binary array that contained it."
|
||||||
|
);
|
||||||
assertTrue(
|
assertTrue(
|
||||||
"The " + (int)MsgFixture.UNKNOWN_ATTRIBUTES_3D_ATT +" attribute id "
|
|
||||||
+ "was not found after decoding a binary array that contained it.",
|
|
||||||
unknownAttributesAttribute.contains(
|
unknownAttributesAttribute.contains(
|
||||||
MsgFixture.UNKNOWN_ATTRIBUTES_3D_ATT));
|
MsgFixture.UNKNOWN_ATTRIBUTES_3D_ATT),
|
||||||
|
"The " + (int) MsgFixture.UNKNOWN_ATTRIBUTES_3D_ATT
|
||||||
|
+ " attribute id "
|
||||||
|
+ "was not found after decoding a binary array that contained it."
|
||||||
|
);
|
||||||
|
|
||||||
|
assertEquals(
|
||||||
assertEquals("The decoded attribute contained "
|
MsgFixture.UNKNOWN_ATTRIBUTES_CNT_DEC_TST,
|
||||||
|
unknownAttributesAttribute.getAttributeCount(),
|
||||||
|
"The decoded attribute contained "
|
||||||
+ unknownAttributesAttribute.getAttributeCount()
|
+ unknownAttributesAttribute.getAttributeCount()
|
||||||
+ " attribute ids when there were only "
|
+ " attribute ids when there were only "
|
||||||
+ (int) MsgFixture.UNKNOWN_ATTRIBUTES_CNT_DEC_TST
|
+ (int) MsgFixture.UNKNOWN_ATTRIBUTES_CNT_DEC_TST
|
||||||
+ " in the original binary array.",
|
+ " in the original binary array."
|
||||||
MsgFixture.UNKNOWN_ATTRIBUTES_CNT_DEC_TST,
|
|
||||||
unknownAttributesAttribute.getAttributeCount()
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -149,6 +149,7 @@ public class UnknownAttributesAttributeTest extends TestCase
|
|||||||
* Creates a new UnknownAttributesAttribute encodes it and assert equality
|
* Creates a new UnknownAttributesAttribute encodes it and assert equality
|
||||||
* with binMessagesFixture.unknownAttsEncodeExpectedResult.
|
* with binMessagesFixture.unknownAttsEncodeExpectedResult.
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testEncode()
|
public void testEncode()
|
||||||
{
|
{
|
||||||
byte[] expectedReturn = binMessagesFixture.unknownAttsEncodeExpectedResult;
|
byte[] expectedReturn = binMessagesFixture.unknownAttsEncodeExpectedResult;
|
||||||
@ -158,46 +159,36 @@ public class UnknownAttributesAttributeTest extends TestCase
|
|||||||
unknownAttributesAttribute.addAttributeID(
|
unknownAttributesAttribute.addAttributeID(
|
||||||
MsgFixture.UNKNOWN_ATTRIBUTES_2ND_ATT);
|
MsgFixture.UNKNOWN_ATTRIBUTES_2ND_ATT);
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
byte[] actualReturn = unknownAttributesAttribute.encode();
|
byte[] actualReturn = unknownAttributesAttribute.encode();
|
||||||
assertTrue("UnknownAttributesAttribute did not encode properly.",
|
assertArrayEquals(actualReturn, expectedReturn);
|
||||||
Arrays.equals(actualReturn, expectedReturn));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Tests the equals method against a null, a different and an identical
|
* Tests the equals method against a null, a different and an identical
|
||||||
* object.
|
* object.
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testEquals()
|
public void testEquals()
|
||||||
{
|
{
|
||||||
UnknownAttributesAttribute target = new UnknownAttributesAttribute();
|
UnknownAttributesAttribute target = new UnknownAttributesAttribute();
|
||||||
|
|
||||||
boolean expectedReturn = false;
|
assertNotEquals(unknownAttributesAttribute, null);
|
||||||
boolean actualReturn = unknownAttributesAttribute.equals(null);
|
|
||||||
assertEquals("Equals failed for a null object",
|
|
||||||
expectedReturn, actualReturn);
|
|
||||||
|
|
||||||
unknownAttributesAttribute.addAttributeID((char)25);
|
unknownAttributesAttribute.addAttributeID((char)25);
|
||||||
target.addAttributeID((char)25);
|
target.addAttributeID((char)25);
|
||||||
|
|
||||||
unknownAttributesAttribute.addAttributeID((char)26);
|
unknownAttributesAttribute.addAttributeID((char)26);
|
||||||
actualReturn = unknownAttributesAttribute.equals(target);
|
assertNotEquals(unknownAttributesAttribute, target);
|
||||||
assertEquals("Equals failed when comparing different objects.",
|
|
||||||
expectedReturn, actualReturn);
|
|
||||||
|
|
||||||
target.addAttributeID((char)26);
|
target.addAttributeID((char)26);
|
||||||
expectedReturn = true;
|
assertEquals(unknownAttributesAttribute, target);
|
||||||
actualReturn = unknownAttributesAttribute.equals(target);
|
|
||||||
assertEquals("Equals failed to recognize identical objects.",
|
|
||||||
expectedReturn, actualReturn);
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Tests that getAttribute() return the correct attribute id, preserving
|
* Tests that getAttribute() return the correct attribute id, preserving
|
||||||
* entry order.
|
* entry order.
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testGetAttribute()
|
public void testGetAttribute()
|
||||||
{
|
{
|
||||||
char expectedId1 = 20;
|
char expectedId1 = 20;
|
||||||
@ -212,14 +203,15 @@ public class UnknownAttributesAttributeTest extends TestCase
|
|||||||
actualId1 = unknownAttributesAttribute.getAttribute(0);
|
actualId1 = unknownAttributesAttribute.getAttribute(0);
|
||||||
actualId2 = unknownAttributesAttribute.getAttribute(1);
|
actualId2 = unknownAttributesAttribute.getAttribute(1);
|
||||||
|
|
||||||
assertEquals("getAttribute() return value mismatch", expectedId1, actualId1);
|
assertEquals(expectedId1, actualId1, "getAttribute() return value mismatch");
|
||||||
assertEquals("getAttribute() return value mismatch", expectedId2, actualId2);
|
assertEquals(expectedId2, actualId2, "getAttribute() return value mismatch");
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Add some attributes and test whether their number is properly calculated.
|
* Add some attributes and test whether their number is properly calculated.
|
||||||
* Tests duplicate id handling as well.
|
* Tests duplicate id handling as well.
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testGetAttributeCount()
|
public void testGetAttributeCount()
|
||||||
{
|
{
|
||||||
int expectedReturn = 5;
|
int expectedReturn = 5;
|
||||||
@ -232,14 +224,15 @@ public class UnknownAttributesAttributeTest extends TestCase
|
|||||||
unknownAttributesAttribute.addAttributeID((char)25);//duplicate values should be ignored
|
unknownAttributesAttribute.addAttributeID((char)25);//duplicate values should be ignored
|
||||||
|
|
||||||
int actualReturn = unknownAttributesAttribute.getAttributeCount();
|
int actualReturn = unknownAttributesAttribute.getAttributeCount();
|
||||||
assertEquals("getAttributeCount did not return the expected value",
|
assertEquals(expectedReturn, actualReturn,
|
||||||
expectedReturn, actualReturn);
|
"getAttributeCount did not return the expected value");
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Same as testGetAttributeID, only attribute attributes are extracted
|
* Same as testGetAttributeID, only attribute attributes are extracted
|
||||||
* through the getAttributes()'s iterator.
|
* through the getAttributes()'s iterator.
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testGetAttributes()
|
public void testGetAttributes()
|
||||||
{
|
{
|
||||||
char expectedId1 = 20;
|
char expectedId1 = 20;
|
||||||
@ -256,10 +249,8 @@ public class UnknownAttributesAttributeTest extends TestCase
|
|||||||
actualId1 = iterator.next();
|
actualId1 = iterator.next();
|
||||||
actualId2 = iterator.next();
|
actualId2 = iterator.next();
|
||||||
|
|
||||||
assertEquals("getAttributes() return value mismatch", expectedId1, actualId1);
|
assertEquals(expectedId1, actualId1, "getAttributes() return value mismatch");
|
||||||
assertEquals("getAttributes() return value mismatch", expectedId2, actualId2);
|
assertEquals(expectedId2, actualId2, "getAttributes() return value mismatch");
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -267,6 +258,7 @@ public class UnknownAttributesAttributeTest extends TestCase
|
|||||||
* Test is first performed for an odd number of attributes and then again
|
* Test is first performed for an odd number of attributes and then again
|
||||||
* (after adding another attribute id). Both results should be the same.
|
* (after adding another attribute id). Both results should be the same.
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testGetDataLength()
|
public void testGetDataLength()
|
||||||
{
|
{
|
||||||
char expectedReturn = 8;
|
char expectedReturn = 8;
|
||||||
@ -276,25 +268,23 @@ public class UnknownAttributesAttributeTest extends TestCase
|
|||||||
unknownAttributesAttribute.addAttributeID((char)22);
|
unknownAttributesAttribute.addAttributeID((char)22);
|
||||||
|
|
||||||
char actualReturn = unknownAttributesAttribute.getDataLength();
|
char actualReturn = unknownAttributesAttribute.getDataLength();
|
||||||
assertEquals("Incorrect testGetDataLength() return value",
|
assertEquals(expectedReturn, actualReturn,
|
||||||
expectedReturn, actualReturn);
|
"Incorrect testGetDataLength() return value");
|
||||||
|
|
||||||
unknownAttributesAttribute.addAttributeID((char)23);
|
unknownAttributesAttribute.addAttributeID((char)23);
|
||||||
|
|
||||||
actualReturn = unknownAttributesAttribute.getDataLength();
|
actualReturn = unknownAttributesAttribute.getDataLength();
|
||||||
assertEquals("Incorrect testGetDataLength() return value",
|
assertEquals(expectedReturn, actualReturn,
|
||||||
expectedReturn, actualReturn);
|
"Incorrect testGetDataLength() return value");
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Tests whether getName returns a relevant name.
|
* Tests whether getName returns a relevant name.
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testGetName()
|
public void testGetName()
|
||||||
{
|
{
|
||||||
String expectedReturn = "UNKNOWN-ATTRIBUTES";
|
assertEquals("UNKNOWN-ATTRIBUTES", unknownAttributesAttribute.getName());
|
||||||
String actualReturn = unknownAttributesAttribute.getName();
|
|
||||||
assertEquals("getName() return", expectedReturn, actualReturn);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@ -17,19 +17,17 @@
|
|||||||
*/
|
*/
|
||||||
package org.ice4j.attribute;
|
package org.ice4j.attribute;
|
||||||
|
|
||||||
import junit.framework.*;
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
import java.util.*;
|
|
||||||
|
|
||||||
import org.ice4j.*;
|
import org.ice4j.*;
|
||||||
|
import org.junit.jupiter.api.*;
|
||||||
/**
|
/**
|
||||||
* Tests the username attribute class.
|
* Tests the username attribute class.
|
||||||
*
|
*
|
||||||
* @author Emil Ivov
|
* @author Emil Ivov
|
||||||
* @author Sebastien Vincent
|
* @author Sebastien Vincent
|
||||||
*/
|
*/
|
||||||
public class UsernameAttributeTest extends TestCase
|
public class UsernameAttributeTest
|
||||||
{
|
{
|
||||||
private UsernameAttribute usernameAttribute = null;
|
private UsernameAttribute usernameAttribute = null;
|
||||||
MsgFixture msgFixture = null;
|
MsgFixture msgFixture = null;
|
||||||
@ -40,30 +38,27 @@ public class UsernameAttributeTest extends TestCase
|
|||||||
0, (byte)usernameValue.length(),
|
0, (byte)usernameValue.length(),
|
||||||
'u', 's', 'e', 'r', 'n', 'a', 'm','e'};
|
'u', 's', 'e', 'r', 'n', 'a', 'm','e'};
|
||||||
|
|
||||||
protected void setUp() throws Exception
|
@BeforeEach
|
||||||
|
public void setUp() throws Exception
|
||||||
{
|
{
|
||||||
super.setUp();
|
|
||||||
msgFixture = new MsgFixture();
|
msgFixture = new MsgFixture();
|
||||||
|
|
||||||
usernameAttribute = new UsernameAttribute();
|
usernameAttribute = new UsernameAttribute();
|
||||||
usernameAttribute.setUsername(usernameValue.getBytes());
|
usernameAttribute.setUsername(usernameValue.getBytes());
|
||||||
|
|
||||||
msgFixture.setUp();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
protected void tearDown() throws Exception
|
@AfterEach
|
||||||
|
public void tearDown() throws Exception
|
||||||
{
|
{
|
||||||
usernameAttribute = null;
|
usernameAttribute = null;
|
||||||
msgFixture.tearDown();
|
|
||||||
|
|
||||||
msgFixture = null;
|
msgFixture = null;
|
||||||
super.tearDown();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Tests decoding of the username attribute.
|
* Tests decoding of the username attribute.
|
||||||
* @throws StunException upon a failure
|
* @throws StunException upon a failure
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testDecodeAttributeBody() throws StunException
|
public void testDecodeAttributeBody() throws StunException
|
||||||
{
|
{
|
||||||
char offset = 0;
|
char offset = 0;
|
||||||
@ -72,63 +67,62 @@ public class UsernameAttributeTest extends TestCase
|
|||||||
decoded.decodeAttributeBody(usernameValue.getBytes(), offset, length);
|
decoded.decodeAttributeBody(usernameValue.getBytes(), offset, length);
|
||||||
|
|
||||||
//username value
|
//username value
|
||||||
assertEquals( "decode failed", usernameAttribute, decoded);
|
assertEquals(usernameAttribute, decoded);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Tests the encode method
|
* Tests the encode method
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testEncode()
|
public void testEncode()
|
||||||
{
|
{
|
||||||
assertTrue("encode failed",
|
assertArrayEquals(usernameAttribute.encode(), attributeBinValue);
|
||||||
Arrays.equals(usernameAttribute.encode(),
|
|
||||||
attributeBinValue));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Test Equals
|
* Test Equals
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testEquals()
|
public void testEquals()
|
||||||
{
|
{
|
||||||
UsernameAttribute usernameAttribute2 = new UsernameAttribute();
|
UsernameAttribute usernameAttribute2 = new UsernameAttribute();
|
||||||
usernameAttribute2.setUsername(usernameValue.getBytes());
|
usernameAttribute2.setUsername(usernameValue.getBytes());
|
||||||
|
|
||||||
//test positive equals
|
//test positive equals
|
||||||
assertEquals("testequals failed", usernameAttribute, usernameAttribute2);
|
assertEquals(usernameAttribute, usernameAttribute2);
|
||||||
|
|
||||||
//test negative equals
|
//test negative equals
|
||||||
usernameAttribute2 = new UsernameAttribute();
|
usernameAttribute2 = new UsernameAttribute();
|
||||||
usernameAttribute2.setUsername("some other username".getBytes());
|
usernameAttribute2.setUsername("some other username".getBytes());
|
||||||
|
|
||||||
//test positive equals
|
//test positive equals
|
||||||
assertFalse("testequals failed",
|
assertNotEquals(usernameAttribute2, usernameAttribute);
|
||||||
usernameAttribute.equals(usernameAttribute2));
|
|
||||||
|
|
||||||
//test null equals
|
//test null equals
|
||||||
assertFalse("testequals failed",
|
assertNotEquals(usernameAttribute, null);
|
||||||
usernameAttribute.equals(null));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Tests extracting data length
|
* Tests extracting data length
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testGetDataLength()
|
public void testGetDataLength()
|
||||||
{
|
{
|
||||||
char expectedReturn = (char)usernameValue.length();
|
char expectedReturn = (char)usernameValue.length();
|
||||||
char actualReturn = usernameAttribute.getDataLength();
|
char actualReturn = usernameAttribute.getDataLength();
|
||||||
assertEquals("getDataLength - failed", expectedReturn, actualReturn);
|
assertEquals(expectedReturn, actualReturn);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Tests getting the name
|
* Tests getting the name
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testGetName()
|
public void testGetName()
|
||||||
{
|
{
|
||||||
String expectedReturn = "USERNAME";
|
assertEquals("USERNAME", usernameAttribute.getName());
|
||||||
String actualReturn = usernameAttribute.getName();
|
|
||||||
assertEquals("getting name failed", expectedReturn, actualReturn);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testSetGetUsername()
|
public void testSetGetUsername()
|
||||||
{
|
{
|
||||||
byte[] expectedReturn = usernameValue.getBytes();
|
byte[] expectedReturn = usernameValue.getBytes();
|
||||||
@ -137,8 +131,7 @@ public class UsernameAttributeTest extends TestCase
|
|||||||
att.setUsername(expectedReturn);
|
att.setUsername(expectedReturn);
|
||||||
|
|
||||||
byte[] actualReturn = att.getUsername();
|
byte[] actualReturn = att.getUsername();
|
||||||
assertTrue("username setter or getter failed",
|
assertArrayEquals(expectedReturn, actualReturn,
|
||||||
Arrays.equals( expectedReturn,
|
"username setter or getter failed");
|
||||||
actualReturn));
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -17,32 +17,30 @@
|
|||||||
*/
|
*/
|
||||||
package org.ice4j.attribute;
|
package org.ice4j.attribute;
|
||||||
|
|
||||||
import junit.framework.*;
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
import java.util.*;
|
|
||||||
|
|
||||||
import org.ice4j.*;
|
import org.ice4j.*;
|
||||||
|
import org.junit.jupiter.api.*;
|
||||||
/**
|
/**
|
||||||
* @author Emil Ivov
|
* @author Emil Ivov
|
||||||
*/
|
*/
|
||||||
public class XorOnlyTest extends TestCase
|
public class XorOnlyTest
|
||||||
{
|
{
|
||||||
private XorOnlyAttribute xorOnly = null;
|
private XorOnlyAttribute xorOnly = null;
|
||||||
private MsgFixture msgFixture = null;
|
private MsgFixture msgFixture = null;
|
||||||
|
|
||||||
protected void setUp() throws Exception
|
@BeforeEach
|
||||||
|
public void setUp() throws Exception
|
||||||
{
|
{
|
||||||
super.setUp();
|
|
||||||
xorOnly = new XorOnlyAttribute();
|
xorOnly = new XorOnlyAttribute();
|
||||||
msgFixture = new MsgFixture();
|
msgFixture = new MsgFixture();
|
||||||
}
|
}
|
||||||
|
|
||||||
protected void tearDown() throws Exception
|
@AfterEach
|
||||||
|
public void tearDown() throws Exception
|
||||||
{
|
{
|
||||||
xorOnly = null;
|
xorOnly = null;
|
||||||
msgFixture = null;
|
msgFixture = null;
|
||||||
super.tearDown();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -50,6 +48,7 @@ public class XorOnlyTest extends TestCase
|
|||||||
* decode method doesn't do anything in the XorOnly att.
|
* decode method doesn't do anything in the XorOnly att.
|
||||||
* @throws StunException if sth happens
|
* @throws StunException if sth happens
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testDecodeAttributeBody() throws StunException
|
public void testDecodeAttributeBody() throws StunException
|
||||||
{
|
{
|
||||||
byte[] attributeValue = new byte[]{};
|
byte[] attributeValue = new byte[]{};
|
||||||
@ -61,52 +60,52 @@ public class XorOnlyTest extends TestCase
|
|||||||
/**
|
/**
|
||||||
* Test encoding XorOnly attributes.
|
* Test encoding XorOnly attributes.
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testEncode()
|
public void testEncode()
|
||||||
{
|
{
|
||||||
byte[] expectedReturn = new byte[]{Attribute.XOR_ONLY>>8,
|
byte[] expectedReturn = new byte[]{Attribute.XOR_ONLY>>8,
|
||||||
Attribute.XOR_ONLY&0x00FF,
|
Attribute.XOR_ONLY&0x00FF,
|
||||||
0, 0};
|
0, 0};
|
||||||
byte[] actualReturn = xorOnly.encode();
|
byte[] actualReturn = xorOnly.encode();
|
||||||
assertTrue("XorOnly failed to encode",
|
assertArrayEquals(expectedReturn, actualReturn);
|
||||||
Arrays.equals( expectedReturn, actualReturn));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Test positive and negative XorOnly.equals() returns
|
* Test positive and negative XorOnly.equals() returns
|
||||||
* @throws Exception if decoding fails
|
* @throws Exception if decoding fails
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testEquals() throws Exception
|
public void testEquals() throws Exception
|
||||||
{
|
{
|
||||||
XorOnlyAttribute xor2 = new XorOnlyAttribute();
|
XorOnlyAttribute xor2 = new XorOnlyAttribute();
|
||||||
assertEquals("equals() failes for XorOnly", xorOnly, xor2);
|
assertEquals(xorOnly, xor2);
|
||||||
|
|
||||||
MappedAddressAttribute maatt = new MappedAddressAttribute();
|
MappedAddressAttribute maatt = new MappedAddressAttribute();
|
||||||
maatt.decodeAttributeBody( msgFixture.mappedAddress,
|
maatt.decodeAttributeBody( msgFixture.mappedAddress,
|
||||||
(char) 0,
|
(char) 0,
|
||||||
(char) msgFixture.mappedAddress.length );
|
(char) msgFixture.mappedAddress.length );
|
||||||
|
|
||||||
|
assertNotEquals(maatt, xorOnly);
|
||||||
assertFalse("equals failed to see a difference", xorOnly.equals(maatt));
|
assertNotEquals(xorOnly, null);
|
||||||
assertFalse("equals failed for null", xorOnly.equals(null));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Makes sure the data langth is 0
|
* Makes sure the data langth is 0
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testGetDataLength()
|
public void testGetDataLength()
|
||||||
{
|
{
|
||||||
char expectedReturn = 0;
|
char expectedReturn = 0;
|
||||||
char actualReturn = xorOnly.getDataLength();
|
char actualReturn = xorOnly.getDataLength();
|
||||||
assertEquals("data length was not 0", expectedReturn, actualReturn);
|
assertEquals(expectedReturn, actualReturn, "data length was not 0");
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Verifies the name (do we really need this?).
|
* Verifies the name (do we really need this?).
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testGetName()
|
public void testGetName()
|
||||||
{
|
{
|
||||||
String expectedReturn = "XOR-ONLY";
|
assertEquals("XOR-ONLY", xorOnly.getName());
|
||||||
String actualReturn = xorOnly.getName();
|
|
||||||
assertEquals("Is name correct", expectedReturn, actualReturn);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -17,12 +17,42 @@
|
|||||||
*/
|
*/
|
||||||
package org.ice4j.ice;
|
package org.ice4j.ice;
|
||||||
|
|
||||||
import static org.junit.Assert.*;
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
import org.junit.*;
|
import org.junit.jupiter.api.*;
|
||||||
|
|
||||||
public class NetworkUtilsTest
|
public class NetworkUtilsTest
|
||||||
{
|
{
|
||||||
|
@Test
|
||||||
|
public void testIpv4StringToBytes()
|
||||||
|
{
|
||||||
|
byte[] addr = NetworkUtils.strToIPv4("1");
|
||||||
|
assertArrayEquals(new byte[]{0, 0, 0, 1}, addr);
|
||||||
|
|
||||||
|
addr = NetworkUtils.strToIPv4("1.2");
|
||||||
|
assertArrayEquals(new byte[]{1, 0, 0, 2}, addr);
|
||||||
|
|
||||||
|
addr = NetworkUtils.strToIPv4("1.2.3");
|
||||||
|
assertArrayEquals(new byte[]{1, 2, 0, 3}, addr);
|
||||||
|
|
||||||
|
addr = NetworkUtils.strToIPv4("1.2.3.4");
|
||||||
|
assertArrayEquals(new byte[]{1, 2, 3, 4}, addr);
|
||||||
|
|
||||||
|
assertNull(NetworkUtils.strToIPv4(""));
|
||||||
|
assertNull(NetworkUtils.strToIPv4("-1"));
|
||||||
|
assertNull(NetworkUtils.strToIPv4("1.-2"));
|
||||||
|
assertNull(NetworkUtils.strToIPv4("-1.2"));
|
||||||
|
assertNull(NetworkUtils.strToIPv4("1.-2.3"));
|
||||||
|
assertNull(NetworkUtils.strToIPv4("1.2.-3"));
|
||||||
|
assertNull(NetworkUtils.strToIPv4("-1.2.3"));
|
||||||
|
assertNull(NetworkUtils.strToIPv4("1.-2.3.4"));
|
||||||
|
assertNull(NetworkUtils.strToIPv4("1.2.-3.4"));
|
||||||
|
assertNull(NetworkUtils.strToIPv4("1.2.3.-4"));
|
||||||
|
assertNull(NetworkUtils.strToIPv4("-1.2.3.4"));
|
||||||
|
assertNull(NetworkUtils.strToIPv4("1.2.3.4.5"));
|
||||||
|
assertNull(NetworkUtils.strToIPv4("1.2.3.256"));
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testIpv6StringToBytes()
|
public void testIpv6StringToBytes()
|
||||||
{
|
{
|
||||||
@ -42,6 +72,13 @@ public class NetworkUtilsTest
|
|||||||
assertNotNull(addr);
|
assertNotNull(addr);
|
||||||
assertEquals(18, addr[15]);
|
assertEquals(18, addr[15]);
|
||||||
|
|
||||||
|
assertNull(NetworkUtils.strToIPv6(""));
|
||||||
|
assertNull(NetworkUtils.strToIPv6(":::"));
|
||||||
|
assertNull(NetworkUtils.strToIPv6("[^"));
|
||||||
|
assertNull(NetworkUtils.strToIPv6("[%"));
|
||||||
|
assertNull(NetworkUtils.strToIPv6(":?0"));
|
||||||
assertNull(NetworkUtils.strToIPv6("[::12]%1"));
|
assertNull(NetworkUtils.strToIPv6("[::12]%1"));
|
||||||
|
assertNull(NetworkUtils.strToIPv6("[::65536]%1"));
|
||||||
|
assertNull(NetworkUtils.strToIPv6("1111:222:3333:4444:5555:6666:7"));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
196
src/test/java/org/ice4j/ice/RoleConflictResolutionTest.java
Normal file
196
src/test/java/org/ice4j/ice/RoleConflictResolutionTest.java
Normal file
@ -0,0 +1,196 @@
|
|||||||
|
/*
|
||||||
|
* ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
|
||||||
|
*
|
||||||
|
* Copyright @ 2019 8x8, Inc
|
||||||
|
*
|
||||||
|
* 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;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
import org.ice4j.*;
|
||||||
|
|
||||||
|
import java.io.*;
|
||||||
|
import java.util.*;
|
||||||
|
import java.util.concurrent.*;
|
||||||
|
import java.util.logging.*;
|
||||||
|
import org.junit.jupiter.api.*;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* RoleConflictResolutionTest set of tests which does end-to-end test
|
||||||
|
* of ICE role conflict recovery.
|
||||||
|
*
|
||||||
|
* @author Yura Yaroshevich
|
||||||
|
*/
|
||||||
|
public class RoleConflictResolutionTest
|
||||||
|
{
|
||||||
|
protected static final Logger logger
|
||||||
|
= Logger.getLogger(RoleConflictResolutionTest.class.getName());
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testRecoveryFromBothControlledConflict()
|
||||||
|
throws Throwable
|
||||||
|
{
|
||||||
|
testRecoveryFromRoleConflict(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testRecoveryFromBothControllingConflict()
|
||||||
|
throws Throwable
|
||||||
|
{
|
||||||
|
testRecoveryFromRoleConflict(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void testRecoveryFromRoleConflict(boolean bothControlling)
|
||||||
|
throws Throwable
|
||||||
|
{
|
||||||
|
final Agent peer1 = createPeer("[peer-1]", bothControlling);
|
||||||
|
// Set explicit tie-breakers to avoid automatic conflict resolution
|
||||||
|
peer1.setTieBreaker(1);
|
||||||
|
|
||||||
|
final Agent peer2 = createPeer("[peer-2]", bothControlling);
|
||||||
|
peer1.setTieBreaker(2);
|
||||||
|
|
||||||
|
final CountDownLatch countDownLatch = new CountDownLatch(2);
|
||||||
|
|
||||||
|
for (Agent peer : Arrays.asList(peer1, peer2))
|
||||||
|
{
|
||||||
|
peer.addStateChangeListener(evt ->
|
||||||
|
{
|
||||||
|
logger.info(peer.toString() + ": state changed to "
|
||||||
|
+ evt.toString());
|
||||||
|
if (peer.getState().isEstablished())
|
||||||
|
{
|
||||||
|
countDownLatch.countDown();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
exchangeCredentials(peer1, peer2);
|
||||||
|
exchangeCandidates(peer1, peer2);
|
||||||
|
|
||||||
|
peer1.startConnectivityEstablishment();
|
||||||
|
peer2.startConnectivityEstablishment();
|
||||||
|
|
||||||
|
boolean isConnected = countDownLatch.await(20, TimeUnit.SECONDS);
|
||||||
|
|
||||||
|
logSelectedPairs(peer1);
|
||||||
|
logSelectedPairs(peer2);
|
||||||
|
|
||||||
|
assertTrue(isConnected,
|
||||||
|
"Expected connection established within time out");
|
||||||
|
assertTrue(peer1.getState().isEstablished(),
|
||||||
|
"peer 1 connectivity");
|
||||||
|
assertTrue(peer2.getState().isEstablished(),
|
||||||
|
"peer 2 connectivity");
|
||||||
|
|
||||||
|
disposePeer(peer1);
|
||||||
|
disposePeer(peer2);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Agent createPeer(String label, boolean iceControlling)
|
||||||
|
throws IOException
|
||||||
|
{
|
||||||
|
final Agent agent = new Agent(label, null);
|
||||||
|
agent.setControlling(iceControlling);
|
||||||
|
IceMediaStream iceStream = agent.createMediaStream("media-stream");
|
||||||
|
|
||||||
|
agent.createComponent(
|
||||||
|
iceStream,
|
||||||
|
0x400, 0x400, 0xFFFF,
|
||||||
|
KeepAliveStrategy.ALL_SUCCEEDED,
|
||||||
|
true);
|
||||||
|
|
||||||
|
return agent;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void disposePeer(Agent peer)
|
||||||
|
{
|
||||||
|
peer.free();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void logSelectedPairs(Agent peer)
|
||||||
|
{
|
||||||
|
for (IceMediaStream stream : peer.getStreams())
|
||||||
|
{
|
||||||
|
for (Component component : stream.getComponents())
|
||||||
|
{
|
||||||
|
CandidatePair selectedPair = component.getSelectedPair();
|
||||||
|
if (selectedPair != null)
|
||||||
|
{
|
||||||
|
logger.info(
|
||||||
|
peer + ": selected pair for " + "component " + component.getName() + " :" + selectedPair);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void exchangeCredentials(Agent peer1, Agent peer2)
|
||||||
|
{
|
||||||
|
for(IceMediaStream stream : peer2.getStreams())
|
||||||
|
{
|
||||||
|
stream.setRemoteUfrag(peer1.getLocalUfrag());
|
||||||
|
stream.setRemotePassword(peer1.getLocalPassword());
|
||||||
|
}
|
||||||
|
|
||||||
|
for(IceMediaStream stream : peer1.getStreams())
|
||||||
|
{
|
||||||
|
stream.setRemoteUfrag(peer2.getLocalUfrag());
|
||||||
|
stream.setRemotePassword(peer2.getLocalPassword());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void exchangeCandidates(Agent peer1, Agent peer2)
|
||||||
|
{
|
||||||
|
for (String streamName : peer1.getStreamNames())
|
||||||
|
{
|
||||||
|
IceMediaStream peer1Stream = peer1.getStream(streamName);
|
||||||
|
IceMediaStream peer2Stream = peer2.getStream(streamName);
|
||||||
|
if (peer1Stream == null || peer2Stream == null)
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (Integer id : peer1Stream.getComponentIDs())
|
||||||
|
{
|
||||||
|
Component peer1Component = peer1Stream.getComponent(id);
|
||||||
|
Component peer2Component = peer2Stream.getComponent(id);
|
||||||
|
if (peer1Component == null || peer2Component == null)
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
copyRemoteCandidates(peer1Component, peer2Component);
|
||||||
|
copyRemoteCandidates(peer2Component, peer1Component);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void copyRemoteCandidates(Component localComponent,
|
||||||
|
Component remoteComponent)
|
||||||
|
{
|
||||||
|
for(LocalCandidate candidate : remoteComponent.getLocalCandidates())
|
||||||
|
{
|
||||||
|
localComponent.addRemoteCandidate(
|
||||||
|
new RemoteCandidate(
|
||||||
|
candidate.getTransportAddress(),
|
||||||
|
localComponent,
|
||||||
|
candidate.getType(),
|
||||||
|
candidate.getFoundation(),
|
||||||
|
candidate.getPriority(),
|
||||||
|
null));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -17,10 +17,12 @@
|
|||||||
*/
|
*/
|
||||||
package org.ice4j.ice.harvest;
|
package org.ice4j.ice.harvest;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
import org.ice4j.*;
|
import org.ice4j.*;
|
||||||
import org.junit.*;
|
|
||||||
|
|
||||||
import java.net.*;
|
import java.net.*;
|
||||||
|
import org.junit.jupiter.api.*;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Various tests that verify the functionality provided by {@link SinglePortUdpHarvester}.
|
* Various tests that verify the functionality provided by {@link SinglePortUdpHarvester}.
|
||||||
@ -34,8 +36,8 @@ public class SinglePortUdpHarvesterTest
|
|||||||
*
|
*
|
||||||
* @see <a href="https://github.com/jitsi/ice4j/issues/139">https://github.com/jitsi/ice4j/issues/139</a>
|
* @see <a href="https://github.com/jitsi/ice4j/issues/139">https://github.com/jitsi/ice4j/issues/139</a>
|
||||||
*/
|
*/
|
||||||
@Test( expected = java.net.BindException.class )
|
@Test
|
||||||
public void testRebindWithoutClose() throws Exception
|
public void testRebindWithoutCloseThrows() throws Exception
|
||||||
{
|
{
|
||||||
// Setup test fixture.
|
// Setup test fixture.
|
||||||
final TransportAddress address = new TransportAddress( "127.0.0.1", 10000, Transport.UDP );
|
final TransportAddress address = new TransportAddress( "127.0.0.1", 10000, Transport.UDP );
|
||||||
@ -44,7 +46,7 @@ public class SinglePortUdpHarvesterTest
|
|||||||
{
|
{
|
||||||
firstHarvester = new SinglePortUdpHarvester( address );
|
firstHarvester = new SinglePortUdpHarvester( address );
|
||||||
}
|
}
|
||||||
catch ( java.net.BindException ex )
|
catch (BindException ex)
|
||||||
{
|
{
|
||||||
// This is not expected at this stage (the port is likely already in use by another process, voiding this
|
// This is not expected at this stage (the port is likely already in use by another process, voiding this
|
||||||
// test). Rethrow as a different exception than the BindException, that is expected to be thrown later in
|
// test). Rethrow as a different exception than the BindException, that is expected to be thrown later in
|
||||||
@ -57,12 +59,15 @@ public class SinglePortUdpHarvesterTest
|
|||||||
try
|
try
|
||||||
{
|
{
|
||||||
secondHarvester = new SinglePortUdpHarvester( address );
|
secondHarvester = new SinglePortUdpHarvester( address );
|
||||||
|
fail("expected BindException to be thrown at this point");
|
||||||
|
}
|
||||||
|
catch (BindException ex)
|
||||||
|
{
|
||||||
|
//expected, do nothing
|
||||||
}
|
}
|
||||||
// Verification of the results is implicit - this Test expectes BindException to be thrown at this point.
|
|
||||||
|
|
||||||
// Tear down
|
|
||||||
finally
|
finally
|
||||||
{
|
{
|
||||||
|
// Tear down
|
||||||
firstHarvester.close();
|
firstHarvester.close();
|
||||||
if (secondHarvester != null)
|
if (secondHarvester != null)
|
||||||
{
|
{
|
||||||
@ -96,7 +101,7 @@ public class SinglePortUdpHarvesterTest
|
|||||||
// Verify results.
|
// Verify results.
|
||||||
catch ( BindException ex )
|
catch ( BindException ex )
|
||||||
{
|
{
|
||||||
Assert.fail( "A bind exception should not have been thrown, as the original harvester was propertly closed.");
|
fail( "A bind exception should not have been thrown, as the original harvester was properly closed.");
|
||||||
}
|
}
|
||||||
|
|
||||||
// Tear down.
|
// Tear down.
|
||||||
@ -108,4 +113,29 @@ public class SinglePortUdpHarvesterTest
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testBindWithPortZero() throws Exception
|
||||||
|
{
|
||||||
|
// Setup test fixture.
|
||||||
|
final TransportAddress address = new TransportAddress("127.0.0.1", 0, Transport.UDP);
|
||||||
|
SinglePortUdpHarvester harvester;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
harvester = new SinglePortUdpHarvester(address);
|
||||||
|
}
|
||||||
|
catch (BindException ex)
|
||||||
|
{
|
||||||
|
// This is not expected at this stage.
|
||||||
|
// Rethrow as a different exception than the BindException, that is expected to be thrown later in
|
||||||
|
// this test.
|
||||||
|
throw new Exception("Test fixture is invalid.", ex);
|
||||||
|
}
|
||||||
|
|
||||||
|
assertFalse(harvester.localAddress.getPort() == 0,
|
||||||
|
"A random port number not equal to zero should have been chosen by the OS");
|
||||||
|
|
||||||
|
// Tear down
|
||||||
|
harvester.close();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -17,36 +17,15 @@
|
|||||||
*/
|
*/
|
||||||
package org.ice4j.message;
|
package org.ice4j.message;
|
||||||
|
|
||||||
import junit.framework.*;
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
import org.ice4j.*;
|
import org.ice4j.*;
|
||||||
import org.ice4j.attribute.*;
|
import org.ice4j.attribute.*;
|
||||||
|
import org.junit.jupiter.api.*;
|
||||||
|
|
||||||
public class MessageFactoryTest extends TestCase
|
public class MessageFactoryTest
|
||||||
{
|
{
|
||||||
private MsgFixture msgFixture;
|
@Test
|
||||||
|
|
||||||
public MessageFactoryTest(String name)
|
|
||||||
{
|
|
||||||
super(name);
|
|
||||||
}
|
|
||||||
|
|
||||||
protected void setUp() throws Exception
|
|
||||||
{
|
|
||||||
super.setUp();
|
|
||||||
msgFixture = new MsgFixture();
|
|
||||||
|
|
||||||
msgFixture.setUp();
|
|
||||||
}
|
|
||||||
|
|
||||||
protected void tearDown() throws Exception
|
|
||||||
{
|
|
||||||
msgFixture.tearDown();
|
|
||||||
|
|
||||||
msgFixture = null;
|
|
||||||
super.tearDown();
|
|
||||||
}
|
|
||||||
|
|
||||||
public void testCreateBindingErrorResponse() throws StunException
|
public void testCreateBindingErrorResponse() throws StunException
|
||||||
{
|
{
|
||||||
char errorCode = 400;
|
char errorCode = 400;
|
||||||
@ -60,10 +39,11 @@ public class MessageFactoryTest extends TestCase
|
|||||||
|
|
||||||
Message actualReturn
|
Message actualReturn
|
||||||
= MessageFactory.createBindingErrorResponse(errorCode);
|
= MessageFactory.createBindingErrorResponse(errorCode);
|
||||||
assertEquals("return value", expectedReturn, actualReturn);
|
assertEquals(expectedReturn, actualReturn);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void testCreateBindingErrorResponse1() throws StunException
|
@Test
|
||||||
|
public void testCreateBindingErrorResponse1()
|
||||||
{
|
{
|
||||||
char errorCode = 400;
|
char errorCode = 400;
|
||||||
String reasonPhrase = "Bad Request";
|
String reasonPhrase = "Bad Request";
|
||||||
@ -77,10 +57,10 @@ public class MessageFactoryTest extends TestCase
|
|||||||
|
|
||||||
Message actualReturn = MessageFactory
|
Message actualReturn = MessageFactory
|
||||||
.createBindingErrorResponse(errorCode, reasonPhrase);
|
.createBindingErrorResponse(errorCode, reasonPhrase);
|
||||||
assertEquals("Failed to create an error code attribute.",
|
assertEquals(expectedReturn, actualReturn);
|
||||||
expectedReturn, actualReturn);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testCreateBindingErrorResponseUnknownAttributes()
|
public void testCreateBindingErrorResponseUnknownAttributes()
|
||||||
throws StunException
|
throws StunException
|
||||||
{
|
{
|
||||||
@ -91,17 +71,18 @@ public class MessageFactoryTest extends TestCase
|
|||||||
Response expectedReturn = new Response();
|
Response expectedReturn = new Response();
|
||||||
expectedReturn.setMessageType(Message.BINDING_ERROR_RESPONSE);
|
expectedReturn.setMessageType(Message.BINDING_ERROR_RESPONSE);
|
||||||
|
|
||||||
Attribute errorCodeAtt = AttributeFactory
|
ErrorCodeAttribute errorCodeAtt = AttributeFactory
|
||||||
.createErrorCodeAttribute(errorCode);
|
.createErrorCodeAttribute(errorCode);
|
||||||
((ErrorCodeAttribute)errorCodeAtt).setReasonPhrase(
|
errorCodeAtt.setReasonPhrase(
|
||||||
ErrorCodeAttribute.getDefaultReasonPhrase(errorCode));
|
ErrorCodeAttribute.getDefaultReasonPhrase(errorCode));
|
||||||
expectedReturn.putAttribute(errorCodeAtt);
|
expectedReturn.putAttribute(errorCodeAtt);
|
||||||
|
|
||||||
UnknownAttributesAttribute unknownAtts =
|
UnknownAttributesAttribute unknownAtts =
|
||||||
AttributeFactory.createUnknownAttributesAttribute();
|
AttributeFactory.createUnknownAttributesAttribute();
|
||||||
|
|
||||||
for (int i = 0; i < unknownAttributes.length; i++) {
|
for (char unknownAttribute : unknownAttributes)
|
||||||
unknownAtts.addAttributeID(unknownAttributes[i]);
|
{
|
||||||
|
unknownAtts.addAttributeID(unknownAttribute);
|
||||||
}
|
}
|
||||||
expectedReturn.putAttribute(unknownAtts);
|
expectedReturn.putAttribute(unknownAtts);
|
||||||
|
|
||||||
@ -109,9 +90,10 @@ public class MessageFactoryTest extends TestCase
|
|||||||
Message actualReturn = MessageFactory
|
Message actualReturn = MessageFactory
|
||||||
.createBindingErrorResponseUnknownAttributes(unknownAttributes);
|
.createBindingErrorResponseUnknownAttributes(unknownAttributes);
|
||||||
//compare
|
//compare
|
||||||
assertEquals("return value", expectedReturn, actualReturn);
|
assertEquals(expectedReturn, actualReturn);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testCreateBindingErrorResponseUnknownAttributes1()
|
public void testCreateBindingErrorResponseUnknownAttributes1()
|
||||||
throws StunException
|
throws StunException
|
||||||
{
|
{
|
||||||
@ -129,22 +111,22 @@ public class MessageFactoryTest extends TestCase
|
|||||||
UnknownAttributesAttribute unknownAtts =
|
UnknownAttributesAttribute unknownAtts =
|
||||||
AttributeFactory.createUnknownAttributesAttribute();
|
AttributeFactory.createUnknownAttributesAttribute();
|
||||||
|
|
||||||
for (int i = 0; i < unknownAttributes.length; i++)
|
for (char unknownAttribute : unknownAttributes)
|
||||||
{
|
{
|
||||||
unknownAtts.addAttributeID(unknownAttributes[i]);
|
unknownAtts.addAttributeID(unknownAttribute);
|
||||||
}
|
}
|
||||||
expectedReturn.putAttribute(unknownAtts);
|
expectedReturn.putAttribute(unknownAtts);
|
||||||
|
|
||||||
Message actualReturn = MessageFactory
|
Message actualReturn = MessageFactory
|
||||||
.createBindingErrorResponseUnknownAttributes(
|
.createBindingErrorResponseUnknownAttributes(
|
||||||
reasonPhrase, unknownAttributes);
|
reasonPhrase, unknownAttributes);
|
||||||
assertEquals("return value", expectedReturn, actualReturn);
|
assertEquals(expectedReturn, actualReturn);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void testCreateBindingRequest() throws StunException
|
@Test
|
||||||
|
public void testCreateBindingRequest()
|
||||||
{
|
{
|
||||||
Request bindingRequest = new Request();
|
Request bindingRequest = new Request();
|
||||||
Request expectedReturn = bindingRequest;
|
|
||||||
bindingRequest.setMessageType(Message.BINDING_REQUEST);
|
bindingRequest.setMessageType(Message.BINDING_REQUEST);
|
||||||
/*
|
/*
|
||||||
Attribute changeRequest = AttributeFactory.createChangeRequestAttribute(
|
Attribute changeRequest = AttributeFactory.createChangeRequestAttribute(
|
||||||
@ -152,9 +134,10 @@ public class MessageFactoryTest extends TestCase
|
|||||||
bindingRequest.putAttribute(changeRequest);
|
bindingRequest.putAttribute(changeRequest);
|
||||||
*/
|
*/
|
||||||
Request actualReturn = MessageFactory.createBindingRequest();
|
Request actualReturn = MessageFactory.createBindingRequest();
|
||||||
assertEquals("return value", expectedReturn, actualReturn);
|
assertEquals(bindingRequest, actualReturn);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
public void testCreateBindingResponse()
|
public void testCreateBindingResponse()
|
||||||
throws Exception
|
throws Exception
|
||||||
{
|
{
|
||||||
@ -183,7 +166,6 @@ public class MessageFactoryTest extends TestCase
|
|||||||
|
|
||||||
bindingResponse.putAttribute(changedAddress);
|
bindingResponse.putAttribute(changedAddress);
|
||||||
|
|
||||||
Message expectedReturn = bindingResponse;
|
|
||||||
Message actualReturn = MessageFactory.create3489BindingResponse(
|
Message actualReturn = MessageFactory.create3489BindingResponse(
|
||||||
new TransportAddress( MsgFixture.ADDRESS_ATTRIBUTE_ADDRESS,
|
new TransportAddress( MsgFixture.ADDRESS_ATTRIBUTE_ADDRESS,
|
||||||
MsgFixture.ADDRESS_ATTRIBUTE_PORT,
|
MsgFixture.ADDRESS_ATTRIBUTE_PORT,
|
||||||
@ -194,6 +176,6 @@ public class MessageFactoryTest extends TestCase
|
|||||||
new TransportAddress( MsgFixture.ADDRESS_ATTRIBUTE_ADDRESS_3,
|
new TransportAddress( MsgFixture.ADDRESS_ATTRIBUTE_ADDRESS_3,
|
||||||
MsgFixture.ADDRESS_ATTRIBUTE_PORT_3,
|
MsgFixture.ADDRESS_ATTRIBUTE_PORT_3,
|
||||||
Transport.UDP));
|
Transport.UDP));
|
||||||
assertEquals("return value", expectedReturn, actualReturn);
|
assertEquals(bindingResponse, actualReturn);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -17,16 +17,32 @@
|
|||||||
*/
|
*/
|
||||||
package org.ice4j.message;
|
package org.ice4j.message;
|
||||||
|
|
||||||
import java.util.*;
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
import junit.framework.*;
|
|
||||||
|
|
||||||
import org.ice4j.*;
|
import org.ice4j.*;
|
||||||
import org.ice4j.attribute.*;
|
import org.ice4j.attribute.*;
|
||||||
import org.ice4j.stack.*;
|
import org.ice4j.stack.*;
|
||||||
|
import org.jitsi.config.*;
|
||||||
|
import org.junit.jupiter.api.*;
|
||||||
|
|
||||||
public class MessageTest extends TestCase
|
public class MessageTest
|
||||||
{
|
{
|
||||||
|
|
||||||
|
@BeforeAll
|
||||||
|
public static void setupConfig()
|
||||||
|
{
|
||||||
|
System.clearProperty(StackProperties.ALWAYS_SIGN);
|
||||||
|
System.setProperty("ice4j.software", "");
|
||||||
|
JitsiConfig.Companion.reloadNewConfig();
|
||||||
|
}
|
||||||
|
|
||||||
|
@AfterAll
|
||||||
|
public static void resetConfig()
|
||||||
|
{
|
||||||
|
System.clearProperty("ice4j.software");
|
||||||
|
JitsiConfig.Companion.reloadNewConfig();
|
||||||
|
}
|
||||||
|
|
||||||
private Message bindingRequest = null;
|
private Message bindingRequest = null;
|
||||||
private Message bindingResponse = null;
|
private Message bindingResponse = null;
|
||||||
|
|
||||||
@ -43,12 +59,10 @@ public class MessageTest extends TestCase
|
|||||||
*/
|
*/
|
||||||
private StunStack stunStack;
|
private StunStack stunStack;
|
||||||
|
|
||||||
protected void setUp() throws Exception
|
@BeforeEach
|
||||||
|
public void setUp() throws Exception
|
||||||
{
|
{
|
||||||
super.setUp();
|
|
||||||
|
|
||||||
msgFixture = new MsgFixture();
|
msgFixture = new MsgFixture();
|
||||||
msgFixture.setUp();
|
|
||||||
|
|
||||||
stunStack = new StunStack();
|
stunStack = new StunStack();
|
||||||
|
|
||||||
@ -89,7 +103,8 @@ public class MessageTest extends TestCase
|
|||||||
bindingResponse.setTransactionID(MsgFixture.TRANSACTION_ID);
|
bindingResponse.setTransactionID(MsgFixture.TRANSACTION_ID);
|
||||||
}
|
}
|
||||||
|
|
||||||
protected void tearDown() throws Exception
|
@AfterEach
|
||||||
|
public void tearDown() throws Exception
|
||||||
{
|
{
|
||||||
bindingRequest = null;
|
bindingRequest = null;
|
||||||
bindingResponse = null;
|
bindingResponse = null;
|
||||||
@ -97,48 +112,38 @@ public class MessageTest extends TestCase
|
|||||||
sourceAddress = null;
|
sourceAddress = null;
|
||||||
changedAddress = null;
|
changedAddress = null;
|
||||||
changeRequest = null;
|
changeRequest = null;
|
||||||
changeRequest = null;
|
|
||||||
|
|
||||||
stunStack = null;
|
stunStack = null;
|
||||||
|
|
||||||
msgFixture.tearDown();
|
|
||||||
msgFixture = null;
|
msgFixture = null;
|
||||||
|
|
||||||
super.tearDown();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Adds and gets an attribute and test that they are the same then adds a
|
* Adds and gets an attribute and test that they are the same then adds a
|
||||||
* another attribute (same typ different value) and veriies that the first
|
* another attribute (same typ different value) and verifies that the first
|
||||||
* one is properly replaced.
|
* one is properly replaced.
|
||||||
*
|
*
|
||||||
* @throws StunException java.lang.Exception if we fail
|
|
||||||
*/
|
*/
|
||||||
public void testAddAndGetAttribute() throws StunException
|
@Test
|
||||||
|
public void testAddAndGetAttribute()
|
||||||
{
|
{
|
||||||
|
|
||||||
Response message = new Response();
|
Response message = new Response();
|
||||||
message.setMessageType(Message.BINDING_SUCCESS_RESPONSE);
|
message.setMessageType(Message.BINDING_SUCCESS_RESPONSE);
|
||||||
message.putAttribute(mappedAddress);
|
message.putAttribute(mappedAddress);
|
||||||
|
|
||||||
Attribute getResult = null;
|
Attribute getResult;
|
||||||
|
|
||||||
|
|
||||||
getResult = message.getAttribute(mappedAddress.getAttributeType());
|
getResult = message.getAttribute(mappedAddress.getAttributeType());
|
||||||
assertEquals("Originally added attribute did not match the one retrned "
|
assertEquals(mappedAddress, getResult,
|
||||||
+"by getAttribute()",
|
"Originally added attribute did not match the returned");
|
||||||
mappedAddress,
|
|
||||||
getResult);
|
|
||||||
|
|
||||||
//do it again
|
//do it again
|
||||||
message.putAttribute(sourceAddress);
|
message.putAttribute(sourceAddress);
|
||||||
|
|
||||||
getResult = message.getAttribute(sourceAddress.getAttributeType());
|
getResult = message.getAttribute(sourceAddress.getAttributeType());
|
||||||
|
|
||||||
|
assertEquals(sourceAddress, getResult,
|
||||||
assertEquals("The second attribute could not be extracted.",
|
"The second attribute could not be extracted.");
|
||||||
sourceAddress,
|
|
||||||
getResult);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -147,6 +152,7 @@ public class MessageTest extends TestCase
|
|||||||
*
|
*
|
||||||
* @throws StunException java.lang.Exception if we fail
|
* @throws StunException java.lang.Exception if we fail
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testEncode()
|
public void testEncode()
|
||||||
throws StunException
|
throws StunException
|
||||||
{
|
{
|
||||||
@ -154,16 +160,16 @@ public class MessageTest extends TestCase
|
|||||||
byte[] expectedReturn = msgFixture.bindingRequest;
|
byte[] expectedReturn = msgFixture.bindingRequest;
|
||||||
|
|
||||||
byte[] actualReturn = bindingRequest.encode(stunStack);
|
byte[] actualReturn = bindingRequest.encode(stunStack);
|
||||||
assertTrue("A binding request was not properly encoded",
|
assertArrayEquals(expectedReturn, actualReturn,
|
||||||
Arrays.equals( expectedReturn, actualReturn ) );
|
"A binding request was not properly encoded");
|
||||||
|
|
||||||
//Binding Response
|
//Binding Response
|
||||||
expectedReturn = msgFixture.bindingResponse;
|
expectedReturn = msgFixture.bindingResponse;
|
||||||
|
|
||||||
actualReturn = bindingResponse.encode(stunStack);
|
actualReturn = bindingResponse.encode(stunStack);
|
||||||
|
|
||||||
assertTrue("A binding response was not properly encoded",
|
assertArrayEquals(expectedReturn, actualReturn,
|
||||||
Arrays.equals( expectedReturn, actualReturn ) );
|
"A binding response was not properly encoded");
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -172,6 +178,7 @@ public class MessageTest extends TestCase
|
|||||||
*
|
*
|
||||||
* @throws Exception java.lang.Exception if we fail
|
* @throws Exception java.lang.Exception if we fail
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testDecode()
|
public void testDecode()
|
||||||
throws Exception
|
throws Exception
|
||||||
{
|
{
|
||||||
@ -179,21 +186,21 @@ public class MessageTest extends TestCase
|
|||||||
Message expectedReturn = bindingRequest;
|
Message expectedReturn = bindingRequest;
|
||||||
|
|
||||||
Message actualReturn = Message.decode(msgFixture.bindingRequest,
|
Message actualReturn = Message.decode(msgFixture.bindingRequest,
|
||||||
(char)0,
|
0,
|
||||||
(char)msgFixture.bindingRequest.length);
|
msgFixture.bindingRequest.length);
|
||||||
|
|
||||||
assertEquals("A binding request was not properly decoded",
|
assertEquals(expectedReturn, actualReturn,
|
||||||
expectedReturn, actualReturn );
|
"A binding request was not properly decoded");
|
||||||
|
|
||||||
//Binding Response
|
//Binding Response
|
||||||
expectedReturn = bindingResponse;
|
expectedReturn = bindingResponse;
|
||||||
|
|
||||||
actualReturn = Message.decode(msgFixture.bindingResponse,
|
actualReturn = Message.decode(msgFixture.bindingResponse,
|
||||||
(char)0,
|
0,
|
||||||
(char)msgFixture.bindingResponse.length);
|
msgFixture.bindingResponse.length);
|
||||||
|
|
||||||
assertEquals("A binding response was not properly decoded",
|
assertEquals(expectedReturn, actualReturn,
|
||||||
expectedReturn, actualReturn );
|
"A binding response was not properly decoded");
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -202,39 +209,30 @@ public class MessageTest extends TestCase
|
|||||||
*
|
*
|
||||||
* @throws StunException java.lang.Exception if we fail
|
* @throws StunException java.lang.Exception if we fail
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testEquals()
|
public void testEquals()
|
||||||
throws StunException
|
throws StunException
|
||||||
{
|
{
|
||||||
Object target = null;
|
assertNotEquals(bindingRequest, null,
|
||||||
boolean expectedReturn = false;
|
"Equals failed against a null target");
|
||||||
boolean actualReturn = bindingRequest.equals(target);
|
|
||||||
assertEquals("Equals failed against a null target",
|
|
||||||
expectedReturn, actualReturn);
|
|
||||||
|
|
||||||
actualReturn = bindingResponse.equals(target);
|
assertNotEquals(bindingResponse, null,
|
||||||
assertEquals("Equals failed against a null target",
|
"Equals failed against a null target");
|
||||||
expectedReturn, actualReturn);
|
|
||||||
|
|
||||||
//different
|
//different
|
||||||
actualReturn = bindingRequest.equals(bindingResponse);
|
assertNotEquals(bindingRequest, bindingResponse,
|
||||||
assertEquals("Equals failed against a different target",
|
"Equals failed against a different target");
|
||||||
expectedReturn, actualReturn);
|
|
||||||
|
|
||||||
actualReturn = bindingResponse.equals(bindingRequest);
|
assertNotEquals(bindingResponse, bindingRequest,
|
||||||
assertEquals("Equals failed against a different target",
|
"Equals failed against a different target");
|
||||||
expectedReturn, actualReturn);
|
|
||||||
|
|
||||||
//same
|
|
||||||
expectedReturn = true;
|
|
||||||
|
|
||||||
//Create a binding request with the same attributes as
|
//Create a binding request with the same attributes as
|
||||||
//this.bindingRequest
|
//this.bindingRequest
|
||||||
Request binReqTarget = new Request();
|
Request binReqTarget = new Request();
|
||||||
binReqTarget.setMessageType(Message.BINDING_REQUEST);
|
binReqTarget.setMessageType(Message.BINDING_REQUEST);
|
||||||
binReqTarget.putAttribute(changeRequest);
|
binReqTarget.putAttribute(changeRequest);
|
||||||
actualReturn = bindingRequest.equals(binReqTarget);
|
assertEquals(bindingRequest, binReqTarget,
|
||||||
assertEquals("Equals failed against an equal target",
|
"Equals failed against an equal target");
|
||||||
expectedReturn, actualReturn);
|
|
||||||
|
|
||||||
//Create a binding response with the same attributes as
|
//Create a binding response with the same attributes as
|
||||||
//this.bindingRequest
|
//this.bindingRequest
|
||||||
@ -243,42 +241,42 @@ public class MessageTest extends TestCase
|
|||||||
binResTarget.putAttribute(mappedAddress);
|
binResTarget.putAttribute(mappedAddress);
|
||||||
binResTarget.putAttribute(sourceAddress);
|
binResTarget.putAttribute(sourceAddress);
|
||||||
binResTarget.putAttribute(changedAddress);
|
binResTarget.putAttribute(changedAddress);
|
||||||
actualReturn = bindingResponse.equals(binResTarget);
|
assertEquals(bindingResponse, binResTarget,
|
||||||
assertEquals("Equals failed against a different target",
|
"Equals failed against a different target");
|
||||||
expectedReturn, actualReturn);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Tests whether attributes are properly counted
|
* Tests whether attributes are properly counted
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testGetAttributeCount()
|
public void testGetAttributeCount()
|
||||||
{
|
{
|
||||||
int expectedReturn = 1;
|
int expectedReturn = 1;
|
||||||
int actualReturn = bindingRequest.getAttributeCount();
|
int actualReturn = bindingRequest.getAttributeCount();
|
||||||
assertEquals("getAttributeCount failed for a bindingRequest",
|
assertEquals(expectedReturn, actualReturn,
|
||||||
expectedReturn, actualReturn);
|
"getAttributeCount failed for a bindingRequest");
|
||||||
expectedReturn = 3;
|
expectedReturn = 3;
|
||||||
actualReturn = bindingResponse.getAttributeCount();
|
actualReturn = bindingResponse.getAttributeCount();
|
||||||
assertEquals("getAttributeCount failed for a bindingRequest",
|
assertEquals(expectedReturn, actualReturn,
|
||||||
expectedReturn, actualReturn);
|
"getAttributeCount failed for a bindingRequest");
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Test whether attributes are properly removed.
|
* Test whether attributes are properly removed.
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testRemoveAttribute()
|
public void testRemoveAttribute()
|
||||||
{
|
{
|
||||||
|
|
||||||
bindingRequest.removeAttribute(changeRequest.getAttributeType());
|
bindingRequest.removeAttribute(changeRequest.getAttributeType());
|
||||||
|
|
||||||
assertNull("An attribute was still in the request after being removed",
|
assertNull(bindingRequest.getAttribute(changeRequest.getAttributeType()),
|
||||||
bindingRequest.getAttribute(changeRequest.getAttributeType()));
|
"An attribute was still in the request after being removed");
|
||||||
|
|
||||||
//test count
|
//test count
|
||||||
int expectedReturn = 0;
|
int expectedReturn = 0;
|
||||||
int actualReturn = bindingRequest.getAttributeCount();
|
int actualReturn = bindingRequest.getAttributeCount();
|
||||||
assertEquals(
|
assertEquals(expectedReturn, actualReturn,
|
||||||
"Attribute count did not change after removing an attribute",
|
"Attribute count did not change after removing an attribute");
|
||||||
expectedReturn, actualReturn);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -17,32 +17,31 @@
|
|||||||
*/
|
*/
|
||||||
package org.ice4j.pseudotcp;
|
package org.ice4j.pseudotcp;
|
||||||
|
|
||||||
import junit.framework.*;
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
import java.util.function.BooleanSupplier;
|
||||||
|
import java.util.function.Function;
|
||||||
|
import java.util.function.Predicate;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* This class enables multi thread tests where main thread waits in loop
|
* This class enables multi thread tests where main thread waits in loop for
|
||||||
* for specified condition to be met, while others perform some operations.
|
* specified condition to be met, while others perform some operations. For
|
||||||
* For example until the connection is established or closed.
|
* example until the connection is established or closed. It also registers
|
||||||
* It also registers default uncaught exception handler to catch exceptions
|
* default uncaught exception handler to catch exceptions from other threads.
|
||||||
* from other threads.
|
* <p>
|
||||||
*
|
|
||||||
* Condition checks are passed as IWaitUntilDone interface.
|
* Condition checks are passed as IWaitUntilDone interface.
|
||||||
*
|
*
|
||||||
* @author Pawel Domas
|
* @author Pawel Domas
|
||||||
*/
|
*/
|
||||||
public class MultiThreadSupportTest
|
public class MultiThreadSupportTest implements Thread.UncaughtExceptionHandler
|
||||||
extends TestCase
|
|
||||||
implements Thread.UncaughtExceptionHandler
|
|
||||||
{
|
{
|
||||||
private volatile Throwable testError;
|
private volatile Throwable testError;
|
||||||
|
|
||||||
private volatile Thread errorThread;
|
private volatile Thread errorThread;
|
||||||
|
|
||||||
private final Object testLock = new Object();
|
private final Object testLock = new Object();
|
||||||
|
|
||||||
public MultiThreadSupportTest()
|
|
||||||
{
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void uncaughtException(Thread t, Throwable e)
|
public void uncaughtException(Thread t, Throwable e)
|
||||||
{
|
{
|
||||||
@ -54,30 +53,28 @@ public class MultiThreadSupportTest
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private long assertWaitInterval = 100;
|
private static final long ASSERT_WAIT_INTERVAL = 100;
|
||||||
protected interface WaitUntilDone
|
|
||||||
{
|
|
||||||
public boolean isDone();
|
|
||||||
}
|
|
||||||
|
|
||||||
protected boolean assert_wait_until(WaitUntilDone wait, long timeoutMs)
|
protected boolean assert_wait_until(BooleanSupplier wait, long timeoutMs)
|
||||||
{
|
{
|
||||||
|
long timeoutNanos = TimeUnit.MILLISECONDS.toNanos(timeoutMs);
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
long start = System.currentTimeMillis();
|
long start = System.nanoTime();
|
||||||
while (!wait.isDone() && (System.currentTimeMillis() - start) < timeoutMs)
|
while (!wait.getAsBoolean() && (System.nanoTime() - start) < timeoutNanos)
|
||||||
{
|
{
|
||||||
synchronized (testLock)
|
synchronized (testLock)
|
||||||
{
|
{
|
||||||
testLock.wait(assertWaitInterval);
|
testLock.wait(ASSERT_WAIT_INTERVAL);
|
||||||
if (testError != null)
|
if (testError != null)
|
||||||
{
|
{
|
||||||
testError.printStackTrace();
|
testError.printStackTrace();
|
||||||
fail("Error in thread: " + errorThread.getName() + " : " + testError.getMessage());
|
fail("Error in thread: " + errorThread.getName() + " : "
|
||||||
|
+ testError.getMessage());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return wait.isDone();
|
return wait.getAsBoolean();
|
||||||
}
|
}
|
||||||
catch (InterruptedException ex)
|
catch (InterruptedException ex)
|
||||||
{
|
{
|
||||||
@ -87,6 +84,4 @@ public class MultiThreadSupportTest
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@ -17,16 +17,14 @@
|
|||||||
*/
|
*/
|
||||||
package org.ice4j.pseudotcp;
|
package org.ice4j.pseudotcp;
|
||||||
|
|
||||||
import static org.junit.Assert.*;
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
import java.io.*;
|
import java.io.*;
|
||||||
import java.net.*;
|
import java.net.*;
|
||||||
|
import java.util.concurrent.atomic.*;
|
||||||
import java.util.logging.*;
|
import java.util.logging.*;
|
||||||
|
import org.junit.jupiter.api.*;
|
||||||
|
|
||||||
/**
|
|
||||||
*
|
|
||||||
* @author Pawel Domas
|
|
||||||
*/
|
|
||||||
public class PseudoTcpStreamTest
|
public class PseudoTcpStreamTest
|
||||||
extends MultiThreadSupportTest
|
extends MultiThreadSupportTest
|
||||||
{
|
{
|
||||||
@ -36,19 +34,15 @@ public class PseudoTcpStreamTest
|
|||||||
private static final Logger logger = Logger
|
private static final Logger logger = Logger
|
||||||
.getLogger(PseudoTcpStreamTest.class.getName());
|
.getLogger(PseudoTcpStreamTest.class.getName());
|
||||||
|
|
||||||
public PseudoTcpStreamTest()
|
|
||||||
{
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Test one-way transfer with @link(PseudoTcpStream)
|
* Test one-way transfer with @link(PseudoTcpStream)
|
||||||
* @throws IOException
|
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
|
@Timeout(10)
|
||||||
public void testConnectTransferClose()
|
public void testConnectTransferClose()
|
||||||
throws IOException
|
throws IOException
|
||||||
{
|
{
|
||||||
Thread.setDefaultUncaughtExceptionHandler(this);
|
Thread.setDefaultUncaughtExceptionHandler(this);
|
||||||
final int server_port = 49999;
|
|
||||||
int transferTimeout = 5000;
|
int transferTimeout = 5000;
|
||||||
|
|
||||||
// bytes that will be read as a single byte
|
// bytes that will be read as a single byte
|
||||||
@ -59,19 +53,18 @@ public class PseudoTcpStreamTest
|
|||||||
final byte[] bufferA = PseudoTcpTestBase.createDummyData(sizeA);
|
final byte[] bufferA = PseudoTcpTestBase.createDummyData(sizeA);
|
||||||
final int sizeB = 983746;
|
final int sizeB = 983746;
|
||||||
final byte[] bufferB = PseudoTcpTestBase.createDummyData(sizeB);
|
final byte[] bufferB = PseudoTcpTestBase.createDummyData(sizeB);
|
||||||
final InetSocketAddress serverAddress =
|
|
||||||
new InetSocketAddress(InetAddress.getLocalHost(), server_port);
|
|
||||||
final PseudoTcpSocket server =
|
final PseudoTcpSocket server =
|
||||||
new PseudoTcpSocketFactory().createSocket();
|
new PseudoTcpSocketFactory().createSocket();
|
||||||
Thread serverThread = new Thread(new Runnable()
|
server.setDebugName("L");
|
||||||
{
|
server.bind(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0));
|
||||||
@Override
|
final InetSocketAddress serverAddress =
|
||||||
public void run()
|
new InetSocketAddress(InetAddress.getLoopbackAddress(), server.getLocalPort());
|
||||||
|
AtomicBoolean clientThreadEnded = new AtomicBoolean();
|
||||||
|
AtomicBoolean serverThreadEnded = new AtomicBoolean();
|
||||||
|
Thread serverThread = new Thread(() ->
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
server.setDebugName("L");
|
|
||||||
server.bind(serverAddress);
|
|
||||||
server.accept(5000);
|
server.accept(5000);
|
||||||
byte[] rcvdSingle = new byte[singleStepCount];
|
byte[] rcvdSingle = new byte[singleStepCount];
|
||||||
// read by one byte
|
// read by one byte
|
||||||
@ -87,30 +80,31 @@ public class PseudoTcpStreamTest
|
|||||||
receiveBuffer(server.getInputStream(), sizeB);
|
receiveBuffer(server.getInputStream(), sizeB);
|
||||||
assertArrayEquals(bufferB, recvdBufferB);
|
assertArrayEquals(bufferB, recvdBufferB);
|
||||||
// server.close();
|
// server.close();
|
||||||
|
serverThreadEnded.set(true);
|
||||||
}
|
}
|
||||||
catch (IOException ex)
|
catch (IOException ex)
|
||||||
{
|
{
|
||||||
throw new RuntimeException(ex);
|
throw new RuntimeException(ex);
|
||||||
}
|
}
|
||||||
}
|
|
||||||
});
|
});
|
||||||
|
|
||||||
final PseudoTcpSocket client =
|
final PseudoTcpSocket client =
|
||||||
new PseudoTcpSocketFactory().createSocket();
|
new PseudoTcpSocketFactory().createSocket();
|
||||||
Thread clientThread = new Thread(new Runnable()
|
Thread clientThread = new Thread(() ->
|
||||||
{
|
|
||||||
@Override
|
|
||||||
public void run()
|
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
client.setDebugName("R");
|
client.setDebugName("R");
|
||||||
client.connect(serverAddress, 5000);
|
client.connect(serverAddress, 5000);
|
||||||
|
OutputStream os = client.getOutputStream();
|
||||||
|
|
||||||
// write single array
|
// write single array
|
||||||
for (int i = 0; i < singleStepCount; i++)
|
for (int i = 0; i < singleStepCount; i++)
|
||||||
client.getOutputStream().write(bufferSingle[i]);
|
os.write(bufferSingle[i]);
|
||||||
|
|
||||||
// write whole array
|
// write whole array
|
||||||
client.getOutputStream().write(bufferA);
|
os.write(bufferA);
|
||||||
|
|
||||||
// write by parts
|
// write by parts
|
||||||
int partCount = 7;
|
int partCount = 7;
|
||||||
boolean notExact = sizeB % partCount != 0;
|
boolean notExact = sizeB % partCount != 0;
|
||||||
@ -124,39 +118,41 @@ public class PseudoTcpStreamTest
|
|||||||
partsSize[i] = sizeB / partCount;
|
partsSize[i] = sizeB / partCount;
|
||||||
}
|
}
|
||||||
int written = 0;
|
int written = 0;
|
||||||
for (int i = 0; i < partsSize.length; i++)
|
for (int j : partsSize)
|
||||||
{
|
{
|
||||||
client.getOutputStream().write(bufferB, written,
|
os.write(bufferB, written, j);
|
||||||
partsSize[i]);
|
written += j;
|
||||||
written += partsSize[i];
|
|
||||||
}
|
}
|
||||||
assertEquals(sizeB, written);
|
assertEquals(sizeB, written);
|
||||||
client.getOutputStream().flush();
|
os.flush();
|
||||||
client.close();
|
client.close();
|
||||||
|
clientThreadEnded.set(true);
|
||||||
}
|
}
|
||||||
catch (IOException ex)
|
catch (IOException ex)
|
||||||
{
|
{
|
||||||
throw new RuntimeException(ex);
|
throw new RuntimeException(ex);
|
||||||
}
|
}
|
||||||
}
|
|
||||||
});
|
});
|
||||||
|
|
||||||
serverThread.start();
|
serverThread.start();
|
||||||
clientThread.start();
|
clientThread.start();
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
boolean success = assert_wait_until(new WaitUntilDone()
|
boolean success = assert_wait_until(
|
||||||
{
|
() -> client.getState() == PseudoTcpState.TCP_CLOSED,
|
||||||
@Override
|
transferTimeout);
|
||||||
public boolean isDone()
|
|
||||||
{
|
|
||||||
return client.getState() == PseudoTcpState.TCP_CLOSED;
|
|
||||||
}
|
|
||||||
}, transferTimeout);
|
|
||||||
if (success)
|
if (success)
|
||||||
{
|
{
|
||||||
clientThread.join();
|
clientThread.join(10_000);
|
||||||
serverThread.join();
|
if (!clientThreadEnded.get())
|
||||||
|
{
|
||||||
|
fail("client thread did not end");
|
||||||
|
}
|
||||||
|
serverThread.join(10_000);
|
||||||
|
if (!serverThreadEnded.get())
|
||||||
|
{
|
||||||
|
fail("server thread did not end");
|
||||||
|
}
|
||||||
server.close();
|
server.close();
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
@ -191,52 +187,35 @@ public class PseudoTcpStreamTest
|
|||||||
/**
|
/**
|
||||||
* Test the timeout on accept method
|
* Test the timeout on accept method
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testAccept()
|
public void testAccept()
|
||||||
{
|
{
|
||||||
try
|
assertThrows(IOException.class, ()->
|
||||||
{
|
{
|
||||||
PseudoTcpSocketImpl server = new PseudoTcpSocketImpl(0);
|
PseudoTcpSocketImpl server = new PseudoTcpSocketImpl(0);
|
||||||
server.accept(10);
|
server.accept(10);
|
||||||
fail("Should throw timeout exception");
|
});
|
||||||
}
|
|
||||||
catch (IOException ex)
|
|
||||||
{
|
|
||||||
// success
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Interface used to pass timeout test function
|
* Interface used to pass timeout test function
|
||||||
* @author Pawel Domas
|
|
||||||
*
|
|
||||||
*/
|
*/
|
||||||
private interface TimeoutOperationTest
|
private interface TimeoutOperationTest
|
||||||
{
|
{
|
||||||
void testTimeout(PseudoTcpSocketImpl socket) throws IOException;
|
void testTimeout(PseudoTcpSocketImpl socket) throws IOException;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
*
|
|
||||||
* @param testOperation
|
|
||||||
* @throws UnknownHostException
|
|
||||||
*/
|
|
||||||
private void doTestTimeout(final TimeoutOperationTest testOperation)
|
private void doTestTimeout(final TimeoutOperationTest testOperation)
|
||||||
throws Exception
|
throws Exception
|
||||||
{
|
{
|
||||||
Thread.setDefaultUncaughtExceptionHandler(this);
|
Thread.setDefaultUncaughtExceptionHandler(this);
|
||||||
final PseudoTcpSocketImpl server;
|
final PseudoTcpSocketImpl server;
|
||||||
final PseudoTcpSocketImpl client;
|
final PseudoTcpSocketImpl client;
|
||||||
final int server_port = 49998;
|
DatagramSocket serverSocket = new DatagramSocket(0, InetAddress.getLoopbackAddress());
|
||||||
final InetSocketAddress serverAddress =
|
server = new PseudoTcpSocketImpl(0, serverSocket);
|
||||||
new InetSocketAddress(InetAddress.getLocalHost(), server_port);
|
|
||||||
server =
|
|
||||||
new PseudoTcpSocketImpl(0,new DatagramSocket(serverAddress));
|
|
||||||
client = new PseudoTcpSocketImpl(0);
|
client = new PseudoTcpSocketImpl(0);
|
||||||
//Servers thread waiting for connection
|
//Servers thread waiting for connection
|
||||||
new Thread(new Runnable()
|
new Thread(() ->
|
||||||
{
|
|
||||||
@Override
|
|
||||||
public void run()
|
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
@ -249,7 +228,7 @@ public class PseudoTcpStreamTest
|
|||||||
try
|
try
|
||||||
{
|
{
|
||||||
testOperation.testTimeout(server);
|
testOperation.testTimeout(server);
|
||||||
fail("No expected timeout occured on operation");
|
fail("No expected timeout occurred on operation");
|
||||||
}
|
}
|
||||||
catch (IOException e)
|
catch (IOException e)
|
||||||
{
|
{
|
||||||
@ -263,18 +242,16 @@ public class PseudoTcpStreamTest
|
|||||||
throw new RuntimeException(exc);
|
throw new RuntimeException(exc);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
}).start();
|
}).start();
|
||||||
//Clients thread connects and closes socket
|
//Clients thread connects and closes socket
|
||||||
new Thread(new Runnable()
|
new Thread(() ->
|
||||||
{
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void run()
|
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
client.connect(serverAddress, 2000);
|
client.connect(new InetSocketAddress(
|
||||||
|
InetAddress.getLoopbackAddress(),
|
||||||
|
serverSocket.getLocalPort()),
|
||||||
|
2000);
|
||||||
Thread.sleep(500);
|
Thread.sleep(500);
|
||||||
client.close();
|
client.close();
|
||||||
}
|
}
|
||||||
@ -282,18 +259,10 @@ public class PseudoTcpStreamTest
|
|||||||
{
|
{
|
||||||
throw new RuntimeException(e);
|
throw new RuntimeException(e);
|
||||||
}
|
}
|
||||||
}
|
|
||||||
}).start();
|
}).start();
|
||||||
//Waits for server to close socket
|
//Waits for server to close socket
|
||||||
boolean done = assert_wait_until(new WaitUntilDone()
|
boolean done = assert_wait_until(()
|
||||||
{
|
-> server.getState() == PseudoTcpState.TCP_CLOSED, 3000);
|
||||||
|
|
||||||
@Override
|
|
||||||
public boolean isDone()
|
|
||||||
{
|
|
||||||
return server.getState() == PseudoTcpState.TCP_CLOSED;
|
|
||||||
}
|
|
||||||
}, 3000);
|
|
||||||
if(!done)
|
if(!done)
|
||||||
{
|
{
|
||||||
fail("Test timed out");
|
fail("Test timed out");
|
||||||
@ -302,51 +271,39 @@ public class PseudoTcpStreamTest
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Tests timeout on read method
|
* Tests timeout on read method
|
||||||
* @throws UnknownHostException
|
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testReadTimeout() throws Exception
|
public void testReadTimeout() throws Exception
|
||||||
{
|
{
|
||||||
doTestTimeout(new TimeoutOperationTest()
|
doTestTimeout(socket ->
|
||||||
{
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void testTimeout(PseudoTcpSocketImpl socket) throws IOException
|
|
||||||
{
|
{
|
||||||
socket.setPTCPOption(Option.OPT_READ_TIMEOUT, 300);
|
socket.setPTCPOption(Option.OPT_READ_TIMEOUT, 300);
|
||||||
socket.getInputStream().read(new byte[500]);
|
socket.getInputStream().read(new byte[500]);
|
||||||
}
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Tests timeout on write method
|
* Tests timeout on write method
|
||||||
* @throws UnknownHostException
|
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testWriteTimeout() throws Exception
|
public void testWriteTimeout() throws Exception
|
||||||
{
|
{
|
||||||
doTestTimeout(new TimeoutOperationTest()
|
doTestTimeout(socket ->
|
||||||
{
|
|
||||||
@Override
|
|
||||||
public void testTimeout(PseudoTcpSocketImpl socket) throws IOException
|
|
||||||
{
|
{
|
||||||
//buffer that will exceed stack's buffer size
|
//buffer that will exceed stack's buffer size
|
||||||
byte[] bigBuffer = new byte[PseudoTCPBase.DEFAULT_SND_BUF_SIZE*2];
|
byte[] bigBuffer = new byte[PseudoTCPBase.DEFAULT_SND_BUF_SIZE*2];
|
||||||
socket.setPTCPOption(Option.OPT_WRITE_TIMEOUT, 300);
|
socket.setPTCPOption(Option.OPT_WRITE_TIMEOUT, 300);
|
||||||
socket.getOutputStream().write(bigBuffer);
|
socket.getOutputStream().write(bigBuffer);
|
||||||
}
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Tests timeout on flush method
|
* Tests timeout on flush method
|
||||||
* @throws UnknownHostException
|
|
||||||
*/
|
*/
|
||||||
|
@Test
|
||||||
public void testFlushTimeout() throws Exception
|
public void testFlushTimeout() throws Exception
|
||||||
{
|
{
|
||||||
doTestTimeout(new TimeoutOperationTest()
|
doTestTimeout(socket ->
|
||||||
{
|
|
||||||
@Override
|
|
||||||
public void testTimeout(PseudoTcpSocketImpl socket) throws IOException
|
|
||||||
{
|
{
|
||||||
//buffer that will exceed stack's buffer size
|
//buffer that will exceed stack's buffer size
|
||||||
byte[] buffer = new byte[PseudoTCPBase.DEFAULT_SND_BUF_SIZE];
|
byte[] buffer = new byte[PseudoTCPBase.DEFAULT_SND_BUF_SIZE];
|
||||||
@ -360,8 +317,6 @@ public class PseudoTcpStreamTest
|
|||||||
throw new RuntimeException("Unexpected exception: "+e);
|
throw new RuntimeException("Unexpected exception: "+e);
|
||||||
}
|
}
|
||||||
socket.getOutputStream().flush();
|
socket.getOutputStream().flush();
|
||||||
}
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@ -608,9 +608,9 @@ public abstract class PseudoTcpTestBase
|
|||||||
runClocks = false;
|
runClocks = false;
|
||||||
localClockThread.interrupt();
|
localClockThread.interrupt();
|
||||||
remoteClockThread.interrupt();
|
remoteClockThread.interrupt();
|
||||||
localClockThread.join();
|
localClockThread.join(5000);
|
||||||
localClockThread = null;
|
localClockThread = null;
|
||||||
remoteClockThread.join();
|
remoteClockThread.join(5000);
|
||||||
remoteClockThread = null;
|
remoteClockThread = null;
|
||||||
}
|
}
|
||||||
catch (InterruptedException ex)
|
catch (InterruptedException ex)
|
||||||
@ -633,14 +633,9 @@ public abstract class PseudoTcpTestBase
|
|||||||
*/
|
*/
|
||||||
protected boolean assert_Connected_wait(int kConnectTimeoutMs)
|
protected boolean assert_Connected_wait(int kConnectTimeoutMs)
|
||||||
{
|
{
|
||||||
return assert_wait_until(new WaitUntilDone()
|
return assert_wait_until(
|
||||||
{
|
() -> PseudoTcpTestBase.this.have_connected_,
|
||||||
@Override
|
kConnectTimeoutMs);
|
||||||
public boolean isDone()
|
|
||||||
{
|
|
||||||
return PseudoTcpTestBase.this.have_connected_;
|
|
||||||
}
|
|
||||||
}, kConnectTimeoutMs);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -652,14 +647,9 @@ public abstract class PseudoTcpTestBase
|
|||||||
*/
|
*/
|
||||||
protected boolean assert_Disconnected_wait(long kTransferTimeoutMs)
|
protected boolean assert_Disconnected_wait(long kTransferTimeoutMs)
|
||||||
{
|
{
|
||||||
return assert_wait_until(new WaitUntilDone()
|
return assert_wait_until(
|
||||||
{
|
() -> PseudoTcpTestBase.this.have_disconnected_,
|
||||||
@Override
|
kTransferTimeoutMs);
|
||||||
public boolean isDone()
|
|
||||||
{
|
|
||||||
return PseudoTcpTestBase.this.have_disconnected_;
|
|
||||||
}
|
|
||||||
}, kTransferTimeoutMs);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user