Compare commits

..

1 Commits
master ... nlj

Author SHA1 Message Date
Boris Grozev
4a8af3e161 ref: Moves some utility classes to jitsi-java-utils. 2019-03-18 13:57:35 +00:00
168 changed files with 6858 additions and 4497 deletions

View File

@ -1,17 +0,0 @@
[*]
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

View File

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

4
.gitignore vendored
View File

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

View File

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

View File

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

View File

@ -1,40 +0,0 @@
<?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>

415
pom.xml
View File

@ -1,292 +1,114 @@
<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>3.0-SNAPSHOT</version> <version>2.0.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>
<groupId>org.jitsi</groupId>
<artifactId>jitsi-java-utils</artifactId>
<version>1.0.0-SNAPSHOT</version>
</dependency>
<dependency> <dependency>
<groupId>org.opentelecoms.sdp</groupId> <groupId>org.opentelecoms.sdp</groupId>
<artifactId>java-sdp-nist-bridge</artifactId> <artifactId>java-sdp-nist-bridge</artifactId>
<version>1.2</version> </dependency>
<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>org.junit.platform</groupId> <groupId>junit</groupId>
<artifactId>junit-platform-launcher</artifactId> <artifactId>junit</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>
<build> <build>
<plugins> <plugins>
<plugin>
<groupId>org.jetbrains.kotlin</groupId>
<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>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId> <artifactId>maven-compiler-plugin</artifactId>
<version>3.10.1</version>
<executions>
<!-- Replacing default-compile as it is treated specially by maven -->
<execution>
<id>default-compile</id>
<phase>none</phase>
</execution>
<!-- Replacing default-testCompile as it is treated specially by maven -->
<execution>
<id>default-testCompile</id>
<phase>none</phase>
</execution>
<execution>
<id>java-compile</id>
<phase>compile</phase>
<goals>
<goal>compile</goal>
</goals>
</execution>
<execution>
<id>java-test-compile</id>
<phase>test-compile</phase>
<goals>
<goal>testCompile</goal>
</goals>
</execution>
</executions>
<configuration> <configuration>
<release>11</release> <source>1.8</source>
<compilerArgs> <target>1.8</target>
<arg>-Xlint:all</arg>
</compilerArgs>
</configuration> </configuration>
</plugin> </plugin>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
</plugin>
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId> <artifactId>maven-javadoc-plugin</artifactId>
<version>3.1.2</version> <version>2.10.4</version>
<configuration> <configuration>
<configLocation>checkstyle.xml</configLocation> <show>private</show>
</configuration> <nohelp>true</nohelp>
<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>
<systemPropertyVariables> <include>**/*TestSuite.*</include>
<java.util.logging.config.file>${project.build.testSourceDirectory}/../resources/logging.properties</java.util.logging.config.file> </includes>
</systemPropertyVariables>
</configuration> </configuration>
</plugin> </plugin>
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>com.github.siom79.japicmp</groupId>
<artifactId>maven-deploy-plugin</artifactId> <artifactId>japicmp-maven-plugin</artifactId>
<version>3.0.0-M2</version> <version>0.10.0</version>
</plugin>
<plugin>
<groupId>org.sonatype.plugins</groupId>
<artifactId>nexus-staging-maven-plugin</artifactId>
<version>1.6.13</version>
<extensions>true</extensions>
<configuration> <configuration>
<serverId>ossrh</serverId> <newVersion>
<nexusUrl>https://oss.sonatype.org/</nexusUrl> <file>
<autoReleaseAfterClose>true</autoReleaseAfterClose> <path>${project.build.directory}/${project.build.finalName}.jar</path>
</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>
@ -295,7 +117,6 @@
<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>
@ -318,32 +139,6 @@
</build> </build>
<profiles> <profiles>
<profile>
<id>coverage</id>
<build>
<plugins>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.8.8</version>
<executions>
<execution>
<goals>
<goal>prepare-agent</goal>
</goals>
</execution>
<execution>
<id>report</id>
<phase>test</phase>
<goals>
<goal>report</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
<profile> <profile>
<id>run-sample</id> <id>run-sample</id>
<build> <build>
@ -448,95 +243,5 @@
</plugins> </plugins>
</build> </build>
</profile> </profile>
<profile>
<id>release</id>
<activation>
<property>
<name>release</name>
<value>true</value>
</property>
</activation>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
<version>3.3.0</version>
<executions>
<execution>
<phase>generate-sources</phase>
<goals>
<goal>add-source</goal>
</goals>
<configuration>
<sources>
<source>src/main/kotlin</source>
</sources>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<version>3.2.1</version>
<executions>
<execution>
<id>attach-sources</id>
<phase>verify</phase>
<goals>
<goal>jar-no-fork</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.jetbrains.dokka</groupId>
<artifactId>dokka-maven-plugin</artifactId>
<version>${dokka.version}</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>javadocJar</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-gpg-plugin</artifactId>
<version>3.0.1</version>
<executions>
<execution>
<id>sign-artifacts</id>
<phase>verify</phase>
<goals>
<goal>sign</goal>
</goals>
</execution>
</executions>
<configuration>
<gpgArguments>
<arg>--pinentry-mode</arg>
<arg>loopback</arg>
</gpgArguments>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles> </profiles>
<distributionManagement>
<snapshotRepository>
<id>ossrh</id>
<url>https://oss.sonatype.org/content/repositories/snapshots</url>
</snapshotRepository>
<repository>
<id>ossrh</id>
<url>https://oss.sonatype.org/service/local/staging/deploy/maven2/</url>
</repository>
</distributionManagement>
</project> </project>

View File

@ -59,6 +59,43 @@ public class StackProperties
*/ */
public static final String BIND_WILDCARD = "org.ice4j.BIND_WILDCARD"; public static final String BIND_WILDCARD = "org.ice4j.BIND_WILDCARD";
/**
* How often a STUN Binding request used for consent freshness check will be
* sent(value in milliseconds).
*/
public static final String CONSENT_FRESHNESS_INTERVAL
= "org.ice4j.ice.CONSENT_FRESHNESS_INTERVAL";
/**
* The maximum number of retransmissions of a STUN Binding request without
* a valid STUN Binding response after which consent freshness is to be
* considered unconfirmed according to &quot;STUN Usage for Consent
* Freshness&quot;.
*/
public static final String CONSENT_FRESHNESS_MAX_RETRANSMISSIONS
= "org.ice4j.ice.CONSENT_FRESHNESS_MAX_RETRANSMISSIONS";
/**
* The number of milliseconds without a valid STUN Binding response after
* which a STUN Binding request is to be retransmitted according to
* &quot;STUN Usage for Consent Freshness&quot;. This is the final value
* for the back-off strategy.
* {@link #CONSENT_FRESHNESS_ORIGINAL_WAIT_INTERVAL} defines the initial
* interval for the first request sent. Value in milliseconds.
*/
public static final String CONSENT_FRESHNESS_MAX_WAIT_INTERVAL
= "org.ice4j.ice.CONSENT_FRESHNESS_MAX_WAIT_INTERVAL";
/**
* The number of milliseconds without a valid STUN Binding response after
* which a STUN Binding request is to be retransmitted according to
* &quot;STUN Usage for Consent Freshness&quot;. This is the original value
* for back-off strategy. {@link #CONSENT_FRESHNESS_MAX_WAIT_INTERVAL} sets
* the upper limit. Value in milliseconds.
*/
public static final String CONSENT_FRESHNESS_ORIGINAL_WAIT_INTERVAL
= "org.ice4j.ice.CONSENT_FRESHNESS_WAIT_INTERVAL";
/** /**
* The number of milliseconds a client transaction should wait before * The number of milliseconds a client transaction should wait before
* retransmitting, after it has sent a request for the first time. * retransmitting, after it has sent a request for the first time.
@ -86,6 +123,19 @@ 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.
@ -114,6 +164,14 @@ 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.
@ -132,6 +190,11 @@ 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.
@ -156,6 +219,13 @@ public class StackProperties
public static final String ALLOWED_ADDRESSES public static final String ALLOWED_ADDRESSES
= "org.ice4j.ice.harvest.ALLOWED_ADDRESSES"; = "org.ice4j.ice.harvest.ALLOWED_ADDRESSES";
/**
* The name of the property which, if set to true, specifies that
* link local addresses should not be used for candidate allocations.
*/
public static final String DISABLE_LINK_LOCAL_ADDRESSES
= "org.ice4j.ice.harvest.DISABLE_LINK_LOCAL_ADDRESSES";
/** /**
* The name of the property which specifies a ";"-separated list of IP * The name of the property which specifies a ";"-separated list of IP
* addresses that are not allowed to be used for host candidate allocations. * addresses that are not allowed to be used for host candidate allocations.
@ -166,6 +236,31 @@ public class StackProperties
public static final String BLOCKED_ADDRESSES public static final String BLOCKED_ADDRESSES
= "org.ice4j.ice.harvest.BLOCKED_ADDRESSES"; = "org.ice4j.ice.harvest.BLOCKED_ADDRESSES";
/**
* The name of the property which specifies whether the dynamic port UDP
* host harvester should be used by <tt>Agent</tt> instances.
*/
public static final String USE_DYNAMIC_HOST_HARVESTER
= "org.ice4j.ice.harvest.USE_DYNAMIC_HOST_HARVESTER";
/**
* Timeout, in seconds, of how long to wait for an individual harvest before timing out
*/
public static final String HARVESTING_TIMEOUT
= "org.ice4j.ice.harvest.HARVESTING_TIMEOUT";
/**
* The name of the property which specifies whether the per-component
* merging socket should be enabled by default (the default value can be
* overridden with {@link Agent#createComponent(IceMediaStream, Transport,
* int, int, int, KeepAliveStrategy, boolean)}.
* If enabled, the user of the library must use the socket instance provided
* by {@link Component#getSocket()}. Otherwise, the socket instance from the
* desired {@link CandidatePair} must be used.
*/
public static final String USE_COMPONENT_SOCKET
= "org.ice4j.ice.USE_COMPONENT_SOCKET";
/** /**
* Returns the String value of the specified property (minus all * Returns the String value of the specified property (minus all
* encompassing whitespaces)and null in case no property value was mapped * encompassing whitespaces)and null in case no property value was mapped

View File

@ -221,12 +221,10 @@ 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);
} }

View File

@ -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,
int offset, char offset,
int length) char length)
throws StunException throws StunException
{ {
if(bytes == null || bytes.length < Attribute.HEADER_LENGTH) if(bytes == null || bytes.length < Attribute.HEADER_LENGTH)

View File

@ -308,12 +308,12 @@ public class MessageIntegrityAttribute
logger.warning("Can not encode a message of type Indication."); logger.warning("Can not encode a message of type Indication.");
} }
Objects.requireNonNull(key, "key=null; msgType=" + String.format("%04X", (int)msgType)); Objects.requireNonNull(key, "key=null; msgType=" + 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, HEADER_LENGTH, getDataLength()); System.arraycopy(hmacSha1Content, 0, binValue, 4, getDataLength());
return binValue; return binValue;
} }

View File

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

View File

@ -17,11 +17,11 @@
*/ */
package org.ice4j.ice; package org.ice4j.ice;
import org.jitsi.utils.logging2.*;
import java.beans.*; import java.beans.*;
import java.util.*; import java.util.*;
import org.ice4j.util.Logger;
/** /**
* A check list is a list of <tt>CandidatePair</tt>s with a state (i.e. a * A check list is a list of <tt>CandidatePair</tt>s with a state (i.e. a
* <tt>CheckListState</tt>). The pairs in a check list are those that an ICE * <tt>CheckListState</tt>). The pairs in a check list are those that an ICE
@ -35,6 +35,15 @@ import java.util.*;
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.
*/ */
@ -98,7 +107,8 @@ public class CheckList
protected CheckList(IceMediaStream parentStream) protected CheckList(IceMediaStream parentStream)
{ {
this.parentStream = parentStream; this.parentStream = parentStream;
logger = parentStream.getLogger().createChildLogger(this.getClass().getName()); logger
= new Logger(classLogger, parentStream.getParentAgent().getLogger());
} }
/** /**
@ -209,25 +219,6 @@ 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

View File

@ -18,13 +18,15 @@
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.jitsi.utils.logging2.*; import org.ice4j.util.Logger; //Disambiguation
/** /**
* 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
@ -41,6 +43,15 @@ import org.jitsi.utils.logging2.*;
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.
*/ */
@ -164,10 +175,9 @@ 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, parentLogger); this(componentID, mediaStream, keepAliveStrategy, true);
} }
/** /**
@ -182,24 +192,21 @@ 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(
this.getClass().getName(), Logger agentLogger = mediaStream.getParentAgent().getLogger();
Collections.singletonMap("componentId", Integer.toString(componentID))
);
if (useComponentSocket) if (useComponentSocket)
{ {
try try
{ {
componentSocket = new ComponentSocket(this, logger); componentSocket = new ComponentSocket(this, agentLogger);
socket = new MultiplexingDatagramSocket(componentSocket); socket = new MultiplexingDatagramSocket(componentSocket);
socketWrapper = new IceUdpSocketWrapper(socket); socketWrapper = new IceUdpSocketWrapper(socket);
} }
@ -216,6 +223,7 @@ public class Component
} }
mediaStream.addPairChangeListener(this); mediaStream.addPairChangeListener(this);
logger = new Logger(classLogger, agentLogger);
} }
/** /**
@ -435,6 +443,9 @@ 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);
} }
} }
@ -460,28 +471,8 @@ 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()
+ ".");
}
} }
} }
} }
@ -703,7 +694,11 @@ public class Component
&& (cand.getPriority() >= cand2.getPriority())) && (cand.getPriority() >= cand2.getPriority()))
{ {
localCandidates.remove(j); localCandidates.remove(j);
logger.trace(() -> "eliminating redundant cand: "+ cand2); if (logger.isLoggable(Level.FINEST))
{
logger.finest(
"eliminating redundant cand: "+ cand2);
}
} }
else else
j++; j++;
@ -904,7 +899,12 @@ public class Component
*/ */
if (t instanceof ThreadDeath) if (t instanceof ThreadDeath)
throw (ThreadDeath) t; throw (ThreadDeath) t;
logger.info(() -> "Failed to free LocalCandidate: " + localCandidate); if (logger.isLoggable(Level.INFO))
{
logger.log(
Level.INFO,
"Failed to free LocalCandidate: " + localCandidate);
}
} }
} }
@ -921,47 +921,10 @@ public class Component
*/ */
public LocalCandidate findLocalCandidate(TransportAddress localAddress) public LocalCandidate findLocalCandidate(TransportAddress localAddress)
{ {
return findLocalCandidate(localAddress, null); for (LocalCandidate localCnd : localCandidates)
}
/**
* Returns the local <tt>LocalCandidate</tt> with the specified
* <tt>address</tt> if it belongs to this component or <tt>null</tt>
* if it doesn't. If {@code base} is also specified, tries to find a
* candidate whose base matches {@code base}.
*
* @param address the {@link TransportAddress} we are looking for.
* @param base an optional base to match.
*
* @return the local <tt>LocalCandidate</tt> with the specified
* <tt>address</tt> if it belongs to this component or <tt>null</tt>
* if it doesn't.
*/
public LocalCandidate findLocalCandidate(TransportAddress address, LocalCandidate base)
{ {
for (LocalCandidate localCandidate : localCandidates) if (localCnd.getTransportAddress().equals(localAddress))
{ 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;
@ -1054,16 +1017,15 @@ public class Component
* parent of this component. * parent of this component.
* @return Component * @return Component
*/ */
public static Component build(int componentID, IceMediaStream mediaStream, Logger parentLogger) public static Component build(int componentID, IceMediaStream mediaStream)
{ {
return return
new Component( new Component(
componentID, componentID,
mediaStream, mediaStream,
KeepAliveStrategy.SELECTED_ONLY, KeepAliveStrategy.SELECTED_ONLY,
AgentConfig.config.getUseComponentSocket(), StackProperties.getBoolean(
parentLogger StackProperties.USE_COMPONENT_SOCKET, true));
);
} }
/** /**
@ -1174,9 +1136,4 @@ public class Component
keepAlivePairs.add(pair); keepAlivePairs.add(pair);
} }
} }
public Logger getLogger()
{
return logger;
}
} }

View File

@ -33,6 +33,14 @@ 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}.
*/ */
@ -60,16 +68,22 @@ 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, org.jitsi.utils.logging2.Logger parentLogger) ComponentSocket(Component component, Logger levelDelegate)
throws SocketException throws SocketException
{ {
super(parentLogger); super(levelDelegate);
this.component = component; this.component = component;
this.logger = new Logger(classLogger, levelDelegate);
component.getParentStream().addPairChangeListener(this); component.getParentStream().addPairChangeListener(this);
} }
@ -155,9 +169,7 @@ public class ComponentSocket
LocalCandidate localCandidate = pair.getLocalCandidate(); LocalCandidate localCandidate = pair.getLocalCandidate();
LocalCandidate base = localCandidate.getBase(); LocalCandidate base = localCandidate.getBase();
if (base != null) if (base != null)
{
localCandidate = base; localCandidate = base;
}
TransportAddress remoteAddress = null; TransportAddress remoteAddress = null;
RemoteCandidate remoteCandidate = pair.getRemoteCandidate(); RemoteCandidate remoteCandidate = pair.getRemoteCandidate();

View File

@ -21,6 +21,7 @@ import java.net.*;
import java.time.*; import java.time.*;
import java.util.*; import java.util.*;
import java.util.concurrent.*; import java.util.concurrent.*;
import java.util.logging.*;
import org.ice4j.*; import org.ice4j.*;
import org.ice4j.attribute.*; import org.ice4j.attribute.*;
@ -28,7 +29,7 @@ import org.ice4j.message.*;
import org.ice4j.socket.*; import org.ice4j.socket.*;
import org.ice4j.stack.*; import org.ice4j.stack.*;
import org.ice4j.util.*; import org.ice4j.util.*;
import org.jitsi.utils.logging2.Logger; import org.ice4j.util.Logger; //Disambiguation
/** /**
* The class that will be generating our outgoing connectivity checks and that * The class that will be generating our outgoing connectivity checks and that
@ -40,6 +41,17 @@ import org.jitsi.utils.logging2.Logger;
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.
*/ */
@ -66,12 +78,6 @@ class ConnectivityCheckClient
private final Queue<PaceMaker> paceMakers private final Queue<PaceMaker> paceMakers
= new ConcurrentLinkedQueue<>(); = new ConcurrentLinkedQueue<>();
/**
* Whether this {@link ConnectivityCheckClient} has been stopped.
* Synchronized by {@link #paceMakers}.
*/
private boolean stopped = false;
/** /**
* Timer that is used to let some seconds before a CheckList is considered * Timer that is used to let some seconds before a CheckList is considered
* as FAILED. * as FAILED.
@ -108,7 +114,7 @@ class ConnectivityCheckClient
this.parentAgent = parentAgent; this.parentAgent = parentAgent;
this.scheduledExecutorService = scheduledExecutorService; this.scheduledExecutorService = scheduledExecutorService;
this.executorService = executorService; this.executorService = executorService;
logger = parentAgent.getLogger().createChildLogger(this.getClass().getName()); logger = new Logger(classLogger, parentAgent.getLogger());
stunStack = this.parentAgent.getStunStack(); stunStack = this.parentAgent.getStunStack();
} }
@ -144,7 +150,8 @@ class ConnectivityCheckClient
if (streamsWithPendingConnectivityEstablishment.size() > 0) if (streamsWithPendingConnectivityEstablishment.size() > 0)
{ {
logger.info("Start connectivity checks."); logger.info("Start connectivity checks. Local ufrag "
+ parentAgent.getLocalUfrag());
startChecks( startChecks(
streamsWithPendingConnectivityEstablishment streamsWithPendingConnectivityEstablishment
.get(0).getCheckList()); .get(0).getCheckList());
@ -165,17 +172,10 @@ class ConnectivityCheckClient
*/ */
public void startChecks(CheckList checkList) public void startChecks(CheckList checkList)
{ {
synchronized (paceMakers)
{
if (stopped)
{
return;
}
PaceMaker paceMaker = new PaceMaker(checkList); PaceMaker paceMaker = new PaceMaker(checkList);
paceMakers.add(paceMaker); paceMakers.add(paceMaker);
paceMaker.schedule(); paceMaker.schedule();
} }
}
/** /**
* Creates a STUN Binding {@link Indication} to a candidate pair. It is used * Creates a STUN Binding {@link Indication} to a candidate pair. It is used
@ -195,18 +195,23 @@ class ConnectivityCheckClient
indication, indication,
candidatePair.getRemoteCandidate().getTransportAddress(), candidatePair.getRemoteCandidate().getTransportAddress(),
localCandidate.getBase().getTransportAddress()); localCandidate.getBase().getTransportAddress());
logger.trace(() -> if (logger.isLoggable(Level.FINEST))
{
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.info("Failed to send " + indication + " through " logger.log(
+ stunSocket.getLocalSocketAddress() + "\n" + Level.INFO,
ex.toString()); "Failed to send " + indication + " through "
+ stunSocket.getLocalSocketAddress(),
ex);
} }
} }
} }
@ -277,7 +282,7 @@ class ConnectivityCheckClient
//nominated pairs. //nominated pairs.
if (candidatePair.isNominated()) if (candidatePair.isNominated())
{ {
logger.debug(() -> logger.fine(
"Add USE-CANDIDATE in check for: " "Add USE-CANDIDATE in check for: "
+ candidatePair.toShortString()); + candidatePair.toShortString());
request.putAttribute( request.putAttribute(
@ -321,12 +326,9 @@ class ConnectivityCheckClient
tran.setApplicationData(candidatePair); tran.setApplicationData(candidatePair);
if (logger.isDebugEnabled()) logger.fine(
{
logger.debug(
"start check for " + candidatePair.toShortString() + " tid " "start check for " + candidatePair.toShortString() + " tid "
+ tran); + tran);
}
try try
{ {
tran tran
@ -340,15 +342,12 @@ class ConnectivityCheckClient
originalWaitInterval, originalWaitInterval,
maxWaitInterval, maxWaitInterval,
maxRetransmissions); maxRetransmissions);
if (logger.isTraceEnabled()) if (logger.isLoggable(Level.FINEST))
{ {
logger.trace("checking pair " + candidatePair + " tid " + tran); logger.finest(
"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;
@ -368,11 +367,7 @@ class ConnectivityCheckClient
msg += " No route to host."; msg += " No route to host.";
ex = null; ex = null;
} }
logger.info(msg + (ex == null ? "" : "\n" + ex.toString())); logger.log(Level.INFO, msg, ex);
}
else
{
logger.warn("Failed to send " + request, ex);
} }
} }
@ -412,7 +407,7 @@ class ConnectivityCheckClient
{ {
if (!response.containsAttribute(Attribute.ERROR_CODE)) if (!response.containsAttribute(Attribute.ERROR_CODE))
{ {
logger.debug(() -> "Received a malformed error response."); logger.fine("Received a malformed error response.");
return; //malformed error response return; //malformed error response
} }
@ -533,10 +528,11 @@ class ConnectivityCheckClient
if (!response.containsAttribute(Attribute.XOR_MAPPED_ADDRESS)) if (!response.containsAttribute(Attribute.XOR_MAPPED_ADDRESS))
{ {
logger.debug(() -> "Received a success response with no " logger.fine("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() + "."); + checkedPair.toShortString() + ". Local ufrag"
+ parentAgent.getLocalUfrag());
checkedPair.setStateFailed(); checkedPair.setStateFailed();
return; //malformed error response return; //malformed error response
} }
@ -558,12 +554,9 @@ class ConnectivityCheckClient
Transport.TCP); Transport.TCP);
} }
// In some situations we may have more than one local candidate matching LocalCandidate validLocalCandidate = null;
// the mapped address. In this case we want to find the that matches
// the socket we received the response on. validLocalCandidate = parentAgent.findLocalCandidate(mappedAddress);
LocalCandidate base = checkedPair.getLocalCandidate().getBase();
LocalCandidate validLocalCandidate
= parentAgent.findLocalCandidate(mappedAddress, base);
RemoteCandidate validRemoteCandidate = checkedPair.getRemoteCandidate(); RemoteCandidate validRemoteCandidate = checkedPair.getRemoteCandidate();
@ -609,7 +602,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());
} }
} }
@ -647,7 +640,8 @@ 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();
} }
@ -656,7 +650,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);
} }
@ -728,7 +722,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-
@ -741,12 +735,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.debug(() -> logger.fine(
"Keep alive for pair: " + validPair.toShortString()); "Keep alive for pair: " + validPair.toShortString());
} }
} }
@ -768,7 +762,7 @@ class ConnectivityCheckClient
} }
else else
{ {
logger.debug(() -> logger.fine(
"Keep alive for pair: " + validPair.toShortString()); "Keep alive for pair: " + validPair.toShortString());
} }
} }
@ -838,7 +832,7 @@ class ConnectivityCheckClient
CandidatePair pair CandidatePair pair
= (CandidatePair) ev.getTransactionID().getApplicationData(); = (CandidatePair) ev.getTransactionID().getApplicationData();
logger.trace(() -> "Received error code " + ((int) errorCode)); logger.finer("Received error code " + ((int) errorCode));
//RESOLVE ROLE_CONFLICTS //RESOLVE ROLE_CONFLICTS
if (errorCode == ErrorCodeAttribute.ROLE_CONFLICT) if (errorCode == ErrorCodeAttribute.ROLE_CONFLICT)
@ -846,7 +840,7 @@ class ConnectivityCheckClient
boolean wasControlling boolean wasControlling
= originalRequest.containsAttribute(Attribute.ICE_CONTROLLING); = originalRequest.containsAttribute(Attribute.ICE_CONTROLLING);
logger.trace(() -> "Switching to isControlling=" + !wasControlling); logger.finer("Switching to isControlling=" + !wasControlling);
parentAgent.setControlling(!wasControlling); parentAgent.setControlling(!wasControlling);
pair.getParentComponent().getParentStream().getCheckList() pair.getParentComponent().getParentStream().getCheckList()
@ -855,12 +849,10 @@ 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 + "): " + trimmedReason); "(class=" + cl + "; number=" + co + ")");
pair.setStateFailed(); pair.setStateFailed();
} }
} }
@ -958,7 +950,7 @@ class ConnectivityCheckClient
* its final state in either the processResponse(), * its final state in either the processResponse(),
* processTimeout() or processFailure() method. * processTimeout() or processFailure() method.
*/ */
logger.trace(() -> "will skip a check beat."); logger.finest("will skip a check beat.");
checkList.fireEndOfOrdinaryChecks(); checkList.fireEndOfOrdinaryChecks();
} }
} }
@ -990,9 +982,6 @@ class ConnectivityCheckClient
*/ */
public void stop() public void stop()
{ {
synchronized (paceMakers)
{
stopped = true;
while (true) while (true)
{ {
final PaceMaker paceMaker = paceMakers.poll(); final PaceMaker paceMaker = paceMakers.poll();
@ -1004,4 +993,3 @@ class ConnectivityCheckClient
} }
} }
} }
}

View File

@ -17,12 +17,14 @@
*/ */
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.jitsi.utils.logging2.*; import org.ice4j.util.Logger; // Disambiguation.
/** /**
* The class that would be handling and responding to incoming connectivity * The class that would be handling and responding to incoming connectivity
@ -35,6 +37,34 @@ 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.
*/ */
@ -71,7 +101,7 @@ class ConnectivityCheckServer
public ConnectivityCheckServer(Agent parentAgent) public ConnectivityCheckServer(Agent parentAgent)
{ {
this.parentAgent = parentAgent; this.parentAgent = parentAgent;
logger = parentAgent.getLogger().createChildLogger(this.getClass().getName()); logger = new Logger(classLogger, parentAgent.getLogger());
stunStack = this.parentAgent.getStunStack(); stunStack = this.parentAgent.getStunStack();
stunStack.getCredentialsManager().registerAuthority(this); stunStack.getCredentialsManager().registerAuthority(this);
@ -111,7 +141,8 @@ class ConnectivityCheckServer
public void processRequest(StunMessageEvent evt) public void processRequest(StunMessageEvent evt)
throws IllegalArgumentException throws IllegalArgumentException
{ {
logger.trace(() -> "Received request " + evt); if(logger.isLoggable(Level.FINER))
logger.finer("Received request " + evt);
alive = true; alive = true;
@ -181,9 +212,11 @@ class ConnectivityCheckServer
} }
catch (Exception e) catch (Exception e)
{ {
logger.info("Failed to send " + response logger.log(
+ " through " + evt.getLocalAddress() + "\n" + Level.INFO,
e.toString()); "Failed to send " + response
+ " 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);
@ -216,8 +249,11 @@ class ConnectivityCheckServer
//extract priority //extract priority
if(priorityAttr == null) if(priorityAttr == null)
{ {
logger.debug(() -> "Received a connectivity check with" if(logger.isLoggable(Level.FINE))
{
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!");
} }
@ -242,51 +278,29 @@ class ConnectivityCheckServer
*/ */
private boolean repairRoleConflict(StunMessageEvent evt) private boolean repairRoleConflict(StunMessageEvent evt)
{ {
final Message req = evt.getMessage(); Message req = evt.getMessage();
final boolean selfIceControlling = parentAgent.isControlling(); long ourTieBreaker = parentAgent.getTieBreaker();
// 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:
final boolean bothControllingConflict = selfIceControlling && if(parentAgent.isControlling()
req.containsAttribute(Attribute.ICE_CONTROLLING); && req.containsAttribute(Attribute.ICE_CONTROLLING))
// If the agent is in the controlled role, and the ICE-CONTROLLED
// attribute is present in the request:
final boolean bothControlledConflict = !selfIceControlling &&
req.containsAttribute(Attribute.ICE_CONTROLLED);
if (!(bothControllingConflict || bothControlledConflict))
{ {
// we don't have a role conflict IceControllingAttribute controlling = (IceControllingAttribute)
return true; req.getAttribute(Attribute.ICE_CONTROLLING);
}
final long selfTieBreaker = parentAgent.getTieBreaker(); long theirTieBreaker = controlling.getTieBreaker();
final IceControlAttribute theirIceControl = bothControllingConflict
? (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 // If the agent's tie-breaker is larger than or equal to the
// contents of the ICE control attribute, the agent generates // contents of the ICE-CONTROLLING attribute, the agent generates
// a Binding error response and includes an ERROR-CODE attribute // a Binding error response and includes an ERROR-CODE attribute
// with a value of 487 (Role Conflict) but retains its role. // with a value of 487 (Role Conflict) but retains its role.
if (Long.compareUnsigned(selfTieBreaker, theirTieBreaker) >= 0) if(compareUnsignedLong(ourTieBreaker, theirTieBreaker) >= 0)
{ {
final UsernameAttribute requestUserName = (UsernameAttribute)req Response response = MessageFactory.createBindingErrorResponse(
.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(
@ -294,6 +308,7 @@ class ConnectivityCheckServer
response, response,
evt.getLocalAddress(), evt.getLocalAddress(),
evt.getRemoteAddress()); evt.getRemoteAddress());
return false; return false;
} }
catch(Exception exc) catch(Exception exc)
@ -303,19 +318,68 @@ class ConnectivityCheckServer
} }
} }
//If the agent's tie-breaker is less than the contents of the //If the agent's tie-breaker is less than the contents of the
//ICE control attribute, the agent toggles its ICE control role. //ICE-CONTROLLING attribute, the agent switches to the controlled
//role.
else else
{ {
final String selfNextControlState logger.finer(
= selfIceControlling ? "controlled" : "controlling"; "Switching to controlled because theirTieBreaker="
logger.trace(() -> + theirTieBreaker + " and ourTieBreaker="
"Switching to " + selfNextControlState + " because " + + ourTieBreaker);
" theirTieBreaker= " + theirTieBreaker + " and " + parentAgent.setControlling(false);
"selfTieBreaker= " + selfTieBreaker);
parentAgent.setControlling(!selfIceControlling);
return true; return true;
} }
} }
// If the agent is in the controlled role, and the ICE-CONTROLLED
// attribute is present in the request:
else if(!parentAgent.isControlling()
&& req.containsAttribute(Attribute.ICE_CONTROLLED))
{
IceControlledAttribute controlled = (IceControlledAttribute)
req.getAttribute(Attribute.ICE_CONTROLLED);
long theirTieBreaker = controlled.getTieBreaker();
//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(
"Switching to controlling because theirTieBreaker="
+ theirTieBreaker + " and ourTieBreaker="
+ ourTieBreaker);
parentAgent.setControlling(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
// response and includes an ERROR-CODE attribute with a value of
// 487 (Role Conflict) but retains its role.
else
{
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);
}
}
}
return true; // we don't have a role conflict
}
/** /**
* Verifies whether <tt>username</tt> is currently known to this server * Verifies whether <tt>username</tt> is currently known to this server

View File

@ -17,11 +17,11 @@
*/ */
package org.ice4j.ice; package org.ice4j.ice;
import org.jitsi.utils.logging2.*;
import java.beans.*; import java.beans.*;
import java.util.*; import java.util.*;
import org.ice4j.util.*;
/** /**
* Implements ice4j internal nomination strategies. * Implements ice4j internal nomination strategies.
* *
@ -30,6 +30,15 @@ import java.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.
*/ */
@ -62,7 +71,7 @@ public class DefaultNominator
public DefaultNominator(Agent parentAgent) public DefaultNominator(Agent parentAgent)
{ {
this.parentAgent = parentAgent; this.parentAgent = parentAgent;
logger = parentAgent.getLogger().createChildLogger(this.getClass().getName()); logger = new Logger(classLogger, parentAgent.getLogger());
parentAgent.addStateChangeListener(this); parentAgent.addStateChangeListener(this);
} }
@ -98,20 +107,17 @@ 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(propertyName)) if (IceMediaStream.PROPERTY_PAIR_CONSENT_FRESHNESS_CHANGED.equals(
{ 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 nominated pair for // do not nominate pair if there is currently a selected pair for
// the component // the component
if (parentStream.validListContainsNomineeForComponent(parentComponent)) if (validPair.getParentComponent().getSelectedPair() != null)
{ {
logger.debug(() -> logger.fine(
"Keep-alive for pair: " + validPair.toShortString()); "Keep-alive for pair: " + validPair.toShortString());
return; return;
} }
@ -141,7 +147,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);
} }
} }
@ -185,18 +191,6 @@ public class DefaultNominator
} }
} }
/**
* The {@link NominationStrategy} that this nominator is using when
* deciding whether or not a valid {@link CandidatePair} is suitable for
* nomination.
*
* @return the {@link NominationStrategy} we are using.
*/
public NominationStrategy getStrategy()
{
return strategy;
}
/** /**
* The {@link NominationStrategy} that this nominator should use when * The {@link NominationStrategy} that this nominator should use when
* deciding whether or not a valid {@link CandidatePair} is suitable for * deciding whether or not a valid {@link CandidatePair} is suitable for

View File

@ -19,12 +19,9 @@ 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
@ -35,6 +32,15 @@ import static org.ice4j.ice.AgentConfig.config;
*/ */
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.
@ -129,7 +135,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 = config.getMaxCheckListSize(); private int maxCheckListSize = Agent.DEFAULT_MAX_CHECK_LIST_SIZE;
/** /**
* The user fragment that we received from the remote party. * The user fragment that we received from the remote party.
@ -144,7 +150,7 @@ public class IceMediaStream
/** /**
* The {@link Logger} used by {@link IceMediaStream} instances. * The {@link Logger} used by {@link IceMediaStream} instances.
*/ */
private Logger logger; private org.ice4j.util.Logger logger;
/** /**
* Initializes a new <tt>IceMediaStream</tt> object. * Initializes a new <tt>IceMediaStream</tt> object.
@ -155,9 +161,7 @@ public class IceMediaStream
*/ */
protected IceMediaStream(Agent parentAgent, String name) protected IceMediaStream(Agent parentAgent, String name)
{ {
logger = parentAgent.getLogger().createChildLogger( logger = new org.ice4j.util.Logger(classLogger, parentAgent.getLogger());
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);
@ -172,7 +176,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 AgentConfig#getUseComponentSocket()}. * or not. See {@link StackProperties#USE_COMPONENT_SOCKET}.
* *
* @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.
@ -190,8 +194,7 @@ public class IceMediaStream
++lastComponentID, ++lastComponentID,
this, this,
keepAliveStrategy, keepAliveStrategy,
useComponentSocket, useComponentSocket);
logger);
components.put(component.getComponentID(), component); components.put(component.getComponentID(), component);
} }
@ -364,7 +367,7 @@ public class IceMediaStream
orderCheckList(); orderCheckList();
pruneCheckList(checkList); pruneCheckList(checkList);
logger.trace(() -> "Checklist initialized."); logger.finest("Checklist initialized.");
} }
} }
@ -511,28 +514,23 @@ public class IceMediaStream
/** /**
* Returns the local <tt>LocalCandidate</tt> with the specified * Returns the local <tt>LocalCandidate</tt> with the specified
* <tt>address</tt> if it belongs to any of this stream's components * <tt>localAddress</tt> if it belongs to any of this stream's components
* or <tt>null</tt> otherwise. If {@code base} is also specified, tries to * or <tt>null</tt> otherwise.
* find a candidate whose base matches {@code base}.
* *
* @param address the {@link TransportAddress} we are looking for. * @param localAddress 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>address</tt> if it belongs to any of this stream's components * <tt>localAddress</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 address, LocalCandidate base) public LocalCandidate findLocalCandidate(TransportAddress localAddress)
{ {
for (Component component : components.values()) for( Component cmp : components.values())
{ {
LocalCandidate localCandidate LocalCandidate cnd = cmp.findLocalCandidate(localAddress);
= component.findLocalCandidate(address, base);
if (localCandidate != null) if(cnd != null)
{ return cnd;
return localCandidate;
}
} }
return null; return null;
@ -923,9 +921,4 @@ public class IceMediaStream
{ {
return remotePassword; return remotePassword;
} }
public Logger getLogger()
{
return logger;
}
} }

View File

@ -19,11 +19,12 @@ 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.jitsi.utils.logging2.*; import org.ice4j.util.Logger; // Disambiguation.
/** /**
* <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
@ -65,7 +66,7 @@ public abstract class LocalCandidate
/** /**
* The {@link Logger} used by {@link LocalCandidate} instances. * The {@link Logger} used by {@link LocalCandidate} instances.
*/ */
private final Logger logger; private Logger logger;
/** /**
* Creates a <tt>LocalCandidate</tt> instance for the specified transport * Creates a <tt>LocalCandidate</tt> instance for the specified transport
@ -90,10 +91,12 @@ 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 = parentComponent.getLogger().createChildLogger(this.getClass().getName()); logger
= new Logger(classLogger,
parentComponent.
getParentStream().getParentAgent().getLogger());
this.extendedType = extendedType; this.extendedType = extendedType;
} }
@ -202,7 +205,8 @@ 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.error("Failed to acquire Socket" logger.log(Level.SEVERE,
"Failed to acquire Socket"
+ " specific to STUN communication.", + " specific to STUN communication.",
sex); sex);
exception = sex; exception = sex;
@ -258,7 +262,8 @@ 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.error("Failed to acquire DatagramSocket" logger.log(Level.SEVERE,
"Failed to acquire DatagramSocket"
+ " specific to STUN communication.", + " specific to STUN communication.",
sex); sex);
exception = sex; exception = sex;

View File

@ -44,11 +44,8 @@ public enum NominationStrategy
NOMINATE_FIRST_VALID("NominateFirstValid"), NOMINATE_FIRST_VALID("NominateFirstValid"),
/** /**
* The strategy consists in nominating the highest priority valid pair. * The strategy consists in nominating the highest priority valid pair once
* Once a pair is validated, if no higher-priority pairs remain outstanding, * all checks in a list have completed.
* 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"),
@ -93,19 +90,4 @@ public enum NominationStrategy
{ {
return strategyName; return strategyName;
} }
/**
* @return the {@link NominationStrategy} with name equal to the given
* string, or {@code null} if there is no such strategy.
* @param string the name of the strategy.
*/
public static NominationStrategy fromString(String string)
{
for (NominationStrategy strategy : NominationStrategy.values())
{
if (strategy.strategyName.equals(string))
return strategy;
}
return null;
}
} }

