From 55082823ddb09882e3d39f7d12b8d70cbe78096e Mon Sep 17 00:00:00 2001 From: emcho Date: Fri, 21 Feb 2014 00:45:49 +0000 Subject: [PATCH] Adds a harvester for Amazon AWS EC2 instances. Adds a mapping harvester for manual configuration on NATed servers. Removes legacy support for Google ICE. Hooray --- build.xml | 33 ++- src/org/ice4j/ice/Agent.java | 155 +---------- src/org/ice4j/ice/CandidateExtendedType.java | 18 +- src/org/ice4j/ice/CheckList.java | 9 +- src/org/ice4j/ice/CompatibilityMode.java | 25 -- src/org/ice4j/ice/Component.java | 69 +---- .../ice4j/ice/ConnectivityCheckClient.java | 256 +++++------------- .../ice4j/ice/ConnectivityCheckServer.java | 113 ++------ src/org/ice4j/ice/FoundationsRegistry.java | 7 +- src/org/ice4j/ice/IceMediaStream.java | 74 +---- .../ice/harvest/AwsCandidateHarvester.java | 217 +++++++++++++++ .../harvest/MappingCandidateHarvester.java | 110 ++++++++ src/org/ice4j/message/Message.java | 17 +- src/org/ice4j/stack/StunStack.java | 38 +-- test/test/AwsTest.java | 78 ++++++ test/test/Ice.java | 83 ++++-- 16 files changed, 622 insertions(+), 680 deletions(-) delete mode 100644 src/org/ice4j/ice/CompatibilityMode.java create mode 100644 src/org/ice4j/ice/harvest/AwsCandidateHarvester.java create mode 100644 src/org/ice4j/ice/harvest/MappingCandidateHarvester.java create mode 100644 test/test/AwsTest.java diff --git a/build.xml b/build.xml index 0d837f4..13f5e87 100644 --- a/build.xml +++ b/build.xml @@ -28,6 +28,7 @@ + @@ -41,12 +42,16 @@ nowarn="false" optimize="true" target="1.5" - source="1.5"> + source="1.5" + includeantruntime="false"> - + + + + - + @@ -153,7 +158,7 @@ - + @@ -189,7 +194,7 @@ - + @@ -199,8 +204,9 @@ value="lib/logging.properties"/> + - + @@ -214,12 +220,12 @@ - + - + @@ -266,6 +272,17 @@ + + + + + + + + diff --git a/src/org/ice4j/ice/Agent.java b/src/org/ice4j/ice/Agent.java index b0f7f4a..ca69374 100644 --- a/src/org/ice4j/ice/Agent.java +++ b/src/org/ice4j/ice/Agent.java @@ -123,11 +123,6 @@ public class Agent */ private final DefaultNominator nominator; - /** - * ICE compatibility mode for this agent. - */ - private final CompatibilityMode compatibilityMode; - /** * The name of the {@link PropertyChangeEvent} that we use to deliver * events on changes in the state of ICE processing in this agent. @@ -262,21 +257,9 @@ public class Agent * Creates an empty Agent with no streams, and no address. */ public Agent() - { - this(CompatibilityMode.RFC5245); - } - - /** - * Creates an empty Agent with no streams, and no address. - * - * @param compatibilityMode ICE compatibility mode - */ - public Agent(CompatibilityMode compatibilityMode) { SecureRandom random = new SecureRandom(); - this.compatibilityMode = compatibilityMode; - connCheckServer = new ConnectivityCheckServer(this); connCheckClient = new ConnectivityCheckClient(this); @@ -287,24 +270,8 @@ public class Agent if (StackProperties.getString(StackProperties.SOFTWARE) == null) System.setProperty(StackProperties.SOFTWARE, "ice4j.org"); - if (compatibilityMode == CompatibilityMode.GTALK) - { - /* - * The ufrag is 16 bytes in the Google Talk dialect but it is set - * per candidate, not globally. - */ - ufrag = null; - /* - * There is no password in the Google Talk dialect. (At least - * libnice does not use one.) - */ - password = ""; - } - else - { - ufrag = new BigInteger(24, random).toString(32); - password = new BigInteger(128, random).toString(32); - } + ufrag = new BigInteger(24, random).toString(32); + password = new BigInteger(128, random).toString(32); tieBreaker = Math.abs(random.nextLong()); nominator = new DefaultNominator(this); @@ -386,20 +353,6 @@ public class Agent { logger.info("\t" + candidate.getTransportAddress() + " (" + candidate.getType() + ")"); - - if(compatibilityMode == CompatibilityMode.GTALK) - { - /* assign a local ufrag of 16 bytes for each candidate */ - LocalCandidate localCand = (LocalCandidate)candidate; - - /* Google relayed candidate should have already set their - * ufrag since it must be the same as username present in - * HTTP response - */ - if(localCand.getUfrag() == null) - localCand.setUfrag(generateGTalkUfrag()); - - } } /* @@ -417,23 +370,6 @@ public class Agent return component; } - /** - * Generates Ufrag for GTalk mode. - * - * @return 16 bytes Ufrag - */ - public String generateGTalkUfrag() - { - SecureRandom random = new SecureRandom(); - String s = null; - - while(s == null || s.length() != 16) - { - s = new BigInteger(80, random).toString(32); - } - return s; - } - /** * Uses all CandidateHarvesters currently registered with this * Agent to obtain whatever addresses they can discover. @@ -471,13 +407,6 @@ public class Agent component, preferredPort, minPort, maxPort, Transport.UDP); - if(compatibilityMode == CompatibilityMode.GTALK) - { - hostCandidateHarvester.harvest( - component, - preferredPort, minPort, maxPort, Transport.TCP); - } - logger.fine("host candidate count: " + component.getLocalCandidateCount()); @@ -903,16 +832,7 @@ public class Agent return null; } - if(compatibilityMode == CompatibilityMode.RFC5245) - { - ret = getLocalUfrag() + ":" + stream.getRemoteUfrag(); - } - else if(compatibilityMode == CompatibilityMode.GTALK) - { - ret = getLocalUfrag() + stream.getRemoteUfrag(); - } - - return ret; + return getLocalUfrag() + ":" + stream.getRemoteUfrag(); } /** @@ -964,16 +884,6 @@ public class Agent String ufrag1 = candidate1.getUfrag(); String ufrag2 = candidate2.getUfrag(); - /* Google Talk specific - * each candidate has its own username/password - */ - if(ufrag1 != null - && ufrag2 != null - && compatibilityMode == CompatibilityMode.GTALK) - { - ret = ufrag1 + ufrag2; - } - return ret; } @@ -1099,7 +1009,7 @@ public class Agent public synchronized StunStack getStunStack() { if (stunStack == null) - stunStack = new StunStack(compatibilityMode); + stunStack = new StunStack(); return stunStack; } @@ -1391,15 +1301,7 @@ public class Agent String ufrag = null; LocalCandidate localCandidate = null; - if(compatibilityMode == CompatibilityMode.GTALK - && localAddress.getTransport() != Transport.TCP) - { - localCandidate = findLocalCandidate(localAddress, remoteUFrag); - } - else - { - localCandidate = findLocalCandidate(localAddress); - } + localCandidate = findLocalCandidate(localAddress); if(localCandidate == null) { @@ -1411,31 +1313,6 @@ public class Agent Component parentComponent = localCandidate.getParentComponent(); RemoteCandidate remoteCandidate = null; - // we need to find the username for the couple - if(compatibilityMode == CompatibilityMode.GTALK) - { - CandidatePair pair = findCandidatePair(localUFrag, remoteUFrag); - if(pair == null) - { - logger.info("No GTalk CandidatePair that match Lufrag/Rufrag" + - " " + localUFrag + " " + remoteUFrag); - return; - } - - CandidatePair pair2 = findCandidatePair( - localCandidate.getTransportAddress(), - remoteAddress); - if(pair2 == null) - { - useCandidate = false; - } - else - { - useCandidate = pair2.useCandidateReceived(); - } - - ufrag = pair.getRemoteCandidate().getUfrag(); - } remoteCandidate = new RemoteCandidate( remoteAddress, parentComponent, @@ -1517,8 +1394,7 @@ public class Agent //we already know about the remote address so we only need to //trigger a check for the existing pair - if(compatibilityMode != CompatibilityMode.RFC5245 && - !isControlling()) + if(!isControlling()) { logger.fine("set useCandidateReceived for " + triggerPair.toShortString()); @@ -1776,8 +1652,7 @@ public class Agent scheduleStunKeepAlive(); } - if (compatibilityMode == CompatibilityMode.RFC5245) - scheduleTermination(); + scheduleTermination(); //print logs for the types of addresses we chose. logCandTypes(); @@ -2192,16 +2067,6 @@ public class Agent this.generation = generation; } - /** - * Returns the compatibility mode used by this agent. - * - * @return compatibility mode - */ - public CompatibilityMode getCompatibilityMode() - { - return compatibilityMode; - } - /** * Schedule STUN checks for selected pair. */ @@ -2217,9 +2082,7 @@ public class Agent if(pair != null) { - if(performConsentFreshness - || (compatibilityMode - == CompatibilityMode.GTALK)) + if(performConsentFreshness) { connCheckClient.startCheckForPair( pair, @@ -2227,7 +2090,7 @@ public class Agent CONSENT_FRESHNESS_WAIT_INTERVAL, CONSENT_FRESHNESS_MAX_RETRANSMISSIONS); } - else if(compatibilityMode == CompatibilityMode.RFC5245) + else { connCheckClient.sendBindingIndicationForPair(pair); } diff --git a/src/org/ice4j/ice/CandidateExtendedType.java b/src/org/ice4j/ice/CandidateExtendedType.java index 1606482..2b82957 100644 --- a/src/org/ice4j/ice/CandidateExtendedType.java +++ b/src/org/ice4j/ice/CandidateExtendedType.java @@ -21,10 +21,16 @@ public enum CandidateExtendedType HOST_CANDIDATE("host"), /** - * There candidate is discovered by using UPNP method. + * The candidate is discovered by using UPNP method. */ UPNP_CANDIDATE("upnp"), + /** + * The candidate is discovered through the use of a static mask (probably + * obtained through configuration). + */ + STATICALLY_MAPPED_CANDIDATE("statically mapped"), + /** * There candidate is discovered by using STUN peer reflexive method (cf. * RFC5389). @@ -32,29 +38,29 @@ public enum CandidateExtendedType STUN_PEER_REFLEXIVE_CANDIDATE("stun peer reflexive"), /** - * There candidate is discovered by using STUN server reflexive method (cf. + * The candidate is discovered by using STUN server reflexive method (cf. * RFC5389). */ STUN_SERVER_REFLEXIVE_CANDIDATE("stun server reflexive"), /** - * There candidate is discovered by using TURN relayed method (cf. RFC5766). + * The candidate is discovered by using TURN relayed method (cf. RFC5766). */ TURN_RELAYED_CANDIDATE("turn relayed"), /** - * There candidate is discovered by using TURN relayed method (cf. RFC5766). + * The candidate is discovered by using TURN relayed method (cf. RFC5766). */ GOOGLE_TURN_RELAYED_CANDIDATE("google turn relayed"), /** - * There candidate is discovered by using TURN relayed method and using TCP + * The candidate is discovered by using TURN relayed method and using TCP * (cf. RFC5766). */ GOOGLE_TCP_TURN_RELAYED_CANDIDATE("google tcp turn relayed"), /** - * There candidate is discovered by using JINGLE NODE method (cf. XEP-0278). + * The candidate is discovered by using JINGLE NODE method (cf. XEP-0278). */ JINGLE_NODE_CANDIDATE("jingle node"); diff --git a/src/org/ice4j/ice/CheckList.java b/src/org/ice4j/ice/CheckList.java index a665dd5..41ed1e3 100644 --- a/src/org/ice4j/ice/CheckList.java +++ b/src/org/ice4j/ice/CheckList.java @@ -390,11 +390,7 @@ public class CheckList || (pair.getState() == CandidatePairState.IN_PROGRESS && pair.getPriority() < nominatedPair.getPriority()))) { - if(parentStream.getParentAgent().getCompatibilityMode() == - CompatibilityMode.RFC5245) - { - pairsIter.remove(); - } + pairsIter.remove(); } } @@ -550,9 +546,6 @@ public class CheckList /** * Creates a new {@link PropertyChangeEvent} and delivers it to all * currently registered checks listeners. - * - * @param oldState old state - * @param newState new state */ protected void fireEndOfOrdinaryChecks() { diff --git a/src/org/ice4j/ice/CompatibilityMode.java b/src/org/ice4j/ice/CompatibilityMode.java deleted file mode 100644 index b567660..0000000 --- a/src/org/ice4j/ice/CompatibilityMode.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - * ice4j, the OpenSource Java Solution for NAT and Firewall Traversal. - * Maintained by the SIP Communicator community (http://sip-communicator.org). - * - * Distributable under LGPL license. See terms of license at gnu.org. - */ -package org.ice4j.ice; - -/** - * ICE compatibility mode. - * - * @author Sebastien Vincent - */ -public enum CompatibilityMode -{ - /** - * Standard ICE from RFC5245; - */ - RFC5245, - - /** - * Google ICE dialect used by Google Talk (web and application). - */ - GTALK; -} diff --git a/src/org/ice4j/ice/Component.java b/src/org/ice4j/ice/Component.java index 3e9bc43..d6635f1 100644 --- a/src/org/ice4j/ice/Component.java +++ b/src/org/ice4j/ice/Component.java @@ -151,16 +151,7 @@ public class Component agent.getFoundationsRegistry().assignFoundation(candidate); //compute priority - CompatibilityMode compatibilityMode = getParentStream().getParentAgent() - .getCompatibilityMode(); - if(compatibilityMode == CompatibilityMode.GTALK) - { - candidate.computeGTalkPriority(); - } - else - { - candidate.computePriority(); - } + candidate.computePriority(); synchronized(localCandidates) { @@ -268,43 +259,6 @@ public class Component logger.info("Update remote candidate for " + toShortString() + ": " + candidate.getTransportAddress()); - if(candidate.getTransport() == Transport.TCP && - parentStream.getParentAgent().getCompatibilityMode() - == CompatibilityMode.GTALK) - { - /* for TCP, create a new Candidate to each of remote - * TCP candidates - */ - for(LocalCandidate localCnd : getLocalCandidates()) - { - if(localCnd.getTransport() != Transport.TCP - || (localCnd.getType() != CandidateType.LOCAL_CANDIDATE - && localCnd.getType() != CandidateType.HOST_CANDIDATE) - || !(localCnd.getIceSocketWrapper() - instanceof IceTcpServerSocketWrapper) - || !localCnd.getTransportAddress().canReach( - candidate.getTransportAddress()) - ) - { - continue; - } - - LocalCandidate newLocalCandidate - = createLocalTcpCandidate4GTalk(candidate, localCnd); - - if (newLocalCandidate == null) - { - //sth wen wrong but we've already logged so ... - continue; - } - - synchronized(localCandidates) - { - localCandidates.add(newLocalCandidate); - } - } - } - synchronized(remoteUpdateCandidates) { remoteUpdateCandidates.add(candidate); @@ -412,15 +366,6 @@ public class Component if(localCnd == upnpBase) continue; - //don't pair local GTalk TCP candidates with the new remote ones - if(parentStream.getParentAgent(). - getCompatibilityMode() == CompatibilityMode.GTALK && - localCnd.getIceSocketWrapper() instanceof - IceTcpServerSocketWrapper) - { - continue; - } - //pair each of the new remote candidates with each of our locals for(RemoteCandidate remoteCnd : remoteUpdateCandidates) { @@ -629,9 +574,6 @@ public class Component { synchronized(localCandidates) { - CompatibilityMode compatibility = getParentStream().getParentAgent() - .getCompatibilityMode(); - LocalCandidate[] candidates = new LocalCandidate[localCandidates.size()]; @@ -640,14 +582,7 @@ public class Component //first compute the actual priorities for (Candidate cand : candidates) { - if(compatibility == CompatibilityMode.GTALK) - { - cand.computeGTalkPriority(); - } - else - { - cand.computePriority(); - } + cand.computePriority(); } //sort diff --git a/src/org/ice4j/ice/ConnectivityCheckClient.java b/src/org/ice4j/ice/ConnectivityCheckClient.java index c96ba65..64f4cb9 100644 --- a/src/org/ice4j/ice/ConnectivityCheckClient.java +++ b/src/org/ice4j/ice/ConnectivityCheckClient.java @@ -169,7 +169,7 @@ class ConnectivityCheckClient * * @param candidatePair that {@link CandidatePair} that we'd like to start * a check for. - * @param originalWiatIterval + * @param originalWiatInterval * @param maxWaitInterval * @param maxRetransmissions * @return a reference to the {@link TransactionID} used in the connectivity @@ -178,7 +178,7 @@ class ConnectivityCheckClient */ protected TransactionID startCheckForPair( CandidatePair candidatePair, - int originalWiatIterval, + int originalWiatInterval, int maxWaitInterval, int maxRetransmissions) { @@ -188,92 +188,67 @@ class ConnectivityCheckClient Request request = MessageFactory.createBindingRequest(); - if(parentAgent.getCompatibilityMode() == CompatibilityMode.GTALK) - { - /* Google Talk ICE dialect just need the username */ - String localUserName - = parentAgent.generateLocalUserName( - candidatePair.getRemoteCandidate(), - candidatePair.getLocalCandidate()); - UsernameAttribute unameAttr - = AttributeFactory.createUsernameAttribute(localUserName); + //the priority we'd like the remote party to use for a peer + //reflexive candidate if one is discovered as a consequence of this + //check. + PriorityAttribute priority + = AttributeFactory.createPriorityAttribute( + localCandidate.computePriorityForType( + CandidateType.PEER_REFLEXIVE_CANDIDATE)); - request.addAttribute(unameAttr); + request.addAttribute(priority); + + //controlling controlled + if (parentAgent.isControlling()) + { + request.addAttribute( + AttributeFactory.createIceControllingAttribute( + parentAgent.getTieBreaker())); //if we are the controlling agent then we need to indicate our //nominated pairs. - if (parentAgent.isControlling() && candidatePair.isNominated()) + if(candidatePair.isNominated()) { logger.fine( - "set useCandidateSent for " + "Add USE-CANDIDATE in check for: " + candidatePair.toShortString()); - candidatePair.setUseCandidateSent(); + request.addAttribute( + AttributeFactory.createUseCandidateAttribute()); } } else { - //the priority we'd like the remote party to use for a peer - //reflexive candidate if one is discovered as a consequence of this - //check. - PriorityAttribute priority - = AttributeFactory.createPriorityAttribute( - localCandidate.computePriorityForType( - CandidateType.PEER_REFLEXIVE_CANDIDATE)); - - request.addAttribute(priority); - - //controlling controlled - if (parentAgent.isControlling()) - { - request.addAttribute( - AttributeFactory.createIceControllingAttribute( - parentAgent.getTieBreaker())); - - //if we are the controlling agent then we need to indicate our - //nominated pairs. - if(candidatePair.isNominated()) - { - logger.fine( - "Add USE-CANDIDATE in check for: " - + candidatePair.toShortString()); - request.addAttribute( - AttributeFactory.createUseCandidateAttribute()); - } - } - else - { - request.addAttribute( - AttributeFactory.createIceControlledAttribute( - parentAgent.getTieBreaker())); - } - - //credentials - String media - = candidatePair - .getParentComponent().getParentStream().getName(); - String localUserName = parentAgent.generateLocalUserName(media); - - if(localUserName == null) - return null; - - UsernameAttribute unameAttr - = AttributeFactory.createUsernameAttribute(localUserName); - - request.addAttribute(unameAttr); - - // TODO Also implement SASL prepare - MessageIntegrityAttribute msgIntegrity - = AttributeFactory.createMessageIntegrityAttribute( - localUserName); - - // when we will encode the MESSAGE-INTEGRITY attribute (thus - // generate the HMAC-SHA1 authentication), we need to know the - // remote key of the current stream, that why we pass the media - // name. - msgIntegrity.setMedia(media); - request.addAttribute(msgIntegrity); + request.addAttribute( + AttributeFactory.createIceControlledAttribute( + parentAgent.getTieBreaker())); } + //credentials + String media + = candidatePair + .getParentComponent().getParentStream().getName(); + String localUserName = parentAgent.generateLocalUserName(media); + + if(localUserName == null) + return null; + + UsernameAttribute unameAttr + = AttributeFactory.createUsernameAttribute(localUserName); + + request.addAttribute(unameAttr); + + // TODO Also implement SASL prepare + MessageIntegrityAttribute msgIntegrity + = AttributeFactory.createMessageIntegrityAttribute( + localUserName); + + // when we will encode the MESSAGE-INTEGRITY attribute (thus + // generate the HMAC-SHA1 authentication), we need to know the + // remote key of the current stream, that why we pass the media + // name. + msgIntegrity.setMedia(media); + request.addAttribute(msgIntegrity); + TransactionID tran = TransactionID.createNewTransactionID(); tran.setApplicationData(candidatePair); @@ -291,7 +266,7 @@ class ConnectivityCheckClient localCandidate.getBase().getTransportAddress(), this, tran, - originalWiatIterval, + originalWiatInterval, maxWaitInterval, maxRetransmissions); if(logger.isLoggable(Level.FINEST)) @@ -341,8 +316,7 @@ class ConnectivityCheckClient = (CandidatePair) ev.getTransactionID().getApplicationData(); //make sure that the response came from the right place. - if (parentAgent.getCompatibilityMode() == CompatibilityMode.RFC5245 - && !checkSymmetricAddresses(ev)) + if (!checkSymmetricAddresses(ev)) { logger.fine("Received a non-symmetric response for pair: " + checkedPair.toShortString() + ". Failing"); @@ -470,54 +444,23 @@ class ConnectivityCheckClient = (CandidatePair) ev.getTransactionID().getApplicationData(); TransportAddress mappedAddress = null; - if(parentAgent.getCompatibilityMode() == CompatibilityMode.GTALK) + + if(! response.containsAttribute(Attribute.XOR_MAPPED_ADDRESS)) { - if(response.containsAttribute(Attribute.XOR_MAPPED_ADDRESS)) - { - XorMappedAddressAttribute mappedAddressAttr - = (XorMappedAddressAttribute)response - .getAttribute(Attribute.XOR_MAPPED_ADDRESS); - mappedAddress = mappedAddressAttr.getAddress( - response.getTransactionID()); - } - else if(response.containsAttribute(Attribute.MAPPED_ADDRESS)) - { - - MappedAddressAttribute mappedAddressAttr - = (MappedAddressAttribute)response - .getAttribute(Attribute.MAPPED_ADDRESS); - - mappedAddress = mappedAddressAttr.getAddress(); - } - else - { - logger.fine("Received a success response with no " - + "MAPPED_ADDRESS attribute."); - logger.info("Pair failed (no MAPPED-ADDRESS): " - + checkedPair.toShortString()); - checkedPair.setStateFailed(); - return; //malformed error response - } + logger.fine("Received a success response with no " + + "XOR_MAPPED_ADDRESS attribute."); + logger.info("Pair failed (no XOR-MAPPED-ADDRESS): " + + checkedPair.toShortString()); + checkedPair.setStateFailed(); + return; //malformed error response } - else - { - if(! response.containsAttribute(Attribute.XOR_MAPPED_ADDRESS)) - { - logger.fine("Received a success response with no " - + "XOR_MAPPED_ADDRESS attribute."); - logger.info("Pair failed (no XOR-MAPPED-ADDRESS): " - + checkedPair.toShortString()); - checkedPair.setStateFailed(); - return; //malformed error response - } - XorMappedAddressAttribute mappedAddressAttr - = (XorMappedAddressAttribute)response - .getAttribute(Attribute.XOR_MAPPED_ADDRESS); + XorMappedAddressAttribute mappedAddressAttr + = (XorMappedAddressAttribute)response + .getAttribute(Attribute.XOR_MAPPED_ADDRESS); - mappedAddress = mappedAddressAttr - .getAddress(response.getTransactionID()); - } + mappedAddress = mappedAddressAttr + .getAddress(response.getTransactionID()); // XXX AddressAttribute always returns UDP based TransportAddress if(checkedPair.getLocalCandidate().getTransport() == Transport.TCP) @@ -531,26 +474,8 @@ class ConnectivityCheckClient LocalCandidate validLocalCandidate = null; - if(parentAgent.getCompatibilityMode() == CompatibilityMode.GTALK) - { - // find local candidate with ufrag rather than mapped address - UsernameAttribute uname = (UsernameAttribute)request - .getAttribute(Attribute.USERNAME); - String username = new String(uname.getUsername()); - String ufrag = username.substring(16, 32); - - if(mappedAddress.getTransport() == Transport.TCP) - validLocalCandidate = parentAgent.findLocalCandidate( - mappedAddress); - else - validLocalCandidate = parentAgent.findLocalCandidate( - mappedAddress, ufrag); - } - else if(parentAgent.getCompatibilityMode() == CompatibilityMode.RFC5245) - { - validLocalCandidate = parentAgent - .findLocalCandidate(mappedAddress); - } + validLocalCandidate = parentAgent + .findLocalCandidate(mappedAddress); RemoteCandidate validRemoteCandidate = checkedPair.getRemoteCandidate(); @@ -568,16 +493,9 @@ class ConnectivityCheckClient //o Its priority is set equal to the value of the PRIORITY attribute // in the Binding request. long priority = 0; - if(parentAgent.getCompatibilityMode() == CompatibilityMode.GTALK) - { - priority = 900; - } - else - { - PriorityAttribute prioAttr = (PriorityAttribute)request - .getAttribute(Attribute.PRIORITY); - priority = prioAttr.getPriority(); - } + PriorityAttribute prioAttr = (PriorityAttribute)request + .getAttribute(Attribute.PRIORITY); + priority = prioAttr.getPriority(); LocalCandidate peerReflexiveCandidate = new PeerReflexiveCandidate( @@ -599,12 +517,6 @@ class ConnectivityCheckClient //generated from it momentarily validLocalCandidate = peerReflexiveCandidate; - if(parentAgent.getCompatibilityMode() == CompatibilityMode.GTALK) - { - validLocalCandidate.setUfrag( - checkedPair.getLocalCandidate().getUfrag()); - } - if(checkedPair.getParentComponent().getSelectedPair() == null) logger.info("Receive a peer-reflexive candidate: " + peerReflexiveCandidate.getTransportAddress()); @@ -721,10 +633,7 @@ class ConnectivityCheckClient //CANDIDATE attribute in the Binding request, the valid pair generated //from that check has its nominated flag set to true. if((parentAgent.isControlling() - && request.containsAttribute(Attribute.USE_CANDIDATE)) - || ((parentAgent.getCompatibilityMode() - == CompatibilityMode.GTALK) - && validPair.isNominated())) + && request.containsAttribute(Attribute.USE_CANDIDATE))) { if(validPair.getParentComponent().getSelectedPair() == null) { @@ -769,8 +678,8 @@ class ConnectivityCheckClient /** * Returns true if the {@link Response} in evt had a - * source or a destination address that did not match those of the - * {@link Request}, or false otherwise. + * source or a destination address that match those of the {@link Request}, + * or false otherwise.

* RFC 5245: The agent MUST check that the source IP address and port of * the response equal the destination IP address and port to which the * Binding request was sent, and that the destination IP address and @@ -784,7 +693,7 @@ class ConnectivityCheckClient * Response} we need to examine * * @return true if the {@link Response} in evt had a - * source or a destination address that did not match those of the + * source or a destination address that matched those of the * {@link Request}, or false otherwise. */ private boolean checkSymmetricAddresses(StunResponseEvent evt) @@ -838,23 +747,6 @@ class ConnectivityCheckClient pair.getParentComponent().getParentStream().getCheckList() .scheduleTriggeredCheck(pair); } - else if(parentAgent.getCompatibilityMode() == CompatibilityMode.GTALK - && cl == 1 - && co == 0xae) // STALE_CREDENTIALS (430) - { - // it may be an error due to remote peer that does not processed - // our candidates IQ and we start connectivity checks too quickly - // (that's why we get a STALE CREDENTIALS because remote peer does - // not know the candidate ufrag). So let's send another check for - // that pair - logger.info("stale credentials for GTalk check for " + - pair.toShortString()); - - // try again after some delay - //startDelayedCheckForPair(pair, 100); - startCheckForPair(pair); - return; - } else { int code = cl * 100 + co; diff --git a/src/org/ice4j/ice/ConnectivityCheckServer.java b/src/org/ice4j/ice/ConnectivityCheckServer.java index b13c9ed..c4ff337 100644 --- a/src/org/ice4j/ice/ConnectivityCheckServer.java +++ b/src/org/ice4j/ice/ConnectivityCheckServer.java @@ -92,8 +92,7 @@ class ConnectivityCheckServer .getAttribute(Attribute.USERNAME); if( uname == null - || ( parentAgent.getCompatibilityMode() == CompatibilityMode.RFC5245 - && !checkLocalUserName(new String(uname.getUsername())))) + || !checkLocalUserName(new String(uname.getUsername()))) { return; } @@ -116,64 +115,9 @@ class ConnectivityCheckServer String remoteUfrag = null; String localUFrag = null; - if(parentAgent.getCompatibilityMode() == CompatibilityMode.GTALK) - { - /* Google Talk ICE dialect considers every request to have - * USE-CANDIDATE behavior. - */ - // it will be set in Agent.incomingCheckReceived - useCandidate = false; //true; - - /* Google Talk STUN request does not contains PRIORITY attribute - * set it to the peer reflexive value (0.9 * 1000); - * - * In all cases priority will just be used if a we discover that - * effectively the peer is a peer reflexive ones. - */ - priority = 900; - - /* Google Talk uses username of length 16 for local and remote */ - remoteUfrag = username.substring(0, 16); - localUFrag = username.substring(16, 32); - } - else - { - priority = extractPriority(request); - int colon = username.indexOf(":"); - remoteUfrag = username.substring(0, colon); - } - - if( parentAgent.getCompatibilityMode() == CompatibilityMode.GTALK - && parentAgent.findCandidatePair(localUFrag, remoteUfrag) == null) - { - logger.info("No candidate pair that match local and remote ufrag"); - - // no candidate pair for the moment so do not send response - // trigger an error so that other peer try again after some time - Response response = MessageFactory.createBindingErrorResponse( - ErrorCodeAttribute.STALE_CREDENTIALS); - ErrorCodeAttribute err = (ErrorCodeAttribute)response.getAttribute( - Attribute.ERROR_CODE); - // Gtalk error code is not RFC5389 compliant - err.setErrorClass((byte)0x01); - err.setErrorNumber((byte)0xae); - - try - { - stunStack.sendResponse( - evt.getTransactionID().getBytes(), - response, - evt.getLocalAddress(), - evt.getRemoteAddress()); - - return; - } - catch(Exception exc) - { - //rethrow so that we would send a 500 response instead. - throw new RuntimeException("Failed to send a 430", exc); - } - } + priority = extractPriority(request); + int colon = username.indexOf(":"); + remoteUfrag = username.substring(0, colon); //tell our address handler we saw a new remote address; parentAgent.incomingCheckReceived(evt.getRemoteAddress(), @@ -192,22 +136,10 @@ class ConnectivityCheckServer AttributeFactory.createUsernameAttribute(uname.getUsername()); response.addAttribute(usernameAttribute); - if(parentAgent.getCompatibilityMode() == CompatibilityMode.GTALK) - { - /* add Mapped address and remove the XOR_MAPPED_ADDRESS one*/ - Attribute mappedAddressAttribute = - AttributeFactory.createMappedAddressAttribute( - evt.getRemoteAddress()); - response.addAttribute(mappedAddressAttribute); - response.removeAttribute(Attribute.XOR_MAPPED_ADDRESS); - } - else - { - Attribute messageIntegrityAttribute = - AttributeFactory.createMessageIntegrityAttribute( - new String(uname.getUsername())); - response.addAttribute(messageIntegrityAttribute); - } + Attribute messageIntegrityAttribute = + AttributeFactory.createMessageIntegrityAttribute( + new String(uname.getUsername())); + response.addAttribute(messageIntegrityAttribute); try { @@ -398,32 +330,19 @@ class ConnectivityCheckServer { String ufrag = null; - if(parentAgent.getCompatibilityMode() == CompatibilityMode.GTALK) + int colon = username.indexOf(":"); + + if (colon < 0) { - if(username.length() == 32) - { - ufrag = username.substring(0, 16); - } - else - { - ufrag = username; - } + //caller gave us a ufrag + ufrag = username; } else { - int colon = username.indexOf(":"); - - if (colon < 0) - { - //caller gave us a ufrag - ufrag = username; - } - else - { - //caller gave us the entire username. - ufrag = username.substring(0, colon); - } + //caller gave us the entire username. + ufrag = username.substring(0, colon); } + return ufrag.equals(parentAgent.getLocalUfrag()); } diff --git a/src/org/ice4j/ice/FoundationsRegistry.java b/src/org/ice4j/ice/FoundationsRegistry.java index 1da978f..b7a1ddd 100644 --- a/src/org/ice4j/ice/FoundationsRegistry.java +++ b/src/org/ice4j/ice/FoundationsRegistry.java @@ -7,6 +7,8 @@ */ package org.ice4j.ice; +import org.ice4j.*; + import java.util.*; /** @@ -54,7 +56,10 @@ public class FoundationsRegistry switch (candidateType) { case SERVER_REFLEXIVE_CANDIDATE: - server = candidate.getStunServerAddress().getHostAddress(); + TransportAddress serverAddress = candidate.getStunServerAddress(); + server = (serverAddress == null) + ? "" + : serverAddress.getHostAddress(); break; case RELAYED_CANDIDATE: server = candidate.getRelayServerAddress().getHostAddress(); diff --git a/src/org/ice4j/ice/IceMediaStream.java b/src/org/ice4j/ice/IceMediaStream.java index 2dff3a1..506f378 100644 --- a/src/org/ice4j/ice/IceMediaStream.java +++ b/src/org/ice4j/ice/IceMediaStream.java @@ -380,55 +380,6 @@ public class IceMediaStream { if(localCnd.canReach(remoteCnd)) { - if(localCnd.getTransport() == Transport.TCP - && parentAgent.getCompatibilityMode() - == CompatibilityMode.GTALK) - { - final LocalCandidate loc = localCnd; - final RemoteCandidate remot = remoteCnd; - - new Thread() - { - public void run() - { - /* for TCP, create a new Candidate (a new - * connection) to each of remote TCP candidates - */ - try - { - Socket sock = new MultiplexingSocket(); - int timeout = sock.getSoTimeout(); - sock.setSoTimeout(1000); - - sock.connect(new InetSocketAddress( - remot.getTransportAddress(). - getAddress(), - remot.getTransportAddress(). - getPort()), - 1000); - - sock.setSoTimeout(timeout); - LocalCandidate tmp = - new HostCandidate( - new IceTcpSocketWrapper(sock), - component); - tmp.setUfrag(loc.getUfrag()); - - CandidatePair pair = new CandidatePair(tmp, - remot); - checkList.add(pair); - } - catch (IOException e) - { - logger.info("Failed to TCP connect to " + - remot.getTransportAddress()); - return; - } - } - }.start(); - continue; - } - CandidatePair pair = new CandidatePair(localCnd, remoteCnd); checkList.add(pair); @@ -483,22 +434,19 @@ public class IceMediaStream continue; } - if(parentAgent.getCompatibilityMode() == CompatibilityMode.RFC5245) + //replace local server reflexive candidates with their base. + LocalCandidate localCnd = pair.getLocalCandidate(); + if( localCnd.getType() + == CandidateType.SERVER_REFLEXIVE_CANDIDATE) { - //replace local server reflexive candidates with their base. - LocalCandidate localCnd = pair.getLocalCandidate(); - if( localCnd.getType() - == CandidateType.SERVER_REFLEXIVE_CANDIDATE) - { - pair.setLocalCandidate(localCnd.getBase()); + pair.setLocalCandidate(localCnd.getBase()); - //if the new pair corresponds to another one with a higher - //priority, then remove it. - if(tmpCheckList.contains(pair)) - { - ckListIter.remove(); - continue; - } + //if the new pair corresponds to another one with a higher + //priority, then remove it. + if(tmpCheckList.contains(pair)) + { + ckListIter.remove(); + continue; } } diff --git a/src/org/ice4j/ice/harvest/AwsCandidateHarvester.java b/src/org/ice4j/ice/harvest/AwsCandidateHarvester.java new file mode 100644 index 0000000..348810d --- /dev/null +++ b/src/org/ice4j/ice/harvest/AwsCandidateHarvester.java @@ -0,0 +1,217 @@ +/* + * Jitsi Videobridge, OpenSource video conferencing. + * + * Distributable under LGPL license. + * See terms of license at gnu.org. + */ +package org.ice4j.ice.harvest; + +import org.ice4j.*; +import org.ice4j.ice.*; + +import java.io.*; +import java.net.*; +import java.util.*; +import java.util.logging.*; + +/** + * Uses the Amazon AWS APIs to retrieve the public and private IPv4 addresses + * for an EC2 instance. + * + * @author Emil Ivov + */ +public class AwsCandidateHarvester + extends MappingCandidateHarvester +{ + /** + * The Logger used by the AwsCandidateHarvester + * class and its instances for logging output. + */ + private static final Logger logger + = Logger.getLogger(AwsCandidateHarvester.class.getName()); + + /** + * The URL where one obtains AWS public addresses. + */ + private static final String PUBLIC_IP_URL + = "http://169.254.169.254/latest/meta-data/public-ipv4"; + + /** + * The URL where one obtains AWS private/local addresses. + */ + private static final String LOCAL_IP_URL + = "http://169.254.169.254/latest/meta-data/local-ipv4"; + + /** + * The addresses that we will use as a mask + */ + private static TransportAddress mask; + + /** + * The addresses that we will be masking + */ + private static TransportAddress face; + + /** + * Creates an AWS harvester. The actual addresses wil be retrieved later, + * during the first harvest. + */ + public AwsCandidateHarvester() + { + super(null, null); + } + /** + * Maps all candidates to this harvester's mask and adds them to + * component. + * + * @param component the {@link Component} that we'd like to map candidates + * to. + * @return the LocalCandidates gathered by this + * CandidateHarvester or null if no mask is specified. + */ + public Collection harvest(Component component) + { + + if (mask == null || face == null) + { + if(!obtainEC2Addresses()) + return null; + } + + + /* + * Report the LocalCandidates gathered by this CandidateHarvester so + * that the harvest is sure to be considered successful. + */ + Collection candidates = new HashSet(); + + for (Candidate cand : component.getLocalCandidates()) + { + if (!(cand instanceof HostCandidate) + || !cand.getTransportAddress().getHostAddress() + .equals(face.getHostAddress())) + { + continue; + } + + TransportAddress mappedAddress = new TransportAddress( + mask.getHostAddress(), + cand.getHostAddress().getPort(), + cand.getHostAddress().getTransport()); + + ServerReflexiveCandidate mappedCandidate + = new ServerReflexiveCandidate( + mappedAddress, + (HostCandidate)cand, + cand.getStunServerAddress(), + CandidateExtendedType.STATICALLY_MAPPED_CANDIDATE); + + //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; + } + + /** + * Sends HTTP GET queries to + * http://169.254.169.254/latest/meta-data/local-ipv4 and + * http://169.254.169.254/latest/meta-data/public-ipv4 to learn the + * private (face) and public (mask) addresses of this EC2 instance. + * + * @return true if we managed to obtain addresses or someone else + * had already achieved that before us, false otherwise. + */ + private static synchronized boolean obtainEC2Addresses() + { + if(mask != null && face != null) + return true; + + String localIPStr = null; + String publicIPStr = null; + + try + { + localIPStr = fetch(LOCAL_IP_URL); + publicIPStr = fetch(PUBLIC_IP_URL); + + //now let's cross our fingers and hope that what we got above are + //real IP addresses + face = new TransportAddress(localIPStr, 9, Transport.UDP); + mask = new TransportAddress(publicIPStr, 9, Transport.UDP); + + logger.info("Detected AWS local IP: " + face); + logger.info("Detected AWS public IP: " + mask); + + + } + catch (Exception exc) + { + //whatever happens, we just log and bail + logger.log(Level.INFO, "We failed to obtain EC2 instance addresses " + + "for the following reason: ", exc); + logger.info("String for local IP: " + localIPStr); + logger.info("String for public IP: " + publicIPStr); + + } + + return true; + } + + /** + * Determines if there is a decent chance for the box executing this + * application to be an AWS EC2 instance and returns true if so. + * Note that this method does not provide any guarantees. It just tries + * to provide a way to quickly determine if we are unlikely to be running + * an EC2 so as to avoid the GET queries during harvesting. Running those + * queries on a non-EC2 machine takes them a while to expire. + * + * @return true if there appear to be decent chances for this + * machine to be an AWS EC2 (i.e. ec2metadata executes) and false + * otherwise. + */ + public static boolean smellsLikeAnEC2() + { + try + { + Runtime.getRuntime().exec("ec2metadata"); + + //if this is an AWS EC2 we would throw an exception above and not + //get here, so ... be happy + return true; + } + catch(Exception exc) + { + //ah! I knew you weren't one of those ... + return false; + } + } + + /** + * Retrieves the content at the specified url. No more, no less. + * + * @param url the URL we'd like to open and query. + * + * @return the String we retrieved from the URL. + * + * @throws Exception if anything goes wrong. + */ + private static String fetch(String url) + throws Exception + { + URLConnection conn = new URL(url).openConnection(); + BufferedReader in = new BufferedReader(new InputStreamReader( + conn.getInputStream(), "UTF-8")); + + String retString = in.readLine(); + + in.close(); + + return retString; + } +} diff --git a/src/org/ice4j/ice/harvest/MappingCandidateHarvester.java b/src/org/ice4j/ice/harvest/MappingCandidateHarvester.java new file mode 100644 index 0000000..a522847 --- /dev/null +++ b/src/org/ice4j/ice/harvest/MappingCandidateHarvester.java @@ -0,0 +1,110 @@ +/* + * Jitsi Videobridge, OpenSource video conferencing. + * + * Distributable under LGPL license. + * See terms of license at gnu.org. + */ +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. + *

