Compare commits

..

94 Commits

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

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

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

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

* feat: Port SOFTWARE to AgentConfig.

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

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

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

* ref: Move MappingCandidateHarvester to kotlin.

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

* feat: Support statically mapping a specific port.

* feat: Add a name to MappingCandidateHarvester.

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

* chore: Update jitsi-utils.

* chore: Update kotlin to 1.5.20.

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

* chore: Update jicoco.

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

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

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

* Use random ports for transaction tests

* Apply ktlint format

* Fix flaky tests

* Use jicoco from Maven Central

* Remove semver checks

* Add Kotlin linting check

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

* Release to Maven Central

Closes #213
Closes #95

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

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

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

* ref: Port the receive buffer size property.

* ref: Port the "disable ipv6" property.

* ref: Port the "dynamic ports" propertty.

* ref: Port the timeout property.

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

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

* fix: Fix a typo.

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

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

* Add getters for NominationStrategy.

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

* Updated logs and fixed comments.

* Added unit test of role conflict recovery.

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

* remove packetqueue (exists in jitsi-utils)

* use executorfactory in jitsi-utils

* use customizablethreadfactory on jitsi-utils

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

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

* use new logger in localcandidate

* use new logger in checklist

* use new logger in defaultnominator

* use new logger in connectivitycheckclient, connectivitycheckserver

* fix typo, allow taking in a parent logger

* use jitsi-utils

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

