diff --git a/src/main/java/org/ice4j/ice/Agent.java b/src/main/java/org/ice4j/ice/Agent.java index 1f22240..3f1cd2a 100644 --- a/src/main/java/org/ice4j/ice/Agent.java +++ b/src/main/java/org/ice4j/ice/Agent.java @@ -19,9 +19,6 @@ package org.ice4j.ice; import java.beans.*; import java.io.*; -import java.math.*; -import java.net.*; -import java.security.*; import java.util.*; import java.util.logging.*; @@ -51,6 +48,7 @@ import org.ice4j.stack.*; * @author Boris Grozev */ public class Agent + extends BaseAgent { /** * The maximum number of retransmissions of a STUN Binding request without @@ -102,27 +100,6 @@ public class Agent public static final String PROPERTY_ICE_PROCESSING_STATE = "IceProcessingState"; - /** - * The LinkedHashMap used to store the media streams - * This map preserves the insertion order of the media streams. - */ - private final Map mediaStreams - = new LinkedHashMap<>(); - - /** - * The candidate harvester that we use to gather candidate on the local - * machine. - */ - private final HostCandidateHarvester hostCandidateHarvester - = new HostCandidateHarvester(); - - /** - * A list of additional CandidateHarvesters which will be used to - * harvest candidates synchronously, and previously to harvesting by - * {@link #harvesters}. - */ - private final List hostHarvesters = new LinkedList<>(); - /** * The set of harvesters (i.e. STUN, TURN, and others) that the agent should * use when gathering candidates for components. @@ -135,14 +112,6 @@ public class Agent */ // private final HarvestStatistics harvestStats = new HarvestStatistics(); - /** - * We use the FoundationsRegistry to keep track of the foundations - * we assign within a session (i.e. the entire life time of an - * Agent) - */ - private final FoundationsRegistry foundationsRegistry - = new FoundationsRegistry(); - /** * Our internal nominator implementing several nomination strategies. */ @@ -171,16 +140,6 @@ public class Agent */ private final Object startLock = new Object(); - /** - * The user fragment that we should use for the ice-ufrag attribute. - */ - private final String ufrag; - - /** - * The password that we should use for the ice-pwd attribute. - */ - private final String password; - /** * The tie-breaker number is used in connectivity checks to detect and * repair the case where both agents believe to have the controlling or the @@ -188,21 +147,11 @@ public class Agent */ private long tieBreaker; - /** - * Determines whether this is the controlling agent in a an ICE interaction. - */ - private boolean isControlling = true; - /** * The entity that will be taking care of outgoing connectivity checks. */ private final ConnectivityCheckClient connCheckClient; - /** - * The entity that will be taking care of incoming connectivity checks. - */ - private final ConnectivityCheckServer connCheckServer; - /** * Indicates the state of ICE processing in this Agent. An * Agent is in the Waiting state until it has both sent and @@ -227,12 +176,6 @@ public class Agent */ private final List stateListeners = new LinkedList<>(); - - /** - * The StunStack used by this Agent. - */ - private StunStack stunStack; - /** * The thread that we use for moving from COMPLETED into a TERMINATED state. */ @@ -281,42 +224,20 @@ public class Agent */ private boolean performConsentFreshness = false; - /** - * The flag which specifies whether {@link #hostCandidateHarvester} should - * be used or not. - */ - private Boolean useHostHarvester = null; - /** * Creates an empty Agent with no streams, and no address. */ public Agent() { - SecureRandom random = new SecureRandom(); - - 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"); - - ufrag - = ensureIceAttributeLength( - new BigInteger(24, random).toString(32) - + BigInteger.valueOf( - System.currentTimeMillis()).toString(32), - /* min */ 4, /* max */ 256); - password - = ensureIceAttributeLength( - new BigInteger(128, random).toString(32), - /* min */ 22, /* max */ 256); - tieBreaker = Math.abs(random.nextLong()); nominator = new DefaultNominator(this); + + // The default value of controlling was true before the class BaseAgent + // was split out of the class Agent. BaseAgent defaults to false for + // controlling since it is unable to perform connectivity checks. + setControlling(true); } /** @@ -333,95 +254,27 @@ public class Agent * Creates a new media stream and stores it. * * @param mediaStreamName the name of the media stream - * * @return the newly created and stored IceMediaStream */ + @Override public IceMediaStream createMediaStream(String mediaStreamName) { - logger.fine("Create media stream for " + mediaStreamName); - IceMediaStream mediaStream - = new IceMediaStream(Agent.this, mediaStreamName); + IceMediaStream mediaStream = super.createMediaStream(mediaStreamName); - mediaStreams.put(mediaStreamName, mediaStream); - - // Since we add a new stream, we must wait to add the component and the - // remote candidates before starting to "RUN" this Agent. - // This is useful if this Agent is already in COMPLETED state - // (isStarted() == true) due to a previous successful ICE procedure: - // this way incoming connectivity checks are registered in the - // preDiscoveredPairsQueue until this Agent is in RUNNING state. - this.setState(IceProcessingState.WAITING); + if (mediaStream != null) + { + // Since we add a new stream, we must wait to add the component and + // the remote candidates before starting to "RUN" this Agent. + // This is useful if this Agent is already in COMPLETED state + // (isStarted() == true) due to a previous successful ICE procedure: + // this way incoming connectivity checks are registered in the + // preDiscoveredPairsQueue until this Agent is in RUNNING state. + setState(IceProcessingState.WAITING); + } return mediaStream; } - /** - * Creates a new {@link Component} for the specified stream and - * allocates potentially all local candidates that should belong to it. - * - * @param stream the {@link IceMediaStream} that the new {@link Component} - * should belong to. - * @param transport the transport protocol used by the component - * @param preferredPort the port number that should be tried first when - * binding local Candidate sockets for this Component. - * @param minPort the port number where we should first try to bind before - * moving to the next one (i.e. minPort + 1) - * @param maxPort the maximum port number where we should try binding - * before giving up and throwing an exception. - * - * @return the newly created {@link Component} and with a list containing - * all and only local candidates. - * - * @throws IllegalArgumentException if either minPort or - * maxPort is not a valid port number or if minPort > - * maxPort, or if transport is not currently supported. - * @throws IOException if an error occurs while the underlying resolver lib - * is using sockets. - * @throws BindException if we couldn't find a free port between - * minPort and maxPort before reaching the maximum allowed - * number of retries. - */ - public Component createComponent( IceMediaStream stream, - Transport transport, - int preferredPort, - int minPort, - int maxPort) - throws IllegalArgumentException, - IOException, - BindException - { - if(transport != Transport.UDP) - { - throw new IllegalArgumentException( - "This implementation does not currently support transport: " - + transport); - } - - Component component = stream.createComponent(); - - gatherCandidates(component, preferredPort, minPort, maxPort); - - for(Candidate candidate : component.getLocalCandidates()) - { - logger.info("\t" + candidate.getTransportAddress() + " (" + - candidate.getType() + ")"); - } - - /* - * Lyubomir: After we've gathered the LocalCandidate for a Component and - * before we've made them available to the caller, we have to make sure - * that the ConnectivityCheckServer is started. If there's been a - * previous connectivity establishment which has completed, it has - * stopped the ConnectivityCheckServer. If the ConnectivityCheckServer is - * not started after we've made the gathered LocalCandidates available - * to the caller, the caller may send them and a connectivity check may - * arrive from the remote Agent. - */ - connCheckServer.start(); - - return component; - } - /** * Uses all CandidateHarvesters currently registered with this * Agent to obtain whatever addresses they can discover. @@ -445,56 +298,21 @@ public class Agent * @throws IOException if an error occurs while the underlying resolver lib * is gathering candidates and we end up without even a single one. */ - private void gatherCandidates( Component component, - int preferredPort, - int minPort, - int maxPort) + @Override + protected void gatherCandidates( + Component component, + int preferredPort, int minPort, int maxPort) throws IllegalArgumentException, IOException { - logger.info("Gather candidates for component " + - component.toShortString()); + super.gatherCandidates(component, preferredPort, minPort, maxPort); - if (useHostHarvester()) + // in case we are not trickling, apply other harvesters here + if (!isTrickling()) { - hostCandidateHarvester.harvest( - component, - preferredPort, minPort, maxPort, Transport.UDP); - } - else - { - if (hostHarvesters.isEmpty()) - logger.warning("No host harvesters available!"); - } - - for (CandidateHarvester harvester : hostHarvesters) - { - harvester.harvest(component); - } - - if (component.getLocalCandidateCount() == 0) - logger.warning("Failed to gather any host candidates!"); - - //in case we are not trickling, apply other harvesters here - if(!isTrickling()) - { - harvestingStarted = true; //raise a flag to warn on a second call. + harvestingStarted = true; // raise a flag to warn on a second call. harvesters.harvest(component); } - - logger.fine("Candidate count in first harvest: " + - component.getLocalCandidateCount()); - - // Emil: Because of trickle, we now assign foundations, compute - // priorities, and eliminate redundancies while adding candidates on a - // component. This means that we no longer need to do it here, where we - // did before. - //computeFoundations(component); - //component.prioritizeCandidates(); - //component.eliminateRedundantCandidates(); - - //select the candidate to put in the media line. - component.selectDefaultCandidate(); } /** @@ -744,7 +562,11 @@ public class Agent */ private boolean setState(IceProcessingState newState) { + if (newState == null) + throw new NullPointerException("newState"); + IceProcessingState oldState; + synchronized (stateSyncRoot) { oldState = state; @@ -753,8 +575,8 @@ public class Agent if (!oldState.equals(newState)) { - logger.info("ICE state changed from " + oldState + " to " - + newState); + logger.info( + "ICE state changed from " + oldState + " to " + newState); fireStateChange(oldState, newState); return true; @@ -819,7 +641,7 @@ public class Agent public void addCandidateHarvester(CandidateHarvester harvester) { if (harvester.isHostHarvester()) - hostHarvesters.add(harvester); + addHostHarvester(harvester); else harvesters.add(harvester); } @@ -834,30 +656,6 @@ public class Agent return harvesters; } - /** - * Returns that user name that should be advertised in session descriptions - * containing ICE data from this agent. - * - * @return that user name that should be advertised in session descriptions - * containing ICE data from this agent. - */ - public String getLocalUfrag() - { - return ufrag; - } - - /** - * Returns that password that should be advertised in session descriptions - * containing ICE data from this agent. - * - * @return that password that should be advertised in session descriptions - * containing ICE data from this agent. - */ - public String getLocalPassword() - { - return password; - } - /** * Returns the user name that this Agent should use in connectivity * checks for outgoing Binding Requests. According to RFC 5245, a Binding @@ -996,83 +794,6 @@ public class Agent return null; } - /** - * Returns the {@link FoundationsRegistry} this agent is using to assign - * candidate foundations. We use the FoundationsRegistry to keep - * track of the foundations we assign within a session (i.e. the entire life - * time of an Agent) - */ - public final FoundationsRegistry getFoundationsRegistry() - { - return foundationsRegistry; - } - - /** - * Returns the IceMediaStream with the specified name or - * null if no such stream has been registered with this - * Agent yet. - * - * @param name the name of the stream that we'd like to obtain a reference - * to. - * - * @return the IceMediaStream with the specified name or - * null if no such stream has been registered with this - * Agent yet. - */ - public IceMediaStream getStream(String name) - { - synchronized(mediaStreams) - { - return mediaStreams.get(name); - } - } - - /** - * Returns a List containing the names of all currently registered - * media streams. - * - * @return a List containing the names of all currently registered - * media streams. - */ - public List getStreamNames() - { - synchronized(mediaStreams) - { - return new LinkedList<>(mediaStreams.keySet()); - } - } - - /** - * Returns a List containing all IceMediaStreams currently - * registered with this agent. - * - * @return a List containing all IceMediaStreams currently - * registered with this agent. - */ - public List getStreams() - { - synchronized(mediaStreams) - { - return new LinkedList<>(mediaStreams.values()); - } - } - - /** - * Returns the number of IceMediaStreams currently registered with - * this agent. - * - * @return the number of IceMediaStreams currently registered with - * this agent. - * - */ - public int getStreamCount() - { - synchronized(mediaStreams) - { - return mediaStreams.size(); - } - } - /** * Gets the IceMediaStreams registered with this Agent for * which connectivity establishment is pending. For example, after a set of @@ -1110,29 +831,6 @@ public class Agent return streams; } - /** - * Gets the StunStack used by this Agent. - * - * @return the StunStack used by this Agent - */ - public synchronized StunStack getStunStack() - { - if (stunStack == null) - stunStack = new StunStack(); - return stunStack; - } - - /** - * Sets the StunStack used by this Agent. - * - * @param stunStack the stunStack to be used by this Agent. - * - */ - public void setStunStack(StunStack stunStack) - { - this.stunStack = stunStack; - } - /** * Returns the number of {@link CheckList}s that are currently active. * @@ -1191,14 +889,12 @@ public class Agent } /** - * Specifies whether this agent has the controlling role in an ICE exchange. - * - * @param isControlling true if this is to be the controlling - * Agent and false otherwise. + * {@inheritDoc} */ - public void setControlling(boolean isControlling) + @Override + public void setControlling(boolean controlling) { - this.isControlling = isControlling; + super.setControlling(controlling); //in case we have already initialized our check lists we'd need to //recompute pair priorities. @@ -1211,96 +907,6 @@ public class Agent } } - /** - * Removes stream and all its child Components and - * Candidates from the this agent and releases all resources that - * they had allocated (like sockets for example) - * - * @param stream the Component we'd like to remove and free. - */ - public void removeStream(IceMediaStream stream) - { - synchronized (mediaStreams) - { - mediaStreams.remove(stream.getName()); - } - /* - * XXX The invocation of IceMediaStream#free() on stream has been moved - * out of the synchronized block in order to reduce the chances of a - * deadlock. There was no obvious reason why it should stay in the - * synchronized block at the time of the modification. - */ - stream.free(); - } - - /** - * Determines whether this agent has the controlling role in an ICE - * exchange. - * - * @return true if this is to be the controlling Agent - * and false otherwise. - */ - public boolean isControlling() - { - return isControlling; - } - - /** - * Returns the local LocalCandidate with the specified - * localAddress if it belongs to any of this {@link Agent}'s - * streams or null if it doesn't. - * - * @param localAddress the {@link TransportAddress} we are looking for. - * - * @return the local LocalCandidate with the specified - * localAddress if it belongs to any of this {@link Agent}'s - * streams or null if it doesn't. - */ - public LocalCandidate findLocalCandidate(TransportAddress localAddress) - { - for(IceMediaStream stream : mediaStreams.values()) - { - LocalCandidate cnd = stream.findLocalCandidate(localAddress); - - if(cnd != null) - return cnd; - } - return null; - } - - /** - * Returns the local LocalCandidate with the specified - * localAddress if it belongs to any of this {@link Agent}'s - * streams or null if it doesn't. - * - * @param localAddress the {@link TransportAddress} we are looking for. - * @param ufrag local ufrag - * @return the local LocalCandidate with the specified - * localAddress if it belongs to any of this {@link Agent}'s - * streams or null if it doesn't. - */ - public LocalCandidate findLocalCandidate( - TransportAddress localAddress, - String ufrag) - { - for(IceMediaStream stream : mediaStreams.values()) - { - for(Component c : stream.getComponents()) - { - for(LocalCandidate cnd : c.getLocalCandidates()) - { - if(cnd != null - && cnd.getUfrag() != null - && cnd.getUfrag().equals(ufrag)) - { - return cnd; - } - } - } - } - return null; - } - /** * Returns the remote Candidate with the specified * remoteAddress if it belongs to any of this {@link Agent}'s @@ -1433,22 +1039,25 @@ public class Agent Component parentComponent = localCandidate.getParentComponent(); RemoteCandidate remoteCandidate = null; - remoteCandidate = new RemoteCandidate( - remoteAddress, - parentComponent, - CandidateType.PEER_REFLEXIVE_CANDIDATE, - foundationsRegistry.obtainFoundationForPeerReflexiveCandidate(), - priority, - // We can not know the related candidate of a remote peer - // reflexive candidate. We must set it to "null". - null, - ufrag); + remoteCandidate + = new RemoteCandidate( + remoteAddress, + parentComponent, + CandidateType.PEER_REFLEXIVE_CANDIDATE, + getFoundationsRegistry() + .obtainFoundationForPeerReflexiveCandidate(), + priority, + // We can not know the related candidate of a remote peer + // reflexive candidate. We must set it to "null". + null, + ufrag); CandidatePair triggeredPair = new CandidatePair(localCandidate, remoteCandidate); - logger.fine("set use-candidate " + useCandidate + " for pair " + - triggeredPair.toShortString()); + logger.fine( + "set use-candidate " + useCandidate + " for pair " + + triggeredPair.toShortString()); if(useCandidate) { triggeredPair.setUseCandidateReceived(); @@ -1462,8 +1071,10 @@ public class Agent //so it's now safe to go and see whether this is a new PR cand. if(triggeredPair.getParentComponent().getSelectedPair() == null) { - logger.info("Received check from " + - triggeredPair.toShortString() + " triggered a check"); + logger.info( + "Received check from " + + triggeredPair.toShortString() + + " triggered a check"); } triggerCheck(triggeredPair); } @@ -1820,26 +1431,6 @@ public class Agent } } - /** - * Returns the number of host {@link Candidate}s in this {@link Agent}. - * - * @return the number of host {@link Candidate}s in this {@link Agent}. - */ - protected int countHostCandidates() - { - int num = 0; - - synchronized (mediaStreams) - { - Collection streamsCol = mediaStreams.values(); - - for( IceMediaStream stream : streamsCol) - num += stream.countHostCandidates(); - } - - return num; - } - /** * Lets the application specify a custom value for the Ta timer * so that we don't calculate one. @@ -2076,57 +1667,6 @@ public class Agent setState(terminationState); } - /** - * Adds or removes ICE characters (i.e. ALPHA, DIGIT, +, or /) to or from a - * specific String in order to produce a String with a - * length within a specific range. - * - * @param s the String to add or remove characters to or from in - * case its length is less than min or greater than max - * @param min the minimum length in (ICE) characters of the returned - * String - * @param max the maximum length in (ICE) characters of the returned - * String - * @return s if its length is greater than or equal to - * min and less than or equal to max; a new - * String which is equal to s with prepended ICE - * characters if the length of s is less than min; a new - * String which is composed of the first max characters of - * s if the length of s is greater than max - * @throws IllegalArgumentException if min is negative or - * max is less than min - * @throws NullPointerException if s is equal to null - */ - private String ensureIceAttributeLength(String s, int min, int max) - { - if (s == null) - throw new NullPointerException("s"); - if (min < 0) - throw new IllegalArgumentException("min " + min); - if (max < min) - throw new IllegalArgumentException("max " + max); - - int length = s.length(); - int numberOfIceCharsToAdd = min - length; - - if (numberOfIceCharsToAdd > 0) - { - StringBuilder sb = new StringBuilder(min); - - for (; numberOfIceCharsToAdd > 0; --numberOfIceCharsToAdd) - { - sb.append('0'); - } - sb.append(s); - s = sb.toString(); - } - else if (max < length) - { - s = s.substring(0, max); - } - return s; - } - /** * Called by the garbage collector when garbage collection determines that * there are no more references to this instance. Calls {@link #free()} on @@ -2375,7 +1915,6 @@ public class Agent this.trickle = trickle; } - /** * Returns the harvesting time (in ms) for the harvester given in parameter. * @@ -2401,7 +1940,6 @@ public class Agent } } } - return 0; } @@ -2433,7 +1971,6 @@ public class Agent } } } - return 0; } @@ -2451,7 +1988,6 @@ public class Agent harvestDuration += harvester.getHarvestStatistics().getHarvestDuration(); } - return harvestDuration; } @@ -2471,7 +2007,6 @@ public class Agent { harvestCount += harvester.getHarvestStatistics().getHarvestCount(); } - return harvestCount; } @@ -2498,32 +2033,4 @@ public class Agent { this.performConsentFreshness = performConsentFreshness; } - - /** - * Checks whether the dynamic host harvester should be used or not. - * @return true if the dynamic host harvester should be used and - * false otherwise. - */ - public boolean useHostHarvester() - { - if (useHostHarvester == null) - { - useHostHarvester - = StackProperties.getBoolean( - StackProperties.USE_DYNAMIC_HOST_HARVESTER, - true); - } - - return useHostHarvester; - } - - /** - * Sets the flag which indicates whether the dynamic host harvester will - * be used or not by this Agent. - * @param useHostHarvester the value to set. - */ - public void setUseHostHarvester(boolean useHostHarvester) - { - this.useHostHarvester = useHostHarvester; - } } diff --git a/src/main/java/org/ice4j/ice/BaseAgent.java b/src/main/java/org/ice4j/ice/BaseAgent.java new file mode 100644 index 0000000..df4d100 --- /dev/null +++ b/src/main/java/org/ice4j/ice/BaseAgent.java @@ -0,0 +1,655 @@ +/* + * ice4j, the OpenSource Java Solution for NAT and Firewall Traversal. + * + * Copyright @ 2015 Atlassian Pty Ltd + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.ice4j.ice; + +import java.io.*; +import java.math.*; +import java.net.*; +import java.security.*; +import java.util.*; +import java.util.logging.*; + +import org.ice4j.*; +import org.ice4j.ice.harvest.*; +import org.ice4j.stack.*; + +/** + * Implements a (common) base of full and lite ICE agents (within the ice4j + * library). + * + * @author Lyubomir Marinov + */ +public class BaseAgent +{ + /** + * The Logger used by the BaseAgent class and its + * instances for logging output. + */ + private static final Logger logger + = Logger.getLogger(BaseAgent.class.getName()); + + /** + * Adds or removes ICE characters (i.e. ALPHA, DIGIT, +, or /) to or from a + * specific String in order to produce a String with a + * length within a specific range. + * + * @param s the String to add or remove characters to or from in + * case its length is less than min or greater than max + * @param min the minimum length in (ICE) characters of the returned + * String + * @param max the maximum length in (ICE) characters of the returned + * String + * @return s if its length is greater than or equal to + * min and less than or equal to max; a new + * String which is equal to s with prepended ICE + * characters if the length of s is less than min; a new + * String which is composed of the first max characters of + * s if the length of s is greater than max + * @throws IllegalArgumentException if min is negative or + * max is less than min + * @throws NullPointerException if s is equal to null + */ + private static String ensureIceAttributeLength(String s, int min, int max) + { + if (s == null) + throw new NullPointerException("s"); + if (min < 0) + throw new IllegalArgumentException("min " + min); + if (max < min) + throw new IllegalArgumentException("max " + max); + + int length = s.length(); + int numberOfIceCharsToAdd = min - length; + + if (numberOfIceCharsToAdd > 0) + { + StringBuilder sb = new StringBuilder(min); + + for (; numberOfIceCharsToAdd > 0; --numberOfIceCharsToAdd) + { + sb.append('0'); + } + sb.append(s); + s = sb.toString(); + } + else if (max < length) + { + s = s.substring(0, max); + } + return s; + } + + /** + * The entity that will be taking care of incoming connectivity checks. + */ + private final ConnectivityCheckServer connCheckServer; + + /** + * Determines whether this is the controlling agent in a an ICE interaction. + * The default value of {@code BaseAgent} is {@code false} since it is + * unable to perform connectivity checks. + */ + private boolean controlling = false; + + /** + * We use the FoundationsRegistry to keep track of the foundations + * we assign within a session (i.e. the entire life time of a + * BaseAgent.) + */ + private final FoundationsRegistry foundationsRegistry + = new FoundationsRegistry(); + + /** + * The candidate harvester that we use to gather candidate on the local + * machine. + */ + private final HostCandidateHarvester hostHarvester + = new HostCandidateHarvester(); + + /** + * A list of additional CandidateHarvesters which will be used to + * harvest candidates synchronously, and previously to harvesting by + * non-host CandidateHarvesters (if implemented by extenders). + */ + private final List hostHarvesters = new LinkedList<>(); + + /** + * The LinkedHashMap used to store the IceMediaStreams. + * Preserves the insertion order. + */ + private final Map mediaStreams + = new LinkedHashMap<>(); + + /** + * The password that we should use for the ice-pwd attribute. + */ + private final String password; + + protected final SecureRandom random = new SecureRandom(); + + /** + * The StunStack used by this BaseAgent. + */ + private StunStack stunStack; + + /** + * The user fragment that we should use for the ice-ufrag attribute. + */ + private final String ufrag; + + /** + * The flag which specifies whether {@link #hostHarvester} is (to be) used. + */ + private Boolean useHostHarvester; + + /** + * Creates an empty BaseAgent with no streams, and no address. + */ + public BaseAgent() + { + connCheckServer = new ConnectivityCheckServer(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"); + + ufrag + = ensureIceAttributeLength( + new BigInteger(24, random).toString(32) + + BigInteger + .valueOf(System.currentTimeMillis()) + .toString(32), + /* min */ 4, /* max */ 256); + password + = ensureIceAttributeLength( + new BigInteger(128, random).toString(32), + /* min */ 22, /* max */ 256); + } + + /** + * Adds harvester to the list of host harvesters that this agent + * will use when gathering Candidates. + * + * @param harvester a CandidateHarvester that this agent should use + * when gathering candidates. + */ + protected void addHostHarvester(CandidateHarvester harvester) + { + if (harvester.isHostHarvester()) + hostHarvesters.add(harvester); + else + throw new IllegalArgumentException("harvester.isHostHarvester"); + } + + /** + * Returns the number of host {@link Candidate}s in this {@code BaseAgent}. + * + * @return the number of host {@link Candidate}s in this {@code BaseAgent}. + */ + protected int countHostCandidates() + { + int num = 0; + + synchronized (mediaStreams) + { + Collection streamsCol = mediaStreams.values(); + + for( IceMediaStream stream : streamsCol) + num += stream.countHostCandidates(); + } + + return num; + } + + /** + * Creates a new {@link Component} for the specified stream and + * allocates potentially all local candidates that should belong to it. + * + * @param stream the {@link IceMediaStream} that the new {@link Component} + * should belong to. + * @param transport the transport protocol used by the component + * @param preferredPort the port number that should be tried first when + * binding local Candidate sockets for this Component. + * @param minPort the port number where we should first try to bind before + * moving to the next one (i.e. minPort + 1) + * @param maxPort the maximum port number where we should try binding + * before giving up and throwing an exception. + * + * @return the newly created {@link Component} and with a list containing + * all and only local candidates. + * + * @throws IllegalArgumentException if either minPort or + * maxPort is not a valid port number or if minPort > + * maxPort, or if transport is not currently supported. + * @throws IOException if an error occurs while the underlying resolver lib + * is using sockets. + * @throws BindException if we couldn't find a free port between + * minPort and maxPort before reaching the maximum allowed + * number of retries. + */ + public Component createComponent( + IceMediaStream stream, + Transport transport, + int preferredPort, int minPort, int maxPort) + throws IllegalArgumentException, + IOException, + BindException + { + if(transport != Transport.UDP) + { + throw new IllegalArgumentException( + "This implementation does not currently support transport: " + + transport); + } + + Component component = stream.createComponent(); + + gatherCandidatesAndSelectDefaultCandidate( + component, + preferredPort, minPort, maxPort); + + for(Candidate candidate : component.getLocalCandidates()) + { + logger.info( + "\t" + candidate.getTransportAddress() + " (" + + candidate.getType() + ")"); + } + + /* + * Lyubomir: After we've gathered the LocalCandidate for a Component and + * before we've made them available to the caller, we have to make sure + * that the ConnectivityCheckServer is started. If there's been a + * previous connectivity establishment which has completed, it has + * stopped the ConnectivityCheckServer. If the ConnectivityCheckServer is + * not started after we've made the gathered LocalCandidates available + * to the caller, the caller may send them and a connectivity check may + * arrive from the remote Agent. + */ + connCheckServer.start(); + + return component; + } + + /** + * Creates a new media stream and stores it. + * + * @param mediaStreamName the name of the media stream + * @return the newly created and stored IceMediaStream + */ + public IceMediaStream createMediaStream(String mediaStreamName) + { + logger.fine("Create media stream for " + mediaStreamName); + + IceMediaStream mediaStream = new IceMediaStream(this, mediaStreamName); + + mediaStreams.put(mediaStreamName, mediaStream); + + return mediaStream; + } + + /** + * Returns the local LocalCandidate with the specified + * localAddress if it belongs to any of this {@code BaseAgent}'s + * streams or null if it doesn't. + * + * @param localAddress the {@link TransportAddress} we are looking for. + * + * @return the local LocalCandidate with the specified + * localAddress if it belongs to any of this {@code BaseAgent}'s + * streams or null if it doesn't. + */ + public LocalCandidate findLocalCandidate(TransportAddress localAddress) + { + for(IceMediaStream stream : mediaStreams.values()) + { + LocalCandidate cnd = stream.findLocalCandidate(localAddress); + + if(cnd != null) + return cnd; + } + return null; + } + + /** + * Returns the local LocalCandidate with the specified + * localAddress if it belongs to any of this {@code BaseAgent}'s + * streams or null if it doesn't. + * + * @param localAddress the {@link TransportAddress} we are looking for. + * @param ufrag local ufrag + * @return the local LocalCandidate with the specified + * localAddress if it belongs to any of this {@code BaseAgent}'s + * streams or null if it doesn't. + */ + public LocalCandidate findLocalCandidate( + TransportAddress localAddress, + String ufrag) + { + for(IceMediaStream stream : mediaStreams.values()) + { + for(Component c : stream.getComponents()) + { + for(LocalCandidate cnd : c.getLocalCandidates()) + { + if(cnd != null + && cnd.getUfrag() != null + && cnd.getUfrag().equals(ufrag)) + { + return cnd; + } + } + } + } + return null; + } + + /** + * Uses all CandidateHarvesters currently registered with this + * Agent to obtain whatever addresses they can discover. + *

+ * Not that the method would only use existing harvesters so make sure + * you've registered all harvesters that you would want to use before + * calling it. + *

+ * @param component the Component that we'd like to gather + * candidates for. + * @param preferredPort the port number that should be tried first when + * binding local Candidate sockets for this Component. + * @param minPort the port number where we should first try to bind before + * moving to the next one (i.e. minPort + 1) + * @param maxPort the maximum port number where we should try binding + * before giving up and throwing an exception. + * + * @throws IllegalArgumentException if either minPort or + * maxPort is not a valid port number or if minPort > + * maxPort. + * @throws IOException if an error occurs while the underlying resolver lib + * is gathering candidates and we end up without even a single one. + */ + protected void gatherCandidates( + Component component, + int preferredPort, int minPort, int maxPort) + throws IllegalArgumentException, + IOException + { + logger.info( + "Gather candidates for component " + component.toShortString()); + + if (useHostHarvester()) + { + hostHarvester.harvest( + component, + preferredPort, minPort, maxPort, + Transport.UDP); + } + else if (hostHarvesters.isEmpty()) + { + logger.warning("No host harvesters available!"); + } + + for (CandidateHarvester harvester : hostHarvesters) + { + harvester.harvest(component); + } + + if (component.getLocalCandidateCount() == 0) + logger.warning("Failed to gather any host candidates!"); + } + + /** + * Uses all CandidateHarvesters currently registered with this + * Agent to obtain whatever addresses they can discover. + *

+ * Not that the method would only use existing harvesters so make sure + * you've registered all harvesters that you would want to use before + * calling it. + *

+ * @param component the Component that we'd like to gather + * candidates for. + * @param preferredPort the port number that should be tried first when + * binding local Candidate sockets for this Component. + * @param minPort the port number where we should first try to bind before + * moving to the next one (i.e. minPort + 1) + * @param maxPort the maximum port number where we should try binding + * before giving up and throwing an exception. + * + * @throws IllegalArgumentException if either minPort or + * maxPort is not a valid port number or if minPort > + * maxPort. + * @throws IOException if an error occurs while the underlying resolver lib + * is gathering candidates and we end up without even a single one. + */ + private void gatherCandidatesAndSelectDefaultCandidate( + Component component, + int preferredPort, int minPort, int maxPort) + throws IllegalArgumentException, + IOException + { + gatherCandidates(component, preferredPort, minPort, maxPort); + + logger.fine( + "Candidate count in first harvest: " + + component.getLocalCandidateCount()); + + //select the candidate to put in the media line. + component.selectDefaultCandidate(); + } + + /** + * Returns the {@link FoundationsRegistry} this agent is using to assign + * candidate foundations. We use the FoundationsRegistry to keep + * track of the foundations we assign within a session (i.e. the entire life + * time of a BaseAgent.) + */ + public final FoundationsRegistry getFoundationsRegistry() + { + return foundationsRegistry; + } + + /** + * Returns that password that should be advertised in session descriptions + * containing ICE data from this agent. + * + * @return that password that should be advertised in session descriptions + * containing ICE data from this agent. + */ + public String getLocalPassword() + { + return password; + } + + /** + * Returns that user name that should be advertised in session descriptions + * containing ICE data from this agent. + * + * @return that user name that should be advertised in session descriptions + * containing ICE data from this agent. + */ + public String getLocalUfrag() + { + return ufrag; + } + + /** + * Returns the IceMediaStream with the specified name or + * null if no such stream has been registered with this + * BaseAgent yet. + * + * @param name the name of the stream that we'd like to obtain a reference + * to. + * + * @return the IceMediaStream with the specified name or + * null if no such stream has been registered with this + * BaseAgent yet. + */ + public IceMediaStream getStream(String name) + { + synchronized(mediaStreams) + { + return mediaStreams.get(name); + } + } + + /** + * Returns the number of IceMediaStreams currently registered with + * this agent. + * + * @return the number of IceMediaStreams currently registered with + * this agent. + * + */ + public int getStreamCount() + { + synchronized(mediaStreams) + { + return mediaStreams.size(); + } + } + + /** + * Returns a List containing the names of all currently registered + * media streams. + * + * @return a List containing the names of all currently registered + * media streams. + */ + public List getStreamNames() + { + synchronized(mediaStreams) + { + return new LinkedList<>(mediaStreams.keySet()); + } + } + + /** + * Returns a List containing all IceMediaStreams currently + * registered with this agent. + * + * @return a List containing all IceMediaStreams currently + * registered with this agent. + */ + public List getStreams() + { + synchronized(mediaStreams) + { + return new LinkedList<>(mediaStreams.values()); + } + } + + /** + * Gets the StunStack used by this BaseAgent. + * + * @return the StunStack used by this BaseAgent + */ + public synchronized StunStack getStunStack() + { + if (stunStack == null) + stunStack = new StunStack(); + return stunStack; + } + + /** + * Determines whether this agent has the controlling role in an ICE + * exchange. + * + * @return true if this is to be the controlling BaseAgent + * and false otherwise. + */ + public boolean isControlling() + { + return controlling; + } + + /** + * Removes stream and all its child Components and + * Candidates from the this agent and releases all resources that + * they had allocated (like sockets for example) + * + * @param stream the Component we'd like to remove and free. + */ + public void removeStream(IceMediaStream stream) + { + synchronized (mediaStreams) + { + mediaStreams.remove(stream.getName()); + } + /* + * XXX The invocation of IceMediaStream#free() on stream has been moved + * out of the synchronized block in order to reduce the chances of a + * deadlock. There was no obvious reason why it should stay in the + * synchronized block at the time of the modification. + */ + stream.free(); + } + + /** + * Specifies whether this agent has the controlling role in an ICE exchange. + * + * @param controlling true if this is to be the controlling + * BaseAgent and false otherwise. + */ + public void setControlling(boolean controlling) + { + this.controlling = controlling; + } + + /** + * Sets the StunStack to be used by this BaseAgent. + * + * @param stunStack the StunStack to be used by this + * BaseAgent. + */ + public void setStunStack(StunStack stunStack) + { + this.stunStack = stunStack; + } + + /** + * Sets the flag which indicates whether the dynamic host harvester (i.e. + * {@link #hostHarvester}) is (to be) used by this BaseAgent. + * + * @param useHostHarvester {@code true} to use the dynamic host harvester; + * otherwise, {@code false}. + */ + public void setUseHostHarvester(boolean useHostHarvester) + { + this.useHostHarvester = useHostHarvester; + } + + /** + * Determines whether the dynamic host harvester (i.e. + * {@link #hostHarvester}) is (to be) used. + * + * @return true if the dynamic host harvester is (to be) used; + * false, otherwise. + */ + public boolean useHostHarvester() + { + if (useHostHarvester == null) + { + useHostHarvester + = StackProperties.getBoolean( + StackProperties.USE_DYNAMIC_HOST_HARVESTER, + true); + } + return useHostHarvester; + } +} diff --git a/src/main/java/org/ice4j/ice/Component.java b/src/main/java/org/ice4j/ice/Component.java index 3b860b2..6b1586b 100644 --- a/src/main/java/org/ice4j/ice/Component.java +++ b/src/main/java/org/ice4j/ice/Component.java @@ -141,7 +141,7 @@ public class Component */ public boolean addLocalCandidate(LocalCandidate candidate) { - Agent agent = getParentStream().getParentAgent(); + BaseAgent agent = getParentStream().getParentAgent(); //assign foundation. agent.getFoundationsRegistry().assignFoundation(candidate); diff --git a/src/main/java/org/ice4j/ice/ConnectivityCheckServer.java b/src/main/java/org/ice4j/ice/ConnectivityCheckServer.java index fdcaa59..49ca4b6 100644 --- a/src/main/java/org/ice4j/ice/ConnectivityCheckServer.java +++ b/src/main/java/org/ice4j/ice/ConnectivityCheckServer.java @@ -63,7 +63,7 @@ class ConnectivityCheckServer /** * The agent that created us. */ - private final Agent parentAgent; + private final BaseAgent parentAgent; /** * The indicator which determines whether this @@ -88,7 +88,7 @@ class ConnectivityCheckServer * * @param parentAgent the Agent that is creating this instance. */ - public ConnectivityCheckServer(Agent parentAgent) + public ConnectivityCheckServer(BaseAgent parentAgent) { this.parentAgent = parentAgent; @@ -139,7 +139,7 @@ class ConnectivityCheckServer //ignore incoming requests that are not meant for the local user. //normally the stack will get rid of faulty user names but we could - //still see messages not meant for this server if both peers or running + //still see messages not meant for this server if both peers are running //on this same instance of the stack. UsernameAttribute uname = (UsernameAttribute)request .getAttribute(Attribute.USERNAME); diff --git a/src/main/java/org/ice4j/ice/IceMediaStream.java b/src/main/java/org/ice4j/ice/IceMediaStream.java index 6768e81..238be07 100644 --- a/src/main/java/org/ice4j/ice/IceMediaStream.java +++ b/src/main/java/org/ice4j/ice/IceMediaStream.java @@ -63,6 +63,19 @@ public class IceMediaStream */ public static final String PROPERTY_PAIR_VALIDATED = "PairValidated"; + /** + * Use builder pattern to provide an immutable IceMediaStream instance. + * + * @param name the name of the media stream + * @param parentAgent the agent that is handling the session that this + * media stream is a part of + * @return IceMediaStream + */ + public static IceMediaStream build(BaseAgent parentAgent, String name) + { + return new IceMediaStream(parentAgent, name); + } + /** * The name of this media stream. The name is equal to the value specified * in the SDP description. @@ -101,7 +114,7 @@ public class IceMediaStream /** * The agent that this media stream belongs to. */ - private final Agent parentAgent; + private final BaseAgent parentAgent; /** * Contains {@link PropertyChangeListener}s registered with this {@link @@ -138,7 +151,7 @@ public class IceMediaStream * @param parentAgent the agent that is handling the session that this * media stream is a part of */ - protected IceMediaStream(Agent parentAgent, String name) + protected IceMediaStream(BaseAgent parentAgent, String name) { this.name = name; this.parentAgent = parentAgent; @@ -278,7 +291,7 @@ public class IceMediaStream * * @return a reference to the Agent that this stream belongs to. */ - public Agent getParentAgent() + public BaseAgent getParentAgent() { return parentAgent; } @@ -898,18 +911,4 @@ public class IceMediaStream { return remotePassword; } - - /** - * Use builder pattern to provide an immutable IceMediaStream instance. - * - * @param name the name of the media stream - * @param parentAgent the agent that is handling the session that this - * media stream is a part of - * @return IceMediaStream - */ - public static IceMediaStream build(Agent parentAgent, String name) - { - return new IceMediaStream(parentAgent, name); - } - } diff --git a/src/main/java/org/ice4j/ice/RemoteCandidate.java b/src/main/java/org/ice4j/ice/RemoteCandidate.java index e6b5a3a..43e6385 100644 --- a/src/main/java/org/ice4j/ice/RemoteCandidate.java +++ b/src/main/java/org/ice4j/ice/RemoteCandidate.java @@ -131,10 +131,9 @@ public class RemoteCandidate { Component parentCmp = getParentComponent(); - if (parentCmp == null) - return false; - - return equals(parentCmp.getDefaultRemoteCandidate()); + return + (parentCmp != null) + && equals(parentCmp.getDefaultRemoteCandidate()); } /** diff --git a/src/main/java/org/ice4j/ice/harvest/SinglePortUdpHarvester.java b/src/main/java/org/ice4j/ice/harvest/SinglePortUdpHarvester.java index 9c47161..22840f0 100644 --- a/src/main/java/org/ice4j/ice/harvest/SinglePortUdpHarvester.java +++ b/src/main/java/org/ice4j/ice/harvest/SinglePortUdpHarvester.java @@ -414,7 +414,7 @@ public class SinglePortUdpHarvester public Collection harvest(Component component) { IceMediaStream stream = component.getParentStream(); - Agent agent = stream.getParentAgent(); + BaseAgent agent = stream.getParentAgent(); String ufrag = agent.getLocalUfrag(); if (stream.getComponentCount() != 1 || agent.getStreamCount() != 1) diff --git a/src/main/java/org/ice4j/ice/harvest/TcpHarvester.java b/src/main/java/org/ice4j/ice/harvest/TcpHarvester.java index 3a66010..835049c 100644 --- a/src/main/java/org/ice4j/ice/harvest/TcpHarvester.java +++ b/src/main/java/org/ice4j/ice/harvest/TcpHarvester.java @@ -571,7 +571,7 @@ public class TcpHarvester public Collection harvest(Component component) { IceMediaStream stream = component.getParentStream(); - Agent agent = stream.getParentAgent(); + BaseAgent agent = stream.getParentAgent(); if (stream.getComponentCount() != 1 || agent.getStreamCount() != 1) { @@ -583,7 +583,7 @@ public class TcpHarvester */ logger.info( "More than one Component for an Agent, cannot harvest."); - return new LinkedList<>(); + return Collections.EMPTY_LIST; } List candidates = createLocalCandidates(component); @@ -1080,8 +1080,8 @@ public class TcpHarvester } /** - * Adds the channels from {@link #newChannels} to {@link #channels} and - * registers them in {@link #readSelector}. + * Registers the channels from {@link #newChannels} with + * {@link #readSelector}. */ private void checkForNewChannels() { @@ -1108,8 +1108,9 @@ public class TcpHarvester } /** - * Checks {@link #channels} for channels which have been added over - * {@link #READ_TIMEOUT} milliseconds ago and closes them. + * Checks {@link #readSelector} for channels which have been added over + * {@link MuxServerSocketChannelFactory#SOCKET_CHANNEL_READ_TIMEOUT} + * milliseconds ago and closes them. */ private void cleanup() {