Compare commits

..

No commits in common. "master" and "stable/jitsi-meet_3547" have entirely different histories.

174 changed files with 8115 additions and 6007 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>

416
pom.xml
View File

@ -1,119 +1,42 @@
<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>
<groupId>org.jitsi</groupId> <parent>
<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> <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>
@ -121,172 +44,58 @@
<build> <build>
<plugins> <plugins>
<plugin> <plugin>
<groupId>org.jetbrains.kotlin</groupId> <groupId>org.apache.felix</groupId>
<artifactId>kotlin-maven-plugin</artifactId> <artifactId>maven-bundle-plugin</artifactId>
<version>${kotlin.version}</version>
<executions>
<execution>
<id>compile</id>
<phase>compile</phase>
<goals>
<goal>compile</goal>
</goals>
<configuration>
<sourceDirs>
<sourceDir>${project.basedir}/src/main/kotlin</sourceDir>
<sourceDir>${project.basedir}/src/main/java</sourceDir>
</sourceDirs>
</configuration>
</execution>
<execution>
<id>test-compile</id>
<phase>test-compile</phase>
<goals>
<goal>test-compile</goal>
</goals>
<configuration>
<sourceDirs>
<sourceDir>${project.basedir}/src/test/kotlin</sourceDir>
<sourceDir>${project.basedir}/src/test/java</sourceDir>
</sourceDirs>
</configuration>
</execution>
</executions>
<configuration>
<jvmTarget>11</jvmTarget>
<args>
<arg>-Xallow-result-return-type</arg>
</args>
</configuration>
</plugin> </plugin>
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId> <artifactId>maven-javadoc-plugin</artifactId>
<version>3.10.1</version> <version>2.10.4</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> <show>private</show>
<compilerArgs> <nohelp>true</nohelp>
<arg>-Xlint:all</arg>
</compilerArgs>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId>
<version>3.1.2</version>
<configuration>
<configLocation>checkstyle.xml</configLocation>
</configuration>
<dependencies>
<dependency>
<groupId>com.puppycrawl.tools</groupId>
<artifactId>checkstyle</artifactId>
<version>10.1</version>
</dependency>
</dependencies>
<executions>
<execution>
<goals>
<goal>check</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>com.github.gantsign.maven</groupId>
<artifactId>ktlint-maven-plugin</artifactId>
<version>3.0.0</version>
<configuration>
<sourceRoots>
<sourceRoot>${project.basedir}/src/main/kotlin</sourceRoot>
</sourceRoots>
<testSourceRoots>
<testSourceRoot>${project.basedir}/src/test/kotlin</testSourceRoot>
</testSourceRoots>
</configuration>
<executions>
<execution>
<id>check</id>
<goals>
<goal>check</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>biz.aQute.bnd</groupId>
<artifactId>bnd-maven-plugin</artifactId>
<version>6.2.0</version>
<executions>
<execution>
<goals>
<goal>bnd-process</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>3.2.2</version>
<configuration>
<archive>
<manifestFile>${project.build.outputDirectory}/META-INF/MANIFEST.MF</manifestFile>
</archive>
</configuration> </configuration>
</plugin> </plugin>
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId> <artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M6</version>
<configuration> <configuration>
<includes>**/*</includes> <includes>
<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 +104,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>
@ -319,31 +127,25 @@
<profiles> <profiles>
<profile> <profile>
<id>coverage</id> <id>skip-pre-jdk8</id>
<activation>
<jdk>(,1.8)</jdk>
</activation>
<build> <build>
<plugins> <plugins>
<plugin> <plugin>
<groupId>org.jacoco</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>jacoco-maven-plugin</artifactId> <artifactId>maven-compiler-plugin</artifactId>
<version>0.8.8</version> <configuration>
<executions> <excludes>
<execution> <exclude>**/jdk8/**</exclude>
<goals> </excludes>
<goal>prepare-agent</goal> </configuration>
</goals>
</execution>
<execution>
<id>report</id>
<phase>test</phase>
<goals>
<goal>report</goal>
</goals>
</execution>
</executions>
</plugin> </plugin>
</plugins> </plugins>
</build> </build>
</profile> </profile>
<profile> <profile>
<id>run-sample</id> <id>run-sample</id>
<build> <build>
@ -448,95 +250,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 IPv6
* link local addresses should not be used for candidate allocations.
*/
public static final String DISABLE_LINK_LOCAL_ADDRESSES
= "org.ice4j.ice.harvest.DISABLE_LINK_LOCAL_ADDRESSES";
/** /**
* The name of the property which specifies a ";"-separated list of IP * The name of the property which specifies a ";"-separated list of IP
* addresses that are not allowed to be used for host candidate allocations. * addresses that are not allowed to be used for host candidate allocations.
@ -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

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

View File

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

View File

@ -176,7 +176,7 @@ abstract class AddressAttribute extends Attribute
return false; return false;
//addresses //addresses
if ( att.getAddress() == null && getAddress() == null) if( att.getAddress() == null && getAddress() == null)
return true; return true;
return true; return true;
@ -221,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);
} }
@ -309,7 +307,7 @@ abstract class AddressAttribute extends Attribute
//address //address
byte address[] = null; byte address[] = null;
if (family == ADDRESS_FAMILY_IPV6) if(family == ADDRESS_FAMILY_IPV6)
{ {
address = new byte[16]; address = new byte[16];
} }

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -308,12 +308,12 @@ public class MessageIntegrityAttribute
logger.warning("Can not encode a message of type Indication."); logger.warning("Can not encode a message of type Indication.");
} }
Objects.requireNonNull(key, "key=null; msgType=" + 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

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

File diff suppressed because it is too large Load Diff

View File

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

View File

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

View File

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

View File

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

View File

@ -17,11 +17,11 @@
*/ */
package org.ice4j.ice; package org.ice4j.ice;
import org.jitsi.utils.logging2.*;
import java.beans.*; import java.beans.*;
import java.util.*; import java.util.*;
import org.ice4j.util.Logger;
/** /**
* A check list is a list of <tt>CandidatePair</tt>s with a state (i.e. a * A check list is a list of <tt>CandidatePair</tt>s with a state (i.e. a
* <tt>CheckListState</tt>). The pairs in a check list are those that an ICE * <tt>CheckListState</tt>). The pairs in a check list are those that an ICE
@ -35,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());
} }
/** /**
@ -135,7 +145,7 @@ public class CheckList
{ {
synchronized(triggeredCheckQueue) synchronized(triggeredCheckQueue)
{ {
if (!triggeredCheckQueue.contains(pair)) if(!triggeredCheckQueue.contains(pair))
{ {
triggeredCheckQueue.add(pair); triggeredCheckQueue.add(pair);
pair.setStateWaiting(); pair.setStateWaiting();
@ -154,7 +164,7 @@ public class CheckList
{ {
synchronized(triggeredCheckQueue) synchronized(triggeredCheckQueue)
{ {
if (triggeredCheckQueue.size() > 0) if(triggeredCheckQueue.size() > 0)
return triggeredCheckQueue.remove(0); return triggeredCheckQueue.remove(0);
} }
return null; return null;
@ -182,7 +192,7 @@ public class CheckList
{ {
if (pair.getState() == CandidatePairState.WAITING) if (pair.getState() == CandidatePairState.WAITING)
{ {
if (highestPriorityPair == null if(highestPriorityPair == null
|| pair.getPriority() > highestPriorityPair.getPriority()) || pair.getPriority() > highestPriorityPair.getPriority())
{ {
highestPriorityPair = pair; highestPriorityPair = pair;
@ -190,14 +200,14 @@ public class CheckList
} }
} }
if (highestPriorityPair != null) if(highestPriorityPair != null)
return highestPriorityPair; return highestPriorityPair;
for (CandidatePair pair : this) for (CandidatePair pair : this)
{ {
if (pair.getState() == CandidatePairState.FROZEN) if (pair.getState() == CandidatePairState.FROZEN)
{ {
if (highestPriorityPair == null if(highestPriorityPair == null
|| pair.getPriority() > highestPriorityPair.getPriority()) || pair.getPriority() > highestPriorityPair.getPriority())
{ {
highestPriorityPair = pair; highestPriorityPair = pair;
@ -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
@ -319,14 +310,14 @@ public class CheckList
Map<String, CandidatePair> pairsToWait = new Hashtable<>(); Map<String, CandidatePair> pairsToWait = new Hashtable<>();
//first, determine the pairs that we'd need to put in the waiting state. //first, determine the pairs that we'd need to put in the waiting state.
for (CandidatePair pair : this) for(CandidatePair pair : this)
{ {
//we need to check whether the pair is already in the wait list. if //we need to check whether the pair is already in the wait list. if
//so we'll compare it with this one and determine which of the two //so we'll compare it with this one and determine which of the two
//needs to stay. //needs to stay.
CandidatePair prevPair = pairsToWait.get(pair.getFoundation()); CandidatePair prevPair = pairsToWait.get(pair.getFoundation());
if (prevPair == null) if(prevPair == null)
{ {
//first pair with this foundation. //first pair with this foundation.
pairsToWait.put(pair.getFoundation(), pair); pairsToWait.put(pair.getFoundation(), pair);
@ -336,9 +327,9 @@ public class CheckList
//we already have a pair with the same foundation. determine which //we already have a pair with the same foundation. determine which
//of the two has the lower component id and higher priority and //of the two has the lower component id and higher priority and
//keep that one in the list. //keep that one in the list.
if ( prevPair.getParentComponent() == pair.getParentComponent()) if( prevPair.getParentComponent() == pair.getParentComponent())
{ {
if (pair.getPriority() > prevPair.getPriority()) if(pair.getPriority() > prevPair.getPriority())
{ {
//need to replace the pair in the list. //need to replace the pair in the list.
pairsToWait.put(pair.getFoundation(), pair); pairsToWait.put(pair.getFoundation(), pair);
@ -346,7 +337,7 @@ public class CheckList
} }
else else
{ {
if (pair.getParentComponent().getComponentID() if(pair.getParentComponent().getComponentID()
< prevPair.getParentComponent().getComponentID()) < prevPair.getParentComponent().getComponentID())
{ {
//need to replace the pair in the list. //need to replace the pair in the list.
@ -368,7 +359,7 @@ public class CheckList
protected synchronized void recomputePairPriorities() protected synchronized void recomputePairPriorities()
{ {
//first, determine the pairs that we'd need to put in the waiting state. //first, determine the pairs that we'd need to put in the waiting state.
for (CandidatePair pair : this) for(CandidatePair pair : this)
pair.computePriority(); pair.computePriority();
} }
@ -398,7 +389,7 @@ public class CheckList
{ {
Component cmp = nominatedPair.getParentComponent(); Component cmp = nominatedPair.getParentComponent();
if (cmp.getSelectedPair() != null) if(cmp.getSelectedPair() != null)
{ {
return; return;
} }
@ -410,7 +401,7 @@ public class CheckList
cmp.setSelectedPair(nominatedPair); cmp.setSelectedPair(nominatedPair);
Iterator<CandidatePair> pairsIter = iterator(); Iterator<CandidatePair> pairsIter = iterator();
while (pairsIter.hasNext()) while(pairsIter.hasNext())
{ {
CandidatePair pair = pairsIter.next(); CandidatePair pair = pairsIter.next();
if (pair.getParentComponent() == cmp if (pair.getParentComponent() == cmp
@ -427,7 +418,7 @@ public class CheckList
{ {
Iterator<CandidatePair> triggeredPairsIter Iterator<CandidatePair> triggeredPairsIter
= triggeredCheckQueue.iterator(); = triggeredCheckQueue.iterator();
while (triggeredPairsIter.hasNext()) while(triggeredPairsIter.hasNext())
{ {
CandidatePair pair = triggeredPairsIter.next(); CandidatePair pair = triggeredPairsIter.next();
if (pair.getParentComponent() == cmp if (pair.getParentComponent() == cmp
@ -493,7 +484,7 @@ public class CheckList
{ {
synchronized(stateListeners) synchronized(stateListeners)
{ {
if (!stateListeners.contains(l)) if(!stateListeners.contains(l))
this.stateListeners.add(l); this.stateListeners.add(l);
} }
} }
@ -532,7 +523,7 @@ public class CheckList
PropertyChangeEvent evt = new PropertyChangeEvent( PropertyChangeEvent evt = new PropertyChangeEvent(
this, PROPERTY_CHECK_LIST_STATE, oldState, newState); this, PROPERTY_CHECK_LIST_STATE, oldState, newState);
for (PropertyChangeListener l : listenersCopy) for(PropertyChangeListener l : listenersCopy)
{ {
l.propertyChange(evt); l.propertyChange(evt);
} }
@ -548,7 +539,7 @@ public class CheckList
{ {
synchronized(checkListeners) synchronized(checkListeners)
{ {
if (!checkListeners.contains(l)) if(!checkListeners.contains(l))
{ {
checkListeners.add(l); checkListeners.add(l);
} }
@ -564,7 +555,7 @@ public class CheckList
{ {
synchronized(checkListeners) synchronized(checkListeners)
{ {
if (checkListeners.contains(l)) if(checkListeners.contains(l))
{ {
checkListeners.remove(l); checkListeners.remove(l);
} }
@ -587,7 +578,7 @@ public class CheckList
PropertyChangeEvent evt = new PropertyChangeEvent( PropertyChangeEvent evt = new PropertyChangeEvent(
this, PROPERTY_CHECK_LIST_CHECKS, false, true); this, PROPERTY_CHECK_LIST_CHECKS, false, true);
for (PropertyChangeListener l : listenersCopy) for(PropertyChangeListener l : listenersCopy)
{ {
l.propertyChange(evt); l.propertyChange(evt);
} }

View File

@ -18,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);
} }
} }
@ -461,27 +472,7 @@ public class Component
{ {
for (CandidatePair pair : checkList) for (CandidatePair pair : checkList)
{ {
/* Check whether the pair is already in the check list. streamCheckList.add(pair);
* (This can happen for pairs with remote peer-reflexive candidates,
* since those candidates aren't added to the candidate list even
* though the pair is added to the check list).
*/
CandidatePair existingPair
= streamCheckList.findPairMatching(pair.getLocalCandidate(), pair.getRemoteCandidate());
if (existingPair != null)
{
logger.info("existing Pair updated: " +
existingPair.toShortString() +
" to " + pair.toShortString() + ".");
existingPair.setRemoteCandidate(pair.getRemoteCandidate());
existingPair.computePriority();
}
else
{
streamCheckList.add(pair);
logger.info("new Pair added: " + pair.toShortString()
+ ".");
}
} }
} }
} }
@ -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 (localCandidate.getTransportAddress().equals(address)) if (localCnd.getTransportAddress().equals(localAddress))
{ return localCnd;
if (base == null || base.equals(localCandidate.getBase()))
{
return localCandidate;
}
}
}
// In case the above loop failed to find a result because `base` was
// specified, fallback to the original behavior and return the first
// candidate matching `address` regardless of `base`.
for (LocalCandidate localCandidate : localCandidates)
{
if (localCandidate.getTransportAddress().equals(address))
{
logger.warn("Returning a candidate matching the address, "
+ "while no candidates match both address ("
+ address + ") and base (" + base +"): " + localCandidate
+ " with base " + localCandidate.getBase());
return localCandidate;
}
} }
return null; return null;
@ -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