+ * 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. + *

+ * Example: You run this on a server with address 192.168.0.1, that is behind + * a NAT with public IP: 93.184.216.119. You allocate a host candidate + * 192.168.0.1/UDP/5000. This harvester is going to then generate an address + * 93.184.216.119/UDP/5000 + *

+ * This harvester is instant and does not introduce any harvesting latency. + * + * @author Emil Ivov + */ +public class MappingCandidateHarvester + extends CandidateHarvester +{ + /** + * The addresses that we will use as a mask + */ + private TransportAddress mask; + + /** + * The addresses that we will be masking + */ + private TransportAddress face; + + /** + * Creates a mapping harvester with the specified mask + * + * @param mask the TransportAddresses that would be used as a mask. + * @param face the TransportAddresses 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 + * component. + * + * @param component the {@link Component} that we'd like to map candidates + * to. + * @return the LocalCandidates gathered by this + * CandidateHarvester or null if no mask is specified. + */ + public Collection harvest(Component component) + { + + if (mask == null || face == null) + return null; + + /* + * Report the LocalCandidates gathered by this CandidateHarvester so + * that the harvest is sure to be considered successful. + */ + Collection candidates = new HashSet(); + + for (Candidate cand : component.getLocalCandidates()) + { + if (!(cand instanceof HostCandidate) + || !cand.getTransportAddress().getHostAddress() + .equals(face.getHostAddress())) + { + continue; + } + + TransportAddress mappedAddress = new TransportAddress( + mask.getHostAddress(), + cand.getHostAddress().getPort(), + cand.getHostAddress().getTransport()); + + ServerReflexiveCandidate mappedCandidate + = new ServerReflexiveCandidate( + mappedAddress, + (HostCandidate)cand, + cand.getStunServerAddress(), + CandidateExtendedType.STATICALLY_MAPPED_CANDIDATE); + + //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; + } +} diff --git a/src/org/ice4j/message/Message.java b/src/org/ice4j/message/Message.java index fe9f62f..dc40cb1 100644 --- a/src/org/ice4j/message/Message.java +++ b/src/org/ice4j/message/Message.java @@ -834,23 +834,8 @@ public abstract class Message validateAttributePresentity(); final char dataLength; - if(stunStack.getCompatibilityMode() == CompatibilityMode.GTALK) - { - /* Google Talk will return error response if it sees unknown - * attributes (typically attributes introduced in RFC5349 and - */ - if(getAttribute(Attribute.SOFTWARE) != null) - removeAttribute(Attribute.SOFTWARE); - if(getAttribute(Attribute.FINGERPRINT) != null) - removeAttribute(Attribute.FINGERPRINT); - - dataLength = getDataLengthWithoutPadding(); - } - else - { - dataLength = getDataLength(); - } + dataLength = getDataLength(); byte binMsg[] = new byte[HEADER_LENGTH + dataLength]; int offset = 0; diff --git a/src/org/ice4j/stack/StunStack.java b/src/org/ice4j/stack/StunStack.java index 03da7f7..c1d53a7 100644 --- a/src/org/ice4j/stack/StunStack.java +++ b/src/org/ice4j/stack/StunStack.java @@ -97,11 +97,6 @@ public class StunStack */ private static PacketLogger packetLogger; - /** - * Compatibility mode. - */ - private final CompatibilityMode mode; - /** * Sets the number of Message processors running in the same time. * @@ -290,16 +285,6 @@ public class StunStack * Initializes a new StunStack instance. */ public StunStack() - { - this(CompatibilityMode.RFC5245); - } - - /** - * Initializes a new StunStack instance. - * - * @param mode compatibility mode - */ - public StunStack(CompatibilityMode mode) { /* * The Mac instantiation used in MessageIntegrityAttribute could take @@ -323,13 +308,7 @@ public class StunStack } } } - this.mode = mode; netAccessManager = new NetAccessManager(this); - - if(mode == CompatibilityMode.GTALK) - { - netAccessManager.setThreadPoolSize(1); - } } /** @@ -462,7 +441,7 @@ public class StunStack * @param transactionID the ID that we'd like the new transaction to use * in case the application created it in order to use it for application * data correlation. - * @param originalWiatIterval + * @param originalWaitInterval * @param maxWaitInterval * @param maxRetransmissions * @return the TransactionID of the StunClientTransaction @@ -946,11 +925,6 @@ public class StunStack private void validateRequestAttributes(StunMessageEvent evt) throws IllegalArgumentException, StunException, IOException { - if(mode != CompatibilityMode.RFC5245) - { - return; - } - Message request = evt.getMessage(); //assert valid username @@ -1253,16 +1227,6 @@ public class StunStack return packetLogger != null && packetLogger.isEnabled(); } - /** - * Returns compatibility mode. - * - * @return compatibility mode - */ - public CompatibilityMode getCompatibilityMode() - { - return mode; - } - /** * Initializes and starts {@link #serverTransactionExpireThread} if * necessary. diff --git a/test/test/AwsTest.java b/test/test/AwsTest.java new file mode 100644 index 0000000..c9fe139 --- /dev/null +++ b/test/test/AwsTest.java @@ -0,0 +1,78 @@ +/* + * ice4j, the OpenSource Java Solution for NAT and Firewall Traversal. + * Maintained by the SIP Communicator community (http://sip-communicator.org). + * + * Distributable under LGPL license. See terms of license at gnu.org. + */ +package test; + +import java.util.*; +import java.util.logging.*; + +import javax.sdp.*; + +import org.ice4j.*; +import org.ice4j.ice.*; +import org.ice4j.ice.harvest.*; +import org.ice4j.ice.sdp.*; + +/** + * An example of using the AWS Harvester. + *

+ * @author Emil Ivov + */ +public class AwsTest + extends Ice +{ + /** + * The Logger used by the TrickleIce + * class and its instances for logging output. + */ + private static final Logger logger + = Logger.getLogger(TrickleIce.class.getName()); + + /** + * Runs a test application that creates an agent, attaches an AWS harvester + * as well as a few allocates streams, generates an SDP and dumps + * it on stdout + * + * @param args none currently handled + * @throws Throwable every now and then. + */ + public static void main(String[] args) throws Throwable + { + if(!AwsCandidateHarvester.smellsLikeAnEC2()) + { + logger.info("This does not appear to be an EC2 machine"); + return; + } + else + { + logger.info("Oh nice! Looks like we are on an EC2 machine"); + + } + AwsCandidateHarvester mch = new AwsCandidateHarvester(); + + List harvesters + = new ArrayList(); + harvesters.add(mch); + + Agent localAgent = createAgent(2020, false, harvesters); + localAgent.setNominationStrategy( + NominationStrategy.NOMINATE_HIGHEST_PRIO); + + String localSDP = SdpUtils.createSDPDescription(localAgent); + + //wait a bit so that the logger can stop dumping stuff: + Thread.sleep(500); + + logger.info("=================== feed the following" + +" to the remote agent ==================="); + + + logger.info("\n" + localSDP); + + logger.info("======================================" + + "========================================\n"); + } +} diff --git a/test/test/Ice.java b/test/test/Ice.java index dd9bc8a..de07e17 100644 --- a/test/test/Ice.java +++ b/test/test/Ice.java @@ -296,39 +296,74 @@ public class Ice */ protected static Agent createAgent(int rtpPort, boolean isTrickling) throws Throwable + { + return createAgent(rtpPort, isTrickling, null); + } + + /** + * Creates an ICE Agent (vanilla or trickle, depending on the + * value of isTrickling) and adds to it an audio and a video stream + * with RTP and RTCP components. + * + * @param rtpPort the port that we should try to bind the RTP component on + * (the RTCP one would automatically go to rtpPort + 1) + * @return an ICE Agent with an audio stream with RTP and RTCP + * components. + * @param isTrickling indicates whether the newly created agent should be + * performing trickle ICE. + * @param harvesters the list of {@link CandidateHarvester}s that the new + * agent should use or null if it should include the default ones. + * + * @throws Throwable if anything goes wrong. + */ + protected static Agent createAgent(int rtpPort, + boolean isTrickling, + List harvesters) + throws Throwable { long startTime = System.currentTimeMillis(); Agent agent = new Agent(); agent.setTrickling(isTrickling); - // STUN - StunCandidateHarvester stunHarv = new StunCandidateHarvester( - new TransportAddress("stun.jitsi.net", 3478, Transport.UDP)); - StunCandidateHarvester stun6Harv = new StunCandidateHarvester( - new TransportAddress("stun6.jitsi.net", 3478, Transport.UDP)); + if(harvesters == null) + { + // STUN + StunCandidateHarvester stunHarv = new StunCandidateHarvester( + new TransportAddress("stun.jitsi.net", 3478, Transport.UDP)); + StunCandidateHarvester stun6Harv = new StunCandidateHarvester( + new TransportAddress("stun6.jitsi.net", 3478, Transport.UDP)); - agent.addCandidateHarvester(stunHarv); - agent.addCandidateHarvester(stun6Harv); + agent.addCandidateHarvester(stunHarv); + agent.addCandidateHarvester(stun6Harv); - // TURN - String[] hostnames = new String[] - { - "stun.jitsi.net", - "stun6.jitsi.net" - }; - int port = 3478; - LongTermCredential longTermCredential - = new LongTermCredential("guest", "anonymouspower!!"); + // TURN + String[] hostnames = new String[] + { + "stun.jitsi.net", + "stun6.jitsi.net" + }; + int port = 3478; + LongTermCredential longTermCredential + = new LongTermCredential("guest", "anonymouspower!!"); - for (String hostname : hostnames) - agent.addCandidateHarvester( - new TurnCandidateHarvester( - new TransportAddress(hostname, port, Transport.UDP), - longTermCredential)); + for (String hostname : hostnames) + agent.addCandidateHarvester( + new TurnCandidateHarvester( + new TransportAddress( + hostname, port, Transport.UDP), + longTermCredential)); - //UPnP: adding an UPnP harvester because they are generally slow - //which makes it more convenient to test things like trickle. - agent.addCandidateHarvester( new UPNPHarvester() ); + //UPnP: adding an UPnP harvester because they are generally slow + //which makes it more convenient to test things like trickle. + agent.addCandidateHarvester( new UPNPHarvester() ); + } + else + { + for(CandidateHarvester harvester: harvesters) + { + agent.addCandidateHarvester(harvester); + } + } //STREAMS createStream(rtpPort, "audio", agent);