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

@ -448,18 +448,62 @@ public class Agent
int preferredPort, int preferredPort,
int minPort, int minPort,
int maxPort) int maxPort)
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, throws IllegalArgumentException,
IOException, IOException,
BindException BindException
{ {
if(transport != Transport.UDP) if (transport != Transport.UDP)
{ {
throw new IllegalArgumentException( throw new IllegalArgumentException(
"This implementation does not currently support transport: " "This implementation does not currently support transport: "
+ transport); + transport);
} }
Component component = stream.createComponent(); Component component = stream.createComponent(keepAliveStrategy);
gatherCandidates(component, preferredPort, minPort, maxPort); gatherCandidates(component, preferredPort, minPort, maxPort);
@ -554,7 +598,7 @@ public class Agent
logger.warning("Failed to gather any host candidates!"); logger.warning("Failed to gather any host candidates!");
//in case we are not trickling, apply other harvesters here //in case we are not trickling, apply other harvesters here
if(!isTrickling()) 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); harvesters.harvest(component);
@ -588,13 +632,13 @@ public class Agent
public void startCandidateTrickle(TrickleCallback trickleCallback) public void startCandidateTrickle(TrickleCallback trickleCallback)
throws IllegalStateException throws IllegalStateException
{ {
if(!isTrickling()) if (!isTrickling())
{ {
throw new IllegalStateException( throw new IllegalStateException(
"Trying to start trickling without enabling it on the agent!"); "Trying to start trickling without enabling it on the agent!");
} }
if(harvestingStarted) if (harvestingStarted)
{ {
logger.warning( logger.warning(
"Hmmm ... why are you harvesting twice? You shouldn't be!"); "Hmmm ... why are you harvesting twice? You shouldn't be!");
@ -642,7 +686,7 @@ public class Agent
//if we have received connectivity checks before RUNNING state, //if we have received connectivity checks before RUNNING state,
//trigger a check for those candidate pairs. //trigger a check for those candidate pairs.
if(this.preDiscoveredPairsQueue.size() > 0) if (this.preDiscoveredPairsQueue.size() > 0)
{ {
logger.info( logger.info(
"Trigger checks for pairs that were received before " "Trigger checks for pairs that were received before "
@ -863,7 +907,7 @@ public class Agent
? 0 ? 0
: maxCheckListSize / streamCount; : maxCheckListSize / streamCount;
for(IceMediaStream stream : streams) for (IceMediaStream stream : streams)
{ {
logger.info("Init checklist for stream " + stream.getName()); logger.info("Init checklist for stream " + stream.getName());
stream.setMaxCheckListSize(maxPerStreamSize); stream.setMaxCheckListSize(maxPerStreamSize);
@ -1252,8 +1296,10 @@ public class Agent
buff.append(" tie-breaker:").append(getTieBreaker()); buff.append(" tie-breaker:").append(getTieBreaker());
buff.append("):\n"); buff.append("):\n");
for(IceMediaStream stream : getStreams()) for (IceMediaStream stream : getStreams())
{
buff.append(stream).append("\n"); buff.append(stream).append("\n");
}
return buff.toString(); return buff.toString();
} }
@ -1282,12 +1328,14 @@ public class Agent
//in case we have already initialized our check lists we'd need to //in case we have already initialized our check lists we'd need to
//recompute pair priorities. //recompute pair priorities.
for(IceMediaStream stream : getStreams()) for (IceMediaStream stream : getStreams())
{ {
CheckList list = stream.getCheckList(); CheckList list = stream.getCheckList();
if (list != null) if (list != null)
{
list.recomputePairPriorities(); list.recomputePairPriorities();
}
} }
} }
@ -1338,12 +1386,14 @@ public class Agent
*/ */
public LocalCandidate findLocalCandidate(TransportAddress localAddress) public LocalCandidate findLocalCandidate(TransportAddress localAddress)
{ {
for(IceMediaStream stream : mediaStreams.values()) for (IceMediaStream stream : mediaStreams.values())
{ {
LocalCandidate cnd = stream.findLocalCandidate(localAddress); LocalCandidate cnd = stream.findLocalCandidate(localAddress);
if(cnd != null) if (cnd != null)
{
return cnd; return cnd;
}
} }
return null; return null;
} }
@ -1363,13 +1413,13 @@ public class Agent
TransportAddress localAddress, TransportAddress localAddress,
String ufrag) String ufrag)
{ {
for(IceMediaStream stream : mediaStreams.values()) for (IceMediaStream stream : mediaStreams.values())
{ {
for(Component c : stream.getComponents()) for (Component c : stream.getComponents())
{ {
for(LocalCandidate cnd : c.getLocalCandidates()) for (LocalCandidate cnd : c.getLocalCandidates())
{ {
if(cnd != null if (cnd != null
&& cnd.getUfrag() != null && cnd.getUfrag() != null
&& cnd.getUfrag().equals(ufrag)) && cnd.getUfrag().equals(ufrag))
{ {
@ -1394,12 +1444,14 @@ public class Agent
*/ */
public RemoteCandidate findRemoteCandidate(TransportAddress remoteAddress) public RemoteCandidate findRemoteCandidate(TransportAddress remoteAddress)
{ {
for(IceMediaStream stream : mediaStreams.values()) for (IceMediaStream stream : mediaStreams.values())
{ {
RemoteCandidate cnd = stream.findRemoteCandidate(remoteAddress); RemoteCandidate cnd = stream.findRemoteCandidate(remoteAddress);
if(cnd != null) if (cnd != null)
{
return cnd; return cnd;
}
} }
return null; return null;
} }
@ -1503,7 +1555,7 @@ public class Agent
localCandidate = findLocalCandidate(localAddress); localCandidate = findLocalCandidate(localAddress);
if(localCandidate == null) if (localCandidate == null)
{ {
logger.info("No localAddress for this incoming checks: " + logger.info("No localAddress for this incoming checks: " +
localAddress); localAddress);
@ -1529,18 +1581,18 @@ public class Agent
logger.fine("set use-candidate " + useCandidate + " for pair " + logger.fine("set use-candidate " + useCandidate + " for pair " +
triggeredPair.toShortString()); triggeredPair.toShortString());
if(useCandidate) if (useCandidate)
{ {
triggeredPair.setUseCandidateReceived(); triggeredPair.setUseCandidateReceived();
} }
synchronized(startLock) synchronized(startLock)
{ {
if(isStarted()) if (isStarted())
{ {
//we are started, which means we have the remote candidates //we are started, which means we have the remote candidates
//so it's now safe to go and see whether this is a new PR cand. //so it's now safe to go and see whether this is a new PR cand.
if(triggeredPair.getParentComponent().getSelectedPair() == null) if (triggeredPair.getParentComponent().getSelectedPair() == null)
{ {
logger.info("Received check from " logger.info("Received check from "
+ triggeredPair.toShortString() + " triggered a check. " + triggeredPair.toShortString() + " triggered a check. "
@ -1637,7 +1689,7 @@ public class Agent
// Its state is set to Waiting [and it] is enqueued into the // Its state is set to Waiting [and it] is enqueued into the
// triggered check queue. // triggered check queue.
// //
if(triggerPair.getParentComponent().getSelectedPair() == null) if (triggerPair.getParentComponent().getSelectedPair() == null)
logger.info("Add peer CandidatePair with new reflexive " + logger.info("Add peer CandidatePair with new reflexive " +
"address to checkList: " + triggerPair); "address to checkList: " + triggerPair);
parentStream.addToCheckList(triggerPair); parentStream.addToCheckList(triggerPair);
@ -1696,7 +1748,7 @@ public class Agent
public synchronized void nominate(CandidatePair pair) public synchronized void nominate(CandidatePair pair)
throws IllegalStateException throws IllegalStateException
{ {
if(!isControlling()) if (!isControlling())
{ {
throw new IllegalStateException( throw new IllegalStateException(
"Only controlling agents can nominate pairs"); "Only controlling agents can nominate pairs");
@ -1745,13 +1797,15 @@ public class Agent
IceMediaStream parentStream = parentComponent.getParentStream(); IceMediaStream parentStream = parentComponent.getParentStream();
CheckList checkList = parentStream.getCheckList(); CheckList checkList = parentStream.getCheckList();
if( checkList.getState() == CheckListState.RUNNING ) if ( checkList.getState() == CheckListState.RUNNING )
{
checkList.handleNominationConfirmed(nominatedPair); checkList.handleNominationConfirmed(nominatedPair);
}
//Once there is at least one nominated pair in the valid list for //Once there is at least one nominated pair in the valid list for
//every component of the media stream and the state of the //every component of the media stream and the state of the
//check list is Running //check list is Running
if(parentStream.allComponentsHaveSelected() if (parentStream.allComponentsHaveSelected()
&& checkList.getState() == CheckListState.RUNNING) && checkList.getState() == CheckListState.RUNNING)
{ {
//The agent MUST change the state of processing for its check //The agent MUST change the state of processing for its check
@ -1770,21 +1824,23 @@ public class Agent
boolean allListsEnded = true; boolean allListsEnded = true;
boolean atLeastOneListSucceeded = false; boolean atLeastOneListSucceeded = false;
if(getState().isEstablished()) if (getState().isEstablished())
{
return; return;
}
List<IceMediaStream> streams = getStreams(); List<IceMediaStream> streams = getStreams();
for(IceMediaStream stream : streams) for (IceMediaStream stream : streams)
{ {
CheckListState checkListState = stream.getCheckList().getState(); CheckListState checkListState = stream.getCheckList().getState();
if(checkListState == CheckListState.RUNNING) if (checkListState == CheckListState.RUNNING)
{ {
allListsEnded = false; allListsEnded = false;
break; break;
} }
else if(checkListState == CheckListState.COMPLETED) else if (checkListState == CheckListState.COMPLETED)
{ {
logger.info("CheckList of stream " + stream.getName() + logger.info("CheckList of stream " + stream.getName() +
" is COMPLETED"); " is COMPLETED");
@ -1793,10 +1849,12 @@ public class Agent
} }
if(!allListsEnded) if (!allListsEnded)
{
return; return;
}
if(!atLeastOneListSucceeded) if (!atLeastOneListSucceeded)
{ {
//all lists ended but none succeeded. No love today ;( //all lists ended but none succeeded. No love today ;(
if (logger.isLoggable(Level.INFO)) if (logger.isLoggable(Level.INFO))
@ -1817,7 +1875,7 @@ public class Agent
//Once the state of each check list is Completed: //Once the state of each check list is Completed:
//The agent sets the state of ICE processing overall to Completed. //The agent sets the state of ICE processing overall to Completed.
if(getState() != IceProcessingState.RUNNING) if (getState() != IceProcessingState.RUNNING)
{ {
//Oh, seems like we already did this. //Oh, seems like we already did this.
return; return;
@ -1827,7 +1885,9 @@ public class Agent
// under our nose here has been observed (and not in a single instance) // under our nose here has been observed (and not in a single instance)
// So check that we did indeed just trigger the change. // So check that we did indeed just trigger the change.
if (!setState(IceProcessingState.COMPLETED)) if (!setState(IceProcessingState.COMPLETED))
{
return; return;
}
// keep ICE running (answer STUN Binding requests, send STUN Binding // keep ICE running (answer STUN Binding requests, send STUN Binding
// indications or requests) // indications or requests)
@ -1855,9 +1915,9 @@ public class Agent
{ {
List<IceMediaStream> strms = getStreams(); List<IceMediaStream> strms = getStreams();
for(IceMediaStream stream : strms) for (IceMediaStream stream : strms)
{ {
for(Component component : stream.getComponents()) for (Component component : stream.getComponents())
{ {
CandidatePair selectedPair = component.getSelectedPair(); CandidatePair selectedPair = component.getSelectedPair();
@ -1867,7 +1927,7 @@ public class Agent
buf.append(" (local ufrag ").append(getLocalUfrag()); buf.append(" (local ufrag ").append(getLocalUfrag());
buf.append("): "); buf.append("): ");
if(selectedPair == null) if (selectedPair == null)
{ {
buf.append("none (conn checks failed)"); buf.append("none (conn checks failed)");
logger.info(buf.toString()); logger.info(buf.toString());
@ -1880,7 +1940,7 @@ public class Agent
buf.append(localCnd.getType()); buf.append(localCnd.getType());
if(serverAddr != null) if (serverAddr != null)
{ {
buf.append(" (STUN server = "); buf.append(" (STUN server = ");
buf.append(serverAddr); buf.append(serverAddr);
@ -1891,7 +1951,7 @@ public class Agent
TransportAddress relayAddr TransportAddress relayAddr
= localCnd.getRelayServerAddress(); = localCnd.getRelayServerAddress();
if(relayAddr != null) if (relayAddr != null)
{ {
buf.append(" (relay = "); buf.append(" (relay = ");
buf.append(relayAddr); buf.append(relayAddr);
@ -1916,8 +1976,10 @@ public class Agent
{ {
Collection<IceMediaStream> streamsCol = mediaStreams.values(); Collection<IceMediaStream> streamsCol = mediaStreams.values();
for( IceMediaStream stream : streamsCol) for (IceMediaStream stream : streamsCol)
{
num += stream.countHostCandidates(); num += stream.countHostCandidates();
}
} }
return num; return num;
@ -2276,32 +2338,37 @@ public class Agent
while (runInStunKeepAliveThreadCondition()) while (runInStunKeepAliveThreadCondition())
{ {
for(IceMediaStream stream : getStreams()) for (IceMediaStream stream : getStreams())
{ {
for(Component component : stream.getComponents()) for (Component component : stream.getComponents())
{ {
CandidatePair pair = component.getSelectedPair(); for (CandidatePair pair : component.getKeepAlivePairs())
if(pair != null)
{ {
if(performConsentFreshness)
if (pair != null)
{ {
connCheckClient.startCheckForPair( if (performConsentFreshness)
{
connCheckClient.startCheckForPair(
pair, pair,
originalConsentFreshnessWaitInterval, originalConsentFreshnessWaitInterval,
maxConsentFreshnessWaitInterval, maxConsentFreshnessWaitInterval,
consentFreshnessMaxRetransmissions); consentFreshnessMaxRetransmissions);
} }
else else
{ {
connCheckClient.sendBindingIndicationForPair(pair); connCheckClient
.sendBindingIndicationForPair(pair);
}
} }
} }
} }
} }
if (!runInStunKeepAliveThreadCondition()) if (!runInStunKeepAliveThreadCondition())
{
break; break;
}
try try
{ {
@ -2427,15 +2494,15 @@ public class Agent
{ {
long harvestingTime = 0; long harvestingTime = 0;
for(CandidateHarvester harvester : harvesters) for (CandidateHarvester harvester : harvesters)
{ {
if(harvester.getClass().getName().endsWith(harvesterName)) if (harvester.getClass().getName().endsWith(harvesterName))
{ {
harvestingTime harvestingTime
= harvester.getHarvestStatistics().getHarvestDuration(); = harvester.getHarvestStatistics().getHarvestDuration();
// There may be several harvester with the same class name. // There may be several harvester with the same class name.
// Thus, returns only an active one (if any). // Thus, returns only an active one (if any).
if(harvestingTime != 0) if (harvestingTime != 0)
{ {
return harvestingTime; return harvestingTime;
} }
@ -2459,15 +2526,15 @@ public class Agent
{ {
int harvestCount; int harvestCount;
for(CandidateHarvester harvester : harvesters) for (CandidateHarvester harvester : harvesters)
{ {
if(harvester.getClass().getName().endsWith(harvesterName)) if (harvester.getClass().getName().endsWith(harvesterName))
{ {
harvestCount harvestCount
= harvester.getHarvestStatistics().getHarvestCount(); = harvester.getHarvestStatistics().getHarvestCount();
// There may be several harvester with the same class name. // There may be several harvester with the same class name.
// Thus, returns only an active one (if any). // Thus, returns only an active one (if any).
if(harvestCount != 0) if (harvestCount != 0)
{ {
return harvestCount; return harvestCount;
} }
@ -2486,7 +2553,7 @@ public class Agent
{ {
long harvestDuration = 0; long harvestDuration = 0;
for(CandidateHarvester harvester : harvesters) for (CandidateHarvester harvester : harvesters)
{ {
harvestDuration harvestDuration
+= harvester.getHarvestStatistics().getHarvestDuration(); += harvester.getHarvestStatistics().getHarvestDuration();
@ -2507,7 +2574,7 @@ public class Agent
{ {
int harvestCount = 0; int harvestCount = 0;
for(CandidateHarvester harvester : harvesters) for (CandidateHarvester harvester : harvesters)
{ {
harvestCount += harvester.getHarvestStatistics().getHarvestCount(); harvestCount += harvester.getHarvestStatistics().getHarvestCount();
} }

View File

@ -17,8 +17,10 @@
*/ */
package org.ice4j.ice; package org.ice4j.ice;
import java.beans.*;
import java.net.*; import java.net.*;
import java.util.*; import java.util.*;
import java.util.concurrent.*;
import java.util.logging.*; import java.util.logging.*;
import org.ice4j.*; import org.ice4j.*;
@ -38,6 +40,7 @@ import org.ice4j.util.Logger; //Disambiguation
* @author Boris Grozev * @author Boris Grozev
*/ */
public class Component public class Component
implements PropertyChangeListener
{ {
/** /**
* Our class logger. * Our class logger.
@ -146,6 +149,19 @@ public class Component
@Deprecated @Deprecated
private final IceSocketWrapper socketWrapper; 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> * Creates a new <tt>Component</tt> with the specified <tt>componentID</tt>
* as a child of the specified <tt>IceMediaStream</tt>. * as a child of the specified <tt>IceMediaStream</tt>.
@ -155,11 +171,14 @@ public class Component
* parent of this component. * parent of this component.
*/ */
protected Component(int componentID, protected Component(int componentID,
IceMediaStream mediaStream) IceMediaStream mediaStream,
KeepAliveStrategy keepAliveStrategy)
{ {
// the max value for componentID is 256 // the max value for componentID is 256
this.componentID = componentID; this.componentID = componentID;
this.parentStream = mediaStream; this.parentStream = mediaStream;
this.keepAliveStrategy
= Objects.requireNonNull(keepAliveStrategy, "keepAliveStrategy");
Logger agentLogger = mediaStream.getParentAgent().getLogger(); Logger agentLogger = mediaStream.getParentAgent().getLogger();
@ -174,6 +193,7 @@ public class Component
throw new RuntimeException(se); throw new RuntimeException(se);
} }
mediaStream.addPairChangeListener(this);
logger = new Logger(classLogger, agentLogger); logger = new Logger(classLogger, agentLogger);
} }
@ -248,7 +268,7 @@ public class Component
synchronized(localCandidates) synchronized(localCandidates)
{ {
int count = 0; int count = 0;
for(Candidate<?> cand : localCandidates) for (Candidate<?> cand : localCandidates)
{ {
if ((cand.getType() == CandidateType.HOST_CANDIDATE) if ((cand.getType() == CandidateType.HOST_CANDIDATE)
&& !cand.isVirtual()) && !cand.isVirtual())
@ -343,7 +363,7 @@ public class Component
synchronized(remoteUpdateCandidates) synchronized(remoteUpdateCandidates)
{ {
if(remoteUpdateCandidates.size() == 0) if (remoteUpdateCandidates.size() == 0)
return; return;
newRemoteCandidates = new LinkedList<>(remoteUpdateCandidates); newRemoteCandidates = new LinkedList<>(remoteUpdateCandidates);
@ -352,9 +372,9 @@ public class Component
// remove UPnP base from local candidate // remove UPnP base from local candidate
LocalCandidate upnpBase = null; LocalCandidate upnpBase = null;
for(LocalCandidate lc : localCnds) for (LocalCandidate lc : localCnds)
{ {
if(lc instanceof UPNPCandidate) if (lc instanceof UPNPCandidate)
{ {
upnpBase = lc.getBase(); upnpBase = lc.getBase();
} }
@ -362,26 +382,26 @@ public class Component
checkList = new Vector<>(); checkList = new Vector<>();
for(LocalCandidate localCnd : localCnds) for (LocalCandidate localCnd : localCnds)
{ {
if(localCnd == upnpBase) if (localCnd == upnpBase)
continue; continue;
//pair each of the new remote candidates with each of our locals //pair each of the new remote candidates with each of our locals
for(RemoteCandidate remoteCnd : remoteUpdateCandidates) for (RemoteCandidate remoteCnd : remoteUpdateCandidates)
{ {
if(localCnd.canReach(remoteCnd) if (localCnd.canReach(remoteCnd)
&& remoteCnd.getTransportAddress().getPort() != 0) && remoteCnd.getTransportAddress().getPort() != 0)
{ {
// A single LocalCandidate might be/become connected // A single LocalCandidate might be/become connected
// to more more than one remote address, and that's ok // to more more than one remote address, and that's ok
// (that is, we need to form pairs with them all). // (that is, we need to form pairs with them all).
/* /*
if(localCnd.getTransport() == Transport.TCP && if (localCnd.getTransport() == Transport.TCP &&
localCnd.getIceSocketWrapper().getTCPSocket(). localCnd.getIceSocketWrapper().getTCPSocket().
isConnected()) isConnected())
{ {
if(!localCnd.getIceSocketWrapper().getTCPSocket(). if (!localCnd.getIceSocketWrapper().getTCPSocket().
getRemoteSocketAddress().equals( getRemoteSocketAddress().equals(
remoteCnd.getTransportAddress())) remoteCnd.getTransportAddress()))
{ {
@ -413,7 +433,7 @@ public class Component
Collections.sort(checkList, CandidatePair.comparator); Collections.sort(checkList, CandidatePair.comparator);
parentStream.pruneCheckList(checkList); parentStream.pruneCheckList(checkList);
if(parentStream.getCheckList().getState().equals( if (parentStream.getCheckList().getState().equals(
CheckListState.RUNNING)) CheckListState.RUNNING))
{ {
//add the updated CandidatePair list to the currently running //add the updated CandidatePair list to the currently running
@ -421,7 +441,7 @@ public class Component
CheckList streamCheckList = parentStream.getCheckList(); CheckList streamCheckList = parentStream.getCheckList();
synchronized(streamCheckList) synchronized(streamCheckList)
{ {
for(CandidatePair pair : checkList) for (CandidatePair pair : checkList)
{ {
streamCheckList.add(pair); streamCheckList.add(pair);
} }
@ -513,7 +533,7 @@ public class Component
//local candidates //local candidates
int localCandidatesCount = getLocalCandidateCount(); int localCandidatesCount = getLocalCandidateCount();
if(localCandidatesCount > 0) if (localCandidatesCount > 0)
{ {
buff.append("\n") buff.append("\n")
.append(localCandidatesCount) .append(localCandidatesCount)
@ -536,7 +556,7 @@ public class Component
//remote candidates //remote candidates
int remoteCandidatesCount = getRemoteCandidateCount(); int remoteCandidatesCount = getRemoteCandidateCount();
if(remoteCandidatesCount > 0) if (remoteCandidatesCount > 0)
{ {
buff.append("\n") buff.append("\n")
.append(remoteCandidatesCount) .append(remoteCandidatesCount)
@ -645,7 +665,7 @@ public class Component
&& (cand.getPriority() >= cand2.getPriority())) && (cand.getPriority() >= cand2.getPriority()))
{ {
localCandidates.remove(j); localCandidates.remove(j);
if(logger.isLoggable(Level.FINEST)) if (logger.isLoggable(Level.FINEST))
{ {
logger.finest( logger.finest(
"eliminating redundant cand: "+ cand2); "eliminating redundant cand: "+ cand2);
@ -817,6 +837,8 @@ public class Component
} }
} }
getParentStream().removePairStateChangeListener(this);
keepAlivePairs.clear();
getComponentSocket().close(); getComponentSocket().close();
} }
@ -885,10 +907,12 @@ public class Component
*/ */
public RemoteCandidate findRemoteCandidate(TransportAddress remoteAddress) public RemoteCandidate findRemoteCandidate(TransportAddress remoteAddress)
{ {
for(RemoteCandidate remoteCnd : remoteCandidates) for (RemoteCandidate remoteCnd : remoteCandidates)
{ {
if(remoteCnd.getTransportAddress().equals(remoteAddress)) if (remoteCnd.getTransportAddress().equals(remoteAddress))
{
return remoteCnd; return remoteCnd;
}
} }
return null; return null;
@ -902,6 +926,12 @@ public class Component
*/ */
protected void setSelectedPair(CandidatePair pair) protected void setSelectedPair(CandidatePair pair)
{ {
if (keepAliveStrategy == KeepAliveStrategy.SELECTED_ONLY)
{
keepAlivePairs.clear();
}
keepAlivePairs.add(pair);
this.selectedPair = pair; this.selectedPair = pair;
} }
@ -929,11 +959,17 @@ public class Component
public String getName() public String getName()
{ {
if (componentID == RTP) if (componentID == RTP)
{
return "RTP"; return "RTP";
else if(componentID == RTCP) }
else if (componentID == RTCP)
{
return "RTCP"; return "RTCP";
}
else else
{
return Integer.toString(componentID); return Integer.toString(componentID);
}
} }
/** /**
@ -947,7 +983,9 @@ public class Component
*/ */
public static Component build(int componentID, IceMediaStream mediaStream) 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 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.beans.*;
import java.util.*; import java.util.*;
import java.util.logging.*;
import java.util.logging.Logger; import java.util.logging.Logger;
import org.ice4j.*; import org.ice4j.*;
import org.ice4j.util.*;
/** /**
* The class represents a media stream from the ICE perspective, i.e. a * 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 * when creating the component so make sure you keep that in mind in case
* assigning a specific component ID is important to you. * 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 * @return the newly created stream <tt>Component</tt> after adding it to
* the stream first. * the stream first.
*/ */
protected Component createComponent() protected Component createComponent(KeepAliveStrategy keepAliveStrategy)
{ {
Component component; Component component;
synchronized (components) synchronized (components)
{ {
component = new Component(++lastComponentID, this); component
= new Component(++lastComponentID, this, keepAliveStrategy);
components.put(component.getComponentID(), component); 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

@ -206,7 +206,7 @@ class Connector
localSock.receive(packet); localSock.receive(packet);
//get lost if we are no longer running. //get lost if we are no longer running.
if(!running) if (!running)
return; return;
if (logger.isLoggable(Level.FINEST)){ if (logger.isLoggable(Level.FINEST)){
@ -258,15 +258,19 @@ class Connector
} }
catch (ClosedChannelException cce) catch (ClosedChannelException cce)
{ {
logger.log(Level.WARNING, // The socket was closed, possibly by the remote peer.
"A net access point has gone useless:", cce); // If we were already stopped, just ignore it.
if (running)
stop(); {
errorHandler.handleFatalError( // 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, this,
"ClosedChannelException occurred while listening" "The socket was closed:",
+ " for messages!", null);
cce); }
} }
catch (IOException ex) catch (IOException ex)
{ {

View File

@ -256,7 +256,14 @@ class NetAccessManager
//make sure nothing's left and notify user //make sure nothing's left and notify user
removeSocket(connector.getListenAddress(), removeSocket(connector.getListenAddress(),
connector.getRemoteAddress()); 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 ) else if( callingThread instanceof MessageProcessor )
{ {