@ -18,17 +18,15 @@
package org.ice4j.ice; package org.ice4j.ice;
import java.net.*; import java.net.*;
import java.time.*;
import java.util.*; import java.util.*;
import java.util.concurrent.*; 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.socket.*; import org.ice4j.socket.*;
import org.ice4j.stack.*; import org.ice4j.stack.*;
import org.ice4j.util.*; import org.ice4j.util.Logger; //Disambiguation
import org.jitsi.utils.logging2.Logger;
/** /**
* The class that will be generating our outgoing connectivity checks and that * The class that will be generating our outgoing connectivity checks and that
@ -40,21 +38,22 @@ 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.
*/ */
private final Agent parentAgent; private final Agent parentAgent;
/**
* A scheduled executor service to perform periodic tasks of the client
*/
private final ScheduledExecutorService scheduledExecutorService;
/**
* An executor service to perform background tasks of the client
*/
private final ExecutorService executorService;
/** /**
* The <tt>StunStack</tt> that we will use for connectivity checks. * The <tt>StunStack</tt> that we will use for connectivity checks.
*/ */
@ -63,21 +62,13 @@ class ConnectivityCheckClient
/** /**
* The {@link PaceMaker}s that are currently running checks in this client. * The {@link PaceMaker}s that are currently running checks in this client.
*/ */
private final Queue<PaceMaker> paceMakers private final List<PaceMaker> paceMakers = new LinkedList<>();
= new ConcurrentLinkedQueue<>();
/**
* Whether this {@link ConnectivityCheckClient} has been stopped.
* Synchronized by {@link #paceMakers}.
*/
private boolean stopped = false;
/** /**
* Timer that is used to let some seconds before a CheckList is considered * Timer that is used to let some seconds before a CheckList is considered
* as FAILED. * as FAILED.
*/ */
private ConcurrentMap<String, ScheduledFuture<?>> private Map<String, Timer> timers = new HashMap<>();
checkListCompletionCheckers = new ConcurrentHashMap<>();
/** /**
* A flag that determines whether we have received a STUN response or not. * A flag that determines whether we have received a STUN response or not.
@ -95,20 +86,11 @@ class ConnectivityCheckClient
* information such as user fragments for example. * information such as user fragments for example.
* *
* @param parentAgent the <tt>Agent</tt> that is creating this instance. * @param parentAgent the <tt>Agent</tt> that is creating this instance.
* @param scheduledExecutorService the <tt>ScheduledExecutorService</tt>
* to execute clients tasks
* @param executorService the <tt>ExecutorService</tt> to execute
* background tasks of connectivity check client
*/ */
public ConnectivityCheckClient( public ConnectivityCheckClient(Agent parentAgent)
Agent parentAgent,
ScheduledExecutorService scheduledExecutorService,
ExecutorService executorService)
{ {
this.parentAgent = parentAgent; this.parentAgent = parentAgent;
this.scheduledExecutorService = scheduledExecutorService; logger = new Logger(classLogger, parentAgent.getLogger());
this.executorService = executorService;
logger = parentAgent.getLogger().createChildLogger(this.getClass().getName());
stunStack = this.parentAgent.getStunStack(); stunStack = this.parentAgent.getStunStack();
} }
@ -144,7 +126,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,16 +148,13 @@ class ConnectivityCheckClient
*/ */
public void startChecks(CheckList checkList) public void startChecks(CheckList checkList)
{ {
PaceMaker paceMaker = new PaceMaker(checkList);
synchronized (paceMakers) synchronized (paceMakers)
{ {
if (stopped)
{
return;
}
PaceMaker paceMaker = new PaceMaker(checkList);
paceMakers.add(paceMaker); paceMakers.add(paceMaker);
paceMaker.schedule();
} }
paceMaker.start();
} }
/** /**
@ -195,8 +175,11 @@ class ConnectivityCheckClient
indication, indication,
candidatePair.getRemoteCandidate().getTransportAddress(), candidatePair.getRemoteCandidate().getTransportAddress(),
localCandidate.getBase().getTransportAddress()); localCandidate.getBase().getTransportAddress());
logger.trace(() -> if (logger.isLoggable(Level.FINEST))
"sending binding indication to pair " + candidatePair); {
logger.finest(
"sending binding indication to pair " + candidatePair);
}
} }
catch (Exception ex) catch (Exception ex)
{ {
@ -204,9 +187,11 @@ class ConnectivityCheckClient
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 +262,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 +306,9 @@ class ConnectivityCheckClient
tran.setApplicationData(candidatePair); tran.setApplicationData(candidatePair);
if (logger.isDebugEnabled()) logger.fine(
{ "start check for " + candidatePair.toShortString() + " tid "
logger.debug( + tran);
"start check for " + candidatePair.toShortString() + " tid "
+ tran);
}
try try
{ {
tran tran
@ -340,15 +322,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 +347,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 +387,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
} }
@ -456,12 +431,14 @@ class ConnectivityCheckClient
if ( !stream.validListContainsAllComponents()) if ( !stream.validListContainsAllComponents())
{ {
final String streamName = stream.getName(); final String streamName = stream.getName();
if (!checkListCompletionCheckers.containsKey(streamName)) Timer timer = timers.get(streamName);
{
logger.info("CheckList will failed in a few seconds" +
" if no succeeded checks come");
Runnable checkLickCompletedChecker = new Runnable() if (timer == null)
{
logger.info("CheckList will failed in a few seconds if no" +
"succeeded checks come");
TimerTask task = new TimerTask()
{ {
@Override @Override
public void run() public void run()
@ -476,20 +453,9 @@ class ConnectivityCheckClient
} }
} }
}; };
timer = new Timer();
final ScheduledFuture<?> scheduledCheckerFuture timers.put(streamName, timer);
= scheduledExecutorService.schedule( timer.schedule(task, 5000);
checkLickCompletedChecker,
5000,
TimeUnit.MILLISECONDS);
final ScheduledFuture<?> existingCheckerFuture
= checkListCompletionCheckers
.putIfAbsent(streamName, scheduledCheckerFuture);
if (existingCheckerFuture != null)
{
scheduledCheckerFuture.cancel(false);
}
} }
} }
@ -533,10 +499,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 +525,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 +573,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 +611,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 +621,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 +693,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 +706,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 +733,7 @@ class ConnectivityCheckClient
} }
else else
{ {
logger.debug(() -> logger.fine(
"Keep alive for pair: " + validPair.toShortString()); "Keep alive for pair: " + validPair.toShortString());
} }
} }
@ -838,7 +803,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 +811,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 +820,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();
} }
} }
@ -884,11 +847,17 @@ class ConnectivityCheckClient
} }
/** /**
* A class to control periodically scheduled runnable that actually sends * The thread that actually sends the checks for a particular check list
* the checks for a particular check list in the pace defined in RFC 5245. * in the pace defined in RFC 5245.
*/ */
private final class PaceMaker extends PeriodicRunnable private class PaceMaker
extends Thread
{ {
/**
* Indicates whether this <tt>Thread</tt> should still be running.
*/
boolean running = true;
/** /**
* The {@link CheckList} that this <tt>PaceMaker</tt> will be running * The {@link CheckList} that this <tt>PaceMaker</tt> will be running
* checks for. * checks for.
@ -904,63 +873,18 @@ class ConnectivityCheckClient
*/ */
public PaceMaker(CheckList checkList) public PaceMaker(CheckList checkList)
{ {
super(scheduledExecutorService, executorService); super("ICE PaceMaker: " + parentAgent.getLocalUfrag());
this.checkList = checkList; this.checkList = checkList;
}
/** /*
* Sends connectivity checks at the pace determined by the {@link * Because PaceMaker does not seem to be a daemon at least on Ubuntu
* Agent#calculateTa()} method and using either the trigger check queue * in the run-sample target and it looks like it should be from the
* or the regular check lists. * standpoint of the application, explicitly tell it to be a daemon.
*/ * Otherwise, it could prevent the application from exiting because
@Override * of a problem in the ICE implementation.
protected void run() */
{ setDaemon(true);
CandidatePair pairToCheck = checkList.popTriggeredCheck();
//if there are no triggered checks, go for an ordinary one.
if (pairToCheck == null)
{
pairToCheck = checkList.getNextOrdinaryPairToCheck();
}
if (pairToCheck != null)
{
/*
* Since we suspect that it is possible to
* startCheckForPair, processSuccessResponse and only
* then setStateInProgress, we'll synchronize. The
* synchronization root is the one of the
* CandidatePair#setState method.
*/
synchronized (pairToCheck)
{
TransactionID transactionID
= startCheckForPair(pairToCheck);
if (transactionID == null)
{
logger.info(
"Pair failed: "
+ pairToCheck.toShortString());
pairToCheck.setStateFailed();
}
else
{
pairToCheck.setStateInProgress(transactionID);
}
}
}
else
{
/*
* We are done sending checks for this list. We'll set
* its final state in either the processResponse(),
* processTimeout() or processFailure() method.
*/
logger.trace(() -> "will skip a check beat.");
checkList.fireEndOfOrdinaryChecks();
}
} }
/** /**
@ -970,7 +894,7 @@ class ConnectivityCheckClient
* @return the number milliseconds to wait before we send the next * @return the number milliseconds to wait before we send the next
* check. * check.
*/ */
protected Duration getDelayUntilNextRun() private long getNextWaitInterval()
{ {
int activeCheckLists = parentAgent.getActiveCheckListCount(); int activeCheckLists = parentAgent.getActiveCheckListCount();
@ -981,7 +905,96 @@ class ConnectivityCheckClient
activeCheckLists = 1; activeCheckLists = 1;
} }
return Duration.ofMillis(parentAgent.calculateTa() * activeCheckLists); return parentAgent.calculateTa() * activeCheckLists;
}
/**
* Sends connectivity checks at the pace determined by the {@link
* Agent#calculateTa()} method and using either the trigger check queue
* or the regular check lists.
*/
@Override
public synchronized void run()
{
try
{
while(running)
{
long waitFor = getNextWaitInterval();
if (waitFor > 0)
{
/*
* waitFor will be 0 for the first check since we won't
* have any active check lists at that point yet.
*/
try
{
wait(waitFor);
}
catch (InterruptedException e)
{
logger.log(Level.FINER, "PaceMaker got interrupted",
e);
}
if (!running)
break;
}
CandidatePair pairToCheck = checkList.popTriggeredCheck();
//if there are no triggered checks, go for an ordinary one.
if (pairToCheck == null)
pairToCheck = checkList.getNextOrdinaryPairToCheck();
if (pairToCheck != null)
{
/*
* Since we suspect that it is possible to
* startCheckForPair, processSuccessResponse and only
* then setStateInProgress, we'll synchronize. The
* synchronization root is the one of the
* CandidatePair#setState method.
*/
synchronized (pairToCheck)
{
TransactionID transactionID
= startCheckForPair(pairToCheck);
if (transactionID == null)
{
logger.info(
"Pair failed: "
+ pairToCheck.toShortString());
pairToCheck.setStateFailed();
}
else
pairToCheck.setStateInProgress(transactionID);
}
}
else
{
/*
* We are done sending checks for this list. We'll set
* its final state in either the processResponse(),
* processTimeout() or processFailure() method.
*/
logger.finest("will skip a check beat.");
checkList.fireEndOfOrdinaryChecks();
}
}
}
finally
{
synchronized (paceMakers)
{
synchronized (this)
{
paceMakers.remove(this);
}
}
}
} }
} }
@ -992,15 +1005,19 @@ class ConnectivityCheckClient
{ {
synchronized (paceMakers) synchronized (paceMakers)
{ {
stopped = true; Iterator<PaceMaker> paceMakersIter = paceMakers.iterator();
while (true)
while(paceMakersIter.hasNext())
{ {
final PaceMaker paceMaker = paceMakers.poll(); PaceMaker paceMaker = paceMakersIter.next();
if (paceMaker == null)
synchronized (paceMaker)
{ {
break; paceMaker.running = false;
paceMaker.notify();
} }
paceMaker.cancel();
paceMakersIter.remove();
} }
} }
} }

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;
@ -124,14 +155,14 @@ class ConnectivityCheckServer
UsernameAttribute uname = (UsernameAttribute)request UsernameAttribute uname = (UsernameAttribute)request
.getAttribute(Attribute.USERNAME); .getAttribute(Attribute.USERNAME);
if ( uname == null if( uname == null
|| !checkLocalUserName(new String(uname.getUsername()))) || !checkLocalUserName(new String(uname.getUsername())))
{ {
return; return;
} }
//detect role conflicts //detect role conflicts
if ( ( parentAgent.isControlling() if( ( parentAgent.isControlling()
&& request.containsAttribute(Attribute.ICE_CONTROLLING)) && request.containsAttribute(Attribute.ICE_CONTROLLING))
|| ( ! parentAgent.isControlling() || ( ! parentAgent.isControlling()
&& request.containsAttribute(Attribute.ICE_CONTROLLED))) && request.containsAttribute(Attribute.ICE_CONTROLLED)))
@ -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);
@ -214,10 +247,13 @@ class ConnectivityCheckServer
//apply tie-breaking //apply tie-breaking
//extract priority //extract priority
if (priorityAttr == null) if(priorityAttr == null)
{ {
logger.debug(() -> "Received a connectivity check with" if(logger.isLoggable(Level.FINE))
+ "no PRIORITY attribute. Discarding."); {
logger.log(Level.FINE, "Received a connectivity check with"
+ "no PRIORITY attribute. Discarding.");
}
throw new IllegalArgumentException("Missing PRIORITY attribute!"); throw new IllegalArgumentException("Missing PRIORITY attribute!");
} }
@ -242,79 +278,107 @@ 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))
{
IceControllingAttribute controlling = (IceControllingAttribute)
req.getAttribute(Attribute.ICE_CONTROLLING);
long theirTieBreaker = controlling.getTieBreaker();
// If the agent's tie-breaker is larger than or equal to the
// contents of the ICE-CONTROLLING attribute, the agent generates
// a Binding error response and includes an ERROR-CODE attribute
// with a value of 487 (Role Conflict) but retains its role.
if(compareUnsignedLong(ourTieBreaker, theirTieBreaker) >= 0)
{
Response response = MessageFactory.createBindingErrorResponse(
ErrorCodeAttribute.ROLE_CONFLICT);
try
{
stunStack.sendResponse(
evt.getTransactionID().getBytes(),
response,
evt.getLocalAddress(),
evt.getRemoteAddress());
return false;
}
catch(Exception exc)
{
//rethrow so that we would send a 500 response instead.
throw new RuntimeException("Failed to send a 487", exc);
}
}
//If the agent's tie-breaker is less than the contents of the
//ICE-CONTROLLING attribute, the agent switches to the controlled
//role.
else
{
logger.finer(
"Switching to controlled because theirTieBreaker="
+ theirTieBreaker + " and ourTieBreaker="
+ ourTieBreaker);
parentAgent.setControlling(false);
return true;
}
}
// If the agent is in the controlled role, and the ICE-CONTROLLED // If the agent is in the controlled role, and the ICE-CONTROLLED
// attribute is present in the request: // attribute is present in the request:
final boolean bothControlledConflict = !selfIceControlling && else if(!parentAgent.isControlling()
req.containsAttribute(Attribute.ICE_CONTROLLED); && req.containsAttribute(Attribute.ICE_CONTROLLED))
if (!(bothControllingConflict || bothControlledConflict))
{ {
// we don't have a role conflict IceControlledAttribute controlled = (IceControlledAttribute)
return true; req.getAttribute(Attribute.ICE_CONTROLLED);
}
final long selfTieBreaker = parentAgent.getTieBreaker(); long theirTieBreaker = controlled.getTieBreaker();
final IceControlAttribute theirIceControl = bothControllingConflict //If the agent's tie-breaker is larger than or equal to the
? (IceControlAttribute)req.getAttribute(Attribute.ICE_CONTROLLING) //contents of the ICE-CONTROLLED attribute, the agent switches to
: (IceControlAttribute)req.getAttribute(Attribute.ICE_CONTROLLED); //the controlling role.
if(compareUnsignedLong(ourTieBreaker, theirTieBreaker) >= 0)
final long theirTieBreaker = theirIceControl.getTieBreaker();
// If the agent's tie-breaker is larger than or equal to the
// contents of the ICE control attribute, the agent generates
// a Binding error response and includes an ERROR-CODE attribute
// with a value of 487 (Role Conflict) but retains its role.
if (Long.compareUnsigned(selfTieBreaker, theirTieBreaker) >= 0)
{
final UsernameAttribute requestUserName = (UsernameAttribute)req
.getAttribute(Attribute.USERNAME);
final Response response =
MessageFactory.createBindingErrorResponse(
ErrorCodeAttribute.ROLE_CONFLICT);
final Attribute messageIntegrityAttribute =
AttributeFactory.createMessageIntegrityAttribute(
new String(requestUserName.getUsername()));
response.putAttribute(messageIntegrityAttribute);
try
{ {
stunStack.sendResponse( logger.finer(
evt.getTransactionID().getBytes(), "Switching to controlling because theirTieBreaker="
response, + theirTieBreaker + " and ourTieBreaker="
evt.getLocalAddress(), + ourTieBreaker);
evt.getRemoteAddress()); parentAgent.setControlling(true);
return false; return true;
} }
catch(Exception exc) // 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
{ {
//rethrow so that we would send a 500 response instead. Response response = MessageFactory.createBindingErrorResponse(
throw new RuntimeException("Failed to send a 487", exc); ErrorCodeAttribute.ROLE_CONFLICT);
try
{
stunStack.sendResponse(
evt.getTransactionID().getBytes(),
response,
evt.getLocalAddress(),
evt.getRemoteAddress());
return false;
}
catch(Exception exc)
{
//rethrow so that we would send a 500 response instead.
throw new RuntimeException("Failed to send a 487", exc);
}
} }
} }
//If the agent's tie-breaker is less than the contents of the return true; // we don't have a role conflict
//ICE control attribute, the agent toggles its ICE control role.
else
{
final String selfNextControlState
= selfIceControlling ? "controlled" : "controlling";
logger.trace(() ->
"Switching to " + selfNextControlState + " because " +
" theirTieBreaker= " + theirTieBreaker + " and " +
"selfTieBreaker= " + selfTieBreaker);
parentAgent.setControlling(!selfIceControlling);
return true;
}
} }
/** /**
@ -380,7 +444,7 @@ class ConnectivityCheckServer
public byte[] getRemoteKey(String username, String media) public byte[] getRemoteKey(String username, String media)
{ {
IceMediaStream stream = parentAgent.getStream(media); IceMediaStream stream = parentAgent.getStream(media);
if (stream == null) if(stream == null)
{ {
return null; return null;
} }
@ -400,7 +464,7 @@ class ConnectivityCheckServer
//caller gave us the entire username. //caller gave us the entire username.
if (username.equals(parentAgent.generateLocalUserName(media))) if (username.equals(parentAgent.generateLocalUserName(media)))
{ {
if (stream.getRemotePassword() != null) if(stream.getRemotePassword() != null)
return stream.getRemotePassword().getBytes(); return stream.getRemotePassword().getBytes();
} }
} }

View File

@ -17,11 +17,11 @@
*/ */
package org.ice4j.ice; package org.ice4j.ice;
import org.jitsi.utils.logging2.*;
import java.beans.*; import java.beans.*;
import java.util.*; import java.util.*;
import org.ice4j.util.*;
/** /**
* Implements ice4j internal nomination strategies. * Implements ice4j internal nomination strategies.
* *
@ -30,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

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

View File

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

View File

@ -19,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,14 +176,14 @@ public class IceMediaStream
* @param keepAliveStrategy the keep-alive strategy, which dictates which * @param keepAliveStrategy the keep-alive strategy, which dictates which
* candidates pairs are going to be kept alive. * candidates pairs are going to be kept alive.
* @param useComponentSocket whether the "component socket" should be used * @param useComponentSocket whether the "component socket" should be used
* or not. See {@link 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.
*/ */
protected Component createComponent( protected Component createComponent(
KeepAliveStrategy keepAliveStrategy, KeepAliveStrategy keepAliveStrategy,
boolean useComponentSocket) boolean useComponentSocket)
{ {
Component component; Component component;
@ -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.");
} }
} }
@ -376,7 +379,7 @@ public class IceMediaStream
*/ */
protected void createCheckList(List<CandidatePair> checkList) protected void createCheckList(List<CandidatePair> checkList)
{ {
for (Component cmp : getComponents()) for(Component cmp : getComponents())
createCheckList(cmp, checkList); createCheckList(cmp, checkList);
} }
@ -395,22 +398,22 @@ public class IceMediaStream
List<RemoteCandidate> remoteCnds = component.getRemoteCandidates(); List<RemoteCandidate> remoteCnds = component.getRemoteCandidates();
LocalCandidate upnpBase = null; LocalCandidate upnpBase = null;
for (LocalCandidate lc : localCnds) for(LocalCandidate lc : localCnds)
{ {
// XXX do we assume a single UPNPCandidate here? // XXX do we assume a single UPNPCandidate here?
if (lc instanceof UPNPCandidate) if(lc instanceof UPNPCandidate)
upnpBase = lc.getBase(); upnpBase = lc.getBase();
} }
for (LocalCandidate localCnd : localCnds) for(LocalCandidate localCnd : localCnds)
{ {
// Don't take into consideration UPnP base candidate // Don't take into consideration UPnP base candidate
if (localCnd == upnpBase) if(localCnd == upnpBase)
continue; continue;
for (RemoteCandidate remoteCnd : remoteCnds) for(RemoteCandidate remoteCnd : remoteCnds)
{ {
if (localCnd.canReach(remoteCnd) if(localCnd.canReach(remoteCnd)
&& remoteCnd.getTransportAddress().getPort() != 0) && remoteCnd.getTransportAddress().getPort() != 0)
{ {
CandidatePair pair CandidatePair pair
@ -456,12 +459,12 @@ public class IceMediaStream
Iterator<CandidatePair> ckListIter = checkList.iterator(); Iterator<CandidatePair> ckListIter = checkList.iterator();
while (ckListIter.hasNext()) while(ckListIter.hasNext())
{ {
CandidatePair pair = ckListIter.next(); CandidatePair pair = ckListIter.next();
//drop all pairs above MAX_CHECK_LIST_SIZE. //drop all pairs above MAX_CHECK_LIST_SIZE.
if (tmpCheckList.size() > maxCheckListSize) if(tmpCheckList.size() > maxCheckListSize)
{ {
ckListIter.remove(); ckListIter.remove();
continue; continue;
@ -469,14 +472,14 @@ public class IceMediaStream
//replace local server reflexive candidates with their base. //replace local server reflexive candidates with their base.
LocalCandidate localCnd = pair.getLocalCandidate(); LocalCandidate localCnd = pair.getLocalCandidate();
if ( localCnd.getType() if( localCnd.getType()
== CandidateType.SERVER_REFLEXIVE_CANDIDATE) == CandidateType.SERVER_REFLEXIVE_CANDIDATE)
{ {
pair.setLocalCandidate(localCnd.getBase()); pair.setLocalCandidate(localCnd.getBase());
//if the new pair corresponds to another one with a higher //if the new pair corresponds to another one with a higher
//priority, then remove it. //priority, then remove it.
if (tmpCheckList.contains(pair)) if(tmpCheckList.contains(pair))
{ {
ckListIter.remove(); ckListIter.remove();
continue; continue;
@ -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;
@ -552,11 +550,11 @@ public class IceMediaStream
*/ */
public RemoteCandidate findRemoteCandidate(TransportAddress remoteAddress) public RemoteCandidate findRemoteCandidate(TransportAddress remoteAddress)
{ {
for ( Component cmp : components.values()) for( Component cmp : components.values())
{ {
RemoteCandidate cnd = cmp.findRemoteCandidate(remoteAddress); RemoteCandidate cnd = cmp.findRemoteCandidate(remoteAddress);
if (cnd != null) if(cnd != null)
return cnd; return cnd;
} }
@ -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

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

View File

@ -44,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

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

View File

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

View File

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

View File

@ -19,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<>();
@ -97,7 +89,7 @@ public abstract class AbstractTcpListener
Enumeration<InetAddress> ifaceAddresses = iface.getInetAddresses(); Enumeration<InetAddress> ifaceAddresses = iface.getInetAddresses();
while (ifaceAddresses.hasMoreElements()) while(ifaceAddresses.hasMoreElements())
{ {
InetAddress addr = ifaceAddresses.nextElement(); InetAddress addr = ifaceAddresses.nextElement();
@ -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 useIPv6LinkLocal = !StackProperties.getBoolean(
StackProperties.DISABLE_LINK_LOCAL_ADDRESSES,
false);
// White list from the configuration // White list from the configuration
String[] allowedAddressesStr String[] allowedAddressesStr
= StackProperties.getStringArray(StackProperties.ALLOWED_ADDRESSES, = StackProperties.getStringArray(StackProperties.ALLOWED_ADDRESSES,
@ -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,15 @@ 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 (!useIPv6LinkLocal
&& (address instanceof Inet6Address)
&& 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 +441,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 +466,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 +607,7 @@ public abstract class AbstractTcpListener
selector.close(); selector.close();
} }
catch (IOException ioe) catch (IOException ioe)
{ {}
// ignore
}
} }
} }
@ -522,6 +622,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 +792,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 +830,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 +924,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())
{ {
@ -811,7 +965,7 @@ public abstract class AbstractTcpListener
bytesRead, 2, bytesRead.length); bytesRead, 2, bytesRead.length);
// if we had read enough data // if we had read enough data
if (channel.length <= bytesRead.length - 2) if(channel.length <= bytesRead.length - 2)
{ {
processFirstDatagram( processFirstDatagram(
preBuffered, channel, key); preBuffered, channel, key);
@ -846,7 +1000,7 @@ public abstract class AbstractTcpListener
channel.buffer.flip(); channel.buffer.flip();
channel.buffer.get(bytesRead); channel.buffer.get(bytesRead);
if (channel.preBuffered != null) if(channel.preBuffered != null)
{ {
// will store preBuffered and currently read data // will store preBuffered and currently read data
byte[] newBytesRead = new byte[ byte[] newBytesRead = new byte[
@ -957,6 +1111,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 +1173,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.ice4j.util.*;
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,10 +488,10 @@ 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.notifyAll();
} }
} }
@ -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

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

View File

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

View File

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

View File

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

View File

@ -26,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 isIPv6LinkLocalDisabled = StackProperties.getBoolean(
StackProperties.DISABLE_LINK_LOCAL_ADDRESSES,
false);
try try
{ {
for (NetworkInterface iface for (NetworkInterface iface
@ -252,9 +257,11 @@ 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 (isIPv6LinkLocalDisabled
&& address instanceof Inet6Address
&& address.isLinkLocalAddress())
continue; continue;
addresses.add(address); addresses.add(address);
@ -276,8 +283,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 +309,21 @@ public class HostCandidateHarvester
{ {
harvestStatistics.startHarvestTiming(); harvestStatistics.startHarvestTiming();
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); Enumeration<NetworkInterface> interfaces
= NetworkInterface.getNetworkInterfaces();
if (transport != Transport.UDP && transport != Transport.TCP) boolean isIPv6Disabled = StackProperties.getBoolean(
StackProperties.DISABLE_IPv6,
false);
boolean isIPv6LinkLocalDisabled = StackProperties.getBoolean(
StackProperties.DISABLE_LINK_LOCAL_ADDRESSES,
false);
if(transport != Transport.UDP && transport != Transport.TCP)
{ {
throw new IllegalArgumentException("Transport protocol not supported: " + transport); throw new IllegalArgumentException(
"Transport protocol not supported: " + transport);
} }
boolean boundAtLeastOneSocket = false; boolean boundAtLeastOneSocket = false;
@ -329,7 +344,7 @@ public class HostCandidateHarvester
Enumeration<InetAddress> addresses = iface.getInetAddresses(); Enumeration<InetAddress> addresses = iface.getInetAddresses();
while (addresses.hasMoreElements()) while(addresses.hasMoreElements())
{ {
InetAddress addr = addresses.nextElement(); InetAddress addr = addresses.nextElement();
@ -338,25 +353,28 @@ public class HostCandidateHarvester
continue; continue;
} }
if (!config.useLinkLocalAddresses() && addr.isLinkLocalAddress()) if (isIPv6LinkLocalDisabled
&& (addr instanceof Inet6Address)
&& 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)
{ {
if (addr instanceof Inet6Address) if(addr instanceof Inet6Address)
continue; continue;
sock = createServerSocket( sock = createServerSocket(
addr, addr,
@ -386,8 +404,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 +423,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 +447,8 @@ public class HostCandidateHarvester
+ foundAtLeastOneUsableAddress); + foundAtLeastOneUsableAddress);
} }
this.harvestStatistics.stopHarvestTiming(component.getLocalCandidateCount()); this.harvestStatistics
.stopHarvestTiming(component.getLocalCandidateCount());
} }
/** /**
@ -441,7 +463,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 +543,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 +569,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,
@ -579,7 +588,7 @@ public class HostCandidateHarvester
new DelegatingServerSocket(sock), new DelegatingServerSocket(sock),
component); component);
if (logger.isLoggable(Level.FINEST)) if(logger.isLoggable(Level.FINEST))
{ {
logger.log( logger.log(
Level.FINEST, Level.FINEST,
@ -604,7 +613,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 +629,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 +656,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,
@ -672,7 +671,7 @@ public class HostCandidateHarvester
= new IceUdpSocketWrapper(new = new IceUdpSocketWrapper(new
MultiplexingDatagramSocket(port, laddr)); MultiplexingDatagramSocket(port, laddr));
if (logger.isLoggable(Level.FINEST)) if(logger.isLoggable(Level.FINEST))
{ {
logger.log( logger.log(
Level.FINEST, Level.FINEST,
@ -719,10 +718,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 +731,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 +758,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,72 +299,67 @@ 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>()
{ {
stunHarvester.discover(); @Override
return stunHarvester; public StunMappingCandidateHarvester call()
throws Exception
{
stunHarvester.discover();
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.
ExecutorService es = Executors.newFixedThreadPool(tasks.size());
List<Future<StunMappingCandidateHarvester>> futures;
try
{ {
logger.warning("STUN mapping harvesters are configured, but no allowed local addresses were found." + futures = es.invokeAll(tasks);
" Not using STUN."); }
catch (InterruptedException ie)
{
Thread.currentThread().interrupt();
return stunHarvesters; return stunHarvesters;
} }
// Now run discover() on all created harvesters in parallel and pick the ones which succeeded. for (Future<StunMappingCandidateHarvester> future : futures)
ExecutorService es = ExecutorFactory.createFixedThreadPool(tasks.size(), "ice4j.Harvester-executor-");
try
{ {
List<Future<StunMappingCandidateHarvester>> futures;
try try
{ {
futures = es.invokeAll(tasks); StunMappingCandidateHarvester harvester = future.get();
// The STUN server replied successfully.
if (harvester.getMask() != null)
{
stunHarvesters.add(harvester);
}
} }
catch (InterruptedException ie) catch (ExecutionException ee)
{
// The harvester failed for some reason, discard it.
}
catch(InterruptedException ie)
{ {
Thread.currentThread().interrupt(); Thread.currentThread().interrupt();
return stunHarvesters; throw new RuntimeException(ie);
}
for (Future<StunMappingCandidateHarvester> future : futures)
{
try
{
StunMappingCandidateHarvester harvester = future.get();
// The STUN server replied successfully.
if (harvester.getMask() != null)
{
stunHarvesters.add(harvester);
}
}
catch (ExecutionException ee)
{
// The harvester failed for some reason, discard it.
}
catch (InterruptedException ie)
{
Thread.currentThread().interrupt();
throw new RuntimeException(ie);
}
} }
} }
finally
{
es.shutdown();
}
return stunHarvesters; return stunHarvesters;
} }

View File

@ -101,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
@ -404,10 +404,8 @@ public class SinglePortUdpHarvester
protected IceSocketWrapper getCandidateIceSocketWrapper( protected IceSocketWrapper getCandidateIceSocketWrapper(
SocketAddress remoteAddress) SocketAddress remoteAddress)
{ {
synchronized (candidateSockets) return candidateSockets.get(remoteAddress);
{
return candidateSockets.get(remoteAddress);
}
} }
} }
} }

View File

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

View File

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

View File

@ -20,13 +20,13 @@ package org.ice4j.ice.harvest;
import org.ice4j.*; import org.ice4j.*;
import org.ice4j.socket.*; import org.ice4j.socket.*;
import org.ice4j.stunclient.*; import org.ice4j.stunclient.*;
import org.jetbrains.annotations.*;
import java.net.*; import java.net.*;
import java.util.logging.*; import java.util.logging.*;
/** /**
* A {@link MappingCandidateHarvester} which uses a STUN servers to discover 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

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

View File

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

View File

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

View File

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

View File

@ -22,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.
@ -690,7 +687,7 @@ public abstract class Message
public void setTransactionID(byte[] tranID) public void setTransactionID(byte[] tranID)
throws StunException throws StunException
{ {
if (tranID == null if(tranID == null
|| (tranID.length != TRANSACTION_ID_LENGTH && || (tranID.length != TRANSACTION_ID_LENGTH &&
tranID.length != RFC3489_TRANSACTION_ID_LENGTH)) tranID.length != RFC3489_TRANSACTION_ID_LENGTH))
throw new StunException(StunException.ILLEGAL_ARGUMENT, throw new StunException(StunException.ILLEGAL_ARGUMENT,
@ -724,7 +721,7 @@ public abstract class Message
*/ */
protected byte getAttributePresentity(char attributeType) protected byte getAttributePresentity(char attributeType)
{ {
if (!rfc3489CompatibilityMode) if(!rfc3489CompatibilityMode)
return O; return O;
byte msgIndex = -1; byte msgIndex = -1;
@ -875,22 +872,22 @@ public abstract class Message
@Override @Override
public boolean equals(Object obj) public boolean equals(Object obj)
{ {
if (!(obj instanceof Message)) if(!(obj instanceof Message))
return false; return false;
if (obj == this) if(obj == this)
return true; return true;
Message msg = (Message) obj; Message msg = (Message) obj;
if ( msg.getMessageType() != getMessageType()) if( msg.getMessageType() != getMessageType())
return false; return false;
if (msg.getDataLength() != getDataLength()) if(msg.getDataLength() != getDataLength())
return false; return false;
//compare attributes //compare attributes
for (Attribute localAtt : attributes.values()) for (Attribute localAtt : attributes.values())
{ {
if (!localAtt.equals(msg.getAttribute(localAtt.getAttributeType()))) if(!localAtt.equals(msg.getAttribute(localAtt.getAttributeType())))
return false; return false;
} }
@ -933,7 +930,7 @@ public abstract class Message
byte tranID[] = getTransactionID(); byte tranID[] = getTransactionID();
if (tranID.length == 12) if(tranID.length == 12)
{ {
System.arraycopy(MAGIC_COOKIE, 0, binMsg, offset, 4); System.arraycopy(MAGIC_COOKIE, 0, binMsg, offset, 4);
offset += 4; offset += 4;
@ -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,13 +1057,13 @@ public abstract class Message
* @throws StunException <tt>ILLEGAL_ARGUMENT</tt> if one or more of the * @throws StunException <tt>ILLEGAL_ARGUMENT</tt> if one or more of the
* arguments have invalid values. * arguments have invalid values.
*/ */
public static Message decode(byte[] binMessage, 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)
{ {
throw new StunException( StunException.ILLEGAL_ARGUMENT, throw new StunException( StunException.ILLEGAL_ARGUMENT,
"The given binary array is not a valid StunMessage"); "The given binary array is not a valid StunMessage");
@ -1080,7 +1077,7 @@ public abstract class Message
if (Message.isResponseType(messageType) && if (Message.isResponseType(messageType) &&
messageType != OLD_DATA_INDICATION) messageType != OLD_DATA_INDICATION)
message = new Response(); message = new Response();
else if (Message.isRequestType(messageType)) else if(Message.isRequestType(messageType))
message = new Request(); message = new Request();
else /* indication */ else /* indication */
message = new Indication(); message = new Indication();
@ -1091,38 +1088,38 @@ public abstract class Message
| (binMessage[offset++] & 0xFF)); | (binMessage[offset++] & 0xFF));
/* copy the cookie */ /* copy the cookie */
byte[] cookie = new byte[4]; byte cookie[] = new byte[4];
System.arraycopy(binMessage, offset, cookie, 0, 4); System.arraycopy(binMessage, offset, cookie, 0, 4);
offset += 4; offset += 4;
boolean rfc3489Compat = false; boolean rfc3489Compat = false;
if (!Arrays.equals(MAGIC_COOKIE, cookie)) if(!Arrays.equals(MAGIC_COOKIE, cookie))
{ {
rfc3489Compat = true; rfc3489Compat = true;
} }
if (arrayLen - offset - TRANSACTION_ID_LENGTH < length) if(arrayLen - offset - TRANSACTION_ID_LENGTH < length)
{ {
throw throw
new StunException( new StunException(
StunException.ILLEGAL_ARGUMENT, StunException.ILLEGAL_ARGUMENT,
"The given binary array does not seem to contain" "The given binary array does not seem to contain"
+ " a whole StunMessage: given " + " a whole StunMessage: given "
+ 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);
@ -1142,7 +1139,7 @@ public abstract class Message
offset += TRANSACTION_ID_LENGTH; offset += TRANSACTION_ID_LENGTH;
while (offset - Message.HEADER_LENGTH < length) while(offset - Message.HEADER_LENGTH < length)
{ {
Attribute att = AttributeDecoder.decode( Attribute att = AttributeDecoder.decode(
binMessage, offset, (char)(length - offset)); binMessage, offset, (char)(length - offset));
@ -1155,7 +1152,7 @@ public abstract class Message
//now also skip any potential padding that might have come with //now also skip any potential padding that might have come with
//this attribute. //this attribute.
if ((att.getDataLength() % 4) > 0) if((att.getDataLength() % 4) > 0)
{ {
offset += (4 - (att.getDataLength() % 4)); offset += (4 - (att.getDataLength() % 4));
} }
@ -1252,11 +1249,11 @@ public abstract class Message
protected void validateAttributePresentity() protected void validateAttributePresentity()
throws IllegalStateException throws IllegalStateException
{ {
if (! rfc3489CompatibilityMode ) if(! rfc3489CompatibilityMode )
return; return;
for (char i = Attribute.MAPPED_ADDRESS; i < Attribute.REFLECTED_FROM; i++) for(char i = Attribute.MAPPED_ADDRESS; i < Attribute.REFLECTED_FROM;i++)
if (getAttributePresentity(i) == M && getAttribute(i) == null) if(getAttributePresentity(i) == M && getAttribute(i) == null)
throw new IllegalStateException( throw new IllegalStateException(
"A mandatory attribute (type=" + (int)i + ") is missing!"); "A mandatory attribute (type=" + (int)i + ") is missing!");
} }
@ -1278,7 +1275,7 @@ public abstract class Message
*/ */
public static boolean isSuccessResponseType(char type) public static boolean isSuccessResponseType(char type)
{ {
return ((type & MESSAGE_CLASS_MASK) == STUN_SUCCESS_RESP); return ((type & MESSAGE_CLASS_MASK) == STUN_SUCCESS_RESP);
} }
/** /**
@ -1289,8 +1286,8 @@ public abstract class Message
*/ */
public static boolean isResponseType(char type) public static boolean isResponseType(char type)
{ {
/* return (((type >> 8) & 1) != 0); */ /* return (((type >> 8) & 1) != 0); */
return (isSuccessResponseType(type) || isErrorResponseType(type)); return (isSuccessResponseType(type) || isErrorResponseType(type));
} }
/** /**
@ -1311,8 +1308,8 @@ public abstract class Message
*/ */
public static boolean isRequestType(char type) public static boolean isRequestType(char type)
{ {
/* return !isResponseType(type); */ /* return !isResponseType(type); */
return ((type & MESSAGE_CLASS_MASK) == STUN_REQUEST); return ((type & MESSAGE_CLASS_MASK) == STUN_REQUEST);
} }
/** /**

View File

@ -54,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);
@ -431,8 +428,8 @@ public class MessageFactory
int lifetime ) int lifetime )
throws IllegalArgumentException throws IllegalArgumentException
{ {
return createAllocationResponse( return createAllocationResponse(
request, mappedAddress, relayedAddress, null , lifetime); request, mappedAddress, relayedAddress, null ,lifetime);
} }
/** /**
@ -476,8 +473,8 @@ public class MessageFactory
//xor relayed address //xor relayed address
XorRelayedAddressAttribute xorRelayedAddressAttribute XorRelayedAddressAttribute xorRelayedAddressAttribute
= AttributeFactory = AttributeFactory
.createXorRelayedAddressAttribute(relayedAddress, .createXorRelayedAddressAttribute(relayedAddress,
request.getTransactionID()); request.getTransactionID());
allocationSuccessResponse.putAttribute(xorRelayedAddressAttribute); allocationSuccessResponse.putAttribute(xorRelayedAddressAttribute);
@ -487,12 +484,12 @@ public class MessageFactory
allocationSuccessResponse.putAttribute(lifetimeAttribute); allocationSuccessResponse.putAttribute(lifetimeAttribute);
if (token != null) if(token != null)
{ {
//reservation token //reservation token
ReservationTokenAttribute reservationTokenAttribute ReservationTokenAttribute reservationTokenAttribute
= AttributeFactory = AttributeFactory
.createReservationTokenAttribute(token); .createReservationTokenAttribute(token);
allocationSuccessResponse.putAttribute(reservationTokenAttribute); allocationSuccessResponse.putAttribute(reservationTokenAttribute);
} }
@ -511,7 +508,7 @@ public class MessageFactory
*/ */
public static Response createAllocationErrorResponse(char errorCode) public static Response createAllocationErrorResponse(char errorCode)
{ {
return createAllocationErrorResponse(errorCode, null); return createAllocationErrorResponse(errorCode,null);
} }
/** /**
@ -527,7 +524,7 @@ public class MessageFactory
* @return a allocation error response message containing an error code. * @return a allocation error response message containing an error code.
*/ */
public static Response createAllocationErrorResponse(char errorCode, public static Response createAllocationErrorResponse(char errorCode,
String reasonPhrase) String reasonPhrase)
{ {
Response allocationErrorResponse = new Response(); Response allocationErrorResponse = new Response();
@ -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);
} }
@ -810,7 +806,7 @@ public class MessageFactory
*/ */
public static Response createChannelBindErrorResponse(char errorCode) public static Response createChannelBindErrorResponse(char errorCode)
{ {
return createChannelBindErrorResponse(errorCode, null); return createChannelBindErrorResponse(errorCode, null);
} }
/** /**
@ -830,7 +826,7 @@ public class MessageFactory
ErrorCodeAttribute errorCodeAttribute ErrorCodeAttribute errorCodeAttribute
= AttributeFactory = AttributeFactory
.createErrorCodeAttribute(errorCode, reasonPhrase); .createErrorCodeAttribute(errorCode,reasonPhrase);
channelBindErrorResponse.putAttribute(errorCodeAttribute); channelBindErrorResponse.putAttribute(errorCodeAttribute);
@ -916,7 +912,7 @@ public class MessageFactory
ErrorCodeAttribute errorCodeAttribute ErrorCodeAttribute errorCodeAttribute
= AttributeFactory = AttributeFactory
.createErrorCodeAttribute( .createErrorCodeAttribute(
errorCode, reasonPhrase); errorCode,reasonPhrase);
createPermissionErrorResponse.putAttribute(errorCodeAttribute); createPermissionErrorResponse.putAttribute(errorCodeAttribute);
@ -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);
} }
@ -1185,7 +1180,7 @@ public class MessageFactory
public static Response createConnectErrorResponse(char errorCode) public static Response createConnectErrorResponse(char errorCode)
throws IllegalArgumentException throws IllegalArgumentException
{ {
return createConnectErrorResponse(errorCode, null); return createConnectErrorResponse(errorCode, null);
} }
/** /**
@ -1275,7 +1270,7 @@ public class MessageFactory
public static Response createConnectionBindErrorResponse(char errorCode) public static Response createConnectionBindErrorResponse(char errorCode)
throws IllegalArgumentException throws IllegalArgumentException
{ {
return createConnectionBindErrorResponse(errorCode, null); return createConnectionBindErrorResponse(errorCode,null);
} }
/** /**

View File

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

View File

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

View File

@ -387,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.
@ -914,7 +914,7 @@ public class PseudoTCPBase
public static String segToStr(Segment seg) public static String segToStr(Segment seg)
{ {
String data="data: "; String data="data: ";
for (byte b : seg.data) for(byte b : seg.data)
{ {
data += b; data += b;
} }
@ -1064,7 +1064,7 @@ public class PseudoTCPBase
bConnect = true; bConnect = true;
// TCP options are in the remainder of the payload after CTL_CONNECT. // TCP options are in the remainder of the payload after CTL_CONNECT.
if (!parseOptions(seg.data, 1, seg.len - 1)) if(!parseOptions(seg.data, 1, seg.len - 1))
{ {
return false; return false;
} }
@ -1252,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
@ -1758,11 +1757,11 @@ public class PseudoTCPBase
else else
{ {
m_t_ack = now(); m_t_ack = now();
if (logger.isLoggable(Level.FINER)) if (logger.isLoggable(Level.FINER))
{ {
logger.log( logger.log(
Level.FINER, "Delayed ack, m_t_ack: " + m_t_ack); Level.FINER, "Delayed ack, m_t_ack: " + m_t_ack);
} }
} }
return; return;
} }
@ -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)
@ -2124,7 +2123,7 @@ public class PseudoTCPBase
void setConversationID(long convID) void setConversationID(long convID)
{ {
if (m_state != PseudoTcpState.TCP_LISTEN) if(m_state != PseudoTcpState.TCP_LISTEN)
throw new IllegalStateException(); throw new IllegalStateException();
this.m_conv = convID; this.m_conv = convID;
} }

View File

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

View File

@ -34,10 +34,10 @@ public class PseudoTcpSocket extends Socket
PseudoTcpSocket(PseudoTcpSocketImpl socketImpl) PseudoTcpSocket(PseudoTcpSocketImpl socketImpl)
throws SocketException throws SocketException
{ {
super(socketImpl); super(socketImpl);
this.socketImpl = socketImpl; this.socketImpl = socketImpl;
} }
/** /**
* *
@ -65,57 +65,57 @@ public class PseudoTcpSocket extends Socket
* Sets MTU (maximum transmission unit) value * Sets MTU (maximum transmission unit) value
* @param mtu the MTU value * @param mtu the MTU value
*/ */
public void setMTU(int mtu) public void setMTU(int mtu)
{ {
socketImpl.setMTU(mtu); socketImpl.setMTU(mtu);
} }
/** /**
* Gets MTU (maximum transmission unit) value * Gets MTU (maximum transmission unit) value
* @return MTU value * @return MTU value
*/ */
public int getMTU() public int getMTU()
{ {
return socketImpl.getMTU(); return socketImpl.getMTU();
} }
/** /**
* Sets an {@link Option} on this socket. * Sets an {@link Option} on this socket.
* @return PseudoTCP option value * @return PseudoTCP option value
* *
* @param option the option to set on this socket. * @param option the option to set on this socket.
* @see Option * @see Option
*/ */
public long getOption(Option option) public long getOption(Option option)
{ {
return socketImpl.getPTCPOption(option); return socketImpl.getPTCPOption(option);
} }
/** /**
* *
* @param option PseudoTCP option to set * @param option PseudoTCP option to set
* @param optValue option's value * @param optValue option's value
* *
* @see Option * @see Option
*/ */
public void setOption(Option option, long optValue) public void setOption(Option option, long optValue)
{ {
socketImpl.setPTCPOption(option, optValue); socketImpl.setPTCPOption(option, optValue);
} }
/** /**
* Blocking method waits for connection. * Blocking method waits for connection.
* *
* @param timeout for this operation in ms * @param timeout for this operation in ms
* @throws IOException If socket gets closed or timeout expires * @throws IOException If socket gets closed or timeout expires
*/ */
public void accept(int timeout) public void accept(int timeout)
throws IOException throws IOException
{ {
socketImpl.accept(timeout); socketImpl.accept(timeout);
} }
/** /**
* Sets debug name that will be displayed in log messages for this socket * Sets debug name that will be displayed in log messages for this socket
* @param debugName the name of this socket for debug messages * @param debugName the name of this socket for debug messages
*/ */
@ -245,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,13 +247,12 @@ class PseudoTcpSocketImpl
* @param port the port number. * @param port the port number.
* @throws IOException * @throws IOException
*/ */
@Override
public void bind(InetAddress host, int port) public void bind(InetAddress host, int port)
throws IOException throws IOException
{ {
if (socket != null) if(socket != null)
socket.close(); socket.close();
InetSocketAddress newAddr = new InetSocketAddress(host.getHostAddress(), port); InetSocketAddress newAddr = new InetSocketAddress(host.getHostAddress(),port);
this.socket = new DatagramSocket(newAddr); this.socket = new DatagramSocket(newAddr);
} }
@ -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,32 +278,31 @@ class PseudoTcpSocketImpl
options.put(optID, value); options.put(optID, value);
} }
@Override
public Object getOption(int optID) public Object getOption(int optID)
throws SocketException throws SocketException
{ {
//TODO: map options to PTCP options/method calls //TODO: map options to PTCP options/method calls
if (optID == SocketOptions.TCP_NODELAY) if(optID == SocketOptions.TCP_NODELAY)
{ {
Object ret = options.get(Option.OPT_NODELAY.ordinal()); Object ret = options.get(Option.OPT_NODELAY.ordinal());
return ret != null; return ret != null;
} }
Object option = options.get(optID); Object option = options.get(optID);
if (option == null) if(option == null)
{ {
logger.warning("Asked for unknown optID" + optID); logger.warning("Asked for unknown optID" + optID);
} }
return option; return option;
} }
public long getPTCPOption(Option opt) public long getPTCPOption(Option opt)
{ {
if (Option.OPT_READ_TIMEOUT == opt) if(Option.OPT_READ_TIMEOUT == opt)
{ {
return this.readTimeout; return this.readTimeout;
} }
else if (Option.OPT_WRITE_TIMEOUT == opt) else if(Option.OPT_WRITE_TIMEOUT == opt)
{ {
return this.writeTimeout; return this.writeTimeout;
} }
@ -315,11 +314,11 @@ class PseudoTcpSocketImpl
public void setPTCPOption(Option opt, long optValue) public void setPTCPOption(Option opt, long optValue)
{ {
if (Option.OPT_WRITE_TIMEOUT == opt) if(Option.OPT_WRITE_TIMEOUT == opt)
{ {
this.writeTimeout = optValue >= 0 ? optValue : 0; this.writeTimeout = optValue >= 0 ? optValue : 0;
} }
else if (Option.OPT_READ_TIMEOUT == opt) else if(Option.OPT_READ_TIMEOUT == opt)
{ {
this.readTimeout = optValue >= 0 ? optValue : 0; this.readTimeout = optValue >= 0 ? optValue : 0;
} }
@ -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
{ {
@ -453,7 +453,7 @@ class PseudoTcpSocketImpl
*/ */
private void updateClock() private void updateClock()
{ {
scheduleClockTask(0); scheduleClockTask(0);
} }
/** /**
@ -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,10 +501,9 @@ class PseudoTcpSocketImpl
* @param tcp the {@link PseudoTCPBase} that caused an event * @param tcp the {@link PseudoTCPBase} that caused an event
* @see PseudoTcpNotify#onTcpReadable(PseudoTCPBase) * @see PseudoTcpNotify#onTcpReadable(PseudoTCPBase)
*/ */
@Override
public void onTcpReadable(PseudoTCPBase tcp) public void onTcpReadable(PseudoTCPBase tcp)
{ {
if (logger.isLoggable(Level.FINER)) if(logger.isLoggable(Level.FINER))
{ {
logger.log( logger.log(
Level.FINER, Level.FINER,
@ -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)
@ -565,7 +560,7 @@ class PseudoTcpSocketImpl
runClock = false; runClock = false;
this.exception = e; this.exception = e;
releaseAllLocks(); releaseAllLocks();
cancelClockTask(true); cancelClockTask(true);
} }
@ -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))
@ -715,69 +709,74 @@ class PseudoTcpSocketImpl
*/ */
private void runClock() private void runClock()
{ {
if (!runClock) if(!runClock)
{ {
return; return;
} }
long sleep; long sleep;
synchronized (pseudoTcp) synchronized (pseudoTcp)
{ {
pseudoTcp.notifyClock(PseudoTCPBase.now()); pseudoTcp.notifyClock(PseudoTCPBase.now());
sleep = pseudoTcp.getNextClock(PseudoTCPBase.now()); sleep = pseudoTcp.getNextClock(PseudoTCPBase.now());
} }
//there might be negative interval even if there's no error //there might be negative interval even if there's no error
if (sleep == -1) if (sleep == -1)
{ {
releaseAllLocks(); releaseAllLocks();
if (exception != null) if (exception != null)
{ {
logger.log(Level.SEVERE, logger.log(Level.SEVERE,
"STATE: " + pseudoTcp.getState() "STATE: " + pseudoTcp.getState()
+ " ERROR: " + exception.getMessage()); + " ERROR: " + exception.getMessage());
} }
} }
else else
{ {
//logger.log(Level.FINEST, "Clock sleep for " + sleep); //logger.log(Level.FINEST, "Clock sleep for " + sleep);
scheduleClockTask(sleep); scheduleClockTask(sleep);
} }
} }
private 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)
{ {
synchronized (clockTaskRunner) synchronized (clockTaskRunner)
{ {
// Cancel any existing tasks, to make sure we don't run duplicates. // Cancel any existing tasks, to make sure we don't run duplicates.
cancelClockTask(false); cancelClockTask(false);
if (runClock) if(runClock)
{ {
currentlyScheduledClockTask currentlyScheduledClockTask
= clockExecutor.schedule( = clockExecutor.schedule(
clockTaskRunner, sleep, TimeUnit.MILLISECONDS); clockTaskRunner, sleep, TimeUnit.MILLISECONDS);
} }
} }
} }
private void cancelClockTask(boolean interruptIfRunning) private void cancelClockTask(boolean interruptIfRunning)
{ {
// Copy the reference, in case it changes. // Copy the reference, in case it changes.
ScheduledFuture<?> taskToCancel = this.currentlyScheduledClockTask; ScheduledFuture<?> taskToCancel = this.currentlyScheduledClockTask;
if (taskToCancel != null) if(taskToCancel != null)
{ {
taskToCancel.cancel(interruptIfRunning); taskToCancel.cancel(interruptIfRunning);
} }
} }
/** /**
* Returns an output stream for this socket. * Returns an output stream for this socket.
* @return an output stream for writing to this socket. * @return an output stream for writing to this socket.
* @throws IOException if an I/O error occurs when creating the output stream. * @throws IOException if an I/O error occurs when creating the output stream.
*/ */
@Override
public OutputStream getOutputStream() public OutputStream getOutputStream()
throws IOException throws IOException
{ {
@ -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)
{ {
@ -930,12 +926,12 @@ class PseudoTcpSocketImpl
return read; return read;
} }
logger.log(Level.FINER, "Read wait for data available"); logger.log(Level.FINER, "Read wait for data available");
if (readTimeout > 0) if(readTimeout > 0)
{ {
//Check for timeout //Check for timeout
long elapsed = 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)
{ {
IOException exc = IOException exc =
new IOException("Read operation timeout"); new IOException("Read operation timeout");
@ -944,7 +940,7 @@ class PseudoTcpSocketImpl
} }
synchronized (read_notify) synchronized (read_notify)
{ {
if (pseudoTcp.getAvailable() == 0) if(pseudoTcp.getAvailable() == 0)
{ {
read_notify.wait(left); read_notify.wait(left);
} }
@ -954,7 +950,7 @@ class PseudoTcpSocketImpl
{ {
synchronized (read_notify) synchronized (read_notify)
{ {
if (pseudoTcp.getAvailable() == 0) if(pseudoTcp.getAvailable() == 0)
{ {
read_notify.wait(); read_notify.wait();
} }
@ -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)
@ -1069,11 +1071,11 @@ class PseudoTcpSocketImpl
logger.log(Level.FINER, "Write wait for notify"); logger.log(Level.FINER, "Write wait for notify");
synchronized (write_notify) synchronized (write_notify)
{ {
if (writeTimeout > 0) if(writeTimeout > 0)
{ {
long elapsed = 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)
{ {
IOException exc = IOException exc =
new IOException("Write operation timeout"); new IOException("Write operation timeout");
@ -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)
{ {
@ -1127,12 +1129,12 @@ class PseudoTcpSocketImpl
{ {
try try
{ {
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)
{ {
IOException e = IOException e =
new IOException("Flush operation timeout"); new IOException("Flush operation timeout");
@ -1158,7 +1160,6 @@ class PseudoTcpSocketImpl
@Override @Override
public void close() throws IOException public void close() throws IOException
{ {
PseudoTcpSocketImpl.this.close();
} }
} }

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -18,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))
+ socket.getLocalAddress()); {
logger.fine("Adding a DelegatingSocket instance: "
+ 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))
+ socket.getLocalAddress()); {
logger.fine("Adding a DatagramSocket instance: "
+ 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;
} }
@ -322,7 +337,7 @@ public class MergingDatagramSocket
synchronized (socketContainersSyncRoot) synchronized (socketContainersSyncRoot)
{ {
int i = indexOf(socketContainers, socket); int i = indexOf(socketContainers, socket);
if (i >= 0) if (i > 0)
{ {
socketContainer = socketContainers[i]; socketContainer = socketContainers[i];
@ -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,10 +595,10 @@ 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);
} }
synchronized (socketContainersSyncRoot) synchronized (socketContainersSyncRoot)
@ -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))
+ getLocalSocketAddress() + " -> " {
+ getRemoteSocketAddress()); logger.fine("Starting the thread for socket "
+ getLocalSocketAddress() + " -> "
+ getRemoteSocketAddress());
}
thread.start(); thread.start();
} }
@ -779,7 +797,7 @@ public class MergingDatagramSocket
queue.put(buffer); queue.put(buffer);
synchronized (receiveLock) synchronized (receiveLock)
{ {
receiveLock.notify(); receiveLock.notifyAll();
} }
} }
catch (InterruptedException ie) catch (InterruptedException ie)
@ -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

@ -55,8 +55,19 @@ public class MultiplexedDatagramSocket
* The list of <tt>DatagramPacket</tt>s to be received through this * The list of <tt>DatagramPacket</tt>s to be received through this
* <tt>DatagramSocket</tt> i.e. accepted by {@link #filter}. * <tt>DatagramSocket</tt> i.e. accepted by {@link #filter}.
*/ */
final SocketReceiveBuffer received final List<DatagramPacket> received
= new SocketReceiveBuffer(this::getReceiveBufferSize); = new SocketReceiveBuffer()
{
private static final long serialVersionUID
= -5763976093759762087L;
@Override
public int getReceiveBufferSize()
throws SocketException
{
return MultiplexedDatagramSocket.this.getReceiveBufferSize();
}
};
/** /**
* Initializes a new <tt>MultiplexedDatagramSocket</tt> which is unbound and * Initializes a new <tt>MultiplexedDatagramSocket</tt> which is unbound and

View File

@ -67,8 +67,19 @@ public class MultiplexedSocket
* The list of <tt>DatagramPacket</tt>s to be received through this * The list of <tt>DatagramPacket</tt>s to be received through this
* <tt>Socket</tt> i.e. accepted by {@link #filter}. * <tt>Socket</tt> i.e. accepted by {@link #filter}.
*/ */
final SocketReceiveBuffer received final List<DatagramPacket> received
= new SocketReceiveBuffer(this::getReceiveBufferSize); = new SocketReceiveBuffer()
{
private static final long serialVersionUID
= 678744096057601141L;
@Override
public int getReceiveBufferSize()
throws SocketException
{
return MultiplexedSocket.this.getReceiveBufferSize();
}
};
/** /**
* Initializes a new <tt>MultiplexedSocket</tt> which is unbound and filters * Initializes a new <tt>MultiplexedSocket</tt> which is unbound and filters
@ -276,7 +287,7 @@ public class MultiplexedSocket
public void reset() public void reset()
throws IOException throws IOException
{ {
if (!markSupported()) if(!markSupported())
{ {
throw new IOException( throw new IOException(
"InputStreamImpl does not support reset()"); "InputStreamImpl does not support reset()");

View File

@ -81,7 +81,7 @@ public class MultiplexingDatagramSocket
* {@inheritDoc} * {@inheritDoc}
*/ */
@Override @Override
protected SocketReceiveBuffer getReceived() protected List<DatagramPacket> getReceived()
{ {
return received; return received;
} }
@ -90,7 +90,7 @@ public class MultiplexingDatagramSocket
* {@inheritDoc} * {@inheritDoc}
*/ */
@Override @Override
protected SocketReceiveBuffer getReceived( protected List<DatagramPacket> getReceived(
MultiplexedDatagramSocket socket) MultiplexedDatagramSocket socket)
{ {
return socket.received; return socket.received;
@ -103,8 +103,19 @@ public class MultiplexingDatagramSocket
* {@link MultiplexedDatagramSocket} of this instance at the time of the * {@link MultiplexedDatagramSocket} of this instance at the time of the
* reading from the network. * reading from the network.
*/ */
private final SocketReceiveBuffer received private final List<DatagramPacket> received
= new SocketReceiveBuffer(this::getReceiveBufferSize); = new SocketReceiveBuffer()
{
private static final long serialVersionUID
= 3125772367019091216L;
@Override
public int getReceiveBufferSize()
throws SocketException
{
return MultiplexingDatagramSocket.this.getReceiveBufferSize();
}
};
/** /**
* Buffer variable for storing the SO_TIMEOUT value set by the * Buffer variable for storing the SO_TIMEOUT value set by the

View File

@ -92,7 +92,7 @@ public class MultiplexingSocket
* {@inheritDoc} * {@inheritDoc}
*/ */
@Override @Override
protected SocketReceiveBuffer getReceived() protected List<DatagramPacket> getReceived()
{ {
return received; return received;
} }
@ -101,7 +101,7 @@ public class MultiplexingSocket
* {@inheritDoc} * {@inheritDoc}
*/ */
@Override @Override
protected SocketReceiveBuffer getReceived( protected List<DatagramPacket> getReceived(
MultiplexedSocket socket) MultiplexedSocket socket)
{ {
return socket.received; return socket.received;
@ -118,8 +118,19 @@ public class MultiplexingSocket
* <tt>Socket</tt> i.e. not accepted by the <tt>DatagramFilter</tt>s of * <tt>Socket</tt> i.e. not accepted by the <tt>DatagramFilter</tt>s of
* {@link #sockets} at the time of the reading from the network. * {@link #sockets} at the time of the reading from the network.
*/ */
private final SocketReceiveBuffer received private final List<DatagramPacket> received
= new SocketReceiveBuffer(this::getReceiveBufferSize); = new SocketReceiveBuffer()
{
private static final long serialVersionUID
= 4097024214973676873L;
@Override
public int getReceiveBufferSize()
throws SocketException
{
return MultiplexingSocket.this.getReceiveBufferSize();
}
};
/** /**
* Buffer variable for storing the SO_TIMEOUT value set by the last * Buffer variable for storing the SO_TIMEOUT value set by the last
@ -322,7 +333,7 @@ public class MultiplexingSocket
@Override @Override
public int getSoTimeout() public int getSoTimeout()
{ {
return soTimeout; return soTimeout;
} }
/** /**
@ -427,10 +438,10 @@ public class MultiplexingSocket
*/ */
@Override @Override
public void setSoTimeout(int timeout) public void setSoTimeout(int timeout)
throws SocketException throws SocketException
{ {
super.setSoTimeout(timeout); super.setSoTimeout(timeout);
soTimeout = timeout; soTimeout = timeout;
} }
} }

View File

@ -18,9 +18,9 @@
package org.ice4j.socket; package org.ice4j.socket;
import java.io.*; import java.io.*;
import java.lang.reflect.*;
import java.net.*; import java.net.*;
import java.util.*; import java.util.*;
import java.util.concurrent.*;
import java.util.logging.*; import java.util.logging.*;
/** /**
@ -188,24 +188,6 @@ abstract class MultiplexingXXXSocketSupport
} }
} }
/**
* The max number of {@link DatagramPacket}'s stored in the receive pool.
*/
private static final int RECEIVE_DATAGRAM_PACKETS_POOL_SIZE = 64;
/**
* The buffer size of pooled datagram packet used to read from
* underlying socket.
*/
private static final int POOLED_DATAGRAM_PACKET_SIZE = 1500;
/**
* A pool of {@link DatagramPacket}s used to receive data from unrelying
* socket.
*/
private final BlockingQueue<DatagramPacket> receiveDatagramPacketsPool
= new ArrayBlockingQueue<>(RECEIVE_DATAGRAM_PACKETS_POOL_SIZE);
/** /**
* The indicator which determines whether this <tt>DatagramSocket</tt> is * The indicator which determines whether this <tt>DatagramSocket</tt> is
* currently reading from the network using * currently reading from the network using
@ -265,7 +247,7 @@ abstract class MultiplexingXXXSocketSupport
{ {
if (getFilter(socket).accept(p)) if (getFilter(socket).accept(p))
{ {
SocketReceiveBuffer socketReceived = getReceived(socket); List<DatagramPacket> socketReceived = getReceived(socket);
synchronized (socketReceived) synchronized (socketReceived)
{ {
@ -281,7 +263,7 @@ abstract class MultiplexingXXXSocketSupport
} }
if (!accepted) if (!accepted)
{ {
SocketReceiveBuffer thisReceived = getReceived(); List<DatagramPacket> thisReceived = getReceived();
synchronized (thisReceived) synchronized (thisReceived)
{ {
@ -370,7 +352,7 @@ abstract class MultiplexingXXXSocketSupport
* not accepted by any (existing) {@code DatagramPacketFilter} at the time of * not accepted by any (existing) {@code DatagramPacketFilter} at the time of
* receipt * receipt
*/ */
protected abstract SocketReceiveBuffer getReceived(); protected abstract List<DatagramPacket> getReceived();
/** /**
* Gets the list of {@code DatagramPacket}s received by this multiplexing * Gets the list of {@code DatagramPacket}s received by this multiplexing
@ -383,7 +365,7 @@ abstract class MultiplexingXXXSocketSupport
* socket and accepted by the {@code DatagramPacketFilter} of the * socket and accepted by the {@code DatagramPacketFilter} of the
* multiplexed {@code socket} at the time of receipt * multiplexed {@code socket} at the time of receipt
*/ */
protected abstract SocketReceiveBuffer getReceived( protected abstract List<DatagramPacket> getReceived(
MultiplexedXXXSocketT socket); MultiplexedXXXSocketT socket);
/** /**
@ -488,27 +470,47 @@ abstract class MultiplexingXXXSocketSupport
{ {
// Pull the packets which have been received already and are accepted by // Pull the packets which have been received already and are accepted by
// the specified multiplexed socket out of the multiplexing socket. // the specified multiplexed socket out of the multiplexing socket.
final SocketReceiveBuffer thisReceived = getReceived(); List<DatagramPacket> thisReceived = getReceived();
final DatagramPacketFilter socketFilter = getFilter(socket); DatagramPacketFilter socketFilter = getFilter(socket);
final List<DatagramPacket> toMove; List<DatagramPacket> toMove = null;
synchronized (thisReceived) synchronized (thisReceived)
{ {
toMove = thisReceived.scan(socketFilter); if (thisReceived.isEmpty())
{
return;
}
else
{
for (Iterator<DatagramPacket> i = thisReceived.iterator();
i.hasNext();)
{
DatagramPacket p = i.next();
if (socketFilter.accept(p))
{
if (toMove == null)
toMove = new LinkedList<>();
toMove.add(p);
// XXX In the method receive, we allow multiple filters
// to accept one and the same packet.
i.remove();
}
}
}
} }
// Push the packets which have been accepted already and are accepted by // Push the packets which have been accepted already and are accepted by
// the specified multiplexed socket into the multiplexed socket in // the specified multiplexed socket into the multiplexed socket in
// question. // question.
if (!toMove.isEmpty()) if (toMove != null)
{ {
final SocketReceiveBuffer socketReceived = getReceived(socket); List<DatagramPacket> socketReceived = getReceived(socket);
synchronized (socketReceived) synchronized (socketReceived)
{ {
for (DatagramPacket datagramPacket : toMove) { socketReceived.addAll(toMove);
socketReceived.add(datagramPacket);
}
// The notifyAll will practically likely be unnecessary because // The notifyAll will practically likely be unnecessary because
// the specified socket will likely be a newly-created one to // the specified socket will likely be a newly-created one to
// which noone else has a reference. Anyway, dp the invocation // which noone else has a reference. Anyway, dp the invocation
@ -537,11 +539,11 @@ abstract class MultiplexingXXXSocketSupport
* @throws SocketTimeoutException if <tt>timeout</tt> is positive and has * @throws SocketTimeoutException if <tt>timeout</tt> is positive and has
* expired * expired
*/ */
void receive(SocketReceiveBuffer received, DatagramPacket p, int timeout) void receive(List<DatagramPacket> received, DatagramPacket p, int timeout)
throws IOException throws IOException
{ {
long startTime = System.currentTimeMillis(); long startTime = System.currentTimeMillis();
DatagramPacket receivedPacket; DatagramPacket r = null;
do do
{ {
@ -553,9 +555,12 @@ abstract class MultiplexingXXXSocketSupport
// SocketTimeoutException. // SocketTimeoutException.
synchronized (received) synchronized (received)
{ {
receivedPacket = received.poll(); if (!received.isEmpty())
if (receivedPacket != null) {
break; r = received.remove(0);
if (r != null)
break;
}
} }
// Throw a SocketTimeoutException if the timeout is over/up. // Throw a SocketTimeoutException if the timeout is over/up.
@ -617,18 +622,8 @@ abstract class MultiplexingXXXSocketSupport
continue; continue;
} }
// The pooled datagram packet instance will be used to receive // The caller will receive from the network.
// from the network. DatagramPacket c = clone(p, /* arraycopy */ false);
DatagramPacket receivePacket
= receiveDatagramPacketsPool.poll();
if (receivePacket == null)
{
receivePacket = new DatagramPacket(
new byte[POOLED_DATAGRAM_PACKET_SIZE],
POOLED_DATAGRAM_PACKET_SIZE);
}
receivePacket.setLength(POOLED_DATAGRAM_PACKET_SIZE);
synchronized (receiveSyncRoot) synchronized (receiveSyncRoot)
{ {
@ -646,11 +641,11 @@ abstract class MultiplexingXXXSocketSupport
} }
} }
} }
doReceive(receivePacket); doReceive(c);
// The caller received from the network. Copy/add the packet to // The caller received from the network. Copy/add the packet to
// the receive list of the sockets which accept it. // the receive list of the sockets which accept it.
acceptBySocketsOrThis(receivePacket); acceptBySocketsOrThis(c);
} }
finally finally
{ {
@ -663,12 +658,7 @@ abstract class MultiplexingXXXSocketSupport
} }
while (true); while (true);
copy(receivedPacket, p); copy(r, p);
// receivePacket is a datagram packet retrieved from SocketReceiveBuffer
// SocketReceiveBuffers only store datagrams borrowed from pool,
// so return datagram back to pool.
receiveDatagramPacketsPool.offer(receivedPacket);
} }
/** /**

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.
* *
@ -64,7 +225,7 @@ public class MuxServerSocketChannelFactory
* @throws IOException if an I/O error occurs * @throws IOException if an I/O error occurs
*/ */
public static ServerSocketChannel openAndBindServerSocketChannel( public static ServerSocketChannel openAndBindServerSocketChannel(
Map<String, Object> properties, Map<String,Object> properties,
SocketAddress endpoint, SocketAddress endpoint,
int backlog) int backlog)
throws IOException throws IOException
@ -75,7 +236,7 @@ public class MuxServerSocketChannelFactory
if (properties != null && !properties.isEmpty()) if (properties != null && !properties.isEmpty())
{ {
for (Map.Entry<String, Object> property for (Map.Entry<String,Object> property
: properties.entrySet()) : properties.entrySet())
{ {
String name = property.getKey(); String name = property.getKey();
@ -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

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

View File

@ -19,7 +19,6 @@ package org.ice4j.socket;
import java.io.*; import java.io.*;
import java.net.*; import java.net.*;
import java.util.concurrent.locks.*;
/** /**
* Represents a <tt>DatagramSocket</tt> which fixes the following problem: when * Represents a <tt>DatagramSocket</tt> which fixes the following problem: when
@ -30,17 +29,22 @@ import java.util.concurrent.locks.*;
* returns. * returns.
* *
* @author Lubomir Marinov * @author Lubomir Marinov
* @author Yura Yaroshevich
*/ */
public class SafeCloseDatagramSocket public class SafeCloseDatagramSocket
extends DelegatingDatagramSocket extends DelegatingDatagramSocket
{ {
/** /**
* A reader-writer lock to prevent {@link #close()} completion if any thread * The number of {@link #receive(DatagramPacket)} calls that have to return
* is blocked within {@link #receive(DatagramPacket)}. * before {@link #close()} returns.
*/ */
private final ReadWriteLock receiveCloseLock private int inReceive = 0;
= new ReentrantReadWriteLock();
/**
* The <tt>Object</tt> which synchronizes the access to {@link #inReceive}
* and implements the related inter-thread communication.
*/
private final Object inReceiveSyncRoot = new Object();
/** /**
* Initializes a new <tt>SafeCloseDatagramSocket</tt> instance and binds it * Initializes a new <tt>SafeCloseDatagramSocket</tt> instance and binds it
@ -139,10 +143,22 @@ public class SafeCloseDatagramSocket
{ {
super.close(); super.close();
final Lock closeLock = receiveCloseLock.writeLock(); synchronized (inReceiveSyncRoot)
closeLock.lock(); {
// we now know all read threads have finished boolean interrupted = false;
closeLock.unlock();
while (inReceive > 0)
try
{
inReceiveSyncRoot.wait();
}
catch (InterruptedException iex)
{
interrupted = true;
}
if (interrupted)
Thread.currentThread().interrupt();
}
} }
/** /**
@ -166,15 +182,21 @@ public class SafeCloseDatagramSocket
public void receive(DatagramPacket p) public void receive(DatagramPacket p)
throws IOException throws IOException
{ {
final Lock receiveLock = receiveCloseLock.readLock(); synchronized (inReceiveSyncRoot)
receiveLock.lock(); {
inReceive++;
}
try try
{ {
super.receive(p); super.receive(p);
} }
finally finally
{ {
receiveLock.unlock(); synchronized (inReceiveSyncRoot)
{
inReceive--;
inReceiveSyncRoot.notifyAll();
}
} }
} }
} }

View File

@ -19,269 +19,132 @@ package org.ice4j.socket;
import java.net.*; import java.net.*;
import java.util.*; import java.util.*;
import java.util.concurrent.*;
/** /**
* Implements a buffer of <tt>DatagramPacket</tt>s received by a * Implements a list of <tt>DatagramPacket</tt>s received by a
* <tt>DatagramSocket</tt> or a <tt>Socket</tt>. The list enforces the * <tt>DatagramSocket</tt> or a <tt>Socket</tt>. The list enforces the
* <tt>SO_RCVBUF</tt> option for the associated <tt>DatagramSocket</tt> or * <tt>SO_RCVBUF</tt> option for the associated <tt>DatagramSocket</tt> or
* <tt>Socket</tt>. * <tt>Socket</tt>.
* *
* @author Lyubomir Marinov * @author Lyubomir Marinov
* @author Yura Yaroshevich
*/ */
class SocketReceiveBuffer abstract class SocketReceiveBuffer
extends LinkedList<DatagramPacket>
{ {
/**
* Default size in bytes of socket receive buffer.
*/
private static final int DEFAULT_RECEIVE_BUFFER_SIZE = 1024 * 1024; private static final int DEFAULT_RECEIVE_BUFFER_SIZE = 1024 * 1024;
/** private static final long serialVersionUID = 2804762379509257652L;
* Maxumum number of datagrams buffer is capable to store regardless
* of total datagram size in bytes.
*/
private static final int DATAGRAMS_BUFFER_CAPACITY = 10000;
/** /**
* Queue to store received datagrams. * The value of the <tt>SO_RCVBUF</tt> option for the associated
* <tt>DatagramSocket</tt> or <tt>Socket</tt>. Cached for the sake of
* performance.
*/ */
private final BlockingQueue<DatagramPacket> buffer private int receiveBufferSize;
= new ArrayBlockingQueue<>(DATAGRAMS_BUFFER_CAPACITY);
/** /**
* An instance of datagram size tracker to compute total number of bytes * The (total) size in bytes of this receive buffer.
* stored in datagrams witin {@link #buffer}.
*/ */
private final DatagramSizeTracker tracker; private int size;
/** /**
* Constructs {@link SocketReceiveBuffer} with user-provided * {@inheritDoc}
* @param receiveBufferSizeSupplier a function to obtain receive buffer
* size from associated socket.
*/ */
public SocketReceiveBuffer(Callable<Integer> receiveBufferSizeSupplier) @Override
public boolean add(DatagramPacket p)
{ {
this.tracker = new DatagramSizeTracker(receiveBufferSizeSupplier); boolean added = super.add(p);
}
/**
* Check if receive buffer is empty
* @return true if buffer is empty, false - otherwise.
*/
public boolean isEmpty()
{
return buffer.isEmpty();
}
/**
* Adds {@link DatagramPacket} at the end of the socket receive buffer.
* @param p datagram to add into receive buffer
*/
public void add(DatagramPacket p)
{
while (!buffer.offer(p))
{
// ensure buffer capacity restriction enforced
poll();
}
tracker.trackDatagramAdded(p);
while (tracker.isExceedReceiveBufferSize() && buffer.size() > 1)
{
// enforce SO_RCVBUF restriction
poll();
}
}
/**
* Polls socket receive buffer for already stored {@link DatagramPacket}
* @return the first datagram in the buffer, or {@code null} if buffer
* is empty.
*/
public DatagramPacket poll()
{
DatagramPacket p = buffer.poll();
// Keep track of the (total) size in bytes of this receive buffer in // Keep track of the (total) size in bytes of this receive buffer in
// order to be able to enforce SO_RCVBUF restriction. // order to be able to enforce SO_RCVBUF.
if (p != null) if (added && (p != null))
{ {
tracker.trackDatagramRemoved(p); int pSize = p.getLength();
}
return p; if (pSize > 0)
}
/**
* Scans buffer of received {@link DatagramPacket}s and move
* datagrams which matches the {@code filter} into returned list.
* @param filter a predicate to filter {@link DatagramPacket} stored
* in receive buffer.
* @return list of datagrams matched to {@code filter}.
*/
public List<DatagramPacket> scan(DatagramPacketFilter filter)
{
List<DatagramPacket> matchedDatagrams = null;
final Iterator<DatagramPacket> it = buffer.iterator();
while (it.hasNext())
{
final DatagramPacket p = it.next();
if (filter.accept(p))
{ {
if (matchedDatagrams == null) size += pSize;
// If the added packet is the only element of this list, do not
// drop it because of the enforcement of SO_RCVBUF.
if (size() > 1)
{ {
matchedDatagrams = new ArrayList<>(); // For the sake of performance, do not invoke the method
} // getReceiveBufferSize() of DatagramSocket or Socket on
matchedDatagrams.add(p); // every packet added to this buffer.
int receiveBufferSize = this.receiveBufferSize;
it.remove(); if ((receiveBufferSize <= 0) || (modCount % 1000 == 0))
tracker.trackDatagramRemoved(p);
}
}
if (matchedDatagrams != null)
{
return matchedDatagrams;
}
return Collections.emptyList();
}
/**
* A helper class to keep track of total size in bytes of all
* {@link DatagramPacket} instances stored in {@link #buffer} to
* be able to enforce SO_RCVBUF.
*/
private final class DatagramSizeTracker
{
/**
* The value of the <tt>SO_RCVBUF</tt> option for the associated
* <tt>DatagramSocket</tt> or <tt>Socket</tt>. Cached for the sake of
* performance.
*/
private int cachedReceiveBufferSize;
/**
* The (total) size in bytes of this receive buffer.
*/
private int totalBuffersByteSize;
/**
* Counts total number of datagrams added to buffer.
*/
private int totalDatagramsAdded;
/**
* A user provided getter of receive buffer size, might
* fail with {@link Exception} when called.
*/
private final Callable<Integer> receiveBufferSizeSupplier;
/**
* Create a tracker of datagram packet size stored in buffer.
* @param receiveBufferSizeSupplier a function to obtain receive buffer
* size from associated socket.
*/
public DatagramSizeTracker(
Callable<Integer> receiveBufferSizeSupplier)
{
this.receiveBufferSizeSupplier = receiveBufferSizeSupplier;
}
/**
* Check if total bytes stored in {@link #buffer} exceeds socket's
* receive buffer size.
* @return true if size exceeded, false - otherwise
*/
boolean isExceedReceiveBufferSize()
{
return totalBuffersByteSize > cachedReceiveBufferSize;
}
/**
* Updates computed value of total datagrams size in bytes
* stored in {@link #buffer} with datagram just added to buffer.
* @param p datagram packed added to {@link #buffer}
*/
void trackDatagramAdded(DatagramPacket p)
{
++totalDatagramsAdded;
final int pSize = p.getLength();
if (pSize <= 0)
{
return;
}
totalBuffersByteSize += pSize;
// If the added packet is the only element of this list, do not
// drop it because of the enforcement of SO_RCVBUF.
if (buffer.size() > 1)
{
// For the sake of performance, do not invoke the method
// getReceiveBufferSize() of DatagramSocket or Socket on
// every packet added to this buffer.
int receiveBufferSize = this.cachedReceiveBufferSize;
if ((receiveBufferSize <= 0)
|| (totalDatagramsAdded % 1000 == 0))
{
try
{ {
receiveBufferSize try
= this.receiveBufferSizeSupplier.call(); {
} receiveBufferSize = getReceiveBufferSize();
catch (Exception e) }
{ catch (SocketException sex)
// nothing to do {
} }
if (receiveBufferSize <= 0)
{
receiveBufferSize = DEFAULT_RECEIVE_BUFFER_SIZE;
}
else if (receiveBufferSize
< DEFAULT_RECEIVE_BUFFER_SIZE)
{
// Well, a manual page on SO_RCVBUF talks about
// doubling. In order to stay on the safe side and
// given that there was no limit on the size of the
// buffer before, double the receive buffer size.
receiveBufferSize *= 2;
if (receiveBufferSize <= 0) if (receiveBufferSize <= 0)
{ {
receiveBufferSize receiveBufferSize = DEFAULT_RECEIVE_BUFFER_SIZE;
= DEFAULT_RECEIVE_BUFFER_SIZE;
} }
else if (receiveBufferSize
< DEFAULT_RECEIVE_BUFFER_SIZE)
{
// Well, a manual page on SO_RCVBUF talks about
// doubling. In order to stay on the safe side and
// given that there was no limit on the size of the
// buffer before, double the receive buffer size.
receiveBufferSize *= 2;
if (receiveBufferSize <= 0)
{
receiveBufferSize
= DEFAULT_RECEIVE_BUFFER_SIZE;
}
}
this.receiveBufferSize = receiveBufferSize;
} }
this.cachedReceiveBufferSize = receiveBufferSize; if (size > receiveBufferSize)
remove(0);
} }
} }
} }
return added;
}
/** /**
* Updates computed value of total datagrams size in bytes * Gets the value of the <tt>SO_RCVBUF</tt> option for the associated
* stored in {@link #buffer} with datagram just removed from buffer. * <tt>DatagramSocket</tt> or <tt>Socket</tt> which is the buffer size used
* @param p datagram packed removed from {@link #buffer} * by the platform for input on the <tt>DatagramSocket</tt> or
*/ * <tt>Socket</tt>.
void trackDatagramRemoved(DatagramPacket p) *
* @return the value of the <tt>SO_RCVBUF</tt> option for the associated
* <tt>DatagramSocket</tt> or <tt>Socket</tt>
* @throws SocketException if there is an error in the underlying protocol
*/
public abstract int getReceiveBufferSize()
throws SocketException;
/**
* {@inheritDoc}
*/
@Override
public DatagramPacket remove(int index)
{
DatagramPacket p = super.remove(index);
// Keep track of the (total) size in bytes of this receive buffer in
// order to be able to enforce SO_RCVBUF.
if (p != null)
{ {
final int pSize = p.getLength(); int pSize = p.getLength();
if (pSize <= 0)
{
return;
}
totalBuffersByteSize -= pSize; if (pSize > 0)
if (totalBuffersByteSize < 0)
{ {
totalBuffersByteSize = 0; size -= pSize;
if (size < 0)
size = 0;
} }
} }
return p;
} }
} }

View File

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

View File

@ -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"));
}
}

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