From b687bdb9ebe984036fdb4a897c417a10444408b5 Mon Sep 17 00:00:00 2001 From: seb Date: Thu, 9 Jun 2011 08:47:22 +0000 Subject: [PATCH] Support of the Google ICE dialect (UDP only for now). --- src/org/ice4j/ice/Agent.java | 300 ++++++++- src/org/ice4j/ice/Candidate.java | 52 ++ src/org/ice4j/ice/CandidateType.java | 29 +- src/org/ice4j/ice/CompatibilityMode.java | 25 + src/org/ice4j/ice/Component.java | 16 +- .../ice4j/ice/ConnectivityCheckClient.java | 184 ++++-- .../ice4j/ice/ConnectivityCheckServer.java | 95 ++- src/org/ice4j/ice/GoogleRelayedCandidate.java | 146 +++++ src/org/ice4j/ice/LocalCandidate.java | 25 + src/org/ice4j/ice/NetworkUtils.java | 7 +- src/org/ice4j/ice/RemoteCandidate.java | 41 ++ .../harvest/GoogleTurnCandidateHarvest.java | 390 ++++++++++++ .../harvest/GoogleTurnCandidateHarvester.java | 68 +++ .../ice/harvest/HostCandidateHarvester.java | 1 - .../ice/harvest/StunCandidateHarvest.java | 17 +- src/org/ice4j/message/Indication.java | 6 +- src/org/ice4j/message/Message.java | 255 +++++++- src/org/ice4j/message/MessageFactory.java | 68 +++ .../GoogleRelayedCandidateDatagramSocket.java | 577 ++++++++++++++++++ .../socket/StunDatagramPacketFilter.java | 24 + .../socket/TurnDatagramPacketFilter.java | 1 + src/org/ice4j/stack/Connector.java | 2 +- src/org/ice4j/stack/EventDispatcher.java | 65 +- src/org/ice4j/stack/MessageQueue.java | 5 +- src/org/ice4j/stack/NetAccessManager.java | 2 +- src/org/ice4j/stack/StunStack.java | 52 +- src/org/ice4j/stack/TransactionID.java | 97 ++- test/test/Ice.java | 2 +- 28 files changed, 2385 insertions(+), 167 deletions(-) create mode 100644 src/org/ice4j/ice/CompatibilityMode.java create mode 100644 src/org/ice4j/ice/GoogleRelayedCandidate.java create mode 100644 src/org/ice4j/ice/harvest/GoogleTurnCandidateHarvest.java create mode 100644 src/org/ice4j/ice/harvest/GoogleTurnCandidateHarvester.java create mode 100644 src/org/ice4j/socket/GoogleRelayedCandidateDatagramSocket.java diff --git a/src/org/ice4j/ice/Agent.java b/src/org/ice4j/ice/Agent.java index 8f37bdc..e219016 100644 --- a/src/org/ice4j/ice/Agent.java +++ b/src/org/ice4j/ice/Agent.java @@ -36,6 +36,7 @@ import org.ice4j.stack.*; * * @author Emil Ivov * @author Lyubomir Marinov + * @author Sebastien Vincent */ public class Agent { @@ -101,6 +102,11 @@ public class Agent */ private final DefaultNominator nominator; + /** + * ICE compatibility mode for this agent. + */ + private CompatibilityMode compatibilityMode = CompatibilityMode.RFC5245; + /** * The name of the {@link PropertyChangeEvent} that we use to deliver * events on changes in the state of ICE processing in this agent. @@ -156,14 +162,12 @@ public class Agent /** * The entity that will be taking care of outgoing connectivity checks. */ - private final ConnectivityCheckClient connCheckClient - = new ConnectivityCheckClient(this); + private final ConnectivityCheckClient connCheckClient; /** * The entity that will be taking care of incoming connectivity checks. */ - private final ConnectivityCheckServer connCheckServer - = new ConnectivityCheckServer(this); + private final ConnectivityCheckServer connCheckServer; /** * Indicates the state of ICE processing in this Agent. An @@ -195,6 +199,11 @@ public class Agent */ private TerminationThread terminationThread; + /** + * The thread that we use for STUN keep-alive. + */ + private StunKeepAliveThread stunKeepAliveThread; + /** * Some protocols, such as XMPP, need to be able to distinguish the separate * ICE sessions that occur as a result of ICE restarts, which is why we need @@ -205,24 +214,53 @@ public class Agent private int generation = 0; /** - * Creates an empty Agent with no streams, and no address + * 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(); - ufrag = new BigInteger(24, random).toString(32); - password = new BigInteger(128, random).toString(32); + this.compatibilityMode = compatibilityMode; - tieBreaker = Math.abs(random.nextLong()); + connCheckServer = new ConnectivityCheckServer(this); + connCheckClient = new ConnectivityCheckClient(this); + + //add the FINGERPRINT attribute to all messages. + System.setProperty(StackProperties.ALWAYS_SIGN, "true"); //add the software attribute to all messages if (StackProperties.getString(StackProperties.SOFTWARE) == null) System.setProperty(StackProperties.SOFTWARE, "ice4j.org"); - //add the FINGERPRINT attribute to all messages. - System.setProperty(StackProperties.ALWAYS_SIGN, "true"); + if(compatibilityMode == CompatibilityMode.GTALK) + { + /* username is 16 byte in Google Talk dialect but it is set + * for each candidate and not globally + */ + ufrag = null; + /* no password in 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); + } + + tieBreaker = Math.abs(random.nextLong()); nominator = new DefaultNominator(this); } @@ -278,6 +316,8 @@ public class Agent IOException, BindException { + SecureRandom random = new SecureRandom(); + if(transport != Transport.UDP) { throw new IllegalArgumentException( @@ -295,6 +335,29 @@ 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) + { + continue; + } + + String s = null; + while(s == null || s.length() != 16) + { + s = new BigInteger(80, random).toString(32); + } + + localCand.setUfrag(s); + } } /* @@ -628,13 +691,15 @@ public class Agent public String generateLocalUserName(String media) { IceMediaStream stream = getStream(media); + String ret = null; if(stream == null || stream.getRemoteUfrag() == null) { return null; } - return stream.getRemoteUfrag() + ":" + getLocalUfrag(); + ret = stream.getRemoteUfrag() + ":" + getLocalUfrag(); + return ret; } /** @@ -661,13 +726,83 @@ public class Agent public String generateRemoteUserName(String media) { IceMediaStream stream = getStream(media); + String ret = null; if(stream == null) { return null; } - return getLocalUfrag() + ":" + stream.getRemoteUfrag(); + if(compatibilityMode == CompatibilityMode.RFC5245) + { + ret = getLocalUfrag() + ":" + stream.getRemoteUfrag(); + } + else if(compatibilityMode == CompatibilityMode.GTALK) + { + ret = getLocalUfrag() + stream.getRemoteUfrag(); + } + + return ret; + } + + /** + * Returns the user name that this Agent should use in connectivity + * checks for outgoing Binding Requests in a Google Talk session. + * + * @param remoteCandidate remote candidate + * @param localCandidate local candidate + * @return a user name that this Agent can use in connectivity + * check for outgoing Binding Requests. + */ + public String generateLocalUserName(RemoteCandidate remoteCandidate, + LocalCandidate localCandidate) + { + String ret = null; + String remoteUfrag = remoteCandidate.getUfrag(); + String localUfrag = localCandidate.getUfrag(); + + /* Google Talk specific + * each candidate has its own username/password + */ + if(localUfrag == null || remoteUfrag == null || + compatibilityMode != CompatibilityMode.GTALK) + { + return null; + } + + ret = remoteUfrag + localUfrag; + return ret; + } + + /** + * Returns the user name that we should expect a peer Agent to use + * in connectivity checks for Binding Requests its sending our way in a + * Google Talk session. + * + * @param remoteCandidate remote candidate + * @param localCandidate local candidate + * @return a user name that a peer Agent would use in connectivity + * check for outgoing Binding Requests. + */ + public String generateRemoteUserName(RemoteCandidate remoteCandidate, + LocalCandidate localCandidate) + { + String ret = null; + String remoteUfrag = remoteCandidate.getUfrag(); + String localUfrag = localCandidate.getUfrag(); + + /* Google Talk specific + * each candidate has its own username/password + */ + if(remoteUfrag == null || localUfrag == null || + compatibilityMode != CompatibilityMode.GTALK) + { + return null; + } + + ret = localUfrag + remoteUfrag; + + return ret; } /** @@ -750,7 +885,6 @@ public class Agent */ List getStreamsWithPendingConnectivityEstablishment() { - /* * Lyubomir: We want to support establishing connectivity for streams * which have been created after connectivity has been established for @@ -782,7 +916,7 @@ public class Agent public synchronized StunStack getStunStack() { if (stunStack == null) - stunStack = new StunStack(); + stunStack = new StunStack(compatibilityMode); return stunStack; } @@ -1017,11 +1151,34 @@ public class Agent Component parentComponent = localCandidate.getParentComponent(); - RemoteCandidate remoteCandidate = new RemoteCandidate( - remoteAddress, parentComponent, - CandidateType.PEER_REFLEXIVE_CANDIDATE, - foundationsRegistry.obtainFoundationForPeerReflexiveCandidate(), - priority); + RemoteCandidate remoteCandidate = null; + + // we need to find the username for the couple + if(compatibilityMode == CompatibilityMode.GTALK) + { + CandidatePair pair = findCandidatePair(localAddress, remoteAddress); + if(pair == null) + { + return; + } + + remoteCandidate = new RemoteCandidate( + remoteAddress, parentComponent, + CandidateType.PEER_REFLEXIVE_CANDIDATE, + foundationsRegistry. + obtainFoundationForPeerReflexiveCandidate(), + priority, + ((RemoteCandidate)pair.getRemoteCandidate()).getUfrag()); + } + else + { + remoteCandidate = new RemoteCandidate( + remoteAddress, parentComponent, + CandidateType.PEER_REFLEXIVE_CANDIDATE, + foundationsRegistry. + obtainFoundationForPeerReflexiveCandidate(), + priority); + } CandidatePair triggeredPair = new CandidatePair(localCandidate, remoteCandidate); @@ -1072,7 +1229,8 @@ public class Agent { //if the incoming request contained a USE-CANDIDATE attribute then //make sure we don't lose this piece of info. - if (triggerPair.useCandidateReceived()) + if (triggerPair.useCandidateReceived() || + compatibilityMode == CompatibilityMode.GTALK) knownPair.setUseCandidateReceived(); triggerPair = knownPair; @@ -1193,6 +1351,7 @@ public class Agent && !parentStream.validListContainsNomineeForComponent( parentComponent)) { + logger.info("verify if nominated pair answer again"); pair.nominate(); pair.getParentComponent().getParentStream() .getCheckList().scheduleTriggeredCheck(pair); @@ -1252,6 +1411,9 @@ public class Agent boolean allListsEnded = true; boolean atLeastOneListSucceeded = false; + if(state == IceProcessingState.COMPLETED) + return; + List streams = getStreams(); for(IceMediaStream stream : streams) @@ -1280,8 +1442,20 @@ public class Agent if(getState() == IceProcessingState.RUNNING) { logger.info("ICE state is COMPLETED"); + setState(IceProcessingState.COMPLETED); - scheduleTermination(); + + // keep ICE running (answer binding request) + if(compatibilityMode == CompatibilityMode.GTALK + && stunKeepAliveThread == null) + { + // schedule STUN checks for selected candidates + scheduleSTUNKeepAlive(); + } + else + { + scheduleTermination(); + } List strms = getStreams(); @@ -1479,6 +1653,18 @@ public class Agent } } + /** + * Initializes and starts the {@link STUNKeepAliveThread} + */ + private void scheduleSTUNKeepAlive() + { + if (stunKeepAliveThread == null) + { + stunKeepAliveThread = new StunKeepAliveThread(); + stunKeepAliveThread.start(); + } + } + /** * RFC 5245 says: Once ICE processing has reached the Completed state for * all peers for media streams using those candidates, the agent SHOULD @@ -1621,4 +1807,76 @@ public class Agent { this.generation = generation; } + + /** + * Returns the compatibility mode used by this agent. + * + * @return compatibility mode + */ + public CompatibilityMode getCompatibilityMode() + { + return compatibilityMode; + } + + /** + * Thread that performs STUN keep-alive once ICE has COMPLETED. + */ + private class StunKeepAliveThread + extends Thread + { + /** + * Creates a new termination timer. + */ + private StunKeepAliveThread() + { + super("StunKeepAliveThread"); + } + + /** + * Thread entry to point. + */ + @Override + public synchronized void run() + { + runInStunKeepAliveThread(); + } + } + + /** + * Schedule STUN checks for selected pair. + */ + public void runInStunKeepAliveThread() + { + while(state == IceProcessingState.COMPLETED) + { + List streams = getStreams(); + + for(IceMediaStream stream : streams) + { + List cmps = stream.getComponents(); + for(Component cmp : cmps) + { + CandidatePair pair = cmp.getSelectedPair(); + + if(pair != null) + { + connCheckClient.startCheckForPair(pair); + pair = null; + } + } + stream = null; + } + + streams = null; + + try + { + Thread.sleep(5000); + Thread.yield(); + } + catch(InterruptedException e) + { + } + } + } } diff --git a/src/org/ice4j/ice/Candidate.java b/src/org/ice4j/ice/Candidate.java index dee572f..cefe625 100644 --- a/src/org/ice4j/ice/Candidate.java +++ b/src/org/ice4j/ice/Candidate.java @@ -321,6 +321,20 @@ public abstract class Candidate return this.priority; } + /** + * Computes the priority for this Candidate based on the procedures + * defined in the Google Talk specification. + * + * @return the priority for this Candidate as per the procedures + * defined in the ICE specification.. + */ + public long computeGTalkPriority() + { + this.priority = computeGTalkPriorityForType(getType()); + + return this.priority; + } + /** * Computes the priority this Candidate would have if it were of * the specified candidateType and based on the procedures @@ -345,7 +359,45 @@ public abstract class Candidate return (long) (getTypePreference(candidateType) << 24) + (long) (getLocalPreference() << 8 ) + (long) (256 - getParentComponent().getComponentID()); + } + /** + * Computes the priority this Candidate would have if it were of + * the specified candidateType and based on the procedures + * defined in the Google Talk specification. + * + * @param candidateType the hypothetical type that we'd like to use when + * computing the priority for this Candidate. + * @return the priority this Candidate would have had if it were + * of the specified candidateType. + */ + public long computeGTalkPriorityForType(CandidateType candidateType) + { + long priority = 0; + + /* 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) + { + priority += 1 * 1000; + } + else if(candidateType == CandidateType.PEER_REFLEXIVE_CANDIDATE) + { + priority += (long)(0.9 * 1000); + } + else if(candidateType == CandidateType.SERVER_REFLEXIVE_CANDIDATE) + { + priority += (long)(0.9 * 1000); + } + else //relayed candidates + { + priority += (long)(0.5 * 1000); + } + + priority -= getParentComponent().getComponentID() - 1; + + return priority; } /** diff --git a/src/org/ice4j/ice/CandidateType.java b/src/org/ice4j/ice/CandidateType.java index 9647dce..e8d5b7a 100644 --- a/src/org/ice4j/ice/CandidateType.java +++ b/src/org/ice4j/ice/CandidateType.java @@ -47,7 +47,27 @@ public enum CandidateType * Private Networks (VPNs) and Realm Specific IP (RSIP) [RFC3102] * (which lives at the operating system level). */ - HOST_CANDIDATE("host"); + HOST_CANDIDATE("host"), + + /** + * A candidate obtained by binding to a specific port + * from an interface on the host. This includes both physical + * interfaces and logical ones, such as ones obtained through Virtual + * Private Networks (VPNs) and Realm Specific IP (RSIP) [RFC3102] + * (which lives at the operating system level). This is the old name for + * "host". + */ + LOCAL_CANDIDATE("local"), + + /** + * A Server Reflexive Candidate is a candidate whose IP address and port + * are a binding allocated by a NAT for an agent when it sent a + * packet through the NAT to a server. Server reflexive candidates + * can be learned by STUN servers using the Binding Request, or TURN + * servers, which provides both a Relayed and Server Reflexive + * candidate. This is the old name for "srflx". + */ + STUN_CANDIDATE("stun"); /** * The name of this CandidateType instance. @@ -105,6 +125,13 @@ public enum CandidateType if(HOST_CANDIDATE.toString().equals(candidateTypeName)) return HOST_CANDIDATE; + // old name but returns the standard name + if(STUN_CANDIDATE.toString().equals(candidateTypeName)) + return SERVER_REFLEXIVE_CANDIDATE; + + if(LOCAL_CANDIDATE.toString().equals(candidateTypeName)) + return HOST_CANDIDATE; + throw new IllegalArgumentException( candidateTypeName + " is not a currently supported CandidateType"); } diff --git a/src/org/ice4j/ice/CompatibilityMode.java b/src/org/ice4j/ice/CompatibilityMode.java new file mode 100644 index 0000000..b567660 --- /dev/null +++ b/src/org/ice4j/ice/CompatibilityMode.java @@ -0,0 +1,25 @@ +/* + * 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 37858ff..565be15 100644 --- a/src/org/ice4j/ice/Component.java +++ b/src/org/ice4j/ice/Component.java @@ -253,7 +253,8 @@ public class Component { if(localCnd.canReach(remoteCnd)) { - CandidatePair pair = new CandidatePair(localCnd, remoteCnd); + CandidatePair pair = new CandidatePair(localCnd, + remoteCnd); checkList.add(pair); } @@ -458,13 +459,24 @@ public class Component { synchronized(localCandidates) { + CompatibilityMode compat = getParentStream().getParentAgent(). + getCompatibilityMode(); LocalCandidate[] candidates = new LocalCandidate[localCandidates.size()]; localCandidates.toArray(candidates); //first compute the actual priorities for (Candidate cand : candidates) - cand.computePriority(); + { + if(compat == CompatibilityMode.GTALK) + { + cand.computeGTalkPriority(); + } + else + { + cand.computePriority(); + } + } //sort Arrays.sort(candidates, candidatePrioritizer); diff --git a/src/org/ice4j/ice/ConnectivityCheckClient.java b/src/org/ice4j/ice/ConnectivityCheckClient.java index 3ba970b..2652ddb 100644 --- a/src/org/ice4j/ice/ConnectivityCheckClient.java +++ b/src/org/ice4j/ice/ConnectivityCheckClient.java @@ -110,68 +110,87 @@ class ConnectivityCheckClient * check client transaction or null if sending the check has * failed for some reason. */ - private TransactionID startCheckForPair(CandidatePair candidatePair) + protected TransactionID startCheckForPair(CandidatePair candidatePair) { LocalCandidate localCandidate = candidatePair.getLocalCandidate(); //we don't need to do a canReach() verification here as it has been //already verified during the gathering process. - DatagramSocket stunSocket = localCandidate.getStunSocket(null); Request request = MessageFactory.createBindingRequest(); - //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()) + if(parentAgent.getCompatibilityMode() == CompatibilityMode.GTALK) { - request.addAttribute(AttributeFactory - .createIceControllingAttribute(parentAgent - .getTieBreaker())); + /* Google Talk ICE dialect just need the username */ + String localUserName = parentAgent.generateLocalUserName( + (RemoteCandidate)candidatePair.getRemoteCandidate(), + candidatePair.getLocalCandidate()); - //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()); - } + UsernameAttribute unameAttr = + AttributeFactory.createUsernameAttribute(localUserName); + + request.addAttribute(unameAttr); } else { - request.addAttribute(AttributeFactory - .createIceControlledAttribute(parentAgent - .getTieBreaker())); + //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 localUserName = parentAgent.generateLocalUserName( + candidatePair.getParentComponent().getParentStream(). + getName()); + + 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( + candidatePair.getParentComponent().getParentStream(). + getName()); + + request.addAttribute(msgIntegrity); } - //credentials - String localUserName = parentAgent.generateLocalUserName( - candidatePair.getParentComponent().getParentStream().getName()); - - 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( - candidatePair.getParentComponent().getParentStream().getName()); - - request.addAttribute(msgIntegrity); - TransactionID tran = TransactionID.createNewTransactionID(); tran.setApplicationData(candidatePair); @@ -197,13 +216,16 @@ class ConnectivityCheckClient } catch (Exception ex) { + DatagramSocket stunSocket = localCandidate.getStunSocket(null); logger.log( Level.INFO, "Failed to send " + request + " through " + stunSocket.getLocalSocketAddress(), ex); + stunSocket = null; tran = null; } + return tran; } @@ -334,21 +356,44 @@ class ConnectivityCheckClient CandidatePair checkedPair = (CandidatePair) evt.getTransactionID().getApplicationData(); - if(! response.containsAttribute(Attribute.XOR_MAPPED_ADDRESS)) + TransportAddress mappedAddress = null; + if(this.parentAgent.getCompatibilityMode() == CompatibilityMode.GTALK) { - logger.fine("Received a success response with no " - + "XOR_MAPPED_ADDRESS attribute."); - logger.info("Pair failed: " + checkedPair.toShortString()); - checkedPair.setStateFailed(); - return; //malformed error response + if(!response.containsAttribute(Attribute.MAPPED_ADDRESS)) + { + 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 + } + + MappedAddressAttribute mappedAddressAttr + = (MappedAddressAttribute)response + .getAttribute(Attribute.MAPPED_ADDRESS); + + mappedAddress = mappedAddressAttr.getAddress(); } + 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); - TransportAddress mappedAddress = mappedAddressAttr - .getAddress(response.getTransactionID()); + mappedAddress = mappedAddressAttr + .getAddress(response.getTransactionID()); + } LocalCandidate validLocalCandidate = parentAgent .findLocalCandidate(mappedAddress); @@ -367,13 +412,22 @@ class ConnectivityCheckClient // pair from which the STUN check was sent. //o Its priority is set equal to the value of the PRIORITY attribute // in the Binding request. - PriorityAttribute prioAttr = (PriorityAttribute)request - .getAttribute(Attribute.PRIORITY); + long priority = 0; + if(parentAgent.getCompatibilityMode() == CompatibilityMode.GTALK) + { + priority = 900; + } + else + { + PriorityAttribute prioAttr = (PriorityAttribute)request + .getAttribute(Attribute.PRIORITY); + priority = prioAttr.getPriority(); + } LocalCandidate peerReflexiveCandidate = new PeerReflexiveCandidate( mappedAddress, checkedPair.getParentComponent(), checkedPair.getLocalCandidate(), - prioAttr.getPriority()); + priority); peerReflexiveCandidate.setBase(checkedPair.getLocalCandidate()); @@ -480,8 +534,10 @@ class ConnectivityCheckClient //If the agent was a controlling agent, and it had included a USE- //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)) + if((parentAgent.isControlling() + && (request.containsAttribute(Attribute.USE_CANDIDATE)) || + parentAgent.getCompatibilityMode() == + CompatibilityMode.GTALK)) { logger.info("Nomination confirmed for pair: " + validPair.toShortString()); diff --git a/src/org/ice4j/ice/ConnectivityCheckServer.java b/src/org/ice4j/ice/ConnectivityCheckServer.java index 6ef668d..f43674e 100644 --- a/src/org/ice4j/ice/ConnectivityCheckServer.java +++ b/src/org/ice4j/ice/ConnectivityCheckServer.java @@ -91,18 +91,13 @@ class ConnectivityCheckServer UsernameAttribute uname = (UsernameAttribute)request .getAttribute(Attribute.USERNAME); - if(uname == null - || !checkLocalUserName(new String(uname.getUsername()))) + if(uname == null || + (parentAgent.getCompatibilityMode() == CompatibilityMode.RFC5245 + && !checkLocalUserName(new String(uname.getUsername())))) { return; } - String username = new String(uname.getUsername()); - int colon = username.indexOf(":"); - - //caller gave us the entire username. - String remoteUfrag = username.substring(0, colon); - //detect role conflicts if( ( parentAgent.isControlling() && request.containsAttribute(Attribute.ICE_CONTROLLING)) @@ -113,9 +108,37 @@ class ConnectivityCheckServer return; } - long priority = extractPriority(request); + long priority = 0; boolean useCandidate = request.containsAttribute(Attribute.USE_CANDIDATE); + String username = new String(uname.getUsername()); + //caller gave us the entire username. + String remoteUfrag = null; + + if(parentAgent.getCompatibilityMode() == CompatibilityMode.GTALK) + { + /* Google Talk ICE dialect considers every request to have + * USE-CANDIDATE behavior. + */ + useCandidate = 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); + } + else + { + 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(), @@ -131,13 +154,24 @@ class ConnectivityCheckServer */ Attribute usernameAttribute = AttributeFactory.createUsernameAttribute(uname.getUsername()); - - Attribute messageIntegrityAttribute = - AttributeFactory.createMessageIntegrityAttribute( - new String(uname.getUsername())); - response.addAttribute(usernameAttribute); - response.addAttribute(messageIntegrityAttribute); + + if(parentAgent.getCompatibilityMode() == CompatibilityMode.GTALK) + { + /* add Mapped address */ + 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); + } try { @@ -186,7 +220,7 @@ class ConnectivityCheckServer if(logger.isLoggable(Level.FINE)) { logger.log(Level.FINE, "Received a connectivity ckeck with" - +"no PRIORITY attribute. Discarting."); + + "no PRIORITY attribute. Discarding."); } throw new IllegalArgumentException("Missing PRIORITY attribtue!"); @@ -326,18 +360,33 @@ class ConnectivityCheckServer */ public boolean checkLocalUserName(String username) { - int colon = username.indexOf(":"); - String ufrag; + String ufrag = null; - if (colon < 0) + if(parentAgent.getCompatibilityMode() == CompatibilityMode.GTALK) { - //caller gave us a ufrag - ufrag = username; + if(username.length() == 32) + { + ufrag = username.substring(0, 16); + } + else + { + ufrag = username; + } } else { - //caller gave us the entire username. - ufrag = username.substring(0, colon); + 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); + } } return ufrag.equals(parentAgent.getLocalUfrag()); } diff --git a/src/org/ice4j/ice/GoogleRelayedCandidate.java b/src/org/ice4j/ice/GoogleRelayedCandidate.java new file mode 100644 index 0000000..c94d229 --- /dev/null +++ b/src/org/ice4j/ice/GoogleRelayedCandidate.java @@ -0,0 +1,146 @@ +/* + * 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; + +import java.lang.reflect.*; +import java.net.*; + +import org.ice4j.*; +import org.ice4j.ice.harvest.*; +import org.ice4j.socket.*; + +/** + * Represents a Candidate obtained by sending a Google TURN Allocate + * request from a HostCandidate to a TURN server. The Google relayed + * candidate is resident on the TURN server, and the TURN server relays packets + * back towards the agent. + * + * @author Lubomir Marinov + * @author Sebastien Vincent + */ +public class GoogleRelayedCandidate + extends LocalCandidate +{ + /** + * The RelayedCandidateDatagramSocket of this + * GoogleRelayedCandidate. + */ + private GoogleRelayedCandidateDatagramSocket relayedCandidateDatagramSocket; + + /** + * The application-purposed DatagramSocket associated with this + * Candidate. + */ + private DatagramSocket socket; + + /** + * The GoogleTurnCandidateHarvest which has harvested this + * GoogleRelayedCandidate. + */ + private final GoogleTurnCandidateHarvest turnCandidateHarvest; + + /** + * Username. + */ + private final String username; + + /** + * Initializes a new RelayedCandidate which is to represent a + * specific TransportAddress harvested through a specific + * HostCandidate and a TURN server with a specific + * TransportAddress. + * + * @param transportAddress the TransportAddress to be represented + * by the new instance + * @param turnCandidateHarvest the TurnCandidateHarvest which has + * harvested the new instance + * @param mappedAddress the mapped TransportAddress reported by the + * TURN server with the delivery of the replayed transportAddress + * to be represented by the new instance + * @param username username (Send request to the Google relay server need + * it + */ + public GoogleRelayedCandidate( + TransportAddress transportAddress, + GoogleTurnCandidateHarvest turnCandidateHarvest, + TransportAddress mappedAddress, + String username) + { + super( + transportAddress, + turnCandidateHarvest.hostCandidate.getParentComponent(), + CandidateType.RELAYED_CANDIDATE); + + this.turnCandidateHarvest = turnCandidateHarvest; + this.username = username; + + // RFC 5245: The base of a relayed candidate is that candidate itself. + setBase(this); + setRelayServerAddress(turnCandidateHarvest.harvester.stunServer); + setMappedAddress(mappedAddress); + } + + /** + * Gets the RelayedCandidateDatagramSocket of this + * RelayedCandidate. + *

+ * Note: The method is part of the internal API of + * RelayedCandidate and TurnCandidateHarvest and is not + * intended for public use. + *

+ * + * @return the RelayedCandidateDatagramSocket of this + * RelayedCandidate + */ + public synchronized GoogleRelayedCandidateDatagramSocket + getRelayedCandidateDatagramSocket() + { + if (relayedCandidateDatagramSocket == null) + { + try + { + relayedCandidateDatagramSocket + = new GoogleRelayedCandidateDatagramSocket( + this, + turnCandidateHarvest, + username); + } + catch (SocketException sex) + { + throw new UndeclaredThrowableException(sex); + } + } + return relayedCandidateDatagramSocket; + } + + /** + * Gets the application-purposed DatagramSocket associated with + * this Candidate. + * + * @return the DatagramSocket associated with this + * Candidate + * @see LocalCandidate#getSocket() + */ + public synchronized DatagramSocket getSocket() + { + if (socket == null) + { + try + { + socket + = new MultiplexingDatagramSocket( + getRelayedCandidateDatagramSocket()); + } + catch (SocketException sex) + { + throw new UndeclaredThrowableException(sex); + } + } + return socket; + } +} \ No newline at end of file diff --git a/src/org/ice4j/ice/LocalCandidate.java b/src/org/ice4j/ice/LocalCandidate.java index e0ec25d..a9fe8c9 100644 --- a/src/org/ice4j/ice/LocalCandidate.java +++ b/src/org/ice4j/ice/LocalCandidate.java @@ -24,6 +24,11 @@ import org.ice4j.stack.*; public abstract class LocalCandidate extends Candidate { + /** + * Ufrag for the local candidat + */ + private String ufrag = null; + /** * The Logger used by the LocalCandidate class and its * instances for logging output. @@ -191,4 +196,24 @@ public abstract class LocalCandidate return (parentCmp != null) && equals(parentCmp.getDefaultCandidate()); } + + /** + * Set the local ufrag. + * + * @param ufrag local ufrag + */ + public void setUfrag(String ufrag) + { + this.ufrag = ufrag; + } + + /** + * Get the local ufrag. + * + * @return local ufrag + */ + public String getUfrag() + { + return ufrag; + } } diff --git a/src/org/ice4j/ice/NetworkUtils.java b/src/org/ice4j/ice/NetworkUtils.java index 1c15857..2b860af 100644 --- a/src/org/ice4j/ice/NetworkUtils.java +++ b/src/org/ice4j/ice/NetworkUtils.java @@ -61,17 +61,16 @@ public class NetworkUtils public static final String IN_ADDR_ANY = determineAnyAddress(); /** - * The maximum int value that could correspond to a port nubmer. + * The maximum int value that could correspond to a port number. */ public static final int MAX_PORT_NUMBER = 65535; /** - * The minimum int value that could correspond to a port nubmer bindable - * by the SIP Communicator. + * The minimum int value that could correspond to a port number bindable + * by ice4j. */ public static final int MIN_PORT_NUMBER = 1024; - /** * The random port number generator that we use in getRandomPortNumer() */ diff --git a/src/org/ice4j/ice/RemoteCandidate.java b/src/org/ice4j/ice/RemoteCandidate.java index 51a2467..ee209fa 100644 --- a/src/org/ice4j/ice/RemoteCandidate.java +++ b/src/org/ice4j/ice/RemoteCandidate.java @@ -24,6 +24,11 @@ public class RemoteCandidate */ private TransportAddress raddr; + /** + * Ufrag for the Google Talk candidate. + */ + private String ufrag = null; + /** * Creates a RemoteCandidate instance for the specified transport * address and properties. @@ -49,6 +54,32 @@ public class RemoteCandidate setPriority(priority); } + /** + * Creates a RemoteCandidate instance for the specified transport + * address and properties. + * + * @param transportAddress the transport address that this candidate is + * encapsulating. + * @param parentComponent the Component that this candidate + * belongs to. + * @param type the CandidateType for this Candidate. + * @param foundation the RemoteCandidate's foundation as reported + * by the session description protocol. + * @param priority the RemoteCandidate's priority as reported + * by the session description protocol. + * @param ufrag ufrag for the remote candidate + */ + public RemoteCandidate(TransportAddress transportAddress, + Component parentComponent, + CandidateType type, + String foundation, + long priority, + String ufrag) + { + this(transportAddress, parentComponent, type, foundation, priority); + this.ufrag = ufrag; + } + /** * Sets the priority of this RemoteCandidate. Priority is a unique * priority number that MUST be a positive integer between 1 and @@ -114,4 +145,14 @@ public class RemoteCandidate { this.raddr = relatedAddr; } + + /** + * Get the remote ufrag. + * + * @return remote ufrag + */ + public String getUfrag() + { + return ufrag; + } } diff --git a/src/org/ice4j/ice/harvest/GoogleTurnCandidateHarvest.java b/src/org/ice4j/ice/harvest/GoogleTurnCandidateHarvest.java new file mode 100644 index 0000000..c3f374b --- /dev/null +++ b/src/org/ice4j/ice/harvest/GoogleTurnCandidateHarvest.java @@ -0,0 +1,390 @@ +/* + * 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.harvest; + +import java.util.logging.*; + +import org.ice4j.*; +import org.ice4j.attribute.*; +import org.ice4j.ice.*; +import org.ice4j.message.*; +import org.ice4j.socket.*; +import org.ice4j.stack.*; + +/** + * Represents the harvesting of Google TURN Candidates for a specific + * HostCandidate performed by a specific + * GoogleTurnCandidateHarvester. + * + * @author Lyubomir Marinov + * @author Sebastien Vincent + */ +public class GoogleTurnCandidateHarvest + extends StunCandidateHarvest +{ + /** + * The Logger used by the TurnCandidateHarvest class and + * its instances for logging output. + */ + private static final Logger logger + = Logger.getLogger(GoogleTurnCandidateHarvest.class.getName()); + + /** + * The Request created by the last call to + * {@link #createRequestToStartResolvingCandidate()}. + */ + private Request requestToStartResolvingCandidate; + + /** + * Initializes a new TurnCandidateHarvest which is to represent the + * harvesting of TURN Candidates for a specific + * HostCandidate performed by a specific + * TurnCandidateHarvester. + * + * @param harvester the TurnCandidateHarvester which is performing + * the TURN harvesting + * @param hostCandidate the HostCandidate for which TURN + * Candidates are to be harvested + */ + public GoogleTurnCandidateHarvest( + GoogleTurnCandidateHarvester harvester, + HostCandidate hostCandidate) + { + super(harvester, hostCandidate); + } + + /** + * Creates new Candidates determined by a specific STUN + * Response. + * + * @param response the received STUN Response + * @see StunCandidateHarvest#createCandidates(Response) + */ + @Override + protected void createCandidates(Response response) + { + createRelayedCandidate(response); + } + + /** + * Creates a RelayedCandidate using the + * XOR-RELAYED-ADDRESS attribute in a specific STUN + * Response for the actual TransportAddress of the new + * candidate. If the message is malformed and/or does not contain the + * corresponding attribute, this method simply has no effect. + * + * @param response the STUN Response which is supposed to contain + * the address we should use for the new candidate + */ + private void createRelayedCandidate(Response response) + { + Attribute attribute + = response.getAttribute(Attribute.MAPPED_ADDRESS); + + if(attribute != null) + { + TransportAddress relayedAddress + = ((MappedAddressAttribute) attribute).getAddress(); + GoogleRelayedCandidate relayedCandidate + = createRelayedCandidate( + relayedAddress, + getMappedAddress(response)); + + if (relayedCandidate != null) + { + /* + * The ICE connectivity checks will utilize STUN on the + * (application-purposed) socket of the RelayedCandidate and + * will not add it to the StunStack so we have to do it. + */ + harvester.getStunStack().addSocket( + relayedCandidate.getStunSocket(null)); + + addCandidate(relayedCandidate); + } + } + } + + /** + * Creates a new RelayedCandidate instance which is to represent a + * specific TransportAddress harvested through + * {@link #hostCandidate} and the TURN server associated with + * {@link #harvester}. + * + * @param transportAddress the TransportAddress to be represented + * by the new RelayedCandidate instance + * @param mappedAddress the mapped TransportAddress reported by the + * TURN server with the delivery of the relayed transportAddress to + * be represented by the new RelayedCandidate instance + * @return a new RelayedCandidate instance which represents the + * specified TransportAddress harvested through + * {@link #hostCandidate} and the TURN server associated with + * {@link #harvester} + */ + protected GoogleRelayedCandidate createRelayedCandidate( + TransportAddress transportAddress, + TransportAddress mappedAddress) + { + GoogleRelayedCandidate candidate = + new GoogleRelayedCandidate( + transportAddress, + this, + mappedAddress, + harvester.getShortTermCredentialUsername()); + + candidate.setUfrag(harvester.getShortTermCredentialUsername()); + return candidate; + } + + /** + * Creates a new Request which is to be sent to + * {@link TurnCandidateHarvester#stunServer} in order to start resolving + * {@link #hostCandidate}. + * + * @return a new Request which is to be sent to + * {@link TurnCandidateHarvester#stunServer} in order to start resolving + * {@link #hostCandidate} + * @see StunCandidateHarvest#createRequestToStartResolvingCandidate() + */ + @Override + protected Request createRequestToStartResolvingCandidate() + { + if (requestToStartResolvingCandidate == null) + { + requestToStartResolvingCandidate + = MessageFactory.createGoogleAllocateRequest( + harvester.getShortTermCredentialUsername()); + + return requestToStartResolvingCandidate; + } + else + return null; + } + + /** + * Adds the Attributes to a specific Request which support + * the STUN short-term credential mechanism if the mechanism in question is + * utilized by this StunCandidateHarvest (i.e. by the associated + * StunCandidateHarvester). + * + * @param request the Request to which to add the + * Attributes supporting the STUN short-term credential mechanism + * if the mechanism in question is utilized by this + * StunCandidateHarvest + * @return true if the STUN short-term credential mechanism is + * actually utilized by this StunCandidateHarvest for the specified + * request; otherwise, false + */ + @Override + protected boolean addShortTermCredentialAttributes(Request request) + { + return false; + } + + /** + * Completes the harvesting of Candidates for + * {@link #hostCandidate}. Notifies {@link #harvester} about the completion + * of the harvesting of Candidate for hostCandidate + * performed by this StunCandidateHarvest. + * + * @param request the Request sent by this + * StunCandidateHarvest with which the harvesting of + * Candidates for hostCandidate has completed + * @param response the Response received by this + * StunCandidateHarvest, if any, with which the harvesting of + * Candidates for hostCandidate has completed + * @return true if the harvesting of Candidates for + * hostCandidate performed by this StunCandidateHarvest + * has completed; otherwise, false + * @see StunCandidateHarvest#completedResolvingCandidate(Request, Response) + */ + @Override + protected boolean completedResolvingCandidate( + Request request, + Response response) + { + if ((response == null) + || (!response.isSuccessResponse() + && (request.getMessageType() + == Message.ALLOCATE_REQUEST))) + { + try + { + if (startResolvingCandidate()) + return false; + } + catch (Exception ex) + { + /* + * Complete the harvesting of Candidates for hostCandidate + * because the new attempt has just failed. + */ + } + } + return super.completedResolvingCandidate(request, response); + } + + /** + * Notifies this TurnCandidateHarvest that a specific + * RelayedCandidateDatagramSocket is closing and that this instance + * is to delete the associated TURN Allocation. + *

+ * Note: The method is part of the internal API of + * RelayedCandidateDatagramSocket and TurnCandidateHarvest + * and is not intended for public use. + *

+ * + * @param relayedCandidateSocket the RelayedCandidateDatagramSocket + * which notifies this instance and which requests that the associated TURN + * Allocation be deleted + */ + public void close( + GoogleRelayedCandidateDatagramSocket relayedCandidateSocket) + { + /* + * FIXME As far as logic goes, it seems that it is possible to send a + * TURN Refresh, cancel the STUN keep-alive functionality here and only + * then receive the response to the TURN Refresh which will enable the + * STUN keep-alive functionality again. + */ + setSendKeepAliveMessageInterval( + SEND_KEEP_ALIVE_MESSAGE_INTERVAL_NOT_SPECIFIED); + } + + /** + * Sends a specific Request on behalf of a specific + * RelayedCandidateDatagramSocket to the TURN server associated + * with this GoogleTurnCandidateHarvest. + * + * @param relayedCandidateDatagramSocket the + * RelayedCandidateDatagramSocket which sends the specified + * Request and which is to be notified of the result + * @param request the Request to be sent to the TURN server + * associated with this TurnCandidateHarvest + * @return an array of bytes which represents the ID of the + * transaction with which the specified Request has been sent to + * the TURN server + * @throws StunException if anything goes wrong while sending the specified + * Request + */ + public byte[] sendRequest( + RelayedCandidateDatagramSocket relayedCandidateDatagramSocket, + Request request) + throws StunException + { + TransactionID transactionID = TransactionID.createNewTransactionID(); + + transactionID.setApplicationData(relayedCandidateDatagramSocket); + transactionID = sendRequest(request, false, transactionID); + return (transactionID == null) ? null : transactionID.getBytes(); + } + + /** + * Notifies this StunCandidateHarvest that a specific + * Request has either received an error Response or has + * failed to receive any Response. + * + * @param response the error Response which has been received for + * request + * @param request the Request to which Response responds + * @param transactionID the TransactionID of response and + * request because response and request only have + * it as a byte array and TransactionID is required for + * the applicationData property value + * @return true if the error or failure condition has been + * processed and this instance can continue its execution (e.g. the + * resolution of the candidate) as if it was expected; otherwise, + * false + * @see StunCandidateHarvest#processErrorOrFailure(Response, Request, + * TransactionID) + */ + @Override + protected boolean processErrorOrFailure( + Response response, + Request request, + TransactionID transactionID) + { + logger.info("Google TURN processErrorOrFailure"); + /* + * TurnCandidateHarvest uses the applicationData of TransactionID to + * deliver the results of Requests sent by + * RelayedCandidateDatagramSocket back to it. + */ + Object applicationData = transactionID.getApplicationData(); + + if ((applicationData instanceof RelayedCandidateDatagramSocket) + && ((RelayedCandidateDatagramSocket) applicationData) + .processErrorOrFailure(response, request)) + return true; + + return super.processErrorOrFailure(response, request, transactionID); + } + + /** + * Handles a specific STUN success Response to a specific STUN + * Request. + * + * @param response the received STUN success Response which is to + * be handled + * @param request the STUN Request to which response + * responds + * @param transactionID the TransactionID of response and + * request because response and request only have + * it as a byte array and TransactionID is required for + * the applicationData property value + * @see StunCandidateHarvest#processSuccess(Response, Request, + * TransactionID) + */ + @Override + protected void processSuccess( + Response response, + Request request, + TransactionID transactionID) + { + super.processSuccess(response, request, transactionID); + + LifetimeAttribute lifetimeAttribute; + int lifetime /* minutes */ = -1; + + switch (response.getMessageType()) + { + case Message.ALLOCATE_RESPONSE: + // The default lifetime of an allocation is 10 minutes. + // The default lifetime of an allocation is 10 minutes. + lifetimeAttribute + = (LifetimeAttribute) response.getAttribute(Attribute.LIFETIME); + lifetime + = (lifetimeAttribute == null) + ? (10 * 60) + : lifetimeAttribute.getLifetime(); + logger.info("Successful Google TURN allocate"); + break; + default: + break; + } + + if (lifetime >= 0) + { + setSendKeepAliveMessageInterval( + /* milliseconds */ 1000L * lifetime); + } + + /* + * TurnCandidateHarvest uses the applicationData of TransactionID to + * deliver the results of Requests sent by + * RelayedCandidateDatagramSocket back to it. + */ + Object applicationData = transactionID.getApplicationData(); + + if (applicationData instanceof RelayedCandidateDatagramSocket) + { + ((RelayedCandidateDatagramSocket) applicationData) + .processSuccess(response, request); + } + } +} diff --git a/src/org/ice4j/ice/harvest/GoogleTurnCandidateHarvester.java b/src/org/ice4j/ice/harvest/GoogleTurnCandidateHarvester.java new file mode 100644 index 0000000..015a102 --- /dev/null +++ b/src/org/ice4j/ice/harvest/GoogleTurnCandidateHarvester.java @@ -0,0 +1,68 @@ +/* + * 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.harvest; + +import org.ice4j.*; +import org.ice4j.ice.*; + +/** + * Implements a CandidateHarvester which gathers Google TURN dialect + * Candidates for a specified {@link Component}. + * + * @author Sebastien Vincent + */ +public class GoogleTurnCandidateHarvester + extends StunCandidateHarvester +{ + /** + * Initializes a new GoogleTurnCandidateHarvester instance which + * is to work with a specific GoogleTURN server. + * + * @param turnServer the TransportAddress of the TURN server the + * new instance is to work with + */ + public GoogleTurnCandidateHarvester(TransportAddress turnServer) + { + this(turnServer, null); + } + + /** + * Initializes a new GoogleTurnCandidateHarvester instance which is + * to work with a specific TURN server using a specific username for the + * purposes of the STUN short-term credential mechanism. + * + * @param turnServer the TransportAddress of the TURN server the + * new instance is to work with + * @param shortTermCredentialUsername the username to be used by the new + * instance for the purposes of the STUN short-term credential mechanism or + * null if the use of the STUN short-term credential mechanism is + * not determined at the time of the construction of the new instance + */ + public GoogleTurnCandidateHarvester(TransportAddress turnServer, + String shortTermCredentialUsername) + { + super(turnServer, shortTermCredentialUsername); + } + + /** + * Creates a new GoogleTurnCandidateHarvest instance which is to + * perform TURN harvesting of a specific HostCandidate. + * + * @param hostCandidate the HostCandidate for which harvesting is + * to be performed by the new TurnCandidateHarvest instance + * @return a new GoogleTurnCandidateHarvest instance which is to + * perform TURN harvesting of the specified hostCandidate + * @see StunCandidateHarvester#createHarvest(HostCandidate) + */ + @Override + protected GoogleTurnCandidateHarvest createHarvest( + HostCandidate hostCandidate) + { + return new GoogleTurnCandidateHarvest(this, hostCandidate); + } +} diff --git a/src/org/ice4j/ice/harvest/HostCandidateHarvester.java b/src/org/ice4j/ice/harvest/HostCandidateHarvester.java index d6a2bc0..69db97c 100644 --- a/src/org/ice4j/ice/harvest/HostCandidateHarvester.java +++ b/src/org/ice4j/ice/harvest/HostCandidateHarvester.java @@ -200,7 +200,6 @@ public class HostCandidateHarvester int port = preferredPort; for (int i = 0; i < bindRetries; i++) { - try { DatagramSocket sock diff --git a/src/org/ice4j/ice/harvest/StunCandidateHarvest.java b/src/org/ice4j/ice/harvest/StunCandidateHarvest.java index 69c7802..bfe57b0 100644 --- a/src/org/ice4j/ice/harvest/StunCandidateHarvest.java +++ b/src/org/ice4j/ice/harvest/StunCandidateHarvest.java @@ -439,6 +439,17 @@ public class StunCandidateHarvest ((XorMappedAddressAttribute) attribute) .getAddress(response.getTransactionID()); } + + // old STUN servers (RFC3489) send MAPPED-ADDRESS address + attribute + = response.getAttribute(Attribute.MAPPED_ADDRESS); + + if(attribute instanceof MappedAddressAttribute) + { + return + ((MappedAddressAttribute) attribute) + .getAddress(); + } else return null; } @@ -991,7 +1002,7 @@ public class StunCandidateHarvest /** * Runs in {@link #sendKeepAliveMessageThread} and sends STUN * keep-alive Messages to the STUN server associated with the - * StunCandidateHarvester of this instance + * StunCandidateHarvester of this instance */ private void runInSendKeepAliveMessageThread() { @@ -1074,11 +1085,11 @@ public class StunCandidateHarvest * Well, if the currentThread is finishing and this instance is * still to send keep-alive messages, we'd better start another * Thread for the purpose to continue the work that the - * currentThread was supposed to carry out. + * currentThread was supposed to carry out. */ if ((sendKeepAliveMessageThread == null) && (sendKeepAliveMessageInterval - != SEND_KEEP_ALIVE_MESSAGE_INTERVAL_NOT_SPECIFIED)) + != SEND_KEEP_ALIVE_MESSAGE_INTERVAL_NOT_SPECIFIED)) createSendKeepAliveMessageThread(); } } diff --git a/src/org/ice4j/message/Indication.java b/src/org/ice4j/message/Indication.java index 257bf7c..f100e10 100644 --- a/src/org/ice4j/message/Indication.java +++ b/src/org/ice4j/message/Indication.java @@ -36,7 +36,11 @@ public class Indication public void setMessageType(char indicationType) throws IllegalArgumentException { - if(!isIndicationType(indicationType)) + /* old TURN DATA indication type is an indication despite + * 0x0115 & 0x0110 indicates STUN error response type + */ + if(!isIndicationType(indicationType) && + indicationType != OLD_DATA_INDICATION) throw new IllegalArgumentException( (int)(indicationType) + " - is not a valid indication type."); diff --git a/src/org/ice4j/message/Message.java b/src/org/ice4j/message/Message.java index 9a5f32b..f25ca2f 100644 --- a/src/org/ice4j/message/Message.java +++ b/src/org/ice4j/message/Message.java @@ -11,6 +11,7 @@ import java.util.logging.*; import org.ice4j.*; import org.ice4j.attribute.*; +import org.ice4j.ice.*; import org.ice4j.stack.*; /** @@ -34,60 +35,191 @@ public abstract class Message = Logger.getLogger(Message.class.getName()); /* general declaration */ + /** + * STUN request code. + */ public static final char STUN_REQUEST = 0x0000; + + /** + * STUN indication code. + */ public static final char STUN_INDICATION = 0x0010; + + /** + * STUN success response code. + */ public static final char STUN_SUCCESS_RESP = 0x0100; + + /** + * STUN error response code. + */ public static final char STUN_ERROR_RESP = 0x0110; /* STUN methods */ + /** + * STUN binding method. + */ public static final char STUN_METHOD_BINDING = 0x0001; + + /** + * STUN binding request code. + */ 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); + + /** + * STUN binding error response code. + */ public static final char BINDING_ERROR_RESPONSE = (STUN_METHOD_BINDING | STUN_ERROR_RESP); + + /** + * STUN shared secret request. + */ public static final char SHARED_SECRET_REQUEST = 0x0002; + + /** + * STUN shared secret response. + */ public static final char SHARED_SECRET_RESPONSE = 0x0102; + + /** + * STUN shared secret error response. + */ public static final char SHARED_SECRET_ERROR_RESPONSE = 0x0112; /* TURN methods */ + /** + * TURN allocate method code. + */ public static final char TURN_METHOD_ALLOCATE = 0x0003; + + /** + * TURN refresh method code. + */ public static final char TURN_METHOD_REFRESH = 0x0004; + + /** + * TURN send method code. + */ public static final char TURN_METHOD_SEND = 0x0006; + + /** + * TURN data method code. + */ public static final char TURN_METHOD_DATA = 0x0007; + + /** + * TURN CreatePermission method code. + */ public static final char TURN_METHOD_CREATEPERMISSION = 0x0008; + + /** + * TURN ChannelBind method code. + */ public static final char TURN_METHOD_CHANNELBIND = 0x0009; + /** + * TURN allocate request code. + */ 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); + + /** + * TURN allocate error response code. + */ 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); + + /** + * TURN refresh response code. + */ 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); + + /** + * TURN ChannelBind request code. + */ 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); + + /** + * TURN ChannelBind error response code. + */ 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); + + /** + * TURN CreatePermission response code. + */ 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); + + /** + * TURN send indication code. + */ 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); + /* Old TURN method */ + /** + * TURN Send request. + */ + public static final char SEND_REQUEST = 0x0004; + + /** + * TURN Send request. + */ + public static final char OLD_DATA_INDICATION = 0x0115; + //Message fields /** * The length of Stun Message Headers in bytes @@ -117,6 +249,11 @@ public abstract class Message */ public static final byte TRANSACTION_ID_LENGTH = 12; + /** + * The length of the RFC3489 transaction id (in bytes). + */ + public static final byte RFC3489_TRANSACTION_ID_LENGTH = 16; + /** * The list of attributes contained by the message. We are using a Map * rather than a uni-dimensional list, in order to facilitate attribute @@ -167,8 +304,25 @@ public abstract class Message * */ public 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; + + /** + * O means the parameter is optional. + * + * @see Message#N_A + */ public static final byte O = 2; + + /** + * M indicates that inclusion of the attribute in the message is + * mandatory. + * + * @see Message#N_A + */ public static final byte M = 3; //Message indices @@ -227,6 +381,9 @@ public abstract class Message protected static final byte ICE_CONTROLLED_PRESENTITY_INDEX = 30; protected static final byte USE_CANDIDATE_PRESENTITY_INDEX = 31; + /* Old TURN attributes */ + protected static final byte DESTINATION_ADDRESS_PRESENTITY_INDEX = 29; + 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. @@ -236,7 +393,7 @@ public abstract class Message /*MAPPED-ADDRESS*/ { N_A, M, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A}, /*RESPONSE-ADDRESS*/ { 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}, /*CHANGE-REQUEST*/ { 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}, - /*SOURCE-ADDRESS*/ { N_A, M, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A}, + /*SOURCE-ADDRESS*/ { N_A, M, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, M}, /*CHANGED-ADDRESS*/ { N_A, M, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A}, /*USERNAME*/ { O, N_A, N_A, N_A, M, N_A, O, N_A, O, N_A, O, N_A, N_A, N_A}, /*PASSWORD*/ { N_A, N_A, N_A, N_A, M, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A}, @@ -244,7 +401,7 @@ public abstract class Message /*ERROR-CODE*/ { N_A, N_A, M, N_A, N_A, M, N_A, M, N_A, M, N_A, M, N_A, N_A}, /*UNKNOWN-ATTRIBUTES*/{ N_A, N_A, C, N_A, N_A, C, N_A, C, N_A, C, N_A, C, N_A, N_A}, /*REFLECTED-FROM*/ { N_A, C, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A}, - /*XOR-MAPPED-ADDRESS*/{ N_A, M, N_A, N_A, N_A, N_A, N_A, M, N_A, N_A, N_A, N_A, N_A, N_A}, + /*XOR-MAPPED-ADDRESS*/{ N_A, C, N_A, N_A, N_A, N_A, N_A, M, N_A, N_A, N_A, N_A, N_A, N_A}, /*XOR-ONLY*/ { 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}, /*SOFTWARE*/ { N_A, O, O, N_A, O, O, O, O, O, O, O, O, O, N_A}, /*UNKNOWN_OPTIONAL*/ { O, O, O, O, O, O, O, O, O, O, O, O, N_A, N_A}, @@ -253,9 +410,9 @@ public abstract class Message /*NONCE*/ { O, N_A, N_A, N_A, M, N_A, O, O, O, O, O, O, N_A, N_A}, /*FINGERPRINT*/ { O, O, O, O, O, O, O, O, O, O, O, O, N_A, N_A}, /*CHANNEL-NUMBER*/ { N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, M, N_A, N_A, N_A}, - /*LIFETIME*/ { N_A, N_A, N_A, N_A, N_A, N_A, O, N_A, M, N_A, N_A, N_A, N_A, N_A}, + /*LIFETIME*/ { N_A, N_A, N_A, N_A, N_A, N_A, O, N_A, O, N_A, N_A, N_A, N_A, N_A}, /*XOR-PEER-ADDRESS*/ { N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, M, N_A, M, M}, - /*DATA*/ { N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, O, M}, + /*DATA*/ { N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, O, N_A, N_A, N_A, O, M}, /*XOR-RELAYED-ADDRESS*/{N_A, N_A, N_A, N_A, N_A, N_A, N_A, M, N_A, N_A, N_A, N_A, N_A, N_A}, /*EVEN-PORT*/ { N_A, N_A, N_A, N_A, N_A, N_A, O, N_A, N_A, N_A, N_A, N_A, N_A, N_A}, /*REQUESTED-TRANSPORT*/{N_A, N_A, N_A, N_A, N_A, N_A, M, N_A, N_A, N_A, N_A, N_A, N_A, N_A}, @@ -265,6 +422,7 @@ public abstract class Message /*ICE-CONTROLLING*/ { 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}, /*ICE-CONTROLLED*/ { O, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A}, /*USE-CANDIDATE*/ { O, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A}, + /*DESTINATION-ADDRESS*/{N_A, N_A, N_A, N_A, N_A, N_A, N_A, N_A, O, N_A, N_A, N_A, M, N_A}, }; /** @@ -377,8 +535,6 @@ public abstract class Message return attributes.size(); } - - /** * Sets this message's type to be messageType. Method is package access * as it should not permit changing the type of message once it has been @@ -414,13 +570,16 @@ public abstract class Message throws StunException { if(tranID == null - || tranID.length != TRANSACTION_ID_LENGTH) + || (tranID.length != TRANSACTION_ID_LENGTH && + tranID.length != RFC3489_TRANSACTION_ID_LENGTH)) throw new StunException(StunException.ILLEGAL_ARGUMENT, - "Invalid transaction id"); + "Invalid transaction id length"); - this.transactionID = new byte[TRANSACTION_ID_LENGTH]; + int tranIDLength = tranID.length; + + this.transactionID = new byte[tranIDLength]; System.arraycopy(tranID, 0, - this.transactionID, 0, TRANSACTION_ID_LENGTH); + this.transactionID, 0, tranIDLength); } /** @@ -635,6 +794,18 @@ public abstract class Message //make sure we have everything necessary to encode a proper message validateAttributePresentity(); + 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); + } + final char dataLength = getDataLength(); byte binMsg[] = new byte[HEADER_LENGTH + dataLength]; int offset = 0; @@ -648,11 +819,24 @@ public abstract class Message offset += 2; - System.arraycopy(MAGIC_COOKIE, 0, binMsg, offset, 4); - offset+=4; - System.arraycopy(getTransactionID(), 0, binMsg, offset, - TRANSACTION_ID_LENGTH); - offset+=TRANSACTION_ID_LENGTH; + byte tranID[] = getTransactionID(); + + if(tranID.length == 12) + { + System.arraycopy(MAGIC_COOKIE, 0, binMsg, offset, 4); + offset += 4; + System.arraycopy(tranID, 0, binMsg, offset, + TRANSACTION_ID_LENGTH); + offset += TRANSACTION_ID_LENGTH; + } + else + { + /* RFC3489 behavior */ + System.arraycopy(tranID, 0, binMsg, offset, + RFC3489_TRANSACTION_ID_LENGTH); + offset += RFC3489_TRANSACTION_ID_LENGTH; + + } Iterator> iter = attributes.entrySet().iterator(); @@ -675,7 +859,7 @@ public abstract class Message { /* * The "Message Length" seen by a ContentDependentAttribute is - * upto and including the very Attribute but without any other + * up to and including the very Attribute but without any other * Attribute instances after it. */ binMsg[messageLengthOffset] @@ -716,14 +900,14 @@ public abstract class Message //remove MESSAGE-INTEGRITY and FINGERPRINT attributes so that we can //make sure they are added at the end. Attribute msgIntAttr = removeAttribute(Attribute.MESSAGE_INTEGRITY); - Attribute fingerprint = removeAttribute(Attribute.FINGERPRINT); + Attribute fingerprint = removeAttribute(Attribute.FINGERPRINT); //add a SOFTWARE attribute if the user said so, and unless they did it //themselves. String software = System.getProperty(StackProperties.SOFTWARE); if (getAttribute(Attribute.SOFTWARE) == null - && software != null) + && software != null && software.length() > 0) { addAttribute(AttributeFactory .createSoftwareAttribute(software.getBytes())); @@ -771,10 +955,13 @@ public abstract class Message "The given binary array is not a valid StunMessage"); } - char messageType = (char)((binMessage[offset++]<<8) - | (binMessage[offset++]&0xFF)); + char messageType = (char)((binMessage[offset++] << 8) + | (binMessage[offset++] & 0xFF)); + Message message; - if (Message.isResponseType(messageType)) + /* 0x0115 is a old TURN DATA indication message type */ + if (Message.isResponseType(messageType) && + messageType != OLD_DATA_INDICATION) message = new Response(); else if(Message.isRequestType(messageType)) message = new Request(); @@ -789,7 +976,14 @@ public abstract class Message /* copy the cookie */ byte cookie[] = new byte[4]; System.arraycopy(binMessage, offset, cookie, 0, 4); - offset+=4; + offset += 4; + + boolean rfc3489Compat = false; + + if(!Arrays.equals(MAGIC_COOKIE, cookie)) + { + rfc3489Compat = true; + } if(arrayLen - offset - TRANSACTION_ID_LENGTH < length) { @@ -809,7 +1003,18 @@ public abstract class Message System.arraycopy(binMessage, offset, tranID, 0, TRANSACTION_ID_LENGTH); try { - message.setTransactionID(tranID); + if(rfc3489Compat) + { + byte rfc3489TranID[] = new byte[TRANSACTION_ID_LENGTH + 4]; + System.arraycopy(cookie, 0, rfc3489TranID, 0, 4); + System.arraycopy(tranID, 0, rfc3489TranID, 4, + TRANSACTION_ID_LENGTH); + message.setTransactionID(rfc3489TranID); + } + else + { + message.setTransactionID(tranID); + } } catch (StunException exc) { @@ -818,7 +1023,7 @@ public abstract class Message + "contain a whole StunMessage", exc); } - offset+=TRANSACTION_ID_LENGTH; + offset += TRANSACTION_ID_LENGTH; while(offset - Message.HEADER_LENGTH < length) { @@ -936,7 +1141,7 @@ public abstract class Message 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!"); + "A mandatory attribute (type=" + (int)i + ") is missing!"); } /** diff --git a/src/org/ice4j/message/MessageFactory.java b/src/org/ice4j/message/MessageFactory.java index 0239759..4fe78c7 100644 --- a/src/org/ice4j/message/MessageFactory.java +++ b/src/org/ice4j/message/MessageFactory.java @@ -379,6 +379,29 @@ public class MessageFactory return allocateRequest; } + /** + * Create an allocate request for a Google TURN relay (old TURN protocol + * modified). + * + * @param username short-term username + * @return an allocation request + */ + public static Request createGoogleAllocateRequest(String username) + { + Request allocateRequest = new Request(); + Attribute usernameAttr = AttributeFactory.createUsernameAttribute( + username); + Attribute magicCookieAttr = + AttributeFactory.createMagicCookieAttribute(); + + allocateRequest.setMessageType(Message.ALLOCATE_REQUEST); + // first attribute is MAGIC-COOKIE + allocateRequest.addAttribute(magicCookieAttr); + allocateRequest.addAttribute(usernameAttr); + + return allocateRequest; + } + /** * Adds the Attributes to a specific Request which support * the STUN long-term credential mechanism. @@ -602,6 +625,51 @@ public class MessageFactory return sendIndication; } + /** + * Create a old Send Request. + * @param username the username + * @param peerAddress peer address + * @param data data (could be 0 byte) + * @return send indication message + */ + public static Request createSendRequest( + String username, TransportAddress peerAddress, byte[] data) + { + Request sendRequest = new Request(); + + try + { + sendRequest.setMessageType(Message.SEND_REQUEST); + + /* add MAGIC-COOKIE attribute */ + sendRequest.addAttribute( + AttributeFactory.createMagicCookieAttribute()); + + /* add USERNAME attribute */ + sendRequest.addAttribute( + AttributeFactory.createUsernameAttribute(username)); + + /* add DESTINATION-ADDRESS attribute */ + DestinationAddressAttribute peerAddressAttribute = AttributeFactory + .createDestinationAddressAttribute(peerAddress); + sendRequest.addAttribute(peerAddressAttribute); + + /* add DATA if data */ + if (data != null && data.length > 0) + { + DataAttribute dataAttribute = AttributeFactory + .createDataAttribute(data); + sendRequest.addAttribute(dataAttribute); + } + } + catch (IllegalArgumentException ex) + { + logger.log(Level.FINE, "Failed to set message type.", ex); + } + + return sendRequest; + } + // ======================== NOT CURRENTLY SUPPORTED /** * Create a shared secret request. diff --git a/src/org/ice4j/socket/GoogleRelayedCandidateDatagramSocket.java b/src/org/ice4j/socket/GoogleRelayedCandidateDatagramSocket.java new file mode 100644 index 0000000..c471dcf --- /dev/null +++ b/src/org/ice4j/socket/GoogleRelayedCandidateDatagramSocket.java @@ -0,0 +1,577 @@ +/* + * 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.socket; + +import java.io.*; +import java.net.*; +import java.util.*; +import java.util.logging.*; + +import org.ice4j.*; +import org.ice4j.attribute.*; +import org.ice4j.ice.*; +import org.ice4j.ice.harvest.*; +import org.ice4j.message.*; +import org.ice4j.stack.*; + +/** + * Represents an application-purposed (as opposed to an ICE-specific) + * DatagramSocket for a RelayedCandidate harvested by a + * TurnCandidateHarvest (and its associated + * TurnCandidateHarvester, of course). + * GoogleRelayedCandidateDatagramSocket is associated with a successful + * Allocation on a TURN server and implements sends and receives through it + * using TURN messages to and from that TURN server. + * + * @author Lyubomir Marinov + * @author Sebastien Vincent + */ +public class GoogleRelayedCandidateDatagramSocket + extends DatagramSocket + implements MessageEventHandler, + ResponseCollector +{ + /** + * The Logger used by the + * GoogleRelayedCandidateDatagramSocket class and its instances for + * logging output. + */ + private static final Logger logger + = Logger.getLogger( + GoogleRelayedCandidateDatagramSocket.class.getName()); + + /** + * The indicator which determines whether this instance has started + * executing or has executed its {@link #close()} method. + */ + private boolean closed = false; + + /** + * The DatagramPackets which are to be received through this + * DatagramSocket upon calls to its + * {@link #receive(DatagramPacket)} method. They have been received from the + * TURN server in the form of Data indications. + */ + private final List packetsToReceive + = new LinkedList(); + + /** + * The DatagramSockets which have been sent through this + * DatagramSocket using its {@link #send(DatagramPacket)} method + * and which are to be relayed through its associated TURN server in the + * form of Send indications. + */ + private final List packetsToSend + = new LinkedList(); + + /** + * The GoogleRelayedCandidate which uses this instance as the value + * of its socket property. + */ + private final GoogleRelayedCandidate relayedCandidate; + + /** + * The Thread which is to send the {@link #packetsToSend} to the + * associated TURN server. + */ + private Thread sendThread; + + /** + * The GoogleTurnCandidateHarvest which has harvested + * {@link #relayedCandidate}. + */ + private final GoogleTurnCandidateHarvest turnCandidateHarvest; + + /** + * Username. + */ + private final String username; + + /** + * Initializes a new GoogleRelayedCandidateDatagramSocket instance + * which is to be the socket of a specific + * RelayedCandidate harvested by a specific + * TurnCandidateHarvest. + * + * @param relayedCandidate the RelayedCandidate which is to use the + * new instance as the value of its socket property + * @param turnCandidateHarvest the TurnCandidateHarvest which has + * harvested relayedCandidate + * @param username username + * @throws SocketException if anything goes wrong while initializing the new + * GoogleRelayedCandidateDatagramSocket instance + */ + public GoogleRelayedCandidateDatagramSocket( + GoogleRelayedCandidate relayedCandidate, + GoogleTurnCandidateHarvest turnCandidateHarvest, + String username) + throws SocketException + { + super(/* bindaddr */ (SocketAddress) null); + + this.relayedCandidate = relayedCandidate; + this.turnCandidateHarvest = turnCandidateHarvest; + this.username = username; + + this.turnCandidateHarvest + .harvester + .getStunStack() + .addOldIndicationListener( + this.turnCandidateHarvest.hostCandidate + .getTransportAddress(), + this); + } + + /** + * Closes this datagram socket. + * + * @see DatagramSocket#close() + */ + @Override + public void close() + { + synchronized (this) + { + if (this.closed) + return; + else + this.closed = true; + } + synchronized (packetsToReceive) + { + packetsToReceive.notifyAll(); + } + synchronized (packetsToSend) + { + packetsToSend.notifyAll(); + } + turnCandidateHarvest.harvester.getStunStack().removeIndicationListener( + turnCandidateHarvest.hostCandidate.getTransportAddress(), + this); + turnCandidateHarvest.close(this); + } + + /** + * Gets the local address to which the socket is bound. + * GoogleRelayedCandidateDatagramSocket returns the + * address of its localSocketAddress. + *

+ * If there is a security manager, its checkConnect method is first + * called with the host address and -1 as its arguments to see if + * the operation is allowed. + *

+ * + * @return the local address to which the socket is bound, or an + * InetAddress representing any local address if either the socket + * is not bound, or the security manager checkConnect method does + * not allow the operation + * @see #getLocalSocketAddress() + * @see DatagramSocket#getLocalAddress() + */ + @Override + public InetAddress getLocalAddress() + { + return getLocalSocketAddress().getAddress(); + } + + /** + * Returns the port number on the local host to which this socket is bound. + * GoogleRelayedCandidateDatagramSocket returns the port + * of its localSocketAddress. + * + * @return the port number on the local host to which this socket is bound + * @see #getLocalSocketAddress() + * @see DatagramSocket#getLocalPort() + */ + @Override + public int getLocalPort() + { + return getLocalSocketAddress().getPort(); + } + + /** + * Returns the address of the endpoint this socket is bound to, or + * null if it is not bound yet. Since + * GoogleRelayedCandidateDatagramSocket represents an + * application-purposed DatagramSocket relaying data to and from a + * TURN server, the localSocketAddress is the + * transportAddress of the respective RelayedCandidate. + * + * @return a SocketAddress representing the local endpoint of this + * socket, or null if it is not bound yet + * @see DatagramSocket#getLocalSocketAddress() + */ + @Override + public InetSocketAddress getLocalSocketAddress() + { + return getRelayedCandidate().getTransportAddress(); + } + + /** + * Gets the RelayedCandidate which uses this instance as the value + * of its socket property. + * + * @return the RelayedCandidate which uses this instance as the + * value of its socket property + */ + public final GoogleRelayedCandidate getRelayedCandidate() + { + return relayedCandidate; + } + + /** + * Notifies this MessageEventHandler that a specific STUN message + * has been received, parsed and is ready for delivery. + * GoogleRelayedCandidateDatagramSocket handles STUN indications sent + * from the associated TURN server and received at the associated local + * TransportAddress. + * + * @param e a StunMessageEvent which encapsulates the received STUN + * message + */ + public void handleMessageEvent(StunMessageEvent e) + { + Message message = e.getMessage(); + char messageType = message.getMessageType(); + + if (messageType != Message.OLD_DATA_INDICATION) + return; + + if (!turnCandidateHarvest.hostCandidate.getTransportAddress().equals( + e.getLocalAddress())) + return; + + // Is it from our TURN server? + if (!turnCandidateHarvest.harvester.stunServer.equals( + e.getRemoteAddress())) + return; + + logger.finest("handle old DATA Indication"); + + /* as REMOTE-ADDRESS and XOR-PEER-ADDRESS has the same attribute type + * we cast it to XorPeerAddressAttribute but we do not apply XOR to get + * the address + */ + XorPeerAddressAttribute peerAddressAttribute + = (XorPeerAddressAttribute) + message.getAttribute(Attribute.REMOTE_ADDRESS); + + if (peerAddressAttribute == null) + { + logger.info("peerAddressAttribute is null"); + return; + } + + DataAttribute dataAttribute + = (DataAttribute) message.getAttribute(Attribute.DATA); + + if (dataAttribute == null) + { + logger.info("data is null"); + return; + } + + TransportAddress peerAddress + = peerAddressAttribute.getAddress(); + if (peerAddress == null) + return; + + byte[] data = dataAttribute.getData(); + + if (data == null) + return; + + DatagramPacket packetToReceive; + + try + { + packetToReceive + = new DatagramPacket(data, 0, data.length, peerAddress); + } + catch (SocketException sex) + { + packetToReceive = null; + } + + if (packetToReceive != null) + { + synchronized (packetsToReceive) + { + packetsToReceive.add(packetToReceive); + packetsToReceive.notifyAll(); + } + } + } + + /** + * Notifies this GoogleRelayedCandidateDatagramSocket that a + * specific Request it has sent has either failed or received a + * STUN error Response. + * + * @param response the Response which responds to request + * @param request the Request sent by this instance to which + * response responds + * @return true if the failure or error condition has been handled + * and the caller should assume this instance has recovered from it; + * otherwise, false + */ + public boolean processErrorOrFailure(Response response, Request request) + { + return false; + } + + /** + * Notifies this GoogleRelayedCandidateDatagramSocket that a + * specific Request it has sent has received a STUN success + * Response. + * + * @param response the Response which responds to request + * @param request the Request sent by this instance to which + * response responds + */ + public void processSuccess(Response response, Request request) + { + } + + /** + * Dispatch the specified response. + * + * @param response the response to dispatch. + */ + public void processResponse(StunResponseEvent response) + { + + } + + /** + * Notifies this collector that no response had been received after repeated + * retransmissions of the original request (as described by rfc3489) and + * that the request should be considered unanswered. + * + * @param event the StunTimeoutEvent containing a reference to the + * transaction that has just failed. + */ + public void processTimeout(StunTimeoutEvent event) + { + } + + /** + * Receives a datagram packet from this socket. When this method returns, + * the DatagramPacket's buffer is filled with the data received. + * The datagram packet also contains the sender's IP address, and the port + * number on the sender's machine. + * + * @param p the DatagramPacket into which to place the incoming + * data + * @throws IOException if an I/O error occurs + * @see DatagramSocket#receive(DatagramPacket) + */ + @Override + public void receive(DatagramPacket p) + throws IOException + { + synchronized (packetsToReceive) + { + while (true) + { + /* + * According to the javadoc of DatagramSocket#close(), any + * thread currently blocked in #receive(DatagramPacket) upon + * this socket will throw a SocketException. + */ + if (closed) + { + throw + new SocketException( + GoogleRelayedCandidateDatagramSocket.class + .getSimpleName() + + " has been closed."); + } + else if (packetsToReceive.isEmpty()) + { + try + { + packetsToReceive.wait(); + } + catch (InterruptedException iex) + { + } + continue; + } + else + { + DatagramPacket packetToReceive = packetsToReceive.remove(0); + + MultiplexingDatagramSocket.copy(packetToReceive, p); + packetsToReceive.notifyAll(); + break; + } + } + } + } + + /** + * Sends a datagram packet from this socket. The DatagramPacket + * includes information indicating the data to be sent, its length, the IP + * address of the remote host, and the port number on the remote host. + * + * @param p the DatagramPacket to be sent + * @throws IOException if an I/O error occurs + * @see DatagramSocket#send(DatagramPacket) + */ + @Override + public void send(DatagramPacket p) + throws IOException + { + synchronized (packetsToSend) + { + if (closed) + { + throw + new IOException( + GoogleRelayedCandidateDatagramSocket.class. + getSimpleName() + " has been closed."); + } + else + { + packetsToSend.add(MultiplexingDatagramSocket.clone(p)); + + if (sendThread == null) + createSendThread(); + else + packetsToSend.notifyAll(); + } + } + } + + /** + * Creates {@link #sendThread} which is to send {@link #packetsToSend} to + * the associated TURN server. + */ + private void createSendThread() + { + sendThread + = new Thread() + { + @Override + public void run() + { + try + { + runInSendThread(); + } + finally + { + /* + * If sendThread is dying and there are packetsToSend, + * then spawn a new sendThread. + */ + synchronized (packetsToSend) + { + if (sendThread == Thread.currentThread()) + sendThread = null; + if ((sendThread == null) + && !closed + && !packetsToSend.isEmpty()) + createSendThread(); + } + } + } + }; + sendThread.start(); + } + + /** + * Runs in {@link #sendThread} to send {@link #packetsToSend} to the + * associated TURN server. + */ + private void runInSendThread() + { + synchronized (packetsToSend) + { + while (!closed) + { + if (packetsToSend.isEmpty()) + { + try + { + packetsToSend.wait(); + } + catch (InterruptedException iex) + { + } + continue; + } + + int packetToSendCount = packetsToSend.size(); + + for (int packetToSendIndex = 0; + packetToSendIndex < packetToSendCount; + packetToSendIndex++) + { + DatagramPacket packetToSend = packetsToSend.remove(0); + TransportAddress peerAddress + = new TransportAddress( + packetToSend.getAddress(), + packetToSend.getPort(), + Transport.UDP); + byte[] pData = packetToSend.getData(); + int pOffset = packetToSend.getOffset(); + int pLength = packetToSend.getLength(); + byte[] data; + + if ((pOffset == 0) && (pLength == pData.length)) + data = pData; + else + { + data = new byte[pLength]; + System.arraycopy(pData, pOffset, data, 0, pLength); + } + + byte[] transactionID + = TransactionID.createNewTransactionID().getBytes(); + Request sendRequest + = MessageFactory.createSendRequest(username, + peerAddress, + data); + + try + { + sendRequest.setTransactionID(transactionID); + turnCandidateHarvest.harvester.getStunStack(). + sendRequest(sendRequest, + turnCandidateHarvest.harvester.stunServer, + turnCandidateHarvest.hostCandidate. + getTransportAddress(), + this); + } + catch(Exception e) + { + logger.fine("Failed to send TURN Send request: " + e); + } + } + + /* + * If no packetToSend has been sent by the current iteration, + * then we must be waiting for some condition to change in order + * to be able to send. + */ + if (packetsToSend.size() == packetToSendCount) + { + try + { + packetsToSend.wait(); + } + catch (InterruptedException iex) + { + } + } + } + } + } +} \ No newline at end of file diff --git a/src/org/ice4j/socket/StunDatagramPacketFilter.java b/src/org/ice4j/socket/StunDatagramPacketFilter.java index d218d05..2ffdfd5 100644 --- a/src/org/ice4j/socket/StunDatagramPacketFilter.java +++ b/src/org/ice4j/socket/StunDatagramPacketFilter.java @@ -130,4 +130,28 @@ public class StunDatagramPacketFilter return false; } } + + /** + * Indicates whether some other DatagramPacketFilter is "equal to" this one. + * + * @param obj the reference object with which to compare. + * @return true if this StunDatagramPacketFilter is + * equal to the obj argument; false otherwise. + * + * @throws java.lang.NullPointerException if obj is null; + */ + @Override + public boolean equals(Object obj) + throws NullPointerException + { + if(obj == this) + return true; + + if(obj.getClass().equals(getClass())) + { + return true; + } + + return false; + } } diff --git a/src/org/ice4j/socket/TurnDatagramPacketFilter.java b/src/org/ice4j/socket/TurnDatagramPacketFilter.java index 122c3ec..737b8ff 100644 --- a/src/org/ice4j/socket/TurnDatagramPacketFilter.java +++ b/src/org/ice4j/socket/TurnDatagramPacketFilter.java @@ -105,6 +105,7 @@ public class TurnDatagramPacketFilter case Message.TURN_METHOD_DATA: case Message.TURN_METHOD_REFRESH: case Message.TURN_METHOD_SEND: + case 0x0005: /* old TURN DATA indication */ return true; default: return false; diff --git a/src/org/ice4j/stack/Connector.java b/src/org/ice4j/stack/Connector.java index 2cdff90..8f0029d 100644 --- a/src/org/ice4j/stack/Connector.java +++ b/src/org/ice4j/stack/Connector.java @@ -252,7 +252,7 @@ class Connector sock.send(datagramPacket); - // no exception packet is successfully sent, log it + // no exception packet is successfully sent, log it if(StunStack.isPacketLoggerEnabled()) { StunStack.getPacketLogger().logPacket( diff --git a/src/org/ice4j/stack/EventDispatcher.java b/src/org/ice4j/stack/EventDispatcher.java index e8303fe..7337a9f 100644 --- a/src/org/ice4j/stack/EventDispatcher.java +++ b/src/org/ice4j/stack/EventDispatcher.java @@ -49,7 +49,7 @@ public class EventDispatcher /** * Registers a specific MessageEventHandler for notifications about * STUN indications received at a specific local TransportAddress. - * + * * @param localAddr the local TransportAddress STUN indications * received at which are to be reported to the specified * indicationListener @@ -66,6 +66,26 @@ public class EventDispatcher new IndicationEventHandler(indicationListener)); } + /** + * Registers a specific MessageEventHandler for notifications about + * old indications received at a specific local TransportAddress. + * + * @param localAddr the local TransportAddress STUN indications + * received at which are to be reported to the specified + * indicationListener + * @param indicationListener the MessageEventHandler which is to be + * registered for notifications about old indications received at the + * specified local TransportAddress + */ + public void addOldIndicationListener( + TransportAddress localAddr, + MessageEventHandler indicationListener) + { + addMessageListener( + localAddr, + new OldIndicationEventHandler(indicationListener)); + } + /** * Registers a specific MessageTypeEventHandler for notifications * about received STUN messages. @@ -325,13 +345,52 @@ public class EventDispatcher } } + /** + * Implements MessageEventHandler for a + * MessageEventHandler which handles old DATA indications (0x0115). + * + * @author Lubomir Marinov + * @author Sebastien Vincent + */ + private static class OldIndicationEventHandler + extends MessageTypeEventHandler + { + + /** + * Initializes a new IndicationEventHandler which is to + * implement MessageEventHandler for a specific + * MessageEventHandler which handles old DATA indications + * (0x0115). + * + * @param indicationListener the RequestListener for which the + * new instance is to implement MessageEventHandler + */ + public OldIndicationEventHandler(MessageEventHandler indicationListener) + { + super((char)0x0110, indicationListener); + } + + /** + * Notifies this MessageEventHandler that a STUN message has + * been received, parsed and is ready for delivery. + * + * @param e a StunMessageEvent which encapsulates the STUN + * message to be handled + * @see MessageEventHandler#handleMessageEvent(StunMessageEvent) + */ + public void handleMessageEvent(StunMessageEvent e) + { + delegate.handleMessageEvent(e); + } + } + /** * Represents the base for providers of MessageEventHandler * implementations to specific Objects. * * @author Lubomir Marinov * @param the type of the delegate to which the notifications are to be - * forwarded + * forwarded */ private static abstract class MessageTypeEventHandler implements MessageEventHandler @@ -345,7 +404,7 @@ public class EventDispatcher /** * The type of the STUN messages that this MessageEventHandler - * is interested in. + * is interested in. */ public final char messageType; diff --git a/src/org/ice4j/stack/MessageQueue.java b/src/org/ice4j/stack/MessageQueue.java index 78d5c78..ecc0f26 100644 --- a/src/org/ice4j/stack/MessageQueue.java +++ b/src/org/ice4j/stack/MessageQueue.java @@ -29,11 +29,12 @@ class MessageQueue //sync all methods ... review later private Vector queue = new Vector(); - //keep a copy of the fifo size and make it accessible for concurrent queries. + //keep a copy of the fifo size and make it accessible for concurrent + // queries. private int size = 0; /** - * Create an empty MessaeFIFO + * Create an empty MessageFIFO */ MessageQueue() { diff --git a/src/org/ice4j/stack/NetAccessManager.java b/src/org/ice4j/stack/NetAccessManager.java index 41c9257..08494cd 100644 --- a/src/org/ice4j/stack/NetAccessManager.java +++ b/src/org/ice4j/stack/NetAccessManager.java @@ -99,7 +99,7 @@ class NetAccessManager /** * Gets the MessageQueue of this NetAccessManager in which * incoming messages are stocked for processing. - * + * * @return the MessageQueue of this NetAccessManager in * which incoming messages are stocked for processing */ diff --git a/src/org/ice4j/stack/StunStack.java b/src/org/ice4j/stack/StunStack.java index 5156dc8..48a4fcd 100644 --- a/src/org/ice4j/stack/StunStack.java +++ b/src/org/ice4j/stack/StunStack.java @@ -16,6 +16,7 @@ import javax.crypto.*; import org.ice4j.*; import org.ice4j.attribute.*; +import org.ice4j.ice.*; import org.ice4j.message.*; import org.ice4j.security.*; @@ -88,6 +89,11 @@ public class StunStack */ private static PacketLogger packetLogger; + /** + * Compatibility mode. + */ + private final CompatibilityMode mode; + /** * Sets the number of Message processors running in the same time. * @@ -251,6 +257,16 @@ 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 @@ -274,6 +290,7 @@ public class StunStack } } } + this.mode = mode; netAccessManager = new NetAccessManager(this); } @@ -502,6 +519,24 @@ public class StunStack eventDispatcher.addIndicationListener(localAddr, indicationListener); } + /** + * Adds a new MessageEventHandler which is to be notified about + * old indications received at a specific local TransportAddress. + * + * @param localAddr the TransportAddress of the local socket for + * which received STUN indications are to be reported to the specified + * MessageEventHandler + * @param indicationListener the MessageEventHandler which is to be + * registered for notifications about old indications received at the + * specified local TransportAddress + */ + public void addOldIndicationListener( + TransportAddress localAddr, + MessageEventHandler indicationListener) + { + eventDispatcher.addOldIndicationListener(localAddr, indicationListener); + } + /** * Sets the listener that should be notified when a new Request is received. * @param requestListener the listener interested in incoming requests. @@ -762,6 +797,11 @@ public class StunStack private void validateRequestAttributes(StunMessageEvent evt) throws IllegalArgumentException, StunException, IOException { + if(mode != CompatibilityMode.RFC5245) + { + return; + } + Message request = evt.getMessage(); //assert valid username @@ -863,7 +903,7 @@ public class StunStack evt.getRemoteAddress()); throw new IllegalArgumentException( - "Missing MESSAGE-INTEGRITY."); + "Unknown attribute(s)."); } } @@ -1063,4 +1103,14 @@ public class StunStack { return packetLogger != null && packetLogger.isEnabled(); } + + /** + * Returns compatibility mode. + * + * @return compatibility mode + */ + public CompatibilityMode getCompatibilityMode() + { + return mode; + } } diff --git a/src/org/ice4j/stack/TransactionID.java b/src/org/ice4j/stack/TransactionID.java index 33d090d..d856509 100644 --- a/src/org/ice4j/stack/TransactionID.java +++ b/src/org/ice4j/stack/TransactionID.java @@ -17,10 +17,20 @@ import java.util.*; */ public class TransactionID { + /** + * RFC5289 Transaction ID length. + */ + public static final int RFC5389_TRANSACTION_ID_LENGTH = 12; + + /** + * RFC3489 Transaction ID length. + */ + public static final int RFC3489_TRANSACTION_ID_LENGTH = 16; + /** * The id itself */ - private final byte transactionID[] = new byte[12]; + private final byte transactionID[]; /** * Any object that the application would like to correlate to a transaction. @@ -43,6 +53,24 @@ public class TransactionID */ private TransactionID() { + transactionID = new byte[RFC5389_TRANSACTION_ID_LENGTH]; + } + + /** + * Limits access to TransactionID instantiation. + * + * @param rfc3489Compatibility true to create a RFC3489 transaction ID + */ + private TransactionID(boolean rfc3489Compatibility) + { + if(rfc3489Compatibility) + { + transactionID = new byte[RFC3489_TRANSACTION_ID_LENGTH]; + } + else + { + transactionID = new byte[RFC5389_TRANSACTION_ID_LENGTH]; + } } /** @@ -59,13 +87,44 @@ public class TransactionID { TransactionID tid = new TransactionID(); - long left = System.currentTimeMillis();//the first 6 bytes of the id - long right = random.nextLong();//the last 6 bytes of the id + generateTransactionID(tid, 12); + return tid; + } - for(int i = 0; i < 6; i++) + /** + * Creates a RFC3489 transaction id object.The transaction id itself is + * generated using the following algorithm: + * + * The first 8 bytes of the id are given the value of + * System.currentTimeMillis(). Putting the right most bits first + * so that we get a more optimized equals() method. + * + * @return A TransactionID object with a unique transaction id. + */ + public static TransactionID createNewRFC3489TransactionID() + { + TransactionID tid = new TransactionID(true); + + generateTransactionID(tid, 16); + return tid; + } + + /** + * Generates a random transaction ID + * + * @param tid transaction ID + * @param nb number of bytes to generate + */ + private static void generateTransactionID(TransactionID tid, int nb) + { + long left = System.currentTimeMillis();//the first nb/2 bytes of the id + long right = random.nextLong();//the last nb/2 bytes of the id + int b = nb / 2; + + for(int i = 0; i < b; i++) { - tid.transactionID[i] = (byte)((left >> (i*8))& 0xFFl); - tid.transactionID[i+6] = (byte)((right >> (i*8))& 0xFFl); + tid.transactionID[i] = (byte)((left >> (i * 8)) & 0xFFl); + tid.transactionID[i + b] = (byte)((right >> (i * 8)) & 0xFFl); } //calculate hashcode for Hashtable storage. @@ -73,8 +132,6 @@ public class TransactionID | (tid.transactionID[2] << 16 & 0x00FF0000) | (tid.transactionID[1] << 8 & 0x0000FF00) | (tid.transactionID[0] & 0x000000FF); - - return tid; } /** @@ -111,9 +168,11 @@ public class TransactionID return serTran.getTransactionID(); //seems that the caller really wants a new ID - TransactionID tid = new TransactionID(); + TransactionID tid = null; + tid = new TransactionID((transactionID.length == 16)); - System.arraycopy(transactionID, 0, tid.transactionID, 0, 12); + System.arraycopy(transactionID, 0, tid.transactionID, 0, + tid.transactionID.length); //calculate hashcode for Hashtable storage. tid.hashCode = (tid.transactionID[3] << 24 & 0xFF000000) @@ -125,7 +184,9 @@ public class TransactionID } /** - * Returns the transaction id byte array (length 12). + * Returns the transaction id byte array (length 12 or 16 if RFC3489 + * compatible). + * * @return the transaction ID byte array. */ public byte[] getBytes() @@ -133,6 +194,16 @@ public class TransactionID return transactionID; } + /** + * If the transaction is compatible with RFC3489 (16 bytes). + * + * @return true if transaction ID is compatible with RFC3489 + */ + public boolean isRFC3489Compatible() + { + return (transactionID.length == 16); + } + /** * Compares two TransactionID objects. * @param obj the object to compare with. @@ -197,12 +268,12 @@ public class TransactionID for(int i = 0; i < transactionID.length; i++) { - if((transactionID[i]&0xFF) <= 15) + if((transactionID[i] & 0xFF) <= 15) { idStr.append("0"); } - idStr.append(Integer.toHexString(transactionID[i]&0xff) + idStr.append(Integer.toHexString(transactionID[i] & 0xff) .toUpperCase()); } diff --git a/test/test/Ice.java b/test/test/Ice.java index ac4be80..d6d2714 100644 --- a/test/test/Ice.java +++ b/test/test/Ice.java @@ -308,7 +308,7 @@ public class Ice * @param streamName the name of the stream to create * @param agent the Agent that should create the stream. * - *@return the newly created IceMediaStream. + * @return the newly created IceMediaStream. * @throws Throwable if anything goes wrong. */ private static IceMediaStream createStream(int rtpPort,