Merge pull request #89 from bgrozev/tcp-fallback

Tcp fallback
This commit is contained in:
bbaldino 2016-12-15 09:26:10 -08:00 committed by GitHub
commit e300997924
6 changed files with 353 additions and 91 deletions

View File

@ -451,6 +451,50 @@ public class Agent
throws IllegalArgumentException,
IOException,
BindException
{
return createComponent(
stream, transport,
preferredPort, minPort, maxPort,
KeepAliveStrategy.SELECTED_ONLY);
}
/**
* Creates a new {@link Component} for the specified <tt>stream</tt> 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 <tt>Candidate</tt> sockets for this <tt>Component</tt>.
* @param minPort the port number where we should first try to bind before
* moving to the next one (i.e. <tt>minPort + 1</tt>)
* @param maxPort the maximum port number where we should try binding
* before giving up and throwing an exception.
* @param keepAliveStrategy the keep-alive strategy, which dictates which
* candidates pairs are going to be kept alive.
*
* @return the newly created {@link Component} and with a list containing
* all and only local candidates.
*
* @throws IllegalArgumentException if either <tt>minPort</tt> or
* <tt>maxPort</tt> is not a valid port number or if <tt>minPort &gt;
* maxPort</tt>, or if <tt>transport</tt> 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
* <tt>minPort</tt> and <tt>maxPort</tt> before reaching the maximum allowed
* number of retries.
*/
public Component createComponent( IceMediaStream stream,
Transport transport,
int preferredPort,
int minPort,
int maxPort,
KeepAliveStrategy keepAliveStrategy)
throws IllegalArgumentException,
IOException,
BindException
{
if (transport != Transport.UDP)
{
@ -459,7 +503,7 @@ public class Agent
+ transport);
}
Component component = stream.createComponent();
Component component = stream.createComponent(keepAliveStrategy);
gatherCandidates(component, preferredPort, minPort, maxPort);
@ -1253,7 +1297,9 @@ public class Agent
buff.append("):\n");
for (IceMediaStream stream : getStreams())
{
buff.append(stream).append("\n");
}
return buff.toString();
}
@ -1287,9 +1333,11 @@ public class Agent
CheckList list = stream.getCheckList();
if (list != null)
{
list.recomputePairPriorities();
}
}
}
/**
* Removes <tt>stream</tt> and all its child <tt>Component</tt>s and
@ -1343,8 +1391,10 @@ public class Agent
LocalCandidate cnd = stream.findLocalCandidate(localAddress);
if (cnd != null)
{
return cnd;
}
}
return null;
}
@ -1399,8 +1449,10 @@ public class Agent
RemoteCandidate cnd = stream.findRemoteCandidate(remoteAddress);
if (cnd != null)
{
return cnd;
}
}
return null;
}
@ -1746,7 +1798,9 @@ public class Agent
CheckList checkList = parentStream.getCheckList();
if ( checkList.getState() == CheckListState.RUNNING )
{
checkList.handleNominationConfirmed(nominatedPair);
}
//Once there is at least one nominated pair in the valid list for
//every component of the media stream and the state of the
@ -1771,7 +1825,9 @@ public class Agent
boolean atLeastOneListSucceeded = false;
if (getState().isEstablished())
{
return;
}
List<IceMediaStream> streams = getStreams();
@ -1794,7 +1850,9 @@ public class Agent
if (!allListsEnded)
{
return;
}
if (!atLeastOneListSucceeded)
{
@ -1827,7 +1885,9 @@ public class Agent
// under our nose here has been observed (and not in a single instance)
// So check that we did indeed just trigger the change.
if (!setState(IceProcessingState.COMPLETED))
{
return;
}
// keep ICE running (answer STUN Binding requests, send STUN Binding
// indications or requests)
@ -1917,8 +1977,10 @@ public class Agent
Collection<IceMediaStream> streamsCol = mediaStreams.values();
for (IceMediaStream stream : streamsCol)
{
num += stream.countHostCandidates();
}
}
return num;
}
@ -2280,7 +2342,8 @@ public class Agent
{
for (Component component : stream.getComponents())
{
CandidatePair pair = component.getSelectedPair();
for (CandidatePair pair : component.getKeepAlivePairs())
{
if (pair != null)
{
@ -2294,14 +2357,18 @@ public class Agent
}
else
{
connCheckClient.sendBindingIndicationForPair(pair);
connCheckClient
.sendBindingIndicationForPair(pair);
}
}
}
}
}
if (!runInStunKeepAliveThreadCondition())
{
break;
}
try
{

View File

@ -17,8 +17,10 @@
*/
package org.ice4j.ice;
import java.beans.*;
import java.net.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.logging.*;
import org.ice4j.*;
@ -38,6 +40,7 @@ import org.ice4j.util.Logger; //Disambiguation
* @author Boris Grozev
*/
public class Component
implements PropertyChangeListener
{
/**
* Our class logger.
@ -146,6 +149,19 @@ public class Component
@Deprecated
private final IceSocketWrapper socketWrapper;
/**
* The {@link KeepAliveStrategy} used by this component to select which
* pairs are to be kept alive.
*/
private final KeepAliveStrategy keepAliveStrategy;
/**
* The set of pairs which this component wants to keep alive.
*/
private final Set<CandidatePair> keepAlivePairs
= Collections.newSetFromMap(
new ConcurrentHashMap<CandidatePair, Boolean>());
/**
* Creates a new <tt>Component</tt> with the specified <tt>componentID</tt>
* as a child of the specified <tt>IceMediaStream</tt>.
@ -155,11 +171,14 @@ public class Component
* parent of this component.
*/
protected Component(int componentID,
IceMediaStream mediaStream)
IceMediaStream mediaStream,
KeepAliveStrategy keepAliveStrategy)
{
// the max value for componentID is 256
this.componentID = componentID;
this.parentStream = mediaStream;
this.keepAliveStrategy
= Objects.requireNonNull(keepAliveStrategy, "keepAliveStrategy");
Logger agentLogger = mediaStream.getParentAgent().getLogger();
@ -174,6 +193,7 @@ public class Component
throw new RuntimeException(se);
}
mediaStream.addPairChangeListener(this);
logger = new Logger(classLogger, agentLogger);
}
@ -817,6 +837,8 @@ public class Component
}
}
getParentStream().removePairStateChangeListener(this);
keepAlivePairs.clear();
getComponentSocket().close();
}
@ -888,8 +910,10 @@ public class Component
for (RemoteCandidate remoteCnd : remoteCandidates)
{
if (remoteCnd.getTransportAddress().equals(remoteAddress))
{
return remoteCnd;
}
}
return null;
}
@ -902,6 +926,12 @@ public class Component
*/
protected void setSelectedPair(CandidatePair pair)
{
if (keepAliveStrategy == KeepAliveStrategy.SELECTED_ONLY)
{
keepAlivePairs.clear();
}
keepAlivePairs.add(pair);
this.selectedPair = pair;
}
@ -929,12 +959,18 @@ public class Component
public String getName()
{
if (componentID == RTP)
{
return "RTP";
}
else if (componentID == RTCP)
{
return "RTCP";
}
else
{
return Integer.toString(componentID);
}
}
/**
* Use builder pattern to allow creation of immutable Component instances,
@ -947,7 +983,9 @@ public class Component
*/
public static Component build(int componentID, IceMediaStream mediaStream)
{
return new Component(componentID, mediaStream);
return
new Component(
componentID, mediaStream, KeepAliveStrategy.SELECTED_ONLY);
}
/**
@ -977,4 +1015,77 @@ public class Component
{
return socketWrapper;
}
/**
* @return the set of candidate pairs which are to be kept alive.
*/
Set<CandidatePair> getKeepAlivePairs()
{
return keepAlivePairs;
}
/**
* {@inheritDoc}
* </p>
* Handles events coming from candidate pairs.
*/
@Override
public void propertyChange(PropertyChangeEvent event)
{
String propertyName = event.getPropertyName();
if (!(event.getSource() instanceof CandidatePair))
{
return;
}
CandidatePair pair = (CandidatePair) event.getSource();
if (!equals(pair.getParentComponent()))
{
// Events are fired by the IceMediaStream, which might have
// multiple components. Make sure that we only handle events for
// this component.
return;
}
boolean addToKeepAlive = false;
// We handle this case in setSelectedPair
if (keepAliveStrategy == KeepAliveStrategy.SELECTED_ONLY)
return;
if (IceMediaStream.PROPERTY_PAIR_STATE_CHANGED.equals(propertyName))
{
CandidatePairState newState
= (CandidatePairState) event.getNewValue();
if (CandidatePairState.SUCCEEDED.equals(newState))
{
if (keepAliveStrategy == KeepAliveStrategy.ALL_SUCCEEDED)
{
addToKeepAlive = true;
}
else if (keepAliveStrategy == KeepAliveStrategy.SELECTED_AND_TCP)
{
Transport transport
= pair.getLocalCandidate().getTransport();
addToKeepAlive = transport == Transport.TCP
|| transport == Transport.SSLTCP;
// Pairs with a remote TCP port 9 cannot be checked.
// Instead, the corresponding pair with the peer reflexive
// candidate needs to be checked. However, we observe
// such pairs transitioning into the SUCCEEDED state.
// Ignore them.
addToKeepAlive
&= pair.getRemoteCandidate()
.getTransportAddress().getPort() != 9;
}
}
}
if (addToKeepAlive && !keepAlivePairs.contains(pair))
{
keepAlivePairs.add(pair);
}
}
}