View File

@ -19,6 +19,7 @@ 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.*;
@ -28,8 +29,6 @@ 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
@ -60,15 +59,7 @@ public abstract class AbstractTcpListener
*/ */
static void closeNoExceptions(Channel channel) static void closeNoExceptions(Channel channel)
{ {
try MuxServerSocketChannelFactory.closeNoExceptions(channel);
{
channel.close();
}
catch (IOException ioe)
{
// The whole idea of the method is to close a specific Channel
// without caring about any possible IOException.
}
} }
/** /**
@ -82,6 +73,7 @@ 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<>();
@ -107,6 +99,83 @@ 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}.
@ -147,6 +216,12 @@ 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
@ -208,6 +283,13 @@ public abstract class AbstractTcpListener
protected void addLocalAddresses(List<TransportAddress> transportAddresses) protected void addLocalAddresses(List<TransportAddress> transportAddresses)
throws IOException throws IOException
{ {
boolean useIPv6 = !StackProperties.getBoolean(
StackProperties.DISABLE_IPv6,
false);
boolean useLinkLocalAddresses = !StackProperties.getBoolean(
StackProperties.DISABLE_LINK_LOCAL_ADDRESSES,
false);
// White list from the configuration // White list from the configuration
String[] allowedAddressesStr String[] allowedAddressesStr
= StackProperties.getStringArray(StackProperties.ALLOWED_ADDRESSES, = StackProperties.getStringArray(StackProperties.ALLOWED_ADDRESSES,
@ -219,7 +301,8 @@ 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] = InetAddress.getByName(allowedAddressesStr[i]); allowedAddresses[i]
= InetAddress.getByName(allowedAddressesStr[i]);
} }
} }
@ -249,12 +332,14 @@ public abstract class AbstractTcpListener
continue; continue;
} }
if (!config.useIpv6() && (address instanceof Inet6Address)) if (!useIPv6 && (address instanceof Inet6Address))
continue; continue;
if (!config.useLinkLocalAddresses() && address.isLinkLocalAddress()) if (!useLinkLocalAddresses
&& address.isLinkLocalAddress())
{ {
logger.info("Not using link-local address " + address +" for TCP candidates."); logger.info("Not using link-local address " + address +" for"
+ " TCP candidates.");
continue; continue;
} }
@ -355,7 +440,21 @@ public abstract class AbstractTcpListener
throws IOException throws IOException
{ {
ServerSocketChannel channel = MuxServerSocketChannelFactory ServerSocketChannel channel = MuxServerSocketChannelFactory
.openAndBindServerSocketChannel(null, address, 0); .openAndBindMuxServerSocketChannel(
/* properties */ null,
address,
/* backlog */ 0,
new DatagramPacketFilter()
{
/**
* {@inheritDoc}
*/
@Override
public boolean accept(DatagramPacket p)
{
return isFirstDatagramPacket(p);
}
});
serverSocketChannels.add(channel); serverSocketChannels.add(channel);
} }
@ -366,6 +465,8 @@ 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)
@ -505,9 +606,7 @@ public abstract class AbstractTcpListener
selector.close(); selector.close();
} }
catch (IOException ioe) catch (IOException ioe)
{ {}
// ignore
}
} }
} }
@ -522,6 +621,11 @@ 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.
*/ */
@ -687,8 +791,11 @@ 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);
@ -722,6 +829,50 @@ 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
@ -772,6 +923,8 @@ 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())
{ {
@ -957,6 +1110,9 @@ public abstract class AbstractTcpListener
break; break;
} }
// clean up stale channels
cleanup();
checkForNewChannels(); checkForNewChannels();
for (SelectionKey key : readSelector.keys()) for (SelectionKey key : readSelector.keys())
@ -1016,9 +1172,7 @@ public abstract class AbstractTcpListener
readSelector.close(); readSelector.close();
} }
catch (IOException ioe) catch (IOException ioe)
{ {}
// ignore
}
} }
} }
} }

View File

@ -20,18 +20,15 @@ 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.jitsi.utils.queue.*; import org.jitsi.javautils.*;
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.
@ -46,6 +43,14 @@ import static org.ice4j.ice.harvest.HarvestConfig.config;
*/ */
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.
*/ */
@ -126,7 +131,10 @@ public abstract class AbstractUdpListener
try try
{ {
Message stunMessage = Message.decode(buf, off, len); Message stunMessage
= Message.decode(buf,
(char) off,
(char) len);
if (stunMessage.getMessageType() if (stunMessage.getMessageType()
!= Message.BINDING_REQUEST) != Message.BINDING_REQUEST)
@ -196,51 +204,41 @@ 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. If the port is 0 an ephemeral port will be chosen by the OS and the * @param localAddress the address to bind to.
* 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)
{ {
tempAddress = new TransportAddress( this.localAddress = new TransportAddress(
(InetAddress) null, (InetAddress) null,
localAddress.getPort(), localAddress.getPort(),
localAddress.getTransport() localAddress.getTransport()
); );
} }
else
{
this.localAddress = localAddress;
}
socket = new DatagramSocket( tempAddress ); socket = new DatagramSocket( this.localAddress );
Integer receiveBufferSize = config.udpReceiveBufferSize(); int receiveBufferSize = StackProperties.getInt(SO_RCVBUF_PNAME, -1);
if (receiveBufferSize != null) if (receiveBufferSize > 0)
{ {
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 != null) if (receiveBufferSize > 0)
{ {
logMessage += " (asked for " + receiveBufferSize + ")"; logMessage += " (asked for " + receiveBufferSize + ")";
} }
@ -255,16 +253,12 @@ public abstract class AbstractUdpListener
} }
}; };
thread.setName(AbstractUdpListener.class.getName() + " thread for " + this.localAddress); thread.setName(AbstractUdpListener.class.getName() + " thread for "
+ 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.
*/ */
@ -397,13 +391,12 @@ 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, String ufrag) protected MySocket addSocket(InetSocketAddress remoteAddress)
throws SocketException throws SocketException
{ {
MySocket newSocket = new MySocket(remoteAddress, ufrag); MySocket newSocket = new MySocket(remoteAddress);
sockets.put(remoteAddress, newSocket); sockets.put(remoteAddress, newSocket);
return newSocket; return newSocket;
} }
@ -447,8 +440,6 @@ 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.
@ -456,17 +447,17 @@ public abstract class AbstractUdpListener
* new instance. * new instance.
* @throws SocketException * @throws SocketException
*/ */
MySocket(InetSocketAddress remoteAddress, String ufrag) MySocket(InetSocketAddress remoteAddress)
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(QUEUE_SIZE, Clock.systemUTC()); queueStatistics = new QueueStatistics(
"SinglePort" + remoteAddress.toString().replace('/', '-'));
} }
else else
{ {
@ -486,12 +477,10 @@ 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( logger.info("Dropping a packet because the queue is full.");
"Dropping a packet because the queue is full. Remote address = "
+ remoteAddress + " ufrag=" + ufrag);
if (queueStatistics != null) if (queueStatistics != null)
{ {
queueStatistics.dropped(); queueStatistics.remove(System.currentTimeMillis());
} }
queue.poll(); queue.poll();
} }
@ -499,7 +488,7 @@ public abstract class AbstractUdpListener
queue.offer(buf); queue.offer(buf);
if (queueStatistics != null) if (queueStatistics != null)
{ {
queueStatistics.added(); queueStatistics.add(System.currentTimeMillis());
} }
queue.notify(); queue.notify();
@ -637,9 +626,9 @@ public abstract class AbstractUdpListener
} }
buf = queue.poll(); buf = queue.poll();
if (buf != null && queueStatistics != null) if (queueStatistics != null)
{ {
queueStatistics.removed(queue.size(), null); queueStatistics.remove(System.currentTimeMillis());
} }
} }
} }

View File

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

View File

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

View File

@ -26,8 +26,6 @@ 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
@ -231,6 +229,13 @@ public class HostCandidateHarvester
public static List<InetAddress> getAllAllowedAddresses() public static List<InetAddress> getAllAllowedAddresses()
{ {
List<InetAddress> addresses = new LinkedList<>(); List<InetAddress> addresses = new LinkedList<>();
boolean isIPv6Disabled = StackProperties.getBoolean(
StackProperties.DISABLE_IPv6,
false);
boolean isLinkLocalAddressesDisabled = StackProperties.getBoolean(
StackProperties.DISABLE_LINK_LOCAL_ADDRESSES,
false);
try try
{ {
for (NetworkInterface iface for (NetworkInterface iface
@ -252,9 +257,10 @@ public class HostCandidateHarvester
if (!isAddressAllowed(address)) if (!isAddressAllowed(address))
continue; continue;
if (!config.useIpv6() && address instanceof Inet6Address) if (isIPv6Disabled && address instanceof Inet6Address)
continue; continue;
if (!config.useLinkLocalAddresses() && address.isLinkLocalAddress()) if (isLinkLocalAddressesDisabled
&& address.isLinkLocalAddress())
continue; continue;
addresses.add(address); addresses.add(address);
@ -276,8 +282,6 @@ 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
@ -304,11 +308,21 @@ public class HostCandidateHarvester
{ {
harvestStatistics.startHarvestTiming(); harvestStatistics.startHarvestTiming();
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); Enumeration<NetworkInterface> interfaces
= NetworkInterface.getNetworkInterfaces();
boolean isIPv6Disabled = StackProperties.getBoolean(
StackProperties.DISABLE_IPv6,
false);
boolean isLinkLocalAddressesDisabled = 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("Transport protocol not supported: " + transport); throw new IllegalArgumentException(
"Transport protocol not supported: " + transport);
} }
boolean boundAtLeastOneSocket = false; boolean boundAtLeastOneSocket = false;
@ -338,20 +352,22 @@ public class HostCandidateHarvester
continue; continue;
} }
if (!config.useLinkLocalAddresses() && addr.isLinkLocalAddress()) if (isLinkLocalAddressesDisabled
&& addr.isLinkLocalAddress())
{ {
continue; continue;
} }
foundAtLeastOneUsableAddress = true; foundAtLeastOneUsableAddress = true;
if ((addr instanceof Inet4Address) || config.useIpv6()) if((addr instanceof Inet4Address) || !isIPv6Disabled)
{ {
IceSocketWrapper sock = null; IceSocketWrapper sock = null;
try try
{ {
if(transport == Transport.UDP) if(transport == Transport.UDP)
{ {
sock = createDatagramSocket(addr, preferredPort, minPort, maxPort); sock = createDatagramSocket(
addr, preferredPort, minPort, maxPort);
boundAtLeastOneSocket = true; boundAtLeastOneSocket = true;
} }
else if(transport == Transport.TCP) else if(transport == Transport.TCP)
@ -386,8 +402,10 @@ public class HostCandidateHarvester
continue; continue;
} }
HostCandidate candidate = new HostCandidate(sock, component, transport); HostCandidate candidate
candidate.setVirtual(NetworkUtils.isInterfaceVirtual(iface)); = new HostCandidate(sock, component, transport);
candidate.setVirtual(
NetworkUtils.isInterfaceVirtual(iface));
component.addLocalCandidate(candidate); component.addLocalCandidate(candidate);
if (transport == Transport.TCP) if (transport == Transport.TCP)
@ -403,7 +421,8 @@ public class HostCandidateHarvester
// them as well while harvesting reflexive candidates. // them as well while harvesting reflexive candidates.
createAndRegisterStunSocket(candidate); createAndRegisterStunSocket(candidate);
ComponentSocket componentSocket = component.getComponentSocket(); ComponentSocket componentSocket
= component.getComponentSocket();
if (componentSocket != null) if (componentSocket != null)
{ {
componentSocket.add(sock); componentSocket.add(sock);
@ -426,7 +445,8 @@ public class HostCandidateHarvester
+ foundAtLeastOneUsableAddress); + foundAtLeastOneUsableAddress);
} }
this.harvestStatistics.stopHarvestTiming(component.getLocalCandidateCount()); this.harvestStatistics
.stopHarvestTiming(component.getLocalCandidateCount());
} }
/** /**
@ -441,7 +461,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.
*/ */
public static boolean isInterfaceAllowed(NetworkInterface iface) 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");
@ -521,8 +541,6 @@ 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
@ -549,18 +567,7 @@ public class HostCandidateHarvester
BindException BindException
{ {
// make sure port numbers are valid // make sure port numbers are valid
boolean ephemeral = checkPorts(preferredPort, minPort, maxPort); this.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,
@ -604,7 +611,8 @@ public class HostCandidateHarvester
port = minPort; port = minPort;
} }
throw new BindException("Could not bind to any port between " + minPort + " and " + (port - 1)); throw new BindException("Could not bind to any port between "
+ minPort + " and " + (port - 1));
} }
/** /**
@ -619,8 +627,6 @@ 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
@ -648,16 +654,7 @@ public class HostCandidateHarvester
BindException BindException
{ {
// make sure port numbers are valid. // make sure port numbers are valid.
boolean ephemeral = checkPorts(preferredPort, minPort, maxPort); this.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,
@ -719,10 +716,8 @@ public class HostCandidateHarvester
} }
/** /**
* Checks if the different ports are correctly set. If not, throws {@link IllegalArgumentException}. The * Checks if the different ports are correctly set. If not, throws an
* special values 0, 0, 0 for the parameters are interpreted as "use an ephemeral port". * IllegalArgumentException.
*
* @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
@ -734,14 +729,9 @@ 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 static boolean checkPorts(int preferredPort, int minPort, int maxPort) private void 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))
@ -766,8 +756,6 @@ public class HostCandidateHarvester
+") must be between minPort (" + minPort +") must be between minPort (" + minPort
+ ") and maxPort (" + maxPort + ")"); + ") and maxPort (" + maxPort + ")");
} }
return false;
} }
/** /**

View File

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

View File

@ -16,16 +16,12 @@
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.
@ -41,7 +37,44 @@ 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 = Logger.getLogger(MappingCandidateHarvesters.class.getName()); private static final Logger logger
= 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.
@ -51,8 +84,7 @@ 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.
@ -72,21 +104,6 @@ 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,
@ -106,48 +123,64 @@ 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())
{
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
= new TransportAddress(staticMapping.getLocalAddress(), localPort, Transport.UDP);
TransportAddress publicAddress
= new TransportAddress(staticMapping.getPublicAddress(), publicPort, Transport.UDP);
harvesterList.add(new StaticMappingCandidateHarvester( // Pre-configured NAT harvester.
publicAddress, String localAddressStr
localAddress, = StackProperties.getString(NAT_HARVESTER_LOCAL_ADDRESS_PNAME);
staticMapping.getName(), String publicAddressStr
staticMapping.getLocalPort() != null)); = StackProperties.getString(NAT_HARVESTER_PUBLIC_ADDRESS_PNAME);
if (localAddressStr != null && publicAddressStr != null)
{
// the port number is unused, 9 is for "discard"
TransportAddress localAddress
= new TransportAddress(localAddressStr, 9, Transport.UDP);
TransportAddress publicAddress
= new TransportAddress(publicAddressStr, 9, Transport.UDP);
harvesterList.add(
new MappingCandidateHarvester(publicAddress, localAddress));
} }
// AWS harvester // AWS harvester
boolean enableAwsHarvester = config.enableAwsHarvester(); boolean disableAwsHarvester
if (enableAwsHarvester && (config.forceAwsHarvester() || AwsCandidateHarvester.smellsLikeAnEC2())) = StackProperties.getBoolean(DISABLE_AWS_HARVESTER_PNAME, false);
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
List<String> stunServers = config.stunMappingCandidateHarvesterAddresses(); String stunServers
if (!stunServers.isEmpty()) = StackProperties.getString(STUN_MAPPING_HARVESTER_ADDRESSES_PNAME);
if (stunServers != null && !stunServers.isEmpty())
{ {
// Create STUN harvesters (and wait for all of their discovery to finish). // Create STUN harvesters (and wait for all of their discovery to
List<StunMappingCandidateHarvester> stunHarvesters = createStunHarvesters(stunServers); // finish).
List<StunMappingCandidateHarvester> stunHarvesters
= createStunHarvesters(stunServers.split(","));
// We have STUN servers configured, so flag failure if none of them were able to discover an address. // We have STUN servers configured, so flag the failure if none of
// 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 = harvesterList.toArray(new MappingCandidateHarvester[harvesterList.size()]); harvesters
= harvesterList.toArray(
new MappingCandidateHarvester[harvesterList.size()]);
for (MappingCandidateHarvester harvester : harvesters) for (MappingCandidateHarvester harvester : harvesters)
{ {
@ -196,10 +229,10 @@ public class MappingCandidateHarvesters
for (MappingCandidateHarvester h : harvesters) for (MappingCandidateHarvester h : harvesters)
{ {
if (face.getAddress().equals(h.getFace().getAddress()) if (face.getAddress().equals(h.getFace().getAddress()) && mask.getAddress().equals(h.getMask().getAddress()))
&& mask.getAddress().equals(h.getMask().getAddress()))
{ {
logger.info("Discarding a mapping harvester with duplicate addresses: " + harvester + ". Kept: " + h); logger.info("Discarding a mapping harvester with duplicate "
+ "addresses: " + harvester + ". Kept: " + h);
return; return;
} }
} }
@ -214,20 +247,30 @@ 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(@NotNull List<String> stunServers) private static List<StunMappingCandidateHarvester> createStunHarvesters(
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 pair. // Create a StunMappingCandidateHarvester for each local:remote address
List<InetAddress> localAddresses = HostCandidateHarvester.getAllAllowedAddresses(); // pair.
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: " + stunServer); logger.severe("Failed to parse STUN server address: "
+ stunServer);
continue; continue;
} }
int port; int port;
@ -256,34 +299,33 @@ public class MappingCandidateHarvesters
continue; continue;
} }
TransportAddress localAddress = new TransportAddress(localInetAddress, 0, Transport.UDP); TransportAddress localAddress
= new TransportAddress(localInetAddress, 0, Transport.UDP);
logger.info("Using " + remoteAddress + " for StunMappingCandidateHarvester (localAddress="
+ localAddress + ").");
final StunMappingCandidateHarvester stunHarvester final StunMappingCandidateHarvester stunHarvester
= new StunMappingCandidateHarvester(localAddress, remoteAddress); = new StunMappingCandidateHarvester(
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);
} }
} }
if (tasks.isEmpty()) // Now run discover() on all created harvesters in parallel and pick
{ // the ones which succeeded.
logger.warning("STUN mapping harvesters are configured, but no allowed local addresses were found." + ExecutorService es = Executors.newFixedThreadPool(tasks.size());
" 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
{ {
@ -317,11 +359,7 @@ public class MappingCandidateHarvesters
throw new RuntimeException(ie); throw new RuntimeException(ie);
} }
} }
}
finally
{
es.shutdown();
}
return stunHarvesters; return stunHarvesters;
} }

View File

@ -101,8 +101,7 @@ 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. If the port is 0 an ephemeral port is chosen by the OS and the * @param localAddress the address to bind to.
* 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)
@ -110,7 +109,7 @@ public class SinglePortUdpHarvester
{ {
super(localAddress); super(localAddress);
logger.info("Initialized SinglePortUdpHarvester with address " logger.info("Initialized SinglePortUdpHarvester with address "
+ this.localAddress); + localAddress);
} }
/** /**
@ -146,7 +145,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, ufrag); MySocket newSocket = addSocket(remoteAddress);
// 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.
@ -379,6 +378,7 @@ public class SinglePortUdpHarvester
componentSocket.add(multiplexing); componentSocket.add(multiplexing);
} }
// XXX is this necessary?
synchronized (candidateSockets) synchronized (candidateSockets)
{ {
IceSocketWrapper oldSocket IceSocketWrapper oldSocket
@ -403,11 +403,9 @@ 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);
} }
}
} }
} }

View File

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

View File

@ -22,7 +22,6 @@ 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.*;
/** /**
@ -470,7 +469,6 @@ 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.
@ -511,7 +509,6 @@ 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.
@ -1021,7 +1018,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 = AgentConfig.config.getSoftware(); String software = System.getProperty(StackProperties.SOFTWARE);
if (getAttribute(Attribute.SOFTWARE) == null if (getAttribute(Attribute.SOFTWARE) == null
&& software != null && software.length() > 0) && software != null && software.length() > 0)
@ -1060,11 +1057,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, int offset, int arrayLen) public static Message decode(byte binMessage[], char offset, char arrayLen)
throws StunException throws StunException
{ {
int originalOffset = offset; int originalOffset = offset;
arrayLen = Math.min(binMessage.length, arrayLen); arrayLen = (char)Math.min(binMessage.length, arrayLen);
if(arrayLen - offset < Message.HEADER_LENGTH) if(arrayLen - offset < Message.HEADER_LENGTH)
{ {
@ -1091,7 +1088,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;
@ -1109,20 +1106,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 "
+ arrayLen + ((int) 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);

View File

@ -54,8 +54,7 @@ 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);
@ -123,8 +122,7 @@ 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);
@ -358,8 +356,7 @@ 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);
@ -672,8 +669,7 @@ 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);
} }
@ -953,8 +949,7 @@ 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);
} }

View File

@ -387,11 +387,12 @@ 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.nanoTime() / 1000000) & 0xFFFFFFFFL; return System.currentTimeMillis() & 0xFFFFFFFFL;
} }
/** /**
@ -444,8 +445,7 @@ 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) //Logger.Log(LS_INFO) << "m_ssthresh: " << m_ssthresh << " nInFlight: " << nInFlight << " m_mss: " << m_mss;
// << "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,8 +1252,7 @@ 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) //Logger.Log(LS_INFO) << "m_ssthresh: " << m_ssthresh << " nInFlight: " << nInFlight << " m_mss: " << m_mss;
// << "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
@ -1959,7 +1958,7 @@ public class PseudoTCPBase
options_specified.add(kind); options_specified.add(kind);
} }
if (!options_specified.contains(TCP_OPT_WND_SCALE)) if (options_specified.indexOf(TCP_OPT_WND_SCALE) == -1)//options_specified.size() - 1)
{ {
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)

View File

@ -245,7 +245,6 @@ public class PseudoTcpSocket extends Socket
/** /**
* {@inheritDoc} * {@inheritDoc}
*/ */
@Override
public synchronized void close() public synchronized void close()
throws IOException throws IOException
{ {
@ -257,12 +256,6 @@ public class PseudoTcpSocket extends Socket
} }
} }
@Override
public OutputStream getOutputStream() throws IOException
{
return socketImpl.getOutputStream();
}
/** /**
* Allows to set up the remote address directly. * Allows to set up the remote address directly.
* Otherwise, when using the other <tt>accept</tt> methods, * Otherwise, when using the other <tt>accept</tt> methods,

View File

@ -78,8 +78,15 @@ class PseudoTcpSocketImpl
*/ */
private long readTimeout; private long readTimeout;
/**
*
*/
private PseudoTcpInputStream inputStream; private PseudoTcpInputStream inputStream;
/**
*
*/
private PseudoTcpOutputStream outputstream; private PseudoTcpOutputStream outputstream;
/** /**
@ -189,7 +196,6 @@ 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
{ {
@ -202,7 +208,6 @@ 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
{ {
@ -215,7 +220,6 @@ 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
{ {
@ -230,7 +234,6 @@ 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
{ {
@ -244,7 +247,6 @@ 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
{ {
@ -262,7 +264,6 @@ 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
{ {
@ -270,7 +271,6 @@ 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,7 +278,6 @@ 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
{ {
@ -335,6 +334,7 @@ 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,9 +355,10 @@ class PseudoTcpSocketImpl
while (pseudoTcp.getState() != PseudoTcpState.TCP_ESTABLISHED while (pseudoTcp.getState() != PseudoTcpState.TCP_ESTABLISHED
&& (noTimeout || (elapsed < timeout)) ) && (noTimeout || (elapsed < timeout)) )
{ {
long start = System.nanoTime(); long start = System.currentTimeMillis();
state_notify.wait(timeout); state_notify.wait(timeout);
elapsed += TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start); long end = System.currentTimeMillis();
elapsed += end - start;
} }
if (pseudoTcp.getState() != PseudoTcpState.TCP_ESTABLISHED) if (pseudoTcp.getState() != PseudoTcpState.TCP_ESTABLISHED)
{ {
@ -430,7 +431,6 @@ 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,7 +464,6 @@ 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();
@ -484,7 +483,6 @@ 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");
@ -503,7 +501,6 @@ 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))
@ -525,7 +522,6 @@ 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)
{ {
@ -549,7 +545,6 @@ 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)
@ -611,7 +606,6 @@ 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))
@ -745,7 +739,13 @@ class PseudoTcpSocketImpl
} }
} }
private final Runnable clockTaskRunner = this::runClock; private Runnable clockTaskRunner = new Runnable()
{
@Override
public void run() {
runClock();
}
};
private void scheduleClockTask(long sleep) private void scheduleClockTask(long sleep)
{ {
@ -777,7 +777,6 @@ 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
{ {
@ -794,7 +793,6 @@ 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
{ {
@ -810,7 +808,6 @@ 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
{ {
@ -819,16 +816,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();
@ -854,7 +851,6 @@ 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
{ {
@ -912,7 +908,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.nanoTime(); long start = System.currentTimeMillis();
int read; int read;
while (true) while (true)
{ {
@ -933,7 +929,7 @@ class PseudoTcpSocketImpl
if(readTimeout > 0) if(readTimeout > 0)
{ {
//Check for timeout //Check for timeout
long elapsed = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start); long elapsed = System.currentTimeMillis() - start;
long left = readTimeout - elapsed; long left = readTimeout - elapsed;
if(left <= 0) if(left <= 0)
{ {
@ -1037,6 +1033,12 @@ 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.
* *
@ -1051,7 +1053,7 @@ class PseudoTcpSocketImpl
{ {
int toSend = length; int toSend = length;
int sent; int sent;
long start = System.nanoTime(); long start = System.currentTimeMillis();
while (toSend > 0) while (toSend > 0)
{ {
synchronized (pseudoTcp) synchronized (pseudoTcp)
@ -1071,7 +1073,7 @@ class PseudoTcpSocketImpl
{ {
if(writeTimeout > 0) if(writeTimeout > 0)
{ {
long elapsed = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start); long elapsed = System.currentTimeMillis() - start;
long left = writeTimeout - elapsed; long left = writeTimeout - elapsed;
if(left <= 0) if(left <= 0)
{ {
@ -1119,7 +1121,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.nanoTime(); long start = System.currentTimeMillis();
final Object ackNotify = pseudoTcp.getAckNotify(); final Object ackNotify = pseudoTcp.getAckNotify();
synchronized (ackNotify) synchronized (ackNotify)
{ {
@ -1130,7 +1132,7 @@ class PseudoTcpSocketImpl
if(writeTimeout > 0) if(writeTimeout > 0)
{ {
//Check write timeout //Check write timeout
long elapsed = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start); long elapsed = System.currentTimeMillis() - start;
long left = writeTimeout - elapsed; long left = writeTimeout - elapsed;
if(left <= 0) if(left <= 0)
{ {
@ -1158,7 +1160,6 @@ class PseudoTcpSocketImpl
@Override @Override
public void close() throws IOException public void close() throws IOException
{ {
PseudoTcpSocketImpl.this.close();
} }
} }

View File

@ -755,9 +755,8 @@ 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);
} }
} }

View File

@ -18,12 +18,13 @@
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.
@ -43,6 +44,14 @@ import java.util.concurrent.*;
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}.
*/ */
@ -88,7 +97,7 @@ public class MergingDatagramSocket
/** /**
* The {@link Logger} used by {@link MergingDatagramSocket} instances. * The {@link Logger} used by {@link MergingDatagramSocket} instances.
*/ */
protected final Logger logger; private final Logger logger;
/** /**
* Initializes a new {@link MergingDatagramSocket} instance. * Initializes a new {@link MergingDatagramSocket} instance.
@ -102,14 +111,14 @@ public class MergingDatagramSocket
/** /**
* Initializes a new {@link MergingDatagramSocket} instance. * Initializes a new {@link MergingDatagramSocket} instance.
* @param parentLogger the {@link Logger} parent logger from which we'll * @param levelDelegate the {@link Logger} instance which dictates the
* derive this class' logger instance * logging level for the new {@link MergingDatagramSocket} instance.
* @throws SocketException * @throws SocketException
*/ */
public MergingDatagramSocket(Logger parentLogger) public MergingDatagramSocket(Logger levelDelegate)
throws SocketException throws SocketException
{ {
logger = parentLogger.createChildLogger(this.getClass().getName()); logger = new Logger(classLogger, levelDelegate);
} }
/** /**
@ -211,8 +220,11 @@ public class MergingDatagramSocket
public void add(DelegatingSocket socket) public void add(DelegatingSocket socket)
{ {
Objects.requireNonNull(socket, "socket"); Objects.requireNonNull(socket, "socket");
logger.debug(() -> "Adding a DelegatingSocket instance: " if (logger.isLoggable(Level.FINE))
{
logger.fine("Adding a DelegatingSocket instance: "
+ socket.getLocalAddress()); + socket.getLocalAddress());
}
doAdd(socket); doAdd(socket);
} }
@ -239,8 +251,11 @@ public class MergingDatagramSocket
public void add(DatagramSocket socket) public void add(DatagramSocket socket)
{ {
Objects.requireNonNull(socket, "socket"); Objects.requireNonNull(socket, "socket");
logger.debug(() -> "Adding a DatagramSocket instance: " if (logger.isLoggable(Level.FINE))
{
logger.fine("Adding a DatagramSocket instance: "
+ socket.getLocalAddress()); + socket.getLocalAddress());
}
doAdd(socket); doAdd(socket);
} }
@ -265,7 +280,7 @@ public class MergingDatagramSocket
{ {
if (indexOf(socketContainers, socket) != -1) if (indexOf(socketContainers, socket) != -1)
{ {
logger.warn("Socket already added."); logger.warning("Socket already added.");
return; return;
} }
@ -346,7 +361,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.warn( logger.warning(
"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;
@ -354,13 +369,13 @@ public class MergingDatagramSocket
} }
else else
{ {
logger.error("Cannot find socket to remove."); logger.severe("Cannot find socket to remove.");
} }
} }
if (logger.isDebugEnabled()) if (logger.isLoggable(Level.FINE))
{ {
logger.debug("Removed: " + socketContainer); logger.fine("Removed: " + socketContainer);
} }
if (socketContainer != null) if (socketContainer != null)
{ {
@ -580,9 +595,9 @@ public class MergingDatagramSocket
socket = socketWrapper.getUDPSocket(); socket = socketWrapper.getUDPSocket();
} }
if (logger.isDebugEnabled()) if (logger.isLoggable(Level.FINE))
{ {
logger.debug("Initializing the active container, socket=" + socket logger.fine("Initializing the active container, socket=" + socket
+ "; remote address=" + remoteAddress); + "; remote address=" + remoteAddress);
} }
@ -596,7 +611,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.warn("Active socket already initialized."); logger.warning("Active socket already initialized.");
} }
SocketContainer newActive = null; SocketContainer newActive = null;
@ -612,7 +627,7 @@ public class MergingDatagramSocket
if (newActive == null) if (newActive == null)
{ {
logger.error("No SocketContainer found!"); logger.severe("No SocketContainer found!");
return; return;
} }
@ -727,9 +742,12 @@ public class MergingDatagramSocket
+ getLocalSocketAddress() + " -> " + getLocalSocketAddress() + " -> "
+ getRemoteSocketAddress()); + getRemoteSocketAddress());
logger.debug(() -> "Starting the thread for socket " if (logger.isLoggable(Level.FINE))
{
logger.fine("Starting the thread for socket "
+ getLocalSocketAddress() + " -> " + getLocalSocketAddress() + " -> "
+ getRemoteSocketAddress()); + getRemoteSocketAddress());
}
thread.start(); thread.start();
} }
@ -792,7 +810,10 @@ public class MergingDatagramSocket
// container anymore. // container anymore.
close(true); close(true);
logger.debug(() -> "Finished: " + toString()); if (logger.isLoggable(Level.FINE))
{
logger.fine("Finished: " + toString());
}
} }
/** /**
@ -853,7 +874,11 @@ public class MergingDatagramSocket
synchronized (socketContainersSyncRoot) synchronized (socketContainersSyncRoot)
{ {
MergingDatagramSocket.this.active = this; MergingDatagramSocket.this.active = this;
logger.debug(() -> "Switching to new active socket: " + this); if (logger.isLoggable(Level.FINE))
{
logger.fine("Switching to new active socket: "
+ this);
}
} }
} }
} }

View File

@ -18,9 +18,11 @@
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
@ -31,6 +33,19 @@ import java.util.*;
*/ */
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
@ -41,12 +56,158 @@ 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 #openAndBindServerSocketChannel(Map, SocketAddress, int)} which * {@link #openAndBindMuxServerSocketChannel(Map, SocketAddress, int,
* specifies the value of the {@code SO_REUSEADDR} socket option. * DatagramPacketFilter)} which specifies the value of the
* {@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.
* *
@ -90,7 +251,7 @@ public class MuxServerSocketChannelFactory
else if (value instanceof Boolean) else if (value instanceof Boolean)
on = (Boolean) value; on = (Boolean) value;
else else
on = Boolean.parseBoolean(value.toString()); on = Boolean.valueOf(value.toString());
socket.setReuseAddress(on); socket.setReuseAddress(on);
} }

