Compare commits

..

257 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
bgrozev
7d2ad8f9a2
feat: Makes the use of a component socket optional. (#147)
* feat: Makes the use of a component socket optional.
2018-10-05 17:15:00 -05:00
bgrozev
4aef25b91f
fix: Makes sure the ReadThread continues running after an exception. (#144) 2018-07-13 14:42:04 -05:00
bgrozev
38e7b9226d
Log msg type (#138)
* ref: Minor cleanup.

* ref: Uses a constant.

* log: Logs the message type when a message encode fails.
2018-05-23 14:56:43 -05:00
Guus der Kinderen
59693a4894 AbstractUdpListener should be able to release its resources (#140)
* AbstractUdpListener should be able to release its resources

A new 'close' method has been added to AbstractUdpListener that is modeled after the 'close' implementation
of AbstractTcpListener.

This change can be used to prevent the issue described in https://github.com/jitsi/ice4j/issues/139

* Prevent concurrent modification of collection.

Part of the processing is removal from the collection that is being iterated over. To
avoid concurrent modification exceptions, a copy of the collection is made, prior to
iteration.

* Style fixes and added copyright notice.
2018-05-16 18:43:50 -04:00
Boris Grozev
200b383752 log: Adds details to an exception's message. 2018-03-23 14:53:23 -05:00
Guus der Kinderen
f2cd3891e1 Use field instead of local variable. 2017-11-16 15:32:15 -06:00
Guus der Kinderen
9810024b73 Fix negation bug. 2017-11-16 15:32:15 -06:00
Guus der Kinderen
48956f82ba Allow bind to wildcard (any) local address.
This commit allows the project to bind to any local address, by setting
a property.
2017-11-16 15:32:15 -06:00
bgrozev
a2e5ca1d4c Fixes a race condition leading to a thread stuck in receive() (#135)
* fix: Fixes a race condition leading to a thread

being stuck in AbstractUdpListener.MySocket#receive().

* minor: Braces, cleanup.
2017-11-14 12:40:17 -08:00
Guus der Kinderen
610a438dac Annotate Google SSLTCP hardcoded values.
This commit adds documentation only. It does not introduce functional changes.

The documentation was generated by crafting hex dumps from the values hardcoded
in the source code, which were fed to Wireshark (using its "import from hex dump"
option).
2017-11-13 14:59:33 -06:00
bbaldino
c26679744c Merge pull request #131 from bgrozev/revert-username-hack
Reverts feecacefc58e54e83bef527af5b4e058cdcc0403 (username attribute …
2017-08-21 10:35:37 -07:00
brian baldino
39403816f8 remove a transaction if a packet fails validation 2017-08-20 21:33:50 -05:00
Boris Grozev
4c5cc1642a Reverts feecacefc58e54e83bef527af5b4e058cdcc0403 (username attribute hack). 2017-08-18 23:19:25 -05:00
Ingo Bauersachs
9da28850f5 Fail build when version doesn't adhere to semantic versioning 2017-07-20 10:01:45 -05:00
Ingo Bauersachs
3f97648918 Switch to semantic versioning 2017-07-20 10:01:45 -05:00
Ingo Bauersachs
c52dbf7956 Add id to non-JDK8 profile to fix pom error 2017-07-20 10:01:45 -05:00
bgrozev
c2f08ceca2 Merge pull request #122 from bgrozev/multiplexing-fixes-and-features2
Multiplexing fixes and features
2017-07-19 14:29:15 -05:00
Boris Grozev
5188097479 fix: Does not close Multiplexing on Multiplexed.close()
Waits until all of the Multiplexed sockets belonging to a Multiplexing
are closed before closing the Multiplexing socket. Also introduces the
"persistent" flag of Multiplexing, which keeps it open even after all
of its Multiplexed sockets are closed.

fix: Makes MultiplexingDatagramSocket#persistent final.
2017-07-12 16:00:43 -05:00
Boris Grozev
f6e3deb9a5 feat: Adds another utility method. 2017-06-29 11:27:54 -05:00
bbaldino
c25288460d Merge pull request #120 from bgrozev/edge-workaround
fix: Uses the correct index.
2017-06-26 10:55:45 -07:00
Boris Grozev
ed26be48d7 fix: Uses the correct index. 2017-06-26 12:54:03 -05:00
bbaldino
907b36c6c0 Merge pull request #119 from bgrozev/edge-workaround
fix: Works around a bug in Edge
2017-06-23 11:03:57 -07:00
Boris Grozev
feecacefc5 fix: Works around a bug in Edge
https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/12332457/
https://github.com/jitsi/lib-jitsi-meet/issues/498
2017-06-23 12:56:54 -05:00
bgrozev
51baa62ee2 Merge pull request #115 from jitsi/fix-filedescriptor-leak
Fixes leak of file descriptors
2017-05-10 17:52:03 -05:00
Boris Grozev
b6e5d035e5 fix: Fixes a bug which prevents the socket to close.
After the delegate is closed, isClosed() would return true,
which would prevent the DatagramSocket instance (super) from
actually closing and releasing its resources.
2017-05-10 16:59:06 -05:00
damencho
e472f6ac1c Fixes leak of file descriptors by not closing DatagramSockets.
The problem was reproduced with java7 and defining multiple ipv6 fake(not-operational) addresses to one of the interfaces and running for a while.
Fixes jitsi/jitsi-meet#1390 and fixes jitsi/jicofo#167.
2017-05-10 15:06:15 -05:00
bgrozev
e099d4acbe Merge pull request #113 from imont/harvest-timeout
Introduce harvesting timeout option
2017-05-08 11:22:29 -05:00
Romanas Sonkinas
969e363bc6 Introduce harvesting timeout option 2017-04-28 17:28:44 +01:00
bgrozev
dffdf0cbc8 Merge pull request #112 from jitsi/so-rcvbuf-public
ref: Makes the single port recv buffer sysprop public.
2017-04-20 10:31:47 -05:00
George Politis
f9eded5078 ref: Makes the single port recv buffer sysprop public. 2017-04-20 10:27:39 -05:00
Дамян Минков
b3c304146b Merge pull request #97 from bgrozev/minor-changes
Minor changes: fixes typos and removes duplicated code
2017-04-11 10:58:47 -05:00
Дамян Минков
8cf47c00c2 Merge pull request #110 from bgrozev/fix-leaks
Fix leaks
2017-04-10 13:52:22 -05:00
Boris Grozev
a524e1b2c0 fix: Closes the MultiplexingDatagramSocket instances created by single-port UDP candidates. 2017-04-10 13:47:22 -05:00
Boris Grozev
5085b042bb fix: Closes the MultiplexingDatagramSocket held by a Component. 2017-04-10 13:46:48 -05:00
bbaldino
3784d5681b Merge pull request #107 from bgrozev/fix-101
Fix 101
2017-03-30 15:22:46 -07:00
bbaldino
3547d35e9b Merge pull request #108 from bgrozev/update-docs
Update docs
2017-03-30 15:19:45 -07:00
bbaldino
7f3a3806ca Merge pull request #105 from bgrozev/fix-100
fix: Removes an unused, broken and misnamed method. Fixes #100.
2017-03-30 15:17:21 -07:00
Boris Grozev
bf0892e8d2 doc: Formatting changes. 2017-03-30 17:11:54 -05:00
Boris Grozev
36553e203a doc: Adds documentation for setting the receive buffer size. 2017-03-30 17:10:23 -05:00
Boris Grozev
4847672519 ref: Removes an unused an buggy method.
port*2 can be outside the [min, max] range (if min > 0).
2017-03-29 14:21:10 -05:00
Boris Grozev
183e115cf2 fix: Fixes an incorrect port range computation (#101). 2017-03-29 14:20:56 -05:00
bbaldino
47acf238bf Merge pull request #106 from bgrozev/fix-102
fix: Fixes #102 (inexact port range validation).
2017-03-29 12:10:24 -07:00
Boris Grozev
9348af1624 fix: Fixes #102 (inexact port range validation). 2017-03-29 14:08:03 -05:00
Boris Grozev
02992ee8d1 fix: Removes an unused, broken and misnamed method. Fixes #100. 2017-03-29 14:00:42 -05:00
Boris Grozev
7a78b72d5b ref: Removes MuxServerSocketChannel#assertIsNotNull
Uses the equivalent Objects#requireNonNull instead.
2017-03-23 15:56:49 -05:00
Boris Grozev
6401fcd436 doc: Fixes typos 2017-03-22 13:56:55 -05:00
George Politis
77fe6973c4 Merge pull request #96 from bgrozev/mobility
Allows some form of mobility
2017-02-24 12:30:28 -06:00
Boris Grozev
6bfe2ac5e5 feat: Allows adding sockets to an Agent late,
after the Agent has completed/terminated.
2017-02-24 09:34:55 -06:00
Boris Grozev
0f86b8797f feat: Handles pairs discovered late,
after the Agent has completed/terminated.
2017-02-24 09:31:23 -06:00
Дамян Минков
cefd964509 Merge pull request #94 from bgrozev/fix-fd-leak
fix: Propagates close() to the underlying DatagramSocket implementation
2017-01-11 13:34:54 -06:00
Boris Grozev
7c63d5202c fix: Propagates close() to the underlying DatagramSocket implementation
fixing a leak of fd's while the the objects waiting to be finalized.
2017-01-11 12:30:33 -06:00
bbaldino
72d1b1441c Merge pull request #93 from bgrozev/fix-local-prflx-candidates
fix: Fixes a failure to inherit the base's tcpType for peer-reflexing…
2017-01-10 16:22:42 -06:00
Boris Grozev
e1338126fe fix: Fixes a failure to inherit the base's tcpType for peer-reflexing candidates. 2017-01-10 15:44:20 -06:00
bgrozev
2e4bf351fe Merge pull request #92 from jitsi/networkutils-rfc2732
Networkutils rfc2732
2017-01-10 15:40:20 -06:00
Ingo Bauersachs
203ffbd92b Add unit test for changed address parsing 2017-01-07 13:41:42 +01:00
Ingo Bauersachs
383002efe2 Handle RFC2732 IPv6 addresses ([::1] or [::1%1]) 2017-01-07 13:31:04 +01:00
bbaldino
43e6e5359d Merge pull request #90 from bgrozev/sctp-close-fix
fix: Fixes a failure to recognize consent
2016-12-21 14:59:07 -08:00
Boris Grozev
cf61003e5b fix: Fixes a failure to recognize consent
confirmation for TCP pairs.
2016-12-21 16:09:32 -06:00
bbaldino
e300997924 Merge pull request #89 from bgrozev/tcp-fallback
Tcp fallback
2016-12-15 09:26:10 -08:00
Boris Grozev
0d769bb46d fix: Makes the keep alive strategy final. 2016-12-15 11:15:31 -06:00
Boris Grozev
19e86e3bc9 Revert "fix: Only allow setting the keep-alive strategy before the Agent is started."
This reverts commit abec6b79e564961575b3372a2ead52053dd3a67e.
2016-12-15 11:07:26 -06:00
Boris Grozev
a1796c9bfb style: Whitespace and braces. 2016-12-15 10:45:43 -06:00
Boris Grozev
abec6b79e5 fix: Only allow setting the keep-alive strategy before the Agent is started. 2016-12-15 10:44:57 -06:00
Boris Grozev
fe2b1a3239 style: Remove an unused import. 2016-12-13 16:26:19 -06:00
Boris Grozev
c46c1a2613 style: Remove unused imports. 2016-12-13 15:11:30 -06:00
Boris Grozev
5f554565b1 feat: Implements different strategies for
selecting the candidate pairs to be kept alive.
2016-12-13 15:11:15 -06:00
Boris Grozev
b340fa22f0 log: Reduce logging when a TCP socket is closed
by the remote peer.
2016-12-13 15:07:52 -06:00
bgrozev
1cd1128b89 Merge pull request #88 from bgrozev/merging
Virtual socket layer
2016-12-13 11:08:29 -06:00
Boris Grozev
9adab9094f style: Fixes a typo. 2016-12-12 13:59:55 -06:00
Boris Grozev
7cac0e50a7 fix: Moves the initializedActive update to after
the actual call to initializeActive(). Synchronizes access.
2016-12-12 13:53:42 -06:00
Boris Grozev
6d6f4710e0 fix: Only initializes propertyName if needed. 2016-12-12 13:49:21 -06:00
Boris Grozev
9c8d22a5bd fix: Uses a regular HashSet. 2016-12-12 13:34:54 -06:00
Boris Grozev
d0587e99e6 doc: Make it clear that a particular property name is used. 2016-12-09 10:07:06 -06:00
Boris Grozev
cb2856a8ae log: Reduces logging. 2016-12-09 09:10:22 -06:00
Boris Grozev
75e8948f4b log: Uses the parent Agent's log level. 2016-12-09 09:01:44 -06:00
Boris Grozev
9a2fe509d4 feat: Initializes the active socket
...when ICE nominates a pair. Sets the correct target for packets sent
through MergingDatagramSocket.
2016-12-06 13:09:07 -06:00
Boris Grozev
d5410b922b feat: Adds accessors for candidatates' sockets when they have more than one. 2016-12-06 11:57:32 -06:00
Boris Grozev
b4a5e2eb83 refactor: Refactors the Component's socket API. 2016-12-01 12:01:10 -06:00
Boris Grozev
dae6d32875 cleanup: Cleaner closing of MergingDatagramSocket. 2016-11-30 15:30:42 -06:00
Boris Grozev
633f05b4e5 feat: Verifies the remove address of packets passed on to the application. 2016-11-30 15:17:33 -06:00
Boris Grozev
d0afb0a55b style: Field order, whitespace, spelling. 2016-11-30 14:00:31 -06:00
Boris Grozev
6603ac3c28 cleanup: Removes an unused and confusing method. 2016-11-30 10:44:36 -06:00
Boris Grozev
ff6eeb343e feat: Closes all socket containers when the the merging socket closes. 2016-11-29 16:38:57 -06:00
Boris Grozev
67f301eebc feat: Implements MergingDatagramSocket#close(). 2016-11-29 16:12:11 -06:00
Boris Grozev
82544254c4 feat: Adds candidates' sockets to the component's merging socket. 2016-11-29 12:54:52 -06:00
Boris Grozev
c378329b8c feat: Returns the known socket address for sockets from the single-port mode. 2016-11-29 10:53:03 -06:00
Boris Grozev
15a2df1e59 feat: Splits the API to obtain sockets for a candidate/candidate pair.
The public-facing API returns the socket instance for the associated
Component, while the internal API (getCandidateIceSocket) returns
the internal socket instance for the candidate.
2016-11-28 16:11:24 -06:00
Boris Grozev
91858ba6a3 feat: Removes the VIRTUAL_SOCKET_LAYER flag, enabling it
by default.
2016-11-28 14:05:40 -06:00
Boris Grozev
3ddb19ff2c fix: Updates getActiveSocket. 2016-11-28 13:34:49 -06:00
Boris Grozev
eaceca57ac feat: Allows to add sockets to a completed agent. 2016-11-28 11:23:37 -06:00
Boris Grozev
f19dbc1984 doc: Notes that the VSL is experimental. 2016-11-21 17:01:03 -06:00
Boris Grozev
f08feea707 feat: Uses the last active socket to send data through. 2016-11-21 17:01:03 -06:00
Boris Grozev
25b0cfdc30 feat: Adds socket from the single-port and TCP harvesters to the Component. 2016-11-21 17:01:03 -06:00
Boris Grozev
2718728e92 feat: Adds an ENABLE_VIRTUAL_SOCKET_LAYER property
and a MergingDatagramSocket instance for each Component.
2016-11-21 17:01:03 -06:00
Boris Grozev
44ca871888 style: Makes the logger field final. 2016-11-21 16:59:47 -06:00
Boris Grozev
aafe003974 docs: Adds a comment. 2016-11-21 16:59:47 -06:00
Boris Grozev
12a4ef19a0 feat: Adds MergingDatagramSocket. 2016-11-21 16:59:47 -06:00
George Politis
f9f2c0f3e9 Merge pull request #87 from bgrozev/harvesting
Harvesting
2016-11-21 16:48:03 -06:00
Boris Grozev
c30ebeca53 mvn: Updates the ice4j version to 2.0. 2016-11-21 13:08:32 -06:00
Boris Grozev
c82717e8e7 docs: Adds documentation. 2016-11-17 11:40:24 -06:00
Boris Grozev
425cf9bb0d logs: Logs more information. 2016-11-16 17:52:00 -06:00
Boris Grozev
d538ca30c0 feat: Adds a toString to MappingCandidateHarvester. 2016-11-16 16:36:49 -06:00
Boris Grozev
6bc252fdd4 style: Adds @Override annotations. 2016-11-16 16:36:46 -06:00
Boris Grozev
c47ecee639 feat: Appends known mappings to the TCP harvester. 2016-11-16 16:36:42 -06:00
Boris Grozev
a8729dda22 feat: Append mapping harvesters in the Agent. 2016-11-16 16:36:38 -06:00
Boris Grozev
1d13bc7175 feat: Adds MappingCandidateHarvesters.
Moves the HarvesterConfiguration class from jitsi-videobridge
to ice4j (now named MappingCandidateHarvesters), and re-implements
the STUN candidate harvester's discovery in a way which allows
us to detect failures.
2016-11-16 16:35:08 -06:00
Boris Grozev
c919de1b3a refactor: Moves the getAllowedInetAddresses method to HostCandidateHarvester. 2016-11-16 16:34:49 -06:00
Boris Grozev
256176dde6 feat: Exposes a method to retrieve a list of allowed local InetAddress-es. 2016-11-16 16:34:43 -06:00
Boris Grozev
a08c77a3c1 fix: Fixes a potential synchronization issue. 2016-11-16 16:34:38 -06:00
Boris Grozev
99600368f6 style: Simplifies code. 2016-11-16 16:34:33 -06:00
Boris Grozev
3e01bff25e style: Checks the log level before logging a FINE message. 2016-11-16 16:34:08 -06:00
Boris Grozev
a7ff3b8dca style: Adds @Override annotations. 2016-11-16 16:34:03 -06:00
Boris Grozev
452af370a5 logs: Logs a warning
if a mapping harvester is not configured at harvest time.
2016-11-16 16:33:58 -06:00
Emil Ivov
dc4e05e5d9 Merge pull request #81 from bgrozev/refactor
Refactor
2016-10-25 12:00:09 -05:00
Emil Ivov
7acb9fd5cc Update AbstractCandidateHarvester.java 2016-10-25 11:59:42 -05:00
Boris Grozev
b5d3bb2ddc Merge branch 'master' into refactor 2016-10-12 18:20:06 +03:00
Emil Ivov
2b8b025fbe Merge pull request #85 from bgrozev/configureble-so-rcvbuf
feat: Makes the single-port harvester's sockets' receive buffer sizes
2016-10-05 04:48:24 -05:00
Boris Grozev
84ca00a325 feat: Makes the single-port harvester's sockets' receive buffer sizes
configurable.
2016-10-05 11:28:21 +03:00
bgrozev
38cfe178c6 Merge pull request #83 from matteocampana/logging_improvement
Do not use String.format and construct the string only if logger…
2016-10-03 14:44:20 +03:00
Matteo Campana
350fb833ac Do not use String.format and construct the string only if logger FINEST is enabled. 2016-09-27 16:54:05 +02:00
Boris Grozev
3aaee5acde refactor: Expose a method. 2016-09-09 07:26:55 -05:00
Boris Grozev
4216982445 refactor: Extracts AbstractTcpListener from TcpHarvester. 2016-09-08 21:26:52 -05:00
Boris Grozev
35e603d346 refactor: Extracts an abstract base class from SinglePortUdpHarvester. 2016-09-08 13:20:31 -05:00
Boris Grozev
0abaef19e8 refactor: Splits CandidateHarvester into an interface
and an abstract implementation.
2016-09-08 12:09:34 -05:00
Дамян Минков
94b3cb2661 Merge pull request #80 from bgrozev/ufrag-prefix
feat: Adds an optional prefix to the local ufrag.
2016-09-06 16:04:59 -05:00
Boris Grozev
1dc41efb1e feat: Adds an optional prefix to the local ufrag. 2016-09-06 14:18:19 -05:00
Lyubomir Marinov
bed87bcbd3 Merge branch 'javadoc' 2016-08-26 13:39:21 -05:00
damencho
4ba7247480 Adds javadoc target. 2016-08-26 12:50:52 -05:00
Ingo Bauersachs
4e8f3474e7 Merge pull request #73 from ubivent-seuffert/pmaster
Handover IOException to higher level
2016-08-18 06:35:23 +02:00
George Politis
d6c4c62689 Merge pull request #77 from bgrozev/statistics
Exposes RateStatistics#getAccumulatedCount
2016-08-17 13:30:12 -05:00
Boris Grozev
a21088dc7a Exposes RateStatistics#getAccumulatedCount and
synchronizes access to some of the methods.
2016-08-11 16:37:36 -05:00
bgrozev
5f2261af43 Merge pull request #76 from jitsi/consent_freshness_config
Make "consent freshness" intervals configurable
2016-07-21 22:20:36 +02:00
paweldomas
58c319981c Make "consent freshness" intervals configurable 2016-07-21 15:01:30 -05:00
Ingo Bauersachs
26aa42cc37 Merge pull request #75 from bgrozev/improve-logging
Improve logging
2016-07-06 21:19:29 +02:00
Boris Grozev
6fe376a56d Lowers the log level of a message. 2016-07-06 12:45:27 -05:00
Boris Grozev
2af7613491 Lowers the log level of a message. 2016-07-06 12:04:03 -05:00
Boris Grozev
27f6f62c27 Include the local username fragment in various log messages. 2016-07-05 16:10:43 -05:00
Boris Grozev
dc29172a2c Introduces a separate log level for each Agent instance.
Makes instances belonging to an Agent use the log level from the Agent
instance.

The motivation is to disable logging output from Agents created
for the purposes of jitsi-videobridge health checks (but not other
Agents).
2016-07-05 15:31:50 -05:00
ubivent-seuffert
ded13aa230 Merge branch 'master' of https://github.com/jitsi/ice4j into pmaster 2016-06-01 16:15:55 +02:00
ubivent-seuffert
aa22012c5d throw needed exception 2016-06-01 16:15:34 +02:00
George Politis
4f946f38a4 Merge pull request #72 from bgrozev/fix-failiure-to-close
Fixes a failure to close a Socket instance.
2016-05-20 13:13:50 -05:00
Boris Grozev
568ace382b Fixes a failure to close a Socket instance.
Makes sure that Socket instances which are discarded because
they are only added after the corresponding ICE Agent has
moved away from the WAITING or RUNNING state are closed. This
prevents a file descriptor leak, since Socket instances which are
not closed (even after they are garbage collected) leave behind
sockets in state CLOSE_WAIT.
2016-05-20 11:38:22 -05:00
Boris Grozev
e4f5534b3d Minor fixes to the documentation. 2016-05-20 11:35:00 -05:00
champtar
7312077fd9 Ensure tieBreaker is positive (#71)
Math.abs(Integer.MIN_VALUE) == Integer.MIN_VALUE
http://findbugs.sourceforge.net/bugDescriptions.html#RV_ABSOLUTE_VALUE_OF_RANDOM_INT

Signed-off-by: Etienne CHAMPETIER <champetier.etienne@gmail.com>
2016-05-09 15:12:19 +02:00
champtar
164ca04236 Drop MessageQueue, use a LinkedBlockingQueue instead (#63)
LinkedBlockingQueue are available since java 5

This is a bit more efficient as we were calling notifyAll()
instead of notify() in add(), thus waking up too much

This also remove 'logger.finest("Adding raw message to queue.");'

Signed-off-by: Etienne CHAMPETIER <champetier.etienne@gmail.com>
2016-05-06 20:03:52 +02:00
champtar
a363a973eb Use an ArrayList instead of reimplementing it (#62)
This should not change performance but is way more readable

Signed-off-by: Etienne CHAMPETIER <champetier.etienne@gmail.com>
2016-05-06 19:54:50 +02:00
Ingo Bauersachs
a51af3f90f Merge pull request #68 from champtar/ChannelData_padding
ChannelData: fix padding
2016-05-06 19:42:04 +02:00
Etienne CHAMPETIER
b76f9abfc9 ChannelData: fix decode()
I haven't found any user of this method.

This method was only working if offset == 0
and binMessage isn't a padded message.

arrayLen is useless as we have msgLen, so remove it,
and introduce a deprecated decode() to keep same api

Signed-off-by: Etienne CHAMPETIER <champetier.etienne@gmail.com>
2016-05-03 11:25:03 +02:00
Etienne CHAMPETIER
84bd07c665 Use new ChannelData.encode(pad)
Padding is mandatory for TCP and TLS
See https://tools.ietf.org/html/rfc5766#section-11.5

Signed-off-by: Etienne CHAMPETIER <champetier.etienne@gmail.com>
2016-05-03 11:25:03 +02:00
Etienne CHAMPETIER
d33d8b87e4 ChannelData: rework padding
getDataLength() was returning data length without
padding, so keep current behavior and update the javadoc.
(spotted with findbugs because length in
getDataLength was a dead store)

Introduce padTo4() to round up a number to the next
multiple of 4.

Deprecate encode() and introduce encode(boolean pad)
so we can let the caller decide if he wants padding
(mandatory when using tcp or tls)

See https://tools.ietf.org/html/rfc5766#section-11.5

Signed-off-by: Etienne CHAMPETIER <champetier.etienne@gmail.com>
2016-05-03 11:25:03 +02:00
Emil Ivov
b877467bc4 Merge pull request #58 from jitsi/remove-ant
Remove obsolete Ant-build and the embedded libraries
2016-05-02 17:44:41 -05:00
bgrozev
249ebb913a Merge pull request #65 from jitsi/fix-javadoc
Fix Javadoc formatting and missing parameters
2016-04-25 13:26:57 -05:00
Ingo Bauersachs
de1260610d Merge pull request #69 from champtar/nullequals
Remove unneeded null checks & fix MagicCookieAttribute equals
2016-04-20 22:15:05 +02:00
champtar
caa313739a Remove uneeded boxing/unboxing (#70)
http://findbugs.sourceforge.net/bugDescriptions.html#DM_BOXED_PRIMITIVE_FOR_PARSING

Signed-off-by: Etienne CHAMPETIER <champetier.etienne@gmail.com>
2016-04-20 22:12:53 +02:00
champtar
08f6ee8c64 org.ice4j.attribute: fix bytes conversion bugs (#67)
http://findbugs.sourceforge.net/bugDescriptions.html#BIT_IOR_OF_SIGNED_BYTE
http://findbugs.sourceforge.net/bugDescriptions.html#BIT_ADD_OF_SIGNED_BYTE

Signed-off-by: Etienne CHAMPETIER <champetier.etienne@gmail.com>
2016-04-20 22:02:15 +02:00
champtar
ce4126701e NetworkUtils: fix IndexOutOfBoundsException (#66)
http://findbugs.sourceforge.net/bugDescriptions.html#RANGE_ARRAY_LENGTH

Signed-off-by: Etienne CHAMPETIER <champetier.etienne@gmail.com>
2016-04-20 21:54:04 +02:00
Etienne CHAMPETIER
9155707329 Remove unneeded null checks in equals
instanceof already check for null

Signed-off-by: Etienne CHAMPETIER <champetier.etienne@gmail.com>
2016-04-19 10:41:20 +02:00
Etienne CHAMPETIER
af8c32ecd7 Fix MagicCookieAttribute equals
this looks like a copy/paste error

Signed-off-by: Etienne CHAMPETIER <champetier.etienne@gmail.com>
2016-04-19 10:41:18 +02:00
Ingo Bauersachs
7e152e0367 Add run targets that used to existed in Ant
mvn test-compile
mvn exec:java -Prun-<whatever>
2016-04-18 22:18:59 +02:00
Ingo Bauersachs
71b2874d46 Remove obsolete Ant-build and the embedded libraries 2016-04-18 22:14:02 +02:00
Ingo Bauersachs
02e1217144 Fix Javadoc formatting and missing parameters
This now satisfies Java 8's Javadoc compiler with it's default options.
2016-04-16 00:11:00 +02:00
lyubomir
8536ff347b Merge pull request #61 from jitsi/maven-release
Maven release 1.0
2016-04-04 17:10:53 -05:00
Ingo Bauersachs
0f0fb9d06f [maven-release-plugin] prepare for next development iteration 2016-04-04 23:40:28 +02:00
209 changed files with 11660 additions and 10342 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

306
build.xml
View File

@ -1,306 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project name="ice4j" basedir="." default="rebuild">
<property name="dest" value="classes"/>
<property name="dest-test" value="classes-test"/>
<property name="lib" value="lib"/>
<property name="JUnit.home" value="${lib}"/>
<property name="src" value="src/main/java"/>
<property name="src2" value="src/test/java"/>
<property name="junit.reports" value="junit-reports"/>
<property name="junit.html.reports" value="${junit.reports}/html"/>
<property name="ice4j.jar" value="ice4j.jar"/>
<property name="doc" value="doc"/>
<property name="java.doc" value="${doc}/api"/>
<path id="project.class.path">
<pathelement location="${dest}"/>
<pathelement location="${lib}/jain-sdp.jar"/>
<pathelement location="${lib}/weupnp-0.1.2-SNAPSHOT.jar"/>
</path>
<path id="test.class.path">
<path refid="project.class.path" />
<pathelement location="${dest-test}"/>
<pathelement location="${JUnit.home}/junit.jar"/>
</path>
<!--Patternset to exclude files from the output directory:-->
<patternset id="dest.exclude">
<exclude name="package cache/"/>
<exclude name="dependency cache/"/>
<exclude name="test/"/>
</patternset>
<!-- ANT TARGETS -->
<!-- compiles all classes -->
<target name="compile" depends="init">
<condition property="compile.javac.exclude.name" value="**/jdk8/**">
<not>
<matches string="${java.runtime.version}" pattern="^1\.8(\..*)?$"/>
</not>
</condition>
<javac classpathref="project.class.path"
debug="true"
deprecation="true"
destdir="${dest}"
includeantruntime="false"
nowarn="false"
optimize="true"
source="1.6"
target="1.6">
<compilerarg value="-Xlint"/>
<src path="${src}"/>
<exclude name="${compile.javac.exclude.name}"/>
</javac>
</target>
<!-- compiles all tests -->
<target name="compile-tests" depends="init">
<javac classpathref="test.class.path"
debug="true"
deprecation="true"
destdir="${dest-test}"
nowarn="false"
optimize="true"
source="1.6"
target="1.6">
<src path="${src2}"/>
<compilerarg value="-Xlint"/>
</javac>
</target>
<!-- copies ressource files if any to the classes directory -->
<target name="resource">
<copy todir="${dest}">
<fileset dir="${src}">
<include name="**/*.jpe"/>
<include name="**/*.jpeg"/>
<include name="**/*.rmf"/>
<include name="**/*.wav"/>
<include name="**/*.mid"/>
<include name="**/*.midi"/>
<include name="**/*.au"/>
<include name="**/*.gif"/>
<include name="**/*.png"/>
<include name="**/*.jpg"/>
<include name="**/*.aiff"/>
<include name="**/*.properties"/>
</fileset>
<fileset dir="${src2}">
<include name="**/*.jpe"/>
<include name="**/*.jpeg"/>
<include name="**/*.rmf"/>
<include name="**/*.wav"/>
<include name="**/*.mid"/>
<include name="**/*.midi"/>
<include name="**/*.au"/>
<include name="**/*.gif"/>
<include name="**/*.png"/>
<include name="**/*.jpg"/>
<include name="**/*.aiff"/>
<include name="**/*.properties"/>
</fileset>
</copy>
</target>
<!-- creates the javadocs -->
<target name="javadoc">
<javadoc author="true" destdir="${java.doc}" package="true">
<fileset dir="${src}"/>
</javadoc>
</target>
<!-- delete the contents of the classes directory-->
<target name="clean">
<delete failonerror="false" includeemptydirs="true">
<fileset dir="${dest}"/>
<fileset dir="${dest-test}"/>
<fileset dir="${junit.reports}"/>
<fileset dir="doc" />
</delete>
<delete file="${ice4j.jar}" failonerror="true" quiet="false"/>
</target>
<!-- make everything -->
<target name="make" depends="compile,compile-tests,resource,jar"/>
<!-- clean and make everything -->
<target name="rebuild" depends="clean,make" />
<!-- make javadoc -->
<target name="doc" depends="make,javadoc" />
<!-- create needed subdirs-->
<target name="init">
<mkdir dir="${dest}"/>
<mkdir dir="${dest-test}"/>
<mkdir dir="${junit.reports}"/>
<mkdir dir="${junit.html.reports}"/>
</target>
<!-- create jar file-->
<target name="jar" depends="compile">
<jar compress="true" destfile="${ice4j.jar}">
<fileset dir="${dest}">
<patternset refid="dest.exclude"/>
<include name="**/*.*"/>
</fileset>
</jar>
</target>
<!-- We use this target from within the test target in order to generate
a human readable test report. We do not directly use the htmlreport
target because we need to include xalan in the classpath before we
do.-->
<target name="htmlreport">
<junitreport todir="${junit.reports}">
<fileset dir="${junit.reports}">
<include name="TEST-*.xml"/>
</fileset>
<report format="frames" todir="${junit.html.reports}"/>
</junitreport>
</target>
<!-- Run the tests-->
<target name="test" depends="compile-tests">
<junit haltonfailure="true" fork="true" forkmode="once">
<formatter type="xml"/>
<formatter type="brief" usefile="false"/>
<test name="org.ice4j.StunTestSuite" todir="${junit.reports}"/>
<test name="org.ice4j.PseudoTcpTestSuite" todir="${junit.reports}"/>
<classpath refid="test.class.path"/>
</junit>
<!-- Generate the html report.
Run it quietly (i.e. redirect the output) because we don't won't to
see its "Build Successful" output line as users might confuse it
for a general build success while this might not be the case.-->
<echo message="Generating HTML test reports ..."/>
<java fork="true"
classname="org.apache.tools.ant.launch.Launcher"
classpath="${java.class.path}:${lib}/xalan-2.6.0.jar"
failonerror="true"
output="${junit.html.reports}/output.txt">
<arg value="htmlreport"/>
</java>
</target>
<!-- runs our sample application -->
<target name="run-sample">
<java fork="true"
classname="test.Ice"
classpathref="test.class.path">
<!-- Tell java.util.logging about our logging preferences -->
<sysproperty key="java.util.logging.config.file"
value="lib/logging.properties"/>
</java>
</target>
<!-- Run pseudotcp sample application -->
<target name="run-pseudotcp" depends="compile">
<java fork="true"
classname="test.IcePseudoTcp"
classpathref="test.class.path">
<!-- Tell java.util.logging about our logging preferences -->
<sysproperty key="java.util.logging.config.file"
value="lib/logging.properties"/>
</java>
</target>
<!-- Debug pseudotcp example on port 5005 -->
<target name="debug-pseudotcp" depends="compile">
<java fork="true"
classname="test.IcePseudoTcp"
classpathref="test.class.path">
<!-- Tell java.util.logging about our logging preferences -->
<sysproperty key="java.util.logging.config.file"
value="lib/logging.properties"/>
<jvmarg value="-Xdebug" />
<jvmarg value="-Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=5005" />
</java>
</target>
<!-- Debug pseudotcp example with netbeans -->
<target name="nb-debug-pseudotcp" depends="compile">
<nbjpdastart addressproperty="jpda.address" name="ice4j" transport="dt_socket">
<classpath refid="test.class.path"/>
</nbjpdastart>
<java classname="test.IcePseudoTcp" fork="true">
<classpath refid="test.class.path"/>
<jvmarg value="-Xdebug"/>
<jvmarg value="-Xnoagent"/>
<jvmarg value="-Djava.compiler=none"/>
<jvmarg value="-Xrunjdwp:transport=dt_socket,address=${jpda.address}"/>
<!-- Tell java.util.logging about our logging preferences -->
<sysproperty key="java.util.logging.config.file"
value="lib/logging.properties"/>
</java>
</target>
<!-- runs our sample distributed application -->
<target name="run-dist">
<java fork="true"
classname="test.IceDistributed"
classpathref="test.class.path">
<!-- Tell java.util.logging about our logging preferences -->
<sysproperty key="java.util.logging.config.file"
value="lib/logging.properties"/>
</java>
</target>
<!-- runs our sample Trickle ICE application -->
<target name="run-trickle">
<java fork="true"
classname="test.TrickleIce"
classpathref="test.class.path">
<!-- Tell java.util.logging about our logging preferences -->
<sysproperty key="java.util.logging.config.file"
value="lib/logging.properties"/>
</java>
</target>
<!-- runs our sample lite application -->
<target name="run-lite">
<java fork="true"
classname="test.IceLite"
classpathref="test.class.path">
<!-- Tell java.util.logging about our logging preferences -->
<sysproperty key="java.util.logging.config.file"
value="lib/logging.properties"/>
</java>
</target>
<!-- runs our sample NAT mapping application -->
<target name="run-map">
<java fork="true"
classname="test.MappingTest"
classpathref="test.class.path">
<!-- Tell java.util.logging about our logging preferences -->
<sysproperty key="java.util.logging.config.file"
value="lib/logging.properties"/>
</java>
</target>
<!-- runs our sample aws application -->
<target name="run-aws">
<java fork="true"
classname="test.AwsTest"
classpathref="test.class.path">
<!-- Tell java.util.logging about our logging preferences -->
<sysproperty key="java.util.logging.config.file"
value="lib/logging.properties"/>
</java>
</target>
<!-- Cruise Control Target-->
<target name="cc-buildloop" depends="rebuild,test"/>
</project>

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>

87
doc/configuration.md Normal file
View File

@ -0,0 +1,87 @@
# General
This file describes some of the java properties which ```ice4j``` uses
to configure itself.
## Interfaces and IP addresses
### ```org.ice4j.ice.harvest.ALLOWED_INTERFACES```
Default: all interfaces are allowed.
This property can be used to specify a ";"-separated list of interfaces which are
allowed to be used for candidate allocations. If not specified, all interfaces are
considered allowed, unless they are explicitly blocked (see below).
### ```org.ice4j.ice.harvest.BLOCKED_INTERFACES```
Default: no interfaces are blocked.
This property can be used to specify a ";"-separated list of interfaces which are
not allowed to be used for candidate allocations.
### ```org.ice4j.ice.harvest.ALLOWED_ADDRESSES```
Default: all addresses are allowed.
This property can be used to specify a ";"-separated list of IP addresses which
are allowed to be used for candidate allocations. If not specified, all addresses
are considered allowed, unless they are explicitly blocked (see below).
### ```org.ice4j.ice.harvest.BLOCKED_ADDRESSES```
Default: no addresses are blocked.
This property can be used to specify a ";"-separated list of IP addresses which
are not allowed to be used for candidate allocations.
### ```org.ice4j.ipv6.DISABLED```
Type: boolean
Default: false
This property can be used to disable binding on IPv6 addresses.
## Mapping harvesters
Ice4j uses the concept of "mapping harvesters" to handle known IP address
mappings. A set of mapping harvesters is configured once when the library
initializes, and each of them contains a pair of IP addresses (local and public).
When an ICE Agent gathers candidates, it uses the set of mapping harvesters
to obtain ```srflx``` candidates without the use to e.g. a STUN server dynamically.
Mapping harvesters preserve the port number of the original candidate, so they should
only be used when port numbers are preserved.
Ice4j implements three types of mapping harvesters: one with a pre-configured pair of
addresses, one two which discover addresses dynamically using the AWS API and STUN.
### ```org.ice4j.ice.harvest.NAT_HARVESTER_LOCAL_ADDRESS```
### ```org.ice4j.ice.harvest.NAT_HARVESTER_PUBLIC_ADDRESS```
Default: none
Configures the addresses of the pre-configured mapping harvester.
### ```org.ice4j.ice.harvest.DISABLE_AWS_HARVESTER```
Default: false
Explicitly disables the AWS mapping harvester. By default the harvester
is enabled if ice4j detects that it is running in the AWS network.
### ```org.ice4j.ice.harvest.FORCE_AWS_HARVESTER```
Default: false
Force the use of the AWS mapping harvester, even if ice4j did not detect
that it is running in the AWS network.
### ```org.ice4j.ice.harvest.STUN_MAPPING_HARVESTER_ADDRESSES```
Default: none
A comma-separated list of STUN server addresses to use for mapping harvesters.
Each STUN server address is an ip_address:port pair.
Example: ```stun1.example.com:12345,stun2.example.com:23456```
## Single port UDP harvester
### ```org.ice4j.ice.harvest.AbstractUdpHarvester.SO_RCVBUF```
Configures the receive buffer size for the single port UDP harvester
(or other AbstractUdpListener implementations). If this is not set
the system default value will be used (the ```net.core.rmem_default```
sysctl parameter on linux). Note that the system maximum value may need to
be increased (```net.core.rmem_max``` on linux).

Binary file not shown.

Binary file not shown.

Binary file not shown.

514
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>1.0</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>ice4j-1.0</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,39 +121,422 @@
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-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>
<includes>
<include>**/*TestSuite.*</include>
</includes>
<jvmTarget>11</jvmTarget>
<args>
<arg>-Xallow-result-return-type</arg>
</args>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.10.1</version>
<executions>
<!-- Replacing default-compile as it is treated specially by maven -->
<execution>
<id>default-compile</id>
<phase>none</phase>
</execution>
<!-- Replacing default-testCompile as it is treated specially by maven -->
<execution>
<id>default-testCompile</id>
<phase>none</phase>
</execution>
<execution>
<id>java-compile</id>
<phase>compile</phase>
<goals>
<goal>compile</goal>
</goals>
</execution>
<execution>
<id>java-test-compile</id>
<phase>test-compile</phase>
<goals>
<goal>testCompile</goal>
</goals>
</execution>
</executions>
<configuration>
<release>11</release>
<compilerArgs>
<arg>-Xlint:all</arg>
</compilerArgs>
</configuration>
</plugin>
<plugin>
<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>**/*</includes>
<systemPropertyVariables>
<java.util.logging.config.file>${project.build.testSourceDirectory}/../resources/logging.properties</java.util.logging.config.file>
</systemPropertyVariables>
</configuration>
</plugin>
<plugin>
<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>
<serverId>ossrh</serverId>
<nexusUrl>https://oss.sonatype.org/</nexusUrl>
<autoReleaseAfterClose>true</autoReleaseAfterClose>
</configuration>
</plugin>
</plugins>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>3.0.0</version>
<executions>
<execution>
<goals>
<goal>java</goal>
</goals>
</execution>
</executions>
<configuration>
<classpathScope>test</classpathScope>
<systemProperties>
<systemProperty>
<key>java.util.logging.config.file</key>
<value>logging.properties</value>
</systemProperty>
</systemProperties>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
<profiles>
<profile>
<id>coverage</id>
<build>
<plugins>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.8.8</version>
<executions>
<execution>
<goals>
<goal>prepare-agent</goal>
</goals>
</execution>
<execution>
<id>report</id>
<phase>test</phase>
<goals>
<goal>report</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
<profile>
<id>run-sample</id>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<configuration>
<mainClass>test.Ice</mainClass>
</configuration>
</plugin>
</plugins>
</build>
</profile>
<profile>
<id>run-pseudotcp</id>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<configuration>
<mainClass>test.IcePseudoTcp</mainClass>
</configuration>
</plugin>
</plugins>
</build>
</profile>
<profile>
<id>run-dist</id>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<configuration>
<mainClass>test.IceDistributed</mainClass>
</configuration>
</plugin>
</plugins>
</build>
</profile>
<profile>
<id>run-trickle</id>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<configuration>
<mainClass>test.TrickleIce</mainClass>
</configuration>
</plugin>
</plugins>
</build>
</profile>
<profile>
<id>run-lite</id>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<configuration>
<mainClass>test.IceLite</mainClass>
</configuration>
</plugin>
</plugins>
</build>
</profile>
<profile>
<id>run-map</id>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<configuration>
<mainClass>test.MappingTest</mainClass>
</configuration>
</plugin>
</plugins>
</build>
</profile>
<profile>
<id>run-aws</id>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<configuration>
<mainClass>test.AwsTest</mainClass>
</configuration>
</plugin>
</plugins>
</build>
</profile>
<profile>
<id>release</id>
<activation>
<jdk>(,1.8)</jdk>
<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-compiler-plugin</artifactId>
<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>
<excludes>
<exclude>**/jdk8/**</exclude>
</excludes>
<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

@ -106,10 +106,13 @@ public class ChannelDataMessageEvent
{
return this.remoteAddress;
}
/**
* Gets the <tt>TransportAddress</tt> which is local address on which this
* event was received.
*
* @return the <tt>TransportAddress</tt> which is local address on which
* this event was received.
*/
public TransportAddress getLocalAddress()
{

View File

@ -17,6 +17,8 @@
*/
package org.ice4j;
import org.ice4j.ice.*;
import java.util.*;
import java.util.logging.*;
@ -48,6 +50,15 @@ public class StackProperties
*/
public static final int BIND_RETRIES_DEFAULT_VALUE = 50;
/**
* The name of the property that tells if we should bind to the
* wildcard address instead of the (usually more specific) harvest candidate
* addresses.
*
* The wildcard is a special local IP address. It usually means "any".
*/
public static final String BIND_WILDCARD = "org.ice4j.BIND_WILDCARD";
/**
* The number of milliseconds a client transaction should wait before
* retransmitting, after it has sent a request for the first time.
@ -75,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.
@ -116,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.
@ -142,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.
@ -171,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.
@ -188,13 +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";
/**
* 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;
@ -216,7 +216,7 @@ public class TransportAddress
* address if both the InetAddresses (or hostnames if it is unresolved),
* port numbers, and <tt>Transport</tt>s are equal.
*
* If both addresses are unresolved, then the hostname, the port & and
* If both addresses are unresolved, then the hostname, the port and
* the <tt>Transport</tt> are compared.
*
* @param obj the object to compare against.
@ -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

@ -24,34 +24,32 @@ import org.ice4j.*;
/**
* This class is used to represent Stun attributes that contain an address. Such
* attributes are:
*<p>
* MAPPED-ADDRESS <br/>
* RESPONSE-ADDRESS <br/>
* SOURCE-ADDRESS <br/>
* CHANGED-ADDRESS <br/>
* REFLECTED-FROM <br/>
* ALTERNATE-SERVER <br/>
* XOR-PEER-ADDRESS <br/>
* XOR-RELAYED-ADDRESS <br/>
*</p>
*<ul>
* <li>MAPPED-ADDRESS
* <li>RESPONSE-ADDRESS
* <li>SOURCE-ADDRESS
* <li>CHANGED-ADDRESS
* <li>REFLECTED-FROM
* <li>ALTERNATE-SERVER
* <li>XOR-PEER-ADDRESS
* <li>XOR-RELAYED-ADDRESS
*</ul>
*<p>
* The different attributes are distinguished by the attributeType of
* org.ice4j.attribute.Attribute.
*</p>
* {@link Attribute}.
*<p>
* Address attributes indicate the mapped IP address and
* port. They consist of an eight bit address family, and a sixteen bit
* port, followed by a fixed length value representing the IP address.
*<code>
* 0 1 2 3 <br/>
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 <br/>
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ <br/>
* |x x x x x x x x| Family | Port | <br/>
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ <br/>
* | Address | <br/>
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ <br/>
* <br/>
* </p>
*<pre>
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* |x x x x x x x x| Family | Port |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Address |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* </pre>
* <p>
* The port is a network byte ordered representation of the mapped port.
* The address family is always 0x01, corresponding to IPv4. The first
@ -161,8 +159,7 @@ abstract class AddressAttribute extends Attribute
*/
public boolean equals(Object obj)
{
if (! (obj instanceof AddressAttribute)
|| obj == null)
if (! (obj instanceof AddressAttribute))
return false;
if (obj == this)
@ -179,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;
@ -224,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);
}
@ -310,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

@ -22,53 +22,54 @@ import org.ice4j.*;
/**
* After the header are 0 or more attributes. Each attribute is TLV
* encoded, with a 16 bit type, 16 bit length, and variable value:
*<pre>
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Type | Length |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Value ....
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*
* 0 1 2 3 <br/>
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 <br/>
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ <br/>
* | Type | Length | <br/>
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ <br/>
* | Value .... <br/>
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ <br/>
*<br/>
* The following types are defined:<br/>
*<br/>
* STUN attributes:<br/>
* 0x0001: MAPPED-ADDRESS <br/>
* 0x0002: RESPONSE-ADDRESS <br/>
* 0x0003: CHANGE-REQUEST <br/>
* 0x0004: SOURCE-ADDRESS <br/>
* 0x0005: CHANGED-ADDRESS <br/>
* 0x0006: USERNAME <br/>
* 0x0007: PASSWORD <br/>
* 0x0008: MESSAGE-INTEGRITY <br/>
* 0x0009: ERROR-CODE <br/>
* 0x000a: UNKNOWN-ATTRIBUTES <br/>
* 0x000b: REFLECTED-FROM <br/>
* 0x0014: REALM <br/>
* 0x0015: NONCE <br/>
* 0x0020: XOR-MAPPED-ADDRESS <br/>
* 0x8022: SOFTWARE <br/>
* 0x8023: ALTERNATE-SERVER <br/>
* 0x8028: FINGERPRINT <br/>
* <br/>
* TURN attributes:<br/>
* 0x000C: CHANNEL-NUMBER <br/>
* 0x000D: LIFETIME <br/>
* 0x0012: XOR-PEER-ADDRESS <br/>
* 0x0013: DATA <br/>
* 0x0016: XOR-RELAYED-ADDRESS <br/>
* 0x0018: EVEN-PORT <br/>
* 0x0019: REQUESTED-TRANSPORT <br/>
* 0x001A: DONT-FRAGMENT <br/>
* 0x0022: RESERVATION-TOKEN <br/>
* The following types are defined:
*
* ICE attributes:<br/>
* 0x0024: PRIORITY <br/>
* 0x0025: USE-CANDIDATE <br/>
* 0x8029: ICE-CONTROLLED <br/>
* 0x802A: ICE-CONTROLLING <br/>
* STUN attributes:
* 0x0001: MAPPED-ADDRESS
* 0x0002: RESPONSE-ADDRESS
* 0x0003: CHANGE-REQUEST
* 0x0004: SOURCE-ADDRESS
* 0x0005: CHANGED-ADDRESS
* 0x0006: USERNAME
* 0x0007: PASSWORD
* 0x0008: MESSAGE-INTEGRITY
* 0x0009: ERROR-CODE
* 0x000a: UNKNOWN-ATTRIBUTES
* 0x000b: REFLECTED-FROM
* 0x0014: REALM
* 0x0015: NONCE
* 0x0020: XOR-MAPPED-ADDRESS
* 0x8022: SOFTWARE
* 0x8023: ALTERNATE-SERVER
* 0x8028: FINGERPRINT
*
* TURN attributes:
* 0x000C: CHANNEL-NUMBER
* 0x000D: LIFETIME
* 0x0012: XOR-PEER-ADDRESS
* 0x0013: DATA
* 0x0016: XOR-RELAYED-ADDRESS
* 0x0018: EVEN-PORT
* 0x0019: REQUESTED-TRANSPORT
* 0x001A: DONT-FRAGMENT
* 0x0022: RESERVATION-TOKEN
*
* ICE attributes:
* 0x0024: PRIORITY
* 0x0025: USE-CANDIDATE
* 0x8029: ICE-CONTROLLED
* 0x802A: ICE-CONTROLLING
* </pre>
*
* @author Emil Ivov
* @author Sebastien Vincent
* @author Namal Senarathne

View File

@ -43,23 +43,23 @@ 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.");
}
//Discover attribute type
char attributeType = (char)((bytes[offset] << 8) | bytes[offset + 1]);
int len1 = bytes[offset + 2] & 0xff;
int len2 = bytes[offset + 3] & 0xff;
char attributeLength = (char)((len1 << 8) | len2);
char attributeType = (char)
(((bytes[offset] & 0xFF) << 8) | (bytes[offset + 1] & 0xFF));
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

@ -544,7 +544,8 @@ public class AttributeFactory
*
* @param priority the priority value
* @return the created PriorityAttribute
* @throws IllegalArgumentException if priority < 0 or priority > (2^31 - 1)
* @throws IllegalArgumentException if priority &lt; 0 or priority &gt;
* (2^31 - 1)
*/
public static PriorityAttribute createPriorityAttribute(long priority)
throws IllegalArgumentException
@ -623,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;
}
@ -643,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

@ -24,13 +24,13 @@ import org.ice4j.*;
* attribute is used by the client to request that the server use a different
* address and/or port when sending the response. The attribute is 32 bits
* long, although only two bits (A and B) are used:
*
* 0 1 2 3 <br/>
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 <br/>
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ <br/>
* |0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 A B 0| <br/>
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ <br/>
*
* <pre>
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* |0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 A B 0|
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* </pre>
* The meaning of the flags is:
*
* A: This is the "change IP" flag. If true, it requests the server
@ -100,8 +100,7 @@ public class ChangeRequestAttribute
*/
public boolean equals(Object obj)
{
if (! (obj instanceof ChangeRequestAttribute)
|| obj == null)
if (! (obj instanceof ChangeRequestAttribute))
return false;
if (obj == this)

View File

@ -60,8 +60,7 @@ public class ChannelNumberAttribute extends Attribute
@Override
public boolean equals(Object obj)
{
if (! (obj instanceof ChannelNumberAttribute)
|| obj == null)
if (! (obj instanceof ChannelNumberAttribute))
return false;
if (obj == this)
@ -138,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");
}
@ -169,11 +168,11 @@ public class ChannelNumberAttribute extends Attribute
/**
* Determines if the channelNo is in valid range.
* @param channelNo the channelNo to validate.
* @return true if channnelNo is >= 0x4000.
* @return true if channnelNo is &gt;= 0x4000.
*/
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

@ -52,7 +52,7 @@ public class DataAttribute
private final boolean padding;
/**
* Constructor.
* Creates a new instance of this class with padding enabled.
*/
protected DataAttribute()
{
@ -60,7 +60,9 @@ public class DataAttribute
}
/**
* Constructor.
* Creates a new instance of this class.
* @param padding true to pad the data if the length is not on a word
* boundary.
*/
protected DataAttribute(boolean padding)
{
@ -170,8 +172,7 @@ public class DataAttribute
public boolean equals(Object obj)
{
if (! (obj instanceof DataAttribute)
|| obj == null)
if (! (obj instanceof DataAttribute))
return false;
if (obj == this)

View File

@ -54,11 +54,8 @@ public class DontFragmentAttribute extends Attribute
*/
public boolean equals(Object obj)
{
if (! (obj instanceof DontFragmentAttribute)
|| obj == null)
{
if (! (obj instanceof DontFragmentAttribute))
return false;
}
return true;
}
@ -115,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;
@ -488,8 +488,7 @@ public class ErrorCodeAttribute extends Attribute
@Override
public boolean equals(Object obj)
{
if (! (obj instanceof ErrorCodeAttribute)
|| obj == null)
if (! (obj instanceof ErrorCodeAttribute))
return false;
if (obj == this)

View File

@ -24,8 +24,8 @@ import org.ice4j.*;
* server to allocate an even port and optionally allocate
* the next higher port number.
*
* There are one flag supported : <br/>
* R : ask to reserve a second port.<br/>
* There is one flag supported: <br>
* R : ask to reserve a second port.
*
* @author Sebastien Vincent
*/
@ -62,8 +62,7 @@ public class EvenPortAttribute extends Attribute
*/
public boolean equals(Object obj)
{
if (! (obj instanceof EvenPortAttribute)
|| obj == null)
if (! (obj instanceof EvenPortAttribute))
return false;
if (obj == this)
@ -133,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

@ -122,7 +122,7 @@ public class FingerprintAttribute
*/
public boolean equals(Object obj)
{
if (! (obj instanceof FingerprintAttribute) || obj == null)
if (! (obj instanceof FingerprintAttribute))
return false;
if (obj == this)
@ -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,15 +125,14 @@ public abstract class IceControlAttribute
*/
public boolean equals(Object obj)
{
if(!(obj instanceof IceControlAttribute)
|| obj == null)
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

@ -61,8 +61,7 @@ public class LifetimeAttribute
@Override
public boolean equals(Object obj)
{
if (! (obj instanceof LifetimeAttribute)
|| obj == null)
if (! (obj instanceof LifetimeAttribute))
return false;
if (obj == this)
@ -139,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

@ -83,8 +83,7 @@ public class MagicCookieAttribute
*/
public boolean equals(Object obj)
{
if (! (obj instanceof LifetimeAttribute)
|| obj == null)
if (! (obj instanceof MagicCookieAttribute))
return false;
if (obj == this)
@ -139,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

@ -18,6 +18,7 @@
package org.ice4j.attribute;
import java.util.*;
import java.util.logging.*;
import javax.crypto.*;
import javax.crypto.spec.*;
@ -37,7 +38,6 @@ import org.ice4j.stack.*;
* The key for the HMAC depends on whether long-term or short-term
* credentials are in use. For long-term credentials, the key is 16
* bytes:
* <p>
* <pre>
* key = MD5(username ":" realm ":" SASLprep(password))
* </pre>
@ -54,7 +54,6 @@ import org.ice4j.stack.*;
* 0x8493fbc53ba582fb4c044c456bdc40eb.
* <p>
* For short-term credentials:
* <p>
* <pre>
* key = SASLprep(password)
* </pre>
@ -88,6 +87,13 @@ public class MessageIntegrityAttribute
extends Attribute
implements ContentDependentAttribute
{
/**
* The <tt>Logger</tt> used by the <tt>Message</tt> class and its instances
* for logging output.
*/
private static final Logger logger
= Logger.getLogger(MessageIntegrityAttribute.class.getName());
/**
* Attribute name.
*/
@ -282,26 +288,32 @@ public class MessageIntegrityAttribute
binValue[3] = (byte)(getDataLength() & 0x00FF);
byte[] key = null;
char msgType = (char)((content[0] << 8) + content[1]);
char msgType =
(char) (((content[0] & 0xFF) << 8) | (content[1] & 0xFF));
if(Message.isRequestType(msgType))
if (Message.isRequestType(msgType))
{
/* attribute part of a request, use the remote key */
key = stunStack.getCredentialsManager().getRemoteKey(username,
media);
key
= stunStack.getCredentialsManager()
.getRemoteKey(username, media);
}
else if(Message.isSuccessResponseType(msgType) ||
Message.isErrorResponseType(msgType))
else if (Message.isResponseType(msgType))
{
/* attribute part of a response, use the local key */
key = stunStack.getCredentialsManager().getLocalKey(username);
}
else // msgType is Indication
{
logger.warning("Can not encode a message of type Indication.");
}
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;
}
@ -335,7 +347,7 @@ public class MessageIntegrityAttribute
*/
public boolean equals(Object obj)
{
if (! (obj instanceof MessageIntegrityAttribute) || obj == null)
if (! (obj instanceof MessageIntegrityAttribute))
return false;
if (obj == this)

View File

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

View File

@ -118,8 +118,7 @@ public class PriorityAttribute
*/
public boolean equals(Object obj)
{
if (! (obj instanceof PriorityAttribute)
|| obj == null)
if (! (obj instanceof PriorityAttribute))
return false;
if (obj == this)
@ -175,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

@ -141,7 +141,7 @@ public class RealmAttribute extends Attribute
*/
public boolean equals(Object obj)
{
if (! (obj instanceof RealmAttribute) || obj == null)
if (! (obj instanceof RealmAttribute))
return false;
if (obj == this)

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

@ -70,8 +70,7 @@ public class RequestedTransportAttribute extends Attribute
@Override
public boolean equals(Object obj)
{
if (! (obj instanceof RequestedTransportAttribute)
|| obj == null)
if (! (obj instanceof RequestedTransportAttribute))
return false;
if (obj == this)
@ -148,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);
@ -216,8 +216,7 @@ public class ReservationTokenAttribute
@Override
public boolean equals(Object obj)
{
if (! (obj instanceof ReservationTokenAttribute)
|| obj == null)
if (! (obj instanceof ReservationTokenAttribute))
return false;
if (obj == this)

View File

@ -151,8 +151,7 @@ public class SoftwareAttribute
*/
public boolean equals(Object obj)
{
if (! (obj instanceof SoftwareAttribute)
|| obj == null)
if (! (obj instanceof SoftwareAttribute))
return false;
if (obj == this)

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);
@ -191,8 +191,7 @@ public class UnknownAttributesAttribute extends Attribute
*/
public boolean equals(Object obj)
{
if (! (obj instanceof UnknownAttributesAttribute)
|| obj == null)
if (! (obj instanceof UnknownAttributesAttribute))
return false;
if (obj == this)
@ -222,15 +221,15 @@ 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++] << 8) |
(attributeValue[offset++]) );
char attributeID = (char) (((attributeValue[offset++] & 0xFF) << 8)
| (attributeValue[offset++] & 0xFF));
addAttributeID(attributeID);
}
}

View File

@ -89,15 +89,14 @@ public class UseCandidateAttribute
*/
public boolean equals(Object obj)
{
if(!(obj instanceof UseCandidateAttribute)
|| obj == null)
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

@ -56,6 +56,7 @@ public class UsernameAttribute extends Attribute
* offset is equal to the index of the first byte after length)
* @param length the length of the binary array.
*/
@Override
void decodeAttributeBody(byte[] attributeValue, char offset, char length)
{
username = new byte[length];
@ -147,7 +148,7 @@ public class UsernameAttribute extends Attribute
*/
public boolean equals(Object obj)
{
if (! (obj instanceof UsernameAttribute) || obj == null)
if (! (obj instanceof UsernameAttribute))
return false;
if (obj == this)

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;

View File

@ -111,8 +111,7 @@ public class XorOnlyAttribute
public boolean equals(Object obj)
{
if (! (obj instanceof XorOnlyAttribute)
|| obj == null)
if (! (obj instanceof XorOnlyAttribute))
return false;
if (obj == this)

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

@ -111,8 +111,8 @@ public class CandidatePair
/**
* The {@link TransactionID} of the client transaction for a connectivity
* check over this pair in case it is in the {@link CandidatePairState#
* IN_PROGRESS} state.
* check over this pair in case it is in the
* {@link CandidatePairState#IN_PROGRESS} state.
*/
private TransactionID connCheckTranID = null;
@ -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;
}
@ -290,13 +290,13 @@ public class CandidatePair
this.state = newState;
if(newState == CandidatePairState.IN_PROGRESS)
if (newState == CandidatePairState.IN_PROGRESS)
{
if (tranID == null)
{
throw new IllegalArgumentException(
"Putting a pair into the In-Progress state MUST be"
+ " accomapnied with the TransactionID of the"
+ " accompanied with the TransactionID of the"
+ " connectivity check.");
}
}
@ -367,7 +367,7 @@ public class CandidatePair
* agent. Let D be the priority for the candidate provided by the
* controlled agent. The priority for a pair is computed as:
* <p>
* <i>pair priority = 2^32*MIN(G,D) + 2*MAX(G,D) + (G>D?1:0)</i>
* <i>pair priority = 2^32*MIN(G,D) + 2*MAX(G,D) + (G&gt;D?1:0)</i>
* <p>
* This formula ensures a unique priority for each pair. Once the priority
* is assigned, the agent sorts the candidate pairs in decreasing order of
@ -443,7 +443,7 @@ public class CandidatePair
@Override
public boolean equals(Object obj)
{
if ((obj == null) || !(obj instanceof CandidatePair))
if (! (obj instanceof CandidatePair))
return false;
CandidatePair candidatePair = (CandidatePair) obj;
@ -723,6 +723,7 @@ public class CandidatePair
* @return the UDP <tt>DatagramSocket</tt> (if any) for this
* <tt>CandidatePair</tt>.
*/
@Deprecated
public DatagramSocket getDatagramSocket()
{
IceSocketWrapper wrapper = getIceSocketWrapper();
@ -733,18 +734,28 @@ public class CandidatePair
* Returns the TCP <tt>Socket</tt> (if any) for this <tt>CandidatePair</tt>.
* @return the TCP <tt>Socket</tt> (if any) for this <tt>CandidatePair</tt>.
*/
@Deprecated
public Socket getSocket()
{
IceSocketWrapper wrapper = getIceSocketWrapper();
return wrapper == null ? null : wrapper.getTCPSocket();
return null;
}
/**
* Returns the <tt>IceSocketWrapper</tt> for this <tt>CandidatePair</tt>.
* @return the <tt>IceSocketWrapper</tt> for this <tt>CandidatePair</tt>.
*/
@Deprecated
public IceSocketWrapper getIceSocketWrapper()
{
IceSocketWrapper componentSocket
= getParentComponent().getSocketWrapper();
// If the merging socket is used, all candidate pairs just refer to the
// component.
if (componentSocket != null)
{
return getParentComponent().getSocketWrapper();
}
LocalCandidate localCandidate = getLocalCandidate();
if (localCandidate == null)
{
@ -753,17 +764,21 @@ public class CandidatePair
LocalCandidate base = localCandidate.getBase();
if (base != null)
{
localCandidate = base;
}
RemoteCandidate remoteCandidate = getRemoteCandidate();
if (remoteCandidate != null)
{
SocketAddress remoteAddress
= remoteCandidate.getTransportAddress();
= remoteCandidate.getTransportAddress();
if (remoteAddress != null)
return localCandidate.getIceSocketWrapper(remoteAddress);
{
return localCandidate.getCandidateIceSocketWrapper(remoteAddress);
}
}
return localCandidate.getIceSocketWrapper();
return localCandidate.getCandidateIceSocketWrapper();
}
}

View File

@ -79,11 +79,12 @@ class CandidatePrioritizer
* <code>comp1.equals(comp2)</code> implies that
* <tt>sgn(comp1.compare(o1, o2))==sgn(comp2.compare(o1, o2))</tt> for
* every object reference <tt>o1</tt> and <tt>o2</tt>.<p>
* <p/>
* <p>
* Note that it is <i>always</i> safe <i>not</i> to override
* <tt>Object.equals(Object)</tt>. However, overriding this method may,
* in some cases, improve performance by allowing programs to determine
* that two distinct Comparators impose the same order.
* </p>
*
* @param obj the reference object with which to compare.
*

View File

@ -74,6 +74,8 @@ public enum CandidateTcpType
* Parses the string <tt>candidateTcpTypeName</tt> and return the
* corresponding <tt>CandidateTcpType</tt> instance.
*
* @param candidateTcpTypeName the string to parse
* @return candidateTcpTypeName as an Enum
* @throws IllegalArgumentException in case <tt>candidateTcpTypeName</tt> is
* not a valid or currently supported candidate TCP type.
*/

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,9 +17,10 @@
*/
package org.ice4j.ice;
import org.jitsi.utils.logging2.*;
import java.beans.*;
import java.util.*;
import java.util.logging.*;
/**
* A check list is a list of <tt>CandidatePair</tt>s with a state (i.e. a
@ -34,17 +35,23 @@ import java.util.logging.*;
public class CheckList
extends Vector<CandidatePair>
{
/**
* The logger.
*/
private static final Logger logger =
Logger.getLogger(CheckList.class.getName());
/**
* A dummy serialization id.
*/
private static final long serialVersionUID = 1L;
/**
* The name of the {@link PropertyChangeEvent} that we use to deliver
* changes on the state of this check list.
*/
public static final String PROPERTY_CHECK_LIST_STATE = "CheckListState";
/**
* The name of the {@link PropertyChangeEvent} that we use to deliver
* changes on the end of checks of this check list.
*/
public static final String PROPERTY_CHECK_LIST_CHECKS = "CheckListChecks";
/**
* The state of this check list.
*/
@ -78,16 +85,9 @@ public class CheckList
= new LinkedList<>();
/**
* The name of the {@link PropertyChangeEvent} that we use to deliver
* changes on the state of this check list.
* The {@link Logger} used by {@link CheckList} instances.
*/
public static final String PROPERTY_CHECK_LIST_STATE = "CheckListState";
/**
* The name of the {@link PropertyChangeEvent} that we use to deliver
* changes on the end of checks of this check list.
*/
public static final String PROPERTY_CHECK_LIST_CHECKS = "CheckListChecks";
private Logger logger;
/**
* Creates a check list with the specified name.
@ -98,6 +98,7 @@ public class CheckList
protected CheckList(IceMediaStream parentStream)
{
this.parentStream = parentStream;
logger = parentStream.getLogger().createChildLogger(this.getClass().getName());
}
/**
@ -134,7 +135,7 @@ public class CheckList
{
synchronized(triggeredCheckQueue)
{
if(!triggeredCheckQueue.contains(pair))
if (!triggeredCheckQueue.contains(pair))
{
triggeredCheckQueue.add(pair);
pair.setStateWaiting();
@ -153,7 +154,7 @@ public class CheckList
{
synchronized(triggeredCheckQueue)
{
if(triggeredCheckQueue.size() > 0)
if (triggeredCheckQueue.size() > 0)
return triggeredCheckQueue.remove(0);
}
return null;
@ -181,7 +182,7 @@ public class CheckList
{
if (pair.getState() == CandidatePairState.WAITING)
{
if(highestPriorityPair == null
if (highestPriorityPair == null
|| pair.getPriority() > highestPriorityPair.getPriority())
{
highestPriorityPair = pair;
@ -189,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;
@ -208,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
@ -299,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);
@ -316,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);
@ -326,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.
@ -348,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();
}
@ -378,7 +398,7 @@ public class CheckList
{
Component cmp = nominatedPair.getParentComponent();
if(cmp.getSelectedPair() != null)
if (cmp.getSelectedPair() != null)
{
return;
}
@ -390,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
@ -407,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
@ -473,7 +493,7 @@ public class CheckList
{
synchronized(stateListeners)
{
if(!stateListeners.contains(l))
if (!stateListeners.contains(l))
this.stateListeners.add(l);
}
}
@ -512,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);
}
@ -528,7 +548,7 @@ public class CheckList
{
synchronized(checkListeners)
{
if(!checkListeners.contains(l))
if (!checkListeners.contains(l))
{
checkListeners.add(l);
}
@ -544,7 +564,7 @@ public class CheckList
{
synchronized(checkListeners)
{
if(checkListeners.contains(l))
if (checkListeners.contains(l))
{
checkListeners.remove(l);
}
@ -567,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

@ -20,17 +20,17 @@ package org.ice4j.ice;
/**
* Everty <tt>CheckList</tt> is associated with a state, which captures the
* state of ICE checks for that media stream. There are three states:
* <p/>
* <br>
* Running: In this state, ICE checks are still in progress for this
* media stream.
* <p/>
* <br>
* Completed: In this state, ICE checks have produced nominated pairs
* for each component of the media stream. Consequently, ICE has succeeded and
* media can be sent.
* <p/>
* <br>
* Failed: In this state, the ICE checks have not completed successfully for
* this media stream.
* <p/>
* <br>
* When a check list is first constructed as the consequence of an offer/answer
* exchange, it is placed in the Running state.
*

View File

@ -17,10 +17,14 @@
*/
package org.ice4j.ice;
import java.beans.*;
import java.net.*;
import java.util.*;
import java.util.logging.*;
import java.util.concurrent.*;
import org.ice4j.*;
import org.ice4j.socket.*;
import org.jitsi.utils.logging2.*;
/**
* A component is a piece of a media stream requiring a single transport
@ -35,13 +39,8 @@ import org.ice4j.*;
* @author Boris Grozev
*/
public class Component
implements PropertyChangeListener
{
/**
* Our class logger.
*/
private static final Logger logger
= Logger.getLogger(Component.class.getName());
/**
* The component ID to use with RTP streams.
*/
@ -112,6 +111,48 @@ public class Component
*/
private Candidate<?> defaultRemoteCandidate = null;
/**
* The {@link Logger} used by {@link Component} instances.
*/
private final Logger logger;
/**
* The {@link ComponentSocket} instance which, if enabled, will serve as the
* single socket instance for this {@link Component}, merging received
* packets from all of its candidates.
*/
private final ComponentSocket componentSocket;
/**
* The public view of {@link #componentSocket}, wrapped in a
* {@link MultiplexingDatagramSocket} for the convenience of users of the
* library.
* This is the instance which should be used by applications for
* reading/writing application data.
*/
private final MultiplexingDatagramSocket socket;
/**
* A wrapper around {@link #socket}, kept only to help preserve the old
* API (see {@link LocalCandidate#getIceSocketWrapper()} and
* {@link CandidatePair#getIceSocketWrapper()})
*/
@Deprecated
private final IceSocketWrapper socketWrapper;
/**
* The {@link KeepAliveStrategy} used by this component to select which
* pairs are to be kept alive.
*/
private final KeepAliveStrategy keepAliveStrategy;
/**
* The set of pairs which this component wants to keep alive.
*/
private final Set<CandidatePair> keepAlivePairs
= Collections.newSetFromMap(
new ConcurrentHashMap<CandidatePair, Boolean>());
/**
* Creates a new <tt>Component</tt> with the specified <tt>componentID</tt>
* as a child of the specified <tt>IceMediaStream</tt>.
@ -119,13 +160,62 @@ public class Component
* @param componentID the id of this component.
* @param mediaStream the {@link IceMediaStream} instance that would be the
* parent of this component.
* @deprecated
*/
protected Component(int componentID,
IceMediaStream mediaStream)
protected Component(int componentID,
IceMediaStream mediaStream,
KeepAliveStrategy keepAliveStrategy,
Logger parentLogger)
{
this(componentID, mediaStream, keepAliveStrategy, true, parentLogger);
}
/**
* Creates a new <tt>Component</tt> with the specified <tt>componentID</tt>
* as a child of the specified <tt>IceMediaStream</tt>.
*
* @param componentID the id of this component.
* @param mediaStream the {@link IceMediaStream} instance that would be the
* parent of this component.
* @param useComponentSocket whether the component socket should be used.
*/
protected Component(int componentID,
IceMediaStream mediaStream,
KeepAliveStrategy keepAliveStrategy,
boolean useComponentSocket,
Logger parentLogger)
{
// the max value for componentID is 256
this.componentID = componentID;
this.parentStream = mediaStream;
this.keepAliveStrategy
= Objects.requireNonNull(keepAliveStrategy, "keepAliveStrategy");
this.logger = parentLogger.createChildLogger(
this.getClass().getName(),
Collections.singletonMap("componentId", Integer.toString(componentID))
);
if (useComponentSocket)
{
try
{
componentSocket = new ComponentSocket(this, logger);
socket = new MultiplexingDatagramSocket(componentSocket);
socketWrapper = new IceUdpSocketWrapper(socket);
}
catch (SocketException se)
{
throw new RuntimeException(se);
}
}
else
{
componentSocket = null;
socket = null;
socketWrapper = null;
}
mediaStream.addPairChangeListener(this);
}
/**
@ -199,7 +289,7 @@ public class Component
synchronized(localCandidates)
{
int count = 0;
for(Candidate<?> cand : localCandidates)
for (Candidate<?> cand : localCandidates)
{
if ((cand.getType() == CandidateType.HOST_CANDIDATE)
&& !cand.isVirtual())
@ -294,7 +384,7 @@ public class Component
synchronized(remoteUpdateCandidates)
{
if(remoteUpdateCandidates.size() == 0)
if (remoteUpdateCandidates.size() == 0)
return;
newRemoteCandidates = new LinkedList<>(remoteUpdateCandidates);
@ -303,9 +393,9 @@ public class Component
// remove UPnP base from local candidate
LocalCandidate upnpBase = null;
for(LocalCandidate lc : localCnds)
for (LocalCandidate lc : localCnds)
{
if(lc instanceof UPNPCandidate)
if (lc instanceof UPNPCandidate)
{
upnpBase = lc.getBase();
}
@ -313,26 +403,26 @@ public class Component
checkList = new Vector<>();
for(LocalCandidate localCnd : localCnds)
for (LocalCandidate localCnd : localCnds)
{
if(localCnd == upnpBase)
if (localCnd == upnpBase)
continue;
//pair each of the new remote candidates with each of our locals
for(RemoteCandidate remoteCnd : remoteUpdateCandidates)
for (RemoteCandidate remoteCnd : remoteUpdateCandidates)
{
if(localCnd.canReach(remoteCnd)
if (localCnd.canReach(remoteCnd)
&& remoteCnd.getTransportAddress().getPort() != 0)
{
// A single LocalCandidate might be/become connected
// to more more than one remote address, and that's ok
// (that is, we need to form pairs with them all).
/*
if(localCnd.getTransport() == Transport.TCP &&
if (localCnd.getTransport() == Transport.TCP &&
localCnd.getIceSocketWrapper().getTCPSocket().
isConnected())
{
if(!localCnd.getIceSocketWrapper().getTCPSocket().
if (!localCnd.getIceSocketWrapper().getTCPSocket().
getRemoteSocketAddress().equals(
remoteCnd.getTransportAddress()))
{
@ -345,7 +435,6 @@ public class Component
= getParentStream()
.getParentAgent()
.createCandidatePair(localCnd, remoteCnd);
logger.info("new Pair added: " + pair.toShortString());
checkList.add(pair);
}
}
@ -362,7 +451,7 @@ public class Component
Collections.sort(checkList, CandidatePair.comparator);
parentStream.pruneCheckList(checkList);
if(parentStream.getCheckList().getState().equals(
if (parentStream.getCheckList().getState().equals(
CheckListState.RUNNING))
{
//add the updated CandidatePair list to the currently running
@ -370,9 +459,29 @@ public class Component
CheckList streamCheckList = parentStream.getCheckList();
synchronized(streamCheckList)
{
for(CandidatePair pair : checkList)
for (CandidatePair pair : checkList)
{
streamCheckList.add(pair);
/* Check whether the pair is already in the check list.
* (This can happen for pairs with remote peer-reflexive candidates,
* since those candidates aren't added to the candidate list even
* though the pair is added to the check list).
*/
CandidatePair existingPair
= streamCheckList.findPairMatching(pair.getLocalCandidate(), pair.getRemoteCandidate());
if (existingPair != null)
{
logger.info("existing Pair updated: " +
existingPair.toShortString() +
" to " + pair.toShortString() + ".");
existingPair.setRemoteCandidate(pair.getRemoteCandidate());
existingPair.computePriority();
}
else
{
streamCheckList.add(pair);
logger.info("new Pair added: " + pair.toShortString()
+ ".");
}
}
}
}
@ -462,7 +571,7 @@ public class Component
//local candidates
int localCandidatesCount = getLocalCandidateCount();
if(localCandidatesCount > 0)
if (localCandidatesCount > 0)
{
buff.append("\n")
.append(localCandidatesCount)
@ -485,7 +594,7 @@ public class Component
//remote candidates
int remoteCandidatesCount = getRemoteCandidateCount();
if(remoteCandidatesCount > 0)
if (remoteCandidatesCount > 0)
{
buff.append("\n")
.append(remoteCandidatesCount)
@ -594,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++;
@ -765,6 +870,17 @@ public class Component
localCandidateIter.remove();
}
}
getParentStream().removePairStateChangeListener(this);
keepAlivePairs.clear();
if (componentSocket != null)
{
componentSocket.close();
}
if (socket != null)
{
socket.close();
}
}
/**
@ -788,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);
}
}
@ -810,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;
@ -832,10 +980,12 @@ public class Component
*/
public RemoteCandidate findRemoteCandidate(TransportAddress remoteAddress)
{
for(RemoteCandidate remoteCnd : remoteCandidates)
for (RemoteCandidate remoteCnd : remoteCandidates)
{
if(remoteCnd.getTransportAddress().equals(remoteAddress))
if (remoteCnd.getTransportAddress().equals(remoteAddress))
{
return remoteCnd;
}
}
return null;
@ -849,6 +999,12 @@ public class Component
*/
protected void setSelectedPair(CandidatePair pair)
{
if (keepAliveStrategy == KeepAliveStrategy.SELECTED_ONLY)
{
keepAlivePairs.clear();
}
keepAlivePairs.add(pair);
this.selectedPair = pair;
}
@ -876,11 +1032,17 @@ public class Component
public String getName()
{
if (componentID == RTP)
{
return "RTP";
else if(componentID == RTCP)
}
else if (componentID == RTCP)
{
return "RTCP";
}
else
{
return Integer.toString(componentID);
}
}
/**
@ -892,9 +1054,129 @@ 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);
return
new Component(
componentID,
mediaStream,
KeepAliveStrategy.SELECTED_ONLY,
AgentConfig.config.getUseComponentSocket(),
parentLogger
);
}
/**
* @return the single socket for this {@link Component} which should be
* used for reading and writing data, if the component socket is enabled
* and {@code null} if it is not enabled.
* </p>
* This is for ice4j internal use only! For reading/writing application
* data, use {@link #getSocket()}.
*/
public ComponentSocket getComponentSocket()
{
return componentSocket;
}
/**
* @return the socket for this {@link Component}, which should be used for
* reading/writing application data. If the component socket is not enabled,
* this returns {@code null} and users of the library should use the socket
* instance from the desired candidate pair instead.
*/
public MultiplexingDatagramSocket getSocket()
{
return socket;
}
/**
* @return an {@link IceSocketWrapper} instance wrapping the socket for this
* candidate (see {@link #getSocket()}).
* @deprecated Use {@link #getSocket()} directly. This is only introduced
* to ease the transition of applications which are already written to use
* a {@link IceSocketWrapper} instance.
*/
public IceSocketWrapper getSocketWrapper()
{
return socketWrapper;
}
/**
* @return the set of candidate pairs which are to be kept alive.
*/
Set<CandidatePair> getKeepAlivePairs()
{
return keepAlivePairs;
}
/**
* {@inheritDoc}
* </p>
* Handles events coming from candidate pairs.
*/
@Override
public void propertyChange(PropertyChangeEvent event)
{
String propertyName = event.getPropertyName();
if (!(event.getSource() instanceof CandidatePair))
{
return;
}
CandidatePair pair = (CandidatePair) event.getSource();
if (!equals(pair.getParentComponent()))
{
// Events are fired by the IceMediaStream, which might have
// multiple components. Make sure that we only handle events for
// this component.
return;
}
boolean addToKeepAlive = false;
// We handle this case in setSelectedPair
if (keepAliveStrategy == KeepAliveStrategy.SELECTED_ONLY)
return;
if (IceMediaStream.PROPERTY_PAIR_STATE_CHANGED.equals(propertyName))
{
CandidatePairState newState
= (CandidatePairState) event.getNewValue();
if (CandidatePairState.SUCCEEDED.equals(newState))
{
if (keepAliveStrategy == KeepAliveStrategy.ALL_SUCCEEDED)
{
addToKeepAlive = true;
}
else if (keepAliveStrategy == KeepAliveStrategy.SELECTED_AND_TCP)
{
Transport transport
= pair.getLocalCandidate().getTransport();
addToKeepAlive = transport == Transport.TCP
|| transport == Transport.SSLTCP;
// Pairs with a remote TCP port 9 cannot be checked.
// Instead, the corresponding pair with the peer reflexive
// candidate needs to be checked. However, we observe
// such pairs transitioning into the SUCCEEDED state.
// Ignore them.
addToKeepAlive
&= pair.getRemoteCandidate()
.getTransportAddress().getPort() != 9;
}
}
}
if (addToKeepAlive && !keepAlivePairs.contains(pair))
{
keepAlivePairs.add(pair);
}
}
public Logger getLogger()
{
return logger;
}
}

View File

@ -0,0 +1,202 @@
/*
* ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
*
* Copyright @ 2015-2016 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;
import org.ice4j.*;
import org.ice4j.socket.*;
import java.beans.*;
import java.net.*;
import java.util.*;
import org.ice4j.util.*; //Disambiguation
/**
* Extends {@link MergingDatagramSocket} with functionality specific to
* an ICE {@link Component}.
*/
public class ComponentSocket
extends MergingDatagramSocket
implements PropertyChangeListener
{
/**
* Controls access to {@link #authorizedAddresses}.
*/
private final Object authorizedAddressesSyncRoot = new Object();
/**
* The set of remote addresses, which this socket is allowed to receive
* from. These should be the addresses which we have confirmed (e.g. by
* having received a STUN message with correct authentication fields).
*/
private Set<SocketAddress> authorizedAddresses = new HashSet<>();
/**
* The owning {@link Component}.
*/
private Component component;
/**
* Whether we have invoked {@link #initializeActive}.
*/
private boolean initializedActive = false;
/**
* Used to synchronize access to {@link #initializedActive}.
*/
private final Object initializedActiveSyncRoot = new Object();
/**
* Initializes a new {@link MergingDatagramSocket} instance.
* @throws SocketException
*/
ComponentSocket(Component component, org.jitsi.utils.logging2.Logger parentLogger)
throws SocketException
{
super(parentLogger);
this.component = component;
component.getParentStream().addPairChangeListener(this);
}
/**
* {@inheritDoc}
* </p>
* Verifies that the source of the packet is an authorized remote address.
*/
protected boolean accept(DatagramPacket p)
{
return authorizedAddresses.contains(p.getSocketAddress());
}
/**
* Adds a specific address to the list of authorized remote addresses.
* @param address the address to add.
*/
private void addAuthorizedAddress(SocketAddress address)
{
synchronized (authorizedAddressesSyncRoot)
{
if (authorizedAddresses.contains(address))
{
return;
}
logger.info("Adding allowed address: " + address);
Set<SocketAddress> newSet = new HashSet<>();
newSet.addAll(authorizedAddresses);
newSet.add(address);
authorizedAddresses = newSet;
}
}
/**
* {@inheritDoc}
* </p>
* Handles property change events coming from ICE pairs.
* @param event
*/
@Override
public void propertyChange(PropertyChangeEvent event)
{
if (!(event.getSource() instanceof CandidatePair))
{
return;
}
CandidatePair pair = (CandidatePair) event.getSource();
if (!pair.getParentComponent().equals(component))
{
// Events are fired by the IceMediaStream, which might have
// multiple components. Make sure that we only handle events for
// our own component.
return;
}
String propertyName = event.getPropertyName();
if (IceMediaStream.PROPERTY_PAIR_STATE_CHANGED.equals(propertyName))
{
CandidatePairState newState
= (CandidatePairState) event.getNewValue();
if (CandidatePairState.SUCCEEDED.equals(newState))
{
addAuthorizedAddress(
pair.getRemoteCandidate().getTransportAddress());
}
}
else if (IceMediaStream.PROPERTY_PAIR_NOMINATED.equals(propertyName))
{
synchronized (initializedActiveSyncRoot)
{
if (initializedActive)
{
return;
}
// Find the remote address and the correct socket to be used by
// the pair.
LocalCandidate localCandidate = pair.getLocalCandidate();
LocalCandidate base = localCandidate.getBase();
if (base != null)
{
localCandidate = base;
}
TransportAddress remoteAddress = null;
RemoteCandidate remoteCandidate = pair.getRemoteCandidate();
if (remoteCandidate != null)
{
remoteAddress = remoteCandidate.getTransportAddress();
}
// The local candidate may have more than one associated socket.
// Make sure we get the one for the remote address that we are
// going to use.
IceSocketWrapper socketWrapper
= localCandidate
.getCandidateIceSocketWrapper(remoteAddress);
initializeActive(socketWrapper, remoteAddress);
initializedActive = true;
}
}
}
/**
* {@inheritDoc}
*/
@Override
public void close()
{
try
{
super.close();
}
finally
{
Component component = this.component;
if (component != null)
{
component.getParentStream().removePairStateChangeListener(this);
this.component = null;
}
}
}
}

View File

@ -18,14 +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.*;
import org.jitsi.utils.logging2.Logger;
/**
* The class that will be generating our outgoing connectivity checks and that
@ -37,18 +40,21 @@ import org.ice4j.stack.*;
class ConnectivityCheckClient
implements ResponseCollector
{
/**
* The <tt>Logger</tt> used by the <tt>ConnectivityCheckClient</tt>
* class and its instances for logging output.
*/
private static final Logger logger
= 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.
*/
@ -57,29 +63,52 @@ 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.
*/
private boolean alive = false;
/**
* The {@link Logger} used by {@link ConnectivityCheckClient} instances.
*/
private Logger logger;
/**
* Creates a new <tt>ConnectivityCheckClient</tt> setting
* <tt>parentAgent</tt> as the agent that will be used for retrieving
* 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;
this.scheduledExecutorService = scheduledExecutorService;
this.executorService = executorService;
logger = parentAgent.getLogger().createChildLogger(this.getClass().getName());
stunStack = this.parentAgent.getStunStack();
}
@ -115,7 +144,7 @@ class ConnectivityCheckClient
if (streamsWithPendingConnectivityEstablishment.size() > 0)
{
logger.info("Start connectivity checks!");
logger.info("Start connectivity checks.");
startChecks(
streamsWithPendingConnectivityEstablishment
.get(0).getCheckList());
@ -136,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();
}
/**
@ -163,23 +195,18 @@ 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)
{
IceSocketWrapper stunSocket = localCandidate.getStunSocket(null);
if(stunSocket != null)
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());
}
}
}
@ -250,7 +277,7 @@ class ConnectivityCheckClient
//nominated pairs.
if (candidatePair.isNominated())
{
logger.fine(
logger.debug(() ->
"Add USE-CANDIDATE in check for: "
+ candidatePair.toShortString());
request.putAttribute(
@ -270,7 +297,7 @@ class ConnectivityCheckClient
.getParentComponent().getParentStream().getName();
String localUserName = parentAgent.generateLocalUserName(media);
if(localUserName == null)
if (localUserName == null)
return null;
UsernameAttribute unameAttr
@ -294,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
@ -310,32 +340,39 @@ 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;
IceSocketWrapper stunSocket = localCandidate.getStunSocket(null);
if(stunSocket != null)
if (stunSocket != null)
{
String msg
= "Failed to send " + request + " through "
+ stunSocket.getLocalSocketAddress() + ".";
if((ex instanceof NoRouteToHostException)
if ((ex instanceof NoRouteToHostException)
|| (ex.getMessage() != null
&& ex.getMessage().equals("No route to host")))
{
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);
}
}
@ -371,18 +408,18 @@ class ConnectivityCheckClient
char messageType = response.getMessageType();
//handle error responses.
if(messageType == Response.BINDING_ERROR_RESPONSE)
if (messageType == Response.BINDING_ERROR_RESPONSE)
{
if(!response.containsAttribute(Attribute.ERROR_CODE))
if (!response.containsAttribute(Attribute.ERROR_CODE))
{
logger.fine("Received a malformed error response.");
logger.debug(() -> "Received a malformed error response.");
return; //malformed error response
}
processErrorResponse(ev);
}
//handle success responses.
else if(messageType == Response.BINDING_SUCCESS_RESPONSE)
else if (messageType == Response.BINDING_SUCCESS_RESPONSE)
{
processSuccessResponse(ev);
}
@ -407,31 +444,29 @@ class ConnectivityCheckClient
= checkedPair.getParentComponent().getParentStream();
final CheckList checkList = stream.getCheckList();
if(stream.getParentAgent().getState().isEstablished())
if (stream.getParentAgent().getState().isEstablished())
return;
//If all of the pairs in the check list are now either in the Failed or
//Succeeded state:
if(checkList.allChecksCompleted())
if (checkList.allChecksCompleted())
{
//If there is not a pair in the valid list for each component of the
//media stream, the state of the check list is set to Failed.
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()
{
if(checkList.getState() != CheckListState.COMPLETED)
if (checkList.getState() != CheckListState.COMPLETED)
{
logger.info("CheckList for stream " +
streamName + " FAILED");
@ -441,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);
}
}
}
@ -459,7 +505,7 @@ class ConnectivityCheckClient
{
CheckList anotherCheckList = anotherStream.getCheckList();
if(anotherCheckList.isFrozen())
if (anotherCheckList.isFrozen())
{
anotherCheckList.computeInitialCheckListPairStates();
startChecks(anotherCheckList);
@ -487,10 +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());
+ checkedPair.toShortString() + ".");
checkedPair.setStateFailed();
return; //malformed error response
}
@ -512,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();
@ -558,9 +607,9 @@ class ConnectivityCheckClient
if (checkedPair.getParentComponent().getSelectedPair() == null)
{
logger.info(
"Receive a peer-reflexive candidate: "
+ peerReflexiveCandidate.getTransportAddress());
logger.info("Receive a peer-reflexive candidate: "
+ peerReflexiveCandidate.getTransportAddress()
+ ".");
}
}
@ -596,14 +645,18 @@ class ConnectivityCheckClient
//Succeeded. Note that, the pair which *generated* the check may be
//different than the valid pair constructed above
if (checkedPair.getParentComponent().getSelectedPair() == null)
logger.info("Pair succeeded: " + checkedPair.toShortString());
{
logger.info("Pair succeeded: " + checkedPair.toShortString()
+ ".");
}
checkedPair.setStateSucceeded();
}
if (!validPair.isValid())
{
if (validPair.getParentComponent().getSelectedPair() == null)
logger.info("Pair validated: " + validPair.toShortString());
logger.info("Pair validated: " + validPair.toShortString()
+ ".");
parentAgent.validatePair(validPair);
}
@ -612,12 +665,12 @@ class ConnectivityCheckClient
IceMediaStream parentStream
= checkedPair.getParentComponent().getParentStream();
synchronized(this)
synchronized (this)
{
Vector<CandidatePair> parentCheckList
= new Vector<>(parentStream.getCheckList());
for(CandidatePair pair : parentCheckList)
for (CandidatePair pair : parentCheckList)
{
if (pair.getState() == CandidatePairState.FROZEN
&& checkedPair.getFoundation().equals(
@ -674,7 +727,8 @@ class ConnectivityCheckClient
logger.info("IsControlling: " + parentAgent.isControlling() +
" USE-CANDIDATE:" +
(request.containsAttribute(Attribute.USE_CANDIDATE) ||
checkedPair.useCandidateSent()));
checkedPair.useCandidateSent())
+ ".");
}
//If the agent was a controlling agent, and it had included a USE-
@ -683,16 +737,16 @@ class ConnectivityCheckClient
if (parentAgent.isControlling()
&& request.containsAttribute(Attribute.USE_CANDIDATE))
{
if(validPair.getParentComponent().getSelectedPair() == null)
if (validPair.getParentComponent().getSelectedPair() == null)
{
logger.info(
"Nomination confirmed for pair: "
+ validPair.toShortString());
logger.info("Nomination confirmed for pair: "
+ validPair.toShortString()
+ ".");
parentAgent.nominationConfirmed( validPair );
}
else
{
logger.fine(
logger.debug(() ->
"Keep alive for pair: " + validPair.toShortString());
}
}
@ -705,7 +759,7 @@ class ConnectivityCheckClient
&& checkedPair.useCandidateReceived()
&& !checkedPair.isNominated())
{
if(checkedPair.getParentComponent().getSelectedPair() == null)
if (checkedPair.getParentComponent().getSelectedPair() == null)
{
logger.info(
"Nomination confirmed for pair: "
@ -714,14 +768,17 @@ class ConnectivityCheckClient
}
else
{
logger.fine(
logger.debug(() ->
"Keep alive for pair: " + validPair.toShortString());
}
}
// Selected pairs get their consent freshness confirmed.
if (checkedPair == checkedPair.getParentComponent().getSelectedPair())
// XXX Should we also confirm consent freshness for non-selected pairs?
if (checkedPair.equals(checkedPair.getParentComponent().getSelectedPair()))
{
checkedPair.setConsentFreshness();
}
}
/**
@ -781,15 +838,15 @@ 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)
if (errorCode == ErrorCodeAttribute.ROLE_CONFLICT)
{
boolean wasControlling
= originalRequest.containsAttribute(Attribute.ICE_CONTROLLING);
logger.finer("Swithing to isControlling=" + !wasControlling);
logger.trace(() -> "Switching to isControlling=" + !wasControlling);
parentAgent.setControlling(!wasControlling);
pair.getParentComponent().getParentStream().getCheckList()
@ -798,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();
}
}
@ -825,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.
@ -851,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();
}
}
/**
@ -872,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();
@ -883,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);
}
}
@ -983,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,13 +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.jitsi.utils.logging2.*;
/**
* The class that would be handling and responding to incoming connectivity
@ -36,30 +35,6 @@ class ConnectivityCheckServer
implements RequestListener,
CredentialsAuthority
{
/**
* The <tt>Logger</tt> used by the <tt>ConnectivityCheckServer</tt>
* class and its instances for logging output.
*/
private static final Logger logger
= 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.
*/
@ -81,6 +56,11 @@ class ConnectivityCheckServer
*/
private boolean alive = false;
/**
* The {@link Logger} used by {@link ConnectivityCheckServer} instances.
*/
private Logger logger;
/**
* Creates a new <tt>ConnectivityCheckServer</tt> setting
* <tt>parentAgent</tt> as the agent that will be used for retrieving
@ -91,6 +71,7 @@ class ConnectivityCheckServer
public ConnectivityCheckServer(Agent parentAgent)
{
this.parentAgent = parentAgent;
logger = parentAgent.getLogger().createChildLogger(this.getClass().getName());
stunStack = this.parentAgent.getStunStack();
stunStack.getCredentialsManager().registerAuthority(this);
@ -130,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;
@ -144,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)))
@ -201,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);
@ -236,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!");
}
@ -267,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;
}
}
/**
@ -433,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;
}
@ -453,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,9 +17,10 @@
*/
package org.ice4j.ice;
import org.jitsi.utils.logging2.*;
import java.beans.*;
import java.util.*;
import java.util.logging.*;
/**
* Implements ice4j internal nomination strategies.
@ -29,12 +30,6 @@ import java.util.logging.*;
public class DefaultNominator
implements PropertyChangeListener
{
/**
* The logger.
*/
private static final Logger logger
= Logger.getLogger(DefaultNominator.class.getName());
/**
* The Agent that created us.
*/
@ -48,10 +43,15 @@ public class DefaultNominator
/**
* Map that will remember association between validated relayed candidate
* and a timer. It is use with the NOMINATE_FIRST_HIGHEST_VALID strategy.
* and a timer. It is used with the NOMINATE_FIRST_HIGHEST_VALID strategy.
*/
private final Map<String, TimerTask> validatedCandidates = new HashMap<>();
/**
* The {@link Logger} used by {@link DefaultNominator} instances.
*/
private Logger logger;
/**
* Creates a new instance of this nominator using <tt>parentAgent</tt> as
* a reference to the <tt>Agent</tt> instance that we should use to
@ -62,6 +62,7 @@ public class DefaultNominator
public DefaultNominator(Agent parentAgent)
{
this.parentAgent = parentAgent;
logger = parentAgent.getLogger().createChildLogger(this.getClass().getName());
parentAgent.addStateChangeListener(this);
}
@ -76,12 +77,12 @@ public class DefaultNominator
{
String propertyName = ev.getPropertyName();
if(Agent.PROPERTY_ICE_PROCESSING_STATE.equals(propertyName))
if (Agent.PROPERTY_ICE_PROCESSING_STATE.equals(propertyName))
{
if(ev.getNewValue() != IceProcessingState.RUNNING)
if (ev.getNewValue() != IceProcessingState.RUNNING)
return;
for(IceMediaStream stream : parentAgent.getStreams())
for (IceMediaStream stream : parentAgent.getStreams())
{
stream.addPairChangeListener(this);
stream.getCheckList().addStateChangeListener(this);
@ -94,20 +95,23 @@ public class DefaultNominator
return;
}
if(ev.getSource() instanceof CandidatePair)
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;
}
@ -131,11 +135,13 @@ public class DefaultNominator
*/
private void strategyNominateFirstValid(PropertyChangeEvent evt)
{
if(IceMediaStream.PROPERTY_PAIR_VALIDATED.equals(evt.getPropertyName()))
if (IceMediaStream.PROPERTY_PAIR_VALIDATED
.equals(evt.getPropertyName()))
{
CandidatePair validPair = (CandidatePair)evt.getSource();
logger.info("Nominate (first valid): " + validPair.toShortString());
logger.info("Nominate (first valid): " + validPair.toShortString()
+ ".");
parentAgent.nominate(validPair);
}
}
@ -152,7 +158,7 @@ public class DefaultNominator
{
String pname = ev.getPropertyName();
if(IceMediaStream.PROPERTY_PAIR_VALIDATED.equals(pname)
if (IceMediaStream.PROPERTY_PAIR_VALIDATED.equals(pname)
|| (IceMediaStream.PROPERTY_PAIR_STATE_CHANGED.equals(pname)
&& (ev.getNewValue() == CandidatePairState.FAILED)))
{
@ -161,14 +167,14 @@ public class DefaultNominator
IceMediaStream parentStream = parentComponent.getParentStream();
CheckList parentCheckList = parentStream.getCheckList();
if(!parentCheckList.allChecksCompleted())
if (!parentCheckList.allChecksCompleted())
return;
for(Component component : parentStream.getComponents())
for (Component component : parentStream.getComponents())
{
CandidatePair pair = parentStream.getValidPair(component);
if(pair != null)
if (pair != null)
{
logger.info(
"Nominate (highest priority): "
@ -179,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
@ -204,7 +222,7 @@ public class DefaultNominator
private void strategyNominateFirstHostOrReflexiveValid(
PropertyChangeEvent evt)
{
if(IceMediaStream.PROPERTY_PAIR_VALIDATED.equals(evt.getPropertyName()))
if (IceMediaStream.PROPERTY_PAIR_VALIDATED.equals(evt.getPropertyName()))
{
CandidatePair validPair = (CandidatePair) evt.getSource();
@ -218,12 +236,12 @@ public class DefaultNominator
CandidateType.RELAYED_CANDIDATE);
boolean nominate = false;
synchronized(validatedCandidates)
synchronized (validatedCandidates)
{
TimerTask task
= validatedCandidates.get(component.toShortString());
if(isRelayed && task == null)
if (isRelayed && task == null)
{
/* armed a timer and see if a host or server reflexive pair
* gets nominated. Otherwise nominate the relayed candidate
@ -236,10 +254,10 @@ public class DefaultNominator
timer.schedule(task, 0);
validatedCandidates.put(component.toShortString(), task);
}
else if(!isRelayed)
else if (!isRelayed)
{
// host or server reflexive candidate pair
if(task != null)
if (task != null)
{
task.cancel();
logger.info(
@ -254,7 +272,7 @@ public class DefaultNominator
}
}
if(nominate)
if (nominate)
parentAgent.nominate(validPair);
}
}
@ -303,18 +321,24 @@ public class DefaultNominator
*/
public void propertyChange(PropertyChangeEvent evt)
{
/* check list has running out of ordinary checks, see if all other
* candidates are FAILED, in which case we nominate immediately
* the relayed candidate
*/
// Make it clear that PROPERTY_CHECK_LIST_CHECKS is in use here.
if (!CheckList.PROPERTY_CHECK_LIST_CHECKS.equals(
evt.getPropertyName()))
{
return;
}
// check list has run out of ordinary checks, see if all other
// candidates are FAILED, in which case we nominate immediately
// the relayed candidate
CheckList checkList = (CheckList)evt.getSource();
boolean allFailed = true;
synchronized(checkList)
synchronized (checkList)
{
for(CandidatePair c : checkList)
for (CandidatePair c : checkList)
{
if(c != pair && c.getState() != CandidatePairState.FAILED)
if (c != pair && c.getState() != CandidatePairState.FAILED)
{
allFailed = false;
break;
@ -354,7 +378,7 @@ public class DefaultNominator
{
Thread.sleep(WAIT_TIME);
}
catch(InterruptedException e)
catch (InterruptedException e)
{
cancelled = true;
}
@ -365,7 +389,7 @@ public class DefaultNominator
this);
validatedCandidates.remove(component.toShortString());
if(cancelled)
if (cancelled)
return;
logger.info(

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);
@ -191,21 +191,22 @@ public class GoogleRelayedCandidate
*
* @return the <tt>DatagramSocket</tt> associated with this
* <tt>Candidate</tt>
* @see LocalCandidate#getIceSocketWrapper()
* @see LocalCandidate#getCandidateIceSocketWrapper()
*/
public synchronized IceSocketWrapper getIceSocketWrapper()
@Override
public synchronized IceSocketWrapper getCandidateIceSocketWrapper()
{
if (socket == null)
{
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

@ -131,13 +131,12 @@ public class HostCandidate extends LocalCandidate
}
/**
* Gets the <tt>DatagramSocket</tt> associated with this <tt>Candidate</tt>.
*
* @return the <tt>DatagramSocket</tt> associated with this
* <tt>Candidate</tt>
* @see LocalCandidate#getIceSocketWrapper()
* {@inheritDoc}
* SHOULD NOT be used outside ice4j. Only exposed for use in the
* org.ice4j.socket package.
*/
public IceSocketWrapper getIceSocketWrapper()
@Override
public IceSocketWrapper getCandidateIceSocketWrapper()
{
return socket;
}

View File

@ -19,9 +19,12 @@ package org.ice4j.ice;
import java.beans.*;
import java.util.*;
import java.util.logging.*;
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,12 +35,6 @@ import org.ice4j.*;
*/
public class IceMediaStream
{
/**
* Our class logger.
*/
private static final Logger logger =
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.
@ -63,6 +60,19 @@ public class IceMediaStream
*/
public static final String PROPERTY_PAIR_VALIDATED = "PairValidated";
/**
* Use builder pattern to provide an immutable IceMediaStream instance.
*
* @param name the name of the media stream
* @param parentAgent the agent that is handling the session that this
* media stream is a part of
* @return IceMediaStream
*/
public static IceMediaStream build(Agent parentAgent, String name)
{
return new IceMediaStream(parentAgent, name);
}
/**
* The name of this media stream. The name is equal to the value specified
* in the SDP description.
@ -119,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.
@ -131,6 +141,11 @@ public class IceMediaStream
*/
private String remotePassword = null;
/**
* The {@link Logger} used by {@link IceMediaStream} instances.
*/
private Logger logger;
/**
* Initializes a new <tt>IceMediaStream</tt> object.
*
@ -140,6 +155,9 @@ public class IceMediaStream
*/
protected IceMediaStream(Agent parentAgent, String name)
{
logger = parentAgent.getLogger().createChildLogger(
IceMediaStream.class.getName(),
Collections.singletonMap("name", name));
this.name = name;
this.parentAgent = parentAgent;
checkList = new CheckList(this);
@ -151,16 +169,29 @@ public class IceMediaStream
* when creating the component so make sure you keep that in mind in case
* assigning a specific component ID is important to you.
*
* @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 AgentConfig#getUseComponentSocket()}.
*
* @return the newly created stream <tt>Component</tt> after adding it to
* the stream first.
*/
protected Component createComponent()
protected Component createComponent(
KeepAliveStrategy keepAliveStrategy,
boolean useComponentSocket)
{
Component component;
synchronized (components)
{
component = new Component(++lastComponentID, this);
component
= new Component(
++lastComponentID,
this,
keepAliveStrategy,
useComponentSocket,
logger);
components.put(component.getComponentID(), component);
}
@ -261,18 +292,6 @@ public class IceMediaStream
}
}
/**
* Returns the number of <tt>Component</tt>s currently registered with this
* stream.
*
* @return the number of <tt>Component</tt>s currently registered with this
* stream.
*/
public int getStreamCount()
{
return getComponentCount();
}
/**
* Returns a reference to the <tt>Agent</tt> that this stream belongs to.
*
@ -345,7 +364,7 @@ public class IceMediaStream
orderCheckList();
pruneCheckList(checkList);
logger.finest("Checklist initialized.");
logger.trace(() -> "Checklist initialized.");
}
}
@ -357,7 +376,7 @@ public class IceMediaStream
*/
protected void createCheckList(List<CandidatePair> checkList)
{
for(Component cmp : getComponents())
for (Component cmp : getComponents())
createCheckList(cmp, checkList);
}
@ -376,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
@ -422,7 +441,7 @@ public class IceMediaStream
* candidate with its base. Once this has been done, we remove each pair
* where the local and remote candidates are identical to the local and
* remote candidates of a pair higher up on the priority list.
* <p/>
* <br>
* In addition, in order to limit the attacks described in Section 18.5.2
* of the ICE spec, we limit the total number of pairs and hence
* (connectivity checks) to a specific value, (a total of 100 by default).
@ -437,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;
@ -450,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;
@ -492,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;
@ -528,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;
}
@ -558,12 +582,12 @@ public class IceMediaStream
{
synchronized(checkList)
{
for( CandidatePair pair : checkList)
for (CandidatePair pair : checkList)
{
if( pair.getLocalCandidate().getTransportAddress()
if (pair.getLocalCandidate().getTransportAddress()
.equals(localAddress)
&& pair.getRemoteCandidate().getTransportAddress()
.equals(remoteAddress) )
.equals(remoteAddress))
{
return pair;
}
@ -588,12 +612,12 @@ public class IceMediaStream
{
synchronized(checkList)
{
for( CandidatePair pair : checkList)
for (CandidatePair pair : checkList)
{
LocalCandidate local = pair.getLocalCandidate();
RemoteCandidate remote = pair.getRemoteCandidate();
if(local.getUfrag().equals(remoteUFrag)
if (local.getUfrag().equals(remoteUFrag)
&& remote.getUfrag().equals(localUFrag))
{
return pair;
@ -614,7 +638,7 @@ public class IceMediaStream
synchronized (components)
{
for(Component cmp : components.values())
for (Component cmp : components.values())
num += cmp.countLocalHostCandidates();
}
@ -646,7 +670,7 @@ public class IceMediaStream
{
synchronized (validList)
{
if(!validList.contains(pair))
if (!validList.contains(pair))
validList.add(pair);
}
@ -667,7 +691,7 @@ public class IceMediaStream
{
synchronized(validList)
{
for(CandidatePair pair : validList)
for (CandidatePair pair : validList)
{
if (pair.getFoundation().equals(foundation))
return true;
@ -715,7 +739,7 @@ public class IceMediaStream
*/
protected boolean validListContainsAllComponents()
{
for(Component cmp : getComponents())
for (Component cmp : getComponents())
{
if (getValidPair(cmp) == null)
{
@ -763,9 +787,9 @@ public class IceMediaStream
*/
protected boolean allComponentsHaveSelected()
{
for(Component component : getComponents())
for (Component component : getComponents())
{
if(component.getSelectedPair() == null)
if (component.getSelectedPair() == null)
return false;
}
return true;
@ -783,11 +807,11 @@ public class IceMediaStream
*/
protected CandidatePair getValidPair(Component component)
{
synchronized(validList)
synchronized (validList)
{
for(CandidatePair pair : validList)
for (CandidatePair pair : validList)
{
if(pair.getParentComponent() == component)
if (pair.getParentComponent() == component)
return pair;
}
}
@ -804,9 +828,9 @@ public class IceMediaStream
*/
public void addPairChangeListener(PropertyChangeListener l)
{
synchronized(streamListeners)
synchronized (streamListeners)
{
if(!streamListeners.contains(l))
if (!streamListeners.contains(l))
streamListeners.add(l);
}
}
@ -819,7 +843,7 @@ public class IceMediaStream
*/
public void removePairStateChangeListener(PropertyChangeListener l)
{
synchronized(streamListeners)
synchronized (streamListeners)
{
streamListeners.remove(l);
}
@ -841,7 +865,7 @@ public class IceMediaStream
{
PropertyChangeListener[] ls;
synchronized(streamListeners)
synchronized (streamListeners)
{
ls
= streamListeners.toArray(
@ -851,7 +875,7 @@ public class IceMediaStream
PropertyChangeEvent ev
= new PropertyChangeEvent(source, propertyName, oldValue, newValue);
for(PropertyChangeListener l : ls)
for (PropertyChangeListener l : ls)
l.propertyChange(ev);
}
@ -899,18 +923,9 @@ public class IceMediaStream
{
return remotePassword;
}
/**
* Use builder pattern to provide an immutable IceMediaStream instance.
*
* @param name the name of the media stream
* @param parentAgent the agent that is handling the session that this
* media stream is a part of
* @return IceMediaStream
*/
public static IceMediaStream build(Agent parentAgent, String name)
{
return new IceMediaStream(parentAgent, name);
}
public Logger getLogger()
{
return logger;
}
}

View File

@ -0,0 +1,71 @@
/*
* 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;
/**
* An enumeration of strategies for selecting which candidate pairs to
* keep alive.
*/
public enum KeepAliveStrategy
{
/**
* Only keep alive the selected pair.
*/
SELECTED_ONLY("selected_only"),
/**
* Keep alive the selected pair and any TCP pairs.
*/
SELECTED_AND_TCP("selected_and_tcp"),
/**
* Keep alive all succeeded pairs.
*/
ALL_SUCCEEDED("all_succeeded");
private String name;
KeepAliveStrategy(String name)
{
this.name = name;
}
/**
* @return the {@link KeepAliveStrategy} 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 KeepAliveStrategy fromString(String string)
{
for (KeepAliveStrategy strategy : KeepAliveStrategy.values())
{
if (strategy.name.equals(string))
return strategy;
}
return null;
}
/**
* {@inheritDoc}
*/
@Override
public String toString()
{
return name;
}
}

View File

@ -19,11 +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.jitsi.utils.logging2.*;
/**
* <tt>LocalCandidate</tt>s are obtained by an agent for every stream component
@ -35,6 +35,16 @@ import org.ice4j.stack.*;
public abstract class LocalCandidate
extends Candidate<LocalCandidate>
{
/**
* The <tt>Logger</tt> used by the <tt>LocalCandidate</tt> class for logging
* output.
* 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(HostCandidate.class.getName());
/**
* The type of method used to discover this candidate ("host", "upnp", "stun
* peer reflexive", "stun server reflexive", "turn relayed", "google turn
@ -53,11 +63,9 @@ public abstract class LocalCandidate
private boolean isSSL = false;
/**
* The <tt>Logger</tt> used by the <tt>LocalCandidate</tt> class and its
* instances for logging output.
* The {@link Logger} used by {@link LocalCandidate} instances.
*/
private static final Logger logger
= Logger.getLogger(HostCandidate.class.getName());
private final Logger logger;
/**
* Creates a <tt>LocalCandidate</tt> instance for the specified transport
@ -82,8 +90,10 @@ public abstract class LocalCandidate
CandidateType type,
CandidateExtendedType extendedType,
LocalCandidate relatedCandidate)
{
super(transportAddress, parentComponent, type, relatedCandidate);
logger = parentComponent.getLogger().createChildLogger(this.getClass().getName());
this.extendedType = extendedType;
}
@ -95,8 +105,7 @@ public abstract class LocalCandidate
* <tt>Candidate</tt>
*
* @deprecated This should be used by the library only. Users of ice4j
* should use {@link org.ice4j.ice.CandidatePair#getDatagramSocket()}
* on the appropriate <tt>CandidatePair</tt> instead.
* should use {@link org.ice4j.ice.Component#getSocket()} instead.
*/
@Deprecated
public DatagramSocket getDatagramSocket()
@ -113,37 +122,47 @@ public abstract class LocalCandidate
* <tt>Candidate</tt>
*
* @deprecated This should be used by the library only. Users of ice4j
* should use {@link org.ice4j.ice.CandidatePair#getSocket()} on the
* appropriate <tt>CandidatePair</tt> instead.
* should use {@link org.ice4j.ice.Component#getSocket()} instead.
*/
@Deprecated
public Socket getSocket()
{
IceSocketWrapper wrapper = getIceSocketWrapper();
return wrapper == null ? null : wrapper.getTCPSocket();
return null;
}
/**
* Gets the <tt>IceSocketWrapper</tt> associated with this
* <tt>Candidate</tt>.
*
* @return the <tt>IceSocketWrapper</tt> associated with this
* <tt>Candidate</tt>
* @return the {@link IceSocketWrapper} instance of the {@link Component}
* which owns this {@link LocalCandidate}. Note that this IS NOT an
* instance specific to this {@link LocalCandidate}. See
* {@link #getCandidateIceSocketWrapper()}.
*/
protected abstract IceSocketWrapper getIceSocketWrapper();
protected IceSocketWrapper getIceSocketWrapper()
{
return getParentComponent().getSocketWrapper();
}
/**
* Gets the <tt>IceSocketWrapper</tt> associated with this
* <tt>Candidate</tt> which is to be used for a specific remote address.
* This default implementation ignores the remote address.
*
* @param remoteAddress the remote address for which to get a socket.
* @return the <tt>IceSocketWrapper</tt> associated with this
* <tt>Candidate</tt> which is to be used for a specific remote address.
* @return the {@link IceSocketWrapper} instance, if any, associated with
* this candidate. Note that this IS NOT the instance which should be used
* for reading and writing by the application, and SHOULD NOT be used from
* outside ice4j (even if a subclass exposes it as public). Also see
* {@link #getIceSocketWrapper()}.
*/
protected IceSocketWrapper getIceSocketWrapper(SocketAddress remoteAddress)
protected abstract IceSocketWrapper getCandidateIceSocketWrapper();
/**
* @return the {@link IceSocketWrapper} instance for this candidate,
* associated with a particular remote address.
* @param remoteAddress the remote address for which to return an
* associated socket.
*/
protected IceSocketWrapper getCandidateIceSocketWrapper(
SocketAddress remoteAddress)
{
return getIceSocketWrapper();
// The default implementation just refers to the method which doesn't
// involve a remove address. Extenders which support multiple instances
// mapped by remote address should override.
return getCandidateIceSocketWrapper();
}
/**
@ -161,7 +180,7 @@ public abstract class LocalCandidate
*/
public IceSocketWrapper getStunSocket(TransportAddress serverAddress)
{
IceSocketWrapper hostSocket = getIceSocketWrapper();
IceSocketWrapper hostSocket = getCandidateIceSocketWrapper();
if (hostSocket != null
&& hostSocket.getTCPSocket() != null)
@ -183,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;
@ -240,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;
@ -310,7 +327,7 @@ public abstract class LocalCandidate
protected void free()
{
// Close the socket associated with this LocalCandidate.
IceSocketWrapper socket = getIceSocketWrapper();
IceSocketWrapper socket = getCandidateIceSocketWrapper();
if (socket != null)
{
@ -318,7 +335,7 @@ public abstract class LocalCandidate
if ((base == null)
|| (base == this)
|| (base.getIceSocketWrapper() != socket))
|| (base.getCandidateIceSocketWrapper() != socket))
{
//remove our socket from the stack.
getStunStack().removeSocket(getTransportAddress());

View File

@ -98,35 +98,6 @@ public class NetworkUtils
&& (add.getAddress()[1] & 0xFF) == 254;
}
/**
* Determines whether the address is an IPv4 link local address. IPv4 link
* local addresses are those in the following networks:
*
* 10.0.0.0 to 10.255.255.255
* 172.16.0.0 to 172.31.255.255
* 192.168.0.0 to 192.168.255.255
*
* @param add the address to inspect
* @return true if add is a link local ipv4 address and false if not.
*/
public static boolean isLinkLocalIPv4Address(InetAddress add)
{
if (add instanceof Inet4Address)
{
byte address[] = add.getAddress();
if ( (address[0] & 0xFF) == 10)
return true;
if ( (address[0] & 0xFF) == 172
&& (address[1] & 0xFF) >= 16 && address[1] <= 31)
return true;
if ( (address[0] & 0xFF) == 192
&& (address[1] & 0xFF) == 168)
return true;
return false;
}
return false;
}
/**
* Returns a random local port number that user applications could bind to.
* (i.e. above 1024).
@ -138,44 +109,16 @@ public class NetworkUtils
}
/**
* Returns a random local port number, greater than min and lower than max.
* Returns a random local port number in the interval [min, max].
*
* @param min the minimum allowed value for the returned port number.
* @param max the maximum allowed value for the returned port number.
*
* @return a random int located between greater than min and lower than max.
* @return a random int in the interval [min, max].
*/
public static int getRandomPortNumber(int min, int max)
{
return portNumberGenerator.nextInt(max - min) + min;
}
/**
* Returns a random local port number, greater than min and lower than max.
* If the pair flag is set to true, then the returned port number is
* guaranteed to be pair. This is useful for protocols that require this
* such as RTP
*
* @param min the minimum allowed value for the returned port number.
* @param max the maximum allowed value for the returned port number.
* @param pair specifies whether the caller would like the returned port to
* be pair.
*
* @return a random int located between greater than min and lower than max.
*/
public static int getRandomPortNumber(int min, int max, boolean pair)
{
if(pair)
{
int delta = max - min;
delta /= 2;
int port = getRandomPortNumber(min, min + delta);
return port * 2;
}
else
{
return getRandomPortNumber(min, max);
}
return portNumberGenerator.nextInt(max - min + 1) + min;
}
/**
@ -399,6 +342,15 @@ public class NetworkUtils
colonIndex = -1;
int i = 0, j = 0;
// Can be wrapped in []
if (addrBuff[i] == '[')
{
++i;
if (scopeID == -1)
--srcb_length;
}
// Starting : mean we need to have at least one more.
if (addrBuff[i] == ':')
if (addrBuff[++i] != ':')
@ -530,7 +482,7 @@ public class NetworkUtils
if (isMappedIPv4Addr(addr))
{
byte[] newAddr = new byte[IN4_ADDR_SIZE];
System.arraycopy(addr, 12, newAddr, 0, IN6_ADDR_SIZE);
System.arraycopy(addr, 12, newAddr, 0, IN4_ADDR_SIZE);
return newAddr;
}
@ -662,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;
}
}
@ -683,11 +635,11 @@ public class NetworkUtils
* @param port the port number that we'd like verified.
*
* @return <tt>true</tt> if port is a valid and bindable port number and
* <tt>alse</tt> otherwise.
* <tt>false</tt> otherwise.
*/
public static boolean isValidPortNumber(int port)
{
return MIN_PORT_NUMBER < port && port < MAX_PORT_NUMBER;
return MIN_PORT_NUMBER <= port && port <= MAX_PORT_NUMBER;
}
/**
@ -800,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

@ -61,18 +61,15 @@ public class PeerReflexiveCandidate
base);
super.setBase(base);
super.priority = priority;
super.setTcpType(base.getTcpType());
}
/**
* Returns the <tt>DatagramSocket</tt> associated with this
* <tt>Candidate</tt>.
*
* @return the <tt>DatagramSocket</tt> associated with this
* <tt>Candidate</tt>
* @see LocalCandidate#getIceSocketWrapper()
* {@inheritDoc}
*/
public IceSocketWrapper getIceSocketWrapper()
@Override
public IceSocketWrapper getCandidateIceSocketWrapper()
{
return getBase().getIceSocketWrapper();
return getBase().getCandidateIceSocketWrapper();
}
}

View File

@ -101,7 +101,7 @@ public class RelayedCandidate
* @return the <tt>RelayedCandidateDatagramSocket</tt> of this
* <tt>RelayedCandidate</tt>
*/
public synchronized RelayedCandidateDatagramSocket
private synchronized RelayedCandidateDatagramSocket
getRelayedCandidateDatagramSocket()
{
if (relayedCandidateDatagramSocket == null)
@ -127,9 +127,9 @@ public class RelayedCandidate
*
* @return the <tt>DatagramSocket</tt> associated with this
* <tt>Candidate</tt>
* @see LocalCandidate#getIceSocketWrapper()
*/
public synchronized IceSocketWrapper getIceSocketWrapper()
@Override
public synchronized IceSocketWrapper getCandidateIceSocketWrapper()
{
if (socket == 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

@ -104,16 +104,12 @@ public class ServerReflexiveCandidate
}
/**
* Gets the <tt>DatagramSocket</tt> associated with this <tt>Candidate</tt>.
*
* @return the <tt>DatagramSocket</tt> associated with this
* <tt>Candidate</tt>
* @see LocalCandidate#getIceSocketWrapper()
* {@inheritDoc}
*/
@Override
public IceSocketWrapper getIceSocketWrapper()
public IceSocketWrapper getCandidateIceSocketWrapper()
{
return getBase().getIceSocketWrapper();
return getBase().getCandidateIceSocketWrapper();
}
/**
@ -127,7 +123,7 @@ public class ServerReflexiveCandidate
{
super.free();
if(stunHarvest != null)
if (stunHarvest != null)
stunHarvest.close();
}
}

View File

@ -54,6 +54,23 @@ public class TcpHostCandidate
super(transportAddress, parentComponent);
}
/**
* {@inheritDoc}
*/
@Override
protected IceSocketWrapper getCandidateIceSocketWrapper(
SocketAddress remoteAddress)
{
for (IceSocketWrapper socket : sockets)
{
if (socket.getTCPSocket().getRemoteSocketAddress()
.equals(remoteAddress))
return socket;
}
return null;
}
public void addSocket(IceSocketWrapper socket)
{
sockets.add(socket);
@ -83,16 +100,4 @@ public class TcpHostCandidate
super.free();
}
@Override
protected IceSocketWrapper getIceSocketWrapper(SocketAddress remoteAddress)
{
for (IceSocketWrapper socket : sockets)
{
if (socket.getTCPSocket().getRemoteSocketAddress()
.equals(remoteAddress))
return socket;
}
return null;
}
}

View File

@ -79,8 +79,8 @@ public class UPNPCandidate
{
}
IceSocketWrapper socket = getIceSocketWrapper();
if(socket != null)
IceSocketWrapper socket = getCandidateIceSocketWrapper();
if (socket != null)
{
socket.close();
}
@ -89,13 +89,19 @@ public class UPNPCandidate
}
/**
* Gets the <tt>DatagramSocket</tt> associated with this <tt>Candidate</tt>.
*
* @return the <tt>DatagramSocket</tt> associated with this
* <tt>Candidate</tt>
* {@inheritDoc}
*/
@Override
public IceSocketWrapper getIceSocketWrapper()
public IceSocketWrapper getCandidateIceSocketWrapper()
{
return getBase().getCandidateIceSocketWrapper();
}
/**
* {@inheritDoc}
*/
@Override
protected IceSocketWrapper getIceSocketWrapper()
{
return getBase().getIceSocketWrapper();
}

View File

@ -0,0 +1,52 @@
/*
* 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;
/**
* An abstract partial implementation of {@link CandidateHarvester}.
*
* @author Emil Ivov
* @author Lyubomir Marinov
* @author Boris Grozev
*/
public abstract class AbstractCandidateHarvester
implements CandidateHarvester
{
/**
* Manages statistics about harvesting time.
*/
private HarvestStatistics harvestStatistics = new HarvestStatistics();
/**
* {@inheritDoc}
*/
@Override
public HarvestStatistics getHarvestStatistics()
{
return harvestStatistics;
}
/**
* {@inheritDoc}
*/
@Override
public boolean isHostHarvester()
{
return false;
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,703 @@
/*
* 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.attribute.*;
import org.ice4j.message.*;
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.
*
* When a datagram from an unknown source is received, it is parsed as a STUN
* Binding Request, and if it has a USERNAME attribute, its ufrag is extracted.
* At this point, an implementing class may choose to create a mapping for
* the remote address of the datagram, which will be used for further packets
* from this address.
*
* @author Boris Grozev
*/
public abstract class AbstractUdpListener
{
/**
* Our class logger.
*/
private static final Logger logger
= Logger.getLogger(AbstractUdpListener.class.getName());
/**
* The size for newly allocated <tt>Buffer</tt> instances. This limits the
* maximum size of datagrams we can receive.
*
* XXX should we increase this in case of other MTUs, or set it dynamically
* according to the available network interfaces?
*/
private static final int BUFFER_SIZE
= /* assumed MTU */ 1500 - /* IPv4 header */ 20 - /* UDP header */ 8;
/**
* The number of <tt>Buffer</tt> instances to keep in {@link #pool}.
*/
private static final int POOL_SIZE = 256;
/**
* Returns the list of {@link TransportAddress}es, one for each allowed IP
* address found on each allowed network interface, with the given port.
*
* @param port the UDP port number.
* @return the list of allowed transport addresses.
*/
public static List<TransportAddress> getAllowedAddresses(int port)
{
List<TransportAddress> addresses = new LinkedList<>();
for (InetAddress address
: HostCandidateHarvester.getAllAllowedAddresses())
{
addresses.add(new TransportAddress(address, port, Transport.UDP));
}
return addresses;
}
/**
* Tries to parse the bytes in <tt>buf</tt> at offset <tt>off</tt> (and
* length <tt>len</tt>) as a STUN Binding Request message. If successful,
* looks for a USERNAME attribute and returns the local username fragment
* part (see RFC5245 Section 7.1.2.3).
* In case of any failure returns <tt>null</tt>.
*
* @param buf the bytes.
* @param off the offset.
* @param len the length.
* @return the local ufrag from the USERNAME attribute of the STUN message
* contained in <tt>buf</tt>, or <tt>null</tt>.
*/
static String getUfrag(byte[] buf, int off, int len)
{
// RFC5389, Section 6:
// All STUN messages MUST start with a 20-byte header followed by zero
// or more Attributes.
if (buf == null || buf.length < off + len || len < 20)
{
return null;
}
// RFC5389, Section 6:
// The magic cookie field MUST contain the fixed value 0x2112A442 in
// network byte order.
if ( !( (buf[off + 4] & 0xFF) == 0x21 &&
(buf[off + 5] & 0xFF) == 0x12 &&
(buf[off + 6] & 0xFF) == 0xA4 &&
(buf[off + 7] & 0xFF) == 0x42))
{
if (logger.isLoggable(Level.FINE))
{
logger.fine("Not a STUN packet, magic cookie not found.");
}
return null;
}
try
{
Message stunMessage = Message.decode(buf, off, len);
if (stunMessage.getMessageType()
!= Message.BINDING_REQUEST)
{
return null;
}
UsernameAttribute usernameAttribute
= (UsernameAttribute)
stunMessage.getAttribute(Attribute.USERNAME);
if (usernameAttribute == null)
return null;
String usernameString
= new String(usernameAttribute.getUsername());
return usernameString.split(":")[0];
}
catch (Exception e)
{
// Catch everything. We are going to log, and then drop the packet
// anyway.
if (logger.isLoggable(Level.FINE))
{
logger.fine("Failed to extract local ufrag: " + e);
}
}
return null;
}
/**
* The map which keeps the known remote addresses and their associated
* candidateSockets.
* {@link #thread} is the only thread which adds new entries, while
* other threads remove entries when candidates are freed.
*/
private final Map<SocketAddress, MySocket> sockets
= new ConcurrentHashMap<>();
/**
* A pool of <tt>Buffer</tt> instances used to avoid creating of new java
* objects.
*/
private final ArrayBlockingQueue<Buffer> pool
= new ArrayBlockingQueue<>(POOL_SIZE);
/**
* The local address that this harvester is bound to.
*/
protected final TransportAddress localAddress;
/**
* The "main" socket that this harvester reads from.
*/
private final DatagramSocket socket;
/**
* The thread reading from {@link #socket}.
*/
private final Thread thread;
/**
* Triggers the termination of the threads of this instance.
*/
private boolean close = false;
/**
* Initializes a new <tt>SinglePortUdpHarvester</tt> instance which is to
* bind on the specified local address.
* @param localAddress the address to bind to. If the port is 0 an ephemeral port will be chosen by the OS and the
* 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)
{
tempAddress = new TransportAddress(
(InetAddress) null,
localAddress.getPort(),
localAddress.getTransport()
);
}
socket = new DatagramSocket( tempAddress );
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 != null)
{
logMessage += " (asked for " + receiveBufferSize + ")";
}
logger.info(logMessage);
thread = new Thread()
{
@Override
public void run()
{
AbstractUdpListener.this.runInHarvesterThread();
}
};
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.
*/
public void close()
{
close = true;
socket.close(); // causes socket#receive to stop blocking.
}
/**
* Perpetually reads datagrams from {@link #socket} and handles them
* accordingly.
*
* It is important that this blocks are little as possible (except on
* socket.receive(), of course), because it could potentially delay the
* reception of both ICE and media packets for the whole application.
*/
private void runInHarvesterThread()
{
Buffer buf;
DatagramPacket pkt = null;
MySocket destinationSocket;
InetSocketAddress remoteAddress;
do
{
if (close)
{
break;
}
buf = getFreeBuffer();
if (pkt == null)
pkt = new DatagramPacket(buf.buffer, 0, buf.buffer.length);
else
pkt.setData(buf.buffer, 0, buf.buffer.length);
try
{
socket.receive(pkt);
}
catch (IOException ioe)
{
if (!close)
{
logger.severe("Failed to receive from socket: " + ioe);
}
break;
}
buf.len = pkt.getLength();
remoteAddress = (InetSocketAddress) pkt.getSocketAddress();
destinationSocket = sockets.get(remoteAddress);
if (destinationSocket != null)
{
//make 'pkt' available for reading through destinationSocket
destinationSocket.addBuffer(buf);
}
else
{
// Packet from an unknown source. Is it a STUN Binding Request?
String ufrag = getUfrag(buf.buffer, 0, buf.len);
if (ufrag == null)
{
// Not a STUN Binding Request or doesn't have a valid
// USERNAME attribute. Drop it.
continue;
}
maybeAcceptNewSession(buf, remoteAddress, ufrag);
// Maybe add to #sockets here in the base class?
}
}
while (true);
// now clean up and exit
for (MySocket candidateSocket : new ArrayList<>(sockets.values()))
{
candidateSocket.close();
}
socket.close();
}
/**
* Handles the reception of a STUN Binding Request with a valid USERNAME
* attribute, from a "new" remote address (one which is not in
* {@link #sockets}).
* Implementations may choose to e.g. create a socket and pass it to their
* ICE stack.
*
* Note that this is meant to only be executed by
* {@link AbstractUdpListener}'s read thread, and should not be called from
* implementing classes.
*
* @param buf the UDP payload of the first datagram received on the newly
* accepted socket.
* @param remoteAddress the remote address from which the datagram was
* received.
* @param ufrag the local ICE username fragment of the received STUN Binding
* Request.
*/
protected abstract void maybeAcceptNewSession(
Buffer buf,
InetSocketAddress remoteAddress,
String ufrag);
/**
* Gets an unused <tt>Buffer</tt> instance, creating it if necessary.
* @return an unused <tt>Buffer</tt> instance, creating it if necessary.
*/
private Buffer getFreeBuffer()
{
Buffer buf = pool.poll();
if (buf == null)
{
buf = new Buffer(new byte[BUFFER_SIZE], 0);
}
return buf;
}
/**
* Creates a new {@link MySocket} instance and associates it with the given
* remote address. Returns the created instance.
*
* Note that this is meant to only execute in {@link AbstractUdpListener}'s
* read thread.
*
* @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, String ufrag)
throws SocketException
{
MySocket newSocket = new MySocket(remoteAddress, ufrag);
sockets.put(remoteAddress, newSocket);
return newSocket;
}
/**
* Implements a <tt>DatagramSocket</tt> for the purposes of a specific
* <tt>MyCandidate</tt>.
*
* It is not bound to a specific port, but shares the same local address
* as the bound socket held by the harvester.
*/
protected class MySocket
extends DatagramSocket
{
/**
* The size of {@link #queue}.
*/
private static final int QUEUE_SIZE = 128;
/**
* The FIFO which acts as a buffer for this socket.
*/
private final ArrayBlockingQueue<Buffer> queue
= new ArrayBlockingQueue<>(QUEUE_SIZE);
/**
* The {@link QueueStatistics} instance optionally used to collect and
* print detailed statistics about {@link #queue}.
*/
private final QueueStatistics queueStatistics;
/**
* The remote address that is associated with this socket.
*/
private InetSocketAddress remoteAddress;
/**
* The flag which indicates that this <tt>DatagramSocket</tt> has been
* closed.
*/
private boolean closed = false;
private final String ufrag;
/**
* Initializes a new <tt>MySocket</tt> instance with the given
* remote address.
* @param remoteAddress the remote address to be associated with the
* new instance.
* @throws SocketException
*/
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(QUEUE_SIZE, Clock.systemUTC());
}
else
{
queueStatistics = null;
}
}
/**
* Adds pkt to this socket. If the queue is full, drops a packet. Does
* not block.
*/
public void addBuffer(Buffer buf)
{
synchronized (queue)
{
// Drop the first rather than the current packet, so that
// receivers can notice the loss earlier.
if (queue.size() == QUEUE_SIZE)
{
logger.info(
"Dropping a packet because the queue is full. Remote address = "
+ remoteAddress + " ufrag=" + ufrag);
if (queueStatistics != null)
{
queueStatistics.dropped();
}
queue.poll();
}
queue.offer(buf);
if (queueStatistics != null)
{
queueStatistics.added();
}
queue.notify();
}
}
/**
* {@inheritDoc}
*
* Delegates to the actual socket of the harvester.
*/
@Override
public InetAddress getLocalAddress()
{
return localAddress.getAddress();
}
/**
* {@inheritDoc}
*
* Delegates to the actual socket of the harvester.
*/
@Override
public int getLocalPort()
{
return localAddress.getPort();
}
/**
* {@inheritDoc}
*
* Delegates to the actual socket of the harvester.
*/
@Override
public SocketAddress getLocalSocketAddress()
{
return localAddress;
}
/**
* {@inheritDoc}
* </p>
* This {@link DatagramSocket} will only allow packets from the
* remote address that it has, so we consider it connected to this
* address.
*/
@Override
public SocketAddress getRemoteSocketAddress()
{
return remoteAddress;
}
/**
* {@inheritDoc}
* </p>
* This {@link DatagramSocket} will only allow packets from the
* remote address that it has, so we consider it connected to this
* address.
*/
@Override
public InetAddress getInetAddress()
{
return remoteAddress.getAddress();
}
/**
* {@inheritDoc}
* </p>
* This {@link DatagramSocket} will only allow packets from the
* remote address that it has, so we consider it connected to this
* address.
*/
@Override
public int getPort()
{
return remoteAddress.getPort();
}
/**
* {@inheritDoc}
*
* Removes the association of the remote address with this socket from
* the harvester's map.
*/
@Override
public void close()
{
synchronized (queue)
{
closed = true;
// Wake up any threads still in receive()
queue.notifyAll();
}
// We could be called by the super-class constructor, in which
// case this.removeAddress is not initialized yet.
if (remoteAddress != null)
{
AbstractUdpListener.this.sockets.remove(remoteAddress);
}
super.close();
}
/**
* Reads the data from the first element of {@link #queue} into
* <tt>p</tt>. Blocks until {@link #queue} has an element.
* @param p
* @throws IOException
*/
@Override
public void receive(DatagramPacket p)
throws IOException
{
Buffer buf = null;
while (buf == null)
{
synchronized (queue)
{
if (closed)
{
throw new SocketException("Socket closed");
}
if (queue.isEmpty())
{
try
{
queue.wait();
}
catch (InterruptedException ie)
{}
}
buf = queue.poll();
if (buf != null && queueStatistics != null)
{
queueStatistics.removed(queue.size(), null);
}
}
}
byte[] pData = p.getData();
// XXX Should we use p.setData() here with a buffer of our own?
if (pData == null || pData.length < buf.len)
{
throw new IOException("packet buffer not available");
}
System.arraycopy(buf.buffer, 0, pData, 0, buf.len);
p.setLength(buf.len);
p.setSocketAddress(remoteAddress);
pool.offer(buf);
}
/**
* {@inheritDoc}
*
* Delegates to the actual socket of the harvester.
*/
@Override
public void send(DatagramPacket p)
throws IOException
{
socket.send(p);
}
}
/**
* Represents a buffer for the purposes of <tt>SinglePortUdpHarvester</tt>.
* Wraps a byte[] and adds a length field specifying the number of elements
* actually used.
*/
protected class Buffer
{
/**
* The actual data.
*/
byte[] buffer;
/**
* The number of elements of {@link #buffer} actually used.
*/
int len;
/**
* Initializes a new <tt>Buffer</tt> instance.
* @param buffer the data.
* @param len the length.
*/
private Buffer(byte[] buffer, int len)
{
this.buffer = buffer;
this.len = len;
}
}
}

View File

@ -83,7 +83,7 @@ public class AwsCandidateHarvester
*/
public AwsCandidateHarvester()
{
super(null, null);
super("aws");
}
/**
@ -130,6 +130,7 @@ public class AwsCandidateHarvester
* Returns the public (mask) address, or null.
* @return the public (mask) address, or null.
*/
@Override
public TransportAddress getMask()
{
if (smellsLikeAnEC2())
@ -144,6 +145,7 @@ public class AwsCandidateHarvester
* Returns the local (face) address, or null.
* @return the local (face) address, or null.
*/
@Override
public TransportAddress getFace()
{
if (smellsLikeAnEC2())

View File

@ -28,14 +28,10 @@ import org.ice4j.ice.*;
*
* @author Emil Ivov
* @author Lyubomir Marinov
* @author Boris Grozev
*/
public abstract class CandidateHarvester
public interface CandidateHarvester
{
/**
* Manages statistics about harvesting time.
*/
private HarvestStatistics harvestStatistics = new HarvestStatistics();
/**
* Gathers all candidate addresses of the type that this
* <tt>CandidateHarvester</tt> supports. The gathered candidate addresses
@ -52,7 +48,7 @@ public abstract class CandidateHarvester
* as they are discovered, they should also be returned in order to make
* sure that the gathering will be considered successful.
*/
public abstract Collection<LocalCandidate> harvest(Component component);
Collection<LocalCandidate> harvest(Component component);
/**
* Returns the statistics describing how well the various harvests of this
@ -61,10 +57,7 @@ public abstract class CandidateHarvester
* @return The {@link HarvestStatistics} describing this harvester's
* harvests.
*/
public HarvestStatistics getHarvestStatistics()
{
return harvestStatistics;
}
HarvestStatistics getHarvestStatistics();
/**
* Returns <tt>true</tt> if this <tt>CandidateHarvester</tt> is to be
@ -77,8 +70,5 @@ public abstract class CandidateHarvester
* @return <tt>true</tt> if this <tt>CandidateHarvester</tt> is a harvester
* for host candidates.
*/
public boolean isHostHarvester()
{
return false;
}
boolean isHostHarvester();
}

View File

@ -21,6 +21,7 @@ import java.util.*;
import java.util.concurrent.*;
import java.util.logging.*;
import org.ice4j.*;
import org.ice4j.ice.*;
/**
@ -197,7 +198,17 @@ public class CandidateHarvesterSet
{
try
{
future.get();
future.get(HarvestConfig.config.timeout().toMillis(), TimeUnit.MILLISECONDS);
break;
}
catch (TimeoutException te)
{
CandidateHarvesterSetElement harvester = task.getKey().getHarvester();
if (harvester != null)
{
harvester.setEnabled(false);
}
logger.warning("timed out while harvesting from " + harvester);
break;
}
catch (CancellationException ce)

View File

@ -96,7 +96,7 @@ class CandidateHarvesterSetElement
{
setEnabled(false);
}
else if(trickleCallback != null)
else if (trickleCallback != null)
{
trickleCallback.onIceCandidates(candidates);
}
@ -143,7 +143,7 @@ class CandidateHarvesterSetElement
*/
public void setEnabled(boolean enabled)
{
logger.info((enabled ? "Enabling: " : "Disabling: ") + harvester);
logger.fine((enabled ? "Enabling: " : "Disabling: ") + harvester);
this.enabled = enabled;
}

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();
@ -133,6 +133,18 @@ public class GoogleTurnCandidateHarvest
harvester.getStunStack().addSocket(
relayedCandidate.getStunSocket(null));
// Make the relayed candidate's socket available for reading
// by the component.
IceSocketWrapper candidateSocket
= relayedCandidate.getCandidateIceSocketWrapper();
ComponentSocket componentSocket
= relayedCandidate.getParentComponent().getComponentSocket();
if (componentSocket != null)
{
componentSocket.add(candidateSocket);
}
addCandidate(relayedCandidate);
}
}

View File

@ -29,43 +29,109 @@ import org.ice4j.socket.*;
* Implements a <tt>CandidateHarvester</tt> which gathers Google TURN SSLTCP
* dialect <tt>Candidate</tt>s for a specified {@link Component}.
*
* This dialect exchanges a SSL v2.0 client-hello answered by a TLS v1.0
* server-hello, before TURN data is exchanged. The data is SSL-spec compliant,
* but use hard-coded values for data that typically aught to be generated
* (for example: challenge, session-id and random fields).
*
* @author Sebastien Vincent
*/
public class GoogleTurnSSLCandidateHarvester
extends GoogleTurnCandidateHarvester
{
/**
* Data for the SSL message sent by the server.
* Data for the SSL message sent by the server ('server-hello').
*/
static final byte SSL_SERVER_HANDSHAKE[] =
{
0x16, 0x03, 0x01, 0x00, 0x4a, 0x02, 0x00, 0x00,
0x46, 0x03, 0x01, 0x42, (byte)0x85, 0x45, (byte)0xa7, 0x27,
(byte)0xa9, 0x5d, (byte)0xa0, (byte)0xb3, (byte)0xc5, (byte)0xe7, 0x53,
(byte)0xda,
0x48, 0x2b, 0x3f, (byte)0xc6, 0x5a, (byte)0xca, (byte)0x89, (byte)0xc1,
0x58, 0x52, (byte)0xa1, 0x78, 0x3c, 0x5b, 0x17, 0x46,
0x00, (byte)0x85, 0x3f, 0x20, 0x0e, (byte)0xd3, 0x06, 0x72,
0x5b, 0x5b, 0x1b, 0x5f, 0x15, (byte)0xac, 0x13, (byte)0xf9,
(byte)0x88, 0x53, (byte)0x9d, (byte)0x9b, (byte)0xe8, 0x3d, 0x7b, 0x0c,
// Content type: Handshake
0x16,
// Version: TLS 1.0
0x03, 0x01,
// Length: 74
0x00, 0x4a,
// Handshake Layer starts here
// Handshake type: Server Hello
0x02,
// Length: 70
0x00, 0x00, 0x46,
// Version: TLS 1.0
0x03, 0x01,
// 32 bytes random (well, obviously hardcoded here)
0x42, (byte)0x85, 0x45, (byte)0xa7, 0x27, (byte)0xa9,
0x5d, (byte)0xa0, (byte)0xb3, (byte)0xc5, (byte)0xe7,
0x53, (byte)0xda, 0x48, 0x2b, 0x3f, (byte)0xc6, 0x5a,
(byte)0xca, (byte)0x89, (byte)0xc1, 0x58, 0x52,
(byte)0xa1, 0x78, 0x3c, 0x5b, 0x17, 0x46, 0x00,
(byte)0x85, 0x3f,
// Session-ID length: 32
0x20,
// Session-ID
0x0e, (byte)0xd3, 0x06, 0x72, 0x5b, 0x5b, 0x1b, 0x5f,
0x15, (byte)0xac, 0x13, (byte)0xf9, (byte)0x88, 0x53,
(byte)0x9d, (byte)0x9b, (byte)0xe8, 0x3d, 0x7b, 0x0c,
0x30, 0x32, 0x6e, 0x38, 0x4d, (byte)0xa2, 0x75, 0x57,
0x41, 0x6c, 0x34, 0x5c, 0x00, 0x04, 0x00
0x41, 0x6c, 0x34, 0x5c,
// Selected Cipher suite
0x00, 0x04, // TLS_RSA_WITH_RC4_128_MD5
// Compression method: null
0x00
};
/**
* Data for the SSL message sent by the client.
* Data for the SSL message sent by the client (client-hello).
*/
public static final byte SSL_CLIENT_HANDSHAKE[] =
{
(byte)0x80, 0x46, 0x01, 0x03, 0x01, 0x00, 0x2d, 0x00,
0x00, 0x00, 0x10, 0x01, 0x00, (byte)0x80, 0x03, 0x00,
(byte)0x80, 0x07, 0x00, (byte)0xc0, 0x06, 0x00, 0x40, 0x02,
0x00, (byte)0x80, 0x04, 0x00, (byte)0x80, 0x00, 0x00, 0x04,
0x00, (byte)0xfe, (byte)0xff, 0x00, 0x00, 0x0a, 0x00, (byte)0xfe,
(byte)0xfe, 0x00, 0x00, 0x09, 0x00, 0x00, 0x64, 0x00,
0x00, 0x62, 0x00, 0x00, 0x03, 0x00, 0x00, 0x06,
0x1f, 0x17, 0x0c, (byte)0xa6, 0x2f, 0x00, 0x78, (byte)0xfc,
0x46, 0x55, 0x2e, (byte)0xb1, (byte)0x83, 0x39, (byte)0xf1, (byte)0xea
// Version: SSL 2.0 (0x0002) and length: 70
(byte)0x80, 0x46,
// Handshake message type: Client Hello
0x01,
// Version TLS 1.0
0x03, 0x01,
// Cipher Spec Length: 45
0x00, 0x2d,
// Session ID: 0
0x00, 0x00,
// Challenge length: 16
0x00, 0x10,
// Cipher spec (15 cyphers)
0x01, 0x00, (byte)0x80, // SSL2_RC4_128_WITH_MD5
0x03, 0x00, (byte)0x80, // SSL2_rc2_128_CBC_WITH_MD5
0x07, 0x00, (byte)0xc0, // SSL2_DES_192_EDE3_CBC_WITH_MD5
0x06, 0x00, 0x40, // SSL2_DES_64_CBC_WITH_MD5
0x02, 0x00, (byte)0x80, // SSL2_RC4_128_EXPORT40_WITH_MD5
0x04, 0x00, (byte)0x80, // SSL2_RC2_128_CBC_EXPORT40_WITH_MD5
0x00, 0x00, 0x04, // TLS_RSA_WITH_RC4_128_MD5
0x00, (byte)0xfe, (byte)0xff, // SSL_RSA_FIPS_WITH_3DES_EDE_CBC_SHA
0x00, 0x00, 0x0a, // TLS_RSA_WITH_3DES_EDE_CBC_SHA
0x00, (byte)0xfe, (byte)0xfe, // SSL_RSA_FIPS_WITH_DES_CBC_SHA
0x00, 0x00, 0x09, // TLS_RSA_WITH_DES_CBC_SHA
0x00, 0x00, 0x64, // TLS_RSA_EXPORT1024_WITH_RC4_56_SHA
0x00, 0x00, 0x62, // TLS_RSA_EXPORT1024_WITH_DES_CBC_SHA
0x00, 0x00, 0x03, // TLS_RSA_EXPORT_WITH_RC4_40_MD5
0x00, 0x00, 0x06, // TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5
// Challenge
0x1f, 0x17, 0x0c, (byte)0xa6, 0x2f, 0x00, 0x78, (byte)0xfc, 0x46,
0x55, 0x2e, (byte)0xb1, (byte)0x83, 0x39, (byte)0xf1, (byte)0xea
};
/**
@ -121,7 +187,7 @@ public class GoogleTurnSSLCandidateHarvester
/**
* Returns the host candidate.
* For UDP it simply returns the candidate passed as paramter
* For UDP it simply returns the candidate passed as parameter
*
* However for TCP, we cannot return the same hostCandidate because in Java
* a "server" socket cannot connect to a destination with the same local
@ -143,14 +209,14 @@ public class GoogleTurnSSLCandidateHarvester
OutputStream outputStream = sock.getOutputStream();
InputStream inputStream = sock.getInputStream();
if(sslHandshake(inputStream, outputStream))
if (sslHandshake(inputStream, outputStream))
{
Component parentComponent = hostCand.getParentComponent();
MultiplexingSocket multiplexing = new MultiplexingSocket(sock);
cand
= new HostCandidate(
new IceTcpSocketWrapper(
new MultiplexingSocket(sock)),
new IceTcpSocketWrapper(multiplexing),
parentComponent,
Transport.TCP);
parentComponent
@ -158,6 +224,12 @@ public class GoogleTurnSSLCandidateHarvester
.getParentAgent()
.getStunStack()
.addSocket(cand.getStunSocket(null));
ComponentSocket componentSocket
= parentComponent.getComponentSocket();
if (componentSocket != null)
{
componentSocket.add(multiplexing);
}
}
}
catch (Exception e)
@ -187,12 +259,12 @@ public class GoogleTurnSSLCandidateHarvester
/**
* Do the SSL handshake (send client certificate and wait for receive server
* certificate). We explicitely need <tt>InputStream</tt> and
* certificate). We explicitly need <tt>InputStream</tt> and
* <tt>OutputStream</tt> because some <tt>Socket</tt> may redefine
* getInputStream()/getOutputStream() and we need the original stream.
*
* @param inputStream <tt>InputStream</tt> of the socket
* @param outputStream <tt>OuputStream</tt> of the socket
* @param outputStream <tt>OutputStream</tt> of the socket
* @return true if the SSL handshake is done
* @throws IOException if something goes wrong
*/
@ -207,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
@ -129,17 +131,16 @@ public class HostCandidateHarvester
}
/**
* Gets the list of explicitly allowed addresses.
* Gets the list of addresses which have been explicitly allowed via
* configuration properties. To get the list of all allowed addresses,
* use {@link #getAllAllowedAddresses()}.
* @return the list of explicitly allowed addresses.
*/
public static List<InetAddress> getAllowedAddresses()
public static synchronized List<InetAddress> getAllowedAddresses()
{
synchronized (HostCandidateHarvester.class)
if (!addressFiltersInitialized)
{
if (!addressFiltersInitialized)
{
initializeAddressFilters();
}
initializeAddressFilters();
}
return allowedAddresses;
@ -149,14 +150,11 @@ public class HostCandidateHarvester
* Gets the list of blocked addresses.
* @return the list of blocked addresses.
*/
public static List<InetAddress> getBlockedAddresses()
public static synchronized List<InetAddress> getBlockedAddresses()
{
synchronized (HostCandidateHarvester.class)
if (!addressFiltersInitialized)
{
if (!addressFiltersInitialized)
{
initializeAddressFilters();
}
initializeAddressFilters();
}
return blockedAddresses;
@ -166,68 +164,109 @@ public class HostCandidateHarvester
* Initializes the lists of allowed and blocked addresses according to the
* configuration properties.
*/
private static void initializeAddressFilters()
private static synchronized void initializeAddressFilters()
{
synchronized (HostCandidateHarvester.class)
if (addressFiltersInitialized)
return;
addressFiltersInitialized = true;
String[] allowedAddressesStr
= StackProperties.getStringArray(
StackProperties.ALLOWED_ADDRESSES, ";");
if (allowedAddressesStr != null)
{
if (addressFiltersInitialized)
return;
String[] allowedAddressesStr
= StackProperties.getStringArray(
StackProperties.ALLOWED_ADDRESSES, ";");
if (allowedAddressesStr != null)
for (String addressStr : allowedAddressesStr)
{
for (String addressStr : allowedAddressesStr)
InetAddress address;
try
{
InetAddress address;
try
{
address = InetAddress.getByName(addressStr);
}
catch (Exception e)
{
logger.warning("Failed to add an allowed address: "
+ addressStr);
continue;
}
if (allowedAddresses == null)
allowedAddresses = new ArrayList<>();
allowedAddresses.add(address);
address = InetAddress.getByName(addressStr);
}
}
String[] blockedAddressesStr
= StackProperties.getStringArray(
StackProperties.BLOCKED_ADDRESSES, ";");
if (blockedAddressesStr != null)
{
for (String addressStr : blockedAddressesStr)
catch (Exception e)
{
InetAddress address;
try
{
address = InetAddress.getByName(addressStr);
}
catch (Exception e)
{
logger.warning("Failed to add a blocked address: "
+ addressStr);
continue;
}
if (blockedAddresses == null)
blockedAddresses = new ArrayList<>();
blockedAddresses.add(address);
logger.warning("Failed to add an allowed address: "
+ addressStr);
continue;
}
}
addressFiltersInitialized = true;
if (allowedAddresses == null)
allowedAddresses = new ArrayList<>();
allowedAddresses.add(address);
}
}
String[] blockedAddressesStr
= StackProperties.getStringArray(
StackProperties.BLOCKED_ADDRESSES, ";");
if (blockedAddressesStr != null)
{
for (String addressStr : blockedAddressesStr)
{
InetAddress address;
try
{
address = InetAddress.getByName(addressStr);
}
catch (Exception e)
{
logger.warning("Failed to add a blocked address: "
+ addressStr);
continue;
}
if (blockedAddresses == null)
blockedAddresses = new ArrayList<>();
blockedAddresses.add(address);
}
}
}
/**
* @return the list of all local IP addresses from all allowed network
* interfaces, which are allowed addresses.
*/
public static List<InetAddress> getAllAllowedAddresses()
{
List<InetAddress> addresses = new LinkedList<>();
try
{
for (NetworkInterface iface
: Collections.list(NetworkInterface.getNetworkInterfaces()))
{
if (NetworkUtils.isInterfaceLoopback(iface)
|| !NetworkUtils.isInterfaceUp(iface)
|| !isInterfaceAllowed(iface))
{
continue;
}
Enumeration<InetAddress> ifaceAddresses
= iface.getInetAddresses();
while (ifaceAddresses.hasMoreElements())
{
InetAddress address = ifaceAddresses.nextElement();
if (!isAddressAllowed(address))
continue;
if (!config.useIpv6() && address instanceof Inet6Address)
continue;
if (!config.useLinkLocalAddresses() && address.isLinkLocalAddress())
continue;
addresses.add(address);
}
}
}
catch (SocketException se)
{
logger.info("Failed to get network interfaces: " + se);
}
return addresses;
}
/**
@ -237,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
@ -248,7 +289,7 @@ public class HostCandidateHarvester
* @param transport transport protocol used
*
* @throws IllegalArgumentException if either <tt>minPort</tt> or
* <tt>maxPort</tt> is not a valid port number, <tt>minPort >
* <tt>maxPort</tt> is not a valid port number, <tt>minPort &gt;
* maxPort</tt> or if transport is not supported.
* @throws IOException if an error occurs while the underlying resolver lib
* is using sockets.
@ -263,24 +304,16 @@ 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;
boolean foundAtLeastOneUsableInterface = false;
boolean foundAtLeastOneUsableAddress = false;
while (interfaces.hasMoreElements())
{
NetworkInterface iface = interfaces.nextElement();
@ -292,10 +325,11 @@ public class HostCandidateHarvester
//this one is obviously not going to do
continue;
}
foundAtLeastOneUsableInterface = true;
Enumeration<InetAddress> addresses = iface.getInetAddresses();
while(addresses.hasMoreElements())
while (addresses.hasMoreElements())
{
InetAddress addr = addresses.nextElement();
@ -304,27 +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,
@ -354,13 +386,11 @@ 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)
if (transport == Transport.TCP)
{
// have to wait a client connection to add a STUN socket
// to the StunStack
@ -372,22 +402,31 @@ public class HostCandidateHarvester
// checks. In case we have enabled STUN, we are going to use
// them as well while harvesting reflexive candidates.
createAndRegisterStunSocket(candidate);
ComponentSocket componentSocket = component.getComponentSocket();
if (componentSocket != null)
{
componentSocket.add(sock);
}
}
}
}
if(!boundAtLeastOneSocket)
if (!boundAtLeastOneSocket)
{
throw new IOException(
"Failed to bind even a single host candidate for component:"
+ component
+ " preferredPort=" + preferredPort
+ " minPort=" + minPort
+ " maxPort=" + maxPort);
+ " maxPort=" + maxPort
+ " foundAtLeastOneUsableInterface="
+ foundAtLeastOneUsableInterface
+ " foundAtLeastOneUsableAddress="
+ foundAtLeastOneUsableAddress);
}
this.harvestStatistics
.stopHarvestTiming(component.getLocalCandidateCount());
this.harvestStatistics.stopHarvestTiming(component.getLocalCandidateCount());
}
/**
@ -402,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");
@ -482,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
@ -492,7 +533,7 @@ public class HostCandidateHarvester
* @return the newly created <tt>DatagramSocket</tt>.
*
* @throws IllegalArgumentException if either <tt>minPort</tt> or
* <tt>maxPort</tt> is not a valid port number or if <tt>minPort >
* <tt>maxPort</tt> is not a valid port number or if <tt>minPort &gt;
* maxPort</tt>.
* @throws IOException if an error occurs while the underlying resolver lib
* is using sockets.
@ -508,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,
@ -523,10 +575,11 @@ public class HostCandidateHarvester
sock.setReuseAddress(true);
sock.bind(new InetSocketAddress(laddr, port));
IceSocketWrapper socket
= new IceTcpServerSocketWrapper(sock,
component);
= new IceTcpServerSocketWrapper(
new DelegatingServerSocket(sock),
component);
if(logger.isLoggable(Level.FINEST))
if (logger.isLoggable(Level.FINEST))
{
logger.log(
Level.FINEST,
@ -551,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));
}
/**
@ -567,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
@ -577,7 +631,7 @@ public class HostCandidateHarvester
* @return the newly created <tt>DatagramSocket</tt>.
*
* @throws IllegalArgumentException if either <tt>minPort</tt> or
* <tt>maxPort</tt> is not a valid port number or if <tt>minPort >
* <tt>maxPort</tt> is not a valid port number or if <tt>minPort &gt;
* maxPort</tt>.
* @throws IOException if an error occurs while the underlying resolver lib
* is using sockets.
@ -594,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,
@ -609,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,
@ -656,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
@ -669,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))
@ -696,6 +766,8 @@ public class HostCandidateHarvester
+") must be between minPort (" + minPort
+ ") and maxPort (" + maxPort + ")");
}
return false;
}
/**
@ -718,18 +790,12 @@ public class HostCandidateHarvester
* @throws java.lang.IllegalStateException if there were errors during host
* candidate interface filters initialization.
*/
public static void initializeInterfaceFilters()
public static synchronized void initializeInterfaceFilters()
{
synchronized (HostCandidateHarvester.class)
{
// We want this method to run only once.
if (interfaceFiltersInitialized)
return;
interfaceFiltersInitialized = true;
// Should we hold this lock until we are done modifying the fields?
}
// We want this method to run only once.
if (interfaceFiltersInitialized)
return;
interfaceFiltersInitialized = true;
// Initialize the allowed interfaces array.
allowedInterfaces = StackProperties.getStringArray(

View File

@ -1,143 +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.*;
/**
* 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 CandidateHarvester
{
/**
* 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 = mask;
this.face = face;
}
/**
* 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.
*/
public Collection<LocalCandidate> harvest(Component component)
{
if (getMask() == null || getFace() == null)
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(getFace().getHostAddress())
|| cand.getTransport() != getFace().getTransport())
{
continue;
}
HostCandidate hostCandidate = (HostCandidate) cand;
TransportAddress mappedAddress = new TransportAddress(
getMask().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 this.mask;
}
/**
* Returns the local (face) address, or null.
* @return the local (face) address, or null.
*/
public TransportAddress getFace()
{
return this.face;
}
}

View File

@ -0,0 +1,334 @@
/*
* Copyright @ 2015-2016 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.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.
*
* The instances in the set are safe to use by any {@code Agent}s.
*
* @author Damian Minkov
* @author Boris Grozev
*/
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());
/**
* Whether {@link #harvesters} has been initialized.
*/
private static boolean initialized = false;
/**
* The list of already configured harvesters.
*/
private static MappingCandidateHarvester[] harvesters
= new MappingCandidateHarvester[0];
/**
* Whether the discovery of a public address via STUN has failed.
* It is considered failed if the configuration included at least one STUN
* server, but we failed to receive at least one valid response.
* Note that this defaults to false and is only raised after we are certain
* we failed (i.e. after our STUN transactions timeout).
*/
public static boolean stunDiscoveryFailed = false;
/**
* @return the list of configured harvesters.
*/
public static MappingCandidateHarvester[] getHarvesters()
{
initialize();
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,
* waiting for their initialization (which may include network communication
* and thus take a long time). Then it removes harvesters which failed to
* initialize properly and remove any harvesters with duplicate addresses.
*
* Three types of mapping harvesters are supported: NAT (with
* pre-configured addresses), AWS and STUN.
*/
public static synchronized void initialize()
{
if (initialized)
return;
initialized = true;
long start = System.currentTimeMillis();
List<MappingCandidateHarvester> harvesterList = new LinkedList<>();
for (HarvestConfig.StaticMapping staticMapping : config.getStaticMappings())
{
logger.info("Adding a static mapping: " + staticMapping);
// If the configuration has no port, then the port value is not used in any way. We put 9 (for "discard")
// as a filler.
int localPort = staticMapping.getLocalPort() != null ? staticMapping.getLocalPort() : 9;
int publicPort = staticMapping.getPublicPort() != null ? staticMapping.getPublicPort() : 9;
TransportAddress localAddress
= new TransportAddress(staticMapping.getLocalAddress(), localPort, Transport.UDP);
TransportAddress publicAddress
= new TransportAddress(staticMapping.getPublicAddress(), publicPort, Transport.UDP);
harvesterList.add(new StaticMappingCandidateHarvester(
publicAddress,
localAddress,
staticMapping.getName(),
staticMapping.getLocalPort() != null));
}
// AWS harvester
boolean enableAwsHarvester = config.enableAwsHarvester();
if (enableAwsHarvester && (config.forceAwsHarvester() || AwsCandidateHarvester.smellsLikeAnEC2()))
{
logger.info("Using AwsCandidateHarvester.");
harvesterList.add(new AwsCandidateHarvester());
}
// STUN harvesters
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);
// 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()]);
for (MappingCandidateHarvester harvester : harvesters)
{
logger.info("Using " + harvester);
}
logger.info("Initialized mapping harvesters (delay="
+ (System.currentTimeMillis() - start) + "ms). "
+ " stunDiscoveryFailed=" + stunDiscoveryFailed);
}
/**
* Prunes a list of mapping harvesters, removing the ones without valid
* addresses and those with duplicate addresses.
* @param harvesters the list of harvesters.
* @return the pruned list.
*/
private static List<MappingCandidateHarvester> prune(
List<MappingCandidateHarvester> harvesters)
{
List<MappingCandidateHarvester> pruned = new LinkedList<>();
for (MappingCandidateHarvester harvester : harvesters)
{
maybeAdd(harvester, pruned);
}
return pruned;
}
/**
* Adds {@code harvester} to {@code harvesters}, if it has valid addresses
* and {@code harvesters} doesn't already contain a harvester with the same
* addresses.
* @param harvester the harvester to add.
* @param harvesters the list to add to.
*/
private static void maybeAdd(
MappingCandidateHarvester harvester,
List<MappingCandidateHarvester> harvesters)
{
TransportAddress face = harvester.getFace();
TransportAddress mask = harvester.getMask();
if (face == null || mask == null || face.equals(mask))
{
logger.info("Discarding a mapping harvester: " + harvester);
return;
}
for (MappingCandidateHarvester h : harvesters)
{
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);
return;
}
}
harvesters.add(harvester);
}
/**
* Creates STUN mapping harvesters for each of the given STUN servers, and
* waits for address discovery to finish for all of them.
* @param stunServers an array of STUN server addresses (ip_address:port
* pairs).
* @return the list of those who were successful in discovering an address.
*/
private static List<StunMappingCandidateHarvester> createStunHarvesters(@NotNull List<String> stunServers)
{
List<StunMappingCandidateHarvester> stunHarvesters = new LinkedList<>();
List<Callable<StunMappingCandidateHarvester>> tasks = new LinkedList<>();
// 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);
continue;
}
int port;
try
{
port = Integer.parseInt(addressAndPort[1]);
}
catch (NumberFormatException nfe)
{
logger.severe("Invalid STUN server port: " + addressAndPort[1]);
continue;
}
TransportAddress remoteAddress
= new TransportAddress(
addressAndPort[0],
port,
Transport.UDP);
for (InetAddress localInetAddress : localAddresses)
{
if (localInetAddress instanceof Inet6Address)
{
// This is disabled, because it is broken for an unknown
// reason and it is not currently needed.
continue;
}
TransportAddress localAddress = new TransportAddress(localInetAddress, 0, Transport.UDP);
logger.info("Using " + remoteAddress + " for StunMappingCandidateHarvester (localAddress="
+ localAddress + ").");
final StunMappingCandidateHarvester stunHarvester
= new StunMappingCandidateHarvester(localAddress, remoteAddress);
Callable<StunMappingCandidateHarvester> task = () ->
{
stunHarvester.discover();
return stunHarvester;
};
tasks.add(task);
}
}
if (tasks.isEmpty())
{
logger.warning("STUN mapping harvesters are configured, but no allowed local addresses were found." +
" Not using STUN.");
return stunHarvesters;
}
// Now run discover() on all created harvesters in parallel and pick the ones which succeeded.
ExecutorService es = ExecutorFactory.createFixedThreadPool(tasks.size(), "ice4j.Harvester-executor-");
try
{
List<Future<StunMappingCandidateHarvester>> futures;
try
{
futures = es.invokeAll(tasks);
}
catch (InterruptedException ie)
{
Thread.currentThread().interrupt();
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;
}
/**
* Prevent instance creation.
*/
private MappingCandidateHarvesters()
{
}
}

View File

@ -18,12 +18,9 @@
package org.ice4j.ice.harvest;
import org.ice4j.*;
import org.ice4j.attribute.*;
import org.ice4j.ice.*;
import org.ice4j.message.*;
import org.ice4j.socket.*;
import org.ice4j.stack.*;
import org.ice4j.util.*;
import java.io.*;
import java.net.*;
@ -42,17 +39,16 @@ import java.util.logging.*;
* and associates the component's local username fragment (ufrag) with this
* candidate.
*
* When a datagram from an unknown source is received, it is parsed as a STUN
* Binding Request, and if it has a USERNAME attribute, its ufrag is extracted.
* If this ufrag is associated with a candidate of this harvester, a new socket
* is created and added to the candidate, and the remote address of the datagram
* is associated with this socket. This mapping is then used to de-multiplex
* received datagrams based on their remote address.
* When a STUN Binding Request with a given ufrag is received, if the ufrag
* matches one of the registered candidates, then a new socket is created, which
* is to receive further packets from the remote address, and the socket is
* added to the candidate.
*
* @author Boris Grozev
*/
public class SinglePortUdpHarvester
extends CandidateHarvester
extends AbstractUdpListener
implements CandidateHarvester
{
/**
* Our class logger.
@ -60,21 +56,6 @@ public class SinglePortUdpHarvester
private static final Logger logger
= Logger.getLogger(SinglePortUdpHarvester.class.getName());
/**
* The size for newly allocated <tt>Buffer</tt> instances. This limits the
* maximum size of datagrams we can receive.
*
* XXX should we increase this in case of other MTUs, or set it dynamically
* according to the available network interfaces?
*/
private static final int BUFFER_SIZE
= /* assumed MTU */ 1500 - /* IPv4 header */ 20 - /* UDP header */ 8;
/**
* The number of <tt>Buffer</tt> instances to keep in {@link #pool}.
*/
private static final int POOL_SIZE = 256;
/**
* Creates a new <tt>SinglePortUdpHarvester</tt> instance for each allowed
* IP address found on each allowed network interface, with the given port.
@ -82,58 +63,12 @@ public class SinglePortUdpHarvester
* @param port the UDP port number to use.
* @return the list of created <tt>SinglePortUdpHarvester</tt>s.
*/
public static List<SinglePortUdpHarvester>
createHarvesters(int port)
public static List<SinglePortUdpHarvester> createHarvesters(int port)
{
List<SinglePortUdpHarvester> harvesters = new LinkedList<>();
List<TransportAddress> 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
: Collections.list(NetworkInterface.getNetworkInterfaces()))
{
if (NetworkUtils.isInterfaceLoopback(iface)
|| !NetworkUtils.isInterfaceUp(iface)
|| !HostCandidateHarvester.isInterfaceAllowed(iface))
{
continue;
}
Enumeration<InetAddress> ifaceAddresses
= iface.getInetAddresses();
while (ifaceAddresses.hasMoreElements())
{
InetAddress address = ifaceAddresses.nextElement();
if (!HostCandidateHarvester.isAddressAllowed(address))
continue;
if (isIPv6Disabled && address instanceof Inet6Address)
continue;
if (isIPv6LinkLocalDisabled
&& address instanceof Inet6Address
&& address.isLinkLocalAddress())
continue;
addresses.add(
new TransportAddress(address, port, Transport.UDP));
}
}
}
catch (SocketException se)
{
logger.info("Failed to get network interfaces: " + se);
}
for (TransportAddress address : addresses)
for (TransportAddress address
: AbstractUdpListener.getAllowedAddresses(port))
{
try
{
@ -150,15 +85,6 @@ public class SinglePortUdpHarvester
return harvesters;
}
/**
* The map which keeps the known remote addresses and their associated
* candidateSockets.
* {@link #thread} is the only thread which adds new entries, while
* other threads remove entries when candidates are freed.
*/
private final Map<SocketAddress, MySocket> sockets
= new ConcurrentHashMap<>();
/**
* The map which keeps all currently active <tt>Candidate</tt>s created by
* this harvester. The keys are the local username fragments (ufrags) of
@ -168,244 +94,75 @@ public class SinglePortUdpHarvester
= new ConcurrentHashMap<>();
/**
* A pool of <tt>Buffer</tt> instances used to avoid creating of new java
* objects.
* Manages statistics about harvesting time.
*/
private final ArrayBlockingQueue<Buffer> pool
= new ArrayBlockingQueue<>(POOL_SIZE);
/**
* The local address that this harvester is bound to.
*/
private final TransportAddress localAddress;
/**
* The "main" socket that this harvester reads from.
*/
private final DatagramSocket socket;
/**
* The thread reading from {@link #socket}.
*/
private final Thread thread;
private HarvestStatistics harvestStatistics = new HarvestStatistics();
/**
* 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)
throws IOException
{
this.localAddress = localAddress;
this.socket = new DatagramSocket(localAddress);
super(localAddress);
logger.info("Initialized SinglePortUdpHarvester with address "
+ localAddress);
thread = new Thread()
{
@Override
public void run()
{
SinglePortUdpHarvester.this.runInHarvesterThread();
}
};
thread.setName(SinglePortUdpHarvester.class.getName() + " thread");
thread.setDaemon(true);
thread.start();
+ this.localAddress);
}
/**
* Perpetually reads datagrams from {@link #socket} and handles them
* accordingly.
* {@inheritDoc}
*/
public HarvestStatistics getHarvestStatistics()
{
return harvestStatistics;
}
/**
* {@inheritDoc}
*
* It is important that this blocks are little as possible (except on
* socket.receive(), of course), because it could potentially delay the
* reception of both ICE and media packets for the whole application.
* Looks for an ICE candidate registered with this harvester, which has a
* local ufrag of {@code ufrag}, and if one is found it accepts the new
* socket and adds it to the candidate.
*/
private void runInHarvesterThread()
protected void maybeAcceptNewSession(Buffer buf,
InetSocketAddress remoteAddress,
String ufrag)
{
Buffer buf;
DatagramPacket pkt = null;
Component component;
MyCandidate candidate;
MySocket destinationSocket;
InetSocketAddress remoteAddress;
do
MyCandidate candidate = candidates.get(ufrag);
if (candidate == null)
{
// TODO: implement stopping the thread with a switch?
buf = getFreeBuffer();
if (pkt == null)
pkt = new DatagramPacket(buf.buffer, 0, buf.buffer.length);
else
pkt.setData(buf.buffer, 0, buf.buffer.length);
try
{
socket.receive(pkt);
}
catch (IOException ioe)
{
logger.severe("Failed to receive from socket: " + ioe);
break;
}
buf.len = pkt.getLength();
remoteAddress = (InetSocketAddress) pkt.getSocketAddress();
destinationSocket = sockets.get(remoteAddress);
if (destinationSocket != null)
{
//make 'pkt' available for reading through destinationSocket
destinationSocket.addBuffer(buf);
}
else
{
// Packet from an unknown source. Is it a STUN Binding Request?
String ufrag = getUfrag(buf.buffer, 0, buf.len);
if (ufrag == null)
{
// Not a STUN Binding Request or doesn't have a valid
// USERNAME attribute. Drop it.
continue;
}
candidate = candidates.get(ufrag);
component
= candidate == null ? null : candidate.getParentComponent();
if (component != null)
{
// This is a STUN Binding Request destined for this
// specific Candidate/Component/Agent.
try
{
// 1. Create a socket for this remote address
MySocket newSocket = new MySocket(remoteAddress);
// 2. Set-up de-multiplexing for future datagrams
// with this address to this socket.
sockets.put(remoteAddress, newSocket);
// 3. Let the candidate and its STUN stack no about the
// new socket.
candidate.addSocket(newSocket, remoteAddress);
// 4. Add the original datagram to the new socket.
newSocket.addBuffer(buf);
}
catch (SocketException se)
{
logger.info("Could not create a socket: " + se);
}
catch (IOException ioe)
{
logger.info("Failed to handle new socket: " + ioe);
}
}
else
{
// A STUN Binding Request with an unknown USERNAME. Drop it.
}
}
}
while (true);
// TODO we are all done, clean up.
}
/**
* Gets an unused <tt>Buffer</tt> instance, creating it if necessary.
* @return an unused <tt>Buffer</tt> instance, creating it if necessary.
*/
private Buffer getFreeBuffer()
{
Buffer buf = pool.poll();
if (buf == null)
{
buf = new Buffer(new byte[BUFFER_SIZE], 0);
}
return buf;
}
/**
* Tries to parse the bytes in <tt>buf</tt> at offset <tt>off</tt> (and
* length <tt>len</tt>) as a STUN Binding Request message. If successful,
* looks for a USERNAME attribute and returns the local username fragment
* part (see RFC5245 Section 7.1.2.3).
* In case of any failure returns <tt>null</tt>.
*
* @param buf the bytes.
* @param off the offset.
* @param len the length.
* @return the local ufrag from the USERNAME attribute of the STUN message
* contained in <tt>buf</tt>, or <tt>null</tt>.
*/
private String getUfrag(byte[] buf, int off, int len)
{
// RFC5389, Section 6:
// All STUN messages MUST start with a 20-byte header followed by zero
// or more Attributes.
if (buf == null || buf.length < off + len || len < 20)
{
return null;
}
// RFC5389, Section 6:
// The magic cookie field MUST contain the fixed value 0x2112A442 in
// network byte order.
if ( !( (buf[off + 4] & 0xFF) == 0x21 &&
(buf[off + 5] & 0xFF) == 0x12 &&
(buf[off + 6] & 0xFF) == 0xA4 &&
(buf[off + 7] & 0xFF) == 0x42))
{
if (logger.isLoggable(Level.FINE))
{
logger.fine("Not a STUN packet, magic cookie not found.");
}
return null;
// A STUN Binding Request with an unknown USERNAME. Drop it.
return;
}
// This is a STUN Binding Request destined for this
// specific Candidate/Component/Agent.
try
{
Message stunMessage
= Message.decode(buf,
(char) off,
(char) len);
// 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, ufrag);
if (stunMessage.getMessageType()
!= Message.BINDING_REQUEST)
{
return null;
}
// 3. Let the candidate and its STUN stack no about the
// new socket.
candidate.addSocket(newSocket, remoteAddress);
UsernameAttribute usernameAttribute
= (UsernameAttribute)
stunMessage.getAttribute(Attribute.USERNAME);
if (usernameAttribute == null)
return null;
String usernameString
= new String(usernameAttribute.getUsername());
return usernameString.split(":")[0];
// 4. Add the original datagram to the new socket.
newSocket.addBuffer(buf);
}
catch (Exception e)
catch (SocketException se)
{
// Catch everything. We are going to log, and then drop the packet
// anyway.
if (logger.isLoggable(Level.FINE))
{
logger.fine("Failed to extract local ufrag: " + e);
}
logger.info("Could not create a socket: " + se);
}
catch (IOException ioe)
{
logger.info("Failed to handle new socket: " + ioe);
}
return null;
}
/**
@ -448,249 +205,6 @@ public class SinglePortUdpHarvester
return true;
}
/**
* Implements a <tt>DatagramSocket</tt> for the purposes of a specific
* <tt>MyCandidate</tt>.
*
* It is not bound to a specific port, but shares the same local address
* as the bound socket held by the harvester.
*/
private class MySocket
extends DatagramSocket
{
/**
* The size of {@link #queue}.
*/
private static final int QUEUE_SIZE = 128;
/**
* The FIFO which acts as a buffer for this socket.
*/
private final ArrayBlockingQueue<Buffer> queue
= new ArrayBlockingQueue<>(QUEUE_SIZE);
/**
* The {@link QueueStatistics} instance optionally used to collect and
* print detailed statistics about {@link #queue}.
*/
private final QueueStatistics queueStatistics;
/**
* The remote address that is associated with this socket.
*/
private SocketAddress remoteAddress;
/**
* The flag which indicates that this <tt>DatagramSocket</tt> has been
* closed.
*/
private boolean closed = false;
/**
* Initializes a new <tt>MySocket</tt> instance with the given
* remote address.
* @param remoteAddress the remote address to be associated with the
* new instance.
* @throws SocketException
*/
public MySocket(SocketAddress remoteAddress)
throws SocketException
{
// unbound
super((SocketAddress)null);
this.remoteAddress = remoteAddress;
if (logger.isLoggable(Level.FINEST))
{
queueStatistics = new QueueStatistics(
"SinglePort" + remoteAddress.toString().replace('/', '-'));
}
else
{
queueStatistics = null;
}
}
/**
* Adds pkt to this socket. If the queue is full, drops a packet. Does
* not block.
*/
private void addBuffer(Buffer buf)
{
synchronized (queue)
{
// Drop the first rather than the current packet, so that
// receivers can notice the loss earlier.
if (queue.size() == QUEUE_SIZE)
{
logger.info("Dropping a packet because the queue is full.");
if (queueStatistics != null)
{
queueStatistics.remove(System.currentTimeMillis());
}
queue.poll();
}
queue.offer(buf);
if (queueStatistics != null)
{
queueStatistics.add(System.currentTimeMillis());
}
queue.notifyAll();
}
}
/**
* {@inheritDoc}
*
* Delegates to the actual socket of the harvester.
*/
@Override
public InetAddress getLocalAddress()
{
return localAddress.getAddress();
}
/**
* {@inheritDoc}
*
* Delegates to the actual socket of the harvester.
*/
@Override
public int getLocalPort()
{
return localAddress.getPort();
}
/**
* {@inheritDoc}
*
* Delegates to the actual socket of the harvester.
*/
@Override
public SocketAddress getLocalSocketAddress()
{
return localAddress;
}
/**
* {@inheritDoc}
*
* Removes the association of the remote address with this socket from
* the harvester's map.
*/
@Override
public void close()
{
closed = true;
synchronized (queue)
{
// Wake up any threads still in receive()
queue.notifyAll();
}
// We could be called by the super-class constructor, in which
// case this.removeAddress is not initialized yet.
if (remoteAddress != null)
SinglePortUdpHarvester.this.sockets.remove(remoteAddress);
super.close();
}
/**
* Reads the data from the first element of {@link #queue} into
* <tt>p</tt>. Blocks until {@link #queue} has an element.
* @param p
* @throws IOException
*/
@Override
public void receive(DatagramPacket p)
throws IOException
{
Buffer buf = null;
while (buf == null)
{
if (closed)
throw new SocketException("Socket closed");
synchronized (queue)
{
if (queue.isEmpty())
{
try
{
queue.wait();
}
catch (InterruptedException ie)
{}
}
buf = queue.poll();
if (queueStatistics != null)
{
queueStatistics.remove(System.currentTimeMillis());
}
}
}
byte[] pData = p.getData();
// XXX Should we use p.setData() here with a buffer of our own?
if (pData == null || pData.length < buf.len)
throw new IOException("packet buffer not available");
System.arraycopy(buf.buffer, 0, pData, 0, buf.len);
p.setLength(buf.len);
p.setSocketAddress(remoteAddress);
pool.offer(buf);
}
/**
* {@inheritDoc}
*
* Delegates to the actual socket of the harvester.
*/
@Override
public void send(DatagramPacket p)
throws IOException
{
socket.send(p);
}
}
/**
* Represents a buffer for the purposes of <tt>SinglePortUdpHarvester</tt>.
* Wraps a byte[] and adds a length field specifying the number of elements
* actually used.
*/
private class Buffer
{
/**
* The actual data.
*/
byte[] buffer;
/**
* The number of elements of {@link #buffer} actually used.
*/
int len;
/**
* Initializes a new <tt>Buffer</tt> instance.
* @param buffer the data.
* @param len the length.
*/
private Buffer(byte[] buffer, int len)
{
this.buffer = buffer;
this.len = len;
}
}
/**
* Implements a <tt>Candidate</tt> for the purposes of this
* <tt>SinglePortUdpHarvester</tt>.
@ -713,26 +227,27 @@ public class SinglePortUdpHarvester
* The collection of <tt>IceSocketWrapper</tt>s that can potentially
* be used by the ice4j user to read/write from/to this candidate.
* The keys are the remote addresses for each socket.
*
* <p>
* There are wrappers over <tt>MultiplexedDatagramSocket</tt>s over
* a corresponding socket in {@link #sockets}.
*/
private final Map<SocketAddress, IceSocketWrapper> candidateSockets
= new HashMap<>();
= new HashMap<>();
/**
* The collection of <tt>DatagramSocket</tt>s added to this candidate.
* The keys are the remote addresses for each socket.
*
* <p>
* These are the "raw" sockets, before any wrappers are added for
* the STUN stack or the user of ice4j.
*/
private final Map<SocketAddress, DatagramSocket> sockets
= new HashMap<>();
= new HashMap<>();
/**
* Initializes a new <tt>MyCandidate</tt> instance with the given
* <tt>Component</tt> and the given local username fragment.
*
* @param component the <tt>Component</tt> for which this candidate will
* serve.
* @param ufrag the local ICE username fragment for this candidate (and
@ -746,7 +261,7 @@ public class SinglePortUdpHarvester
/**
* {@inheritDoc}
*
* <p>
* Closes all sockets in use by this <tt>LocalCandidate</tt>.
*/
@Override
@ -766,20 +281,21 @@ public class SinglePortUdpHarvester
StunStack stunStack = getStunStack();
for (Map.Entry<SocketAddress, DatagramSocket> e
: sockets.entrySet())
: sockets.entrySet())
{
DatagramSocket socket = e.getValue();
if (stunStack != null)
{
TransportAddress localAddress
= new TransportAddress(socket.getLocalAddress(),
socket.getLocalPort(),
Transport.UDP);
= new TransportAddress(socket.getLocalAddress(),
socket.getLocalPort(),
Transport.UDP);
TransportAddress remoteAddress
= new TransportAddress((InetSocketAddress) e.getKey(),
= new TransportAddress(
(InetSocketAddress) e.getKey(),
Transport.UDP);
Transport.UDP);
stunStack.removeSocket(localAddress, remoteAddress);
}
@ -792,6 +308,11 @@ public class SinglePortUdpHarvester
synchronized (candidateSockets)
{
for (IceSocketWrapper wrapper : candidateSockets.values())
{
wrapper.close();
}
candidateSockets.clear();
}
@ -801,11 +322,12 @@ public class SinglePortUdpHarvester
/**
* Adds a new <tt>Socket</tt> to this candidate, which is associated
* with a particular remote address.
*
* @param socket the socket to add.
* @param remoteAddress the remote address for the socket.
*/
private synchronized void addSocket(DatagramSocket socket,
InetSocketAddress remoteAddress)
InetSocketAddress remoteAddress)
throws IOException
{
if (freed)
@ -820,16 +342,21 @@ public class SinglePortUdpHarvester
}
IceProcessingState state
= component.getParentStream().getParentAgent().getState();
if (!IceProcessingState.WAITING.equals(state)
&& !IceProcessingState.RUNNING.equals(state))
= component.getParentStream().getParentAgent().getState();
if (state == IceProcessingState.FAILED)
{
throw new IOException(
"Agent state is " + state + ". Cannot add socket.");
"Cannot add socket to an Agent in state FAILED.");
}
else if (state != null && state.isOver()
&& logger.isLoggable(Level.FINE))
{
logger.fine(
"Adding a socket to a completed Agent, state=" + state);
}
MultiplexingDatagramSocket multiplexing
= new MultiplexingDatagramSocket(socket);
= new MultiplexingDatagramSocket(socket);
// Socket to add to the candidate
IceSocketWrapper candidateSocket
@ -838,18 +365,30 @@ public class SinglePortUdpHarvester
// STUN-only filtered socket to add to the StunStack
IceSocketWrapper stunSocket
= new IceUdpSocketWrapper(
multiplexing.getSocket(new StunDatagramPacketFilter()));
multiplexing.getSocket(new StunDatagramPacketFilter()));
component.getParentStream().getParentAgent().getStunStack()
.addSocket(
stunSocket,
new TransportAddress(remoteAddress, Transport.UDP));
.addSocket(
stunSocket,
new TransportAddress(remoteAddress, Transport.UDP));
MergingDatagramSocket componentSocket
= component.getComponentSocket();
if (componentSocket != null)
{
componentSocket.add(multiplexing);
}
// XXX is this necessary?
synchronized (candidateSockets)
{
candidateSockets.put(remoteAddress, candidateSocket);
IceSocketWrapper oldSocket
= candidateSockets.put(remoteAddress, candidateSocket);
if (oldSocket != null)
{
logger.warning("Replacing the socket for remote address "
+ remoteAddress);
oldSocket.close();
}
}
// XXX is this necessary?
@ -858,14 +397,17 @@ public class SinglePortUdpHarvester
sockets.put(remoteAddress, socket);
}
}
/**
* {@inheritDoc}
*/
@Override
public IceSocketWrapper getIceSocketWrapper(SocketAddress remoteAddress)
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)
@ -1433,7 +1433,7 @@ public class StunCandidateHarvest
* instance. The <tt>StunCandidateHarvest</tt> is referenced by a
* <tt>WeakReference</tt> in an attempt to reduce the risk that the
* <tt>Thread</tt> may live regardless of the fact that the specified
* <tt>StunCandidateHarvest<tt> may no longer be reachable.
* <tt>StunCandidateHarvest</tt> may no longer be reachable.
*/
private final WeakReference<StunCandidateHarvest> harvest;

View File

@ -36,7 +36,7 @@ import org.ice4j.stack.*;
* @author Lyubomir Marinov
*/
public class StunCandidateHarvester
extends CandidateHarvester
extends AbstractCandidateHarvester
{
/**
@ -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();
}
}
@ -234,10 +234,14 @@ public class StunCandidateHarvester
* @return the <tt>LocalCandidate</tt>s gathered by this
* <tt>CandidateHarvester</tt>
*/
@Override
public Collection<LocalCandidate> harvest(Component component)
{
logger.fine("starting " + component.toShortString()
+ " harvest for: " + toString() );
if (logger.isLoggable(Level.FINE))
{
logger.fine("starting " + component.toShortString()
+ " harvest for: " + toString());
}
stunStack = component.getParentStream().getParentAgent().getStunStack();
for (Candidate<?> cand : component.getLocalCandidates())
@ -286,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());
}
@ -309,7 +313,7 @@ public class StunCandidateHarvester
HostCandidate cand = getHostCandidate(hostCand);
if(cand == null)
if (cand == null)
{
logger.info(
"server/candidate address type mismatch,"
@ -437,21 +441,32 @@ public class StunCandidateHarvester
*/
protected HostCandidate getHostCandidate(HostCandidate hostCand)
{
HostCandidate cand = null;
HostCandidate cand;
// create a new TCP HostCandidate
if(hostCand.getTransport() == Transport.TCP)
if (hostCand.getTransport() == Transport.TCP)
{
try
{
Socket sock = new Socket(stunServer.getAddress(),
stunServer.getPort());
cand = new HostCandidate(new IceTcpSocketWrapper(
new MultiplexingSocket(sock)),
hostCand.getParentComponent(), Transport.TCP);
hostCand.getParentComponent().getParentStream().
MultiplexingSocket multiplexing = new MultiplexingSocket(sock);
Component component = hostCand.getParentComponent();
cand
= new HostCandidate(
new IceTcpSocketWrapper(multiplexing),
component,
Transport.TCP);
component.getParentStream().
getParentAgent().getStunStack().addSocket(
cand.getStunSocket(null));
ComponentSocket componentSocket
= component.getComponentSocket();
if (componentSocket != null)
{
componentSocket.add(multiplexing);
}
}
catch(Exception io)
{

View File

@ -18,15 +18,18 @@
package org.ice4j.ice.harvest;
import org.ice4j.*;
import org.ice4j.ice.*;
import org.ice4j.socket.*;
import org.ice4j.stunclient.*;
import org.jetbrains.annotations.*;
import java.net.*;
import java.util.logging.*;
/**
* A MappingCandidateHarvester which use a list of pre-configured 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
*/
public class StunMappingCandidateHarvester
extends MappingCandidateHarvester
@ -35,135 +38,97 @@ 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());
/**
* The addresses that we will use as a mask
*/
private static TransportAddress mask;
/**
* The addresses that we will be masking
*/
private static TransportAddress face;
/**
* Whether we have already checked and found the mapping addresses.
*/
private static boolean addressChecked = false;
private static final Logger logger = Logger.getLogger(StunMappingCandidateHarvester.class.getName());
/**
* The list of servers we will use to discover our public address.
*/
private static String[] stunServers;
private final TransportAddress stunServerAddress;
/**
* Creates a mapping harvester with the specified <tt>mask</tt>
* @param servers list of stun servers in the form address:port
* The local address this {@link StunMappingCandidateHarvester} was initialized with, and which will be used to
* communicate to STUN servers.
*/
public StunMappingCandidateHarvester(String[] servers)
@NotNull
private TransportAddress localAddress;
/**
* The public address discovered through STUN, if any.
*/
private TransportAddress publicAddress = null;
/**
* Initializes a new {@link StunMappingCandidateHarvester} instance with
* a given local address and a STUN server address. Note that the actual
* discovery of the public address needs to be initiated to a separate call
* to {@link #discover()}.
* @param localAddress The local address.
* @param stunServerAddress The address of the STUN server.
*/
public StunMappingCandidateHarvester(
@NotNull TransportAddress localAddress,
TransportAddress stunServerAddress)
{
super(null, null);
StunMappingCandidateHarvester.stunServers = servers;
// we have the list of addresses lets, try discovering
obtainAddresses();
super("stun");
this.localAddress = localAddress;
this.stunServerAddress = stunServerAddress;
}
/**
* Creates a mapping harvester with the specified <tt>mask</tt>
* Attempts to discover the the public address (mask) via the STUN server.
* Note that this will block until we either receive a response from the
* STUN server, or a timeout occurs.
*/
public StunMappingCandidateHarvester()
public void discover()
{
super(null, null);
}
/**
* Uses the pre-configured list of stun servers to discover our public
* address. Uses the first successful one and ignore the rest.
* Learn the private (face) and public (mask) addresses of this instance.
*/
private static synchronized void obtainAddresses()
{
if (addressChecked)
return;
addressChecked = true;
try
{
for (String server : stunServers)
SimpleAddressDetector sad
= new SimpleAddressDetector(stunServerAddress);
sad.start();
IceSocketWrapper localSocket = new IceUdpSocketWrapper(new DatagramSocket(localAddress));
publicAddress = sad.getMappingFor(localSocket);
/* Record bound address as face. */
SocketAddress boundAddr = localSocket.getLocalSocketAddress();
if (boundAddr instanceof InetSocketAddress)
{
String[] addressAndPort = server.split(":");
StunCandidateHarvester stunHarv = new StunCandidateHarvester(
new TransportAddress(
addressAndPort[0],
Integer.valueOf(addressAndPort[1]),
Transport.UDP));
Agent agent = new Agent();
agent.setTrickling(false);
agent.addCandidateHarvester(stunHarv);
IceMediaStream stream = agent.createMediaStream("audio");
// local ports does not matter, just to be something
// out of the default used range
agent.createComponent(
stream, Transport.UDP, 32020, 32020, 32020 + 100);
IceMediaStream iceMediaStream = agent.getStreams().get(0);
TransportAddress addr = iceMediaStream
.getComponent(Component.RTP).getDefaultCandidate()
.getTransportAddress();
mask = addr;
Candidate<?> candidate =
iceMediaStream.getComponents().get(0).getDefaultCandidate();
face = candidate.getHostAddress();
agent.free();
if (mask != null && face != null)
break;
localAddress = new TransportAddress((InetSocketAddress)boundAddr, localAddress.getTransport());
}
logger.info("Detected through stun local IP: " + face);
logger.info("Detected through stun public IP: " + mask);
if (publicAddress != null)
{
logger.info("Discovered public address " + publicAddress
+ " from STUN server " + stunServerAddress
+ " using local address " + localSocket);
}
}
catch (Exception exc)
{
//whatever happens, we just log and fail
logger.log(Level.INFO, "We failed to obtain addresses "
+ "for the following reason: ", exc);
//whatever happens, we just log
logger.log(Level.INFO, "We failed to obtain addresses for the following reason: ", exc);
}
}
/**
* Returns the public (mask) address, or null.
* @return the public (mask) address, or null.
*/
public TransportAddress getMask()
{
if (mask == null)
{
obtainAddresses();
}
return mask;
}
/**
* Returns the local (face) address, or null.
* @return the local (face) address, or null.
* {@inheritDoc}
*/
@Nullable
@Override
public TransportAddress getFace()
{
if (face == null)
{
obtainAddresses();
}
return face;
return localAddress;
}
/**
* {@inheritDoc}
*/
@Nullable
@Override
public TransportAddress getMask()
{
return publicAddress;
}
}

File diff suppressed because it is too large Load Diff

View File

@ -258,6 +258,13 @@ public class TurnCandidateHarvest
harvester.getStunStack().addSocket(
relayedCandidate.getStunSocket(null));
ComponentSocket componentSocket
= relayedCandidate.getParentComponent().getComponentSocket();
if (componentSocket != null)
{
componentSocket.add(
relayedCandidate.getCandidateIceSocketWrapper());
}
addCandidate(relayedCandidate);
}
}

View File

@ -34,7 +34,7 @@ import org.bitlet.weupnp.*;
* @author Sebastien Vincent
*/
public class UPNPHarvester
extends CandidateHarvester
extends AbstractCandidateHarvester
{
/**
* The logger.
@ -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);
}
@ -203,25 +203,29 @@ public class UPNPHarvester
* @param socket local socket
* @param externalIP external IP address
* @param port local port
* @param cmp parent component
* @param component parent component
* @param device the UPnP gateway device
* @return a new <tt>UPNPCandidate</tt> instance which
* represents the specified <tt>TransportAddress</tt>
* @throws Exception if something goes wrong during candidate creation
*/
public List<LocalCandidate> createUPNPCandidate(IceSocketWrapper socket,
String externalIP, int port, Component cmp, GatewayDevice device)
throws Exception
private List<LocalCandidate> createUPNPCandidate(IceSocketWrapper socket,
String externalIP, int port, Component component, GatewayDevice device)
{
List<LocalCandidate> ret = new ArrayList<>();
TransportAddress addr
= new TransportAddress(externalIP, port, Transport.UDP);
HostCandidate base = new HostCandidate(socket, cmp);
HostCandidate base = new HostCandidate(socket, component);
UPNPCandidate candidate = new UPNPCandidate(addr, base, cmp, device);
UPNPCandidate candidate
= new UPNPCandidate(addr, base, component, device);
IceSocketWrapper stunSocket = candidate.getStunSocket(null);
candidate.getStunStack().addSocket(stunSocket);
ComponentSocket componentSocket = component.getComponentSocket();
if (componentSocket != null)
{
componentSocket.add(candidate.getCandidateIceSocketWrapper());
}
ret.add(candidate);
ret.add(base);
@ -276,7 +280,7 @@ public class UPNPHarvester
gd.discover();
if(gd.getValidGateway() != null)
if (gd.getValidGateway() != null)
{
device = gd.getValidGateway();
}
@ -290,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

@ -100,27 +100,26 @@ public class ChannelData
}
/**
* Get the data length.
* Get the data length (without padding).
*
* @return data length
*/
public char getDataLength()
{
char length = 0;
if(data == null)
{
return length;
}
/* pad to a multiple of four */
if((length % 4) > 0)
{
length += (4 - (length % 4));
}
if (data == null)
return 0;
return (char)data.length;
}
/**
* @return num padded to 4
*/
private static int padTo4(int num)
{
return (num + 3) & ~3;
}
/**
* Determines whether a specific channel number is in the valid channel
* number range defined by the TURN RFC.
@ -136,17 +135,31 @@ public class ChannelData
}
/**
* Returns a binary representation of this message.
* @return a binary representation of this message.
* Returns a non padded binary representation of this message.
* @return a non padded binary representation of this message.
* @throws StunException if the channel number is invalid
* @deprecated
*/
public byte[] encode() throws StunException
{
char dataLength = getDataLength();
return encode(false);
}
/**
* Returns a binary representation of this message.
* @param pad determine if we pad this message
* @return a binary representation of this message.
* @throws StunException if the channel number is invalid
*/
public byte[] encode(boolean pad) throws StunException
{
int dataLength = getDataLength();
if (pad)
dataLength = padTo4(dataLength);
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");
}
@ -159,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);
}
@ -175,28 +188,42 @@ public class ChannelData
* @return a Message object constructed from the binMessage array
* @throws StunException ILLEGAL_ARGUMENT if one or more of the arguments
* have invalid values.
* @deprecated
*/
public static ChannelData decode(byte binMessage[], char offset, char arrayLen) throws StunException
{
return decode(binMessage, offset);
}
/**
* Constructs a message from its binary representation.
* @param binMessage the binary array that contains the encoded message
* @param offset the index where the message starts.
* @return a Message object constructed from the binMessage array
* @throws StunException ILLEGAL_ARGUMENT if one or more of the arguments
* have invalid values.
*/
public static ChannelData decode(byte binMessage[], char offset) throws StunException
{
char msgLen = 0;
char channelNumber = 0;
ChannelData channelData = null;
byte data[] = null;
if(arrayLen < 4)
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");
}
msgLen = (char)((binMessage[offset++]<<8) | (binMessage[offset++]&0xFF));
if(msgLen != (binMessage.length - 4))
if (msgLen > (binMessage.length - offset))
{
throw new StunException(StunException.ILLEGAL_ARGUMENT, "Size mismatch");
}

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.*;
/**
@ -45,26 +46,31 @@ public abstract class Message
private static final Logger logger
= Logger.getLogger(Message.class.getName());
/* general declaration */
/**
* The mask of the two bits from the message type structure, which indicate
* the message class.
*/
private static final char MESSAGE_CLASS_MASK = 0x0110;
/**
* STUN request code.
*/
public static final char STUN_REQUEST = 0x0000;
public static final char STUN_REQUEST = 0x0000;
/**
* STUN indication code.
*/
public static final char STUN_INDICATION = 0x0010;
public static final char STUN_INDICATION = 0x0010;
/**
* STUN success response code.
*/
public static final char STUN_SUCCESS_RESP = 0x0100;
public static final char STUN_SUCCESS_RESP = 0x0100;
/**
* STUN error response code.
*/
public static final char STUN_ERROR_RESP = 0x0110;
public static final char STUN_ERROR_RESP = 0x0110;
/* STUN methods */
/**
@ -75,62 +81,62 @@ public abstract class Message
/**
* STUN binding request code.
*/
public static final char BINDING_REQUEST =
(STUN_METHOD_BINDING | STUN_REQUEST);
public static final char BINDING_REQUEST
= (STUN_METHOD_BINDING | STUN_REQUEST);
/**
* STUN binding success response code.
*/
public static final char BINDING_SUCCESS_RESPONSE =
(STUN_METHOD_BINDING | STUN_SUCCESS_RESP);
public static final char BINDING_SUCCESS_RESPONSE
= (STUN_METHOD_BINDING | STUN_SUCCESS_RESP);
/**
* STUN binding error response code.
*/
public static final char BINDING_ERROR_RESPONSE =
(STUN_METHOD_BINDING | STUN_ERROR_RESP);
public static final char BINDING_ERROR_RESPONSE
= (STUN_METHOD_BINDING | STUN_ERROR_RESP);
/**
* STUN binding request code.
*/
public static final char BINDING_INDICATION =
(STUN_METHOD_BINDING | STUN_INDICATION);
public static final char BINDING_INDICATION
= (STUN_METHOD_BINDING | STUN_INDICATION);
/**
* STUN shared secret request.
*/
public static final char SHARED_SECRET_REQUEST = 0x0002;
public static final char SHARED_SECRET_REQUEST = 0x0002;
/**
* STUN shared secret response.
*/
public static final char SHARED_SECRET_RESPONSE = 0x0102;
public static final char SHARED_SECRET_RESPONSE = 0x0102;
/**
* STUN shared secret error response.
*/
public static final char SHARED_SECRET_ERROR_RESPONSE = 0x0112;
public static final char SHARED_SECRET_ERROR_RESPONSE = 0x0112;
/* TURN methods */
/**
* TURN allocate method code.
*/
public static final char TURN_METHOD_ALLOCATE = 0x0003;
public static final char TURN_METHOD_ALLOCATE = 0x0003;
/**
* TURN refresh method code.
*/
public static final char TURN_METHOD_REFRESH = 0x0004;
public static final char TURN_METHOD_REFRESH = 0x0004;
/**
* TURN send method code.
*/
public static final char TURN_METHOD_SEND = 0x0006;
public static final char TURN_METHOD_SEND = 0x0006;
/**
* TURN data method code.
*/
public static final char TURN_METHOD_DATA = 0x0007;
public static final char TURN_METHOD_DATA = 0x0007;
/**
* TURN CreatePermission method code.
@ -140,7 +146,7 @@ public abstract class Message
/**
* TURN ChannelBind method code.
*/
public static final char TURN_METHOD_CHANNELBIND = 0x0009;
public static final char TURN_METHOD_CHANNELBIND = 0x0009;
/**
* TURN Connect method code.
@ -160,134 +166,134 @@ public abstract class Message
/**
* TURN allocate request code.
*/
public static final char ALLOCATE_REQUEST =
(TURN_METHOD_ALLOCATE | STUN_REQUEST);
public static final char ALLOCATE_REQUEST
= (TURN_METHOD_ALLOCATE | STUN_REQUEST);
/**
* TURN allocate response code.
*/
public static final char ALLOCATE_RESPONSE =
(TURN_METHOD_ALLOCATE | STUN_SUCCESS_RESP);
public static final char ALLOCATE_RESPONSE
= (TURN_METHOD_ALLOCATE | STUN_SUCCESS_RESP);
/**
* TURN allocate error response code.
*/
public static final char ALLOCATE_ERROR_RESPONSE =
(TURN_METHOD_ALLOCATE | STUN_ERROR_RESP);
public static final char ALLOCATE_ERROR_RESPONSE
= (TURN_METHOD_ALLOCATE | STUN_ERROR_RESP);
/**
* TURN refresh request code.
*/
public static final char REFRESH_REQUEST =
(TURN_METHOD_REFRESH | STUN_REQUEST);
public static final char REFRESH_REQUEST
= (TURN_METHOD_REFRESH | STUN_REQUEST);
/**
* TURN allocate refresh request code.
*/
public static final char ALLOCATE_REFRESH_REQUEST =
(TURN_METHOD_ALLOCATE | REFRESH_REQUEST);
public static final char ALLOCATE_REFRESH_REQUEST
= (TURN_METHOD_ALLOCATE | REFRESH_REQUEST);
/**
* TURN refresh response code.
*/
public static final char REFRESH_RESPONSE =
(TURN_METHOD_REFRESH | STUN_SUCCESS_RESP);
public static final char REFRESH_RESPONSE
= (TURN_METHOD_REFRESH | STUN_SUCCESS_RESP);
/**
* TURN refresh error response code.
*/
public static final char REFRESH_ERROR_RESPONSE =
(TURN_METHOD_REFRESH | STUN_ERROR_RESP);
public static final char REFRESH_ERROR_RESPONSE
= (TURN_METHOD_REFRESH | STUN_ERROR_RESP);
/**
* TURN ChannelBind request code.
*/
public static final char CHANNELBIND_REQUEST =
(TURN_METHOD_CHANNELBIND | STUN_REQUEST);
public static final char CHANNELBIND_REQUEST
= (TURN_METHOD_CHANNELBIND | STUN_REQUEST);
/**
* TURN ChannelBind response code.
*/
public static final char CHANNELBIND_RESPONSE =
(TURN_METHOD_CHANNELBIND | STUN_SUCCESS_RESP);
public static final char CHANNELBIND_RESPONSE
= (TURN_METHOD_CHANNELBIND | STUN_SUCCESS_RESP);
/**
* TURN ChannelBind error response code.
*/
public static final char CHANNELBIND_ERROR_RESPONSE =
(TURN_METHOD_CHANNELBIND | STUN_ERROR_RESP);
public static final char CHANNELBIND_ERROR_RESPONSE
= (TURN_METHOD_CHANNELBIND | STUN_ERROR_RESP);
/**
* TURN CreatePermission request code.
*/
public static final char CREATEPERMISSION_REQUEST =
(TURN_METHOD_CREATEPERMISSION | STUN_REQUEST);
public static final char CREATEPERMISSION_REQUEST
= (TURN_METHOD_CREATEPERMISSION | STUN_REQUEST);
/**
* TURN CreatePermission response code.
*/
public static final char CREATEPERMISSION_RESPONSE =
(TURN_METHOD_CREATEPERMISSION | STUN_SUCCESS_RESP);
public static final char CREATEPERMISSION_RESPONSE
= (TURN_METHOD_CREATEPERMISSION | STUN_SUCCESS_RESP);
/**
* TURN CreatePermission error response code.
*/
public static final char CREATEPERMISSION_ERROR_RESPONSE =
(TURN_METHOD_CREATEPERMISSION | STUN_ERROR_RESP);
public static final char CREATEPERMISSION_ERROR_RESPONSE
= (TURN_METHOD_CREATEPERMISSION | STUN_ERROR_RESP);
/**
* TURN send indication code.
*/
public static final char SEND_INDICATION =
(TURN_METHOD_SEND | STUN_INDICATION);
public static final char SEND_INDICATION
= (TURN_METHOD_SEND | STUN_INDICATION);
/**
* TURN data indication code.
*/
public static final char DATA_INDICATION =
(TURN_METHOD_DATA | STUN_INDICATION);
public static final char DATA_INDICATION
= (TURN_METHOD_DATA | STUN_INDICATION);
/**
* TURN Connect Request code.
*/
public static final char CONNECT_REQUEST =
(TURN_METHOD_CONNECT | STUN_REQUEST);
public static final char CONNECT_REQUEST
= (TURN_METHOD_CONNECT | STUN_REQUEST);
/**
* TURN Connect Success Response code.
*/
public static final char CONNECT_RESPONSE =
(TURN_METHOD_CONNECT | STUN_SUCCESS_RESP);
public static final char CONNECT_RESPONSE
= (TURN_METHOD_CONNECT | STUN_SUCCESS_RESP);
/**
* TURN Connect Error Response code.
*/
public static final char CONNECT_ERROR_RESPONSE =
(TURN_METHOD_CONNECT | STUN_ERROR_RESP);
public static final char CONNECT_ERROR_RESPONSE
= (TURN_METHOD_CONNECT | STUN_ERROR_RESP);
/**
* TURN Connection Bind Request code.
*/
public static final char CONNECTION_BIND_REQUEST =
(TURN_METHOD_CONNECTION_BIND | STUN_REQUEST);
public static final char CONNECTION_BIND_REQUEST
= (TURN_METHOD_CONNECTION_BIND | STUN_REQUEST);
/**
* TURN Connection Bind Success Response code.
*/
public static final char CONNECTION_BIND_SUCCESS_RESPONSE =
(TURN_METHOD_CONNECTION_BIND | STUN_SUCCESS_RESP);
public static final char CONNECTION_BIND_SUCCESS_RESPONSE
= (TURN_METHOD_CONNECTION_BIND | STUN_SUCCESS_RESP);
/**
* TURN Connection Bind error code.
*/
public static final char CONNECTION_BIND_ERROR_RESPONSE =
(TURN_METHOD_CONNECTION_BIND | STUN_ERROR_RESP);
public static final char CONNECTION_BIND_ERROR_RESPONSE
= (TURN_METHOD_CONNECTION_BIND | STUN_ERROR_RESP);
/**
* TURN Connection Attempt Indication code.
*/
public static final char CONNECTION_ATTEMPT_INDICATION =
(TURN_METHOD_CONNECTION_ATTEMPT | STUN_INDICATION);
public static final char CONNECTION_ATTEMPT_INDICATION
= (TURN_METHOD_CONNECTION_ATTEMPT | STUN_INDICATION);
/* Old TURN method */
/**
@ -341,7 +347,7 @@ public abstract class Message
* so we'll be using a <tt>LinkedHashMap</tt>
*/
//not sure this is the best solution but I'm trying to keep entry order
protected LinkedHashMap<Character, Attribute> attributes
protected final LinkedHashMap<Character, Attribute> attributes
= new LinkedHashMap<>();
/**
@ -361,41 +367,41 @@ public abstract class Message
*
* For classic STUN :
*
*
* Binding Shared Shared Shared <br/>
* Binding Binding Error Secret Secret Secret <br/>
* Att. Req. Resp. Resp. Req. Resp. Error <br/>
* Resp. <br/>
* _____________________________________________________________________ <br/>
* MAPPED-ADDRESS N/A M N/A N/A N/A N/A <br/>
* RESPONSE-ADDRESS O N/A N/A N/A N/A N/A <br/>
* CHANGE-REQUEST O N/A N/A N/A N/A N/A <br/>
* SOURCE-ADDRESS N/A M N/A N/A N/A N/A <br/>
* CHANGED-ADDRESS N/A M N/A N/A N/A N/A <br/>
* USERNAME O N/A N/A N/A M N/A <br/>
* PASSWORD N/A N/A N/A N/A M N/A <br/>
* MESSAGE-INTEGRITY O O N/A N/A N/A N/A <br/>
* ERROR-CODE N/A N/A M N/A N/A M <br/>
* UNKNOWN-ATTRIBUTES N/A N/A C N/A N/A C <br/>
* REFLECTED-FROM N/A C N/A N/A N/A N/A <br/>
* XOR-MAPPED-ADDRESS N/A M N/A N/A N/A N/A <br/>
* XOR-ONLY O N/A N/A N/A N/A N/A <br/>
* SOFTWARE N/A O O N/A O O <br/>
*
* <pre>
* Binding Shared Shared Shared
* Binding Binding Error Secret Secret Secret
* Att. Req. Resp. Resp. Req. Resp. Error
* Resp.
* _____________________________________________________________________
* MAPPED-ADDRESS N/A M N/A N/A N/A N/A
* RESPONSE-ADDRESS O N/A N/A N/A N/A N/A
* CHANGE-REQUEST O N/A N/A N/A N/A N/A
* SOURCE-ADDRESS N/A M N/A N/A N/A N/A
* CHANGED-ADDRESS N/A M N/A N/A N/A N/A
* USERNAME O N/A N/A N/A M N/A
* PASSWORD N/A N/A N/A N/A M N/A
* MESSAGE-INTEGRITY O O N/A N/A N/A N/A
* ERROR-CODE N/A N/A M N/A N/A M
* UNKNOWN-ATTRIBUTES N/A N/A C N/A N/A C
* REFLECTED-FROM N/A C N/A N/A N/A N/A
* XOR-MAPPED-ADDRESS N/A M N/A N/A N/A N/A
* XOR-ONLY O N/A N/A N/A N/A N/A
* SOFTWARE N/A O O N/A O O
* </pre>
*/
public static final byte N_A = 0;
private static final byte N_A = 0;
/**
* C means it's conditional based on some other aspect of the message.
*/
public static final byte C = 1;
private static final byte C = 1;
/**
* O means the parameter is optional.
*
* @see Message#N_A
*/
public static final byte O = 2;
public static final byte O = 2;
/**
* M indicates that inclusion of the attribute in the message is
@ -403,7 +409,7 @@ public abstract class Message
*
* @see Message#N_A
*/
public static final byte M = 3;
public static final byte M = 3;
//Message indices
protected static final byte BINDING_REQUEST_PRESENTITY_INDEX = 0;
@ -464,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.
@ -504,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.
@ -682,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,
@ -710,13 +718,13 @@ public abstract class Message
*
* @param attributeType the id of the attribute to check .
*
* @return Message.N_A - for not applicable <br/>
* Message.C - for case depending <br/>
* Message.N_A - for not applicable <br/>
* @return Message.N_A - for not applicable <br>
* Message.C - for case depending <br>
* Message.N_A - for not applicable <br>
*/
protected byte getAttributePresentity(char attributeType)
{
if(!rfc3489CompatibilityMode)
if (!rfc3489CompatibilityMode)
return O;
byte msgIndex = -1;
@ -867,23 +875,22 @@ public abstract class Message
@Override
public boolean equals(Object obj)
{
if(!(obj instanceof Message)
|| obj == null)
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;
}
@ -926,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;
@ -1014,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)
@ -1053,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(binMessage == null || 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");
@ -1073,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();
@ -1084,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);
@ -1135,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));
@ -1148,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));
}
@ -1245,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!");
}
@ -1261,7 +1268,7 @@ public abstract class Message
*/
public static boolean isErrorResponseType(char type)
{
return ((type & 0x0110) == STUN_ERROR_RESP);
return ((type & MESSAGE_CLASS_MASK) == STUN_ERROR_RESP);
}
/**
@ -1271,7 +1278,7 @@ public abstract class Message
*/
public static boolean isSuccessResponseType(char type)
{
return ((type & 0x0110) == STUN_SUCCESS_RESP);
return ((type & MESSAGE_CLASS_MASK) == STUN_SUCCESS_RESP);
}
/**
@ -1282,18 +1289,18 @@ 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));
}
/**
* Determines if the message type is Indication.
* @param type type to test
* @return true if the type is Indictation, false otherwise
* @return true if the type is Indication, false otherwise
*/
public static boolean isIndicationType(char type)
{
return ((type & 0x0110) == STUN_INDICATION);
return ((type & MESSAGE_CLASS_MASK) == STUN_INDICATION);
}
/**
@ -1304,8 +1311,8 @@ public abstract class Message
*/
public static boolean isRequestType(char type)
{
/* return !isResponseType(type); */
return ((type & 0x0110) == 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);
}
/**
@ -1353,6 +1358,7 @@ public class MessageFactory
* mandatory headers.
* @throws IllegalArgumentException if there was something wrong with the
* way we are trying to create the Request.
* @throws StunException when the transaction id is not valid.
*/
public static Indication createConnectionAttemptIndication(
int connectionIdValue, TransportAddress peerAddress,

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

@ -364,9 +364,9 @@ public class PseudoTCPBase
}
/**
* Set the MTU value
* Set the MTU (maximum transmission unit) value
*
* @param mtu
* @param mtu the new MTU value
*/
public void notifyMTU(int mtu)
{
@ -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.
@ -680,11 +680,13 @@ public class PseudoTCPBase
}
/**
*
* @param buffer
* @param len
* Reads the data available in receive buffer. This method returns 0 if
* there's no data available at the moment.
*
* @param buffer destination buffer
* @param len bytes to be read
* @return received byte count
* @throws IOException
* @throws IOException if the protocol is not in the connected state
*/
public int recv(byte[] buffer, int len) throws IOException
{
@ -692,11 +694,12 @@ public class PseudoTCPBase
}
/**
*
* @param buffer
* @param len
* Enqueues data in the send buffer
*
* @param buffer source data buffer
* @param len bytes count to be sent
* @return sent byte count
* @throws IOException
* @throws IOException if the protocol is not in connected state
*/
public int send(byte[] buffer, int len) throws IOException
{
@ -875,6 +878,9 @@ public class PseudoTCPBase
/**
* Method can be used in debugging utilities to parse PTCP segment
* @param buffer data to parse
* @param size length of the data in the buffer
* @return the parsed segment
*/
public static Segment parseSeg(byte[] buffer, int size)
{
@ -898,17 +904,17 @@ public class PseudoTCPBase
return seg;
}
/**
* Can be used to convert segments to text
*
* @param seg
* @param seg the {@link Segment} to format
* @return segment in readable text form
*/
public static String segToStr(Segment seg)
{
String data="data: ";
for(byte b : seg.data)
for (byte b : seg.data)
{
data += b;
}
@ -1058,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;
}
@ -1246,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
@ -1751,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;
}
@ -1952,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)
@ -2117,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;
}

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