View File

@ -19,11 +19,9 @@ package org.ice4j.ice;
import java.beans.*;
import java.util.*;
import java.util.logging.*;
import java.util.logging.Logger;
import org.ice4j.*;
import org.ice4j.util.*;
/**
* The class represents a media stream from the ICE perspective, i.e. a
@ -175,16 +173,20 @@ public class IceMediaStream
* when creating the component so make sure you keep that in mind in case
* assigning a specific component ID is important to you.
*
* @param keepAliveStrategy the keep-alive strategy, which dictates which
* candidates pairs are going to be kept alive.
*
* @return the newly created stream <tt>Component</tt> after adding it to
* the stream first.
*/
protected Component createComponent()
protected Component createComponent(KeepAliveStrategy keepAliveStrategy)
{
Component component;
synchronized (components)
{
component = new Component(++lastComponentID, this);
component
= new Component(++lastComponentID, this, keepAliveStrategy);
components.put(component.getComponentID(), component);
}

View File

@ -0,0 +1,71 @@
/*
* ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
*
* Copyright @ 2015 Atlassian Pty Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.ice4j.ice;
/**
* An enumeration of strategies for selecting which candidate pairs to
* keep alive.
*/
public enum KeepAliveStrategy
{
/**
* Only keep alive the selected pair.
*/
SELECTED_ONLY("selected_only"),
/**
* Keep alive the selected pair and any TCP pairs.
*/
SELECTED_AND_TCP("selected_and_tcp"),
/**
* Keep alive all succeeded pairs.
*/
ALL_SUCCEEDED("all_succeeded");
private String name;
KeepAliveStrategy(String name)
{
this.name = name;
}
/**
* @return the {@link KeepAliveStrategy} with name equal to the given
* string, or {@code null} if there is no such strategy.
* @param string the name of the strategy.
*/
public static KeepAliveStrategy fromString(String string)
{
for (KeepAliveStrategy strategy : KeepAliveStrategy.values())
{
if (strategy.name.equals(string))
return strategy;
}
return null;
}
/**
* {@inheritDoc}
*/
@Override
public String toString()
{
return name;
}
}

View File

@ -258,15 +258,19 @@ class Connector
}
catch (ClosedChannelException cce)
{
logger.log(Level.WARNING,
"A net access point has gone useless:", cce);
// The socket was closed, possibly by the remote peer.
// If we were already stopped, just ignore it.
if (running)
{
// We could be the first thread to realize that the socket
// was closed. But that's normal operation, so don't
// complain too much.
stop();
errorHandler.handleFatalError(
this,
"ClosedChannelException occurred while listening"
+ " for messages!",
cce);
"The socket was closed:",
null);
}
}
catch (IOException ex)
{

View File

@ -256,7 +256,14 @@ class NetAccessManager
//make sure nothing's left and notify user
removeSocket(connector.getListenAddress(),
connector.getRemoteAddress());
logger.log(Level.WARNING, "Removing connector:" + connector, error);
if (error != null)
{
logger.log(Level.WARNING, "Removing connector:" + connector,
error);
} else if (logger.isLoggable(Level.FINE))
{
logger.fine("Removing connector " + connector);
}
}
else if( callingThread instanceof MessageProcessor )
{