View File

@ -0,0 +1,79 @@
/*
* ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
*
* Copyright @ 2015 Atlassian Pty Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.ice4j.socket.jdk8;
import java.net.*;
import java.nio.*;
/**
* Associates a {@link ByteBuffer} with a {@link DatagramPacket} so that the
* {@code ByteBuffer} may be used for writing into a {@code byte} array and the
* {@code DatagramPacket} may be used for reading from the same {@code byte}
* array.
*
* @author Lyubomir Marinov
*/
class DatagramBuffer
extends Timestamped<ByteBuffer>
{
/**
* The {@code DatagramPacket} which is associated with the
* {@link ByteBuffer} {@link #o} and shares its {@code data} with.
*/
private final DatagramPacket datagramPacket;
/**
* Initializes a new {@code DatagramBuffer} instance with a specific
* capacity of {@code byte}s shared between a {@code ByteBuffer} and a
* {@code DatagramPacket}.
*
* @param capacity the maximum number of {@code byte}s to be written into
* and read from the new instance
*/
public DatagramBuffer(int capacity)
{
super(ByteBuffer.allocate(capacity));
datagramPacket
= new DatagramPacket(o.array(), /* offset */ 0, /* length */ 0);
}
/**
* Gets the {@code ByteBuffer} (view) of this instance.
*
* @return the {@code ByteBuffer} (view) of this instance
*/
public ByteBuffer getByteBuffer()
{
return o;
}
/**
* Gets the {@code DatagramPacket} (view) of this instance. The
* {@code length} of the {@code DatagramPacket} equals the {@code position}
* of the {@code ByteBuffer} so that the {@code byte}s written into the
* {@code ByteBuffer} may be read from the {@code DatagramPacket}.
*
* @return the {@code DatagramPacket} (view) of this instance
*/
public DatagramPacket getDatagramPacket()
{
datagramPacket.setLength(getByteBuffer().position());
return datagramPacket;
}
}

View File

@ -0,0 +1,125 @@
/*
* ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
*
* Copyright @ 2015 Atlassian Pty Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.ice4j.socket.jdk8;
import java.io.*;
import java.nio.channels.*;
import org.ice4j.socket.*;
import sun.nio.ch.*;
/**
* Implements a {@code ServerSocketChannel} which delegates (its method calls)
* to another {@code ServerSocketChannel}. In other words, the former wraps the
* latter.
*
* @author Lyubomir Marinov
*/
class DelegatingServerSocketChannel<T extends ServerSocketChannel>
extends BaseDelegatingServerSocketChannel<T>
implements SelChImpl
{
/**
* The view of {@link #delegate} as a <tt>SelChImpl</tt> interface instance
* required by {@link Selector} and related functionality.
*/
protected final SelChImpl delegateAsSelChImpl;
/**
* Initializes a new {@code DelegatingServerSocketChannel} instance which is
* to delegate (its method calls) to a specific {@code ServerSocketChannel}.
*
* @param delegate the {@code ServerSocketChannel} the new instance is to
* delegate (its method calls) to
*/
public DelegatingServerSocketChannel(T delegate)
{
super(delegate);
delegateAsSelChImpl
= (delegate instanceof SelChImpl) ? (SelChImpl) delegate : null;
}
/**
* {@inheritDoc}
*
* Forwards to {@link #delegate}.
*/
@Override
public FileDescriptor getFD()
{
return delegateAsSelChImpl.getFD();
}
/**
* {@inheritDoc}
*
* Forwards to {@link #delegate}.
*/
@Override
public int getFDVal()
{
return delegateAsSelChImpl.getFDVal();
}
/**
* {@inheritDoc}
*
* Forwards to {@link #delegate}.
*/
@Override
public void kill()
throws IOException
{
delegateAsSelChImpl.kill();
}
/**
* {@inheritDoc}
*
* Forwards to {@link #delegate}.
*/
@Override
public void translateAndSetInterestOps(int ops, SelectionKeyImpl sk)
{
delegateAsSelChImpl.translateAndSetInterestOps(ops, sk);
}
/**
* {@inheritDoc}
*
* Forwards to {@link #delegate}.
*/
@Override
public boolean translateAndSetReadyOps(int ops, SelectionKeyImpl sk)
{
return delegateAsSelChImpl.translateAndSetReadyOps(ops, sk);
}
/**
* {@inheritDoc}
*
* Forwards to {@link #delegate}.
*/
@Override
public boolean translateAndUpdateReadyOps(int ops, SelectionKeyImpl sk)
{
return delegateAsSelChImpl.translateAndUpdateReadyOps(ops, sk);
}
}

View File

@ -0,0 +1,124 @@
/*
* ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
*
* Copyright @ 2015 Atlassian Pty Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.ice4j.socket.jdk8;
import java.io.*;
import java.nio.channels.*;
import org.ice4j.socket.*;
import sun.nio.ch.*;
/**
* Implements a {@code SocketChannel} which delegates (its method calls) to
* another {@code SocketChannel}. In other words, the former wraps the latter.
*
* @author Lyubomir Marinov
*/
class DelegatingSocketChannel<T extends SocketChannel>
extends BaseDelegatingSocketChannel<T>
implements SelChImpl
{
/**
* The view of {@link #delegate} as a <tt>SelChImpl</tt> interface instance
* required by {@link Selector} and related functionality.
*/
protected final SelChImpl delegateAsSelChImpl;
/**
* Initializes a new {@code DelegatingSocketChannel} instance which is to
* delegate (its method calls) to a specific {@code SocketChannel}.
*
* @param delegate the {@code SocketChannel} the new instance is to delegate
* (its method calls) to
*/
public DelegatingSocketChannel(T delegate)
{
super(delegate);
delegateAsSelChImpl
= (delegate instanceof SelChImpl) ? (SelChImpl) delegate : null;
}
/**
* {@inheritDoc}
*
* Forwards to {@link #delegate}.
*/
@Override
public FileDescriptor getFD()
{
return delegateAsSelChImpl.getFD();
}
/**
* {@inheritDoc}
*
* Forwards to {@link #delegate}.
*/
@Override
public int getFDVal()
{
return delegateAsSelChImpl.getFDVal();
}
/**
* {@inheritDoc}
*
* Forwards to {@link #delegate}.
*/
@Override
public void kill()
throws IOException
{
delegateAsSelChImpl.kill();
}
/**
* {@inheritDoc}
*
* Forwards to {@link #delegate}.
*/
@Override
public void translateAndSetInterestOps(int ops, SelectionKeyImpl sk)
{
delegateAsSelChImpl.translateAndSetInterestOps(ops, sk);
}
/**
* {@inheritDoc}
*
* Forwards to {@link #delegate}.
*/
@Override
public boolean translateAndSetReadyOps(int ops, SelectionKeyImpl sk)
{
return delegateAsSelChImpl.translateAndSetReadyOps(ops, sk);
}
/**
* {@inheritDoc}
*
* Forwards to {@link #delegate}.
*/
@Override
public boolean translateAndUpdateReadyOps(int ops, SelectionKeyImpl sk)
{
return delegateAsSelChImpl.translateAndUpdateReadyOps(ops, sk);
}
}

View File

@ -0,0 +1,56 @@
/*
* ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
*
* Copyright @ 2015 Atlassian Pty Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.ice4j.socket.jdk8;
import java.io.*;
import java.net.*;
import java.util.*;
import org.ice4j.socket.*;
/**
* Represents a {@link ServerSocket} associated with a
* {@code MuxServerSocketChannel}.
*
* @author Lyubomir Marinov
*/
class MuxServerSocket
extends DelegatingServerSocket
{
/**
* Initializes a new {@code MuxServerSocket} instance which delegates (its
* method calls) to a specific {@code MuxingServerSocket} and is associated
* with a specific {@code MuxServerSocketChannel}.
*
* @param delegate the {@code MuxingServerSocket} the new instance is to
* delegate (its method calls) to. Technically, it is the {@code socket} of
* the {@code delegate} of {@code channel}.
* @param channel the {@code MuxServerSocketChannel} associated with the new
* instance
* @throws IOException if an I/O error occurs
*/
public MuxServerSocket(
MuxingServerSocket delegate,
MuxServerSocketChannel channel)
throws IOException
{
super(
Objects.requireNonNull(delegate, "delegate"),
Objects.requireNonNull(channel, "channel"));
}
}

View File

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

View File

@ -0,0 +1,56 @@
/*
* 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

View File

@ -0,0 +1,108 @@
/*
* ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
*
* Copyright @ 2015 Atlassian Pty Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.ice4j.socket.jdk8;
import java.io.*;
import java.net.*;
import java.nio.*;
import java.nio.channels.*;
/**
* Prepends a {@link DatagramPacket} to a {@link SocketChannel}. In other words,
* enables looking ahead at the {@code byte}s of a {@code SocketChannel}.
*
* @author Lyubomir Marinov
*/
class PreReadSocketChannel
extends DelegatingSocketChannel<SocketChannel>
{
/**
* The {@link DatagramPacket} which is to be prepended to the
* {@link SocketChannel} which is the {@link #delegate} of this
* {@link DelegatingSocketChannel}.
*/
private final DatagramPacket preRead;
/**
* Initializes a new {@code PreReadSocketChannel} instance which is to
* prepend a specific {@link DatagramPacket} to a specific
* {@link SocketChannel}.
*
* @param preRead the {@code DatagramPacket} to prepend to {@code delegate}
* @param delegate the {@code SocketChannel} to prepend {@code preRead} to
*/
public PreReadSocketChannel(DatagramPacket preRead, SocketChannel delegate)
{
super(delegate);
this.preRead = preRead;
}
/**
* {@inheritDoc}
*
* Reads from {@link #preRead} first (until it is fully read) and then
* continues with the {@code super} implementation.
*/
@Override
public int read(ByteBuffer dst)
throws IOException
{
synchronized (preRead)
{
int len = preRead.getLength();
int read;
if (len > 0)
{
int toRead = Math.min(len, dst.remaining());
if (toRead > 0)
{
byte[] buf = preRead.getData();
int off = preRead.getOffset();
dst.put(buf, off, toRead);
read = toRead;
preRead.setData(buf, off + read, len - read);
}
else
{
read = 0;
}
}
else
{
read = 0;
}
if (read == 0)
{
read = super.read(dst);
}
else if (dst.hasRemaining())
{
int superRead = super.read(dst);
if (superRead > 0)
read += superRead;
}
return read;
}
}
}

View File

@ -0,0 +1,66 @@
/*
* ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
*
* Copyright @ 2015 Atlassian Pty Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.ice4j.socket.jdk8;
/**
* Represents an {@code Object} with a timestamp.
*
* @param <T> the type of the {@code Object} which has a timestamp (associated)
* @author Lyubomir Marinov
*/
class Timestamped<T>
{
/**
* The {@code Object} associated with {@link #timestamp}.
*/
final T o;
/**
* The timestamp (in milliseconds) associated with {@link #o}.
*/
long timestamp;
/**
* Initializes a new {@code Timestamped} instance with a specific
* {@code Object} and a default timestamp (value).
*
* @param o the {@code Object} to associate with a timestamp
*/
public Timestamped(T o)
{
this(o, -1);
}
/**
* Initializes a new {@code Timestamped} instance with a specific
* {@code Object} and a specific timestamp (value).
*
* @param o the {@code Object} to associate with {@code timestamp}
* @param timestamp the timestamp (in milliseconds) to associate with
* {@code o}
*/
public Timestamped(T o, long timestamp)
{
// It makes no sense to associate a timestamp with a null.
if (o == null)
throw new NullPointerException("o");
this.o = o;
this.timestamp = timestamp;
}
}

View File

@ -210,8 +210,7 @@ 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());
} }
@ -326,16 +325,8 @@ 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.

View File