* Removes unused import.
2019-05-09 14:22:52 +01:00
Han Xu
59461c9d13 Clear system property at the end of test.
The current test is passing, but still I think it's better to clear
the system property it sets.
2019-04-24 09:44:02 +01:00
Han Xu
105a49749e Fix Retransmitter creation to take effect of originalWaitInterval config 2019-04-24 09:44:02 +01:00
Peter Sear
0ea60d85b3 Add unit tests for org.ice4j.ice.NetworkUtilsTest
These tests were written using Diffblue Cover.
2019-03-28 09:43:48 -07:00
Дамян Минков
17bbc9b97a Removes jitsi-universe dependency. (#177) 2019-03-27 16:01:44 +00:00
Yury Yaroshevich
80471b751a Offload I/O from ScheduledExecutorService thread in PaceMaker. (#173)
* Offload I/O from ScheduledExecutorService thread in PaceMaker.
2019-02-13 09:08:44 +00:00
Yury Yaroshevich
5aec41fc02 Offload I/O from ScheduledExecutorService thread in Retransmitter. (#172)
* Offload I/O from ScheduledExecutorService thread in Retransmitter.

* Use single thread executor for timer.

* Use single thread for timer

* Fixed typo
2019-02-12 11:50:59 -08:00
Reker
f9a357ec17 Fix SDP Connection field generation bug (#136)
The signature of sdpFactory#createConnection is (String netType, String addrType, String addr), so IceSdpUtils always generate wrong Connection in SDP
2019-02-12 11:42:23 +00:00
Yury Yaroshevich
0be8f1aae7 Offload I/O from ScheduledExecutorService thread in StunKeepAliveRunner (#170)
* Added periodic runnable to offload I/O from ScheduledExecutorService's thread.

* Added missing class header.

* Do not invoke `getMillisecondsDelayUntilNextRun` from synchronized section.

* Use java.time.Duration to represent time interval.

* Use synchronized block in scheduleNextRun.
2019-02-11 09:37:44 -08:00
bgrozev
e87d331e57
fix: Changes the fixed thread pool in NetAccessManager to an unbounde… (#171)
* fix: Changes the fixed thread pool in NetAccessManager to an unbounded cached thread pool.
2019-02-08 19:08:08 +00:00
Yury Yaroshevich
e3e78dcda3 Fixed socket receive buffer interface misuse (#167)
* Use type with tiny interface (offer/poll/scan/isEmpty) for socket receive buffer.

* Fixed computation of total bytes stored in buffer due to misuse of iterator and addAll methods of list.

* Rename offer back to add and do not return status.

* Fixed formatting.

* Declare variables as final.

* Check if `toMove` is empty, because it can not be null with new SocketReceiveBuffer.

* Fix after rebase.
2019-01-15 14:26:33 +00:00
Yury Yaroshevich
ce42c77b82 Do not limit org.ice4j.ice.harvest.DISABLE_LINK_LOCAL_ADDRESSES to IPv6. (#156)
* Do not limit DISABLE_LINK_LOCAL_ADDRESSES to IPv6.

* Removed part about IPv6 for in comment for DISABLE_LINK_LOCAL_ADDRESSES.
2019-01-11 03:50:44 +00:00
Yury Yaroshevich
4027cf429d Use pool of datagram packets inside MultiplexingXXXSocketSupport (#168)
Use pool of datagram packets inside MultiplexingXXXSocketSupport to reduce clone() overhead.
2019-01-08 11:53:13 -06:00
Yury Yaroshevich
c56fcc3a3f Use ReadWriteLock to split receive and close execution in SafeCloseDatagramSocket. (#166)
* Use ReadWriteLock to split receive and close execution in SafeCloseDatagramSocket.

* Me into authors lists.

* Removed empty try/finally
2018-12-19 10:29:42 -08:00
Yury Yaroshevich
8b43209b8d Use notify instead of notifyAll when only one thread affected by notification. (#165) 2018-12-19 08:31:58 -08:00
Yury Yaroshevich
6beca2903c Invoke releasePacket on dropped items in PacketQueue. (#164)
* Invoke releasePacket on dropped items in PacketQueue.

* Fixed comment.

* Use Object.notify instead of Object.notifyAll in PacketQueue.doAdd

* Fixed formatting.

* Use atomic for numDroppedPackets because it is no longer under synchronized block.

* Copy number of dropped packets to local variable.
2018-12-17 09:16:16 -08:00
Yury Yaroshevich
c325421927 Do not explicitly create threads in PacketQueue (#157)
* Do not explicitly create threads in PacketQueue, but borrow threads for execution from ExecutorService.

* Added method to release created packet in PacketQueue.

* Added constructor overload to override default ExecutorService of PacketQueue.

* Fixed inconsistent formatting.

* Added throttling support to PacketQueue.

* Added performance tests for various configurations of PacketQueue.

* Updated comments.

* Added test for fixed size thread pool to compare it with ForkJoinPool.

* Fixed comments.

* Changed default values of PacketQueue configuration to closer match old implementation.

* Removed unused constants.

* Added tests to reveal introduced bug. Fixed bug.

* Fixed comments in PacketsQueue.

* Do not hard code class name in thread pool name.

* Return 0 when handler is null (should be not be reachable, but anyway).

* Added test to check capacity constraint of PacketQueue.

* Replaced manual capacity check with checking offer return value.

* Made throttler class static.

* Added test to check that PacketQueue thread is release without work.

* Do GC before running performance benchmark.

* Fixed formatting and added timeout.

* Added test to check cooperative multi-tasking behavior when executor is shared between queues and has less threads then executor has.

* Minor code rearrangement.

* Use dedicated syncronization object for sate of AsyncPacketReader.

* Stop PacketQueue when benchmark is finished.

* Added constant for number of benchmark iterations.

* Minor code style enhancements.

* Added myself to the list of authors.

* Added test to check that million of PacketQueue can share single thread without eating CPU when idle.

* Extracted AsyncQueueHandler class.

* Fixed imports.

* Minor fixes.

* Minimize diff by undoing unnecessary changes.

* Minimized diff.

* Reduce diff.

* Added constructor argument null checks.

* Removed throttling and simplified AsyncQueueHandler.

* Reviewed usage of syncronized blocks.

* Moved variable closer to usage.

* Fixed according to code review.

* Added extra constructor.

* Removed cancel from onYield because it's unnecessary after removing throttling.

* Rearranged onYield and handleQueueItemsUntilEmpty, introduced rescheduleReader

* Updated copyright.
2018-12-12 08:37:28 -08:00
Yury Yaroshevich
17b9bd9c17 Fixed socket remove condition in MergingDatagramSocket. (#159) 2018-12-10 10:30:17 -08:00
Yury Yaroshevich
ee4e8c9452 Eliminate "Stun4J Message Processor" by replacing it with thread pool. (#155)
* Use shared thread pool to execute stun messages decoding and processing. Set minimum required Java version to 1.8.

* Added missing argument comment.

* Added pooling of MessageProcessor objects to avoid extra allocations per RawMessage.

* Made MessageProcessor to be ForkJoinTask<Void> to avoid hidden allocation inside ForkJoinPool.

* Fixed comments according to last changes.

* Added dedicated method to reset state of pooled processor. More comments.

* Fixed comment typo.

* ForkJoinPool by default uses all available processors.

* Rollback JDK 8 changes in pom file since it looks they were only necessary for local build due to misconfigured IDE.

* Avoid usage of Java 8 features (lambda expressions & method references)

* Revert "Rollback JDK 8 changes in pom file since it looks they were only necessary for local build due to misconfigured IDE."

This reverts commit 840f18a554c4910f1af781aa729c58e833b0621f.

* Revert "Avoid usage of Java 8 features (lambda expressions & method references)"

This reverts commit b6ce70ebb40859be8f9249e070b6915feab59200.

* Renamed MessageProcessor into MessageProcessingTask to better reflect changed meaning of class.

* Use ForkJoinPool with prefixed threads to simplify debugging.

* Removed todo.

* Use well-known thread pool instead of ForkJoinPool. Could be easily changed back to ForkJoinPool.

* Fixed missing space.

* Fixes according to code review.

* Fixed active tasks tracking which was broken when pooling was added.

* Keep track of task processing throughput via QueueStatistics.

* Updated comment.

* Fixed comment.

* Updated comment.

* Updated comment.

* Updated comment.

* Renamed field to have better name.

* Fixed formatting.

* Restored old formatting corrupted by IDE.

* Fixed formatting.

* Fixed comment.

* Fixed comment.

* Updated comment.

* Updated log message.

* Code-style fixes to match rest of file.

* Fixed code style to match existing code.

* Fixed formatting.

* Restored accidentally removed comment.

* Added myself to list of authors.
2018-11-29 12:52:23 -08:00
Yury Yaroshevich
3239ed12fc Stun server transaction: reduce number of threads used for expiration. (#154)
* Reorder fields so final fields set in constructor come first, then mutable state of transaction.

* Rename STUN transaction lifetime field.

* Eliminate isRetransmitting field which is actually computed property from response != null

* Use monotonic clock (System.nanoTime) to check expiration. Replaced synchronized methods with atomic variables.

* Re-factored TransactionID implementation. Use less mutable state. Fixed hash function to produce random values, instead of sequentially growing values.

* Do no perform full Hashtable lookup to find transaction with specified ID.

* Use check before acquiring lock in StunStack.

* Implement ScheduledExecutorService based expired transaction collector.

* Restored self-cancel of expired server transactions collector when no server transactions at all.

* Fixed isExpire check in StunServerTransaction

* Fixed collection runnable to remove not only values but also keys from Hashtable.

* Perform elapsed check over milliseconds, not nanoseconds.

* Do not leave null values in clientTransactions/serverTransactions Hashtables when removing transaction, but leaving it's ID in Hashtable.

* Remove condition around cheap logger calls.

* Minor formatting fixes.

* Log number of non-expired transactions after collection to verity it is not growing over time.

* Fixed multi-line string formatting.

* Moved construction of ScheduledThreadPoolExecutor to helper method. Adjusted default settings of pool.

* Allow to create single threaded pool as well as bounded to number of CPUs on machine pool.

* Fixed name collision with same class in other package.

* Minor styling changes to reduce diff.

* Removed unused import.

* Do check of response when it's actually supposed to be non null.

* Add actual length to error message.

* Allow transaction ID of incorrect size.

* Allow constructing TransactionID with invalid length.

* Rollback all refactoring other than reducing thread count.

* Use default 1 minute timeout for threads in pool.

* Fixed typo in method name.
2018-11-20 14:18:51 -08:00
Yury Yaroshevich
513fb588d6 Stun client transaction re-transmission based on ScheduledThreadPoolExecutor (#153)
* Hide Runnable interface in StunClientTransaction class.

* Use CustomizableThreadFactory to give custom names to threads.

* Extracted retransmission logic into separate class.

* Re-implement Retransmitter with ScheduledThreadPoolExecutor.

* Fixed retransmissionCounter increment.

* Directly call logger fine methods instead overload with Level.
2018-10-31 10:53:41 -07:00
Yury Yaroshevich
3fe34dcb97 Reduce number of threads created by ice4j. Eliminate ICE PaceMaker thread & Timer. (#152)
* Eliminate "ICE PaceMaker" thread & Timer inside ConnectivityCheckClient.

* Fixed PaceMaker stop and cleaning.

* Added braces to have explicit blocks for one-liners if/else.
2018-10-30 16:11:48 -07:00
Yury Yaroshevich
6bed63795f Reduce number of threads created by ice4j. Eliminate StunKeepAliveThread. (#151)
* Use ScheduleExecutorService to run STUN keep alives.

* Mark threads as daemon threads.

* Fixed comments. Rearranged properties read in keep alive runnable.

* Added early check that keep alives must not be sent

* Renamed method to check keep alive condition.

* Fixed formatting.

* Renamed metrod which check if KA should run.

* Created CustomizableThreadFactory which support thread name prefixes and if threads are daemons.

* Created dedicated runnable class which perform STUN keep-alive checks.

* Minor comments fixes.

* Do not expose Runnable interface from StunKeepAliveRunner.

* Mark CustomizableThreadFactory fields as final.

* Added java doc to CustomizableThreadFactory
2018-10-29 16:47:20 -07:00
Yury Yaroshevich
ba7e30c189 Fix thread leak when Agent is freed before termination timer triggered. (#150)
* Fix thread leak when Agent is freed before termination timer triggered.

* Use ScheduledExecutorService to terminate agent with timeout

* Fixed formatting to match project code style.
2018-10-24 11:05:00 -05:00
174 changed files with 5995 additions and 8103 deletions

17
.editorconfig Normal file
View File

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

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

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

4
.gitignore vendored
View File

@ -7,3 +7,7 @@
.project
.settings/
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.
ice4j is maintained by the [Jitsi](https://jitsi.org/) community. Use Jitsi's [dev mailing list](https://jitsi.org/Development/MailingLists) for questions and discussions.
ice4j is maintained by the [Jitsi](https://jitsi.org/) community. Use Jitsi's [community forum](https://community.jitsi.org) for questions and discussions.
Thanks
------

6
bnd.bnd Normal file
View File

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

40
checkstyle.xml Normal file
View File

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

416
pom.xml
View File

@ -1,42 +1,119 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.jitsi</groupId>
<artifactId>jitsi-universe-public</artifactId>
<version>1.0</version>
</parent>
<groupId>org.jitsi</groupId>
<artifactId>ice4j</artifactId>
<version>2.0.0-SNAPSHOT</version>
<packaging>bundle</packaging>
<version>3.0-SNAPSHOT</version>
<name>ice4j</name>
<description>A Java implementation of the ICE protocol</description>
<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>
<url>https://github.com/jitsi/ice4j</url>
<connection>scm:git:https://github.com/jitsi/ice4j.git</connection>
<developerConnection>scm:git:https://github.com/jitsi/ice4j.git</developerConnection>
<tag>HEAD</tag>
</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>
<dependency>
<groupId>org.opentelecoms.sdp</groupId>
<artifactId>java-sdp-nist-bridge</artifactId>
</dependency>
<dependency>
<groupId>org.jitsi</groupId>
<artifactId>jain-sip-ri-ossonly</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.bitlet</groupId>
<artifactId>weupnp</artifactId>
<version>0.1.4</version>
</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 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-launcher</artifactId>
<version>1.10.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.kotest</groupId>
<artifactId>kotest-assertions-core-jvm</artifactId>
<version>${kotest.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.kotest</groupId>
<artifactId>kotest-runner-junit5-jvm</artifactId>
<version>${kotest.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jitsi</groupId>
<artifactId>jicoco-test-kotlin</artifactId>
<version>${jicoco.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>4.5.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.mockk</groupId>
<artifactId>mockk-jvm</artifactId>
<version>1.13.8</version>
<scope>test</scope>
</dependency>
</dependencies>
@ -44,58 +121,172 @@
<build>
<plugins>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-plugin</artifactId>
<version>${kotlin.version}</version>
<executions>
<execution>
<id>compile</id>
<phase>compile</phase>
<goals>
<goal>compile</goal>
</goals>
<configuration>
<sourceDirs>
<sourceDir>${project.basedir}/src/main/kotlin</sourceDir>
<sourceDir>${project.basedir}/src/main/java</sourceDir>
</sourceDirs>
</configuration>
</execution>
<execution>
<id>test-compile</id>
<phase>test-compile</phase>
<goals>
<goal>test-compile</goal>
</goals>
<configuration>
<sourceDirs>
<sourceDir>${project.basedir}/src/test/kotlin</sourceDir>
<sourceDir>${project.basedir}/src/test/java</sourceDir>
</sourceDirs>
</configuration>
</execution>
</executions>
<configuration>
<jvmTarget>11</jvmTarget>
<args>
<arg>-Xallow-result-return-type</arg>
</args>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>2.10.4</version>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.10.1</version>
<executions>
<!-- Replacing default-compile as it is treated specially by maven -->
<execution>
<id>default-compile</id>
<phase>none</phase>
</execution>
<!-- Replacing default-testCompile as it is treated specially by maven -->
<execution>
<id>default-testCompile</id>
<phase>none</phase>
</execution>
<execution>
<id>java-compile</id>
<phase>compile</phase>
<goals>
<goal>compile</goal>
</goals>
</execution>
<execution>
<id>java-test-compile</id>
<phase>test-compile</phase>
<goals>
<goal>testCompile</goal>
</goals>
</execution>
</executions>
<configuration>
<show>private</show>
<nohelp>true</nohelp>
<release>11</release>
<compilerArgs>
<arg>-Xlint:all</arg>
</compilerArgs>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId>
<version>3.1.2</version>
<configuration>
<configLocation>checkstyle.xml</configLocation>
</configuration>
<dependencies>
<dependency>
<groupId>com.puppycrawl.tools</groupId>
<artifactId>checkstyle</artifactId>
<version>10.1</version>
</dependency>
</dependencies>
<executions>
<execution>
<goals>
<goal>check</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>com.github.gantsign.maven</groupId>
<artifactId>ktlint-maven-plugin</artifactId>
<version>3.0.0</version>
<configuration>
<sourceRoots>
<sourceRoot>${project.basedir}/src/main/kotlin</sourceRoot>
</sourceRoots>
<testSourceRoots>
<testSourceRoot>${project.basedir}/src/test/kotlin</testSourceRoot>
</testSourceRoots>
</configuration>
<executions>
<execution>
<id>check</id>
<goals>
<goal>check</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>biz.aQute.bnd</groupId>
<artifactId>bnd-maven-plugin</artifactId>
<version>6.2.0</version>
<executions>
<execution>
<goals>
<goal>bnd-process</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>3.2.2</version>
<configuration>
<archive>
<manifestFile>${project.build.outputDirectory}/META-INF/MANIFEST.MF</manifestFile>
</archive>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M6</version>
<configuration>
<includes>
<include>**/*TestSuite.*</include>
</includes>
<includes>**/*</includes>
<systemPropertyVariables>
<java.util.logging.config.file>${project.build.testSourceDirectory}/../resources/logging.properties</java.util.logging.config.file>
</systemPropertyVariables>
</configuration>
</plugin>
<plugin>
<groupId>com.github.siom79.japicmp</groupId>
<artifactId>japicmp-maven-plugin</artifactId>
<version>0.10.0</version>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-deploy-plugin</artifactId>
<version>3.0.0-M2</version>
</plugin>
<plugin>
<groupId>org.sonatype.plugins</groupId>
<artifactId>nexus-staging-maven-plugin</artifactId>
<version>1.6.13</version>
<extensions>true</extensions>
<configuration>
<newVersion>
<file>
<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>
<serverId>ossrh</serverId>
<nexusUrl>https://oss.sonatype.org/</nexusUrl>
<autoReleaseAfterClose>true</autoReleaseAfterClose>
</configuration>
<executions>
<execution>
<phase>verify</phase>
<goals>
<goal>cmp</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
@ -104,6 +295,7 @@
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>3.0.0</version>
<executions>
<execution>
<goals>
@ -127,25 +319,31 @@
<profiles>
<profile>
<id>skip-pre-jdk8</id>
<activation>
<jdk>(,1.8)</jdk>
</activation>
<id>coverage</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<excludes>
<exclude>**/jdk8/**</exclude>
</excludes>
</configuration>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.8.8</version>
<executions>
<execution>
<goals>
<goal>prepare-agent</goal>
</goals>
</execution>
<execution>
<id>report</id>
<phase>test</phase>
<goals>
<goal>report</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
<profile>
<id>run-sample</id>
<build>
@ -250,5 +448,95 @@
</plugins>
</build>
</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>
<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>

View File

@ -59,43 +59,6 @@ public class StackProperties
*/
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
* retransmitting, after it has sent a request for the first time.
@ -123,19 +86,6 @@ public class StackProperties
public static final String MAX_CTRAN_RETRANSMISSIONS
= "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
* let the application see retransmissions of incoming requests.
@ -164,14 +114,6 @@ public class StackProperties
public static final String 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.
* Set to <tt>true</tt> to disable.
@ -190,11 +132,6 @@ public class StackProperties
public static final String 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
* interfaces for host candidate allocations.
@ -219,13 +156,6 @@ public class StackProperties
public static final String 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
* addresses that are not allowed to be used for host candidate allocations.
@ -236,31 +166,6 @@ public class StackProperties
public static final String BLOCKED_ADDRESSES
= "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
* 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)
throws IllegalArgumentException
{
if(UDP.toString().equals(transportName))
if (UDP.toString().equals(transportName))
return UDP;
if(TCP.toString().equals(transportName))
if (TCP.toString().equals(transportName))
return TCP;
if(TLS.toString().equals(transportName))
if (TLS.toString().equals(transportName))
return TLS;
if(SCTP.toString().equals(transportName))
if (SCTP.toString().equals(transportName))
return SCTP;
if(DTLS.toString().equals(transportName))
if (DTLS.toString().equals(transportName))
return DTLS;
if(SSLTCP.toString().equals(transportName))
if (SSLTCP.toString().equals(transportName))
return SSLTCP;
throw new IllegalArgumentException(

View File

@ -148,14 +148,14 @@ public class TransportAddress
public String toString()
{
String hostAddress = getHostAddress();
if(hostAddress == null)
if (hostAddress == null)
{
hostAddress = getHostName();
}
StringBuilder bldr = new StringBuilder(hostAddress);
if(isIPv6())
if (isIPv6())
bldr.insert(0, "[").append("]");
bldr.append(":").append(getPort());
@ -175,7 +175,7 @@ public class TransportAddress
String addressStr
= addr != null ? addr.getHostAddress() : null;
if(addr instanceof Inet6Address)
if (addr instanceof Inet6Address)
addressStr = NetworkUtils.stripScopeID(addressStr);
return addressStr;
@ -258,7 +258,7 @@ public class TransportAddress
*/
public boolean canReach(TransportAddress dst)
{
if( getTransport() != dst.getTransport() )
if ( getTransport() != dst.getTransport() )
return false;
if (isIPv6() != dst.isIPv6())
@ -269,7 +269,7 @@ public class TransportAddress
Inet6Address srcAddr = (Inet6Address)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
//the public address of someone in our local network. however

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -174,7 +174,7 @@ public class PriorityAttribute
throws IllegalArgumentException
{
/* 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 " +
"between 0 and (2**31 - 1)");

View File

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

View File

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

View File

@ -75,7 +75,7 @@ public class ReservationTokenAttribute
void decodeAttributeBody(byte[] attributeValue, char offset, char length)
throws StunException
{
if(length != 8)
if (length != 8)
{
throw new StunException("Length mismatch!");
}
@ -189,12 +189,12 @@ public class ReservationTokenAttribute
private static void generateReservationTokenAttribute(
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
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;
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 + b] = (byte)((right >> (i * 8)) & 0xFFL);

View File

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

View File

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

View File

@ -102,7 +102,7 @@ public class XorMappedAddressAttribute
port ^= portModifier;
for(int i = 0; i < addressBytes.length; i++)
for (int i = 0; i < addressBytes.length; i++)
addressBytes[i] ^= transactionID[i];
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
* to have a long rather than float
*/
if(candidateType == CandidateType.HOST_CANDIDATE)
if (candidateType == CandidateType.HOST_CANDIDATE)
{
priority += 0.95 * 1000 -
(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) -
(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);
}
@ -462,9 +462,9 @@ public abstract class Candidate<T extends Candidate<?>>
InetAddress addr = getTransportAddress().getAddress();
// IPv6 has better priority than IPv4
if(addr instanceof Inet6Address)
if (addr instanceof Inet6Address)
{
if(addr.isLinkLocalAddress())
if (addr.isLinkLocalAddress())
{
priority += 40;
}
@ -499,15 +499,15 @@ public abstract class Candidate<T extends Candidate<?>>
{
int typePreference;
if(candidateType == CandidateType.HOST_CANDIDATE)
if (candidateType == CandidateType.HOST_CANDIDATE)
{
typePreference = MAX_TYPE_PREFERENCE; // 126
}
else if(candidateType == CandidateType.PEER_REFLEXIVE_CANDIDATE)
else if (candidateType == CandidateType.PEER_REFLEXIVE_CANDIDATE)
{
typePreference = 110;
}
else if(candidateType == CandidateType.SERVER_REFLEXIVE_CANDIDATE)
else if (candidateType == CandidateType.SERVER_REFLEXIVE_CANDIDATE)
{
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
//SHOULD be set to.
if(getParentComponent().countLocalHostCandidates() < 2)
if (getParentComponent().countLocalHostCandidates() < 2)
return MAX_LOCAL_PREFERENCE;
//The ICE spec also says: Furthermore, if an agent is multi-homed and
//has multiple IP addresses, the local preference for host candidates
//from a VPN interface SHOULD have a priority of 0.
if(isVirtual())
if (isVirtual())
return MIN_LOCAL_PREFERENCE;
InetAddress addr = getTransportAddress().getAddress();
@ -556,10 +556,10 @@ public abstract class Candidate<T extends Candidate<?>>
//Johnnie seems to think.
//prefer IPv6 to IPv4
if(addr instanceof Inet6Address)
if (addr instanceof Inet6Address)
{
//prefer link local addresses to global ones
if(addr.isLinkLocalAddress())
if (addr.isLinkLocalAddress())
return 30;
else
return 40;
@ -719,7 +719,7 @@ public abstract class Candidate<T extends Candidate<?>>
*/
public TransportAddress getRelatedAddress()
{
if(getRelatedCandidate() != null)
if (getRelatedCandidate() != null)
{
return getRelatedCandidate().getTransportAddress();
}
@ -770,7 +770,7 @@ public abstract class Candidate<T extends Candidate<?>>
TransportAddress relAddr = getRelatedAddress();
if(relAddr != null)
if (relAddr != null)
{
buff.append(" raddr ").append(relAddr.getHostAddress());
buff.append(" rport ").append(relAddr.getPort());
@ -873,19 +873,19 @@ public abstract class Candidate<T extends Candidate<?>>
switch (getType())
{
case SERVER_REFLEXIVE_CANDIDATE:
if(getBase() != null)
if (getBase() != null)
{
return getBase().getHostAddress();
}
break;
case PEER_REFLEXIVE_CANDIDATE:
if(getBase() != null)
if (getBase() != null)
{
return getBase().getHostAddress();
}
break;
case RELAYED_CANDIDATE:
if(getRelatedCandidate() != null)
if (getRelatedCandidate() != null)
{
return getRelatedCandidate().getHostAddress();
}
@ -912,7 +912,7 @@ public abstract class Candidate<T extends Candidate<?>>
return getTransportAddress();
case RELAYED_CANDIDATE:
// Corresponding to getMappedAddress();
if(getRelatedCandidate() != null)
if (getRelatedCandidate() != null)
{
return getRelatedCandidate().getReflexiveAddress();
}
@ -965,19 +965,19 @@ public abstract class Candidate<T extends Candidate<?>>
*/
public T getRelatedCandidate()
{
if(this.relatedCandidate == null)
if (this.relatedCandidate == null)
{
TransportAddress relatedAddress = null;
switch (getType())
{
case SERVER_REFLEXIVE_CANDIDATE:
if(getBase() != null)
if (getBase() != null)
{
relatedAddress = getBase().getTransportAddress();
}
break;
case PEER_REFLEXIVE_CANDIDATE:
if(getBase() != null)
if (getBase() != null)
{
relatedAddress = getBase().getTransportAddress();
}

View File

@ -122,25 +122,25 @@ public enum CandidateExtendedType
public static CandidateExtendedType parse(String extendedTypeName)
throws IllegalArgumentException
{
if(HOST_CANDIDATE.toString().equals(extendedTypeName))
if (HOST_CANDIDATE.toString().equals(extendedTypeName))
return HOST_CANDIDATE;
else if(UPNP_CANDIDATE.toString().equals(extendedTypeName))
else if (UPNP_CANDIDATE.toString().equals(extendedTypeName))
return UPNP_CANDIDATE;
else if(STUN_PEER_REFLEXIVE_CANDIDATE.toString().equals(
else if (STUN_PEER_REFLEXIVE_CANDIDATE.toString().equals(
extendedTypeName))
return STUN_PEER_REFLEXIVE_CANDIDATE;
else if(STUN_SERVER_REFLEXIVE_CANDIDATE.toString().equals(
else if (STUN_SERVER_REFLEXIVE_CANDIDATE.toString().equals(
extendedTypeName))
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;
else if(GOOGLE_TURN_RELAYED_CANDIDATE.toString().equals(
else if (GOOGLE_TURN_RELAYED_CANDIDATE.toString().equals(
extendedTypeName))
return GOOGLE_TURN_RELAYED_CANDIDATE;
else if(GOOGLE_TCP_TURN_RELAYED_CANDIDATE.toString().equals(
else if (GOOGLE_TCP_TURN_RELAYED_CANDIDATE.toString().equals(
extendedTypeName))
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;
throw new IllegalArgumentException(

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -18,15 +18,17 @@
package org.ice4j.ice;
import java.net.*;
import java.time.*;
import java.util.*;
import java.util.logging.*;
import java.util.concurrent.*;
import org.ice4j.*;
import org.ice4j.attribute.*;
import org.ice4j.message.*;
import org.ice4j.socket.*;
import org.ice4j.stack.*;
import org.ice4j.util.Logger; //Disambiguation
import org.ice4j.util.*;
import org.jitsi.utils.logging2.Logger;
/**
* The class that will be generating our outgoing connectivity checks and that
@ -38,22 +40,21 @@ import org.ice4j.util.Logger; //Disambiguation
class ConnectivityCheckClient
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.
*/
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.
*/
@ -62,13 +63,21 @@ class ConnectivityCheckClient
/**
* The {@link PaceMaker}s that are currently running checks in this client.
*/
private final List<PaceMaker> paceMakers = new LinkedList<>();
private final Queue<PaceMaker> paceMakers
= new ConcurrentLinkedQueue<>();
/**
* Whether this {@link ConnectivityCheckClient} has been stopped.
* Synchronized by {@link #paceMakers}.
*/
private boolean stopped = false;
/**
* Timer that is used to let some seconds before a CheckList is considered
* as FAILED.
*/
private Map<String, Timer> timers = new HashMap<>();
private ConcurrentMap<String, ScheduledFuture<?>>
checkListCompletionCheckers = new ConcurrentHashMap<>();
/**
* A flag that determines whether we have received a STUN response or not.
@ -86,11 +95,20 @@ class ConnectivityCheckClient
* information such as user fragments for example.
*
* @param parentAgent the <tt>Agent</tt> that is creating this instance.
* @param scheduledExecutorService the <tt>ScheduledExecutorService</tt>
* to execute clients tasks
* @param executorService the <tt>ExecutorService</tt> to execute
* background tasks of connectivity check client
*/
public ConnectivityCheckClient(Agent parentAgent)
public ConnectivityCheckClient(
Agent parentAgent,
ScheduledExecutorService scheduledExecutorService,
ExecutorService executorService)
{
this.parentAgent = parentAgent;
logger = new Logger(classLogger, parentAgent.getLogger());
this.scheduledExecutorService = scheduledExecutorService;
this.executorService = executorService;
logger = parentAgent.getLogger().createChildLogger(this.getClass().getName());
stunStack = this.parentAgent.getStunStack();
}
@ -126,8 +144,7 @@ class ConnectivityCheckClient
if (streamsWithPendingConnectivityEstablishment.size() > 0)
{
logger.info("Start connectivity checks. Local ufrag "
+ parentAgent.getLocalUfrag());
logger.info("Start connectivity checks.");
startChecks(
streamsWithPendingConnectivityEstablishment
.get(0).getCheckList());
@ -148,13 +165,16 @@ class ConnectivityCheckClient
*/
public void startChecks(CheckList checkList)
{
PaceMaker paceMaker = new PaceMaker(checkList);
synchronized (paceMakers)
{
if (stopped)
{
return;
}
PaceMaker paceMaker = new PaceMaker(checkList);
paceMakers.add(paceMaker);
paceMaker.schedule();
}
paceMaker.start();
}
/**
@ -175,11 +195,8 @@ class ConnectivityCheckClient
indication,
candidatePair.getRemoteCandidate().getTransportAddress(),
localCandidate.getBase().getTransportAddress());
if (logger.isLoggable(Level.FINEST))
{
logger.finest(
"sending binding indication to pair " + candidatePair);
}
logger.trace(() ->
"sending binding indication to pair " + candidatePair);
}
catch (Exception ex)
{
@ -187,11 +204,9 @@ class ConnectivityCheckClient
if (stunSocket != null)
{
logger.log(
Level.INFO,
"Failed to send " + indication + " through "
+ stunSocket.getLocalSocketAddress(),
ex);
logger.info("Failed to send " + indication + " through "
+ stunSocket.getLocalSocketAddress() + "\n" +
ex.toString());
}
}
}
@ -262,7 +277,7 @@ class ConnectivityCheckClient
//nominated pairs.
if (candidatePair.isNominated())
{
logger.fine(
logger.debug(() ->
"Add USE-CANDIDATE in check for: "
+ candidatePair.toShortString());
request.putAttribute(
@ -306,9 +321,12 @@ class ConnectivityCheckClient
tran.setApplicationData(candidatePair);
logger.fine(
"start check for " + candidatePair.toShortString() + " tid "
+ tran);
if (logger.isDebugEnabled())
{
logger.debug(
"start check for " + candidatePair.toShortString() + " tid "
+ tran);
}
try
{
tran
@ -322,12 +340,15 @@ class ConnectivityCheckClient
originalWaitInterval,
maxWaitInterval,
maxRetransmissions);
if (logger.isLoggable(Level.FINEST))
if (logger.isTraceEnabled())
{
logger.finest(
"checking pair " + candidatePair + " tid " + tran);
logger.trace("checking pair " + candidatePair + " tid " + tran);
}
}
catch (NetAccessManager.SocketNotFoundException e)
{
logger.info("Could not start connectivity check: " + e.getMessage());
}
catch (Exception ex)
{
tran = null;
@ -347,7 +368,11 @@ class ConnectivityCheckClient
msg += " No route to host.";
ex = null;
}
logger.log(Level.INFO, msg, ex);
logger.info(msg + (ex == null ? "" : "\n" + ex.toString()));
}
else
{
logger.warn("Failed to send " + request, ex);
}
}
@ -387,7 +412,7 @@ class ConnectivityCheckClient
{
if (!response.containsAttribute(Attribute.ERROR_CODE))
{
logger.fine("Received a malformed error response.");
logger.debug(() -> "Received a malformed error response.");
return; //malformed error response
}
@ -431,14 +456,12 @@ class ConnectivityCheckClient
if ( !stream.validListContainsAllComponents())
{
final String streamName = stream.getName();
Timer timer = timers.get(streamName);
if (timer == null)
if (!checkListCompletionCheckers.containsKey(streamName))
{
logger.info("CheckList will failed in a few seconds if no" +
"succeeded checks come");
logger.info("CheckList will failed in a few seconds" +
" if no succeeded checks come");
TimerTask task = new TimerTask()
Runnable checkLickCompletedChecker = new Runnable()
{
@Override
public void run()
@ -453,9 +476,20 @@ class ConnectivityCheckClient
}
}
};
timer = new Timer();
timers.put(streamName, timer);
timer.schedule(task, 5000);
final ScheduledFuture<?> scheduledCheckerFuture
= scheduledExecutorService.schedule(
checkLickCompletedChecker,
5000,
TimeUnit.MILLISECONDS);
final ScheduledFuture<?> existingCheckerFuture
= checkListCompletionCheckers
.putIfAbsent(streamName, scheduledCheckerFuture);
if (existingCheckerFuture != null)
{
scheduledCheckerFuture.cancel(false);
}
}
}
@ -499,11 +533,10 @@ class ConnectivityCheckClient
if (!response.containsAttribute(Attribute.XOR_MAPPED_ADDRESS))
{
logger.fine("Received a success response with no "
logger.debug(() -> "Received a success response with no "
+ "XOR_MAPPED_ADDRESS attribute.");
logger.info("Pair failed (no XOR-MAPPED-ADDRESS): "
+ checkedPair.toShortString() + ". Local ufrag"
+ parentAgent.getLocalUfrag());
+ checkedPair.toShortString() + ".");
checkedPair.setStateFailed();
return; //malformed error response
}
@ -525,9 +558,12 @@ class ConnectivityCheckClient
Transport.TCP);
}
LocalCandidate validLocalCandidate = null;
validLocalCandidate = parentAgent.findLocalCandidate(mappedAddress);
// In some situations we may have more than one local candidate matching
// the mapped address. In this case we want to find the that matches
// the socket we received the response on.
LocalCandidate base = checkedPair.getLocalCandidate().getBase();
LocalCandidate validLocalCandidate
= parentAgent.findLocalCandidate(mappedAddress, base);
RemoteCandidate validRemoteCandidate = checkedPair.getRemoteCandidate();
@ -573,7 +609,7 @@ class ConnectivityCheckClient
{
logger.info("Receive a peer-reflexive candidate: "
+ peerReflexiveCandidate.getTransportAddress()
+ ". Local ufrag " + parentAgent.getLocalUfrag());
+ ".");
}
}
@ -611,8 +647,7 @@ class ConnectivityCheckClient
if (checkedPair.getParentComponent().getSelectedPair() == null)
{
logger.info("Pair succeeded: " + checkedPair.toShortString()
+ ". Local ufrag "
+ parentAgent.getLocalUfrag());
+ ".");
}
checkedPair.setStateSucceeded();
}
@ -621,7 +656,7 @@ class ConnectivityCheckClient
{
if (validPair.getParentComponent().getSelectedPair() == null)
logger.info("Pair validated: " + validPair.toShortString()
+ ". Local ufrag " + parentAgent.getLocalUfrag());
+ ".");
parentAgent.validatePair(validPair);
}
@ -693,7 +728,7 @@ class ConnectivityCheckClient
" USE-CANDIDATE:" +
(request.containsAttribute(Attribute.USE_CANDIDATE) ||
checkedPair.useCandidateSent())
+ ". Local ufrag " + parentAgent.getLocalUfrag());
+ ".");
}
//If the agent was a controlling agent, and it had included a USE-
@ -706,12 +741,12 @@ class ConnectivityCheckClient
{
logger.info("Nomination confirmed for pair: "
+ validPair.toShortString()
+ ". Loal ufrag " + parentAgent.getLocalUfrag());
+ ".");
parentAgent.nominationConfirmed( validPair );
}
else
{
logger.fine(
logger.debug(() ->
"Keep alive for pair: " + validPair.toShortString());
}
}
@ -733,7 +768,7 @@ class ConnectivityCheckClient
}
else
{
logger.fine(
logger.debug(() ->
"Keep alive for pair: " + validPair.toShortString());
}
}
@ -803,7 +838,7 @@ class ConnectivityCheckClient
CandidatePair pair
= (CandidatePair) ev.getTransactionID().getApplicationData();
logger.finer("Received error code " + ((int) errorCode));
logger.trace(() -> "Received error code " + ((int) errorCode));
//RESOLVE ROLE_CONFLICTS
if (errorCode == ErrorCodeAttribute.ROLE_CONFLICT)
@ -811,7 +846,7 @@ class ConnectivityCheckClient
boolean wasControlling
= originalRequest.containsAttribute(Attribute.ICE_CONTROLLING);
logger.finer("Switching to isControlling=" + !wasControlling);
logger.trace(() -> "Switching to isControlling=" + !wasControlling);
parentAgent.setControlling(!wasControlling);
pair.getParentComponent().getParentStream().getCheckList()
@ -820,10 +855,12 @@ class ConnectivityCheckClient
else
{
int code = cl * 100 + co;
String reason = errorAttr.getReasonPhrase();
String trimmedReason = reason != null ? reason.trim() : null;
logger.info(
"Error response for pair: " + pair.toShortString() +
", failing. Code = " + code +
"(class=" + cl + "; number=" + co + ")");
"(class=" + cl + "; number=" + co + "): " + trimmedReason);
pair.setStateFailed();
}
}
@ -847,17 +884,11 @@ class ConnectivityCheckClient
}
/**
* The thread that actually sends the checks for a particular check list
* in the pace defined in RFC 5245.
* A class to control periodically scheduled runnable that actually sends
* the checks for a particular check list in the pace defined in RFC 5245.
*/
private class PaceMaker
extends Thread
private final class PaceMaker extends PeriodicRunnable
{
/**
* Indicates whether this <tt>Thread</tt> should still be running.
*/
boolean running = true;
/**
* The {@link CheckList} that this <tt>PaceMaker</tt> will be running
* checks for.
@ -873,18 +904,63 @@ class ConnectivityCheckClient
*/
public PaceMaker(CheckList checkList)
{
super("ICE PaceMaker: " + parentAgent.getLocalUfrag());
super(scheduledExecutorService, executorService);
this.checkList = checkList;
}
/*
* Because PaceMaker does not seem to be a daemon at least on Ubuntu
* in the run-sample target and it looks like it should be from the
* standpoint of the application, explicitly tell it to be a daemon.
* Otherwise, it could prevent the application from exiting because
* of a problem in the ICE implementation.
*/
setDaemon(true);
/**
* 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
protected void run()
{
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();
}
}
/**
@ -894,7 +970,7 @@ class ConnectivityCheckClient
* @return the number milliseconds to wait before we send the next
* check.
*/
private long getNextWaitInterval()
protected Duration getDelayUntilNextRun()
{
int activeCheckLists = parentAgent.getActiveCheckListCount();
@ -905,96 +981,7 @@ class ConnectivityCheckClient
activeCheckLists = 1;
}
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);
}
}
}
return Duration.ofMillis(parentAgent.calculateTa() * activeCheckLists);
}
}
@ -1005,19 +992,15 @@ class ConnectivityCheckClient
{
synchronized (paceMakers)
{
Iterator<PaceMaker> paceMakersIter = paceMakers.iterator();
while(paceMakersIter.hasNext())
stopped = true;
while (true)
{
PaceMaker paceMaker = paceMakersIter.next();
synchronized (paceMaker)
final PaceMaker paceMaker = paceMakers.poll();
if (paceMaker == null)
{
paceMaker.running = false;
paceMaker.notify();
break;
}
paceMakersIter.remove();
paceMaker.cancel();
}
}
}

View File

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

View File

@ -17,11 +17,11 @@
*/
package org.ice4j.ice;
import org.jitsi.utils.logging2.*;
import java.beans.*;
import java.util.*;
import org.ice4j.util.*;
/**
* Implements ice4j internal nomination strategies.
*
@ -30,15 +30,6 @@ import org.ice4j.util.*;
public class DefaultNominator
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.
*/
@ -71,7 +62,7 @@ public class DefaultNominator
public DefaultNominator(Agent parentAgent)
{
this.parentAgent = parentAgent;
logger = new Logger(classLogger, parentAgent.getLogger());
logger = parentAgent.getLogger().createChildLogger(this.getClass().getName());
parentAgent.addStateChangeListener(this);
}
@ -107,17 +98,20 @@ public class DefaultNominator
if (ev.getSource() instanceof CandidatePair)
{
// 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;
}
CandidatePair validPair = (CandidatePair) ev.getSource();
Component parentComponent = validPair.getParentComponent();
IceMediaStream parentStream = parentComponent.getParentStream();
// do not nominate pair if there is currently a selected pair for
// do not nominate pair if there is currently a nominated pair for
// the component
if (validPair.getParentComponent().getSelectedPair() != null)
if (parentStream.validListContainsNomineeForComponent(parentComponent))
{
logger.fine(
logger.debug(() ->
"Keep-alive for pair: " + validPair.toShortString());
return;
}
@ -147,7 +141,7 @@ public class DefaultNominator
CandidatePair validPair = (CandidatePair)evt.getSource();
logger.info("Nominate (first valid): " + validPair.toShortString()
+ ". Local ufrag " + parentAgent.getLocalUfrag());
+ ".");
parentAgent.nominate(validPair);
}
}
@ -191,6 +185,18 @@ public class DefaultNominator
}
}
/**
* The {@link NominationStrategy} that this nominator is using when
* deciding whether or not a valid {@link CandidatePair} is suitable for
* nomination.
*
* @return the {@link NominationStrategy} we are using.
*/
public NominationStrategy getStrategy()
{
return strategy;
}
/**
* The {@link NominationStrategy} that this nominator should use when
* 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);
foundationStringBuff.append(base);
if(server != null)
if (server != null)
foundationStringBuff.append(server);
foundationStringBuff.append(transport);
@ -97,7 +97,7 @@ public class FoundationsRegistry
//obtain a new foundation number if we don't have one for this kind
//of candidates.
if(foundationValue == null)
if (foundationValue == null)
{
foundationValue = Integer.toString(++lastAssignedFoundation);
foundations.put(foundationString, foundationValue);

View File

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

View File

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

View File

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

View File

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

View File

@ -44,8 +44,11 @@ public enum NominationStrategy
NOMINATE_FIRST_VALID("NominateFirstValid"),
/**
* The strategy consists in nominating the highest priority valid pair once
* all checks in a list have completed.
* The strategy consists in nominating the highest priority valid pair.
* Once a pair is validated, if no higher-priority pairs remain outstanding,
* it is nominated; otherwise, a timer is armed, and if higher-priority
* pairs are still outstanding after the timeout, the highest-priority validated
* pair is nominated.
*/
NOMINATE_HIGHEST_PRIO("NominateHighestPriority"),
@ -90,4 +93,19 @@ public enum NominationStrategy
{
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,
long priority,
RemoteCandidate relatedCandidate,
String ufrag)
String ufrag)
{
super(transportAddress, parentComponent, type, relatedCandidate);
setFoundation(foundation);

View File

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

View File

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

View File

@ -19,7 +19,6 @@ package org.ice4j.ice.harvest;
import org.ice4j.*;
import org.ice4j.ice.*;
import org.ice4j.message.*;
import org.ice4j.socket.*;
import java.io.*;
@ -29,6 +28,8 @@ import java.nio.channels.*;
import java.util.*;
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
* start with a STUN Binding Request (preceded by an optional fake SSL
@ -59,7 +60,15 @@ public abstract class AbstractTcpListener
*/
static void closeNoExceptions(Channel channel)
{
MuxServerSocketChannelFactory.closeNoExceptions(channel);
try
{
channel.close();
}
catch (IOException ioe)
{
// The whole idea of the method is to close a specific Channel
// without caring about any possible IOException.
}
}
/**
@ -73,7 +82,6 @@ public abstract class AbstractTcpListener
private static List<TransportAddress> getLocalAddresses(
int port,
List<NetworkInterface> interfaces)
throws IOException
{
List<TransportAddress> addresses = new LinkedList<>();
@ -89,7 +97,7 @@ public abstract class AbstractTcpListener
Enumeration<InetAddress> ifaceAddresses = iface.getInetAddresses();
while(ifaceAddresses.hasMoreElements())
while (ifaceAddresses.hasMoreElements())
{
InetAddress addr = ifaceAddresses.nextElement();
@ -99,83 +107,6 @@ public abstract class AbstractTcpListener
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
* {@link #serverSocketChannels}.
@ -216,12 +147,6 @@ public abstract class AbstractTcpListener
private final List<ServerSocketChannel> serverSocketChannels
= 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
* listen on port number <tt>port</tt> on all IP addresses on all available
@ -283,13 +208,6 @@ public abstract class AbstractTcpListener
protected void addLocalAddresses(List<TransportAddress> transportAddresses)
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
String[] allowedAddressesStr
= StackProperties.getStringArray(StackProperties.ALLOWED_ADDRESSES,
@ -301,8 +219,7 @@ public abstract class AbstractTcpListener
allowedAddresses = new InetAddress[allowedAddressesStr.length];
for (int i = 0; i < allowedAddressesStr.length; i++)
{
allowedAddresses[i]
= InetAddress.getByName(allowedAddressesStr[i]);
allowedAddresses[i] = InetAddress.getByName(allowedAddressesStr[i]);
}
}
@ -332,15 +249,12 @@ public abstract class AbstractTcpListener
continue;
}
if (!useIPv6 && (address instanceof Inet6Address))
if (!config.useIpv6() && (address instanceof Inet6Address))
continue;
if (!useIPv6LinkLocal
&& (address instanceof Inet6Address)
&& address.isLinkLocalAddress())
if (!config.useLinkLocalAddresses() && address.isLinkLocalAddress())
{
logger.info("Not using link-local address " + address +" for"
+ " TCP candidates.");
logger.info("Not using link-local address " + address +" for TCP candidates.");
continue;
}
@ -441,21 +355,7 @@ public abstract class AbstractTcpListener
throws IOException
{
ServerSocketChannel channel = MuxServerSocketChannelFactory
.openAndBindMuxServerSocketChannel(
/* properties */ null,
address,
/* backlog */ 0,
new DatagramPacketFilter()
{
/**
* {@inheritDoc}
*/
@Override
public boolean accept(DatagramPacket p)
{
return isFirstDatagramPacket(p);
}
});
.openAndBindServerSocketChannel(null, address, 0);
serverSocketChannels.add(channel);
}
@ -466,8 +366,6 @@ public abstract class AbstractTcpListener
* @param ufrag the local username fragment for the session.
* @param pushback the first "datagram" (RFC4571-framed), already read from
* the socket's stream.
* @throws IllegalStateException
* @throws IOException
*/
protected abstract void acceptSession(
Socket socket, String ufrag, DatagramPacket pushback)
@ -607,7 +505,9 @@ public abstract class AbstractTcpListener
selector.close();
}
catch (IOException ioe)
{}
{
// ignore
}
}
}
@ -622,11 +522,6 @@ public abstract class AbstractTcpListener
*/
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.
*/
@ -792,11 +687,8 @@ public abstract class AbstractTcpListener
{
/**
* Initializes a new <tt>ReadThread</tt>.
*
* @throws IOException if the selector to be used fails to open.
*/
public ReadThread()
throws IOException
{
setName("TcpHarvester ReadThread");
setDaemon(true);
@ -830,50 +722,6 @@ public abstract class AbstractTcpListener
}
}
/**
* Closes any inactive channels registered with {@link #readSelector}.
* A channel is considered inactive if it hasn't been available for
* reading for
* {@link MuxServerSocketChannelFactory#SOCKET_CHANNEL_READ_TIMEOUT}
* milliseconds.
*/
private void cleanup()
{
long now = System.currentTimeMillis();
for (SelectionKey key : readSelector.keys())
{
// An invalid key specifies that either the channel was closed
// (in which case we do not have to do anything else to it) or
// that we no longer control the channel (i.e. we do not want to
// do anything else to it).
if (!key.isValid())
continue;
ChannelDesc channelDesc = (ChannelDesc) key.attachment();
if (channelDesc == null)
continue;
long lastActive = channelDesc.lastActive;
if (lastActive != -1
&& now - lastActive
> MuxServerSocketChannelFactory
.SOCKET_CHANNEL_READ_TIMEOUT)
{
// De-register from the Selector.
key.cancel();
SocketChannel channel = channelDesc.channel;
logger.info("Read timeout for socket: " + channel.socket());
closeNoExceptions(channel);
}
}
}
/**
* Tries to read, without blocking, from <tt>channel</tt> to its
* buffer. If after reading the buffer is filled, handles the data in
@ -924,8 +772,6 @@ public abstract class AbstractTcpListener
if (read == -1)
throw new IOException("End of stream!");
else if (read > 0)
channel.lastActive = System.currentTimeMillis();
if (!channel.buffer.hasRemaining())
{
@ -965,7 +811,7 @@ public abstract class AbstractTcpListener
bytesRead, 2, bytesRead.length);
// if we had read enough data
if(channel.length <= bytesRead.length - 2)
if (channel.length <= bytesRead.length - 2)
{
processFirstDatagram(
preBuffered, channel, key);
@ -1000,7 +846,7 @@ public abstract class AbstractTcpListener
channel.buffer.flip();
channel.buffer.get(bytesRead);
if(channel.preBuffered != null)
if (channel.preBuffered != null)
{
// will store preBuffered and currently read data
byte[] newBytesRead = new byte[
@ -1111,9 +957,6 @@ public abstract class AbstractTcpListener
break;
}
// clean up stale channels
cleanup();
checkForNewChannels();
for (SelectionKey key : readSelector.keys())
@ -1173,7 +1016,9 @@ public abstract class AbstractTcpListener
readSelector.close();
}
catch (IOException ioe)
{}
{
// ignore
}
}
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -26,6 +26,8 @@ import org.ice4j.*;
import org.ice4j.ice.*;
import org.ice4j.socket.*;
import static org.ice4j.ice.harvest.HarvestConfig.config;
/**
* A <tt>HostCandidateHarvester</tt> gathers host <tt>Candidate</tt>s for a
* specified {@link org.ice4j.ice.Component}. Most <tt>CandidateHarvester</tt>s
@ -229,13 +231,6 @@ public class HostCandidateHarvester
public static List<InetAddress> getAllAllowedAddresses()
{
List<InetAddress> addresses = new LinkedList<>();
boolean isIPv6Disabled = StackProperties.getBoolean(
StackProperties.DISABLE_IPv6,
false);
boolean isIPv6LinkLocalDisabled = StackProperties.getBoolean(
StackProperties.DISABLE_LINK_LOCAL_ADDRESSES,
false);
try
{
for (NetworkInterface iface
@ -257,11 +252,9 @@ public class HostCandidateHarvester
if (!isAddressAllowed(address))
continue;
if (isIPv6Disabled && address instanceof Inet6Address)
if (!config.useIpv6() && address instanceof Inet6Address)
continue;
if (isIPv6LinkLocalDisabled
&& address instanceof Inet6Address
&& address.isLinkLocalAddress())
if (!config.useLinkLocalAddresses() && address.isLinkLocalAddress())
continue;
addresses.add(address);
@ -283,6 +276,8 @@ public class HostCandidateHarvester
* 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.
*
* 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
* addresses for.
* @param preferredPort the port number that should be tried first when
@ -309,21 +304,11 @@ public class HostCandidateHarvester
{
harvestStatistics.startHarvestTiming();
Enumeration<NetworkInterface> interfaces
= NetworkInterface.getNetworkInterfaces();
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
boolean isIPv6Disabled = StackProperties.getBoolean(
StackProperties.DISABLE_IPv6,
false);
boolean isIPv6LinkLocalDisabled = StackProperties.getBoolean(
StackProperties.DISABLE_LINK_LOCAL_ADDRESSES,
false);
if(transport != Transport.UDP && transport != Transport.TCP)
if (transport != Transport.UDP && transport != Transport.TCP)
{
throw new IllegalArgumentException(
"Transport protocol not supported: " + transport);
throw new IllegalArgumentException("Transport protocol not supported: " + transport);
}
boolean boundAtLeastOneSocket = false;
@ -344,7 +329,7 @@ public class HostCandidateHarvester
Enumeration<InetAddress> addresses = iface.getInetAddresses();
while(addresses.hasMoreElements())
while (addresses.hasMoreElements())
{
InetAddress addr = addresses.nextElement();
@ -353,28 +338,25 @@ public class HostCandidateHarvester
continue;
}
if (isIPv6LinkLocalDisabled
&& (addr instanceof Inet6Address)
&& addr.isLinkLocalAddress())
if (!config.useLinkLocalAddresses() && addr.isLinkLocalAddress())
{
continue;
}
foundAtLeastOneUsableAddress = true;
if((addr instanceof Inet4Address) || !isIPv6Disabled)
if ((addr instanceof Inet4Address) || config.useIpv6())
{
IceSocketWrapper sock = null;
try
{
if(transport == Transport.UDP)
if (transport == Transport.UDP)
{
sock = createDatagramSocket(
addr, preferredPort, minPort, maxPort);
sock = createDatagramSocket(addr, preferredPort, minPort, maxPort);
boundAtLeastOneSocket = true;
}
else if(transport == Transport.TCP)
else if (transport == Transport.TCP)
{
if(addr instanceof Inet6Address)
if (addr instanceof Inet6Address)
continue;
sock = createServerSocket(
addr,
@ -404,10 +386,8 @@ public class HostCandidateHarvester
continue;
}
HostCandidate candidate
= new HostCandidate(sock, component, transport);
candidate.setVirtual(
NetworkUtils.isInterfaceVirtual(iface));
HostCandidate candidate = new HostCandidate(sock, component, transport);
candidate.setVirtual(NetworkUtils.isInterfaceVirtual(iface));
component.addLocalCandidate(candidate);
if (transport == Transport.TCP)
@ -423,8 +403,7 @@ public class HostCandidateHarvester
// them as well while harvesting reflexive candidates.
createAndRegisterStunSocket(candidate);
ComponentSocket componentSocket
= component.getComponentSocket();
ComponentSocket componentSocket = component.getComponentSocket();
if (componentSocket != null)
{
componentSocket.add(sock);
@ -447,8 +426,7 @@ public class HostCandidateHarvester
+ foundAtLeastOneUsableAddress);
}
this.harvestStatistics
.stopHarvestTiming(component.getLocalCandidateCount());
this.harvestStatistics.stopHarvestTiming(component.getLocalCandidateCount());
}
/**
@ -463,7 +441,7 @@ public class HostCandidateHarvester
* <tt>org.ice4j.ice.harvest.BLOCKED_INTERFACES</tt> list. It returns
* <tt>false</tt> otherwise.
*/
static boolean isInterfaceAllowed(NetworkInterface iface)
public static boolean isInterfaceAllowed(NetworkInterface iface)
{
if (iface == null)
throw new IllegalArgumentException("iface cannot be null");
@ -543,6 +521,8 @@ public class HostCandidateHarvester
* <tt>localAddress</tt> and a port in the range specified by the
* <tt>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 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
@ -569,7 +549,18 @@ public class HostCandidateHarvester
BindException
{
// make sure port numbers are valid
this.checkPorts(preferredPort, minPort, maxPort);
boolean ephemeral = checkPorts(preferredPort, minPort, maxPort);
if (ephemeral)
{
ServerSocket socket = new ServerSocket();
socket.setReuseAddress(true);
socket.bind(new InetSocketAddress(laddr, 0));
if (logger.isLoggable(Level.FINEST))
{
logger.finest("Bound using an ephemeral port to " + socket.getLocalSocketAddress());
}
return new IceTcpServerSocketWrapper(new DelegatingServerSocket(socket), component);
}
int bindRetries = StackProperties.getInt(
StackProperties.BIND_RETRIES,
@ -588,7 +579,7 @@ public class HostCandidateHarvester
new DelegatingServerSocket(sock),
component);
if(logger.isLoggable(Level.FINEST))
if (logger.isLoggable(Level.FINEST))
{
logger.log(
Level.FINEST,
@ -613,8 +604,7 @@ public class HostCandidateHarvester
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));
}
/**
@ -629,6 +619,8 @@ public class HostCandidateHarvester
* start over again at <tt>minPort</tt> and keep going until we run out of
* 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 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
@ -656,7 +648,16 @@ public class HostCandidateHarvester
BindException
{
// make sure port numbers are valid.
this.checkPorts(preferredPort, minPort, maxPort);
boolean ephemeral = checkPorts(preferredPort, minPort, maxPort);
if (ephemeral)
{
DatagramSocket socket = new MultiplexingDatagramSocket(0, laddr);
if (logger.isLoggable(Level.FINEST))
{
logger.finest("Bound using ephemeral port to " + socket.getLocalSocketAddress());
}
return new IceUdpSocketWrapper(socket);
}
int bindRetries = StackProperties.getInt(
StackProperties.BIND_RETRIES,
@ -671,7 +672,7 @@ public class HostCandidateHarvester
= new IceUdpSocketWrapper(new
MultiplexingDatagramSocket(port, laddr));
if(logger.isLoggable(Level.FINEST))
if (logger.isLoggable(Level.FINEST))
{
logger.log(
Level.FINEST,
@ -718,8 +719,10 @@ public class HostCandidateHarvester
}
/**
* Checks if the different ports are correctly set. If not, throws an
* IllegalArgumentException.
* Checks if the different ports are correctly set. If not, throws {@link IllegalArgumentException}. The
* special values 0, 0, 0 for the parameters are interpreted as "use an ephemeral port".
*
* @return {@code true} if the params specify that an ephemeral port should be used, and {@code false} otherwise.
*
* @param preferredPort the port number that we should try to bind to first.
* @param minPort the port number where we should first try to bind before
@ -731,9 +734,14 @@ public class HostCandidateHarvester
* <tt>maxPort</tt> is not a valid port number or if <tt>minPort</tt> is
* greater than <tt>maxPort</tt>.
*/
private void checkPorts(int preferredPort, int minPort, int maxPort)
private static boolean checkPorts(int preferredPort, int minPort, int maxPort)
throws IllegalArgumentException
{
if (preferredPort == 0 && minPort == 0 && maxPort == 0)
{
return true;
}
// make sure port numbers are valid
if (!NetworkUtils.isValidPortNumber(minPort)
|| !NetworkUtils.isValidPortNumber(maxPort))
@ -758,6 +766,8 @@ public class HostCandidateHarvester
+") must be between minPort (" + minPort
+ ") and maxPort (" + maxPort + ")");
}
return false;
}
/**

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -20,13 +20,13 @@ package org.ice4j.ice.harvest;
import org.ice4j.*;
import org.ice4j.socket.*;
import org.ice4j.stunclient.*;
import org.jetbrains.annotations.*;
import java.net.*;
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 Boris Grozev
@ -38,13 +38,24 @@ public class StunMappingCandidateHarvester
* The <tt>Logger</tt> used by the <tt>StunMappingCandidateHarvester</tt>
* 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.
*/
private TransportAddress stunServerAddress;
private final TransportAddress stunServerAddress;
/**
* The local address this {@link StunMappingCandidateHarvester} was initialized with, and which will be used to
* communicate to STUN servers.
*/
@NotNull
private TransportAddress localAddress;
/**
* The public address discovered through STUN, if any.
*/
private TransportAddress publicAddress = null;
/**
* Initializes a new {@link StunMappingCandidateHarvester} instance with
@ -55,10 +66,11 @@ public class StunMappingCandidateHarvester
* @param stunServerAddress The address of the STUN server.
*/
public StunMappingCandidateHarvester(
TransportAddress localAddress,
@NotNull TransportAddress localAddress,
TransportAddress stunServerAddress)
{
face = localAddress;
super("stun");
this.localAddress = localAddress;
this.stunServerAddress = stunServerAddress;
}
@ -75,22 +87,48 @@ public class StunMappingCandidateHarvester
= new SimpleAddressDetector(stunServerAddress);
sad.start();
IceSocketWrapper localSocket
= new IceUdpSocketWrapper(new DatagramSocket(face));
IceSocketWrapper localSocket = new IceUdpSocketWrapper(new DatagramSocket(localAddress));
mask = sad.getMappingFor(localSocket);
if (mask != null)
publicAddress = sad.getMappingFor(localSocket);
/* Record bound address as face. */
SocketAddress boundAddr = localSocket.getLocalSocketAddress();
if (boundAddr instanceof InetSocketAddress)
{
logger.info("Discovered public address " + mask
localAddress = new TransportAddress((InetSocketAddress)boundAddr, localAddress.getTransport());
}
if (publicAddress != null)
{
logger.info("Discovered public address " + publicAddress
+ " from STUN server " + stunServerAddress
+ " using local address " + face);
+ " using local address " + localSocket);
}
}
catch (Exception exc)
{
//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");
try
{
if(device == null)
if (device == null)
{
// do it only once
if(finishThreads == 0)
if (finishThreads == 0)
{
try
{
@ -108,17 +108,17 @@ public class UPNPHarvester
synchronized(rootSync)
{
while(finishThreads != 2)
while (finishThreads != 2)
{
rootSync.wait();
}
}
if(wanIPThread.getDevice() != null)
if (wanIPThread.getDevice() != null)
{
device = wanIPThread.getDevice();
}
else if(wanPPPThread.getDevice() != null)
else if (wanPPPThread.getDevice() != null)
{
device = wanPPPThread.getDevice();
}
@ -130,7 +130,7 @@ public class UPNPHarvester
}
}
if(device == null)
if (device == null)
return candidates;
}
@ -143,12 +143,12 @@ public class UPNPHarvester
int port = 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))
{
if(device.addPortMapping(
if (device.addPortMapping(
externalPort,
port,
localAddress.getHostAddress(),
@ -165,11 +165,11 @@ public class UPNPHarvester
// if we don't add the base, we won't be able to add
// peer reflexive candidate if someone contact us on the
// UPNPCandidate
for(LocalCandidate cand : cands)
for (LocalCandidate cand : cands)
{
//try to add the candidate to the component and then
//only add it to the harvest not redundant
if(component.addLocalCandidate(cand))
if (component.addLocalCandidate(cand))
{
candidates.add(cand);
}
@ -280,7 +280,7 @@ public class UPNPHarvester
gd.discover();
if(gd.getValidGateway() != null)
if (gd.getValidGateway() != null)
{
device = gd.getValidGateway();
}
@ -294,7 +294,7 @@ public class UPNPHarvester
* a method, it is important that it be rethrown so that the
* thread actually dies.
*/
if(e instanceof ThreadDeath)
if (e instanceof ThreadDeath)
throw (ThreadDeath)e;
}
finally

View File

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

View File

@ -106,7 +106,7 @@ public class ChannelData
*/
public char getDataLength()
{
if(data == null)
if (data == null)
return 0;
return (char)data.length;
@ -159,7 +159,7 @@ public class ChannelData
byte binMsg[] = new byte[HEADER_LENGTH + dataLength];
int offset = 0;
if(!validateChannelNumber(channelNumber))
if (!validateChannelNumber(channelNumber))
{
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 & 0xff : 0);
if(data != null)
if (data != null)
{
System.arraycopy(data, 0, binMsg, offset, data.length);
}
@ -210,14 +210,14 @@ public class ChannelData
ChannelData channelData = 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");
}
channelNumber = (char)((binMessage[offset++]<<8) | (binMessage[offset++]&0xFF));
if(!validateChannelNumber(channelNumber))
if (!validateChannelNumber(channelNumber))
{
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
* 0x0115 & 0x0110 indicates STUN error response type
*/
if(!isIndicationType(indicationType) &&
if (!isIndicationType(indicationType) &&
indicationType != OLD_DATA_INDICATION)
throw new IllegalArgumentException(
(int)(indicationType)

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -26,23 +26,23 @@ public enum PseudoTcpState
/**
* Initial state, can accept connection
*/
TCP_LISTEN,// = 0,
TCP_LISTEN, // = 0,
/**
* SYN sent to remote peer, wits for SYN
*/
TCP_SYN_SENT,// = 1,
TCP_SYN_SENT, // = 1,
/**
* SYN received from remote peer, sends back SYN
*/
TCP_SYN_RECEIVED,// = 2;
TCP_SYN_RECEIVED, // = 2;
/**
* SYN sent and received - connection established
*/
TCP_ESTABLISHED,// = 3;
TCP_ESTABLISHED, // = 3;
/**
* Closed state. In current implementation reached on error
* or explicite by close method with force option
* 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
// given in parameter.
if(delegate != null)
if (delegate != null)
{
this.delegate = delegate;
}
@ -233,7 +233,7 @@ public class DelegatingDatagramSocket
{
// Creates a custom DatagramSocket to replace classical "java"
// DatagramSocket and set it as a delegate Socket
if(delegateFactory != null)
if (delegateFactory != null)
{
this.delegate = delegateFactory.createUnboundDatagramSocket();
}
@ -741,7 +741,7 @@ public class DelegatingDatagramSocket
catch(Exception ex)
{
InetAddress tmpAddr = p.getAddress();
if(((ex instanceof NoRouteToHostException)
if (((ex instanceof NoRouteToHostException)
|| (ex.getMessage() != null
&& ex.getMessage().equals("No route to host")))
&& (tmpAddr instanceof Inet6Address)
@ -755,9 +755,10 @@ public class DelegatingDatagramSocket
p.setAddress(newAddr);
super.send(p);
} else if (ex instanceof IOException) {
throw((IOException)ex);
}
else if (ex instanceof IOException)
{
throw((IOException)ex);
}
}
@ -940,7 +941,7 @@ public class DelegatingDatagramSocket
throws SocketException
{
// Only change the buffer size on the real underlying DatagramSocket.
if(delegate == null && defaultReceiveBufferSize > 0)
if (delegate == null && defaultReceiveBufferSize > 0)
{
super.setReceiveBufferSize(defaultReceiveBufferSize);
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -18,11 +18,9 @@
package org.ice4j.socket;
import java.io.*;
import java.lang.reflect.*;
import java.net.*;
import java.nio.channels.*;
import java.util.*;
import java.util.logging.*;
/**
* If supported by the runtime, initializes {@link ServerSocketChannel}s which
@ -33,19 +31,6 @@ import java.util.logging.*;
*/
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
* {@code SocketChannel} to provide incoming/readable data before it is
@ -56,158 +41,12 @@ public class MuxServerSocketChannelFactory
/**
* The name of the {@code boolean} property of the {@code socket} property
* of the {@code ServerSocketChannel} returned by
* {@link #openAndBindMuxServerSocketChannel(Map, SocketAddress, int,
* DatagramPacketFilter)} which specifies the value of the
* {@code SO_REUSEADDR} socket option.
* {@link #openAndBindServerSocketChannel(Map, SocketAddress, int)} which
* specifies the value of the {@code SO_REUSEADDR} socket option.
*/
public static final String SOCKET_REUSE_ADDRESS_PROPERTY_NAME
= "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.
*
@ -225,7 +64,7 @@ public class MuxServerSocketChannelFactory
* @throws IOException if an I/O error occurs
*/
public static ServerSocketChannel openAndBindServerSocketChannel(
Map<String,Object> properties,
Map<String, Object> properties,
SocketAddress endpoint,
int backlog)
throws IOException
@ -236,7 +75,7 @@ public class MuxServerSocketChannelFactory
if (properties != null && !properties.isEmpty())
{
for (Map.Entry<String,Object> property
for (Map.Entry<String, Object> property
: properties.entrySet())
{
String name = property.getKey();
@ -251,7 +90,7 @@ public class MuxServerSocketChannelFactory
else if (value instanceof Boolean)
on = (Boolean) value;
else
on = Boolean.valueOf(value.toString());
on = Boolean.parseBoolean(value.toString());
socket.setReuseAddress(on);
}

View File

@ -296,7 +296,7 @@ public class RelayedCandidateDatagramSocket
* DatagramPacket.
*/
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
* <tt>RelayedCandidateDatagramSocket</tt> to a specific
* <tt>TransportAddress</tt> via the TURN server associated with this

View File

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

View File

@ -19,132 +19,269 @@ package org.ice4j.socket;
import java.net.*;
import java.util.*;
import java.util.concurrent.*;
/**
* Implements a list of <tt>DatagramPacket</tt>s received by a
* Implements a buffer of <tt>DatagramPacket</tt>s received by a
* <tt>DatagramSocket</tt> or a <tt>Socket</tt>. The list enforces the
* <tt>SO_RCVBUF</tt> option for the associated <tt>DatagramSocket</tt> or
* <tt>Socket</tt>.
*
* @author Lyubomir Marinov
* @author Yura Yaroshevich
*/
abstract class SocketReceiveBuffer
extends LinkedList<DatagramPacket>
class SocketReceiveBuffer
{
/**
* Default size in bytes of socket receive buffer.
*/
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;
/**
* 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.
* Queue to store received datagrams.
*/
private int receiveBufferSize;
private final BlockingQueue<DatagramPacket> buffer
= new ArrayBlockingQueue<>(DATAGRAMS_BUFFER_CAPACITY);
/**
* The (total) size in bytes of this receive buffer.
* An instance of datagram size tracker to compute total number of bytes
* stored in datagrams witin {@link #buffer}.
*/
private int size;
private final DatagramSizeTracker tracker;
/**
* {@inheritDoc}
* Constructs {@link SocketReceiveBuffer} with user-provided
* @param receiveBufferSizeSupplier a function to obtain receive buffer
* size from associated socket.
*/
@Override
public boolean add(DatagramPacket p)
public SocketReceiveBuffer(Callable<Integer> receiveBufferSizeSupplier)
{
boolean added = super.add(p);
this.tracker = new DatagramSizeTracker(receiveBufferSizeSupplier);
}
/**
* Check if receive buffer is empty
* @return true if buffer is empty, false - otherwise.
*/
public boolean isEmpty()
{
return buffer.isEmpty();
}
/**
* Adds {@link DatagramPacket} at the end of the socket receive buffer.
* @param p datagram to add into receive buffer
*/
public void add(DatagramPacket p)
{
while (!buffer.offer(p))
{
// ensure buffer capacity restriction enforced
poll();
}
tracker.trackDatagramAdded(p);
while (tracker.isExceedReceiveBufferSize() && buffer.size() > 1)
{
// enforce SO_RCVBUF restriction
poll();
}
}
/**
* Polls socket receive buffer for already stored {@link DatagramPacket}
* @return the first datagram in the buffer, or {@code null} if buffer
* is empty.
*/
public DatagramPacket poll()
{
DatagramPacket p = buffer.poll();
// Keep track of the (total) size in bytes of this receive buffer in
// order to be able to enforce SO_RCVBUF.
if (added && (p != null))
// order to be able to enforce SO_RCVBUF restriction.
if (p != null)
{
int pSize = p.getLength();
tracker.trackDatagramRemoved(p);
}
if (pSize > 0)
return p;
}
/**
* Scans buffer of received {@link DatagramPacket}s and move
* datagrams which matches the {@code filter} into returned list.
* @param filter a predicate to filter {@link DatagramPacket} stored
* in receive buffer.
* @return list of datagrams matched to {@code filter}.
*/
public List<DatagramPacket> scan(DatagramPacketFilter filter)
{
List<DatagramPacket> matchedDatagrams = null;
final Iterator<DatagramPacket> it = buffer.iterator();
while (it.hasNext())
{
final DatagramPacket p = it.next();
if (filter.accept(p))
{
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)
if (matchedDatagrams == null)
{
// 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.receiveBufferSize;
matchedDatagrams = new ArrayList<>();
}
matchedDatagrams.add(p);
if ((receiveBufferSize <= 0) || (modCount % 1000 == 0))
it.remove();
tracker.trackDatagramRemoved(p);
}
}
if (matchedDatagrams != null)
{
return matchedDatagrams;
}
return Collections.emptyList();
}
/**
* A helper class to keep track of total size in bytes of all
* {@link DatagramPacket} instances stored in {@link #buffer} to
* be able to enforce SO_RCVBUF.
*/
private final class DatagramSizeTracker
{
/**
* The value of the <tt>SO_RCVBUF</tt> option for the associated
* <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
{
try
{
receiveBufferSize = getReceiveBufferSize();
}
catch (SocketException sex)
{
}
receiveBufferSize
= this.receiveBufferSizeSupplier.call();
}
catch (Exception e)
{
// 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)
{
receiveBufferSize = DEFAULT_RECEIVE_BUFFER_SIZE;
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)
{
receiveBufferSize
= DEFAULT_RECEIVE_BUFFER_SIZE;
}
}
this.receiveBufferSize = receiveBufferSize;
}
if (size > receiveBufferSize)
remove(0);
this.cachedReceiveBufferSize = receiveBufferSize;
}
}
}
return added;
}
/**
* Gets the value of the <tt>SO_RCVBUF</tt> option for the associated
* <tt>DatagramSocket</tt> or <tt>Socket</tt> which is the buffer size used
* by the platform for input on the <tt>DatagramSocket</tt> or
* <tt>Socket</tt>.
*
* @return the value of the <tt>SO_RCVBUF</tt> option for the associated
* <tt>DatagramSocket</tt> or <tt>Socket</tt>
* @throws SocketException if there is an error in the underlying protocol
*/
public abstract int getReceiveBufferSize()
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)
/**
* Updates computed value of total datagrams size in bytes
* stored in {@link #buffer} with datagram just removed from buffer.
* @param p datagram packed removed from {@link #buffer}
*/
void trackDatagramRemoved(DatagramPacket p)
{
int pSize = p.getLength();
if (pSize > 0)
final int pSize = p.getLength();
if (pSize <= 0)
{
size -= pSize;
if (size < 0)
size = 0;
return;
}
totalBuffersByteSize -= pSize;
if (totalBuffersByteSize < 0)
{
totalBuffersByteSize = 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
// or more Attributes.
if(length >= 20)
if (length >= 20)
{
// If the MAGIC COOKIE is present this is a STUN packet (RFC5389
// 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 + 6] == Message.MAGIC_COOKIE[2]
&& data[offset + 7] == Message.MAGIC_COOKIE[3])

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

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