@ -177,8 +177,8 @@ class MessageProcessingTask
{ {
stunMessage stunMessage
= Message.decode(message.getBytes(), = Message.decode(message.getBytes(),
0, (char) 0,
message.getMessageLength()); (char) message.getMessageLength());
} }
catch (StunException ex) catch (StunException ex)
{ {
@ -206,7 +206,7 @@ class MessageProcessingTask
// On processed callback must be invoked in all cases, even when // On processed callback must be invoked in all cases, even when
// cancellation or early exist happen, otherwise // cancellation or early exist happen, otherwise
// NetAccessManager internal tracking of pooled and active // NetAccessManager internal tracking of pooled and active
// message processors will misbehave. // message processors will missbehave.
if (onProcessed != null) if (onProcessed != null)
{ {
onProcessed.accept(this); onProcessed.accept(this);

View File

@ -17,11 +17,6 @@
*/ */
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.*;
@ -29,6 +24,12 @@ import java.util.concurrent.*;
import java.util.concurrent.atomic.*; import java.util.concurrent.atomic.*;
import java.util.function.*; import java.util.function.*;
import java.util.logging.*; import java.util.logging.*;
import java.util.logging.Logger; // Disambiguation
import org.ice4j.*;
import org.ice4j.message.*;
import org.ice4j.socket.*;
import org.jitsi.javautils.*;
/** /**
* Manages <tt>Connector</tt>s and <tt>MessageProcessingTask</tt> execution and * Manages <tt>Connector</tt>s and <tt>MessageProcessingTask</tt> execution and
@ -42,7 +43,7 @@ import java.util.logging.*;
* @author Boris Grozev * @author Boris Grozev
* @author Yura Yaroshevich * @author Yura Yaroshevich
*/ */
public class NetAccessManager class NetAccessManager
implements ErrorHandler implements ErrorHandler
{ {
/** /**
@ -139,6 +140,15 @@ public class NetAccessManager
*/ */
private final AtomicBoolean isStopped = new AtomicBoolean(false); private final AtomicBoolean isStopped = new AtomicBoolean(false);
/**
* Optionally enabled QueueStatistics to keep track throughput
* of processing {@link MessageProcessingTask}
*/
private final QueueStatistics queueStatistics
= logger.isLoggable(Level.FINEST)
? new QueueStatistics(this.toString())
: null;
/** /**
* Callback to be called when scheduled <tt>MessageProcessingTask</tt> * Callback to be called when scheduled <tt>MessageProcessingTask</tt>
* completes processing it's <tt>RawMessage</tt>. * completes processing it's <tt>RawMessage</tt>.
@ -148,11 +158,17 @@ public class NetAccessManager
activeTasks.remove(messageProcessingTask); activeTasks.remove(messageProcessingTask);
if (queueStatistics != null)
{
queueStatistics.remove(System.currentTimeMillis());
}
final boolean isAdded = taskPool.offer(messageProcessingTask); final boolean isAdded = taskPool.offer(messageProcessingTask);
if (!isAdded && logger.isLoggable(Level.FINEST)) if (!isAdded && logger.isLoggable(Level.FINEST))
{ {
logger.finest("Dropping MessageProcessingTask for " logger.finest("Dropping MessageProcessingTask for "
+ this + " because pool is full, max pool size is " + TASK_POOL_SIZE); + this + " because pool is full, max pool size is "
+ String.valueOf(TASK_POOL_SIZE));
} }
}; };
@ -301,8 +317,7 @@ public 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);
} }
@ -553,6 +568,10 @@ public class NetAccessManager
activeTasks.add(messageProcessingTask); activeTasks.add(messageProcessingTask);
if (queueStatistics != null)
{
queueStatistics.add(System.currentTimeMillis());
}
// Use overload which does not return Future object to avoid // Use overload which does not return Future object to avoid
// unnecessary allocation // unnecessary allocation
messageProcessingExecutor.execute(messageProcessingTask); messageProcessingExecutor.execute(messageProcessingTask);
@ -628,17 +647,10 @@ public class NetAccessManager
Connector ap = getConnector(srcAddr, remoteAddr); Connector ap = getConnector(srcAddr, remoteAddr);
if (ap == null) if (ap == null)
{ {
throw new SocketNotFoundException("No socket found for " + srcAddr + "->" + remoteAddr); throw new IllegalArgumentException(
"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);
}
}
} }

View File

@ -17,17 +17,17 @@
*/ */
package org.ice4j.stack; package org.ice4j.stack;
import org.ice4j.*;
import org.ice4j.message.*;
import org.ice4j.util.PeriodicRunnable;
import org.jitsi.utils.concurrent.*;
import java.io.*; import java.io.*;
import java.time.*; import java.time.*;
import java.util.concurrent.*; import java.util.concurrent.*;
import java.util.concurrent.atomic.*; import java.util.concurrent.atomic.*;
import java.util.logging.*; import java.util.logging.*;
import org.ice4j.*;
import org.ice4j.message.*;
import org.ice4j.util.*;
import org.jitsi.javautils.*;
/** /**
* The {@code StunClientTransaction} class retransmits requests as specified by * The {@code StunClientTransaction} class retransmits requests as specified by
* RFC 3489. * RFC 3489.
@ -151,7 +151,7 @@ public class StunClientTransaction
/** /**
* A transaction request retransmitter * A transaction request retransmitter
*/ */
private final Retransmitter retransmitter; private final Retransmitter retransmitter = new Retransmitter();
/** /**
* Creates a client transaction. * Creates a client transaction.
@ -207,8 +207,6 @@ public class StunClientTransaction
initTransactionConfiguration(); initTransactionConfiguration();
retransmitter = new Retransmitter(); // create it here to support 'originalWaitInterval' configuration
this.transactionID = transactionID; this.transactionID = transactionID;
try try

View File

@ -165,8 +165,7 @@ 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

View File

@ -17,14 +17,6 @@
*/ */
package org.ice4j.stack; package org.ice4j.stack;
import org.ice4j.*;
import org.ice4j.attribute.*;
import org.ice4j.message.*;
import org.ice4j.security.*;
import org.ice4j.socket.*;
import org.jitsi.utils.concurrent.*;
import javax.crypto.*;
import java.io.*; import java.io.*;
import java.net.*; import java.net.*;
import java.security.*; import java.security.*;
@ -32,6 +24,15 @@ import java.util.*;
import java.util.concurrent.*; import java.util.concurrent.*;
import java.util.logging.*; import java.util.logging.*;
import javax.crypto.*;
import org.ice4j.*;
import org.ice4j.attribute.*;
import org.ice4j.message.*;
import org.ice4j.security.*;
import org.ice4j.socket.*;
import org.jitsi.javautils.*;
/** /**
* 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
* configure the stack. * configure the stack.

View File

@ -409,8 +409,7 @@ public class NetworkConfigurationDiscoveryProcess
{ {
Request request = MessageFactory.createBindingRequest(); Request request = MessageFactory.createBindingRequest();
/* ChangeRequestAttribute changeRequest /* ChangeRequestAttribute changeRequest = (ChangeRequestAttribute)request.getAttribute(Attribute.CHANGE_REQUEST); */
= (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);

View File

@ -0,0 +1,234 @@
/*
* 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);
}
}

View File

@ -1,7 +1,5 @@
package org.ice4j.util; package org.ice4j.util;
import org.jitsi.utils.logging2.*;
import java.time.*; import java.time.*;
import java.util.concurrent.*; import java.util.concurrent.*;
@ -13,11 +11,6 @@ import java.util.concurrent.*;
*/ */
public abstract class PeriodicRunnable 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 * A timer to perform periodic scheduling of {@link #run()} execution
* on {@link #executor}'s thread. * on {@link #executor}'s thread.
@ -212,10 +205,6 @@ public abstract class PeriodicRunnable
{ {
this.run(); this.run();
} }
catch (Exception e)
{
logger.warn("Exception in run(), will retry.", e);
}
finally finally
{ {
if (running) if (running)

View File

@ -1,83 +0,0 @@
/*
* 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()
}
}

View File

@ -1,132 +0,0 @@
/*
* 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()
}
}

View File

@ -1,104 +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.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
}
}

View File

@ -1,29 +0,0 @@
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)"
}

View File

@ -1,94 +0,0 @@
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"
#}
]
}
}
}

View File

@ -19,18 +19,18 @@ package org.ice4j;
import java.util.*; import java.util.*;
import static org.junit.jupiter.api.Assertions.*; import junit.framework.*;
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 public class MessageEventDispatchingTest extends TestCase
{ {
/** /**
* The stack that we are using for the tests. * The stack that we are using for the tests.
@ -95,9 +95,10 @@ public class MessageEventDispatchingTest
* *
* @throws Exception if anything goes wrong. * @throws Exception if anything goes wrong.
*/ */
@BeforeEach protected void setUp() throws Exception
public void setUp() throws Exception
{ {
super.setUp();
stunStack = new StunStack(); stunStack = new StunStack();
clientSock = new IceUdpSocketWrapper( clientSock = new IceUdpSocketWrapper(
@ -125,8 +126,7 @@ public class MessageEventDispatchingTest
* *
* @throws Exception if anything goes wrong. * @throws Exception if anything goes wrong.
*/ */
@AfterEach protected void tearDown() throws Exception
public void tearDown() throws Exception
{ {
stunStack.removeSocket(clientAddress); stunStack.removeSocket(clientAddress);
stunStack.removeSocket(serverAddress); stunStack.removeSocket(serverAddress);
@ -138,6 +138,8 @@ public class MessageEventDispatchingTest
requestCollector = null; requestCollector = null;
responseCollector = null; responseCollector = null;
super.tearDown();
} }
/** /**
@ -145,7 +147,6 @@ public class MessageEventDispatchingTest
* *
* @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(
@ -155,11 +156,13 @@ public class MessageEventDispatchingTest
responseCollector); responseCollector);
responseCollector.waitForTimeout(); responseCollector.waitForTimeout();
assertEquals(1, responseCollector.receivedResponses.size(), assertEquals(
"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("timeout", responseCollector.receivedResponses.get(0), assertEquals(
"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.
@ -175,7 +178,6 @@ public class MessageEventDispatchingTest
* *
* @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
@ -187,8 +189,8 @@ public class MessageEventDispatchingTest
requestCollector.waitForRequest(); requestCollector.waitForRequest();
//verify //verify
assertEquals(1, requestCollector.receivedRequests.size(), assertTrue("No MessageEvents have been dispatched",
"No MessageEvents have been dispatched"); requestCollector.receivedRequests.size() == 1);
} }
/** /**
@ -197,7 +199,6 @@ public class MessageEventDispatchingTest
* *
* @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
{ {
@ -215,17 +216,19 @@ public class MessageEventDispatchingTest
requestCollector2.waitForRequest(); requestCollector2.waitForRequest();
//verify //verify
assertEquals(0, requestCollector.receivedRequests.size(), assertTrue(
"A MessageEvent was received by a non-interested selective listener"); "A MessageEvent was received by a non-interested selective listener",
assertEquals(1, requestCollector2.receivedRequests.size(), requestCollector.receivedRequests.size() == 0);
"No MessageEvents have been dispatched for a selective listener"); assertTrue(
"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
@ -246,14 +249,15 @@ public class MessageEventDispatchingTest
responseCollector.waitForResponse(); responseCollector.waitForResponse();
//verify that we got the response. //verify that we got the response.
assertEquals(1, responseCollector.receivedResponses.size(), assertTrue(
"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 static class PlainRequestCollector implements RequestListener private 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<>();

View File

@ -243,4 +243,20 @@ 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()
{
}
} }

View File

@ -0,0 +1,62 @@
/*
* 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;
}
}

View File

@ -0,0 +1,94 @@
/*
* 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;
}
}

View File

@ -1,47 +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 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;
}
}
}
}

View File

@ -17,15 +17,14 @@
*/ */
package org.ice4j; package org.ice4j;
import java.net.*;
import java.util.*; import java.util.*;
import static org.junit.jupiter.api.Assertions.*; import junit.framework.*;
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
@ -33,17 +32,19 @@ import org.junit.jupiter.api.*;
* *
* @author Emil Ivov * @author Emil Ivov
*/ */
public class TransactionSupportTests public class TransactionSupportTests extends TestCase
{ {
/** /**
* 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.
@ -85,19 +86,15 @@ public class TransactionSupportTests
* *
* @throws Exception if something goes bad. * @throws Exception if something goes bad.
*/ */
@BeforeEach protected void setUp()
public void setUp()
throws Exception throws Exception
{ {
clientSock = new IceUdpSocketWrapper( super.setUp();
new SafeCloseDatagramSocket(new InetSocketAddress("127.0.0.1", 0)));
serverSock = new IceUdpSocketWrapper(
new SafeCloseDatagramSocket(new InetSocketAddress("127.0.0.1", 0)));
clientAddress clientSock = new IceUdpSocketWrapper(
= new TransportAddress("127.0.0.1", clientSock.getLocalPort(), Transport.UDP); new SafeCloseDatagramSocket(clientAddress));
serverAddress serverSock = new IceUdpSocketWrapper(
= new TransportAddress("127.0.0.1", serverSock.getLocalPort(), Transport.UDP); new SafeCloseDatagramSocket(serverAddress));
stunStack = new StunStack(); stunStack = new StunStack();
stunStack.addSocket(clientSock); stunStack.addSocket(clientSock);
@ -132,8 +129,7 @@ public class TransactionSupportTests
* *
* @throws Exception if something does not go as planned. * @throws Exception if something does not go as planned.
*/ */
@AfterEach protected void tearDown()
public void tearDown()
throws Exception throws Exception
{ {
stunStack.removeSocket(clientAddress); stunStack.removeSocket(clientAddress);
@ -160,6 +156,8 @@ public class TransactionSupportTests
System.setProperty( System.setProperty(
StackProperties.FIRST_CTRAN_RETRANS_AFTER, StackProperties.FIRST_CTRAN_RETRANS_AFTER,
""); "");
super.tearDown();
} }
/** /**
@ -167,7 +165,6 @@ public class TransactionSupportTests
* *
* @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(
@ -198,10 +195,11 @@ public class TransactionSupportTests
= requestCollector.getRequestsForTransaction( = requestCollector.getRequestsForTransaction(
bindingRequest.getTransactionID()); bindingRequest.getTransactionID());
assertTrue(reqs.size() > 1, assertTrue("No retransmissions of the request have been received",
"No retransmissions of the request have been received"); reqs.size() > 1);
assertTrue(reqs.size() >= 3, assertTrue("The binding request has been retransmitted more than it "
"The binding request has been retransmitted more than it should have!"); +"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.
@ -224,7 +222,6 @@ public class TransactionSupportTests
* *
* @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(
@ -247,8 +244,9 @@ public class TransactionSupportTests
= requestCollector.getRequestsForTransaction( = requestCollector.getRequestsForTransaction(
bindingRequest.getTransactionID()); bindingRequest.getTransactionID());
assertTrue(reqs.size() <= 1, assertTrue(
"Retransmissions of a binding request were propagated to the server"); "Retransmissions of a binding request were propagated "
+ "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.
@ -266,7 +264,6 @@ public class TransactionSupportTests
* *
* @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(
@ -306,9 +303,10 @@ public class TransactionSupportTests
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(responseCollector.receivedResponses.size() < 3, assertTrue(
"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.
@ -325,7 +323,6 @@ public class TransactionSupportTests
* 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);
@ -369,11 +366,10 @@ public class TransactionSupportTests
StunMessageEvent evt2 = reqs2.get(0); StunMessageEvent evt2 = reqs2.get(0);
assertFalse(Arrays.equals( assertFalse(
evt1.getMessage().getTransactionID(), "Consecutive requests were assigned the same transaction id",
evt2.getMessage().getTransactionID()), Arrays.equals( evt1.getMessage().getTransactionID(),
"Consecutive requests were assigned the same transaction id" evt2.getMessage().getTransactionID()));
);
} }
/** /**
@ -382,7 +378,6 @@ public class TransactionSupportTests
* *
* @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
{ {
@ -409,10 +404,13 @@ public class TransactionSupportTests
= requestCollector.getRequestsForTransaction( = requestCollector.getRequestsForTransaction(
bindingRequest.getTransactionID()); bindingRequest.getTransactionID());
assertTrue(reqs.size() > 1, assertTrue("No retransmissions of the request have been received",
"No retransmissions of the request have been received"); reqs.size() > 1);
assertEquals(3, reqs.size(), assertEquals(
"The MAX_RETRANSMISSIONS param was not taken into account!"); "The MAX_RETRANSMISSIONS param was not taken into account!",
reqs.size(),
3);
} }
/** /**
@ -421,7 +419,6 @@ public class TransactionSupportTests
* *
* @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
{ {
@ -445,8 +442,8 @@ public class TransactionSupportTests
//verify //verify
Vector<?> reqs = requestCollector.getRequestsForTransaction( Vector<?> reqs = requestCollector.getRequestsForTransaction(
bindingRequest.getTransactionID()); bindingRequest.getTransactionID());
assertTrue(reqs.size() < 2, assertTrue("A retransmissions of the request was sent too early",
"A retransmissions of the request was sent too early"); reqs.size() < 2);
//wait for a send //wait for a send
Thread.sleep(110); Thread.sleep(110);
@ -455,8 +452,8 @@ public class TransactionSupportTests
bindingRequest.getTransactionID()); bindingRequest.getTransactionID());
//verify //verify
assertEquals(2, reqs.size(), assertEquals("A retransmissions of the request was not sent",
"A retransmissions of the request was not sent"); 2, reqs.size());
} }
/** /**
@ -465,7 +462,6 @@ public class TransactionSupportTests
* *
* @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
{ {
@ -485,39 +481,40 @@ public class TransactionSupportTests
clientAddress, clientAddress,
responseCollector); responseCollector);
//wait until a response arrives //wait a while
synchronized (responseCollector) Thread.sleep(1200);
{
responseCollector.wait(5000);
}
//verify //verify
Vector<StunMessageEvent> reqs Vector<StunMessageEvent> reqs
= requestCollector.getRequestsForTransaction( = requestCollector.getRequestsForTransaction(
bindingRequest.getTransactionID()); bindingRequest.getTransactionID());
assertEquals(12, reqs.size(), assertEquals("Not all retransmissions were made for the expected period "
"Not all retransmissions were made for the expected period of time"); +"of time",
12,
reqs.size());
//wait for a send //wait for a send
requestCollector.waitForRequest(1800); Thread.sleep(1800);
//verify //verify
reqs = requestCollector.getRequestsForTransaction( reqs = requestCollector.getRequestsForTransaction(
bindingRequest.getTransactionID()); bindingRequest.getTransactionID());
assertEquals(12, reqs.size(), assertEquals("A retransmissions of the request was sent, while not "
"A retransmissions of the request was sent, while not supposed to"); +"supposed to",
12,
reqs.size());
} }
/** /**
* A simply utility for asynchronous collection of requests. * A simply utility for asynchronous collection of requests.
*/ */
private static class PlainRequestCollector private class PlainRequestCollector
implements RequestListener implements RequestListener
{ {
/** /**
* *
*/ */
private final Vector<StunMessageEvent> receivedRequestsVector private Vector<StunMessageEvent> receivedRequestsVector
= new Vector<>(); = new Vector<>();
/** /**
@ -562,25 +559,15 @@ public class TransactionSupportTests
* 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(timeoutMillis); wait(50);
} }
catch (InterruptedException e) catch (InterruptedException e)
{ {}
Thread.currentThread().interrupt();
}
} }
} }
} }
@ -605,7 +592,7 @@ public class TransactionSupportTests
* 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 synchronized void processFailure(BaseStunMessageEvent event) protected void processFailure(BaseStunMessageEvent event)
{ {
String receivedResponse; String receivedResponse;
@ -616,7 +603,6 @@ public class TransactionSupportTests
else else
receivedResponse = "failure"; receivedResponse = "failure";
receivedResponses.add(receivedResponse); receivedResponses.add(receivedResponse);
notifyAll();
} }
/** /**
@ -624,10 +610,9 @@ public class TransactionSupportTests
* *
* @param response the event to log. * @param response the event to log.
*/ */
public synchronized void processResponse(StunResponseEvent response) public void processResponse(StunResponseEvent response)
{ {
receivedResponses.add(response); receivedResponses.add(response);
notifyAll();
} }
} }
} }

View File

@ -17,40 +17,46 @@
*/ */
package org.ice4j.attribute; package org.ice4j.attribute;
import static org.junit.jupiter.api.Assertions.*; import java.util.*;
import junit.framework.*;
import org.ice4j.*; import org.ice4j.*;
import org.junit.jupiter.api.*;
/** /**
* *
* @author Emil Ivov * @author Emil Ivov
*/ */
public class AddressAttributeTest public class AddressAttributeTest extends TestCase {
{
private AddressAttribute addressAttribute = null; private AddressAttribute addressAttribute = null;
private MsgFixture msgFixture; private MsgFixture msgFixture;
@BeforeEach public AddressAttributeTest(String name) {
public void setUp() throws Exception super(name);
{
addressAttribute = new MappedAddressAttribute();
msgFixture = new MsgFixture();
} }
@AfterEach protected void setUp() throws Exception {
public void tearDown() throws Exception super.setUp();
{
addressAttribute = new MappedAddressAttribute();
msgFixture = new MsgFixture();
msgFixture.setUp();
}
protected 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.
*/ */
@Test public void testAddressAttributeDescendants() {
public void testAddressAttributeDescendants()
{
char expectedType; char expectedType;
char actualType; char actualType;
String expectedName; String expectedName;
@ -65,10 +71,10 @@ public class AddressAttributeTest
expectedName = "MAPPED-ADDRESS"; expectedName = "MAPPED-ADDRESS";
actualName = addressAttribute.getName(); actualName = addressAttribute.getName();
assertEquals(expectedType, actualType, assertEquals("MappedAddressAttribute does not the right type.",
"MappedAddressAttribute does not the right type."); expectedType, actualType);
assertEquals(expectedName, actualName, assertEquals("MappedAddressAttribute does not the right name.",
"MappedAddressAttribute does not the right name."); expectedName, actualName);
//SOURCE-ADDRESS //SOURCE-ADDRESS
@ -80,10 +86,10 @@ public class AddressAttributeTest
expectedName = "SOURCE-ADDRESS"; expectedName = "SOURCE-ADDRESS";
actualName = addressAttribute.getName(); actualName = addressAttribute.getName();
assertEquals(expectedType, actualType, assertEquals("SourceAddressAttribute does not the right type.",
"SourceAddressAttribute does not the right type."); expectedType, actualType);
assertEquals(expectedName, actualName, assertEquals("SourceAddressAttribute does not the right name.",
"SourceAddressAttribute does not the right name."); expectedName, actualName);
//CHANGED-ADDRESS //CHANGED-ADDRESS
@ -95,10 +101,10 @@ public class AddressAttributeTest
expectedName = "CHANGED-ADDRESS"; expectedName = "CHANGED-ADDRESS";
actualName = addressAttribute.getName(); actualName = addressAttribute.getName();
assertEquals(expectedType, actualType, assertEquals("ChangedAddressAttribute does not the right type.",
"ChangedAddressAttribute does not the right type."); expectedType, actualType);
assertEquals(expectedName, actualName, assertEquals("ChangedAddressAttribute does not the right name.",
"ChangedAddressAttribute does not the right name."); expectedName, actualName);
//RESPONSE-ADDRESS //RESPONSE-ADDRESS
@ -110,10 +116,10 @@ public class AddressAttributeTest
expectedName = "RESPONSE-ADDRESS"; expectedName = "RESPONSE-ADDRESS";
actualName = addressAttribute.getName(); actualName = addressAttribute.getName();
assertEquals(expectedType, actualType, assertEquals("ResponseAddressAttribute does not the right type.",
"ResponseAddressAttribute does not the right type."); expectedType, actualType);
assertEquals(expectedName, actualName, assertEquals("ResponseAddressAttribute does not the right name.",
"ResponseAddressAttribute does not the right name."); expectedName, actualName);
//REFLECTED-FROM //REFLECTED-FROM
@ -125,10 +131,10 @@ public class AddressAttributeTest
expectedName = "REFLECTED-FROM"; expectedName = "REFLECTED-FROM";
actualName = addressAttribute.getName(); actualName = addressAttribute.getName();
assertEquals(expectedType, actualType, assertEquals("ReflectedFromAttribute does not the right type.",
"ReflectedFromAttribute does not the right type."); expectedType, actualType);
assertEquals(expectedName, actualName, assertEquals("ReflectedFromAttribute does not the right name.",
"ReflectedFromAttribute does not the right name."); expectedName, actualName);
//REFLECTED-FROM //REFLECTED-FROM
addressAttribute = new ReflectedFromAttribute(); addressAttribute = new ReflectedFromAttribute();
@ -139,10 +145,10 @@ public class AddressAttributeTest
expectedName = "REFLECTED-FROM"; expectedName = "REFLECTED-FROM";
actualName = addressAttribute.getName(); actualName = addressAttribute.getName();
assertEquals(expectedType, actualType, assertEquals("ReflectedFromAttribute does not the right type.",
"ReflectedFromAttribute does not the right type."); expectedType, actualType);
assertEquals(expectedName, actualName, assertEquals("ReflectedFromAttribute does not the right name.",
"ReflectedFromAttribute does not the right name."); expectedName, actualName);
//XOR-MAPPED-ADDRESS //XOR-MAPPED-ADDRESS
addressAttribute = new XorMappedAddressAttribute(); addressAttribute = new XorMappedAddressAttribute();
@ -153,10 +159,10 @@ public class AddressAttributeTest
expectedName = "XOR-MAPPED-ADDRESS"; expectedName = "XOR-MAPPED-ADDRESS";
actualName = addressAttribute.getName(); actualName = addressAttribute.getName();
assertEquals(expectedType, actualType, assertEquals("XorMappedAddressAttribute does not the right type.",
"XorMappedAddressAttribute does not the right type."); expectedType, actualType);
assertEquals(expectedName, actualName, assertEquals("XorMappedAddressAttribute does not the right name.",
"XorMappedAddressAttribute does not the right name."); expectedName, actualName);
/* ALTERNATE-SERVER */ /* ALTERNATE-SERVER */
addressAttribute = new AlternateServerAttribute(); addressAttribute = new AlternateServerAttribute();
@ -167,10 +173,10 @@ public class AddressAttributeTest
expectedName = "ALTERNATE-SERVER"; expectedName = "ALTERNATE-SERVER";
actualName = addressAttribute.getName(); actualName = addressAttribute.getName();
assertEquals(expectedType, actualType, assertEquals("AlternateServerAttribute does not the right type.",
"AlternateServerAttribute does not the right type."); expectedType, actualType);
assertEquals(expectedName, actualName, assertEquals("AlternateAttribute does not the right name.",
"AlternateAttribute does not the right name."); expectedName, actualName);
/* XOR-PEER-ADDRESS */ /* XOR-PEER-ADDRESS */
@ -182,10 +188,10 @@ public class AddressAttributeTest
expectedName = "XOR-PEER-ADDRESS"; expectedName = "XOR-PEER-ADDRESS";
actualName = addressAttribute.getName(); actualName = addressAttribute.getName();
assertEquals(expectedType, actualType, assertEquals("XorPeerAddressAttribute does not the right type.",
"XorPeerAddressAttribute does not the right type."); expectedType, actualType);
assertEquals(expectedName, actualName, assertEquals("XorPeerAddressAttribute does not the right name.",
"XorPeerAddressAttribute does not the right name."); expectedName, actualName);
/* XOR-RELAYED-ADDRESS */ /* XOR-RELAYED-ADDRESS */
addressAttribute = new XorRelayedAddressAttribute(); addressAttribute = new XorRelayedAddressAttribute();
@ -196,16 +202,15 @@ public class AddressAttributeTest
expectedName = "XOR-RELAYED-ADDRESS"; expectedName = "XOR-RELAYED-ADDRESS";
actualName = addressAttribute.getName(); actualName = addressAttribute.getName();
assertEquals(expectedType, actualType, assertEquals("XorRelayedAddressAttribute does not the right type.",
"XorRelayedAddressAttribute does not the right type."); expectedType, actualType);
assertEquals(expectedName, actualName, assertEquals("XorRelayedAddressAttribute does not the right name.",
"XorRelayedAddressAttribute does not the right name."); expectedName, actualName);
} }
/** /**
* 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();
@ -218,12 +223,11 @@ public class AddressAttributeTest
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});
assertArrayEquals( assertTrue("Xorring the address with itself didn't return 00000...",
xorredAddr.getAddressBytes(), new byte[] { 0, 0, 0, 0 }, Arrays.equals(xorredAddr.getAddressBytes(), new byte[]{0,0,0,0}));
"Xorring the address with itself didn't return 00000...");
assertNotEquals(xorredAddr.getPort(), testAddress.getPort(), assertTrue("Port was not xorred",
"Port was not xorred"); testAddress.getPort() != xorredAddr.getPort());
//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);
@ -233,11 +237,13 @@ public class AddressAttributeTest
xorredAddr = xorredAddr =
addressAttribute.applyXor(xorredAddr.getAddressBytes()); addressAttribute.applyXor(xorredAddr.getAddressBytes());
assertArrayEquals( assertTrue("Xorring the original with the xor-ed didn't "
xorredAddr.getAddressBytes(), new byte[] { 21, 22, 23, 24 }, +"return the code..",
"Xorring the original with the xor-ed didn't return the code."); Arrays.equals( xorredAddr.getAddressBytes(),
new byte[]{21,22,23,24}));
assertNotEquals(0xFFFF, testAddress.getPort(), "Port was not xorred"); assertTrue("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);
@ -248,14 +254,13 @@ public class AddressAttributeTest
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(testAddress, xorredAddr, assertEquals("Double xorring didn't give the original ...",
"Double xorring didn't give the original"); testAddress, xorredAddr);
} }
/** /**
* 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
@ -273,15 +278,15 @@ public class AddressAttributeTest
(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});
assertArrayEquals( assertTrue("Xorring the address with itself didn't return 00000...",
xorredAddr.getAddressBytes(), new byte[] { 0, 0, 0, 0, Arrays.equals(xorredAddr.getAddressBytes(),
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...");
assertNotEquals(testAddress.getPort(), xorredAddr.getPort(), assertTrue("Port was not xorred",
"Port was not xorred"); testAddress.getPort() != xorredAddr.getPort());
//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);
@ -290,13 +295,13 @@ public class AddressAttributeTest
xorredAddr = addressAttribute.applyXor(xorredAddr.getAddressBytes()); xorredAddr = addressAttribute.applyXor(xorredAddr.getAddressBytes());
assertArrayEquals( assertTrue("Xorring the original with the xor-ed didn't return the code..",
Arrays.equals(
xorredAddr.getAddressBytes(), xorredAddr.getAddressBytes(),
new byte[] { 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, new byte[]{21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36}));
35, 36 },
"Xorring the original with the xor-ed didn't return the code.");
assertNotEquals(0xFFFF, testAddress.getPort(), "Port was not xorred"); assertTrue("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);
@ -307,8 +312,8 @@ public class AddressAttributeTest
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(testAddress, xorredAddr, assertEquals("Double xorring didn't give the original ...",
"Double xorring didn't give the original"); testAddress, xorredAddr);
} }
/** /**
@ -316,7 +321,6 @@ public class AddressAttributeTest
* *
* @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;
@ -326,12 +330,12 @@ public class AddressAttributeTest
assertEquals( assertEquals(
MsgFixture.ADDRESS_ATTRIBUTE_PORT, addressAttribute.getPort(), "AddressAttribute.decode() did not properly decode the port field.",
"AddressAttribute.decode() did not properly decode the port field."); MsgFixture.ADDRESS_ATTRIBUTE_PORT, addressAttribute.getPort());
assertArrayEquals( assertTrue(
MsgFixture.ADDRESS_ATTRIBUTE_ADDRESS, "AddressAttribute.decode() did not properly decode the address field.",
addressAttribute.getAddressBytes(), Arrays.equals( MsgFixture.ADDRESS_ATTRIBUTE_ADDRESS,
"AddressAttribute.decode() did not properly decode the address field."); addressAttribute.getAddressBytes()));
} }
@ -340,7 +344,6 @@ public class AddressAttributeTest
* 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;
@ -349,13 +352,14 @@ public class AddressAttributeTest
addressAttribute.decodeAttributeBody(attributeValue, offset, length); addressAttribute.decodeAttributeBody(attributeValue, offset, length);
assertEquals(MsgFixture.ADDRESS_ATTRIBUTE_PORT, assertEquals("decode() failed for an IPv6 Addr's port.",
addressAttribute.getPort(), MsgFixture.ADDRESS_ATTRIBUTE_PORT,
"decode() failed for an IPv6 Addr's port."); addressAttribute.getPort());
assertArrayEquals( assertTrue("AddressAttribute.decode() failed for an IPv6 address.",
MsgFixture.ADDRESS_ATTRIBUTE_ADDRESS_V6, Arrays.equals( MsgFixture.ADDRESS_ATTRIBUTE_ADDRESS_V6,
addressAttribute.getAddressBytes(), addressAttribute.getAddressBytes()));
"AddressAttribute.decode() failed for an IPv6 address.");
} }
/** /**
@ -363,7 +367,6 @@ public class AddressAttributeTest
* *
* @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
{ {
@ -375,8 +378,9 @@ public class AddressAttributeTest
Transport.UDP)); Transport.UDP));
byte[] actualReturn = addressAttribute.encode(); byte[] actualReturn = addressAttribute.encode();
assertArrayEquals(expectedReturn, actualReturn, assertTrue("AddressAttribute.encode() did not "
"AddressAttribute.encode() did not properly encode a sample attribute"); +"properly encode a sample attribute",
Arrays.equals( expectedReturn, actualReturn));
} }
/** /**
@ -384,7 +388,6 @@ public class AddressAttributeTest
* *
* @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
{ {
@ -395,8 +398,8 @@ public class AddressAttributeTest
MsgFixture.ADDRESS_ATTRIBUTE_PORT, Transport.UDP)); MsgFixture.ADDRESS_ATTRIBUTE_PORT, Transport.UDP));
byte[] actualReturn = addressAttribute.encode(); byte[] actualReturn = addressAttribute.encode();
assertArrayEquals(expectedReturn, actualReturn, assertTrue("An AddressAttribute did not properly encode an IPv6 addr.",
"An AddressAttribute did not properly encode an IPv6 addr."); Arrays.equals( expectedReturn, actualReturn));
} }
@ -406,7 +409,6 @@ public class AddressAttributeTest
* *
* @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
{ {
@ -415,8 +417,8 @@ public class AddressAttributeTest
boolean expectedReturn = false; boolean expectedReturn = false;
boolean actualReturn = addressAttribute.equals(target); boolean actualReturn = addressAttribute.equals(target);
assertEquals(expectedReturn, actualReturn, assertEquals("AddressAttribute.equals() failed against a null target.",
"AddressAttribute.equals() failed against a null target."); expectedReturn, actualReturn);
//difference test //difference test
target = new MappedAddressAttribute(); target = new MappedAddressAttribute();
@ -432,8 +434,9 @@ public class AddressAttributeTest
expectedReturn = false; expectedReturn = false;
actualReturn = addressAttribute.equals(target); actualReturn = addressAttribute.equals(target);
assertEquals(expectedReturn, actualReturn, assertEquals(
"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(
@ -442,8 +445,9 @@ public class AddressAttributeTest
expectedReturn = true; expectedReturn = true;
actualReturn = addressAttribute.equals(target); actualReturn = addressAttribute.equals(target);
assertEquals(expectedReturn, actualReturn, assertEquals(
"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(
@ -457,8 +461,8 @@ public class AddressAttributeTest
expectedReturn = true; expectedReturn = true;
actualReturn = addressAttribute.equals(target); actualReturn = addressAttribute.equals(target);
assertEquals(expectedReturn, actualReturn, assertEquals("AddressAttribute.equals() failed for IPv6 addresses.",
"AddressAttribute.equals() failed for IPv6 addresses."); expectedReturn, actualReturn);
} }
/** /**
@ -466,7 +470,6 @@ public class AddressAttributeTest
* *
* @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
{ {
@ -479,8 +482,8 @@ public class AddressAttributeTest
char actualReturn = addressAttribute.getDataLength(); char actualReturn = addressAttribute.getDataLength();
assertEquals(expectedReturn, actualReturn, assertEquals("Datalength is not propoerly calculated",
"Datalength is not propoerly calculated"); expectedReturn, actualReturn);
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(
@ -489,8 +492,8 @@ public class AddressAttributeTest
actualReturn = addressAttribute.getDataLength(); actualReturn = addressAttribute.getDataLength();
assertEquals(expectedReturn, actualReturn, assertEquals("Datalength is not propoerly calculated",
"Datalength is not propoerly calculated"); expectedReturn, actualReturn);
} }
/** /**
@ -498,7 +501,6 @@ public class AddressAttributeTest
* *
* @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
{ {
@ -507,8 +509,8 @@ public class AddressAttributeTest
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(expectedReturn, actualReturn, assertEquals("Address family was not 1 for an IPv4",
"Address family was not 1 for an IPv4"); expectedReturn, actualReturn);
//ipv6 //ipv6
expectedReturn = 2; expectedReturn = 2;
@ -516,7 +518,9 @@ public class AddressAttributeTest
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(expectedReturn, actualReturn, assertEquals("Address family was not 2 for an IPv6 address",
"Address family was not 2 for an IPv6 address"); expectedReturn, actualReturn);
} }
} }

View File

@ -17,23 +17,28 @@
*/ */
package org.ice4j.attribute; package org.ice4j.attribute;
import org.ice4j.*; import org.ice4j.*;
import static org.junit.jupiter.api.Assertions.*; import junit.framework.*;
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 { public class AttributeDecoderTest extends TestCase
{
private MsgFixture msgFixture; private MsgFixture msgFixture;
private byte[] expectedAttributeValue = null; private byte[] expectedAttributeValue = null;
@BeforeEach public AttributeDecoderTest(String name)
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
@ -43,15 +48,18 @@ public class AttributeDecoderTest {
System.arraycopy(msgFixture.unknownOptionalAttribute, offset, System.arraycopy(msgFixture.unknownOptionalAttribute, offset,
expectedAttributeValue, 0, expectedAttributeValue, 0,
expectedAttributeValue.length); expectedAttributeValue.length);
msgFixture.setUp();
} }
@AfterEach protected void tearDown() throws Exception
public void tearDown() throws Exception
{ {
msgFixture.tearDown();
msgFixture = null; msgFixture = null;
super.tearDown();
} }
@Test
public void testDecodeMappedAddress() public void testDecodeMappedAddress()
throws Exception throws Exception
{ {
@ -71,11 +79,11 @@ public class AttributeDecoderTest {
Attribute actualReturn = AttributeDecoder.decode( Attribute actualReturn = AttributeDecoder.decode(
bytes, offset, length); bytes, offset, length);
assertEquals(expectedReturn, actualReturn, assertEquals(
"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
{ {
@ -96,12 +104,10 @@ public class AttributeDecoderTest {
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 testDecodeChangeRequest() public void testDecodeChangeRequest()
throws Exception throws Exception
{ {
@ -117,12 +123,11 @@ public class AttributeDecoderTest {
Attribute actualReturn = AttributeDecoder.decode( Attribute actualReturn = AttributeDecoder.decode(
bytes, offset, length); bytes, offset, length);
assertEquals(expectedReturn, actualReturn, assertEquals("AttributeDecoder.decode() failed for a CHANGE-REQUEST attribute",
"AttributeDecoder.decode() failed for a CHANGE-REQUEST attribute" expectedReturn, actualReturn);
);
} }
@Test
public void testDecodeErrorCode() public void testDecodeErrorCode()
throws Exception throws Exception
{ {
@ -139,11 +144,12 @@ public class AttributeDecoderTest {
Attribute actualReturn = AttributeDecoder.decode( Attribute actualReturn = AttributeDecoder.decode(
bytes, offset, length); bytes, offset, length);
assertEquals(expectedReturn, actualReturn, assertEquals(
"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
{ {
@ -162,11 +168,12 @@ public class AttributeDecoderTest {
Attribute actualReturn = AttributeDecoder.decode( Attribute actualReturn = AttributeDecoder.decode(
bytes, offset, length); bytes, offset, length);
assertEquals(expectedReturn, actualReturn, assertEquals(
"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
{ {
@ -183,8 +190,9 @@ public class AttributeDecoderTest {
Attribute actualReturn = AttributeDecoder.decode( Attribute actualReturn = AttributeDecoder.decode(
bytes, offset, length); bytes, offset, length);
assertEquals(expectedReturn, actualReturn, assertEquals(
"AttributeDecoder.decode() failed for a UNKNOWN_OPTIONAL attribute"); "AttributeDecoder.decode() failed for a UNKNOWN_OPTIONAL attribute",
expectedReturn, actualReturn);
} }
} }

View File

@ -17,47 +17,57 @@
*/ */
package org.ice4j.attribute; package org.ice4j.attribute;
import static org.junit.jupiter.api.Assertions.*; import junit.framework.*;
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 public class ChangeRequestAttributeTest extends TestCase
{ {
private ChangeRequestAttribute changeRequestAttribute = null; private ChangeRequestAttribute changeRequestAttribute = null;
private MsgFixture binMessagesFixture; private MsgFixture binMessagesFixture;
@BeforeEach public ChangeRequestAttributeTest(String name)
public void setUp() throws Exception
{ {
changeRequestAttribute = new ChangeRequestAttribute(); super(name);
binMessagesFixture = new MsgFixture();
} }
@AfterEach protected void setUp() throws Exception
public void tearDown() throws Exception {
super.setUp();
changeRequestAttribute = new ChangeRequestAttribute();
binMessagesFixture = new MsgFixture();
binMessagesFixture.setUp();
}
protected 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."
);
} }
@ -66,7 +76,6 @@ public class ChangeRequestAttributeTest
* *
* @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
{ {
@ -75,39 +84,34 @@ public class ChangeRequestAttributeTest
char length = (char)(attributeValue.length - offset); char length = (char)(attributeValue.length - offset);
changeRequestAttribute.decodeAttributeBody(attributeValue, offset, length); changeRequestAttribute.decodeAttributeBody(attributeValue, offset, length);
assertEquals( assertEquals("decodeAttributeBody() did not properly decode the changeIpFlag",
MsgFixture.CHANGE_IP_FLAG_1, MsgFixture.CHANGE_IP_FLAG_1,
changeRequestAttribute.getChangeIpFlag(), changeRequestAttribute.getChangeIpFlag()
"decodeAttributeBody() did not properly decode the changeIpFlag"
); );
assertEquals( assertEquals("decodeAttributeBody() did not properly decode the changePortFlag",
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 changeRequestAttribute.decodeAttributeBody(attributeValue, offset, length);
.decodeAttributeBody(attributeValue, offset, length); assertEquals("decodeAttributeBody() did not properly decode the changeIpFlag",
assertEquals(
MsgFixture.CHANGE_IP_FLAG_2, MsgFixture.CHANGE_IP_FLAG_2,
changeRequestAttribute.getChangeIpFlag(), changeRequestAttribute.getChangeIpFlag()
"decodeAttributeBody() did not properly decode the changeIpFlag"
); );
assertEquals( assertEquals("decodeAttributeBody() did not properly decode the changePortFlag",
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;
@ -118,8 +122,8 @@ public class ChangeRequestAttributeTest
changeRequestAttribute.setChangePortFlag(MsgFixture.CHANGE_PORT_FLAG_1); changeRequestAttribute.setChangePortFlag(MsgFixture.CHANGE_PORT_FLAG_1);
byte[] actualReturn = changeRequestAttribute.encode(); byte[] actualReturn = changeRequestAttribute.encode();
assertArrayEquals(expectedReturn, actualReturn, assertTrue("Object did not encode properly.",
"Object did not encode properly."); Arrays.equals(expectedReturn, actualReturn));
//2nd test //2nd test
expectedReturn = binMessagesFixture.chngReqTestValue2; expectedReturn = binMessagesFixture.chngReqTestValue2;
@ -129,22 +133,27 @@ public class ChangeRequestAttributeTest
changeRequestAttribute.setChangePortFlag(MsgFixture.CHANGE_PORT_FLAG_2); changeRequestAttribute.setChangePortFlag(MsgFixture.CHANGE_PORT_FLAG_2);
actualReturn = changeRequestAttribute.encode(); actualReturn = changeRequestAttribute.encode();
assertArrayEquals(expectedReturn, actualReturn, assertTrue("Object did not encode properly.",
"Object did not encode properly."); Arrays.equals(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 testEquals() public void testEquals()
{ {
ChangeRequestAttribute target = null;
boolean expectedReturn = false;
//null test //null test
assertNotEquals(changeRequestAttribute, null); boolean actualReturn = changeRequestAttribute.equals(target);
assertEquals("Null value test failed", expectedReturn, actualReturn);
//test against a different object. //test against a different object.
ChangeRequestAttribute target = new ChangeRequestAttribute(); target = new ChangeRequestAttribute();
changeRequestAttribute.setChangeIpFlag(true); changeRequestAttribute.setChangeIpFlag(true);
changeRequestAttribute.setChangePortFlag(false); changeRequestAttribute.setChangePortFlag(false);
@ -152,7 +161,9 @@ public class ChangeRequestAttributeTest
target.setChangeIpFlag(false); target.setChangeIpFlag(false);
target.setChangePortFlag(true); target.setChangePortFlag(true);
assertNotEquals(changeRequestAttribute, target); actualReturn = changeRequestAttribute.equals(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();
@ -162,27 +173,33 @@ public class ChangeRequestAttributeTest
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(expectedReturn, actualReturn, assertEquals("data length returned an invalid value",
"data length returned an invalid value"); expectedReturn, actualReturn);
} }
/** /**
* Test whether we get a relevant name. * Test whether we get a relevant name.
*/ */
@Test
public void testGetName() public void testGetName()
{ {
assertEquals("CHANGE-REQUEST", changeRequestAttribute.getName()); String expectedReturn = "CHANGE-REQUEST";
String actualReturn = changeRequestAttribute.getName();
assertEquals("Invalid name", expectedReturn, actualReturn);
} }
} }

View File

@ -19,9 +19,10 @@ package org.ice4j.attribute;
import org.ice4j.*; import org.ice4j.*;
import static org.junit.jupiter.api.Assertions.*; import java.util.*;
import junit.framework.*;
import org.junit.jupiter.api.*;
/** /**
* Class to test the ConnectionIdAttribute class. * Class to test the ConnectionIdAttribute class.
* *
@ -29,86 +30,108 @@ import org.junit.jupiter.api.*;
* *
*/ */
public class ConnectionIdAttributeTest public class ConnectionIdAttributeTest
extends TestCase
{ {
private ConnectionIdAttribute connectionIdAttribute = null; private ConnectionIdAttribute connectionIdAttribute = null;
private MsgFixture msgFixture; private MsgFixture msgFixture;
@BeforeEach @Override
public void setUp() throws Exception protected void setUp() throws Exception
{ {
super.setUp();
this.connectionIdAttribute = new ConnectionIdAttribute(); this.connectionIdAttribute = new ConnectionIdAttribute();
this.msgFixture = new MsgFixture(); this.msgFixture = new MsgFixture();
msgFixture.setUp();
} }
@AfterEach @Override
public void tearDown() throws Exception protected 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(expectedReturn, actualReturn, assertEquals(
"Datalength is not properly calculated"); "Datalength is not properly calculated", expectedReturn,
actualReturn);
} }
/** /**
* Tests getting the name. * Tests getting the name.
*/ */
@Test
public void testGetName() public void testGetName()
{ {
assertEquals("CONNECTION-ID", connectionIdAttribute.getName()); String expectedReturn = "CONNECTION-ID";
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
assertNotEquals(connectionIdAttribute, null); ConnectionIdAttribute target = null;
boolean expectedReturn = false;
boolean actualReturn = connectionIdAttribute.equals(target);
assertEquals(
"ConnectionIdAttribute.equals() failed against a null target.",
expectedReturn, actualReturn);
// difference test // difference test
ConnectionIdAttribute target = new 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);
assertNotEquals(connectionIdAttribute, target, expectedReturn = false;
"ConnectionIdAttribute.equals() failed against a different target."); actualReturn = connectionIdAttribute.equals(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,
"ConnectionIdAttribute.equals() failed against an equal target."); expectedReturn = true;
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();
assertArrayEquals(expectedReturn, actualReturn, assertTrue(
"ConnectionIdAttribute.encode() did not properly encode a sample attribute"); "ConnectionIdAttribute.encode() did not "
+ "properly encode a sample attribute", Arrays.equals(
expectedReturn, actualReturn));
} }
/** /**
@ -117,7 +140,6 @@ 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;
@ -128,31 +150,31 @@ public class ConnectionIdAttributeTest
attributeValue, offset, length); attributeValue, offset, length);
assertEquals( assertEquals(
MsgFixture.CONNECTION_ID, "ConnectionIdAttribute.decode() did not properly decode the "
connectionIdAttribute.getConnectionIdValue(), + "connection id field.", MsgFixture.CONNECTION_ID,
"ConnectionIdAttribute.decode() did not properly decode the connection id field." connectionIdAttribute.getConnectionIdValue());
);
} }
/** /**
* 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(expectedReturn, actualReturn, assertEquals(
"ConnectionId is not properly calculated"); "ConnectionId is not properly calculated", expectedReturn,
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(expectedReturn, actualReturn, assertEquals(
"ConnectionId is not properly calculated"); "ConnectionId is not properly calculated", expectedReturn,
actualReturn);
} }
} }

View File

@ -17,44 +17,51 @@
*/ */
package org.ice4j.attribute; package org.ice4j.attribute;
import static org.junit.jupiter.api.Assertions.*; import junit.framework.*;
import java.util.Arrays;
import org.ice4j.*; import org.ice4j.*;
import org.junit.jupiter.api.*;
/** /**
* *
* @author Emil Ivov * @author Emil Ivov
*/ */
public class ErrorCodeAttributeTest public class ErrorCodeAttributeTest extends TestCase {
{
private ErrorCodeAttribute errorCodeAttribute = null; private ErrorCodeAttribute errorCodeAttribute = null;
private MsgFixture msgFixture; private MsgFixture msgFixture;
@BeforeEach public ErrorCodeAttributeTest(String name) {
public void setUp() throws Exception super(name);
{
errorCodeAttribute = new ErrorCodeAttribute();
msgFixture = new MsgFixture();
} }
@AfterEach protected void setUp() throws Exception {
public void tearDown() throws Exception { super.setUp();
errorCodeAttribute = new ErrorCodeAttribute();
msgFixture = new MsgFixture();
msgFixture.setUp();
}
protected 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"
);
} }
/** /**
@ -62,7 +69,6 @@ public class ErrorCodeAttributeTest
* *
* @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;
@ -70,22 +76,18 @@ public class ErrorCodeAttributeTest
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( assertEquals("Error Class was not correctly decoded",
MsgFixture.ERROR_CLASS, MsgFixture.ERROR_CLASS,
errorCodeAttribute.getErrorClass(), errorCodeAttribute.getErrorClass());
"Error Class was not correctly decoded"
);
assertEquals( assertEquals("Error Number was not correctly decoded",
MsgFixture.ERROR_NUMBER, MsgFixture.ERROR_NUMBER,
errorCodeAttribute.getErrorNumber(), errorCodeAttribute.getErrorNumber());
"Error Number was not correctly decoded"
);
assertEquals( assertEquals("Reason phrase was not correctly decoded",
MsgFixture.REASON_PHRASE.trim(), MsgFixture.REASON_PHRASE.trim(),
errorCodeAttribute.getReasonPhrase().trim(), errorCodeAttribute.getReasonPhrase().trim());
"Reason phrase was not correctly decoded");
} }
/** /**
@ -94,7 +96,6 @@ public class ErrorCodeAttributeTest
* *
* @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
{ {
@ -107,8 +108,8 @@ public class ErrorCodeAttributeTest
byte[] actualReturn = errorCodeAttribute.encode(); byte[] actualReturn = errorCodeAttribute.encode();
assertArrayEquals(expectedReturn, actualReturn, assertTrue("encode() did not return the expected binary array.",
"encode() did not return the expected binary array."); Arrays.equals( expectedReturn, actualReturn));
} }
/** /**
@ -117,17 +118,20 @@ public class ErrorCodeAttributeTest
* *
* @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
assertNotEquals(errorCodeAttribute, null, ErrorCodeAttribute target = null;
"equals() failed against a null value target."); boolean expectedReturn = false;
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);
@ -135,12 +139,14 @@ public class ErrorCodeAttributeTest
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));
assertNotEquals(errorCodeAttribute, target, actualReturn = errorCodeAttribute.equals(target);
"equals() failed against a not equal target."); assertEquals("equals() failed against a not equal target.",
expectedReturn, actualReturn);
//equal objects //different 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);
@ -148,8 +154,11 @@ public class ErrorCodeAttributeTest
errorCodeAttribute.setErrorClass(MsgFixture.ERROR_CLASS); errorCodeAttribute.setErrorClass(MsgFixture.ERROR_CLASS);
errorCodeAttribute.setErrorNumber(MsgFixture.ERROR_NUMBER); errorCodeAttribute.setErrorNumber(MsgFixture.ERROR_NUMBER);
assertEquals(errorCodeAttribute, target, actualReturn = errorCodeAttribute.equals(target);
"equals() failed against an equal target."); assertEquals("equals() failed against a not equal target.",
expectedReturn, actualReturn);
} }
/** /**
@ -157,7 +166,6 @@ public class ErrorCodeAttributeTest
* *
* @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
{ {
@ -169,14 +177,16 @@ public class ErrorCodeAttributeTest
errorCodeAttribute.setReasonPhrase(MsgFixture.REASON_PHRASE); errorCodeAttribute.setReasonPhrase(MsgFixture.REASON_PHRASE);
char actualReturn = errorCodeAttribute.getDataLength(); char actualReturn = errorCodeAttribute.getDataLength();
assertEquals(expectedReturn, actualReturn, "data length1"); assertEquals("data length1", 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
*/ */
@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);
@ -185,36 +195,35 @@ public class ErrorCodeAttributeTest
errorCodeAttribute.setErrorNumber(MsgFixture.ERROR_NUMBER); errorCodeAttribute.setErrorNumber(MsgFixture.ERROR_NUMBER);
char actualReturn = errorCodeAttribute.getErrorCode(); char actualReturn = errorCodeAttribute.getErrorCode();
assertEquals(expectedReturn, actualReturn); assertEquals("return value", 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() {
assertEquals("ERROR-CODE", errorCodeAttribute.getName()); String expectedReturn = "ERROR-CODE";
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
*/ */
@Test public void testSetErrorCode() throws StunException {
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( assertEquals("An error class was not properly set after decoding an error code.",
MsgFixture.ERROR_CLASS, (int)MsgFixture.ERROR_CLASS,
(int) errorCodeAttribute.getErrorClass(), (int)errorCodeAttribute.getErrorClass());
"An error class was not properly set after decoding an error code." assertEquals("An error number was not properly set after decoding an error code.",
); (int)MsgFixture.ERROR_NUMBER,
assertEquals( (int)errorCodeAttribute.getErrorNumber());
MsgFixture.ERROR_NUMBER,
(int) errorCodeAttribute.getErrorNumber(),
"An error number was not properly set after decoding an error code."
);
} }
} }

View File

@ -17,17 +17,19 @@
*/ */
package org.ice4j.attribute; package org.ice4j.attribute;
import static org.junit.jupiter.api.Assertions.*; import junit.framework.*;
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 public class NonceAttributeTest extends TestCase
{ {
private NonceAttribute nonceAttribute = null; private NonceAttribute nonceAttribute = null;
MsgFixture msgFixture = null; MsgFixture msgFixture = null;
@ -38,26 +40,30 @@ public class NonceAttributeTest
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'};
@BeforeEach protected void setUp() throws Exception
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();
} }
@AfterEach protected void tearDown() throws Exception
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;
@ -66,63 +72,63 @@ public class NonceAttributeTest
decoded.decodeAttributeBody(nonceValue.getBytes(), offset, length); decoded.decodeAttributeBody(nonceValue.getBytes(), offset, length);
//nonce value //nonce value
assertEquals(nonceAttribute, decoded, "decode failed"); assertEquals( "decode failed", nonceAttribute, decoded);
} }
/** /**
* Tests the encode method * Tests the encode method
*/ */
@Test
public void testEncode() public void testEncode()
{ {
assertArrayEquals(nonceAttribute.encode(), attributeBinValue, assertTrue("encode failed",
"encode failed"); Arrays.equals(nonceAttribute.encode(),
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(nonceAttribute, nonceAttribute2); assertEquals("testequals failed", 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
assertNotEquals(nonceAttribute2, nonceAttribute); assertFalse("testequals failed",
nonceAttribute.equals(nonceAttribute2));
//test null equals //test null equals
assertNotEquals(nonceAttribute, null); assertFalse("testequals failed",
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(expectedReturn, actualReturn); assertEquals("getDataLength - failed", expectedReturn, actualReturn);
} }
/** /**
* Tests getting the name * Tests getting the name
*/ */
@Test
public void testGetName() public void testGetName()
{ {
assertEquals("NONCE", nonceAttribute.getName()); String expectedReturn = "NONCE";
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();
@ -131,7 +137,8 @@ public class NonceAttributeTest
att.setNonce(expectedReturn); att.setNonce(expectedReturn);
byte[] actualReturn = att.getNonce(); byte[] actualReturn = att.getNonce();
assertArrayEquals(expectedReturn, actualReturn, assertTrue("nonce setter or getter failed",
"nonce setter or getter failed"); Arrays.equals( expectedReturn,
actualReturn));
} }
} }

View File

@ -17,22 +17,25 @@
*/ */
package org.ice4j.attribute; package org.ice4j.attribute;
import static org.junit.jupiter.api.Assertions.*; import junit.framework.*;
import java.util.Arrays;
import org.ice4j.*; import org.ice4j.*;
import org.junit.jupiter.api.*;
/** /**
* @author Emil Ivov * @author Emil Ivov
*/ */
public class OptionalAttributeAttributeTest public class OptionalAttributeAttributeTest extends TestCase
{ {
private OptionalAttribute optionalAttribute = null; private OptionalAttribute optionalAttribute = null;
private MsgFixture msgFixture = null; private MsgFixture msgFixture = null;
byte[] expectedAttributeValue = null; byte[] expectedAttributeValue = null;
@BeforeEach protected void setUp() throws Exception
public void setUp() throws Exception
{ {
super.setUp();
msgFixture = new MsgFixture(); msgFixture = new MsgFixture();
int offset = Attribute.HEADER_LENGTH; int offset = Attribute.HEADER_LENGTH;
@ -48,18 +51,17 @@ public class OptionalAttributeAttributeTest
msgFixture.optionalAttributeType); msgFixture.optionalAttributeType);
} }
@AfterEach protected void tearDown() throws Exception
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;
@ -68,52 +70,60 @@ public class OptionalAttributeAttributeTest
optionalAttribute.decodeAttributeBody(msgFixture.unknownOptionalAttribute, optionalAttribute.decodeAttributeBody(msgFixture.unknownOptionalAttribute,
offset, length); offset, length);
assertArrayEquals(
expectedAttributeValue, optionalAttribute.getBody(),
"OptionalAttribute did not decode properly.");
assertEquals(length, optionalAttribute.getDataLength(), assertTrue("OptionalAttribute did not decode properly.",
"Length was not properly decoded"); Arrays.equals( expectedAttributeValue,
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);
assertNotEquals(optionalAttribute, null); boolean actualReturn = optionalAttribute.equals(obj);
assertEquals("failed null comparison", expectedReturn, actualReturn);
//wrong type comparison //wrong type comparison
assertNotEquals(optionalAttribute, "hehe :)"); obj = "hehe :)";
actualReturn = optionalAttribute.equals(obj);
assertEquals("failed wrong type comparison", expectedReturn,
actualReturn);
//succesful comparison //succesful comparison
OptionalAttribute obj = obj = new OptionalAttribute(msgFixture.optionalAttributeType);
new OptionalAttribute(msgFixture.optionalAttributeType);
obj.setBody( expectedAttributeValue, 0, ((OptionalAttribute)obj).setBody( expectedAttributeValue, 0,
expectedAttributeValue.length); expectedAttributeValue.length);
assertEquals(obj, optionalAttribute); expectedReturn = true;
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;
@ -122,7 +132,7 @@ public class OptionalAttributeAttributeTest
expectedAttributeValue.length); expectedAttributeValue.length);
char actualReturn = optionalAttribute.getDataLength(); char actualReturn = optionalAttribute.getDataLength();
assertEquals(expectedReturn, actualReturn); assertEquals("return value", expectedReturn, actualReturn);
} }
} }

View File

@ -17,17 +17,19 @@
*/ */
package org.ice4j.attribute; package org.ice4j.attribute;
import static org.junit.jupiter.api.Assertions.*; import junit.framework.*;
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 public class RealmAttributeTest extends TestCase
{ {
private RealmAttribute realmAttribute = null; private RealmAttribute realmAttribute = null;
MsgFixture msgFixture = null; MsgFixture msgFixture = null;
@ -38,27 +40,30 @@ public class RealmAttributeTest
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};
@BeforeEach protected void setUp() throws Exception
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();
} }
@AfterEach protected void tearDown() throws Exception
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;
@ -67,62 +72,63 @@ public class RealmAttributeTest
decoded.decodeAttributeBody(realmValue.getBytes(), offset, length); decoded.decodeAttributeBody(realmValue.getBytes(), offset, length);
//realm value //realm value
assertEquals(realmAttribute, decoded); assertEquals( "decode failed", realmAttribute, decoded);
} }
/** /**
* Tests the encode method * Tests the encode method
*/ */
@Test
public void testEncode() public void testEncode()
{ {
assertArrayEquals(realmAttribute.encode(), attributeBinValue); assertTrue("encode failed",
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(realmAttribute, realmAttribute2); assertEquals("testequals failed", 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
assertNotEquals(realmAttribute2, realmAttribute); assertFalse("testequals failed",
realmAttribute.equals(realmAttribute2));
//test null equals //test null equals
assertNotEquals(realmAttribute, null); assertFalse("testequals failed",
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(expectedReturn, actualReturn); assertEquals("getDataLength - failed", expectedReturn, actualReturn);
} }
/** /**
* Tests getting the name * Tests getting the name
*/ */
@Test
public void testGetName() public void testGetName()
{ {
assertEquals("REALM", realmAttribute.getName()); String expectedReturn = "REALM";
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();
@ -131,7 +137,8 @@ public class RealmAttributeTest
att.setRealm(expectedReturn); att.setRealm(expectedReturn);
byte[] actualReturn = att.getRealm(); byte[] actualReturn = att.getRealm();
assertArrayEquals(expectedReturn, actualReturn, assertTrue("realm setter or getter failed",
"realm setter or getter failed"); Arrays.equals( expectedReturn,
actualReturn));
} }
} }

View File

@ -17,10 +17,12 @@
*/ */
package org.ice4j.attribute; package org.ice4j.attribute;
import static org.junit.jupiter.api.Assertions.*; import java.util.*;
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.
* *
@ -28,31 +30,42 @@ import org.junit.jupiter.api.*;
* *
*/ */
public class RequestedAddressFamilyAttributeTest public class RequestedAddressFamilyAttributeTest
extends TestCase
{ {
private RequestedAddressFamilyAttribute requestedAddressFamilyAttribute = private RequestedAddressFamilyAttribute requestedAddressFamilyAttribute =
null; null;
private MsgFixture msgFixture; private MsgFixture msgFixture;
@BeforeEach @Override
public void setUp() throws Exception protected void setUp() throws Exception
{ {
super.setUp();
this.requestedAddressFamilyAttribute = this.requestedAddressFamilyAttribute =
new RequestedAddressFamilyAttribute(); new RequestedAddressFamilyAttribute();
this.msgFixture = new MsgFixture(); this.msgFixture = new MsgFixture();
msgFixture.setUp();
} }
@AfterEach public RequestedAddressFamilyAttributeTest(String name)
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;
@ -60,39 +73,47 @@ 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(expectedReturn, actualReturn, assertEquals(
"Datalength is not properly calculated"); "Datalength is not properly calculated", expectedReturn,
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(expectedReturn, actualReturn, assertEquals(
"Datalength is not properly calculated"); "Datalength is not properly calculated", expectedReturn,
actualReturn);
} }
/** /**
* Tests getting the name. * Tests getting the name.
*/ */
@Test
public void testGetName() public void testGetName()
{ {
assertEquals("REQUESTED-ADDRESS-FAMILY", requestedAddressFamilyAttribute.getName()); String expectedReturn = "REQUESTED-ADDRESS-FAMILY";
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
assertNotEquals(requestedAddressFamilyAttribute, null); RequestedAddressFamilyAttribute target = 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;
@ -101,12 +122,20 @@ public class RequestedAddressFamilyAttributeTest
requestedAddressFamilyAttribute requestedAddressFamilyAttribute
.setFamily(MsgFixture.REQUESTED_ADDRESS_FAMILY_ATTRIBUTE_V4); .setFamily(MsgFixture.REQUESTED_ADDRESS_FAMILY_ATTRIBUTE_V4);
assertNotEquals(requestedAddressFamilyAttribute, target); expectedReturn = false;
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);
assertEquals(requestedAddressFamilyAttribute, target); expectedReturn = true;
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);
@ -114,7 +143,11 @@ public class RequestedAddressFamilyAttributeTest
requestedAddressFamilyAttribute requestedAddressFamilyAttribute
.setFamily(MsgFixture.REQUESTED_ADDRESS_FAMILY_ATTRIBUTE_V6); .setFamily(MsgFixture.REQUESTED_ADDRESS_FAMILY_ATTRIBUTE_V6);
assertEquals(requestedAddressFamilyAttribute, target); expectedReturn = true;
actualReturn = requestedAddressFamilyAttribute.equals(target);
assertEquals(
"RequestedAddressFamilyAttribute.equals() failed for IPv6 address.",
expectedReturn, actualReturn);
} }
/** /**
@ -123,7 +156,6 @@ 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;
@ -134,10 +166,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."
);
} }
/** /**
@ -146,7 +178,6 @@ 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;
@ -157,62 +188,63 @@ 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();
assertArrayEquals( assertTrue(
expectedReturn, actualReturn, "RequestedAddressFamilyAttribute.encode() did not "
"RequestedAddressFamilyAttribute.encode() did not properly encode a sample attribute for IPv4 family" + "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();
assertArrayEquals( assertTrue(
expectedReturn, actualReturn, "RequestedAddressFamilyAttribute.encode() did not "
"RequestedAddressFamilyAttribute.encode() did not properly encode a sample attribute for IPv6 family" + "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(expectedReturn, actualReturn, assertEquals(
"Family is not properly calculated"); "Family is not properly calculated", expectedReturn,
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(expectedReturn, actualReturn, assertEquals(
"Family is not properly calculated"); "Family is not properly calculated", expectedReturn,
actualReturn);
} }
} }

View File

@ -17,16 +17,18 @@
*/ */
package org.ice4j.attribute; package org.ice4j.attribute;
import static org.junit.jupiter.api.Assertions.*; import junit.framework.*;
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 public class SoftwareAttributeTest extends TestCase
{ {
private SoftwareAttribute softwareAttribute = null; private SoftwareAttribute softwareAttribute = null;
MsgFixture msgFixture = null; MsgFixture msgFixture = null;
@ -38,27 +40,30 @@ public class SoftwareAttributeTest
'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};
@BeforeEach protected void setUp() throws Exception
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();
} }
@AfterEach protected void tearDown() throws Exception
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;
@ -67,62 +72,63 @@ public class SoftwareAttributeTest
decoded.decodeAttributeBody(softwareValue.getBytes(), offset, length); decoded.decodeAttributeBody(softwareValue.getBytes(), offset, length);
//software value //software value
assertEquals(softwareAttribute, decoded); assertEquals( "decode failed", softwareAttribute, decoded);
} }
/** /**
* Tests the encode method * Tests the encode method
*/ */
@Test
public void testEncode() public void testEncode()
{ {
assertArrayEquals(softwareAttribute.encode(), attributeBinValue); assertTrue("encode failed",
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(softwareAttribute, softwareAttribute2); assertEquals("testequals failed", 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
assertNotEquals(softwareAttribute2, softwareAttribute); assertFalse("testequals failed",
softwareAttribute.equals(softwareAttribute2));
//test null equals //test null equals
assertNotEquals(softwareAttribute, null); assertFalse("testequals failed",
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(expectedReturn, actualReturn); assertEquals("getDataLength - failed", expectedReturn, actualReturn);
} }
/** /**
* Tests getting the name * Tests getting the name
*/ */
@Test
public void testGetName() public void testGetName()
{ {
assertEquals("SOFTWARE", softwareAttribute.getName()); String expectedReturn = "SOFTWARE";
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();
@ -131,7 +137,8 @@ public class SoftwareAttributeTest
att.setSoftware(expectedReturn); att.setSoftware(expectedReturn);
byte[] actualReturn = att.getSoftware(); byte[] actualReturn = att.getSoftware();
assertArrayEquals(expectedReturn, actualReturn, assertTrue("software setter or getter failed",
"software setter or getter failed"); Arrays.equals( expectedReturn,
actualReturn));
} }
} }

View File

@ -17,48 +17,57 @@
*/ */
package org.ice4j.attribute; package org.ice4j.attribute;
import static org.junit.jupiter.api.Assertions.*; import junit.framework.*;
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 public class UnknownAttributesAttributeTest extends TestCase
{ {
private UnknownAttributesAttribute unknownAttributesAttribute = null; private UnknownAttributesAttribute unknownAttributesAttribute = null;
private MsgFixture binMessagesFixture; private MsgFixture binMessagesFixture;
@BeforeEach public UnknownAttributesAttributeTest(String name)
public void setUp() throws Exception
{ {
unknownAttributesAttribute = new UnknownAttributesAttribute(); super(name);
binMessagesFixture = new MsgFixture();
} }
@AfterEach protected void setUp() throws Exception
public void tearDown() throws Exception {
super.setUp();
unknownAttributesAttribute = new UnknownAttributesAttribute();
binMessagesFixture = new MsgFixture();
binMessagesFixture.setUp();
}
protected 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(
Attribute.UNKNOWN_ATTRIBUTES, assertEquals("UnknownAttributesAttribute() did not properly set the "
(int) unknownAttributesAttribute.getAttributeType(), +"Attribute's type field!",
"UnknownAttributesAttribute() did not properly set the Attribute's type field!" (int)Attribute.UNKNOWN_ATTRIBUTES,
(int)unknownAttributesAttribute.getAttributeType()
); );
} }
@ -67,40 +76,37 @@ public class UnknownAttributesAttributeTest
* 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( assertEquals("addAttributeID does not seem to properly add the attribute ID",
(int)attributeID, (int)attributeID,
(int) unknownAttributesAttribute.getAttribute(0), (int)unknownAttributesAttribute.getAttribute(0)
"addAttributeID does not seem to properly add the attribute ID"
); );
assertEquals( assertEquals("addAttributeID does not seem to properly add the attribute ID",
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( assertEquals("Adding a 2nd time the same attributeID should not change "
+"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:
@ -112,36 +118,30 @@ public class UnknownAttributesAttributeTest
- 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(
MsgFixture.UNKNOWN_ATTRIBUTES_CNT_DEC_TST, assertEquals("The decoded attribute contained "
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,7 +149,6 @@ public class UnknownAttributesAttributeTest
* 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;
@ -159,36 +158,46 @@ public class UnknownAttributesAttributeTest
unknownAttributesAttribute.addAttributeID( unknownAttributesAttribute.addAttributeID(
MsgFixture.UNKNOWN_ATTRIBUTES_2ND_ATT); MsgFixture.UNKNOWN_ATTRIBUTES_2ND_ATT);
byte[] actualReturn = unknownAttributesAttribute.encode(); byte[] actualReturn = unknownAttributesAttribute.encode();
assertArrayEquals(actualReturn, expectedReturn); assertTrue("UnknownAttributesAttribute did not encode properly.",
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();
assertNotEquals(unknownAttributesAttribute, null); boolean expectedReturn = false;
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);
assertNotEquals(unknownAttributesAttribute, target); actualReturn = unknownAttributesAttribute.equals(target);
assertEquals("Equals failed when comparing different objects.",
expectedReturn, actualReturn);
target.addAttributeID((char)26); target.addAttributeID((char)26);
assertEquals(unknownAttributesAttribute, target); expectedReturn = true;
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;
@ -203,15 +212,14 @@ public class UnknownAttributesAttributeTest
actualId1 = unknownAttributesAttribute.getAttribute(0); actualId1 = unknownAttributesAttribute.getAttribute(0);
actualId2 = unknownAttributesAttribute.getAttribute(1); actualId2 = unknownAttributesAttribute.getAttribute(1);
assertEquals(expectedId1, actualId1, "getAttribute() return value mismatch"); assertEquals("getAttribute() return value mismatch", expectedId1, actualId1);
assertEquals(expectedId2, actualId2, "getAttribute() return value mismatch"); assertEquals("getAttribute() return value mismatch", expectedId2, actualId2);
} }
/** /**
* 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;
@ -224,15 +232,14 @@ public class UnknownAttributesAttributeTest
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(expectedReturn, actualReturn, assertEquals("getAttributeCount did not return the expected value",
"getAttributeCount did not return the expected value"); expectedReturn, actualReturn);
} }
/** /**
* 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;
@ -249,8 +256,10 @@ public class UnknownAttributesAttributeTest
actualId1 = iterator.next(); actualId1 = iterator.next();
actualId2 = iterator.next(); actualId2 = iterator.next();
assertEquals(expectedId1, actualId1, "getAttributes() return value mismatch"); assertEquals("getAttributes() return value mismatch", expectedId1, actualId1);
assertEquals(expectedId2, actualId2, "getAttributes() return value mismatch"); assertEquals("getAttributes() return value mismatch", expectedId2, actualId2);
} }
/** /**
@ -258,7 +267,6 @@ public class UnknownAttributesAttributeTest
* 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;
@ -268,23 +276,25 @@ public class UnknownAttributesAttributeTest
unknownAttributesAttribute.addAttributeID((char)22); unknownAttributesAttribute.addAttributeID((char)22);
char actualReturn = unknownAttributesAttribute.getDataLength(); char actualReturn = unknownAttributesAttribute.getDataLength();
assertEquals(expectedReturn, actualReturn, assertEquals("Incorrect testGetDataLength() return value",
"Incorrect testGetDataLength() return value"); expectedReturn, actualReturn);
unknownAttributesAttribute.addAttributeID((char)23); unknownAttributesAttribute.addAttributeID((char)23);
actualReturn = unknownAttributesAttribute.getDataLength(); actualReturn = unknownAttributesAttribute.getDataLength();
assertEquals(expectedReturn, actualReturn, assertEquals("Incorrect testGetDataLength() return value",
"Incorrect testGetDataLength() return value"); expectedReturn, actualReturn);
} }
/** /**
* Tests whether getName returns a relevant name. * Tests whether getName returns a relevant name.
*/ */
@Test
public void testGetName() public void testGetName()
{ {
assertEquals("UNKNOWN-ATTRIBUTES", unknownAttributesAttribute.getName()); String expectedReturn = "UNKNOWN-ATTRIBUTES";
String actualReturn = unknownAttributesAttribute.getName();
assertEquals("getName() return", expectedReturn, actualReturn);
} }
} }

View File

@ -17,17 +17,19 @@
*/ */
package org.ice4j.attribute; package org.ice4j.attribute;
import static org.junit.jupiter.api.Assertions.*; import junit.framework.*;
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 public class UsernameAttributeTest extends TestCase
{ {
private UsernameAttribute usernameAttribute = null; private UsernameAttribute usernameAttribute = null;
MsgFixture msgFixture = null; MsgFixture msgFixture = null;
@ -38,27 +40,30 @@ public class UsernameAttributeTest
0, (byte)usernameValue.length(), 0, (byte)usernameValue.length(),
'u', 's', 'e', 'r', 'n', 'a', 'm','e'}; 'u', 's', 'e', 'r', 'n', 'a', 'm','e'};
@BeforeEach protected void setUp() throws Exception
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();
} }
@AfterEach protected void tearDown() throws Exception
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;
@ -67,62 +72,63 @@ public class UsernameAttributeTest
decoded.decodeAttributeBody(usernameValue.getBytes(), offset, length); decoded.decodeAttributeBody(usernameValue.getBytes(), offset, length);
//username value //username value
assertEquals(usernameAttribute, decoded); assertEquals( "decode failed", usernameAttribute, decoded);
} }
/** /**
* Tests the encode method * Tests the encode method
*/ */
@Test
public void testEncode() public void testEncode()
{ {
assertArrayEquals(usernameAttribute.encode(), attributeBinValue); assertTrue("encode failed",
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(usernameAttribute, usernameAttribute2); assertEquals("testequals failed", 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
assertNotEquals(usernameAttribute2, usernameAttribute); assertFalse("testequals failed",
usernameAttribute.equals(usernameAttribute2));
//test null equals //test null equals
assertNotEquals(usernameAttribute, null); assertFalse("testequals failed",
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(expectedReturn, actualReturn); assertEquals("getDataLength - failed", expectedReturn, actualReturn);
} }
/** /**
* Tests getting the name * Tests getting the name
*/ */
@Test
public void testGetName() public void testGetName()
{ {
assertEquals("USERNAME", usernameAttribute.getName()); String expectedReturn = "USERNAME";
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();
@ -131,7 +137,8 @@ public class UsernameAttributeTest
att.setUsername(expectedReturn); att.setUsername(expectedReturn);
byte[] actualReturn = att.getUsername(); byte[] actualReturn = att.getUsername();
assertArrayEquals(expectedReturn, actualReturn, assertTrue("username setter or getter failed",
"username setter or getter failed"); Arrays.equals( expectedReturn,
actualReturn));
} }
} }

View File

@ -17,30 +17,32 @@
*/ */
package org.ice4j.attribute; package org.ice4j.attribute;
import static org.junit.jupiter.api.Assertions.*; import junit.framework.*;
import java.util.*;
import org.ice4j.*; import org.ice4j.*;
import org.junit.jupiter.api.*;
/** /**
* @author Emil Ivov * @author Emil Ivov
*/ */
public class XorOnlyTest public class XorOnlyTest extends TestCase
{ {
private XorOnlyAttribute xorOnly = null; private XorOnlyAttribute xorOnly = null;
private MsgFixture msgFixture = null; private MsgFixture msgFixture = null;
@BeforeEach protected void setUp() throws Exception
public void setUp() throws Exception
{ {
super.setUp();
xorOnly = new XorOnlyAttribute(); xorOnly = new XorOnlyAttribute();
msgFixture = new MsgFixture(); msgFixture = new MsgFixture();
} }
@AfterEach protected void tearDown() throws Exception
public void tearDown() throws Exception
{ {
xorOnly = null; xorOnly = null;
msgFixture = null; msgFixture = null;
super.tearDown();
} }
/** /**
@ -48,7 +50,6 @@ public class XorOnlyTest
* 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[]{};
@ -60,52 +61,52 @@ public class XorOnlyTest
/** /**
* 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();
assertArrayEquals(expectedReturn, actualReturn); assertTrue("XorOnly failed to encode",
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(xorOnly, xor2); assertEquals("equals() failes for XorOnly", 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);
assertNotEquals(xorOnly, null); assertFalse("equals failed to see a difference", xorOnly.equals(maatt));
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(expectedReturn, actualReturn, "data length was not 0"); assertEquals("data length was not 0", expectedReturn, actualReturn);
} }
/** /**
* Verifies the name (do we really need this?). * Verifies the name (do we really need this?).
*/ */
@Test
public void testGetName() public void testGetName()
{ {
assertEquals("XOR-ONLY", xorOnly.getName()); String expectedReturn = "XOR-ONLY";
String actualReturn = xorOnly.getName();
assertEquals("Is name correct", expectedReturn, actualReturn);
} }
} }

View File

@ -17,42 +17,12 @@
*/ */
package org.ice4j.ice; package org.ice4j.ice;
import static org.junit.jupiter.api.Assertions.*; import static org.junit.Assert.*;
import org.junit.jupiter.api.*; import org.junit.*;
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()
{ {
@ -72,13 +42,6 @@ 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"));
} }
} }

View File

@ -1,196 +0,0 @@
/*
* 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));
}
}
}

View File

@ -17,12 +17,10 @@
*/ */
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}.
@ -36,8 +34,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 @Test( expected = java.net.BindException.class )
public void testRebindWithoutCloseThrows() throws Exception public void testRebindWithoutClose() 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 );
@ -46,7 +44,7 @@ public class SinglePortUdpHarvesterTest
{ {
firstHarvester = new SinglePortUdpHarvester( address ); firstHarvester = new SinglePortUdpHarvester( address );
} }
catch (BindException ex) catch ( java.net.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
@ -59,15 +57,12 @@ 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 )
{ {
@ -101,7 +96,7 @@ public class SinglePortUdpHarvesterTest
// Verify results. // Verify results.
catch ( BindException ex ) catch ( BindException ex )
{ {
fail( "A bind exception should not have been thrown, as the original harvester was properly closed."); Assert.fail( "A bind exception should not have been thrown, as the original harvester was propertly closed.");
} }
// Tear down. // Tear down.
@ -113,29 +108,4 @@ 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();
}
} }

View File

@ -17,15 +17,36 @@
*/ */
package org.ice4j.message; package org.ice4j.message;
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.junit.jupiter.api.*;
public class MessageFactoryTest public class MessageFactoryTest extends TestCase
{ {
@Test private MsgFixture msgFixture;
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;
@ -39,11 +60,10 @@ public class MessageFactoryTest
Message actualReturn Message actualReturn
= MessageFactory.createBindingErrorResponse(errorCode); = MessageFactory.createBindingErrorResponse(errorCode);
assertEquals(expectedReturn, actualReturn); assertEquals("return value", expectedReturn, actualReturn);
} }
@Test public void testCreateBindingErrorResponse1() throws StunException
public void testCreateBindingErrorResponse1()
{ {
char errorCode = 400; char errorCode = 400;
String reasonPhrase = "Bad Request"; String reasonPhrase = "Bad Request";
@ -57,10 +77,10 @@ public class MessageFactoryTest
Message actualReturn = MessageFactory Message actualReturn = MessageFactory
.createBindingErrorResponse(errorCode, reasonPhrase); .createBindingErrorResponse(errorCode, reasonPhrase);
assertEquals(expectedReturn, actualReturn); assertEquals("Failed to create an error code attribute.",
expectedReturn, actualReturn);
} }
@Test
public void testCreateBindingErrorResponseUnknownAttributes() public void testCreateBindingErrorResponseUnknownAttributes()
throws StunException throws StunException
{ {
@ -71,18 +91,17 @@ public class MessageFactoryTest
Response expectedReturn = new Response(); Response expectedReturn = new Response();
expectedReturn.setMessageType(Message.BINDING_ERROR_RESPONSE); expectedReturn.setMessageType(Message.BINDING_ERROR_RESPONSE);
ErrorCodeAttribute errorCodeAtt = AttributeFactory Attribute errorCodeAtt = AttributeFactory
.createErrorCodeAttribute(errorCode); .createErrorCodeAttribute(errorCode);
errorCodeAtt.setReasonPhrase( ((ErrorCodeAttribute)errorCodeAtt).setReasonPhrase(
ErrorCodeAttribute.getDefaultReasonPhrase(errorCode)); ErrorCodeAttribute.getDefaultReasonPhrase(errorCode));
expectedReturn.putAttribute(errorCodeAtt); expectedReturn.putAttribute(errorCodeAtt);
UnknownAttributesAttribute unknownAtts = UnknownAttributesAttribute unknownAtts =
AttributeFactory.createUnknownAttributesAttribute(); AttributeFactory.createUnknownAttributesAttribute();
for (char unknownAttribute : unknownAttributes) for (int i = 0; i < unknownAttributes.length; i++) {
{ unknownAtts.addAttributeID(unknownAttributes[i]);
unknownAtts.addAttributeID(unknownAttribute);
} }
expectedReturn.putAttribute(unknownAtts); expectedReturn.putAttribute(unknownAtts);
@ -90,10 +109,9 @@ public class MessageFactoryTest
Message actualReturn = MessageFactory Message actualReturn = MessageFactory
.createBindingErrorResponseUnknownAttributes(unknownAttributes); .createBindingErrorResponseUnknownAttributes(unknownAttributes);
//compare //compare
assertEquals(expectedReturn, actualReturn); assertEquals("return value", expectedReturn, actualReturn);
} }
@Test
public void testCreateBindingErrorResponseUnknownAttributes1() public void testCreateBindingErrorResponseUnknownAttributes1()
throws StunException throws StunException
{ {
@ -111,22 +129,22 @@ public class MessageFactoryTest
UnknownAttributesAttribute unknownAtts = UnknownAttributesAttribute unknownAtts =
AttributeFactory.createUnknownAttributesAttribute(); AttributeFactory.createUnknownAttributesAttribute();
for (char unknownAttribute : unknownAttributes) for (int i = 0; i < unknownAttributes.length; i++)
{ {
unknownAtts.addAttributeID(unknownAttribute); unknownAtts.addAttributeID(unknownAttributes[i]);
} }
expectedReturn.putAttribute(unknownAtts); expectedReturn.putAttribute(unknownAtts);
Message actualReturn = MessageFactory Message actualReturn = MessageFactory
.createBindingErrorResponseUnknownAttributes( .createBindingErrorResponseUnknownAttributes(
reasonPhrase, unknownAttributes); reasonPhrase, unknownAttributes);
assertEquals(expectedReturn, actualReturn); assertEquals("return value", expectedReturn, actualReturn);
} }
@Test public void testCreateBindingRequest() throws StunException
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(
@ -134,10 +152,9 @@ public class MessageFactoryTest
bindingRequest.putAttribute(changeRequest); bindingRequest.putAttribute(changeRequest);
*/ */
Request actualReturn = MessageFactory.createBindingRequest(); Request actualReturn = MessageFactory.createBindingRequest();
assertEquals(bindingRequest, actualReturn); assertEquals("return value", expectedReturn, actualReturn);
} }
@Test
public void testCreateBindingResponse() public void testCreateBindingResponse()
throws Exception throws Exception
{ {
@ -166,6 +183,7 @@ public class MessageFactoryTest
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,
@ -176,6 +194,6 @@ public class MessageFactoryTest
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(bindingResponse, actualReturn); assertEquals("return value", expectedReturn, actualReturn);
} }
} }

View File

@ -17,32 +17,16 @@
*/ */
package org.ice4j.message; package org.ice4j.message;
import static org.junit.jupiter.api.Assertions.*; import java.util.*;
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 public class MessageTest extends TestCase
{ {
@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;
@ -59,10 +43,12 @@ public class MessageTest
*/ */
private StunStack stunStack; private StunStack stunStack;
@BeforeEach protected void setUp() throws Exception
public void setUp() throws Exception
{ {
super.setUp();
msgFixture = new MsgFixture(); msgFixture = new MsgFixture();
msgFixture.setUp();
stunStack = new StunStack(); stunStack = new StunStack();
@ -103,8 +89,7 @@ public class MessageTest
bindingResponse.setTransactionID(MsgFixture.TRANSACTION_ID); bindingResponse.setTransactionID(MsgFixture.TRANSACTION_ID);
} }
@AfterEach protected void tearDown() throws Exception
public void tearDown() throws Exception
{ {
bindingRequest = null; bindingRequest = null;
bindingResponse = null; bindingResponse = null;
@ -112,38 +97,48 @@ public class MessageTest
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 verifies that the first * another attribute (same typ different value) and veriies that the first
* one is properly replaced. * one is properly replaced.
* *
* @throws StunException java.lang.Exception if we fail
*/ */
@Test public void testAddAndGetAttribute() throws StunException
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; Attribute getResult = null;
getResult = message.getAttribute(mappedAddress.getAttributeType()); getResult = message.getAttribute(mappedAddress.getAttributeType());
assertEquals(mappedAddress, getResult, assertEquals("Originally added attribute did not match the one retrned "
"Originally added attribute did not match the returned"); +"by getAttribute()",
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,
"The second attribute could not be extracted."); assertEquals("The second attribute could not be extracted.",
sourceAddress,
getResult);
} }
/** /**
@ -152,7 +147,6 @@ public class MessageTest
* *
* @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
{ {
@ -160,16 +154,16 @@ public class MessageTest
byte[] expectedReturn = msgFixture.bindingRequest; byte[] expectedReturn = msgFixture.bindingRequest;
byte[] actualReturn = bindingRequest.encode(stunStack); byte[] actualReturn = bindingRequest.encode(stunStack);
assertArrayEquals(expectedReturn, actualReturn, assertTrue("A binding request was not properly encoded",
"A binding request was not properly encoded"); Arrays.equals( expectedReturn, actualReturn ) );
//Binding Response //Binding Response
expectedReturn = msgFixture.bindingResponse; expectedReturn = msgFixture.bindingResponse;
actualReturn = bindingResponse.encode(stunStack); actualReturn = bindingResponse.encode(stunStack);
assertArrayEquals(expectedReturn, actualReturn, assertTrue("A binding response was not properly encoded",
"A binding response was not properly encoded"); Arrays.equals( expectedReturn, actualReturn ) );
} }
/** /**
@ -178,7 +172,6 @@ public class MessageTest
* *
* @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
{ {
@ -186,21 +179,21 @@ public class MessageTest
Message expectedReturn = bindingRequest; Message expectedReturn = bindingRequest;
Message actualReturn = Message.decode(msgFixture.bindingRequest, Message actualReturn = Message.decode(msgFixture.bindingRequest,
0, (char)0,
msgFixture.bindingRequest.length); (char)msgFixture.bindingRequest.length);
assertEquals(expectedReturn, actualReturn, assertEquals("A binding request was not properly decoded",
"A binding request was not properly decoded"); expectedReturn, actualReturn );
//Binding Response //Binding Response
expectedReturn = bindingResponse; expectedReturn = bindingResponse;
actualReturn = Message.decode(msgFixture.bindingResponse, actualReturn = Message.decode(msgFixture.bindingResponse,
0, (char)0,
msgFixture.bindingResponse.length); (char)msgFixture.bindingResponse.length);
assertEquals(expectedReturn, actualReturn, assertEquals("A binding response was not properly decoded",
"A binding response was not properly decoded"); expectedReturn, actualReturn );
} }
/** /**
@ -209,30 +202,39 @@ public class MessageTest
* *
* @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
{ {
assertNotEquals(bindingRequest, null, Object target = null;
"Equals failed against a null target"); boolean expectedReturn = false;
boolean actualReturn = bindingRequest.equals(target);
assertEquals("Equals failed against a null target",
expectedReturn, actualReturn);
assertNotEquals(bindingResponse, null, actualReturn = bindingResponse.equals(target);
"Equals failed against a null target"); assertEquals("Equals failed against a null target",
expectedReturn, actualReturn);
//different //different
assertNotEquals(bindingRequest, bindingResponse, actualReturn = bindingRequest.equals(bindingResponse);
"Equals failed against a different target"); assertEquals("Equals failed against a different target",
expectedReturn, actualReturn);
assertNotEquals(bindingResponse, bindingRequest, actualReturn = bindingResponse.equals(bindingRequest);
"Equals failed against a different target"); assertEquals("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);
assertEquals(bindingRequest, binReqTarget, actualReturn = bindingRequest.equals(binReqTarget);
"Equals failed against an equal target"); assertEquals("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
@ -241,42 +243,42 @@ public class MessageTest
binResTarget.putAttribute(mappedAddress); binResTarget.putAttribute(mappedAddress);
binResTarget.putAttribute(sourceAddress); binResTarget.putAttribute(sourceAddress);
binResTarget.putAttribute(changedAddress); binResTarget.putAttribute(changedAddress);
assertEquals(bindingResponse, binResTarget, actualReturn = bindingResponse.equals(binResTarget);
"Equals failed against a different target"); assertEquals("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(expectedReturn, actualReturn, assertEquals("getAttributeCount failed for a bindingRequest",
"getAttributeCount failed for a bindingRequest"); expectedReturn, actualReturn);
expectedReturn = 3; expectedReturn = 3;
actualReturn = bindingResponse.getAttributeCount(); actualReturn = bindingResponse.getAttributeCount();
assertEquals(expectedReturn, actualReturn, assertEquals("getAttributeCount failed for a bindingRequest",
"getAttributeCount failed for a bindingRequest"); expectedReturn, actualReturn);
} }
/** /**
* 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(bindingRequest.getAttribute(changeRequest.getAttributeType()), assertNull("An attribute was still in the request after being removed",
"An attribute was still in the request after being removed"); bindingRequest.getAttribute(changeRequest.getAttributeType()));
//test count //test count
int expectedReturn = 0; int expectedReturn = 0;
int actualReturn = bindingRequest.getAttributeCount(); int actualReturn = bindingRequest.getAttributeCount();
assertEquals(expectedReturn, actualReturn, assertEquals(
"Attribute count did not change after removing an attribute"); "Attribute count did not change after removing an attribute",
expectedReturn, actualReturn);
} }
} }

View File

@ -17,31 +17,32 @@
*/ */
package org.ice4j.pseudotcp; package org.ice4j.pseudotcp;
import static org.junit.jupiter.api.Assertions.*; import junit.framework.*;
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 for * This class enables multi thread tests where main thread waits in loop
* specified condition to be met, while others perform some operations. For * for specified condition to be met, while others perform some operations.
* example until the connection is established or closed. It also registers * For example until the connection is established or closed.
* default uncaught exception handler to catch exceptions from other threads. * It also registers default uncaught exception handler to catch exceptions
* <p> * from other threads.
*
* Condition checks are passed as IWaitUntilDone interface. * Condition checks are passed as IWaitUntilDone interface.
* *
* @author Pawel Domas * @author Pawel Domas
*/ */
public class MultiThreadSupportTest implements Thread.UncaughtExceptionHandler public class MultiThreadSupportTest
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)
{ {
@ -53,28 +54,30 @@ public class MultiThreadSupportTest implements Thread.UncaughtExceptionHandler
} }
} }
private static final long ASSERT_WAIT_INTERVAL = 100; private long assertWaitInterval = 100;
protected interface WaitUntilDone
protected boolean assert_wait_until(BooleanSupplier wait, long timeoutMs) {
public boolean isDone();
}
protected boolean assert_wait_until(WaitUntilDone wait, long timeoutMs)
{ {
long timeoutNanos = TimeUnit.MILLISECONDS.toNanos(timeoutMs);
try try
{ {
long start = System.nanoTime(); long start = System.currentTimeMillis();
while (!wait.getAsBoolean() && (System.nanoTime() - start) < timeoutNanos) while (!wait.isDone() && (System.currentTimeMillis() - start) < timeoutMs)
{ {
synchronized (testLock) synchronized (testLock)
{ {
testLock.wait(ASSERT_WAIT_INTERVAL); testLock.wait(assertWaitInterval);
if (testError != null) if (testError != null)
{ {
testError.printStackTrace(); testError.printStackTrace();
fail("Error in thread: " + errorThread.getName() + " : " fail("Error in thread: " + errorThread.getName() + " : " + testError.getMessage());
+ testError.getMessage());
} }
} }
} }
return wait.getAsBoolean(); return wait.isDone();
} }
catch (InterruptedException ex) catch (InterruptedException ex)
{ {
@ -84,4 +87,6 @@ public class MultiThreadSupportTest implements Thread.UncaughtExceptionHandler
return false; return false;
} }
} }
} }

View File

@ -17,14 +17,16 @@
*/ */
package org.ice4j.pseudotcp; package org.ice4j.pseudotcp;
import static org.junit.jupiter.api.Assertions.*; import static org.junit.Assert.*;
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
{ {
@ -34,15 +36,19 @@ 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
@ -53,18 +59,19 @@ 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();
server.setDebugName("L"); Thread serverThread = new Thread(new Runnable()
server.bind(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0)); {
final InetSocketAddress serverAddress = @Override
new InetSocketAddress(InetAddress.getLoopbackAddress(), server.getLocalPort()); public void run()
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
@ -80,31 +87,30 @@ 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(() -> Thread clientThread = new Thread(new Runnable()
{
@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++)
os.write(bufferSingle[i]); client.getOutputStream().write(bufferSingle[i]);
// write whole array // write whole array
os.write(bufferA); client.getOutputStream().write(bufferA);
// write by parts // write by parts
int partCount = 7; int partCount = 7;
boolean notExact = sizeB % partCount != 0; boolean notExact = sizeB % partCount != 0;
@ -118,41 +124,39 @@ public class PseudoTcpStreamTest
partsSize[i] = sizeB / partCount; partsSize[i] = sizeB / partCount;
} }
int written = 0; int written = 0;
for (int j : partsSize) for (int i = 0; i < partsSize.length; i++)
{ {
os.write(bufferB, written, j); client.getOutputStream().write(bufferB, written,
written += j; partsSize[i]);
written += partsSize[i];
} }
assertEquals(sizeB, written); assertEquals(sizeB, written);
os.flush(); client.getOutputStream().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( boolean success = assert_wait_until(new WaitUntilDone()
() -> client.getState() == PseudoTcpState.TCP_CLOSED, {
transferTimeout); @Override
public boolean isDone()
{
return client.getState() == PseudoTcpState.TCP_CLOSED;
}
}, transferTimeout);
if (success) if (success)
{ {
clientThread.join(10_000); clientThread.join();
if (!clientThreadEnded.get()) serverThread.join();
{
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
@ -187,35 +191,52 @@ public class PseudoTcpStreamTest
/** /**
* Test the timeout on accept method * Test the timeout on accept method
*/ */
@Test
public void testAccept() public void testAccept()
{ {
assertThrows(IOException.class, ()-> try
{ {
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;
DatagramSocket serverSocket = new DatagramSocket(0, InetAddress.getLoopbackAddress()); final int server_port = 49998;
server = new PseudoTcpSocketImpl(0, serverSocket); final InetSocketAddress serverAddress =
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 Thread(new Runnable()
{
@Override
public void run()
{ {
try try
{ {
@ -228,7 +249,7 @@ public class PseudoTcpStreamTest
try try
{ {
testOperation.testTimeout(server); testOperation.testTimeout(server);
fail("No expected timeout occurred on operation"); fail("No expected timeout occured on operation");
} }
catch (IOException e) catch (IOException e)
{ {
@ -242,16 +263,18 @@ 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 Thread(new Runnable()
{
@Override
public void run()
{ {
try try
{ {
client.connect(new InetSocketAddress( client.connect(serverAddress, 2000);
InetAddress.getLoopbackAddress(),
serverSocket.getLocalPort()),
2000);
Thread.sleep(500); Thread.sleep(500);
client.close(); client.close();
} }
@ -259,10 +282,18 @@ 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(() boolean done = assert_wait_until(new WaitUntilDone()
-> 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");
@ -271,39 +302,51 @@ 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(socket -> doTestTimeout(new TimeoutOperationTest()
{
@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(socket -> doTestTimeout(new TimeoutOperationTest()
{
@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(socket -> doTestTimeout(new TimeoutOperationTest()
{
@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];
@ -317,6 +360,8 @@ public class PseudoTcpStreamTest
throw new RuntimeException("Unexpected exception: "+e); throw new RuntimeException("Unexpected exception: "+e);
} }
socket.getOutputStream().flush(); socket.getOutputStream().flush();
}
}); });
} }
} }

View File

@ -608,9 +608,9 @@ public abstract class PseudoTcpTestBase
runClocks = false; runClocks = false;
localClockThread.interrupt(); localClockThread.interrupt();
remoteClockThread.interrupt(); remoteClockThread.interrupt();
localClockThread.join(5000); localClockThread.join();
localClockThread = null; localClockThread = null;
remoteClockThread.join(5000); remoteClockThread.join();
remoteClockThread = null; remoteClockThread = null;
} }
catch (InterruptedException ex) catch (InterruptedException ex)
@ -633,9 +633,14 @@ public abstract class PseudoTcpTestBase
*/ */
protected boolean assert_Connected_wait(int kConnectTimeoutMs) protected boolean assert_Connected_wait(int kConnectTimeoutMs)
{ {
return assert_wait_until( return assert_wait_until(new WaitUntilDone()
() -> PseudoTcpTestBase.this.have_connected_, {
kConnectTimeoutMs); @Override
public boolean isDone()
{
return PseudoTcpTestBase.this.have_connected_;
}
}, kConnectTimeoutMs);
} }
/** /**
@ -647,9 +652,14 @@ public abstract class PseudoTcpTestBase
*/ */
protected boolean assert_Disconnected_wait(long kTransferTimeoutMs) protected boolean assert_Disconnected_wait(long kTransferTimeoutMs)
{ {
return assert_wait_until( return assert_wait_until(new WaitUntilDone()
() -> PseudoTcpTestBase.this.have_disconnected_, {
kTransferTimeoutMs); @Override
public boolean isDone()
{
return PseudoTcpTestBase.this.have_disconnected_;
}
}, kTransferTimeoutMs);
} }
/** /**

View File

@ -20,10 +20,7 @@ package org.ice4j.pseudotcp;
import java.io.*; import java.io.*;
import java.util.logging.*; import java.util.logging.*;
import static org.junit.jupiter.api.Assertions.*;
import org.ice4j.pseudotcp.util.*; import org.ice4j.pseudotcp.util.*;
import org.junit.jupiter.api.*;
/** /**
* This class implements test for two way transfers * This class implements test for two way transfers
@ -54,6 +51,10 @@ public class PseudoTcpTestPingPong extends PseudoTcpTestBase
*/ */
private int iterationsRemaining; private int iterationsRemaining;
public PseudoTcpTestPingPong()
{
}
public void setBytesPerSend(int bytes_per_send) public void setBytesPerSend(int bytes_per_send)
{ {
this.bytesPerSend = bytes_per_send; this.bytesPerSend = bytes_per_send;
@ -70,8 +71,11 @@ public class PseudoTcpTestPingPong extends PseudoTcpTestBase
/** /**
* Performs ping-pong test for <tt>iterations</tt> with packets of * Performs ping-pong test for <tt>iterations</tt> with packets of
* <tt>size</tt> bytes * <tt>size</tt> bytes
*
* @param size
* @param iterations
*/ */
private void doTestPingPong(int size, int iterations) public void doTestPingPong(int size, int iterations)
{ {
Thread.setDefaultUncaughtExceptionHandler(this); Thread.setDefaultUncaughtExceptionHandler(this);
long start; long start;
@ -109,11 +113,13 @@ public class PseudoTcpTestPingPong extends PseudoTcpTestBase
/** /**
* Catches onTcpReadable event for receiver * Catches onTcpReadable event for receiver
*
* @param tcp
*/ */
@Override @Override
public void onTcpReadable(PseudoTCPBase tcp) public void onTcpReadable(PseudoTCPBase tcp)
{ {
assertEquals(receiver, tcp, "Unexpected onTcpReadable"); assertEquals("Unexpected onTcpReadable", receiver, tcp);
try try
{ {
// Stream bytes to the recv stream as they arrive. // Stream bytes to the recv stream as they arrive.
@ -157,6 +163,8 @@ public class PseudoTcpTestPingPong extends PseudoTcpTestBase
/** /**
* Catches the ontcpWriteable event for sender * Catches the ontcpWriteable event for sender
*
* @param tcp
*/ */
@Override @Override
public void onTcpWriteable(PseudoTCPBase tcp) public void onTcpWriteable(PseudoTCPBase tcp)
@ -181,11 +189,13 @@ public class PseudoTcpTestPingPong extends PseudoTcpTestBase
/** /**
* Reads the data in loop until is something available * Reads the data in loop until is something available
*
* @throws IOException
*/ */
private void readData() throws IOException private void readData() throws IOException
{ {
byte[] block = new byte[kBlockSize]; byte[] block = new byte[kBlockSize];
int rcvd; int rcvd = 0;
do do
{ {
rcvd = receiver.recv(block, block.length); rcvd = receiver.recv(block, block.length);
@ -204,11 +214,13 @@ public class PseudoTcpTestPingPong extends PseudoTcpTestBase
/** /**
* Writes all data to the receiver * Writes all data to the receiver
*
* @throws IOException
*/ */
private void writeData() throws IOException private void writeData() throws IOException
{ {
int tosend; int tosend;
int sent; int sent = 0;
byte[] block = new byte[kBlockSize]; byte[] block = new byte[kBlockSize];
do do
{ {
@ -238,7 +250,7 @@ public class PseudoTcpTestPingPong extends PseudoTcpTestBase
while (sent > 0); while (sent > 0);
} }
/* /**
* *
* Ping-pong (request/response) tests * Ping-pong (request/response) tests
* *
@ -246,7 +258,6 @@ public class PseudoTcpTestPingPong extends PseudoTcpTestBase
/** /**
* Test sending <= 1x MTU of data in each ping/pong. Should take <10ms. * Test sending <= 1x MTU of data in each ping/pong. Should take <10ms.
*/ */
@Test
public void testPingPong1xMtu() public void testPingPong1xMtu()
{ {
//logger.log(Level.INFO, "Test ping - pong 1xMTU"); //logger.log(Level.INFO, "Test ping - pong 1xMTU");
@ -259,7 +270,6 @@ public class PseudoTcpTestPingPong extends PseudoTcpTestBase
/** /**
* Test sending 2x-3x MTU of data in each ping/pong. Should take <10ms. * Test sending 2x-3x MTU of data in each ping/pong. Should take <10ms.
*/ */
@Test
public void testPingPong3xMtu() public void testPingPong3xMtu()
{ {
//logger.log(Level.INFO, "Test ping - pong 3xMTU"); //logger.log(Level.INFO, "Test ping - pong 3xMTU");
@ -273,7 +283,6 @@ public class PseudoTcpTestPingPong extends PseudoTcpTestBase
* Test sending 1x-2x MTU of data in each ping/pong. Should take ~1s, due to * Test sending 1x-2x MTU of data in each ping/pong. Should take ~1s, due to
* interaction between Nagling and Delayed ACK. * interaction between Nagling and Delayed ACK.
*/ */
@Test
public void testPingPong2xMtu() public void testPingPong2xMtu()
{ {
//logger.log(Level.INFO, "Test ping - pong 2xMTU"); //logger.log(Level.INFO, "Test ping - pong 2xMTU");
@ -287,7 +296,6 @@ public class PseudoTcpTestPingPong extends PseudoTcpTestBase
* Test sending 1x-2x MTU of data in each ping/pong with Delayed ACK off. * Test sending 1x-2x MTU of data in each ping/pong with Delayed ACK off.
* Should take <10ms. * Should take <10ms.
*/ */
@Test
public void testPingPong2xMtuWithAckDelayOff() public void testPingPong2xMtuWithAckDelayOff()
{ {
//logger.log(Level.INFO, "Test ping - pong 2xMTU ack delay off"); //logger.log(Level.INFO, "Test ping - pong 2xMTU ack delay off");
@ -302,7 +310,6 @@ public class PseudoTcpTestPingPong extends PseudoTcpTestBase
* Test sending 1x-2x MTU of data in each ping/pong with Nagling off. Should * Test sending 1x-2x MTU of data in each ping/pong with Nagling off. Should
* take <10ms. * take <10ms.
*/ */
@Test
public void testPingPong2xMtuWithNaglingOff() public void testPingPong2xMtuWithNaglingOff()
{ {
//logger.log(Level.INFO, "Test ping - pong 2xMTU nagling off"); //logger.log(Level.INFO, "Test ping - pong 2xMTU nagling off");
@ -317,7 +324,6 @@ public class PseudoTcpTestPingPong extends PseudoTcpTestBase
* Test sending a ping as pair of short (non-full) segments. Should take * Test sending a ping as pair of short (non-full) segments. Should take
* ~1s, due to Delayed ACK interaction with Nagling. * ~1s, due to Delayed ACK interaction with Nagling.
*/ */
@Test
public void testPingPongShortSegments() public void testPingPongShortSegments()
{ {
//logger.log(Level.INFO, "Test ping - pong short segments"); //logger.log(Level.INFO, "Test ping - pong short segments");
@ -333,7 +339,6 @@ public class PseudoTcpTestPingPong extends PseudoTcpTestBase
* Test sending ping as a pair of short (non-full) segments, with Nagling * Test sending ping as a pair of short (non-full) segments, with Nagling
* off. Should take <10ms. * off. Should take <10ms.
*/ */
@Test
public void testPingPongShortSegmentsWithNaglingOff() public void testPingPongShortSegmentsWithNaglingOff()
{ {
//logger.log(Level.INFO, "Test ping - pong short segments nagling off"); //logger.log(Level.INFO, "Test ping - pong short segments nagling off");
@ -349,7 +354,6 @@ public class PseudoTcpTestPingPong extends PseudoTcpTestBase
* Test sending <= 1x MTU of data ping/pong, in two segments, no Delayed * Test sending <= 1x MTU of data ping/pong, in two segments, no Delayed
* ACK. Should take ~1s. * ACK. Should take ~1s.
*/ */
@Test
public void testPingPongShortSegmentsWithAckDelayOff() public void testPingPongShortSegmentsWithAckDelayOff()
{ {
//logger.log(Level.INFO, "Test ping - pong short segments nagling off"); //logger.log(Level.INFO, "Test ping - pong short segments nagling off");

View File

@ -21,10 +21,7 @@ import java.io.*;
import java.util.*; import java.util.*;
import java.util.logging.*; import java.util.logging.*;
import static org.junit.jupiter.api.Assertions.*;
import org.ice4j.pseudotcp.util.*; import org.ice4j.pseudotcp.util.*;
import org.junit.jupiter.api.*;
/** /**
* Fill the receiver window until it is full, drain it and then fill it with the * Fill the receiver window until it is full, drain it and then fill it with the
@ -65,7 +62,7 @@ public class PseudoTcpTestRecvWindow extends PseudoTcpTestBase
*/ */
private int testDataSize; private int testDataSize;
private void doTestTransfer(int size) public void doTestTransfer(int size)
{ {
Thread.setDefaultUncaughtExceptionHandler(this); Thread.setDefaultUncaughtExceptionHandler(this);
testDataSize = size; testDataSize = size;
@ -97,14 +94,15 @@ public class PseudoTcpTestRecvWindow extends PseudoTcpTestBase
scheduleWriteAction(0); scheduleWriteAction(0);
long transferTout = maxTransferTime(dummy.length, kMinTransferRate); long transferTout = maxTransferTime(dummy.length, kMinTransferRate);
boolean transferInTime = assert_Disconnected_wait(transferTout); boolean transfferInTime = assert_Disconnected_wait(transferTout);
elapsed = PseudoTCPBase.now() - start; elapsed = PseudoTCPBase.now() - start;
stopClocks(); stopClocks();
int received = recv_stream.getBuffered(); int received = recv_stream.getBuffered();
assertTrue(transferInTime, "Transfer timeout, transferred: " + received assertEquals("Transfer timeout, transferred: " + received
+ " required: " + dummy.length + " required: " + dummy.length
+ " elapsed: " + " elapsed: "
+ elapsed + " limit: " + transferTout); + elapsed + " limit: " + transferTout,
true, transfferInTime);
assert 2 == send_position.size(); assert 2 == send_position.size();
assert 2 == recv_position.size(); assert 2 == recv_position.size();
@ -143,6 +141,7 @@ public class PseudoTcpTestRecvWindow extends PseudoTcpTestBase
* *
* *
* @param scaleFactor
* @return count bytes shadowed by scale actor * @return count bytes shadowed by scale actor
*/ */
static int getShadowedBytes(int scaleFactor) static int getShadowedBytes(int scaleFactor)
@ -152,6 +151,8 @@ public class PseudoTcpTestRecvWindow extends PseudoTcpTestBase
/** /**
* Reads all data available at the buffer * Reads all data available at the buffer
*
* @throws IOException
*/ */
void readUntilIOPending() throws IOException void readUntilIOPending() throws IOException
{ {
@ -185,6 +186,8 @@ public class PseudoTcpTestRecvWindow extends PseudoTcpTestBase
/** /**
* Schedules write operation with <tt>delay</tt> given in ms * Schedules write operation with <tt>delay</tt> given in ms
*
* @param delay
*/ */
void scheduleWriteAction(long delay) void scheduleWriteAction(long delay)
{ {
@ -209,6 +212,8 @@ public class PseudoTcpTestRecvWindow extends PseudoTcpTestBase
/** /**
* Writes the data * Writes the data
*
* @throws IOException
*/ */
void writeData() throws IOException void writeData() throws IOException
{ {
@ -331,7 +336,6 @@ public class PseudoTcpTestRecvWindow extends PseudoTcpTestBase
return getRemoteTcp().getM_rwnd_scale(); return getRemoteTcp().getM_rwnd_scale();
} }
@Test
public void testGetShadowedBytes() public void testGetShadowedBytes()
{ {
assert (PseudoTcpTestRecvWindow.getShadowedBytes(0) == 0); assert (PseudoTcpTestRecvWindow.getShadowedBytes(0) == 0);
@ -346,7 +350,6 @@ public class PseudoTcpTestRecvWindow extends PseudoTcpTestBase
/** /**
* Test that receive window expands and contract correctly. * Test that receive window expands and contract correctly.
*/ */
@Test
public void testReceiveWindow() public void testReceiveWindow()
{ {
//logger.log(Level.INFO, "Test receive window"); //logger.log(Level.INFO, "Test receive window");
@ -361,7 +364,6 @@ public class PseudoTcpTestRecvWindow extends PseudoTcpTestBase
/** /**
* Test setting send window size to a very small value. * Test setting send window size to a very small value.
*/ */
@Test
public void testSetVerySmallSendWindowSize() public void testSetVerySmallSendWindowSize()
{ {
//TODO: finish test //TODO: finish test
@ -379,7 +381,6 @@ public class PseudoTcpTestRecvWindow extends PseudoTcpTestBase
/** /**
* Test setting receive window size to a value other than default. * Test setting receive window size to a value other than default.
*/ */
@Test
public void testSetReceiveWindowSize() public void testSetReceiveWindowSize()
{ {
//logger.log(Level.INFO, "Test set receive window size"); //logger.log(Level.INFO, "Test set receive window size");

View File

@ -17,11 +17,10 @@
*/ */
package org.ice4j.pseudotcp; package org.ice4j.pseudotcp;
import static org.junit.jupiter.api.Assertions.*; import static org.junit.Assert.*;
import java.io.*; import java.io.*;
import java.util.logging.*; import java.util.logging.*;
import org.junit.jupiter.api.*;
/** /**
* Implements one way transfer test * Implements one way transfer test
@ -36,6 +35,10 @@ public class PseudoTcpTestTransfer extends PseudoTcpTestBase
private static final Logger logger = private static final Logger logger =
Logger.getLogger(PseudoTCPBase.class.getName()); Logger.getLogger(PseudoTCPBase.class.getName());
public PseudoTcpTestTransfer()
{
super();
}
/** /**
* The send data * The send data
*/ */
@ -55,8 +58,10 @@ public class PseudoTcpTestTransfer extends PseudoTcpTestBase
/** /**
* Transfers the data of <tt>size</tt> bytes * Transfers the data of <tt>size</tt> bytes
*
* @param size
*/ */
private void doTestTransfer(int size) public void doTestTransfer(int size)
{ {
Thread.setDefaultUncaughtExceptionHandler(this); Thread.setDefaultUncaughtExceptionHandler(this);
long start, elapsed; long start, elapsed;
@ -73,6 +78,7 @@ public class PseudoTcpTestTransfer extends PseudoTcpTestBase
try try
{ {
connect(); connect();
//assertEquals(0, Connect());
} }
catch (IOException ex) catch (IOException ex)
{ {
@ -83,14 +89,15 @@ public class PseudoTcpTestTransfer extends PseudoTcpTestBase
// Sending will start from OnTcpWriteable and complete when all data has // Sending will start from OnTcpWriteable and complete when all data has
// been received. // been received.
long transferTout = maxTransferTime(sendData.length, kMinTransferRate); long transferTout = maxTransferTime(sendData.length, kMinTransferRate);
boolean transferInTime = assert_Disconnected_wait(transferTout); boolean transfferInTime = assert_Disconnected_wait(transferTout);
elapsed = PseudoTCPBase.now() - start; elapsed = PseudoTCPBase.now() - start;
stopClocks(); stopClocks();
received = recvStream.size(); received = recvStream.size();
assertTrue(transferInTime,"Transfer timeout, transferred: " + received assertEquals("Transfer timeout, transferred: " + received
+ " required: " + sendData.length + " required: " + sendData.length
+ " elapsed: " + " elapsed: "
+ elapsed + " limit: " + transferTout); + elapsed + " limit: " + transferTout,
true, transfferInTime);
// Ensure we closed down OK and we got the right data. // Ensure we closed down OK and we got the right data.
assertEquals(size, received); assertEquals(size, received);
@ -105,6 +112,8 @@ public class PseudoTcpTestTransfer extends PseudoTcpTestBase
/** /**
* Reads all data available at remote peer's buffer * Reads all data available at remote peer's buffer
*
* @throws IOException
*/ */
void readData() throws IOException void readData() throws IOException
{ {
@ -126,6 +135,7 @@ public class PseudoTcpTestTransfer extends PseudoTcpTestBase
* Writes the data until there's space available * Writes the data until there's space available
* *
* @return true if there's no more data left to write * @return true if there's no more data left to write
* @throws IOException
*/ */
boolean writeData() throws IOException boolean writeData() throws IOException
{ {
@ -168,6 +178,8 @@ public class PseudoTcpTestTransfer extends PseudoTcpTestBase
/** /**
* Catches TCP readable event for remote peer and reads the data. When total * Catches TCP readable event for remote peer and reads the data. When total
* read count equals send data size the test is finished. * read count equals send data size the test is finished.
*
* @param tcp
*/ */
@Override @Override
public void onTcpReadable(PseudoTCPBase tcp) public void onTcpReadable(PseudoTCPBase tcp)
@ -203,6 +215,8 @@ public class PseudoTcpTestTransfer extends PseudoTcpTestBase
/** /**
* Catches on TCP writeable event for local peer. Writes all data and closes * Catches on TCP writeable event for local peer. Writes all data and closes
* the stream * the stream
*
* @param tcp
*/ */
@Override @Override
public void onTcpWriteable(PseudoTCPBase tcp) public void onTcpWriteable(PseudoTCPBase tcp)
@ -231,7 +245,6 @@ public class PseudoTcpTestTransfer extends PseudoTcpTestBase
* Basic end-to-end data transfer tests Test the normal case of sending data * Basic end-to-end data transfer tests Test the normal case of sending data
* from one side to the other. * from one side to the other.
*/ */
@Test
public void testSend() public void testSend()
{ {
//logger.log(Level.INFO, "Test send"); //logger.log(Level.INFO, "Test send");
@ -245,7 +258,6 @@ public class PseudoTcpTestTransfer extends PseudoTcpTestBase
* Test sending data with a 50 ms RTT. Transmission should take longer due * Test sending data with a 50 ms RTT. Transmission should take longer due
* to a slower ramp-up in send rate. * to a slower ramp-up in send rate.
*/ */
@Test
public void testSendWithDelay() public void testSendWithDelay()
{ {
//logger.log(Level.INFO, "Test send with delay"); //logger.log(Level.INFO, "Test send with delay");
@ -260,7 +272,6 @@ public class PseudoTcpTestTransfer extends PseudoTcpTestBase
* Test sending data with packet loss. Transmission should take much longer * Test sending data with packet loss. Transmission should take much longer
* due to send back-off when loss occurs. * due to send back-off when loss occurs.
*/ */
@Test
public void testSendWithLoss() public void testSendWithLoss()
{ {
//logger.log(Level.INFO, "Test send with loss"); //logger.log(Level.INFO, "Test send with loss");
@ -276,7 +287,6 @@ public class PseudoTcpTestTransfer extends PseudoTcpTestBase
* should take much longer due to send back-off and slower detection of * should take much longer due to send back-off and slower detection of
* loss. * loss.
*/ */
@Test
public void testSendWithDelayAndLoss() public void testSendWithDelayAndLoss()
{ {
//logger.log(Level.INFO, "Test send with delay and loss"); //logger.log(Level.INFO, "Test send with delay and loss");
@ -292,7 +302,6 @@ public class PseudoTcpTestTransfer extends PseudoTcpTestBase
* Test sending data with 10% packet loss and Nagling disabled. Transmission * Test sending data with 10% packet loss and Nagling disabled. Transmission
* should take about the same time as with Nagling enabled. * should take about the same time as with Nagling enabled.
*/ */
@Test
public void testSendWithLossAndOptNaglingOff() public void testSendWithLossAndOptNaglingOff()
{ {
//logger.log(Level.INFO, "Test send with loss and OptNagling off"); //logger.log(Level.INFO, "Test send with loss and OptNagling off");
@ -308,7 +317,6 @@ public class PseudoTcpTestTransfer extends PseudoTcpTestBase
* Test sending data with 10% packet loss and Delayed ACK disabled. * Test sending data with 10% packet loss and Delayed ACK disabled.
* Transmission should be slightly faster than with it enabled. * Transmission should be slightly faster than with it enabled.
*/ */
@Test
public void testSendWithLossAndOptAckDelayOff() public void testSendWithLossAndOptAckDelayOff()
{ {
//logger.log(Level.INFO, "Test send with loss and OptAckDelay off"); //logger.log(Level.INFO, "Test send with loss and OptAckDelay off");
@ -323,7 +331,6 @@ public class PseudoTcpTestTransfer extends PseudoTcpTestBase
/** /**
* Test sending data with 50ms delay and Nagling disabled. * Test sending data with 50ms delay and Nagling disabled.
*/ */
@Test
public void testSendWithDelayAndOptNaglingOff() public void testSendWithDelayAndOptNaglingOff()
{ {
//logger.log(Level.INFO, "Test send with delay and OptNagling off"); //logger.log(Level.INFO, "Test send with delay and OptNagling off");
@ -338,7 +345,6 @@ public class PseudoTcpTestTransfer extends PseudoTcpTestBase
/** /**
* Test sending data with 50ms delay and Delayed ACK disabled. * Test sending data with 50ms delay and Delayed ACK disabled.
*/ */
@Test
public void testSendWithDelayAndOptAckDelayOff() public void testSendWithDelayAndOptAckDelayOff()
{ {
//logger.log(Level.INFO, "Test send with delay and OptAckDelay off"); //logger.log(Level.INFO, "Test send with delay and OptAckDelay off");
@ -353,7 +359,6 @@ public class PseudoTcpTestTransfer extends PseudoTcpTestBase
/** /**
* Test a large receive buffer with a sender that doesn't support scaling. * Test a large receive buffer with a sender that doesn't support scaling.
*/ */
@Test
public void testSendRemoteNoWindowScale() public void testSendRemoteNoWindowScale()
{ {
//logger.log(Level.INFO, "Test send - remote no window scale"); //logger.log(Level.INFO, "Test send - remote no window scale");
@ -369,7 +374,6 @@ public class PseudoTcpTestTransfer extends PseudoTcpTestBase
* Test a large sender-side receive buffer with a receiver that doesn't * Test a large sender-side receive buffer with a receiver that doesn't
* support scaling. * support scaling.
*/ */
@Test
public void testSendLocalNoWindowScale() public void testSendLocalNoWindowScale()
{ {
//logger.log(Level.INFO, "Test send - local no window scale"); //logger.log(Level.INFO, "Test send - local no window scale");
@ -384,7 +388,6 @@ public class PseudoTcpTestTransfer extends PseudoTcpTestBase
/** /**
* Test when both sides use window scaling. * Test when both sides use window scaling.
*/ */
@Test
public void testSendBothUseWindowScale() public void testSendBothUseWindowScale()
{ {
//logger.log(Level.INFO, "Test send - both use window scale"); //logger.log(Level.INFO, "Test send - both use window scale");
@ -399,7 +402,6 @@ public class PseudoTcpTestTransfer extends PseudoTcpTestBase
/** /**
* Test using a large window scale value. * Test using a large window scale value.
*/ */
@Test
public void testSendLargeInFlight() public void testSendLargeInFlight()
{ {
//logger.log(Level.INFO, "Test send large in flight"); //logger.log(Level.INFO, "Test send large in flight");
@ -412,7 +414,6 @@ public class PseudoTcpTestTransfer extends PseudoTcpTestBase
test.doTestTransfer(1000000); test.doTestTransfer(1000000);
} }
@Test
public void testSendBothUseLargeWindowScale() public void testSendBothUseLargeWindowScale()
{ {
//logger.log(Level.INFO, "Test send both use large window scale"); //logger.log(Level.INFO, "Test send both use large window scale");
@ -427,7 +428,6 @@ public class PseudoTcpTestTransfer extends PseudoTcpTestBase
/** /**
* Test using a small receive buffer. * Test using a small receive buffer.
*/ */
@Test
public void testSendSmallReceiveBuffer() public void testSendSmallReceiveBuffer()
{ {
//logger.log(Level.INFO, "Test send small receive buffer"); //logger.log(Level.INFO, "Test send small receive buffer");
@ -442,7 +442,6 @@ public class PseudoTcpTestTransfer extends PseudoTcpTestBase
/** /**
* Test using a very small receive buffer. * Test using a very small receive buffer.
*/ */
@Test
public void testSendVerySmallReceiveBuffer() public void testSendVerySmallReceiveBuffer()
{ {
//logger.log(Level.INFO, "Test send very small receive buffer"); //logger.log(Level.INFO, "Test send very small receive buffer");

View File

@ -17,18 +17,19 @@
*/ */
package org.ice4j.pseudotcp.util; package org.ice4j.pseudotcp.util;
import static org.junit.Assert.*;
import java.nio.*; import java.nio.*;
import java.util.*; import java.util.*;
import static org.junit.jupiter.api.Assertions.*; import junit.framework.*;
import org.junit.jupiter.api.*;
/** /**
* *
* @author Pawel Domas * @author Pawel Domas
*/ */
public class ByteFifoBufferTest public class ByteFifoBufferTest
extends TestCase
{ {
public ByteFifoBufferTest() public ByteFifoBufferTest()
{ {
@ -37,7 +38,6 @@ public class ByteFifoBufferTest
/** /**
* Test of Length method, of class ByteFifoBuffer. * Test of Length method, of class ByteFifoBuffer.
*/ */
@Test
public void testLength() public void testLength()
{ {
int expResult = 1000; int expResult = 1000;
@ -52,7 +52,6 @@ public class ByteFifoBufferTest
/** /**
* Test of Read method, of class ByteFifoBuffer. * Test of Read method, of class ByteFifoBuffer.
*/ */
@Test
public void testRead() public void testRead()
{ {
int count = 1024; int count = 1024;
@ -61,8 +60,9 @@ public class ByteFifoBufferTest
instance.write(wData, count); instance.write(wData, count);
byte[] readBuff = new byte[count]; byte[] readBuff = new byte[count];
int expResult = count;
int result = instance.read(readBuff, count); int result = instance.read(readBuff, count);
assertEquals(count, result); assertEquals(expResult, result);
assertArrayEquals(wData, readBuff); assertArrayEquals(wData, readBuff);
} }
@ -70,7 +70,6 @@ public class ByteFifoBufferTest
/** /**
* Tests reading with an offset for destination buffer * Tests reading with an offset for destination buffer
*/ */
@Test
public void testReadWithOffset() public void testReadWithOffset()
{ {
int count = 1024; int count = 1024;
@ -94,6 +93,7 @@ public class ByteFifoBufferTest
* return some random array * return some random array
* *
* @param count array size * @param count array size
* @return
*/ */
private byte[] getWData(int count) private byte[] getWData(int count)
{ {
@ -106,7 +106,6 @@ public class ByteFifoBufferTest
/** /**
* Test of GetWriteRemaining method, of class ByteFifoBuffer. * Test of GetWriteRemaining method, of class ByteFifoBuffer.
*/ */
@Test
public void testGetWriteRemaining() public void testGetWriteRemaining()
{ {
int len = 100; int len = 100;
@ -127,7 +126,6 @@ public class ByteFifoBufferTest
/** /**
* Test of GetBuffered method, of class ByteFifoBuffer. * Test of GetBuffered method, of class ByteFifoBuffer.
*/ */
@Test
public void testGetBuffered() public void testGetBuffered()
{ {
int len = 1000; int len = 1000;
@ -150,14 +148,14 @@ public class ByteFifoBufferTest
/** /**
* Test of Write method, of class ByteFifoBuffer. * Test of Write method, of class ByteFifoBuffer.
*/ */
@Test
public void testWrite() public void testWrite()
{ {
int len = 2048; int len = 2048;
byte[] data = getWData(len); byte[] data = getWData(len);
ByteFifoBuffer instance = new ByteFifoBuffer(len); ByteFifoBuffer instance = new ByteFifoBuffer(len);
int expResult = len;
int result = instance.write(data, len); int result = instance.write(data, len);
assertEquals(len, result); assertEquals(expResult, result);
byte[] read = new byte[len]; byte[] read = new byte[len];
int readCount = instance.read(read, len); int readCount = instance.read(read, len);
@ -165,7 +163,6 @@ public class ByteFifoBufferTest
assertArrayEquals(data, read); assertArrayEquals(data, read);
} }
@Test
public void testWriteWithOffset() public void testWriteWithOffset()
{ {
int len = 2048; int len = 2048;
@ -186,7 +183,6 @@ public class ByteFifoBufferTest
/** /**
* Test of ConsumeWriteBuffer method, of class ByteFifoBuffer. * Test of ConsumeWriteBuffer method, of class ByteFifoBuffer.
*/ */
@Test
public void testConsumeWriteBuffer() public void testConsumeWriteBuffer()
{ {
int len = 100; int len = 100;
@ -212,7 +208,6 @@ public class ByteFifoBufferTest
/** /**
* Test of SetCapacity method, of class ByteFifoBuffer. * Test of SetCapacity method, of class ByteFifoBuffer.
*/ */
@Test
public void testSetCapacity() public void testSetCapacity()
{ {
int old_size = 100; int old_size = 100;
@ -234,7 +229,6 @@ public class ByteFifoBufferTest
/** /**
* Test of ConsumeReadData method, of class ByteFifoBuffer. * Test of ConsumeReadData method, of class ByteFifoBuffer.
*/ */
@Test
public void testConsumeReadData() public void testConsumeReadData()
{ {
int lCount = 100; int lCount = 100;
@ -256,7 +250,6 @@ public class ByteFifoBufferTest
/** /**
* Test of ReadOffset method, of class ByteFifoBuffer. * Test of ReadOffset method, of class ByteFifoBuffer.
*/ */
@Test
public void testReadOffset() public void testReadOffset()
{ {
int dst_buff_offset = 0; int dst_buff_offset = 0;
@ -265,10 +258,11 @@ public class ByteFifoBufferTest
byte[] dst_buff = new byte[len]; byte[] dst_buff = new byte[len];
int offset = 0; int offset = 0;
ByteFifoBuffer instance = new ByteFifoBuffer(len); ByteFifoBuffer instance = new ByteFifoBuffer(len);
int expResult = len;
instance.write(src_buff, len); instance.write(src_buff, len);
int result = int result =
instance.readOffset(dst_buff, dst_buff_offset, len, offset); instance.readOffset(dst_buff, dst_buff_offset, len, offset);
assertEquals(len, result); assertEquals(expResult, result);
assertArrayEquals(dst_buff, src_buff); assertArrayEquals(dst_buff, src_buff);
} }
@ -276,7 +270,6 @@ public class ByteFifoBufferTest
/** /**
* Test of WriteOffset method, of class ByteFifoBuffer. * Test of WriteOffset method, of class ByteFifoBuffer.
*/ */
@Test
public void testWriteOffset() public void testWriteOffset()
{ {
int len = 200; int len = 200;
@ -308,7 +301,6 @@ public class ByteFifoBufferTest
} }
@Test
public void testWriteReadWriteRead() public void testWriteReadWriteRead()
{ {
int len = 2000; int len = 2000;
@ -338,7 +330,6 @@ public class ByteFifoBufferTest
while ((read != wrData.length) || (written != wrData.length)); while ((read != wrData.length) || (written != wrData.length));
} }
@Test
public void testSomeMultiTest() public void testSomeMultiTest()
{ {
int Alen = 16; int Alen = 16;

View File

@ -36,8 +36,7 @@ public class DatagramCollector
{ {
try try
{ {
// The 'receive' method synchronized the packet, hence the 'getData()' (also synchronized) will block
// on this anyway even after 'waitForPacket' and 'collectPacket' calls.
sock.receive(receivedPacket); sock.receive(receivedPacket);
synchronized (this) synchronized (this)
@ -63,11 +62,6 @@ public class DatagramCollector
} }
public void waitForPacket() public void waitForPacket()
{
waitForPacket(50);
}
public void waitForPacket(long timeoutMillis)
{ {
synchronized(this) synchronized(this)
{ {
@ -76,12 +70,12 @@ public class DatagramCollector
try try
{ {
wait(timeoutMillis); wait(50);
} }
catch (InterruptedException e) catch (InterruptedException e)
{ {
// TODO Auto-generated catch block
e.printStackTrace(); e.printStackTrace();
Thread.currentThread().interrupt();
} }
} }
} }

View File

@ -18,39 +18,22 @@
package org.ice4j.stack; package org.ice4j.stack;
import java.net.*; import java.net.*;
import java.util.concurrent.*; import java.util.*;
import java.util.logging.*; import java.util.logging.*;
import static org.junit.jupiter.api.Assertions.*; import junit.framework.*;
import org.ice4j.*; import org.ice4j.*;
import org.ice4j.message.*; import org.ice4j.message.*;
import org.ice4j.socket.*; import org.ice4j.socket.*;
import org.jitsi.config.*;
import org.junit.jupiter.api.*;
/** /**
* All unit stack tests should be provided later. I just don't have the time now. * All unit stack tests should be provided later. I just don't have the time now.
* *
* @author Emil Ivov * @author Emil Ivov
*/ */
public class ShallowStackTest public class ShallowStackTest extends TestCase
{ {
@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();
}
/** /**
* The <tt>Logger</tt> used by the <tt>ShallowStackTest<tt> class and its * The <tt>Logger</tt> used by the <tt>ShallowStackTest<tt> class and its
* instances for logging output. * instances for logging output.
@ -67,37 +50,50 @@ public class ShallowStackTest
private TransportAddress dummyServerAddress = null; private TransportAddress dummyServerAddress = null;
private TransportAddress localAddress = null; private TransportAddress localAddress = null;
private final DatagramCollector dgramCollector = new DatagramCollector(); private DatagramCollector dgramCollector = new DatagramCollector();
private IceSocketWrapper localSock = null; private IceSocketWrapper localSock = null;
private DatagramSocket dummyServerSocket = null; private DatagramSocket dummyServerSocket = null;
/**
* Creates a test instance for the method with the specified name.
*
* @param name the name of the test we'd like to create an instance for.
*/
public ShallowStackTest(String name)
{
super(name);
}
/** /**
* Initializes whatever sockets we'll be using in our tests. * Initializes whatever sockets we'll be using in our tests.
* *
* @throws Exception if something goes wrong with socket initialization. * @throws Exception if something goes wrong with socket initialization.
*/ */
@BeforeEach protected void setUp()
public void setUp()
throws Exception throws Exception
{ {
super.setUp();
msgFixture = new MsgFixture(); msgFixture = new MsgFixture();
msgFixture.setUp();
//Addresses
dummyServerAddress = new TransportAddress(
"127.0.0.1", 6004, Transport.UDP);
localAddress = new TransportAddress(
"127.0.0.1", 5004, Transport.UDP);
//init the stack //init the stack
stunStack = new StunStack(); stunStack = new StunStack();
//access point //access point
localSock = new IceUdpSocketWrapper( localSock = new IceUdpSocketWrapper(
new SafeCloseDatagramSocket(new InetSocketAddress("127.0.0.1", 0))); new SafeCloseDatagramSocket(localAddress));
localAddress = new TransportAddress(
"127.0.0.1", localSock.getLocalPort(), Transport.UDP);
stunStack.addSocket(localSock); stunStack.addSocket(localSock);
//init the dummy server //init the dummy server
dummyServerSocket = new DatagramSocket(new InetSocketAddress("127.0.0.1", 0)); dummyServerSocket = new DatagramSocket( dummyServerAddress );
dummyServerAddress = new TransportAddress(
"127.0.0.1", dummyServerSocket.getLocalPort(), Transport.UDP);
} }
/** /**
@ -105,18 +101,18 @@ public class ShallowStackTest
* *
* @throws Exception if closing the sockets fails. * @throws Exception if closing the sockets fails.
*/ */
@AfterEach protected void tearDown()
public void tearDown()
throws Exception throws Exception
{ {
stunStack.removeSocket(localAddress); stunStack.removeSocket(localAddress);
stunStack.shutDown();
localSock.close(); localSock.close();
dummyServerSocket.close(); dummyServerSocket.close();
msgFixture.tearDown();
msgFixture = null; msgFixture = null;
super.tearDown();
} }
@ -127,7 +123,6 @@ public class ShallowStackTest
* *
* @throws java.lang.Exception if we fail * @throws java.lang.Exception if we fail
*/ */
@Test
public void testSendRequest() public void testSendRequest()
throws Exception throws Exception
{ {
@ -141,37 +136,40 @@ public class ShallowStackTest
new SimpleResponseCollector()); new SimpleResponseCollector());
//wait for its arrival //wait for its arrival
dgramCollector.waitForPacket(1000); dgramCollector.waitForPacket();
DatagramPacket receivedPacket = dgramCollector.collectPacket(); DatagramPacket receivedPacket = dgramCollector.collectPacket();
assertTrue((receivedPacket.getLength() > 0), assertTrue("The stack did not properly send a Binding Request",
"The stack did not properly send a Binding Request"); (receivedPacket.getLength() > 0));
Request receivedRequest = Request receivedRequest =
(Request)Request.decode(receivedPacket.getData(), (Request)Request.decode(receivedPacket.getData(),
(char)0, (char)0,
(char)receivedPacket.getLength()); (char)receivedPacket.getLength());
assertEquals(bindingRequest, receivedRequest, assertEquals("The received request did not match the "
"The received request did not match the one that was sent."); +"one that was sent.",
bindingRequest, //expected
receivedRequest); // actual
//wait for retransmissions //wait for retransmissions
dgramCollector.startListening(dummyServerSocket); dgramCollector.startListening(dummyServerSocket);
dgramCollector.waitForPacket(1000); dgramCollector.waitForPacket();
receivedPacket = dgramCollector.collectPacket(); receivedPacket = dgramCollector.collectPacket();
assertTrue((receivedPacket.getLength() > 0), assertTrue("The stack did not retransmit a Binding Request",
"The stack did not retransmit a Binding Request"); (receivedPacket.getLength() > 0));
receivedRequest = (Request)Request.decode( receivedRequest = (Request)Request.decode(
receivedPacket.getData(), receivedPacket.getData(),
0, (char)0,
receivedPacket.getLength()); (char)receivedPacket.getLength());
assertEquals(bindingRequest, receivedRequest, assertEquals("The retransmitted request did not match the original.",
"The retransmitted request did not match the original."); bindingRequest, //expected
receivedRequest); // actual
} }
/** /**
@ -180,7 +178,6 @@ public class ShallowStackTest
* *
* @throws java.lang.Exception if we fail * @throws java.lang.Exception if we fail
*/ */
@Test
public void testReceiveRequest() public void testReceiveRequest()
throws Exception throws Exception
{ {
@ -197,12 +194,12 @@ public class ShallowStackTest
Request collectedRequest = requestCollector.collectedRequest; Request collectedRequest = requestCollector.collectedRequest;
assertNotNull(collectedRequest, "No request has been received"); assertNotNull("No request has been received", collectedRequest);
byte[] expectedReturn = msgFixture.bindingRequest2; byte expectedReturn[] = msgFixture.bindingRequest2;
byte[] actualReturn = collectedRequest.encode(stunStack); byte actualReturn[] = collectedRequest.encode(stunStack);
assertArrayEquals(expectedReturn, actualReturn, assertTrue("Received request was not the same as the one that was sent",
"Received request was not the same as the one that was sent"); Arrays.equals(expectedReturn, actualReturn));
} }
/** /**
@ -213,7 +210,6 @@ public class ShallowStackTest
* *
* @throws java.lang.Exception if we fail * @throws java.lang.Exception if we fail
*/ */
@Test
public void testSendResponse() public void testSendResponse()
throws Exception throws Exception
{ {
@ -231,10 +227,10 @@ public class ShallowStackTest
Request collectedRequest = requestCollector.collectedRequest; Request collectedRequest = requestCollector.collectedRequest;
byte[] expectedReturn = msgFixture.bindingRequest; byte expectedReturn[] = msgFixture.bindingRequest;
byte[] actualReturn = collectedRequest.encode(stunStack); byte actualReturn[] = collectedRequest.encode(stunStack);
assertArrayEquals(expectedReturn, actualReturn, assertTrue("Received request was not the same as the one that was sent",
"Received request was not the same as the one that was sent"); Arrays.equals(expectedReturn, actualReturn));
//---------- create the response --------------------------------------- //---------- create the response ---------------------------------------
Response bindingResponse = MessageFactory.create3489BindingResponse( Response bindingResponse = MessageFactory.create3489BindingResponse(
@ -258,15 +254,17 @@ public class ShallowStackTest
DatagramPacket receivedPacket = dgramCollector.collectPacket(); DatagramPacket receivedPacket = dgramCollector.collectPacket();
assertTrue((receivedPacket.getLength() > 0), assertTrue("The stack did not properly send a Binding Request",
"The stack did not properly send a Binding Request"); (receivedPacket.getLength() > 0));
Response receivedResponse = Response receivedResponse =
(Response) Response.decode(receivedPacket.getData(), (Response) Response.decode(receivedPacket.getData(),
0, (char) 0,
receivedPacket.getLength()); (char) receivedPacket.getLength());
assertEquals(bindingResponse, receivedResponse, assertEquals(
"The received request did not match the one that was sent."); "The received request did not match the one that was sent.",
bindingResponse, //expected
receivedResponse); // actual
} }
/** /**
@ -274,7 +272,6 @@ public class ShallowStackTest
* *
* @throws Exception if something fails somewhere. * @throws Exception if something fails somewhere.
*/ */
@Test
public void testReceiveResponse() public void testReceiveResponse()
throws Exception throws Exception
{ {
@ -291,7 +288,7 @@ public class ShallowStackTest
collector.waitForResponse(); collector.waitForResponse();
//create the right response //create the right response
byte[] response = new byte[msgFixture.bindingResponse.length]; byte response[] = new byte[msgFixture.bindingResponse.length];
System.arraycopy(msgFixture.bindingResponse, 0, response, 0, System.arraycopy(msgFixture.bindingResponse, 0, response, 0,
response.length); response.length);
@ -313,65 +310,10 @@ public class ShallowStackTest
Response collectedResponse = collector.collectedResponse; Response collectedResponse = collector.collectedResponse;
byte[] actualReturn = collectedResponse.encode(stunStack); byte expectedReturn[] = response;
assertArrayEquals(response, actualReturn, byte actualReturn[] = collectedResponse.encode(stunStack);
"Received request was not the same as the one that was sent"); assertTrue("Received request was not the same as the one that was sent",
} Arrays.equals(expectedReturn, actualReturn));
/**
* Verify StackProperties.FIRST_CTRAN_RETRANS_AFTER can indeed update StunClientTransaction.Retransmitter
*/
@Test
public void testRetransmissionOriginalWait()
throws Exception
{
long originalWait = 200; // milliseconds
System.setProperty(StackProperties.FIRST_CTRAN_RETRANS_AFTER, String.valueOf(originalWait));
Request bindingRequest = MessageFactory.createBindingRequest();
dgramCollector.startListening(dummyServerSocket);
long firstTime = System.nanoTime();
stunStack.sendRequest(bindingRequest,
dummyServerAddress,
localAddress,
new SimpleResponseCollector());
//wait for its arrival
dgramCollector.waitForPacket(1000);
DatagramPacket receivedPacket = dgramCollector.collectPacket();
assertTrue((receivedPacket.getLength() > 0),
"The stack did not properly send a Binding Request");
Request receivedRequest =
(Request)Request.decode(receivedPacket.getData(),
(char)0,
(char)receivedPacket.getLength());
assertEquals(bindingRequest, receivedRequest,
"The received request did not match the one that was sent.");
// wait for the 1st retransmission with originalWait
dgramCollector.startListening(dummyServerSocket);
dgramCollector.waitForPacket(1000);
receivedPacket = dgramCollector.collectPacket();
assertTrue((receivedPacket.getLength() > 0),
"The stack did not retransmit a Binding Request");
receivedRequest = (Request) Request.decode(
receivedPacket.getData(),
0,
receivedPacket.getLength());
assertEquals(bindingRequest, receivedRequest,
"The retransmitted request did not match the original.");
// verify the retransmission is longer than the originalWait
assertTrue(System.nanoTime() - firstTime >= TimeUnit.MILLISECONDS.toNanos(originalWait));
System.clearProperty(StackProperties.FIRST_CTRAN_RETRANS_AFTER);
} }
//--------------------------------------- listener implementations --------- //--------------------------------------- listener implementations ---------

View File

@ -17,12 +17,12 @@
*/ */
package org.ice4j.stunclient; package org.ice4j.stunclient;
import static org.junit.jupiter.api.Assertions.*; import junit.framework.*;
import org.ice4j.*; import org.ice4j.*;
import org.ice4j.message.*; import org.ice4j.message.*;
import org.ice4j.stack.*; import org.ice4j.stack.*;
import org.junit.jupiter.api.*;
/** /**
* The StunAddressDiscovererTest_XXX set of tests were created to verify stun * The StunAddressDiscovererTest_XXX set of tests were created to verify stun
* operation for scenarios of some basic types of firewalls. The purpose of * operation for scenarios of some basic types of firewalls. The purpose of
@ -34,24 +34,32 @@ import org.junit.jupiter.api.*;
* @author Emil Ivov * @author Emil Ivov
*/ */
public class StunAddressDiscovererTest public class StunAddressDiscovererTest
extends TestCase
{ {
private NetworkConfigurationDiscoveryProcess stunAddressDiscoverer = null; private NetworkConfigurationDiscoveryProcess stunAddressDiscoverer = null;
private final TransportAddress discovererAddress private TransportAddress discovererAddress
= new TransportAddress("127.0.0.1", 15555, Transport.UDP); = new TransportAddress("127.0.0.1", 15555, Transport.UDP);
private ResponseSequenceServer responseServer = null; private ResponseSequenceServer responseServer = null;
private final TransportAddress responseServerAddress private TransportAddress responseServerAddress
= new TransportAddress("127.0.0.1", 19999, Transport.UDP); = new TransportAddress("127.0.0.1", 19999, Transport.UDP);
private final TransportAddress mappedClientAddress private TransportAddress mappedClientAddress
= new TransportAddress("212.56.4.10", 15612, Transport.UDP); = new TransportAddress("212.56.4.10", 15612, Transport.UDP);
private final TransportAddress mappedClientAddressPort2 private TransportAddress mappedClientAddressPort2
= new TransportAddress("212.56.4.10", 15611, Transport.UDP); = new TransportAddress("212.56.4.10", 15611, Transport.UDP);
@BeforeEach public StunAddressDiscovererTest(String name)
public void setUp() throws Exception throws StunException
{ {
super(name);
}
protected void setUp() throws Exception
{
super.setUp();
System.setProperty(StackProperties.MAX_CTRAN_RETRANS_TIMER, "100"); System.setProperty(StackProperties.MAX_CTRAN_RETRANS_TIMER, "100");
System.setProperty(StackProperties.MAX_CTRAN_RETRANSMISSIONS, "2"); System.setProperty(StackProperties.MAX_CTRAN_RETRANSMISSIONS, "2");
@ -68,14 +76,15 @@ public class StunAddressDiscovererTest
responseServer.start(); responseServer.start();
} }
@AfterEach protected void tearDown() throws Exception
public void tearDown() throws Exception
{ {
System.clearProperty(StackProperties.MAX_CTRAN_RETRANS_TIMER); System.clearProperty(StackProperties.MAX_CTRAN_RETRANS_TIMER);
System.clearProperty(StackProperties.MAX_CTRAN_RETRANSMISSIONS); System.clearProperty(StackProperties.MAX_CTRAN_RETRANSMISSIONS);
responseServer.shutDown(); responseServer.shutDown();
stunAddressDiscoverer.shutDown(); stunAddressDiscoverer.shutDown();
stunAddressDiscoverer = null; stunAddressDiscoverer = null;
super.tearDown();
} }
/** /**
@ -84,7 +93,6 @@ public class StunAddressDiscovererTest
* *
* @throws Exception if anything goes wrong ( surprised? ). * @throws Exception if anything goes wrong ( surprised? ).
*/ */
@Test
public void testRecognizeBlockedUDP() public void testRecognizeBlockedUDP()
throws Exception throws Exception
{ {
@ -96,8 +104,10 @@ public class StunAddressDiscovererTest
StunDiscoveryReport actualReturn = stunAddressDiscoverer StunDiscoveryReport actualReturn = stunAddressDiscoverer
.determineAddress(); .determineAddress();
assertEquals(expectedReturn, actualReturn, assertEquals("The StunAddressDiscoverer failed for a "
"The StunAddressDiscoverer failed for a no-udp environment."); +"no-udp environment.",
expectedReturn, actualReturn);
} }
@ -106,7 +116,6 @@ public class StunAddressDiscovererTest
* it concludes it is behind a Symmetric NAT. * it concludes it is behind a Symmetric NAT.
* @throws Exception if anything goes wrong ( surprised? ). * @throws Exception if anything goes wrong ( surprised? ).
*/ */
@Test
public void testRecognizeSymmetricNat() throws Exception public void testRecognizeSymmetricNat() throws Exception
{ {
//define the server response sequence //define the server response sequence
@ -130,8 +139,10 @@ public class StunAddressDiscovererTest
StunDiscoveryReport actualReturn StunDiscoveryReport actualReturn
= stunAddressDiscoverer.determineAddress(); = stunAddressDiscoverer.determineAddress();
assertEquals(expectedReturn, actualReturn, assertEquals(
"The StunAddressDiscoverer failed for a no-udp environment."); "The StunAddressDiscoverer failed for a no-udp environment.",
expectedReturn,
actualReturn);
} }
@ -140,7 +151,6 @@ public class StunAddressDiscovererTest
* it concludes it is behind a Port Restricted Cone. * it concludes it is behind a Port Restricted Cone.
* @throws Exception if anything goes wrong ( surprised? ). * @throws Exception if anything goes wrong ( surprised? ).
*/ */
@Test
public void testRecognizePortRestrictedCone() public void testRecognizePortRestrictedCone()
throws Exception throws Exception
{ {
@ -165,8 +175,8 @@ public class StunAddressDiscovererTest
StunDiscoveryReport actualReturn StunDiscoveryReport actualReturn
= stunAddressDiscoverer.determineAddress(); = stunAddressDiscoverer.determineAddress();
assertEquals(expectedReturn, actualReturn, assertEquals("The StunAddressDiscoverer failed for a no-udp environment.",
"The StunAddressDiscoverer failed for a no-udp environment."); expectedReturn, actualReturn);
} }
@ -175,7 +185,6 @@ public class StunAddressDiscovererTest
* it concludes it is behind a Restricted Cone. * it concludes it is behind a Restricted Cone.
* @throws Exception if anything goes wrong ( surprised? ). * @throws Exception if anything goes wrong ( surprised? ).
*/ */
@Test
public void testRecognizeRestrictedCone() throws Exception public void testRecognizeRestrictedCone() throws Exception
{ {
//define the server response sequence //define the server response sequence
@ -199,8 +208,10 @@ public class StunAddressDiscovererTest
StunDiscoveryReport actualReturn = stunAddressDiscoverer StunDiscoveryReport actualReturn = stunAddressDiscoverer
.determineAddress(); .determineAddress();
assertEquals(expectedReturn, actualReturn, assertEquals(
"The StunAddressDiscoverer failed for a no-udp environment."); "The StunAddressDiscoverer failed for a no-udp environment.",
expectedReturn, actualReturn);
} }
/** /**
@ -208,7 +219,6 @@ public class StunAddressDiscovererTest
* it concludes it is behind a Full Cone. * it concludes it is behind a Full Cone.
* @throws Exception if anything goes wrong ( surprised? ). * @throws Exception if anything goes wrong ( surprised? ).
*/ */
@Test
public void testRecognizeFullCone() public void testRecognizeFullCone()
throws Exception throws Exception
{ {
@ -228,8 +238,9 @@ public class StunAddressDiscovererTest
StunDiscoveryReport actualReturn = stunAddressDiscoverer. StunDiscoveryReport actualReturn = stunAddressDiscoverer.
determineAddress(); determineAddress();
assertEquals(expectedReturn, actualReturn, assertEquals(
"The StunAddressDiscoverer failed for a no-udp environment."); "The StunAddressDiscoverer failed for a no-udp environment.",
expectedReturn, actualReturn);
} }
/** /**
@ -238,7 +249,6 @@ public class StunAddressDiscovererTest
* *
* @throws Exception if anything goes wrong ( surprised? ). * @throws Exception if anything goes wrong ( surprised? ).
*/ */
@Test
public void testRecognizeUdpSymmetricFirewall() public void testRecognizeUdpSymmetricFirewall()
throws Exception throws Exception
{ {
@ -257,8 +267,9 @@ public class StunAddressDiscovererTest
StunDiscoveryReport actualReturn = stunAddressDiscoverer. StunDiscoveryReport actualReturn = stunAddressDiscoverer.
determineAddress(); determineAddress();
assertEquals(expectedReturn, actualReturn, assertEquals(
"The StunAddressDiscoverer failed for a no-udp environment."); "The StunAddressDiscoverer failed for a no-udp environment.",
expectedReturn, actualReturn);
} }
@ -268,7 +279,6 @@ public class StunAddressDiscovererTest
* *
* @throws Exception if anything goes wrong ( surprised? ). * @throws Exception if anything goes wrong ( surprised? ).
*/ */
@Test
public void testRecognizeOpenInternet() public void testRecognizeOpenInternet()
throws Exception throws Exception
{ {
@ -288,7 +298,8 @@ public class StunAddressDiscovererTest
StunDiscoveryReport actualReturn = stunAddressDiscoverer. StunDiscoveryReport actualReturn = stunAddressDiscoverer.
determineAddress(); determineAddress();
assertEquals(expectedReturn, actualReturn, assertEquals(
"The StunAddressDiscoverer failed for a no-udp environment."); "The StunAddressDiscoverer failed for a no-udp environment.",
expectedReturn, actualReturn);
} }
} }

View File

@ -17,12 +17,12 @@
*/ */
package org.ice4j.stunclient; package org.ice4j.stunclient;
import static org.junit.jupiter.api.Assertions.*; import junit.framework.*;
import org.ice4j.*; import org.ice4j.*;
import org.ice4j.message.*; import org.ice4j.message.*;
import org.ice4j.stack.*; import org.ice4j.stack.*;
import org.junit.jupiter.api.*;
/** /**
* Makes basic stun tests for cases where local network addresses and the public * Makes basic stun tests for cases where local network addresses and the public
* NAT address are using different IP versions. (e.g. Local addresses are v4 * NAT address are using different IP versions. (e.g. Local addresses are v4
@ -38,41 +38,48 @@ import org.junit.jupiter.api.*;
* <p>Company: Net Research Team, Louis Pasteur University</p> * <p>Company: Net Research Team, Louis Pasteur University</p>
* @author Emil Ivov * @author Emil Ivov
*/ */
public class StunAddressDiscovererTest_v4v6 public class StunAddressDiscovererTest_v4v6 extends TestCase
{ {
private NetworkConfigurationDiscoveryProcess stunAddressDiscoverer_v6 private NetworkConfigurationDiscoveryProcess stunAddressDiscoverer_v6
= null; = null;
private NetworkConfigurationDiscoveryProcess stunAddressDiscoverer_v4 private NetworkConfigurationDiscoveryProcess stunAddressDiscoverer_v4
= null; = null;
private final TransportAddress discovererAddress_v4 private TransportAddress discovererAddress_v4
= new TransportAddress("127.0.0.1", 17555, Transport.UDP); = new TransportAddress("127.0.0.1", 17555, Transport.UDP);
private final TransportAddress discovererAddress_v6 private TransportAddress discovererAddress_v6
= new TransportAddress("::1", 17555, Transport.UDP); = new TransportAddress("::1", 17555, Transport.UDP);
private ResponseSequenceServer responseServer_v6 = null; private ResponseSequenceServer responseServer_v6 = null;
private ResponseSequenceServer responseServer_v4 = null; private ResponseSequenceServer responseServer_v4 = null;
private final TransportAddress responseServerAddress_v6 private TransportAddress responseServerAddress_v6
= new TransportAddress("::1", 21999, Transport.UDP); = new TransportAddress("::1", 21999, Transport.UDP);
private final TransportAddress responseServerAddress_v4 private TransportAddress responseServerAddress_v4
= new TransportAddress("127.0.0.1", 21999, Transport.UDP); = new TransportAddress("127.0.0.1", 21999, Transport.UDP);
private final TransportAddress mappedClientAddress_v6 = new TransportAddress( private TransportAddress mappedClientAddress_v6 = new TransportAddress(
"2001:660:4701:1001:ff::1", 17612, Transport.UDP); "2001:660:4701:1001:ff::1", 17612, Transport.UDP);
private final TransportAddress mappedClientAddress_v6_Port2 private TransportAddress mappedClientAddress_v6_Port2
= new TransportAddress( = new TransportAddress(
"2001:660:4701:1001:ff::1", 17611, Transport.UDP); "2001:660:4701:1001:ff::1", 17611, Transport.UDP);
private final TransportAddress mappedClientAddress_v4 private TransportAddress mappedClientAddress_v4
= new TransportAddress("130.79.99.55", 17612, Transport.UDP); = new TransportAddress("130.79.99.55", 17612, Transport.UDP);
private final TransportAddress mappedClientAddress_v4_Port2 private TransportAddress mappedClientAddress_v4_Port2
= new TransportAddress("130.79.99.55", 17611, Transport.UDP); = new TransportAddress("130.79.99.55", 17611, Transport.UDP);
@BeforeEach public StunAddressDiscovererTest_v4v6(String name)
public void setUp() throws StunException
{
super(name);
}
protected void setUp()
throws Exception throws Exception
{ {
super.setUp();
StunStack stunStack = new StunStack(); StunStack stunStack = new StunStack();
responseServer_v6 responseServer_v6
@ -98,8 +105,7 @@ public class StunAddressDiscovererTest_v4v6
System.setProperty(StackProperties.MAX_CTRAN_RETRANSMISSIONS, "2"); System.setProperty(StackProperties.MAX_CTRAN_RETRANSMISSIONS, "2");
} }
@AfterEach protected void tearDown()
public void tearDown()
throws Exception throws Exception
{ {
System.clearProperty(StackProperties.MAX_CTRAN_RETRANS_TIMER); System.clearProperty(StackProperties.MAX_CTRAN_RETRANS_TIMER);
@ -114,6 +120,8 @@ public class StunAddressDiscovererTest_v4v6
//give the sockets the time to clear out //give the sockets the time to clear out
Thread.sleep(1000); Thread.sleep(1000);
super.tearDown();
} }
/** /**
@ -121,7 +129,6 @@ public class StunAddressDiscovererTest_v4v6
* it concludes it is behind a Symmetric NAT. * it concludes it is behind a Symmetric NAT.
* @throws Exception if anything goes wrong ( surprised? ). * @throws Exception if anything goes wrong ( surprised? ).
*/ */
@Test
public void testRecognizeSymmetricNat_Local_v6_Public_v4() public void testRecognizeSymmetricNat_Local_v6_Public_v4()
throws Exception throws Exception
{ {
@ -148,8 +155,9 @@ public class StunAddressDiscovererTest_v4v6
StunDiscoveryReport actualReturn StunDiscoveryReport actualReturn
= stunAddressDiscoverer_v6.determineAddress(); = stunAddressDiscoverer_v6.determineAddress();
assertEquals(expectedReturn, actualReturn, assertEquals("The StunAddressDiscoverer failed for a v4-v6 sym env.",
"The StunAddressDiscoverer failed for a v4-v6 sym env."); expectedReturn, actualReturn);
} }
/** /**
@ -157,7 +165,6 @@ public class StunAddressDiscovererTest_v4v6
* it concludes it is behind a Symmetric NAT. * it concludes it is behind a Symmetric NAT.
* @throws Exception if anything goes wrong ( surprised? ). * @throws Exception if anything goes wrong ( surprised? ).
*/ */
@Test
public void testRecognizeSymmetricNat_Local_v4_Public_v6() throws Exception public void testRecognizeSymmetricNat_Local_v4_Public_v6() throws Exception
{ {
//define the server response sequence //define the server response sequence
@ -183,8 +190,11 @@ public class StunAddressDiscovererTest_v4v6
StunDiscoveryReport actualReturn StunDiscoveryReport actualReturn
= stunAddressDiscoverer_v4.determineAddress(); = stunAddressDiscoverer_v4.determineAddress();
assertEquals(expectedReturn, actualReturn, assertEquals(
"The StunAddressDiscoverer failed for a no-udp environment."); "The StunAddressDiscoverer failed for a no-udp environment.",
expectedReturn,
actualReturn);
} }
/** /**
@ -192,7 +202,6 @@ public class StunAddressDiscovererTest_v4v6
* it concludes it is behind a Full Cone. * it concludes it is behind a Full Cone.
* @throws Exception if anything goes wrong ( surprised? ). * @throws Exception if anything goes wrong ( surprised? ).
*/ */
@Test
public void testRecognizeFullCone_Local_v6_Public_v4() throws Exception public void testRecognizeFullCone_Local_v6_Public_v4() throws Exception
{ {
//define the server response sequence //define the server response sequence
@ -215,8 +224,10 @@ public class StunAddressDiscovererTest_v4v6
StunDiscoveryReport actualReturn = stunAddressDiscoverer_v6. StunDiscoveryReport actualReturn = stunAddressDiscoverer_v6.
determineAddress(); determineAddress();
assertEquals(expectedReturn, actualReturn, assertEquals(
"The StunAddressDiscoverer failed for a no-udp environment."); "The StunAddressDiscoverer failed for a no-udp environment.",
expectedReturn, actualReturn);
} }
/** /**
@ -224,7 +235,6 @@ public class StunAddressDiscovererTest_v4v6
* it concludes it is behind a Full Cone. * it concludes it is behind a Full Cone.
* @throws Exception if anything goes wrong ( surprised? ). * @throws Exception if anything goes wrong ( surprised? ).
*/ */
@Test
public void testRecognizeFullCone_Local_v4_Public_v6() throws Exception public void testRecognizeFullCone_Local_v4_Public_v6() throws Exception
{ {
//define the server response sequence //define the server response sequence
@ -247,7 +257,9 @@ public class StunAddressDiscovererTest_v4v6
StunDiscoveryReport actualReturn = stunAddressDiscoverer_v4. StunDiscoveryReport actualReturn = stunAddressDiscoverer_v4.
determineAddress(); determineAddress();
assertEquals(expectedReturn, actualReturn, assertEquals(
"The StunAddressDiscoverer failed for a no-udp environment."); "The StunAddressDiscoverer failed for a no-udp environment.",
expectedReturn, actualReturn);
} }
} }

View File

@ -17,12 +17,11 @@
*/ */
package org.ice4j.stunclient; package org.ice4j.stunclient;
import static org.junit.jupiter.api.Assertions.*; import junit.framework.*;
import org.ice4j.*; import org.ice4j.*;
import org.ice4j.message.*; import org.ice4j.message.*;
import org.ice4j.stack.*; import org.ice4j.stack.*;
import org.junit.jupiter.api.*;
/** /**
* The StunAddressDiscovererTest_XXX set of tests were created to verify stun * The StunAddressDiscovererTest_XXX set of tests were created to verify stun
@ -34,24 +33,31 @@ import org.junit.jupiter.api.*;
* <p>Company: Net Research Team, Louis Pasteur University</p> * <p>Company: Net Research Team, Louis Pasteur University</p>
* @author Emil Ivov * @author Emil Ivov
*/ */
public class StunAddressDiscovererTest_v6 public class StunAddressDiscovererTest_v6 extends TestCase
{ {
private NetworkConfigurationDiscoveryProcess stunAddressDiscoverer = null; private NetworkConfigurationDiscoveryProcess stunAddressDiscoverer = null;
private final TransportAddress discovererAddress private TransportAddress discovererAddress
= new TransportAddress("::1", 16555, Transport.UDP); = new TransportAddress("::1", 16555, Transport.UDP);
private ResponseSequenceServer responseServer = null; private ResponseSequenceServer responseServer = null;
private final TransportAddress responseServerAddress private TransportAddress responseServerAddress
= new TransportAddress("::1", 20999, Transport.UDP); = new TransportAddress("::1", 20999, Transport.UDP);
private final TransportAddress mappedClientAddress = new TransportAddress( private TransportAddress mappedClientAddress = new TransportAddress(
"2001:660:4701:1001:ff::1", 16612, Transport.UDP); "2001:660:4701:1001:ff::1", 16612, Transport.UDP);
private final TransportAddress mappedClientAddressPort2 = new TransportAddress( private TransportAddress mappedClientAddressPort2 = new TransportAddress(
"2001:660:4701:1001:ff::1", 16611, Transport.UDP); "2001:660:4701:1001:ff::1", 16611, Transport.UDP);
@BeforeEach public StunAddressDiscovererTest_v6(String name)
public void setUp() throws Exception throws StunException
{ {
super(name);
}
protected void setUp() throws Exception
{
super.setUp();
StunStack stunStack = new StunStack(); StunStack stunStack = new StunStack();
responseServer responseServer
@ -68,14 +74,15 @@ public class StunAddressDiscovererTest_v6
System.setProperty(StackProperties.MAX_CTRAN_RETRANSMISSIONS, "2"); System.setProperty(StackProperties.MAX_CTRAN_RETRANSMISSIONS, "2");
} }
@AfterEach protected void tearDown() throws Exception
public void tearDown() throws Exception
{ {
System.clearProperty(StackProperties.MAX_CTRAN_RETRANS_TIMER); System.clearProperty(StackProperties.MAX_CTRAN_RETRANS_TIMER);
System.clearProperty(StackProperties.MAX_CTRAN_RETRANSMISSIONS); System.clearProperty(StackProperties.MAX_CTRAN_RETRANSMISSIONS);
responseServer.shutDown(); responseServer.shutDown();
stunAddressDiscoverer.shutDown(); stunAddressDiscoverer.shutDown();
stunAddressDiscoverer = null; stunAddressDiscoverer = null;
super.tearDown();
} }
/** /**
@ -83,7 +90,6 @@ public class StunAddressDiscovererTest_v6
* it concludes it's in a network where UDP is blocked. * it concludes it's in a network where UDP is blocked.
* @throws Exception if anything goes wrong ( surprised? ). * @throws Exception if anything goes wrong ( surprised? ).
*/ */
@Test
public void testRecognizeBlockedUDP() public void testRecognizeBlockedUDP()
throws Exception throws Exception
{ {
@ -95,17 +101,20 @@ public class StunAddressDiscovererTest_v6
StunDiscoveryReport actualReturn StunDiscoveryReport actualReturn
= stunAddressDiscoverer.determineAddress(); = stunAddressDiscoverer.determineAddress();
assertEquals(expectedReturn, actualReturn, assertEquals(
"The StunAddressDiscoverer failed for a no-udp environment."); "The StunAddressDiscoverer failed for a no-udp environment.",
expectedReturn,
actualReturn);
} }
/** /**
* Performs a test where no responces are given the stun client so that * Performs a test where no responces are given the stun client so that
* it concludes it is behind a Symmetric NAT. * it concludes it is behind a Symmetric NAT.
* *
* @throws Exception if anything goes wrong ( surprised? ). * @throws Exception if anything goes wrong ( surprised? ).
*/ */
@Test
public void testRecognizeSymmetricNat() public void testRecognizeSymmetricNat()
throws Exception throws Exception
{ {
@ -130,8 +139,10 @@ public class StunAddressDiscovererTest_v6
StunDiscoveryReport actualReturn StunDiscoveryReport actualReturn
= stunAddressDiscoverer.determineAddress(); = stunAddressDiscoverer.determineAddress();
assertEquals(expectedReturn, actualReturn, assertEquals("The StunAddressDiscoverer failed for a "
"The StunAddressDiscoverer failed for a no-udp environment."); +"no-udp environment.",
expectedReturn, actualReturn);
} }
/** /**
@ -139,7 +150,6 @@ public class StunAddressDiscovererTest_v6
* it concludes it is behind a Port Restricted Cone. * it concludes it is behind a Port Restricted Cone.
* @throws Exception if anything goes wrong ( surprised? ). * @throws Exception if anything goes wrong ( surprised? ).
*/ */
@Test
public void testRecognizePortRestrictedCone() public void testRecognizePortRestrictedCone()
throws Exception throws Exception
{ {
@ -164,8 +174,10 @@ public class StunAddressDiscovererTest_v6
StunDiscoveryReport actualReturn StunDiscoveryReport actualReturn
= stunAddressDiscoverer.determineAddress(); = stunAddressDiscoverer.determineAddress();
assertEquals(expectedReturn, actualReturn, assertEquals("The StunAddressDiscoverer failed for"
"The StunAddressDiscoverer failed for a no-udp environment."); +" a no-udp environment.",
expectedReturn, actualReturn);
} }
/** /**
@ -173,7 +185,6 @@ public class StunAddressDiscovererTest_v6
* it concludes it is behind a Restricted Cone. * it concludes it is behind a Restricted Cone.
* @throws Exception if anything goes wrong ( surprised? ). * @throws Exception if anything goes wrong ( surprised? ).
*/ */
@Test
public void testRecognizeRestrictedCone() public void testRecognizeRestrictedCone()
throws Exception throws Exception
{ {
@ -198,8 +209,10 @@ public class StunAddressDiscovererTest_v6
StunDiscoveryReport actualReturn StunDiscoveryReport actualReturn
= stunAddressDiscoverer.determineAddress(); = stunAddressDiscoverer.determineAddress();
assertEquals(expectedReturn, actualReturn, assertEquals(
"The StunAddressDiscoverer failed for a no-udp environment."); "The StunAddressDiscoverer failed for a no-udp environment.",
expectedReturn, actualReturn);
} }
/** /**
@ -207,7 +220,6 @@ public class StunAddressDiscovererTest_v6
* it concludes it is behind a Full Cone. * it concludes it is behind a Full Cone.
* @throws Exception if anything goes wrong ( surprised? ). * @throws Exception if anything goes wrong ( surprised? ).
*/ */
@Test
public void testRecognizeFullCone() throws Exception public void testRecognizeFullCone() throws Exception
{ {
//define the server response sequence //define the server response sequence
@ -226,8 +238,10 @@ public class StunAddressDiscovererTest_v6
StunDiscoveryReport actualReturn = stunAddressDiscoverer StunDiscoveryReport actualReturn = stunAddressDiscoverer
.determineAddress(); .determineAddress();
assertEquals(expectedReturn, actualReturn, assertEquals(
"The StunAddressDiscoverer failed for a no-udp environment."); "The StunAddressDiscoverer failed for a no-udp environment.",
expectedReturn, actualReturn);
} }
/** /**
@ -235,7 +249,6 @@ public class StunAddressDiscovererTest_v6
* it concludes it is behind a UDP Symmetric Firewall. * it concludes it is behind a UDP Symmetric Firewall.
* @throws Exception if anything goes wrong ( surprised? ). * @throws Exception if anything goes wrong ( surprised? ).
*/ */
@Test
public void testRecognizeUdpSymmetricFirewall() public void testRecognizeUdpSymmetricFirewall()
throws Exception throws Exception
{ {
@ -254,8 +267,10 @@ public class StunAddressDiscovererTest_v6
StunDiscoveryReport actualReturn = stunAddressDiscoverer StunDiscoveryReport actualReturn = stunAddressDiscoverer
.determineAddress(); .determineAddress();
assertEquals(expectedReturn, actualReturn, assertEquals(
"The StunAddressDiscoverer failed for a no-udp environment."); "The StunAddressDiscoverer failed for a no-udp environment.",
expectedReturn, actualReturn);
} }
/** /**
@ -263,7 +278,6 @@ public class StunAddressDiscovererTest_v6
* it concludes it is behind a Open Internet. * it concludes it is behind a Open Internet.
* @throws Exception if anything goes wrong ( surprised? ). * @throws Exception if anything goes wrong ( surprised? ).
*/ */
@Test
public void testRecognizeOpenInternet() public void testRecognizeOpenInternet()
throws Exception throws Exception
{ {
@ -283,7 +297,9 @@ public class StunAddressDiscovererTest_v6
StunDiscoveryReport actualReturn = stunAddressDiscoverer. StunDiscoveryReport actualReturn = stunAddressDiscoverer.
determineAddress(); determineAddress();
assertEquals(expectedReturn, actualReturn, assertEquals(
"The StunAddressDiscoverer failed for a no-udp environment."); "The StunAddressDiscoverer failed for a no-udp environment.",
expectedReturn, actualReturn);
} }
} }

View File

@ -0,0 +1,62 @@
package org.ice4j.util;
import java.util.concurrent.*;
/**
* Concrete dummy implementation of PacketQueue. Intended for launching tests
* against base implementation of PacketQueue.
*
* @author Yura Yaroshevich
*/
class DummyQueue
extends PacketQueue<DummyQueue.Dummy>
{
DummyQueue(
int capacity,
PacketHandler<Dummy> packetHandler,
ExecutorService executor)
{
super(capacity, false, false, "DummyQueue", packetHandler,
executor);
}
DummyQueue(int capacity)
{
super(capacity, false, false, "DummyQueue", null, null);
}
@Override
public byte[] getBuffer(Dummy pkt)
{
return null;
}
@Override
public int getOffset(Dummy pkt)
{
return 0;
}
@Override
public int getLength(Dummy pkt)
{
return 0;
}
@Override
public Object getContext(Dummy pkt)
{
return null;
}
@Override
protected Dummy createPacket(byte[] buf, int off, int len,
Object context)
{
return new Dummy();
}
static class Dummy {
int id;
}
}

View File

@ -0,0 +1,236 @@
package org.ice4j.util;
import org.junit.*;
import java.time.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.logging.Logger; // Disambiguation
/**
* Contains test for checking performance aspects of various
* PacketQueue configuration
*
* @author Yura Yaroshevich
*/
@Ignore("Check only performance aspect of PacketQueue")
public class PacketQueueBenchmarkTests
{
/**
* The <tt>Logger</tt> used by the <tt>PacketQueueBenchmarkTests</tt> class
* and its instances for logging output.
*/
private static final java.util.logging.Logger logger
= Logger.getLogger(PacketQueueBenchmarkTests.class.getName());
/**
* Number of iteration to run benchmark and compute
* average execution time.
*/
private final int numberOfBenchmarkIterations = 100;
/**
* Simulates number of concurrent existing PacketQueue instances inside
* application. In case of JVB it is linear to number of connected peers
* to JVB instance.
*/
private final int numberOfQueues = 800;
/**
* Simulates number of messages processed via single PacketQueue
*/
private final int numberOfItemsInQueue = 1000;
/**
* Simulates the computation "weight" of single item processed by
* PacketQueue
*/
private final int singleQueueItemProcessingWeight = 300;
@Test
public void testMultiplePacketQueueThroughputWithThreadPerQueue()
throws Exception
{
/*
* This test roughly simulates initial implementation of PacketQueue
* when each PacketQueue instance has it's own processing thread
*/
measureBenchmark("ThreadPerQueuePool", () -> {
final ExecutorService executorService
= Executors.newFixedThreadPool(numberOfQueues);
Duration duration = runBenchmark(
executorService,
-1 /* Disable cooperative multi-tasking mode,
which is not relevant when each queue has it's own processing
thread*/);
executorService.shutdownNow();
return duration;
});
}
@Test
public void testMultiplePacketQueueThroughputWithCachedThreadPerQueue()
throws Exception
{
/*
* This test is slight modification of previous test, but now threads
* are re-used between PacketQueues when possible.
*/
measureBenchmark("CachedThreadPerQueuePool", () -> {
final ExecutorService executorService
= Executors.newCachedThreadPool();
Duration duration = runBenchmark(
executorService,
-1 /* Disable cooperative multi-tasking mode,
which is not relevant when each queue has it's own processing
thread*/);
executorService.shutdownNow();
return duration;
});
}
@Test
public void testMultiplePacketQueueThroughputWithFixedSizePool()
throws Exception
{
/*
* This test creates pool with limited number of threads, all
* PacketQueues share threads in cooperative multi-tasking mode.
*/
measureBenchmark("FixedSizeCPUBoundPool", () -> {
final ExecutorService executorService
= Executors.newFixedThreadPool(
Runtime.getRuntime().availableProcessors());
Duration duration = runBenchmark(
executorService,
50 /* Because queues will share executor
with limited number of threads, so configure cooperative
multi-tasking mode*/);
executorService.shutdownNow();
return duration;
});
}
@Test
public void testMultiplePacketQueueThroughputWithForkJoinPool()
throws Exception
{
/*
* This test check proposed change to PacketQueue implementation when
* all created PacketQueues share single ExecutorService with limited
* number of threads. Execution starvation is resolved by implementing
* cooperative multi-tasking when each PacketQueue release it's thread
* borrowed for ExecutorService so other PacketQueue instances can
* proceed with execution.
* This modification has noticeable better performance when executed
* on system which is already loaded by other concurrent tasks.
*/
measureBenchmark("ForkJoinCPUBoundPool", () -> {
final ExecutorService executorService
= Executors.newWorkStealingPool(
Runtime.getRuntime().availableProcessors());
Duration duration = runBenchmark(
executorService,
50 /* Because queues will share executor
with limited number of threads, so configure cooperative
multi-tasking mode*/);
executorService.shutdownNow();
return duration;
});
}
private Duration runBenchmark(
final ExecutorService executor,
final long maxSequentiallyPackets)
throws InterruptedException
{
final CountDownLatch completionGuard
= new CountDownLatch(numberOfItemsInQueue * numberOfQueues);
final ArrayList<DummyQueue> queues = new ArrayList<>();
for (int i = 0; i < numberOfQueues; i++) {
queues.add(new DummyQueue(
numberOfItemsInQueue,
new PacketQueue.PacketHandler<DummyQueue.Dummy>()
{
@Override
public boolean handlePacket(DummyQueue.Dummy pkt)
{
double result = 0;
// some dummy computationally exp
final int end
= pkt.id + singleQueueItemProcessingWeight;
for (int i = pkt.id; i < end; i++)
{
result += Math.log(Math.sqrt(i));
}
completionGuard.countDown();
return result > 0;
}
@Override
public long maxSequentiallyProcessedPackets()
{
return maxSequentiallyPackets;
}
},
executor));
}
long startTime = System.nanoTime();
for (DummyQueue queue : queues)
{
for (int i = 0; i < numberOfItemsInQueue; i++)
{
queue.add(new DummyQueue.Dummy());
}
}
completionGuard.await();
long endTime = System.nanoTime();
for (DummyQueue queue : queues) {
queue.close();
}
return Duration.ofNanos(endTime - startTime);
}
private void measureBenchmark(String name, Callable<Duration> runWithDuration) throws Exception
{
final ArrayList<Duration> experimentDuration = new ArrayList<>();
for (int i = 0; i < 1 + numberOfBenchmarkIterations; i++)
{
System.gc();
final Duration duration = runWithDuration.call();
if (i != 0)
{
experimentDuration.add(duration);
}
}
long totalNanos = 0;
for (Duration duration : experimentDuration)
{
totalNanos += duration.toNanos();
}
long averageNanos = totalNanos / experimentDuration.size();
long sumSquares = 0;
for (Duration duration : experimentDuration)
{
long diff = Math.abs(duration.toNanos() - averageNanos);
sumSquares = diff * diff;
}
double stdDev
= Math.sqrt((1.0 / (experimentDuration.size() - 1)) * sumSquares);
System.out.println(name
+ " : avg = " + TimeUnit.NANOSECONDS.toMillis(averageNanos) + " ms"
+ ", std_dev = " + TimeUnit.NANOSECONDS.toMillis((long)stdDev) + " ms");
}
}

View File

@ -0,0 +1,357 @@
package org.ice4j.util;
import org.junit.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import java.util.function.*;
import java.util.logging.Logger; // Disambiguation
/**
* Test various aspects of {@link PacketQueue} implementation.
*
* @author Yura Yaroshevich
*/
public class PacketQueueTests
{
/**
* The <tt>Logger</tt> used by the <tt>PacketQueueTests</tt> class and
* its instances for logging output.
*/
private static final java.util.logging.Logger logger
= Logger.getLogger(PacketQueueTests.class.getName());
@Test
public void testAddingItemToQueueNotifiesBlockedThreadsImmediately()
throws Exception
{
final DummyQueue dummyQueue = new DummyQueue(10);
final CompletableFuture<DummyQueue.Dummy> dummyItem =
CompletableFuture.supplyAsync(dummyQueue::get);
try
{
// This block surrounded with try/catch necessary to ensure that
// thread calling PacketQueue::get blocked before items is added
// to queue. Giving 50ms for CompletableFuture to stuck on get.
final DummyQueue.Dummy nullDummy
= dummyItem.get(50, TimeUnit.MILLISECONDS);
Assert.fail("There is no items in queue, must not be here");
}
catch (TimeoutException e)
{
// no item is added during 50 ms into queue.
}
final DummyQueue.Dummy pushedItem = new DummyQueue.Dummy();
dummyQueue.add(pushedItem);
try
{
// checks that thread stuck in PacketQueue::get notified
// "immediately" when item added to queue. Giving a few ms for
// CompletableFuture to transit to completed state.
final DummyQueue.Dummy poppedItem = dummyItem.get(
50, TimeUnit.MILLISECONDS);
Assert.assertEquals(pushedItem, poppedItem);
}
catch (TimeoutException e)
{
Assert.fail("Expected that blocked thread notified immediately "
+ "about item added to queue");
}
}
@Test
public void testClosingQueueImmediatelyNotifiesAllThreadsBlockedOnGet()
throws Exception
{
final DummyQueue dummyQueue = new DummyQueue(10);
final ArrayList<CompletableFuture<DummyQueue.Dummy>>
dummyItems = new ArrayList<>();
for (int i = 0; i < ForkJoinPool.getCommonPoolParallelism(); i++)
{
dummyItems.add(CompletableFuture.supplyAsync(dummyQueue::get));
}
for (CompletableFuture<DummyQueue.Dummy> dummyItem : dummyItems)
{
try
{
// This block surrounded with try/catch necessary to ensure that
// thread calling PacketQueue::get blocked before items is added
// to queue. Giving 50ms for CompletableFuture to stuck on get.
final DummyQueue.Dummy nullDummy
= dummyItem.get(50, TimeUnit.MILLISECONDS);
Assert.fail("There is no items in queue, must not be here");
}
catch (TimeoutException e)
{
// no item is added during 50 ms into queue.
}
}
dummyQueue.close();
for (CompletableFuture<DummyQueue.Dummy> dummyItem : dummyItems)
{
try
{
// checks that thread stuck in PacketQueue::get notified
// "immediately" when PacketQueue is stopped. Giving 1 ms for
// CompletableFuture to transit to completed state.
final DummyQueue.Dummy poppedItem = dummyItem.get(
1, TimeUnit.MILLISECONDS);
Assert.assertNull("When PacketQueue is closed "
+ "null must be returned", poppedItem);
}
catch (TimeoutException e)
{
Assert.fail("Expected that blocked thread notified immediately "
+ "when queue is stopped");
}
}
}
@Test
public void testAddingWhenCapacityReachedRemovesOldestItem()
{
final int capacity = 10;
final DummyQueue dummyQueue = new DummyQueue(capacity);
for (int i = 0; i < capacity + 1; i++)
{
DummyQueue.Dummy item = new DummyQueue.Dummy();
item.id = i;
dummyQueue.add(item);
}
for (int i = 0; i < capacity + 1; i++)
{
final DummyQueue.Dummy item = dummyQueue.poll();
if (i == capacity)
{
Assert.assertNull(item);
}
else
{
Assert.assertNotEquals("Oldest item must be removed when "
+ "item exceeding capacity added", 0, item.id);
}
}
}
@Test
public void testPacketQueueReaderThreadIsReleasedWhenPacketQueueEmpty()
throws Exception
{
final ExecutorService singleThreadExecutor
= Executors.newSingleThreadExecutor();
final CountDownLatch queueCompletion = new CountDownLatch(1);
final DummyQueue queue = new DummyQueue(
10,
pkt -> {
queueCompletion.countDown();
return true;
},
singleThreadExecutor);
queue.add(new DummyQueue.Dummy());
final boolean completed
= queueCompletion.await(50, TimeUnit.MILLISECONDS);
Assert.assertTrue("Expected all queued items are handled "
+ "at this time point", completed);
Future<?> executorCompletion = singleThreadExecutor.submit(() -> {
// do nothing, just pump Runnable via executor's thread to
// verify it's not stuck
});
try
{
executorCompletion.get(10, TimeUnit.MILLISECONDS);
}
catch (TimeoutException e)
{
Assert.fail("Executors thread must be released by PacketQueue "
+ "when queue is empty");
}
singleThreadExecutor.shutdownNow();
}
@Test
public void testPacketQueueCooperativeMultiTaskingWhenSharingExecutor()
throws Exception
{
final int maxSequentiallyProcessedPackets = 1;
final int queueCapacity = 10 * maxSequentiallyProcessedPackets;
final CountDownLatch completionGuard
= new CountDownLatch(2 * queueCapacity);
final ExecutorService singleThreadExecutor
= Executors.newSingleThreadExecutor();
final AtomicInteger queue1Counter = new AtomicInteger();
final AtomicInteger queue2Counter = new AtomicInteger();
final AtomicBoolean queuesEvenlyProcessed
= new AtomicBoolean(true);
final BiFunction<AtomicInteger,
AtomicInteger,
PacketQueue.PacketHandler<DummyQueue.Dummy>>
newPacketQueue = (AtomicInteger self, AtomicInteger other) ->
new PacketQueue.PacketHandler<DummyQueue.Dummy>()
{
@Override
public boolean handlePacket(DummyQueue.Dummy pkt)
{
int diff = Math.abs(
self.incrementAndGet() - other.get());
queuesEvenlyProcessed.set(queuesEvenlyProcessed.get()
&& diff <= maxSequentiallyProcessedPackets());
completionGuard.countDown();
return false;
}
@Override
public long maxSequentiallyProcessedPackets()
{
return maxSequentiallyProcessedPackets;
}
};
final DummyQueue queue1 = new DummyQueue(
queueCapacity,
newPacketQueue.apply(queue1Counter, queue2Counter),
singleThreadExecutor);
final DummyQueue queue2 = new DummyQueue(
queueCapacity,
newPacketQueue.apply(queue2Counter, queue1Counter),
singleThreadExecutor);
for (int i = 0; i < queueCapacity; i++)
{
queue1.add(new DummyQueue.Dummy());
queue2.add(new DummyQueue.Dummy());
}
final boolean completed
= completionGuard.await(1, TimeUnit.SECONDS);
Assert.assertTrue("Expected all queued items are handled "
+ "at this time point", completed);
Assert.assertTrue(
"Queues sharing same thread with configured cooperative"
+ " multi-tasking must yield execution to be processed evenly",
queuesEvenlyProcessed.get());
singleThreadExecutor.shutdownNow();
}
@Test
public void testManyQueuesCanShareSingleThread()
throws Exception
{
final ExecutorService singleThreadedExecutor
= Executors.newSingleThreadExecutor();
final int numberOfQueues = 1_000_000;
final ArrayList<DummyQueue> queues = new ArrayList<>();
final CountDownLatch completionGuard
= new CountDownLatch(numberOfQueues);
for (int i = 0; i < numberOfQueues; i++)
{
queues.add(new DummyQueue(1,
pkt -> {
completionGuard.countDown();
return true;
},
singleThreadedExecutor));
}
final DummyQueue.Dummy dummyPacket = new DummyQueue.Dummy();
for (DummyQueue queue : queues)
{
// Push item for processing to cause borrowing execution
// thread from ExecutorService
queue.add(dummyPacket);
}
final boolean completed
= completionGuard.await(1, TimeUnit.SECONDS);
Assert.assertTrue("Expected all queued items are handled "
+ "at this time point", completed);
final List<Runnable> packetReaders
= singleThreadedExecutor.shutdownNow();
Assert.assertEquals("Queues must not utilize thread when"
+ "there is no work.", 0, packetReaders.size());
for (DummyQueue queue : queues)
{
queue.close();
}
}
@Test
public void testReleasePacketCalledForPacketsPoppedDueToQueueOverflow()
throws Exception
{
final ExecutorService singleThreadedExecutor
= Executors.newSingleThreadExecutor();
final List<DummyQueue.Dummy> releasedPackets = new ArrayList<>();
final int queueCapacity = 1;
final DummyQueue queue = new DummyQueue(queueCapacity)
{
@Override
protected void releasePacket(Dummy pkt)
{
releasedPackets.add(pkt);
}
};
final int itemsToEnqueue = 10;
for (int i = 0; i < itemsToEnqueue; i++)
{
final DummyQueue.Dummy dummy = new DummyQueue.Dummy();
dummy.id = i + 1;
queue.add(dummy);
}
Assert.assertEquals(
itemsToEnqueue - queueCapacity, releasedPackets.size());
int seed = 1;
for (DummyQueue.Dummy releasedPacket : releasedPackets)
{
Assert.assertEquals(seed, releasedPacket.id);
seed++;
}
singleThreadedExecutor.shutdown();
}
}

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