Uses a Thread pool for StunClientTransaction in order to improve performance.

This commit is contained in:
lubomir.marinov 2014-02-10 07:38:55 +00:00
parent d5c2fa6c8d
commit 987512ede1
12 changed files with 919 additions and 697 deletions

View File

@ -17,9 +17,9 @@ public interface ResponseCollector
/** /**
* Dispatch the specified response. * Dispatch the specified response.
* *
* @param response the response to dispatch. * @param event the response to dispatch.
*/ */
public void processResponse(StunResponseEvent response); public void processResponse(StunResponseEvent event);
/** /**
* Notifies this collector that no response had been received after repeated * Notifies this collector that no response had been received after repeated

View File

@ -151,15 +151,20 @@ public class StackProperties
*/ */
public static String getString(String propertyName) public static String getString(String propertyName)
{ {
Object propValue = System.getProperty(propertyName); Object obj = System.getProperty(propertyName);
if (propValue == null) String str;
return null;
String propStrValue = propValue.toString().trim(); if (obj == null)
{
return (propStrValue.length() > 0) str = null;
? propStrValue }
: null; else
{
str = obj.toString().trim();
if (str.length() == 0)
str = null;
}
return str;
} }
/** /**
@ -194,41 +199,35 @@ public class StackProperties
} }
catch (NumberFormatException ex) catch (NumberFormatException ex)
{ {
logger.log(Level.FINE, propertyName logger.log(
+ " does not appear to be an integer. " + "Defaulting to " Level.FINE,
+ defaultValue + ".", ex); propertyName + " does not appear to be an integer. "
+ "Defaulting to " + defaultValue + ".",
ex);
} }
} }
return intValue; return intValue;
} }
/** /**
* Gets the value of a specific property as a boolean. If the specified * Gets the value of a specific property as a <tt>boolean</tt>. If the
* property name is associated with a value in this * specified property name is associated with a value, the string
* <code>ConfigurationService</code>, the string representation of the value * representation of the value is parsed into a <tt>boolean</tt> according
* is parsed into a boolean according to the rules of * to the rules of {@link Boolean#parseBoolean(String)} . Otherwise,
* {@link Boolean#parseBoolean(String)} . Otherwise, * <tt>defaultValue</tt> is returned.
* <code>defaultValue</code> is returned.
* *
* @param propertyName * @param propertyName the name of the property to get the value of as a
* the name of the property to get the value of as a boolean * <tt>boolean</tt>
* @param defaultValue * @param defaultValue the value to be returned if the specified property
* the value to be returned if the specified property name is not * name is not associated with a value
* associated with a value in this * @return the value of the property with the specified name as a
* <code>ConfigurationService</code> * <tt>boolean</tt>; <tt>defaultValue</tt> if the property with the
* @return the value of the property with the specified name in this * specified name is not associated with a value
* <code>ConfigurationService</code> as a boolean;
* <code>defaultValue</code> if the property with the specified name
* is not associated with a value in this
* <code>ConfigurationService</code>
*/ */
public static boolean getBoolean(String propertyName, boolean defaultValue) public static boolean getBoolean(String propertyName, boolean defaultValue)
{ {
String stringValue = getString(propertyName); String str = getString(propertyName);
return (stringValue == null) return (str == null) ? defaultValue : Boolean.parseBoolean(str);
? defaultValue
: Boolean.parseBoolean(stringValue);
} }
} }

View File

@ -41,6 +41,21 @@ import org.ice4j.stack.*;
*/ */
public class Agent public class Agent
{ {
/**
* The maximum number of retransmissions of a STUN Binding request without
* a valid STUN Binding response after which consent freshness is to be
* considered unconfirmed according to &quot;STUN Usage for Consent
* Freshness&quot;.
*/
private static final int CONSENT_FRESHNESS_MAX_RETRANSMISSIONS = 30;
/**
* The number of milliseconds without a valid STUN Binding response after
* which a STUN Binding request is to be retransmitted according to
* &quot;STUN Usage for Consent Freshness&quot;.
*/
private static final int CONSENT_FRESHNESS_WAIT_INTERVAL = 500;
/** /**
* The default maximum size for check lists. * The default maximum size for check lists.
*/ */
@ -93,7 +108,7 @@ public class Agent
/** /**
* Manages statistics about harvesting time. * Manages statistics about harvesting time.
*/ */
private HarvestStatistics harvestStats = new HarvestStatistics(); // private final HarvestStatistics harvestStats = new HarvestStatistics();
/** /**
* We use the <tt>FoundationsRegistry</tt> to keep track of the foundations * We use the <tt>FoundationsRegistry</tt> to keep track of the foundations
@ -111,7 +126,7 @@ public class Agent
/** /**
* ICE compatibility mode for this agent. * ICE compatibility mode for this agent.
*/ */
private CompatibilityMode compatibilityMode = CompatibilityMode.RFC5245; private final CompatibilityMode compatibilityMode;
/** /**
* The name of the {@link PropertyChangeEvent} that we use to deliver * The name of the {@link PropertyChangeEvent} that we use to deliver
@ -208,7 +223,7 @@ public class Agent
/** /**
* The thread that we use for STUN keep-alive. * The thread that we use for STUN keep-alive.
*/ */
private StunKeepAliveThread stunKeepAliveThread; private Thread stunKeepAliveThread;
/** /**
* Some protocols, such as XMPP, need to be able to distinguish the separate * Some protocols, such as XMPP, need to be able to distinguish the separate
@ -237,6 +252,12 @@ public class Agent
*/ */
private boolean harvestingStarted = false; private boolean harvestingStarted = false;
/**
* The indicator which determines whether this <tt>Agent</tt> is to perform
* consent freshness.
*/
private boolean performConsentFreshness = false;
/** /**
* Creates an empty <tt>Agent</tt> with no streams, and no address. * Creates an empty <tt>Agent</tt> with no streams, and no address.
*/ */
@ -266,15 +287,16 @@ public class Agent
if (StackProperties.getString(StackProperties.SOFTWARE) == null) if (StackProperties.getString(StackProperties.SOFTWARE) == null)
System.setProperty(StackProperties.SOFTWARE, "ice4j.org"); System.setProperty(StackProperties.SOFTWARE, "ice4j.org");
if(compatibilityMode == CompatibilityMode.GTALK) if (compatibilityMode == CompatibilityMode.GTALK)
{ {
/* username is 16 byte in Google Talk dialect but it is set /*
* for each candidate and not globally * The ufrag is 16 bytes in the Google Talk dialect but it is set
* per candidate, not globally.
*/ */
ufrag = null; ufrag = null;
/*
/* no password in Google Talk dialect (at least libnice does not use * There is no password in the Google Talk dialect. (At least
* one) * libnice does not use one.)
*/ */
password = ""; password = "";
} }
@ -374,12 +396,9 @@ public class Agent
* ufrag since it must be the same as username present in * ufrag since it must be the same as username present in
* HTTP response * HTTP response
*/ */
if(localCand.getUfrag() != null) if(localCand.getUfrag() == null)
{
continue;
}
localCand.setUfrag(generateGTalkUfrag()); localCand.setUfrag(generateGTalkUfrag());
} }
} }
@ -472,9 +491,10 @@ public class Agent
logger.fine("Candidate count in first harvest: " + logger.fine("Candidate count in first harvest: " +
component.getLocalCandidateCount()); component.getLocalCandidateCount());
//Emil: because of trickle we now assign foundations, compute priorities // Emil: Because of trickle, we now assign foundations, compute
//and eliminate redundancies while adding candidates on a component. // priorities, and eliminate redundancies while adding candidates on a
// This means that we no longer need to do it here, where we did before. // component. This means that we no longer need to do it here, where we
// did before.
//computeFoundations(component); //computeFoundations(component);
//component.prioritizeCandidates(); //component.prioritizeCandidates();
//component.eliminateRedundantCandidates(); //component.eliminateRedundantCandidates();
@ -513,7 +533,7 @@ public class Agent
for (IceMediaStream stream : getStreams()) for (IceMediaStream stream : getStreams())
{ {
components.addAll( stream.getComponents()); components.addAll(stream.getComponents());
} }
harvesters.harvest(components, trickleCallback); harvesters.harvest(components, trickleCallback);
@ -551,8 +571,10 @@ public class Agent
//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("Trigger checks for pairs that were received " + logger.info(
"before running state"); "Trigger checks for pairs that were received before "
+ "running state");
Iterator<CandidatePair> it = preDiscoveredPairsQueue.iterator(); Iterator<CandidatePair> it = preDiscoveredPairsQueue.iterator();
while(it.hasNext()) while(it.hasNext())
@ -747,13 +769,11 @@ public class Agent
* @param component the component whose candidate foundations we'd like to * @param component the component whose candidate foundations we'd like to
* compute and assign. * compute and assign.
*/ */
private void computeFoundations(Component component) // private void computeFoundations(Component component)
{ // {
List<LocalCandidate> candidates = component.getLocalCandidates(); // for (Candidate<?> localCandidate : component.getLocalCandidates())
// foundationsRegistry.assignFoundation(localCandidate);
for (Candidate<?> cand : candidates) // }
foundationsRegistry.assignFoundation(cand);
}
/** /**
* Adds <tt>harvester</tt> to the list of harvesters that this agent will * Adds <tt>harvester</tt> to the list of harvesters that this agent will
@ -1116,16 +1136,14 @@ public class Agent
{ {
StringBuilder buff = new StringBuilder("ICE Agent (stream-count="); StringBuilder buff = new StringBuilder("ICE Agent (stream-count=");
buff.append(getStreamCount()).append(" ice-pwd:") buff.append(getStreamCount());
.append(getLocalPassword()); buff.append(" ice-pwd:").append(getLocalPassword());
buff.append(getStreamCount()).append(" ice-ufrag:") buff.append(" ice-ufrag:").append(getLocalUfrag());
.append(getLocalUfrag()); buff.append(" tie-breaker:").append(getTieBreaker());
buff.append(getStreamCount()).append(" tie-breaker:")
.append(getTieBreaker());
buff.append("):\n"); buff.append("):\n");
for(IceMediaStream stream : getStreams()) for(IceMediaStream stream : getStreams())
buff.append(stream.toString()).append("\n"); buff.append(stream).append("\n");
return buff.toString(); return buff.toString();
} }
@ -1154,8 +1172,7 @@ 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.
List<IceMediaStream> streams = getStreams(); for(IceMediaStream stream : getStreams())
for(IceMediaStream stream : streams)
{ {
CheckList list = stream.getCheckList(); CheckList list = stream.getCheckList();
@ -1205,16 +1222,13 @@ public class Agent
*/ */
public LocalCandidate findLocalCandidate(TransportAddress localAddress) public LocalCandidate findLocalCandidate(TransportAddress localAddress)
{ {
Collection<IceMediaStream> streamsCollection = mediaStreams.values(); for(IceMediaStream stream : mediaStreams.values())
for( IceMediaStream stream : streamsCollection)
{ {
LocalCandidate cnd = stream.findLocalCandidate(localAddress); LocalCandidate cnd = stream.findLocalCandidate(localAddress);
if(cnd != null) if(cnd != null)
return cnd; return cnd;
} }
return null; return null;
} }
@ -1229,24 +1243,25 @@ public class Agent
* <tt>localAddress</tt> if it belongs to any of this {@link Agent}'s * <tt>localAddress</tt> if it belongs to any of this {@link Agent}'s
* streams or <tt>null</tt> if it doesn't. * streams or <tt>null</tt> if it doesn't.
*/ */
public LocalCandidate findLocalCandidate(TransportAddress localAddress, public LocalCandidate findLocalCandidate(
TransportAddress localAddress,
String ufrag) String ufrag)
{ {
Collection<IceMediaStream> streamsCollection = mediaStreams.values(); for(IceMediaStream stream : mediaStreams.values())
for(IceMediaStream stream : streamsCollection)
{ {
for(Component c : stream.getComponents()) for(Component c : stream.getComponents())
{ {
for(LocalCandidate cnd : c.getLocalCandidates()) for(LocalCandidate cnd : c.getLocalCandidates())
{ {
if(cnd != null && cnd.getUfrag() != null && if(cnd != null
cnd.getUfrag().equals(ufrag)) && cnd.getUfrag() != null
&& cnd.getUfrag().equals(ufrag))
{
return cnd; return cnd;
} }
} }
} }
}
return null; return null;
} }
@ -1263,16 +1278,13 @@ public class Agent
*/ */
public RemoteCandidate findRemoteCandidate(TransportAddress remoteAddress) public RemoteCandidate findRemoteCandidate(TransportAddress remoteAddress)
{ {
Collection<IceMediaStream> streamsCollection = mediaStreams.values(); for(IceMediaStream stream : mediaStreams.values())
for( IceMediaStream stream : streamsCollection)
{ {
RemoteCandidate cnd = stream.findRemoteCandidate(remoteAddress); RemoteCandidate cnd = stream.findRemoteCandidate(remoteAddress);
if(cnd != null) if(cnd != null)
return cnd; return cnd;
} }
return null; return null;
} }
@ -1295,19 +1307,15 @@ public class Agent
{ {
synchronized(mediaStreams) synchronized(mediaStreams)
{ {
Collection<IceMediaStream> streamsCollection for (IceMediaStream stream : mediaStreams.values())
= mediaStreams.values();
for (IceMediaStream stream : streamsCollection)
{ {
CandidatePair pair CandidatePair pair
= stream.findCandidatePair(localAddress, remoteAddress); = stream.findCandidatePair(localAddress, remoteAddress);
if( pair != null ) if (pair != null )
return pair; return pair;
} }
} }
return null; return null;
} }
@ -1327,19 +1335,15 @@ public class Agent
{ {
synchronized(mediaStreams) synchronized(mediaStreams)
{ {
Collection<IceMediaStream> streamsCollection for (IceMediaStream stream : mediaStreams.values())
= mediaStreams.values();
for (IceMediaStream stream : streamsCollection)
{ {
CandidatePair pair CandidatePair pair
= stream.findCandidatePair(localUFrag, remoteUFrag); = stream.findCandidatePair(localUFrag, remoteUFrag);
if( pair != null ) if (pair != null )
return pair; return pair;
} }
} }
return null; return null;
} }
@ -1755,23 +1759,22 @@ public class Agent
setState(IceProcessingState.COMPLETED); setState(IceProcessingState.COMPLETED);
// keep ICE running (answer binding request) // keep ICE running (answer STUN Binding requests, send STUN Binding
// indications or requests)
if(stunKeepAliveThread == null if(stunKeepAliveThread == null
&& ! StackProperties.getBoolean( && !StackProperties.getBoolean(
StackProperties.NO_KEEP_ALIVES, false)) StackProperties.NO_KEEP_ALIVES,
false))
{ {
// schedule STUN checks for selected candidates // schedule STUN checks for selected candidates
scheduleSTUNKeepAlive(); scheduleStunKeepAlive();
} }
if(compatibilityMode == CompatibilityMode.RFC5245) if (compatibilityMode == CompatibilityMode.RFC5245)
{
scheduleTermination(); scheduleTermination();
}
//print logs for the types of addresses we chose. //print logs for the types of addresses we chose.
logCandTypes(); logCandTypes();
} }
/** /**
@ -1977,13 +1980,24 @@ public class Agent
} }
/** /**
* Initializes and starts the {@link StunKeepAliveThread} * Initializes and starts the background <tt>Thread</tt> which is to send
* STUN keep-alives once this <tt>Agent</tt> is <tt>COMPLETED</tt>.
*/ */
private void scheduleSTUNKeepAlive() private void scheduleStunKeepAlive()
{ {
if (stunKeepAliveThread == null) if (stunKeepAliveThread == null)
{ {
stunKeepAliveThread = new StunKeepAliveThread(); stunKeepAliveThread
= new Thread()
{
@Override
public void run()
{
runInStunKeepAliveThread();
}
};
stunKeepAliveThread.setDaemon(true);
stunKeepAliveThread.setName("StunKeepAliveThread");
stunKeepAliveThread.start(); stunKeepAliveThread.start();
} }
} }
@ -2101,7 +2115,7 @@ public class Agent
shutdown = true; shutdown = true;
//stop sending keep alives (STUN Binding Indications). //stop sending keep alives (STUN Binding Indications).
if(stunKeepAliveThread != null) if (stunKeepAliveThread != null)
stunKeepAliveThread.interrupt(); stunKeepAliveThread.interrupt();
//stop responding to STUN Binding Requests. //stop responding to STUN Binding Requests.
@ -2113,26 +2127,35 @@ public class Agent
*/ */
IceProcessingState state = getState(); IceProcessingState state = getState();
if ( !IceProcessingState.FAILED.equals(state) if (!IceProcessingState.FAILED.equals(state)
&& !IceProcessingState.TERMINATED.equals(state)) && !IceProcessingState.TERMINATED.equals(state))
{ {
terminate(IceProcessingState.TERMINATED); terminate(IceProcessingState.TERMINATED);
} }
logger.info("remove streams");
// Free its IceMediaStreams, Components and Candidates. // Free its IceMediaStreams, Components and Candidates.
for(IceMediaStream stream : getStreams()) boolean interrupted = false;
logger.info("remove streams");
for (IceMediaStream stream : getStreams())
{ {
try try
{ {
removeStream(stream); removeStream(stream);
}
catch(Throwable t)
{
logger.info("remove stream failed: " + t);
}
logger.info("remove stream " + stream.getName()); logger.info("remove stream " + stream.getName());
} }
catch (Throwable t)
{
logger.info(
"remove stream " + stream.getName() + " failed: " + t);
if (t instanceof InterruptedException)
interrupted = true;
else if (t instanceof ThreadDeath)
throw (ThreadDeath) t;
}
}
if (interrupted)
Thread.currentThread().interrupt();
getStunStack().shutDown(); getStunStack().shutDown();
@ -2173,63 +2196,30 @@ public class Agent
return compatibilityMode; return compatibilityMode;
} }
/**
* Thread that performs STUN keep-alive once ICE has COMPLETED.
*/
private class StunKeepAliveThread
extends Thread
{
/**
* Creates a new termination timer.
*/
private StunKeepAliveThread()
{
super("StunKeepAliveThread");
}
/**
* Thread entry to point.
*/
@Override
public synchronized void run()
{
runInStunKeepAliveThread();
}
}
/** /**
* Schedule STUN checks for selected pair. * Schedule STUN checks for selected pair.
*/ */
public void runInStunKeepAliveThread() private void runInStunKeepAliveThread()
{ {
while(state == IceProcessingState.COMPLETED || state == while (runInStunKeepAliveThreadCondition())
IceProcessingState.TERMINATED)
{ {
if(shutdown) for(IceMediaStream stream : getStreams())
break;
List<IceMediaStream> streams = getStreams();
for(IceMediaStream stream : streams)
{ {
List<Component> cmps = stream.getComponents(); for(Component component : stream.getComponents())
for(Component cmp : cmps)
{ {
CandidatePair pair = cmp.getSelectedPair(); CandidatePair pair = component.getSelectedPair();
if(pair != null) if(pair != null)
{ {
if(compatibilityMode == CompatibilityMode.GTALK) if(performConsentFreshness
|| (compatibilityMode
== CompatibilityMode.GTALK))
{ {
//apparently GTalk insists on seeing binding connCheckClient.startCheckForPair(
//requests or else it believes we are dead pair,
//Emil: I am not sure this is true. I think it would CONSENT_FRESHNESS_WAIT_INTERVAL,
//be enough for us to respond to their binding CONSENT_FRESHNESS_WAIT_INTERVAL,
//requests. At least that's how it seems to work for CONSENT_FRESHNESS_MAX_RETRANSMISSIONS);
//Chrome and WebRTC.
//TODO: check and maybe remove
connCheckClient.startCheckForPair(pair);
} }
else if(compatibilityMode == CompatibilityMode.RFC5245) else if(compatibilityMode == CompatibilityMode.RFC5245)
{ {
@ -2239,7 +2229,7 @@ public class Agent
} }
} }
if(shutdown) if (!runInStunKeepAliveThreadCondition())
break; break;
try try
@ -2251,7 +2241,23 @@ public class Agent
{ {
} }
} }
logger.info("KeepAliveThread ends"); logger.info(Thread.currentThread().getName() + " ends.");
}
/**
* Determines whether {@link #runInStunKeepAliveThread()} is to run.
*
* @return <tt>true</tt> if <tt>runInStunKeepAliveThread()</tt> is to run;
* otherwise, <tt>false</tt>
*/
private boolean runInStunKeepAliveThreadCondition()
{
IceProcessingState state = this.state;
return
(IceProcessingState.COMPLETED.equals(state)
|| IceProcessingState.TERMINATED.equals(state))
&& !shutdown;
} }
/** /**
@ -2294,12 +2300,10 @@ public class Agent
*/ */
public LocalCandidate getSelectedLocalCandidate(String streamName) public LocalCandidate getSelectedLocalCandidate(String streamName)
{ {
CandidatePair candidatePair = this.getSelectedPair(streamName); CandidatePair candidatePair = getSelectedPair(streamName);
if(candidatePair != null)
{ return
return candidatePair.getLocalCandidate(); (candidatePair == null) ? null : candidatePair.getLocalCandidate();
}
return null;
} }
/** /**
@ -2312,12 +2316,10 @@ public class Agent
*/ */
public RemoteCandidate getSelectedRemoteCandidate(String streamName) public RemoteCandidate getSelectedRemoteCandidate(String streamName)
{ {
CandidatePair candidatePair = this.getSelectedPair(streamName); CandidatePair candidatePair = getSelectedPair(streamName);
if(candidatePair != null)
{ return
return candidatePair.getRemoteCandidate(); (candidatePair == null) ? null : candidatePair.getRemoteCandidate();
}
return null;
} }
/** /**
@ -2367,8 +2369,8 @@ public class Agent
{ {
if(harvester.getClass().getName().endsWith(harvesterName)) if(harvester.getClass().getName().endsWith(harvesterName))
{ {
harvestingTime = harvester.getHarvestStatistics() harvestingTime
.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)
@ -2423,8 +2425,8 @@ public class Agent
for(CandidateHarvester harvester : harvesters) for(CandidateHarvester harvester : harvesters)
{ {
harvestDuration += harvester harvestDuration
.getHarvestStatistics().getHarvestDuration(); += harvester.getHarvestStatistics().getHarvestDuration();
} }
return harvestDuration; return harvestDuration;
@ -2444,10 +2446,34 @@ public class Agent
for(CandidateHarvester harvester : harvesters) for(CandidateHarvester harvester : harvesters)
{ {
harvestCount += harvester harvestCount
.getHarvestStatistics().getHarvestDuration(); += harvester.getHarvestStatistics().getHarvestDuration();
} }
return harvestCount; return harvestCount;
} }
/**
* Gets the indicator which determines whether this <tt>Agent</tt> is to
* perform consent freshness.
*
* @return <tt>true</tt> if this <tt>Agent</tt> is to perform consent
* freshness; otherwise, <tt>false</tt>
*/
public boolean getPerformConsentFreshness()
{
return performConsentFreshness;
}
/**
* Sets the indicator which determines whether this <tt>Agent</tt> is to
* perform consent freshness.
*
* @param performConsentFreshness <tt>true</tt> if this <tt>Agent</tt> is to
* perform consent freshness; otherwise, <tt>false</tt>
*/
public void setPerformConsentFreshness(boolean performConsentFreshness)
{
this.performConsentFreshness = performConsentFreshness;
}
} }

View File

@ -20,10 +20,18 @@ import org.ice4j.stack.*;
* sending a STUN request from the local candidate to the remote candidate. * sending a STUN request from the local candidate to the remote candidate.
* *
* @author Emil Ivov * @author Emil Ivov
* @author Lyubomir Marinov
*/ */
public class CandidatePair public class CandidatePair
implements Comparable<CandidatePair> implements Comparable<CandidatePair>
{ {
/**
* The value of the <tt>consentFreshness</tt> property of
* <tt>CandidatePair</tt> which indicates that the time in milliseconds of
* the latest consent freshness confirmation is unknown.
*/
public static final long CONSENT_FRESHNESS_UNKNOWN = -1;
/** /**
* The value of <tt>Math.pow(2, 32)</tt> calculated once for the purposes of * The value of <tt>Math.pow(2, 32)</tt> calculated once for the purposes of
* optimizing performance. * optimizing performance.
@ -94,6 +102,11 @@ public class CandidatePair
*/ */
private TransactionID connCheckTranID = null; private TransactionID connCheckTranID = null;
/**
* The time in milliseconds of the latest consent freshness confirmation.
*/
private long consentFreshness = CONSENT_FRESHNESS_UNKNOWN;
/** /**
* Creates a <tt>CandidatePair</tt> instance mapping <tt>localCandidate</tt> * Creates a <tt>CandidatePair</tt> instance mapping <tt>localCandidate</tt>
* to <tt>remoteCandidate</tt>. * to <tt>remoteCandidate</tt>.
@ -264,25 +277,32 @@ public class CandidatePair
this.state = newState; this.state = newState;
if(newState != CandidatePairState.IN_PROGRESS) if(newState == CandidatePairState.IN_PROGRESS)
{
if (tranID == null)
{ {
if (tranID != null)
throw new IllegalArgumentException( throw new IllegalArgumentException(
"How could you have a transaction for a pair" "Putting a pair into the In-Progress state MUST be"
+ " that's not in the In-Progress state?"); + " accomapnied with the TransactionID of the"
+ " connectivity check.");
}
} }
else else
{ {
if (tranID == null) if (tranID != null)
throw new IllegalArgumentException("Putting a pair into the " {
+"In-Progress state MUST be accomapnied with " throw new IllegalArgumentException(
+"the TransactionID of the conn check."); "How could you have a transaction for a pair that's not"
+ " in the In-Progress state?");
}
} }
this.connCheckTranID = tranID; this.connCheckTranID = tranID;
getParentComponent().getParentStream().firePairPropertyChange( getParentComponent().getParentStream().firePairPropertyChange(
this, IceMediaStream.PROPERTY_PAIR_STATE_CHANGED, this,
oldState, newState); IceMediaStream.PROPERTY_PAIR_STATE_CHANGED,
oldState,
newState);
} }
/** /**
@ -395,39 +415,32 @@ public class CandidatePair
long thisPri = getPriority(); long thisPri = getPriority();
long otherPri = candidatePair.getPriority(); long otherPri = candidatePair.getPriority();
return (thisPri < otherPri return (thisPri < otherPri) ? 1 : (thisPri == otherPri) ? 0 : -1;
? 1
: (thisPri==otherPri
? 0
: -1));
} }
/** /**
* Compares this <tt>CandidatePair</tt> to <tt>targetPair</tt> and returns * Compares this <tt>CandidatePair</tt> to <tt>obj</tt> and returns
* <tt>true</tt> if pairs have equal local and equal remote candidates and * <tt>true</tt> if pairs have equal local and equal remote candidates and
* <tt>false</tt> otherwise. * <tt>false</tt> otherwise.
* *
* @param targetPair the <tt>Object</tt> that we'd like to compare this * @param obj the <tt>Object</tt> that we'd like to compare this pair to.
* target pair to.
*
* @return <tt>true</tt> if pairs have equal local and equal remote * @return <tt>true</tt> if pairs have equal local and equal remote
* candidates and <tt>false</tt> otherwise. * candidates and <tt>false</tt> otherwise.
*/ */
public boolean equals(Object targetPair) @Override
public boolean equals(Object obj)
{ {
if (! (targetPair instanceof CandidatePair) if ((obj == null) || !(obj instanceof CandidatePair))
|| targetPair == null
|| !localCandidate.equals(((CandidatePair)targetPair)
.localCandidate)
|| !remoteCandidate.equals(((CandidatePair)targetPair)
.remoteCandidate))
return false; return false;
CandidatePair candidatePair = (CandidatePair) obj;
//DO NOT change this method to also depend on other pair properties //DO NOT change this method to also depend on other pair properties
//because the Conn Check Client counts on it only using the candidates //because the Conn Check Client counts on it only using the candidates
//for comparisons. //for comparisons.
return
return true; localCandidate.equals(candidatePair.localCandidate)
&& remoteCandidate.equals(candidatePair.remoteCandidate);
} }
/** /**
@ -435,10 +448,11 @@ public class CandidatePair
* *
* @return a String representation of the object. * @return a String representation of the object.
*/ */
@Override
public String toString() public String toString()
{ {
return "CandidatePair (State=" + getState() return
+ " Priority=" + getPriority() "CandidatePair (State=" + getState() + " Priority=" + getPriority()
+ "):\n\tLocalCandidate=" + getLocalCandidate() + "):\n\tLocalCandidate=" + getLocalCandidate()
+ "\n\tRemoteCandidate=" + getRemoteCandidate(); + "\n\tRemoteCandidate=" + getRemoteCandidate();
} }
@ -504,6 +518,7 @@ public class CandidatePair
* @see java.lang.Object#equals(java.lang.Object) * @see java.lang.Object#equals(java.lang.Object)
* @see java.lang.Object#hashCode() * @see java.lang.Object#hashCode()
*/ */
@Override
public boolean equals(Object obj) public boolean equals(Object obj)
{ {
return obj instanceof PairComparator; return obj instanceof PairComparator;
@ -584,8 +599,11 @@ public class CandidatePair
public void nominate() public void nominate()
{ {
this.isNominated = true; this.isNominated = true;
getParentComponent().getParentStream().firePairPropertyChange(this, getParentComponent().getParentStream().firePairPropertyChange(
IceMediaStream.PROPERTY_PAIR_NOMINATED, false, true); this,
IceMediaStream.PROPERTY_PAIR_NOMINATED,
false,
true);
} }
/** /**
@ -619,7 +637,56 @@ public class CandidatePair
protected void validate() protected void validate()
{ {
this.isValid = true; this.isValid = true;
getParentComponent().getParentStream().firePairPropertyChange(this, getParentComponent().getParentStream().firePairPropertyChange(
IceMediaStream.PROPERTY_PAIR_VALIDATED, false, true); this,
IceMediaStream.PROPERTY_PAIR_VALIDATED,
false,
true);
}
/**
* Gets the time in milliseconds of the latest consent freshness
* confirmation.
*
* @return the time in milliseconds of the latest consent freshness
* confirmation
*/
public long getConsentFreshness()
{
return consentFreshness;
}
/**
* Sets the time in milliseconds of the latest consent freshness
* confirmation to now.
*/
void setConsentFreshness()
{
setConsentFreshness(System.currentTimeMillis());
}
/**
* Sets the time in milliseconds of the latest consent freshness
* confirmation to a specific time.
*
* @param consentFreshness the time in milliseconds of the latest consent
* freshness to be set on this <tt>CandidatePair</tt>
*/
void setConsentFreshness(long consentFreshness)
{
if (this.consentFreshness != consentFreshness)
{
long oldValue = this.consentFreshness;
this.consentFreshness = consentFreshness;
long newValue = this.consentFreshness;
getParentComponent().getParentStream().firePairPropertyChange(
this,
IceMediaStream.PROPERTY_PAIR_CONSENT_FRESHNESS_CHANGED,
oldValue,
newValue);
}
} }
} }

View File

@ -111,26 +111,17 @@ class ConnectivityCheckClient
* @param candidatePair that {@link CandidatePair} that we'd like to send * @param candidatePair that {@link CandidatePair} that we'd like to send
* an indication * an indication
*/ */
protected void sendBindingIndicationForPair( protected void sendBindingIndicationForPair(CandidatePair candidatePair)
CandidatePair candidatePair)
{ {
LocalCandidate localCandidate = candidatePair.getLocalCandidate(); LocalCandidate localCandidate = candidatePair.getLocalCandidate();
Indication indication = MessageFactory.createBindingIndication(); Indication indication = MessageFactory.createBindingIndication();
TransactionID tran = TransactionID.createNewTransactionID();
tran.setApplicationData(candidatePair);
try try
{ {
TransportAddress localAddr = localCandidate.getBase().
getTransportAddress();
stunStack.sendIndication( stunStack.sendIndication(
indication, indication,
candidatePair candidatePair.getRemoteCandidate().getTransportAddress(),
.getRemoteCandidate().getTransportAddress(), localCandidate.getBase().getTransportAddress());
localAddr);
if(logger.isLoggable(Level.FINEST)) if(logger.isLoggable(Level.FINEST))
{ {
logger.finest( logger.finest(
@ -140,14 +131,15 @@ class ConnectivityCheckClient
catch (Exception ex) catch (Exception ex)
{ {
IceSocketWrapper stunSocket = localCandidate.getStunSocket(null); IceSocketWrapper stunSocket = localCandidate.getStunSocket(null);
if(stunSocket != null) if(stunSocket != null)
{
logger.log( logger.log(
Level.INFO, Level.INFO,
"Failed to send " + indication "Failed to send " + indication + " through "
+ " through " + stunSocket.getLocalSocketAddress(), + stunSocket.getLocalSocketAddress(),
ex); ex);
stunSocket = null; }
tran = null;
} }
} }
@ -165,6 +157,30 @@ class ConnectivityCheckClient
* failed for some reason. * failed for some reason.
*/ */
protected TransactionID startCheckForPair(CandidatePair candidatePair) protected TransactionID startCheckForPair(CandidatePair candidatePair)
{
return startCheckForPair(candidatePair, -1, -1, -1);
}
/**
* Creates a STUN {@link Request} containing the necessary PRIORITY and
* CONTROLLING/CONTROLLED attributes. Also stores a reference to
* <tt>candidatePair</tt> in the newly created transactionID so that we
* could then refer back to it in subsequent response or failure events.
*
* @param candidatePair that {@link CandidatePair} that we'd like to start
* a check for.
* @param originalWiatIterval
* @param maxWaitInterval
* @param maxRetransmissions
* @return a reference to the {@link TransactionID} used in the connectivity
* check client transaction or <tt>null</tt> if sending the check has
* failed for some reason.
*/
protected TransactionID startCheckForPair(
CandidatePair candidatePair,
int originalWiatIterval,
int maxWaitInterval,
int maxRetransmissions)
{ {
LocalCandidate localCandidate = candidatePair.getLocalCandidate(); LocalCandidate localCandidate = candidatePair.getLocalCandidate();
//we don't need to do a canReach() verification here as it has been //we don't need to do a canReach() verification here as it has been
@ -175,34 +191,32 @@ class ConnectivityCheckClient
if(parentAgent.getCompatibilityMode() == CompatibilityMode.GTALK) if(parentAgent.getCompatibilityMode() == CompatibilityMode.GTALK)
{ {
/* Google Talk ICE dialect just need the username */ /* Google Talk ICE dialect just need the username */
String localUserName = parentAgent.generateLocalUserName( String localUserName
= parentAgent.generateLocalUserName(
candidatePair.getRemoteCandidate(), candidatePair.getRemoteCandidate(),
candidatePair.getLocalCandidate()); candidatePair.getLocalCandidate());
UsernameAttribute unameAttr
UsernameAttribute unameAttr = = AttributeFactory.createUsernameAttribute(localUserName);
AttributeFactory.createUsernameAttribute(localUserName);
request.addAttribute(unameAttr); request.addAttribute(unameAttr);
if (parentAgent.isControlling())
{
//if we are the controlling agent then we need to indicate our //if we are the controlling agent then we need to indicate our
//nominated pairs. //nominated pairs.
if(candidatePair.isNominated()) if (parentAgent.isControlling() && candidatePair.isNominated())
{ {
logger.fine("set useCandidateSent for " + logger.fine(
candidatePair.toShortString()); "set useCandidateSent for "
+ candidatePair.toShortString());
candidatePair.setUseCandidateSent(); candidatePair.setUseCandidateSent();
} }
} }
}
else else
{ {
//the priority we'd like the remote party to use for a peer //the priority we'd like the remote party to use for a peer
//reflexive candidate if one is discovered as a consequence of this //reflexive candidate if one is discovered as a consequence of this
//check. //check.
PriorityAttribute priority = PriorityAttribute priority
AttributeFactory.createPriorityAttribute( = AttributeFactory.createPriorityAttribute(
localCandidate.computePriorityForType( localCandidate.computePriorityForType(
CandidateType.PEER_REFLEXIVE_CANDIDATE)); CandidateType.PEER_REFLEXIVE_CANDIDATE));
@ -211,102 +225,102 @@ class ConnectivityCheckClient
//controlling controlled //controlling controlled
if (parentAgent.isControlling()) if (parentAgent.isControlling())
{ {
request.addAttribute(AttributeFactory request.addAttribute(
.createIceControllingAttribute(parentAgent AttributeFactory.createIceControllingAttribute(
.getTieBreaker())); parentAgent.getTieBreaker()));
//if we are the controlling agent then we need to indicate our //if we are the controlling agent then we need to indicate our
//nominated pairs. //nominated pairs.
if(candidatePair.isNominated()) if(candidatePair.isNominated())
{ {
logger.fine("Add USE-CANDIDATE in check for: " + logger.fine(
candidatePair.toShortString()); "Add USE-CANDIDATE in check for: "
request.addAttribute(AttributeFactory + candidatePair.toShortString());
.createUseCandidateAttribute()); request.addAttribute(
AttributeFactory.createUseCandidateAttribute());
} }
} }
else else
{ {
request.addAttribute(AttributeFactory request.addAttribute(
.createIceControlledAttribute(parentAgent AttributeFactory.createIceControlledAttribute(
.getTieBreaker())); parentAgent.getTieBreaker()));
} }
//credentials //credentials
String localUserName = parentAgent.generateLocalUserName( String media
candidatePair.getParentComponent().getParentStream(). = candidatePair
getName()); .getParentComponent().getParentStream().getName();
String localUserName = parentAgent.generateLocalUserName(media);
if(localUserName == null) if(localUserName == null)
return null; return null;
UsernameAttribute unameAttr = UsernameAttribute unameAttr
AttributeFactory.createUsernameAttribute(localUserName); = AttributeFactory.createUsernameAttribute(localUserName);
request.addAttribute(unameAttr); request.addAttribute(unameAttr);
// TODO Also implement SASL prepare // TODO Also implement SASL prepare
MessageIntegrityAttribute msgIntegrity = AttributeFactory MessageIntegrityAttribute msgIntegrity
.createMessageIntegrityAttribute(localUserName); = AttributeFactory.createMessageIntegrityAttribute(
localUserName);
// when we will encode the MESSAGE-INTEGRITY attribute (thus // when we will encode the MESSAGE-INTEGRITY attribute (thus
// generate the HMAC-SHA1 authentication), we need to know the // generate the HMAC-SHA1 authentication), we need to know the
// remote key of the current stream, that why we pass the media // remote key of the current stream, that why we pass the media
// name. // name.
msgIntegrity.setMedia( msgIntegrity.setMedia(media);
candidatePair.getParentComponent().getParentStream().
getName());
request.addAttribute(msgIntegrity); request.addAttribute(msgIntegrity);
} }
TransactionID tran = TransactionID.createNewTransactionID(); TransactionID tran = TransactionID.createNewTransactionID();
tran.setApplicationData(candidatePair); tran.setApplicationData(candidatePair);
logger.fine("start check for " + candidatePair.toShortString() logger.fine(
+ " tid " + tran); "start check for " + candidatePair.toShortString() + " tid "
+ tran);
try try
{ {
TransportAddress localAddr = localCandidate.getBase().
getTransportAddress();
tran tran
= stunStack.sendRequest( = stunStack.sendRequest(
request, request,
candidatePair candidatePair
.getRemoteCandidate().getTransportAddress(), .getRemoteCandidate().getTransportAddress(),
localAddr, localCandidate.getBase().getTransportAddress(),
this, this,
tran); tran,
originalWiatIterval,
maxWaitInterval,
maxRetransmissions);
if(logger.isLoggable(Level.FINEST)) if(logger.isLoggable(Level.FINEST))
{ {
logger.finest( logger.finest(
"checking pair " + candidatePair "checking pair " + candidatePair + " tid " + tran);
+ " with tran=" + tran);
} }
} }
catch (Exception ex) catch (Exception ex)
{ {
tran = null;
IceSocketWrapper stunSocket = localCandidate.getStunSocket(null); IceSocketWrapper stunSocket = localCandidate.getStunSocket(null);
if(stunSocket != null) if(stunSocket != null)
{ {
String msg = "Failed to send " + request String msg
+ " through " + stunSocket.getLocalSocketAddress(); = "Failed to send " + request + " through "
+ stunSocket.getLocalSocketAddress() + ".";
if((ex instanceof NoRouteToHostException) || if((ex instanceof NoRouteToHostException)
(ex.getMessage() != null && || (ex.getMessage() != null
ex.getMessage().equals("No route to host"))) && ex.getMessage().equals("No route to host")))
{ {
msg += " No route to host"; msg += " No route to host.";
ex = null; ex = null;
} }
logger.log(Level.INFO, msg, ex); logger.log(Level.INFO, msg, ex);
} }
stunSocket = null;
tran = null;
} }
return tran; return tran;
@ -318,17 +332,17 @@ class ConnectivityCheckClient
* to FAILED, or SUCCEDED, or rescheduling a check in case of a role * to FAILED, or SUCCEDED, or rescheduling a check in case of a role
* conflict. * conflict.
* *
* @param evt the {@link StunResponseEvent} that contains the newly * @param ev the {@link StunResponseEvent} that contains the newly received
* received response. * response.
*/ */
public void processResponse(StunResponseEvent evt) public void processResponse(StunResponseEvent ev)
{ {
CandidatePair checkedPair CandidatePair checkedPair
= (CandidatePair) evt.getTransactionID().getApplicationData(); = (CandidatePair) ev.getTransactionID().getApplicationData();
//make sure that the response came from the right place. //make sure that the response came from the right place.
if (parentAgent.getCompatibilityMode() == CompatibilityMode.RFC5245 && if (parentAgent.getCompatibilityMode() == CompatibilityMode.RFC5245
!checkSymmetricAddresses(evt)) && !checkSymmetricAddresses(ev))
{ {
logger.fine("Received a non-symmetric response for pair: " logger.fine("Received a non-symmetric response for pair: "
+ checkedPair.toShortString() + ". Failing"); + checkedPair.toShortString() + ". Failing");
@ -336,23 +350,27 @@ class ConnectivityCheckClient
+ checkedPair.toShortString() + ", failing"); + checkedPair.toShortString() + ", failing");
checkedPair.setStateFailed(); checkedPair.setStateFailed();
} }
//handle error responses. else
else if(evt.getResponse().getMessageType()
== Response.BINDING_ERROR_RESPONSE)
{ {
if(! evt.getResponse().containsAttribute(Attribute.ERROR_CODE)) Response response = ev.getResponse();
char messageType = response.getMessageType();
//handle error responses.
if(messageType== Response.BINDING_ERROR_RESPONSE)
{
if(!response.containsAttribute(Attribute.ERROR_CODE))
{ {
logger.fine("Received a malformed error response."); logger.fine("Received a malformed error response.");
return; //malformed error response return; //malformed error response
} }
processErrorResponse(evt); processErrorResponse(ev);
} }
//handle success responses. //handle success responses.
else if(evt.getResponse().getMessageType() else if(messageType == Response.BINDING_SUCCESS_RESPONSE)
== Response.BINDING_SUCCESS_RESPONSE)
{ {
processSuccessResponse(evt); processSuccessResponse(ev);
}
} }
//Regardless of whether the check was successful or failed, the //Regardless of whether the check was successful or failed, the
@ -441,18 +459,18 @@ class ConnectivityCheckClient
/** /**
* Handles STUN success responses as per the rules in RFC 5245. * Handles STUN success responses as per the rules in RFC 5245.
* *
* @param evt the event that delivered the error response. * @param ev the event that delivered the error response.
*/ */
private void processSuccessResponse(StunResponseEvent evt) private void processSuccessResponse(StunResponseEvent ev)
{ {
Response response = evt.getResponse(); Response response = ev.getResponse();
Request request = evt.getRequest(); Request request = ev.getRequest();
CandidatePair checkedPair CandidatePair checkedPair
= (CandidatePair) evt.getTransactionID().getApplicationData(); = (CandidatePair) ev.getTransactionID().getApplicationData();
TransportAddress mappedAddress = null; TransportAddress mappedAddress = null;
if(this.parentAgent.getCompatibilityMode() == CompatibilityMode.GTALK) if(parentAgent.getCompatibilityMode() == CompatibilityMode.GTALK)
{ {
if(response.containsAttribute(Attribute.XOR_MAPPED_ADDRESS)) if(response.containsAttribute(Attribute.XOR_MAPPED_ADDRESS))
{ {
@ -504,7 +522,8 @@ class ConnectivityCheckClient
// XXX AddressAttribute always returns UDP based TransportAddress // XXX AddressAttribute always returns UDP based TransportAddress
if(checkedPair.getLocalCandidate().getTransport() == Transport.TCP) if(checkedPair.getLocalCandidate().getTransport() == Transport.TCP)
{ {
mappedAddress = new TransportAddress( mappedAddress
= new TransportAddress(
mappedAddress.getAddress(), mappedAddress.getAddress(),
mappedAddress.getPort(), mappedAddress.getPort(),
Transport.TCP); Transport.TCP);
@ -560,8 +579,10 @@ class ConnectivityCheckClient
priority = prioAttr.getPriority(); priority = prioAttr.getPriority();
} }
LocalCandidate peerReflexiveCandidate = new PeerReflexiveCandidate( LocalCandidate peerReflexiveCandidate
mappedAddress, checkedPair.getParentComponent(), = new PeerReflexiveCandidate(
mappedAddress,
checkedPair.getParentComponent(),
checkedPair.getLocalCandidate(), checkedPair.getLocalCandidate(),
priority); priority);
@ -590,7 +611,8 @@ class ConnectivityCheckClient
} }
//check if the resulting valid pair was already in our check lists. //check if the resulting valid pair was already in our check lists.
CandidatePair existingPair = parentAgent.findCandidatePair( CandidatePair existingPair
= parentAgent.findCandidatePair(
validLocalCandidate.getTransportAddress(), validLocalCandidate.getTransportAddress(),
validRemoteCandidate.getTransportAddress()); validRemoteCandidate.getTransportAddress());
@ -599,26 +621,19 @@ class ConnectivityCheckClient
// remote candidate equals the destination address to which the request // remote candidate equals the destination address to which the request
// was sent. This is called a valid pair, since it has been validated // was sent. This is called a valid pair, since it has been validated
// by a STUN connectivity check. // by a STUN connectivity check.
CandidatePair validPair; CandidatePair validPair
if(existingPair != null) = (existingPair == null)
{ ? new CandidatePair(validLocalCandidate, validRemoteCandidate)
validPair = existingPair; : existingPair;
}
else
{
validPair = new CandidatePair(validLocalCandidate,
validRemoteCandidate);
}
// we synchronize here because the same pair object can be // we synchronize here because the same pair object can be processed (in
// processed (in another thread) in Agent's triggerCheck. // another thread) in Agent's triggerCheck. A controlled agent select
// A controlled agent select its pair here if the pair has // its pair here if the pair has useCandidateReceived as true (set in
// useCandidateReceived as true (set in triggerCheck) or in t // triggerCheck) or in triggerCheck if the pair state is succeeded (set
// triggerCheck if the pair state is succeeded (set here). So be // here). So be sure that if a binding response and a binding request
// sure that if a binding response and a binding request (for // (for the same check) from other peer come at the very same time, that
// the same check) from other peer come at the very same time, // we will trigger the nominationConfirmed (that will pass the pair as
// that we will trigger the nominationConfirmed (that will // as selected if it is the first time).
// pass the pair as selected if it is the first time).
synchronized(checkedPair) synchronized(checkedPair)
{ {
//The agent sets the state of the pair that *generated* the check to //The agent sets the state of the pair that *generated* the check to
@ -647,15 +662,16 @@ class ConnectivityCheckClient
= new Vector<CandidatePair>(parentStream.getCheckList()); = new Vector<CandidatePair>(parentStream.getCheckList());
for(CandidatePair pair : parentCheckList) for(CandidatePair pair : parentCheckList)
if ((pair.getState() == CandidatePairState.FROZEN) && if ((pair.getState() == CandidatePairState.FROZEN)
(checkedPair.getFoundation().equals(pair.getFoundation()))) && checkedPair.getFoundation().equals(
pair.getFoundation()))
pair.setStateWaiting(); pair.setStateWaiting();
} }
// The agent examines the check list for all other streams in turn // The agent examines the check list for all other streams in turn. If
// If the check list is active, the agent changes the state of // the check list is active, the agent changes the state of all Frozen
// all Frozen pairs in that check list whose foundation matches a // pairs in that check list whose foundation matches a pair in the valid
// pair in the valid list under consideration to Waiting. // list under consideration to Waiting.
List<IceMediaStream> allOtherStreams = parentAgent.getStreams(); List<IceMediaStream> allOtherStreams = parentAgent.getStreams();
allOtherStreams.remove(parentStream); allOtherStreams.remove(parentStream);
@ -705,22 +721,22 @@ class ConnectivityCheckClient
//CANDIDATE attribute in the Binding request, the valid pair generated //CANDIDATE attribute in the Binding request, the valid pair generated
//from that check has its nominated flag set to true. //from that check has its nominated flag set to true.
if((parentAgent.isControlling() if((parentAgent.isControlling()
&& request.containsAttribute(Attribute.USE_CANDIDATE)) || && request.containsAttribute(Attribute.USE_CANDIDATE))
((parentAgent.getCompatibilityMode() == || ((parentAgent.getCompatibilityMode()
CompatibilityMode.GTALK) && == CompatibilityMode.GTALK)
validPair.isNominated())) && validPair.isNominated()))
//checkedPair.useCandidateSent()))
{ {
if(validPair.getParentComponent().getSelectedPair() == null) if(validPair.getParentComponent().getSelectedPair() == null)
{ {
logger.info("Nomination confirmed for pair: " + logger.info(
validPair.toShortString()); "Nomination confirmed for pair: "
+ validPair.toShortString());
parentAgent.nominationConfirmed( validPair ); parentAgent.nominationConfirmed( validPair );
} }
else else
{ {
logger.fine("Keep alive for pair: " + logger.fine(
validPair.toShortString()); "Keep alive for pair: " + validPair.toShortString());
} }
} }
//If the agent is the controlled agent, the response may be the result //If the agent is the controlled agent, the response may be the result
@ -728,22 +744,27 @@ class ConnectivityCheckClient
//itself had the USE-CANDIDATE attribute. This case is described in //itself had the USE-CANDIDATE attribute. This case is described in
//Section 7.2.1.5, and may now result in setting the nominated flag for //Section 7.2.1.5, and may now result in setting the nominated flag for
//the pair learned from the original request. //the pair learned from the original request.
else if(!parentAgent.isControlling() && else if(!parentAgent.isControlling()
checkedPair.useCandidateReceived() && && checkedPair.useCandidateReceived()
!checkedPair.isNominated()) && !checkedPair.isNominated())
{ {
if(checkedPair.getParentComponent().getSelectedPair() == null) if(checkedPair.getParentComponent().getSelectedPair() == null)
{ {
logger.info("Nomination confirmed for pair: " + logger.info(
validPair.toShortString()); "Nomination confirmed for pair: "
+ validPair.toShortString());
parentAgent.nominationConfirmed( checkedPair ); parentAgent.nominationConfirmed( checkedPair );
} }
else else
{ {
logger.fine("Keep alive for pair: " + logger.fine(
validPair.toShortString()); "Keep alive for pair: " + validPair.toShortString());
} }
} }
// Selected pairs get their consent freshness confirmed.
if (checkedPair == checkedPair.getParentComponent().getSelectedPair())
checkedPair.setConsentFreshness();
} }
/** /**
@ -768,16 +789,15 @@ class ConnectivityCheckClient
*/ */
private boolean checkSymmetricAddresses(StunResponseEvent evt) private boolean checkSymmetricAddresses(StunResponseEvent evt)
{ {
CandidatePair pair = ((CandidatePair)evt.getTransactionID() CandidatePair pair
.getApplicationData()); = ((CandidatePair) evt.getTransactionID().getApplicationData());
TransportAddress localAddr = pair.getLocalCandidate().getBase(). TransportAddress localAddr
getTransportAddress(); = pair.getLocalCandidate().getBase().getTransportAddress();
boolean sym = localAddr.equals(evt.getLocalAddress()) return
&& pair.getRemoteCandidate().getTransportAddress() localAddr.equals(evt.getLocalAddress())
.equals(evt.getRemoteAddress()); && pair.getRemoteCandidate().getTransportAddress().equals(
evt.getRemoteAddress());
return sym;
} }
/** /**
@ -785,15 +805,15 @@ class ConnectivityCheckClient
* reschedules the check, in all other cases sets the corresponding peer * reschedules the check, in all other cases sets the corresponding peer
* state to FAILED. * state to FAILED.
* *
* @param evt the event that delivered the error response. * @param ev the event that delivered the error response.
*/ */
private void processErrorResponse(StunResponseEvent evt) private void processErrorResponse(StunResponseEvent ev)
{ {
Response response = evt.getResponse(); Response response = ev.getResponse();
Request originalRequest = evt.getRequest(); Request originalRequest = ev.getRequest();
ErrorCodeAttribute errorAttr = (ErrorCodeAttribute)response. ErrorCodeAttribute errorAttr
getAttribute(Attribute.ERROR_CODE); = (ErrorCodeAttribute) response.getAttribute(Attribute.ERROR_CODE);
// GTalk error code is not RFC3489/RFC5389 compliant // GTalk error code is not RFC3489/RFC5389 compliant
// example: 400 becomes 0x01 0x90 with GTalk // example: 400 becomes 0x01 0x90 with GTalk
// RFC3489/RFC5389 gives 0x04 0x00 // RFC3489/RFC5389 gives 0x04 0x00
@ -801,16 +821,16 @@ class ConnectivityCheckClient
int co = errorAttr.getErrorNumber() & 0xff; int co = errorAttr.getErrorNumber() & 0xff;
char errorCode = errorAttr.getErrorCode(); char errorCode = errorAttr.getErrorCode();
CandidatePair pair = ((CandidatePair)evt.getTransactionID() CandidatePair pair
.getApplicationData()); = (CandidatePair) ev.getTransactionID().getApplicationData();
logger.finer("Received error code " + ((int) errorCode)); logger.finer("Received error code " + ((int) errorCode));
//RESOLVE ROLE_CONFLICTS //RESOLVE ROLE_CONFLICTS
if(errorCode == ErrorCodeAttribute.ROLE_CONFLICT) if(errorCode == ErrorCodeAttribute.ROLE_CONFLICT)
{ {
boolean wasControlling = originalRequest boolean wasControlling
.containsAttribute(Attribute.ICE_CONTROLLING); = originalRequest.containsAttribute(Attribute.ICE_CONTROLLING);
logger.finer("Swithing to isControlling=" + !wasControlling); logger.finer("Swithing to isControlling=" + !wasControlling);
parentAgent.setControlling(!wasControlling); parentAgent.setControlling(!wasControlling);
@ -818,8 +838,9 @@ class ConnectivityCheckClient
pair.getParentComponent().getParentStream().getCheckList() pair.getParentComponent().getParentStream().getCheckList()
.scheduleTriggeredCheck(pair); .scheduleTriggeredCheck(pair);
} }
else if(parentAgent.getCompatibilityMode() == CompatibilityMode.GTALK && else if(parentAgent.getCompatibilityMode() == CompatibilityMode.GTALK
cl == 1 && co == 0xae) // STALE_CREDENTIALS (430) && cl == 1
&& co == 0xae) // STALE_CREDENTIALS (430)
{ {
// it may be an error due to remote peer that does not processed // it may be an error due to remote peer that does not processed
// our candidates IQ and we start connectivity checks too quickly // our candidates IQ and we start connectivity checks too quickly
@ -853,13 +874,14 @@ class ConnectivityCheckClient
* {@link CandidatePairState#FAILED} and updates check list and timer * {@link CandidatePairState#FAILED} and updates check list and timer
* states. * states.
* *
* @param event the {@link StunTimeoutEvent} containing the original * @param ev the {@link StunTimeoutEvent} containing the original
* transaction and hence {@link CandidatePair} that's being checked. * transaction and hence {@link CandidatePair} that's being checked.
*/ */
public void processTimeout(StunTimeoutEvent event) public void processTimeout(StunTimeoutEvent ev)
{ {
CandidatePair pair = ((CandidatePair)event.getTransactionID() CandidatePair pair
.getApplicationData()); = (CandidatePair) ev.getTransactionID() .getApplicationData();
logger.info("timeout for pair: " + pair.toShortString() + ", failing."); logger.info("timeout for pair: " + pair.toShortString() + ", failing.");
pair.setStateFailed(); pair.setStateFailed();
updateCheckListAndTimerStates(pair); updateCheckListAndTimerStates(pair);
@ -983,8 +1005,9 @@ class ConnectivityCheckClient
if(transactionID == null) if(transactionID == null)
{ {
logger.info("Pair failed: " + logger.info(
pairToCheck.toShortString()); "Pair failed: "
+ pairToCheck.toShortString());
pairToCheck.setStateFailed(); pairToCheck.setStateFailed();
} }
else else
@ -1017,7 +1040,7 @@ class ConnectivityCheckClient
} }
/** /**
* Stops and removes all PaceMakers. * Stops and removes all <tt>PaceMaker</tt>s.
*/ */
public void stop() public void stop()
{ {

View File

@ -21,8 +21,8 @@ public class DefaultNominator
/** /**
* The logger. * The logger.
*/ */
private static Logger logger = private static final Logger logger
Logger.getLogger(DefaultNominator.class.getName()); = Logger.getLogger(DefaultNominator.class.getName());
/** /**
* The Agent that created us. * The Agent that created us.
@ -39,8 +39,8 @@ public class DefaultNominator
* Map that will remember association between validated relayed candidate * Map that will remember association between validated relayed candidate
* and a timer. It is use with the NOMINATE_FIRST_HIGHEST_VALID strategy. * and a timer. It is use with the NOMINATE_FIRST_HIGHEST_VALID strategy.
*/ */
private Map<String, TimerTask> validatedCandidates = private final Map<String, TimerTask> validatedCandidates
new HashMap<String, TimerTask>(); = new HashMap<String, TimerTask>();
/** /**
* Creates a new instance of this nominator using <tt>parentAgent</tt> as * Creates a new instance of this nominator using <tt>parentAgent</tt> as
@ -59,21 +59,19 @@ public class DefaultNominator
* Tracks changes of state in {@link IceMediaStream}s and {@link * Tracks changes of state in {@link IceMediaStream}s and {@link
* CheckList}s. * CheckList}s.
* *
* @param evt the event that we should use in case it means we should * @param ev the event that we should use in case it means we should
* nominate someone. * nominate someone.
*/ */
public void propertyChange(PropertyChangeEvent evt) public void propertyChange(PropertyChangeEvent ev)
{ {
if(Agent.PROPERTY_ICE_PROCESSING_STATE.equals(evt.getPropertyName())) String propertyName = ev.getPropertyName();
{
IceProcessingState newState = (IceProcessingState)evt.getNewValue();
if(newState != IceProcessingState.RUNNING) if(Agent.PROPERTY_ICE_PROCESSING_STATE.equals(propertyName))
{
if(ev.getNewValue() != IceProcessingState.RUNNING)
return; return;
List<IceMediaStream> streams = parentAgent.getStreams(); for(IceMediaStream stream : parentAgent.getStreams())
for(IceMediaStream stream : streams)
{ {
stream.addPairChangeListener(this); stream.addPairChangeListener(this);
stream.getCheckList().addStateChangeListener(this); stream.getCheckList().addStateChangeListener(this);
@ -86,28 +84,32 @@ public class DefaultNominator
return; return;
} }
if(evt.getSource() instanceof CandidatePair) if(ev.getSource() instanceof CandidatePair)
{ {
CandidatePair validPair = (CandidatePair)evt.getSource(); // STUN Usage for Consent Freshness is of no concern here.
if (IceMediaStream.PROPERTY_PAIR_CONSENT_FRESHNESS_CHANGED.equals(
propertyName))
return;
CandidatePair validPair = (CandidatePair) ev.getSource();
// do not nominate pair if there is currently a selected pair for // do not nominate pair if there is currently a selected pair for
// the component // the component
if(validPair.getParentComponent().getSelectedPair() != null) if(validPair.getParentComponent().getSelectedPair() != null)
{ {
logger.fine("Keep-alive for pair: " + logger.fine(
validPair.toShortString()); "Keep-alive for pair: " + validPair.toShortString());
return; return;
} }
} }
if(strategy == NominationStrategy.NOMINATE_FIRST_VALID) if (strategy == NominationStrategy.NOMINATE_FIRST_VALID)
strategyNominateFirstValid(evt); strategyNominateFirstValid(ev);
else if (strategy == NominationStrategy.NOMINATE_HIGHEST_PRIO) else if (strategy == NominationStrategy.NOMINATE_HIGHEST_PRIO)
strategyNominateHighestPrio(evt); strategyNominateHighestPrio(ev);
else if (strategy == else if (strategy
NominationStrategy.NOMINATE_FIRST_HOST_OR_REFLEXIVE_VALID) == NominationStrategy.NOMINATE_FIRST_HOST_OR_REFLEXIVE_VALID)
strategyNominateFirstHostOrReflexiveValid(evt); strategyNominateFirstHostOrReflexiveValid(ev);
} }
/** /**
@ -133,18 +135,18 @@ public class DefaultNominator
* pairs in a check list to conclude before nominating the one with the * pairs in a check list to conclude before nominating the one with the
* highest priority. * highest priority.
* *
* @param evt the {@link PropertyChangeEvent} containing the new state and * @param ev the {@link PropertyChangeEvent} containing the new state and
* the source {@link CheckList}. * the source {@link CheckList}.
*/ */
private void strategyNominateHighestPrio(PropertyChangeEvent evt) private void strategyNominateHighestPrio(PropertyChangeEvent ev)
{ {
String propName = evt.getPropertyName(); String pname = ev.getPropertyName();
if(IceMediaStream.PROPERTY_PAIR_VALIDATED.equals(propName)
|| (IceMediaStream.PROPERTY_PAIR_STATE_CHANGED.equals(propName) if(IceMediaStream.PROPERTY_PAIR_VALIDATED.equals(pname)
&& ((CandidatePairState)evt.getNewValue()) || (IceMediaStream.PROPERTY_PAIR_STATE_CHANGED.equals(pname)
== CandidatePairState.FAILED)) && (ev.getNewValue() == CandidatePairState.FAILED)))
{ {
CandidatePair validPair = (CandidatePair)evt.getSource(); CandidatePair validPair = (CandidatePair) ev.getSource();
Component parentComponent = validPair.getParentComponent(); Component parentComponent = validPair.getParentComponent();
IceMediaStream parentStream = parentComponent.getParentStream(); IceMediaStream parentStream = parentComponent.getParentStream();
CheckList parentCheckList = parentStream.getCheckList(); CheckList parentCheckList = parentStream.getCheckList();
@ -152,15 +154,15 @@ public class DefaultNominator
if(!parentCheckList.allChecksCompleted()) if(!parentCheckList.allChecksCompleted())
return; return;
List<Component> components = parentStream.getComponents(); for(Component component : parentStream.getComponents())
for(Component component : components)
{ {
CandidatePair pair = parentStream.getValidPair(component); CandidatePair pair = parentStream.getValidPair(component);
if(pair != null) if(pair != null)
{ {
logger.info("Nominate (highest priority): " + logger.info(
validPair.toShortString()); "Nominate (highest priority): "
+ validPair.toShortString());
parentAgent.nominate(pair); parentAgent.nominate(pair);
} }
} }
@ -194,21 +196,22 @@ public class DefaultNominator
{ {
if(IceMediaStream.PROPERTY_PAIR_VALIDATED.equals(evt.getPropertyName())) if(IceMediaStream.PROPERTY_PAIR_VALIDATED.equals(evt.getPropertyName()))
{ {
CandidatePair validPair = (CandidatePair)evt.getSource(); CandidatePair validPair = (CandidatePair) evt.getSource();
TimerTask task = null; Component component = validPair.getParentComponent();
boolean isRelayed = LocalCandidate localCandidate = validPair.getLocalCandidate();
(validPair.getLocalCandidate() instanceof RelayedCandidate) || boolean isRelayed
validPair.getLocalCandidate().getType().equals( = (localCandidate instanceof RelayedCandidate)
CandidateType.RELAYED_CANDIDATE) || || localCandidate.getType().equals(
validPair.getRemoteCandidate().getType().equals( CandidateType.RELAYED_CANDIDATE)
|| validPair.getRemoteCandidate().getType().equals(
CandidateType.RELAYED_CANDIDATE); CandidateType.RELAYED_CANDIDATE);
boolean nominate = false; boolean nominate = false;
synchronized(validatedCandidates) synchronized(validatedCandidates)
{ {
task = validatedCandidates.get( TimerTask task
validPair.getParentComponent().toShortString()); = validatedCandidates.get(component.toShortString());
if(isRelayed && task == null) if(isRelayed && task == null)
{ {
@ -221,9 +224,7 @@ public class DefaultNominator
logger.info("Wait timeout to nominate relayed candidate"); logger.info("Wait timeout to nominate relayed candidate");
timer.schedule(task, 0); timer.schedule(task, 0);
validatedCandidates.put( validatedCandidates.put(component.toShortString(), task);
validPair.getParentComponent().toShortString(),
task);
} }
else if(!isRelayed) else if(!isRelayed)
{ {
@ -233,12 +234,12 @@ public class DefaultNominator
task.cancel(); task.cancel();
logger.info( logger.info(
"Found a better candidate pair to nominate for " "Found a better candidate pair to nominate for "
+ validPair.getParentComponent(). + component.toShortString());
toShortString());
} }
logger.info("Nominate (first highest valid): " + logger.info(
validPair.toShortString()); "Nominate (first highest valid): "
+ validPair.toShortString());
nominate = true; nominate = true;
} }
} }
@ -269,9 +270,9 @@ public class DefaultNominator
private final CandidatePair pair; private final CandidatePair pair;
/** /**
* If the task has been canceled. * If the task has been cancelled.
*/ */
private boolean canceled = false; private boolean cancelled = false;
/** /**
* Constructor. * Constructor.
@ -306,18 +307,20 @@ public class DefaultNominator
if(c != pair && c.getState() != CandidatePairState.FAILED) if(c != pair && c.getState() != CandidatePairState.FAILED)
{ {
allFailed = false; allFailed = false;
break;
} }
} }
} }
if(allFailed && ! pair.isNominated()) if(allFailed && !pair.isNominated())
{ {
// all other pairs are failed to do not waste time, cancel // all other pairs are failed to do not waste time, cancel
// timer and nominate ourself (the relayed candidate). // timer and nominate ourself (the relayed candidate).
this.cancel(); this.cancel();
logger.info("Nominate (first highest valid): " + logger.info(
pair.toShortString()); "Nominate (first highest valid): "
+ pair.toShortString());
parentAgent.nominate(pair); parentAgent.nominate(pair);
} }
} }
@ -328,7 +331,7 @@ public class DefaultNominator
@Override @Override
public boolean cancel() public boolean cancel()
{ {
canceled = true; cancelled = true;
return super.cancel(); return super.cancel();
} }
@ -343,23 +346,22 @@ public class DefaultNominator
} }
catch(InterruptedException e) catch(InterruptedException e)
{ {
canceled = true; cancelled = true;
} }
pair.getParentComponent().getParentStream().getCheckList(). Component component = pair.getParentComponent();
removeChecksListener(this);
validatedCandidates.remove(
pair.getParentComponent().toShortString());
if(canceled) component.getParentStream().getCheckList().removeChecksListener(
{ this);
validatedCandidates.remove(component.toShortString());
if(cancelled)
return; return;
}
logger.info("Nominate (first highest valid): " + logger.info(
pair.toShortString()); "Nominate (first highest valid): " + pair.toShortString());
// task has not been canceled after WAIT_TIME milliseconds so // task has not been cancelled after WAIT_TIME milliseconds so
// nominate the pair // nominate the pair
parentAgent.nominate(pair); parentAgent.nominate(pair);
} }

View File

@ -31,6 +31,31 @@ public class IceMediaStream
private static final Logger logger = private static final Logger logger =
Logger.getLogger(IceMediaStream.class.getName()); Logger.getLogger(IceMediaStream.class.getName());
/**
* The property name that we use when delivering events notifying listeners
* that the consent freshness of a pair has changed.
*/
public static final String PROPERTY_PAIR_CONSENT_FRESHNESS_CHANGED
= "PairConsentFreshnessChanged";
/**
* The property name that we use when delivering events notifying listeners
* of newly nominated pairs.
*/
public static final String PROPERTY_PAIR_NOMINATED = "PairNominated";
/**
* The property name that we use when delivering events notifying listeners
* that a pair has changed states.
*/
public static final String PROPERTY_PAIR_STATE_CHANGED = "PairStateChanged";
/**
* The property name that we use when delivering events notifying listeners
* of newly validated pairs.
*/
public static final String PROPERTY_PAIR_VALIDATED = "PairValidated";
/** /**
* The name of this media stream. The name is equal to the value specified * The name of this media stream. The name is equal to the value specified
* in the SDP description. * in the SDP description.
@ -73,24 +98,6 @@ public class IceMediaStream
*/ */
private final Agent parentAgent; private final Agent parentAgent;
/**
* The property name that we use when delivering events notifying listeners
* of newly validated pairs.
*/
public static final String PROPERTY_PAIR_VALIDATED = "PairValidated";
/**
* The property name that we use when delivering events notifying listeners
* that a pair has changed states..
*/
public static final String PROPERTY_PAIR_STATE_CHANGED = "PairStateChanged";
/**
* The property name that we use when delivering events notifying listeners
* of newly nominated pairs.
*/
public static final String PROPERTY_PAIR_NOMINATED = "PairNominated";
/** /**
* Contains {@link PropertyChangeListener}s registered with this {@link * Contains {@link PropertyChangeListener}s registered with this {@link
* Agent} and following the various events it may be generating. * Agent} and following the various events it may be generating.
@ -176,9 +183,12 @@ public class IceMediaStream
@Override @Override
public String toString() public String toString()
{ {
StringBuffer buff = new StringBuffer( "media stream:") StringBuilder buff
= new StringBuilder( "media stream:")
.append(getName()); .append(getName());
buff.append(" (component count=").append(getComponentCount())
buff.append(" (component count=")
.append(getComponentCount())
.append(")"); .append(")");
for (Component cmp : getComponents()) for (Component cmp : getComponents())
@ -284,9 +294,11 @@ public class IceMediaStream
{ {
Iterator<Map.Entry<Integer, Component>> cmpEntries Iterator<Map.Entry<Integer, Component>> cmpEntries
= components.entrySet().iterator(); = components.entrySet().iterator();
while (cmpEntries.hasNext()) while (cmpEntries.hasNext())
{ {
Component component = cmpEntries.next().getValue(); Component component = cmpEntries.next().getValue();
component.free(); component.free();
cmpEntries.remove(); cmpEntries.remove();
} }
@ -357,10 +369,8 @@ public class IceMediaStream
for(LocalCandidate lc : localCnds) for(LocalCandidate lc : localCnds)
{ {
if(lc instanceof UPNPCandidate) if(lc instanceof UPNPCandidate)
{
upnpBase = lc.getBase(); upnpBase = lc.getBase();
} }
}
for(LocalCandidate localCnd : localCnds) for(LocalCandidate localCnd : localCnds)
{ {
@ -372,9 +382,9 @@ public class IceMediaStream
{ {
if(localCnd.canReach(remoteCnd)) if(localCnd.canReach(remoteCnd))
{ {
if(localCnd.getTransport() == Transport.TCP && if(localCnd.getTransport() == Transport.TCP
parentAgent.getCompatibilityMode() == && parentAgent.getCompatibilityMode()
CompatibilityMode.GTALK) == CompatibilityMode.GTALK)
{ {
final LocalCandidate loc = localCnd; final LocalCandidate loc = localCnd;
final RemoteCandidate remot = remoteCnd; final RemoteCandidate remot = remoteCnd;
@ -533,9 +543,7 @@ public class IceMediaStream
*/ */
public LocalCandidate findLocalCandidate(TransportAddress localAddress) public LocalCandidate findLocalCandidate(TransportAddress localAddress)
{ {
Collection<Component> cmpCol = components.values(); for( Component cmp : components.values())
for( Component cmp : cmpCol)
{ {
LocalCandidate cnd = cmp.findLocalCandidate(localAddress); LocalCandidate cnd = cmp.findLocalCandidate(localAddress);
@ -560,9 +568,7 @@ public class IceMediaStream
*/ */
public RemoteCandidate findRemoteCandidate(TransportAddress remoteAddress) public RemoteCandidate findRemoteCandidate(TransportAddress remoteAddress)
{ {
Collection<Component> cmpCol = components.values(); for( Component cmp : components.values())
for( Component cmp : cmpCol)
{ {
RemoteCandidate cnd = cmp.findRemoteCandidate(remoteAddress); RemoteCandidate cnd = cmp.findRemoteCandidate(remoteAddress);
@ -627,8 +633,8 @@ public class IceMediaStream
LocalCandidate local = pair.getLocalCandidate(); LocalCandidate local = pair.getLocalCandidate();
RemoteCandidate remote = pair.getRemoteCandidate(); RemoteCandidate remote = pair.getRemoteCandidate();
if(local.getUfrag().equals(remoteUFrag) && if(local.getUfrag().equals(remoteUFrag)
remote.getUfrag().equals(localUFrag)) && remote.getUfrag().equals(localUFrag))
{ {
return pair; return pair;
} }
@ -648,13 +654,9 @@ public class IceMediaStream
synchronized (components) synchronized (components)
{ {
Collection<Component> cmpCol = components.values(); for(Component cmp : components.values())
for( Component cmp : cmpCol)
{
num += cmp.coundHostCandidates(); num += cmp.coundHostCandidates();
} }
}
return num; return num;
} }
@ -670,7 +672,7 @@ public class IceMediaStream
{ {
synchronized(checkList) synchronized(checkList)
{ {
this.checkList.add(candidatePair); checkList.add(candidatePair);
} }
} }
@ -706,9 +708,11 @@ public class IceMediaStream
synchronized(validList) synchronized(validList)
{ {
for(CandidatePair pair : validList) for(CandidatePair pair : validList)
{
if (pair.getFoundation().equals(foundation)) if (pair.getFoundation().equals(foundation))
return true; return true;
} }
}
return false; return false;
} }
@ -730,8 +734,8 @@ public class IceMediaStream
{ {
for(CandidatePair pair : validList) for(CandidatePair pair : validList)
{ {
if (pair.isNominated() && pair.getParentComponent() == if (pair.isNominated()
component) && pair.getParentComponent() == component)
{ {
return true; return true;
} }
@ -751,17 +755,15 @@ public class IceMediaStream
*/ */
protected boolean validListContainsAllComponents() protected boolean validListContainsAllComponents()
{ {
List<Component> cmpList = getComponents(); for(Component cmp : getComponents())
for(Component cmp : cmpList) {
if (getValidPair(cmp) == null)
{ {
if (getValidPair(cmp) != null)
continue;
//it looks like there's at least one component we don't have a //it looks like there's at least one component we don't have a
//valid candidate for. //valid candidate for.
return false; return false;
} }
}
return true; return true;
} }
@ -781,9 +783,11 @@ public class IceMediaStream
synchronized (validList) synchronized (validList)
{ {
for(CandidatePair pair : validList) for(CandidatePair pair : validList)
{
if(pair.isNominated()) if(pair.isNominated())
components.remove(pair.getParentComponent()); components.remove(pair.getParentComponent());
} }
}
return components.isEmpty(); return components.isEmpty();
} }
@ -800,9 +804,10 @@ public class IceMediaStream
protected boolean allComponentsHaveSelected() protected boolean allComponentsHaveSelected()
{ {
for(Component component : getComponents()) for(Component component : getComponents())
{
if(component.getSelectedPair() == null) if(component.getSelectedPair() == null)
return false; return false;
}
return true; return true;
} }
@ -821,10 +826,11 @@ public class IceMediaStream
synchronized(validList) synchronized(validList)
{ {
for(CandidatePair pair : validList) for(CandidatePair pair : validList)
{
if(pair.getParentComponent() == component) if(pair.getParentComponent() == component)
return pair; return pair;
} }
}
return null; return null;
} }
@ -841,7 +847,7 @@ public class IceMediaStream
synchronized(streamListeners) synchronized(streamListeners)
{ {
if(!streamListeners.contains(l)) if(!streamListeners.contains(l))
this.streamListeners.add(l); streamListeners.add(l);
} }
} }
@ -855,7 +861,7 @@ public class IceMediaStream
{ {
synchronized(streamListeners) synchronized(streamListeners)
{ {
this.streamListeners.remove(l); streamListeners.remove(l);
} }
} }
@ -873,21 +879,20 @@ public class IceMediaStream
Object oldValue, Object oldValue,
Object newValue) Object newValue)
{ {
List<PropertyChangeListener> listenersCopy; PropertyChangeListener[] ls;
synchronized(streamListeners) synchronized(streamListeners)
{ {
listenersCopy ls
= new LinkedList<PropertyChangeListener>(streamListeners); = streamListeners.toArray(
new PropertyChangeListener[streamListeners.size()]);
} }
PropertyChangeEvent evt = new PropertyChangeEvent( PropertyChangeEvent ev
source, propertyName, oldValue, newValue); = new PropertyChangeEvent(source, propertyName, oldValue, newValue);
for(PropertyChangeListener l : listenersCopy) for(PropertyChangeListener l : ls)
{ l.propertyChange(ev);
l.propertyChange(evt);
}
} }
/** /**

View File

@ -484,8 +484,8 @@ public class MultiplexingDatagramSocket
accepted = true; accepted = true;
/* /*
* Emil: Don't break because we want all * Emil: Don't break because we want all filtering
* filtering sockets to get this. * sockets to get the received packet.
*/ */
//break; //break;
} }

View File

@ -346,35 +346,30 @@ class NetAccessManager
* @param srcAddr the access point to use to send the message * @param srcAddr the access point to use to send the message
* @param remoteAddr the destination of the message. * @param remoteAddr the destination of the message.
* *
* @throws IOException if an error occurs while sending message bytes
* through the network socket.
* @throws IllegalArgumentException if the apDescriptor references an * @throws IllegalArgumentException if the apDescriptor references an
* access point that had not been installed, * access point that had not been installed,
* @throws IOException if an error occurs while sending message bytes
* through the network socket.
*/ */
void sendMessage( void sendMessage(
Message stunMessage, Message stunMessage,
TransportAddress srcAddr, TransportAddress srcAddr,
TransportAddress remoteAddr) TransportAddress remoteAddr)
throws IOException, IllegalArgumentException throws IllegalArgumentException,
IOException
{ {
byte[] bytes = stunMessage.encode(stunStack); byte[] bytes = stunMessage.encode(stunStack);
Connector ap = null; Connector ap = null;
if(srcAddr.getTransport() == Transport.UDP) if (srcAddr.getTransport() == Transport.UDP)
{
ap = netUDPAccessPoints.get(srcAddr); ap = netUDPAccessPoints.get(srcAddr);
} else if (srcAddr.getTransport() == Transport.TCP)
else if(srcAddr.getTransport() == Transport.TCP)
{
ap = netTCPAccessPoints.get(srcAddr); ap = netTCPAccessPoints.get(srcAddr);
}
if (ap == null) if (ap == null)
{ {
throw throw new IllegalArgumentException(
new IllegalArgumentException( "No socket has been added for source address: " + srcAddr);
"No socket has been added for source address: "
+ srcAddr);
} }
ap.sendMessage(bytes, remoteAddr); ap.sendMessage(bytes, remoteAddr);

View File

@ -7,6 +7,7 @@
package org.ice4j.stack; package org.ice4j.stack;
import java.io.*; import java.io.*;
import java.util.concurrent.*;
import java.util.logging.*; import java.util.logging.*;
import org.ice4j.*; import org.ice4j.*;
@ -31,6 +32,7 @@ import org.ice4j.message.*;
* *
* @author Emil Ivov. * @author Emil Ivov.
* @author Pascal Mogeri (contributed configuration of client transactions). * @author Pascal Mogeri (contributed configuration of client transactions).
* @author Lyubomir Marinov
*/ */
class StunClientTransaction class StunClientTransaction
implements Runnable implements Runnable
@ -38,8 +40,8 @@ class StunClientTransaction
/** /**
* Our class logger. * Our class logger.
*/ */
private static final Logger logger = private static final Logger logger
Logger.getLogger(StunClientTransaction.class.getName()); = Logger.getLogger(StunClientTransaction.class.getName());
/** /**
* The number of times to retransmit a request if no explicit value has been * The number of times to retransmit a request if no explicit value has been
@ -47,6 +49,60 @@ class StunClientTransaction
*/ */
public static final int DEFAULT_MAX_RETRANSMISSIONS = 6; public static final int DEFAULT_MAX_RETRANSMISSIONS = 6;
/**
* The maximum number of milliseconds a client should wait between
* consecutive retransmissions, after it has sent a request for the first
* time.
*/
public static final int DEFAULT_MAX_WAIT_INTERVAL = 1600;
/**
* The number of milliseconds a client should wait before retransmitting,
* after it has sent a request for the first time.
*/
public static final int DEFAULT_ORIGINAL_WAIT_INTERVAL = 100;
/**
* The pool of <tt>Thread</tt>s which retransmit
* <tt>StunClientTransaction</tt>s.
*/
private static final ExecutorService retransmissionThreadPool
= Executors.newCachedThreadPool(
new ThreadFactory()
{
/**
* The default <tt>ThreadFactory</tt> implementation
* which is augmented by this instance to create
* daemon <tt>Thread</tt>s.
*/
private final ThreadFactory defaultThreadFactory
= Executors.defaultThreadFactory();
@Override
public Thread newThread(Runnable r)
{
Thread t = defaultThreadFactory.newThread(r);
if (t != null)
{
t.setDaemon(true);
/*
* Additionally, make it known through the
* name of the Thread that it is associated
* with the StunClientTransaction class for
* debugging/informational purposes.
*/
String name = t.getName();
if (name == null)
name = "";
t.setName("StunClientTransaction-" + name);
}
return t;
}
});
/** /**
* Maximum number of retransmissions. Once this number is reached and if no * Maximum number of retransmissions. Once this number is reached and if no
* response is received after MAX_WAIT_INTERVAL milliseconds the request is * response is received after MAX_WAIT_INTERVAL milliseconds the request is
@ -54,25 +110,12 @@ class StunClientTransaction
*/ */
public int maxRetransmissions = DEFAULT_MAX_RETRANSMISSIONS; public int maxRetransmissions = DEFAULT_MAX_RETRANSMISSIONS;
/**
* The number of milliseconds a client should wait before retransmitting,
* after it has sent a request for the first time.
*/
public static final int DEFAULT_ORIGINAL_WAIT_INTERVAL = 100;
/** /**
* The number of milliseconds to wait before the first retransmission of the * The number of milliseconds to wait before the first retransmission of the
* request. * request.
*/ */
public int originalWaitInterval = DEFAULT_ORIGINAL_WAIT_INTERVAL; public int originalWaitInterval = DEFAULT_ORIGINAL_WAIT_INTERVAL;
/**
* The maximum number of milliseconds a client should wait between
* consecutive retransmissions, after it has sent a request for the first
* time.
*/
public static final int DEFAULT_MAX_WAIT_INTERVAL = 1600;
/** /**
* The maximum wait interval. Once this interval is reached we should stop * The maximum wait interval. Once this interval is reached we should stop
* doubling its value. * doubling its value.
@ -126,11 +169,6 @@ class StunClientTransaction
*/ */
private boolean cancelled = false; private boolean cancelled = false;
/**
* The thread that this transaction runs in.
*/
private Thread retransmissionsThread = null;
/** /**
* Creates a client transaction. * Creates a client transaction.
* *
@ -148,8 +186,12 @@ class StunClientTransaction
TransportAddress localAddress, TransportAddress localAddress,
ResponseCollector responseCollector) ResponseCollector responseCollector)
{ {
this(stackCallback, request, requestDestination, localAddress, this(stackCallback,
responseCollector, TransactionID.createNewTransactionID()); request,
requestDestination,
localAddress,
responseCollector,
TransactionID.createNewTransactionID());
} }
/** /**
@ -189,15 +231,12 @@ class StunClientTransaction
} }
catch (StunException ex) catch (StunException ex)
{ {
//Shouldn't happen so lets just through a runtime exception in //Shouldn't happen so lets just through a runtime exception in case
//case anything is real messed up //anything is real messed up
throw new IllegalArgumentException("The TransactionID class " throw new IllegalArgumentException(
+"generated an invalid transaction ID"); "The TransactionID class generated an invalid transaction"
+ " ID");
} }
retransmissionsThread = new Thread(this,
"StunClientTransaction@"+hashCode());
retransmissionsThread.setDaemon(true);
} }
/** /**
@ -210,7 +249,6 @@ class StunClientTransaction
*/ */
public void run() public void run()
{ {
retransmissionsThread.setName("ice4j.ClientTransaction");
nextWaitInterval = originalWaitInterval; nextWaitInterval = originalWaitInterval;
synchronized(this) synchronized(this)
@ -245,7 +283,8 @@ class StunClientTransaction
//I wonder whether we should notify anyone that a //I wonder whether we should notify anyone that a
//retransmission has failed //retransmission has failed
logger.log(Level.INFO, logger.log(Level.INFO,
"A client tran retransmission failed", ex); "A client tran retransmission failed",
ex);
} }
} }
@ -280,13 +319,12 @@ class StunClientTransaction
void sendRequest() void sendRequest()
throws IllegalArgumentException, IOException throws IllegalArgumentException, IOException
{ {
logger.fine("sending STUN " logger.fine(
+ " tid " + transactionID "sending STUN " + " tid " + transactionID + " from "
+ " from " + localAddress + localAddress + " to " + requestDestination);
+ " to " + requestDestination);
sendRequest0(); sendRequest0();
retransmissionsThread.start(); retransmissionThreadPool.execute(this);
} }
/** /**
@ -303,14 +341,15 @@ class StunClientTransaction
if(cancelled) if(cancelled)
{ {
logger.finer("Trying to resend a cancelled transaction."); logger.finer("Trying to resend a cancelled transaction.");
return;
} }
else
{
stackCallback.getNetAccessManager().sendMessage( stackCallback.getNetAccessManager().sendMessage(
this.request, this.request,
localAddress, localAddress,
requestDestination); requestDestination);
} }
}
/** /**
* Returns the request that was the reason for creating this transaction. * Returns the request that was the reason for creating this transaction.
@ -395,8 +434,8 @@ class StunClientTransaction
} }
/** /**
* Init transaction duration/retransmission parameters. * Init transaction duration/retransmission parameters. (Mostly contributed
* (Mostly, contributed by Pascal Maugeri). * by Pascal Maugeri.)
*/ */
private void initTransactionConfiguration() private void initTransactionConfiguration()
{ {
@ -405,7 +444,8 @@ class StunClientTransaction
= System.getProperty(StackProperties.MAX_CTRAN_RETRANSMISSIONS); = System.getProperty(StackProperties.MAX_CTRAN_RETRANSMISSIONS);
if(maxRetransmissionsStr != null if(maxRetransmissionsStr != null
&& maxRetransmissionsStr.trim().length() > 0){ && maxRetransmissionsStr.trim().length() > 0)
{
try try
{ {
maxRetransmissions = Integer.parseInt(maxRetransmissionsStr); maxRetransmissions = Integer.parseInt(maxRetransmissionsStr);
@ -424,7 +464,8 @@ class StunClientTransaction
= System.getProperty(StackProperties.FIRST_CTRAN_RETRANS_AFTER); = System.getProperty(StackProperties.FIRST_CTRAN_RETRANS_AFTER);
if(originalWaitIntervalStr != null if(originalWaitIntervalStr != null
&& originalWaitIntervalStr.trim().length() > 0){ && originalWaitIntervalStr.trim().length() > 0)
{
try try
{ {
originalWaitInterval originalWaitInterval
@ -444,7 +485,8 @@ class StunClientTransaction
= System.getProperty(StackProperties.MAX_CTRAN_RETRANS_TIMER); = System.getProperty(StackProperties.MAX_CTRAN_RETRANS_TIMER);
if(maxWaitIntervalStr != null if(maxWaitIntervalStr != null
&& maxWaitIntervalStr.trim().length() > 0){ && maxWaitIntervalStr.trim().length() > 0)
{
try try
{ {
maxWaitInterval = Integer.parseInt(maxWaitIntervalStr); maxWaitInterval = Integer.parseInt(maxWaitIntervalStr);

View File

@ -38,12 +38,12 @@ class StunServerTransaction
/** /**
* The time that we keep server transactions active. * The time that we keep server transactions active.
*/ */
private long transactionLifetime = 16000; private static final long LIFETIME = 16000;
/** /**
* The <tt>StunStack</tt> that created us. * The <tt>StunStack</tt> that created us.
*/ */
private StunStack stackCallback = null; private final StunStack stackCallback;
/** /**
* The address that we are sending responses to. * The address that we are sending responses to.
@ -53,7 +53,7 @@ class StunServerTransaction
/** /**
* The address that we are receiving requests from. * The address that we are receiving requests from.
*/ */
private TransportAddress requestSource = null; private final TransportAddress requestSource;
/** /**
* The response sent in response to the request. * The response sent in response to the request.
@ -63,7 +63,7 @@ class StunServerTransaction
/** /**
* The <tt>TransportAddress</tt> that we received our request on. * The <tt>TransportAddress</tt> that we received our request on.
*/ */
private TransportAddress localListeningAddress = null; private final TransportAddress localListeningAddress;
/** /**
* The <tt>TransportAddress</tt> we use when sending responses * The <tt>TransportAddress</tt> we use when sending responses
@ -73,7 +73,7 @@ class StunServerTransaction
/** /**
* The id of the transaction. * The id of the transaction.
*/ */
private TransactionID transactionID = null; private final TransactionID transactionID;
/** /**
* The date (in milliseconds) when the next retransmission should follow. * The date (in milliseconds) when the next retransmission should follow.
@ -114,7 +114,6 @@ class StunServerTransaction
{ {
this.stackCallback = stackCallback; this.stackCallback = stackCallback;
this.transactionID = tranID; this.transactionID = tranID;
this.requestSource = requestSource;
this.localListeningAddress = localListeningAddress; this.localListeningAddress = localListeningAddress;
this.requestSource = requestSource; this.requestSource = requestSource;
@ -140,7 +139,7 @@ class StunServerTransaction
{ {
runningThread.setName("ServTran"); runningThread.setName("ServTran");
schedule(transactionLifetime); schedule(LIFETIME);
waitNextScheduledDate(); waitNextScheduledDate();
//let's get lost //let's get lost
@ -212,25 +211,22 @@ class StunServerTransaction
/** /**
* Waits until next retransmission is due or until the transaction is * Waits until next retransmission is due or until the transaction is
* canceled (whichever comes first). * cancelled (whichever comes first).
*/ */
private synchronized void waitNextScheduledDate() private synchronized void waitNextScheduledDate()
{ {
long current = System.currentTimeMillis(); long timeout;
while(expirationDate - current > 0)
while (!expired
&& (timeout = expirationDate - System.currentTimeMillis()) > 0)
{ {
try try
{ {
wait(expirationDate - current); wait(timeout);
} }
catch (InterruptedException ex) catch (InterruptedException ex)
{ {
} }
//did someone ask us to get lost?
if(expired)
return;
current = System.currentTimeMillis();
} }
} }
@ -254,7 +250,6 @@ class StunServerTransaction
notifyAll(); notifyAll();
} }
/** /**
* Returns the ID of the current transaction. * Returns the ID of the current transaction.
* *

View File

@ -344,16 +344,14 @@ public class StunStack
} }
catch (IllegalArgumentException iaex) catch (IllegalArgumentException iaex)
{ {
throw throw new StunException(
new StunException(
StunException.ILLEGAL_ARGUMENT, StunException.ILLEGAL_ARGUMENT,
"Failed to send STUN indication: " + indication, "Failed to send STUN indication: " + indication,
iaex); iaex);
} }
catch (IOException ioex) catch (IOException ioex)
{ {
throw throw new StunException(
new StunException(
StunException.NETWORK_ERROR, StunException.NETWORK_ERROR,
"Failed to send STUN indication: " + indication, "Failed to send STUN indication: " + indication,
ioex); ioex);
@ -402,23 +400,76 @@ public class StunStack
* @return the <tt>TransactionID</tt> of the <tt>StunClientTransaction</tt> * @return the <tt>TransactionID</tt> of the <tt>StunClientTransaction</tt>
* that we used in order to send the request. * that we used in order to send the request.
* *
* @throws IOException if an error occurs while sending message bytes
* through the network socket.
* @throws IllegalArgumentException if the apDescriptor references an * @throws IllegalArgumentException if the apDescriptor references an
* access point that had not been installed, * access point that had not been installed,
* @throws IOException if an error occurs while sending message bytes
* through the network socket.
*/ */
public TransactionID sendRequest( Request request, public TransactionID sendRequest(Request request,
TransportAddress sendTo, TransportAddress sendTo,
TransportAddress sendThrough, TransportAddress sendThrough,
ResponseCollector collector, ResponseCollector collector,
TransactionID transactionID) TransactionID transactionID)
throws IOException, IllegalArgumentException throws IllegalArgumentException,
IOException
{
return
sendRequest(
request, sendTo, sendThrough, collector, transactionID,
-1, -1, -1);
}
/**
* Sends the specified request through the specified access point, and
* registers the specified ResponseCollector for later notification.
* @param request the request to send
* @param sendTo the destination address of the request.
* @param sendThrough the local address to use when sending the request
* @param collector the instance to notify when a response arrives or the
* the transaction timeouts
* @param transactionID the ID that we'd like the new transaction to use
* in case the application created it in order to use it for application
* data correlation.
* @param originalWiatIterval
* @param maxWaitInterval
* @param maxRetransmissions
* @return the <tt>TransactionID</tt> of the <tt>StunClientTransaction</tt>
* that we used in order to send the request.
*
* @throws IllegalArgumentException if the apDescriptor references an
* access point that had not been installed,
* @throws IOException if an error occurs while sending message bytes
* through the network socket.
*/
public TransactionID sendRequest(Request request,
TransportAddress sendTo,
TransportAddress sendThrough,
ResponseCollector collector,
TransactionID transactionID,
int originalWaitInterval,
int maxWaitInterval,
int maxRetransmissions)
throws IllegalArgumentException,
IOException
{ {
StunClientTransaction clientTransaction StunClientTransaction clientTransaction
= new StunClientTransaction(this, request, sendTo, sendThrough, = new StunClientTransaction(
collector, transactionID); this,
request,
sendTo,
sendThrough,
collector,
transactionID);
clientTransactions.put(clientTransaction.getTransactionID(), if (originalWaitInterval > 0)
clientTransaction.originalWaitInterval = originalWaitInterval;
if (maxWaitInterval > 0)
clientTransaction.maxWaitInterval = maxWaitInterval;
if (maxRetransmissions >= 0)
clientTransaction.maxRetransmissions = maxRetransmissions;
clientTransactions.put(
clientTransaction.getTransactionID(),
clientTransaction); clientTransaction);
clientTransaction.sendRequest(); clientTransaction.sendRequest();
@ -620,26 +671,27 @@ public class StunStack
/** /**
* Called to notify this provider for an incoming message. * Called to notify this provider for an incoming message.
* *
* @param event the event object that contains the new message. * @param ev the event object that contains the new message.
*/ */
public void handleMessageEvent(StunMessageEvent event) public void handleMessageEvent(StunMessageEvent ev)
{ {
Message msg = event.getMessage(); Message msg = ev.getMessage();
if(logger.isLoggable(Level.FINEST)) if(logger.isLoggable(Level.FINEST))
logger.finest("Received a message on " {
+ event.getLocalAddress() logger.finest(
+ " of type:" "Received a message on " + ev.getLocalAddress()
+ (int)msg.getMessageType()); + " of type:" + (int) msg.getMessageType());
}
//request //request
if(msg instanceof Request) if(msg instanceof Request)
{ {
logger.finest("parsing request"); logger.finest("parsing request");
TransactionID serverTid = event.getTransactionID(); TransactionID serverTid = ev.getTransactionID();
StunServerTransaction sTran = serverTransactions.get(serverTid); StunServerTransaction sTran = serverTransactions.get(serverTid);
if( sTran != null) if( sTran != null)
{ {
//requests from this transaction have already been seen //requests from this transaction have already been seen
@ -655,7 +707,8 @@ public class StunStack
{ {
//we couldn't really do anything here .. apart from logging //we couldn't really do anything here .. apart from logging
logger.log(Level.WARNING, logger.log(Level.WARNING,
"Failed to retransmit a stun response", ex); "Failed to retransmit a stun response",
ex);
} }
if(!Boolean.getBoolean( if(!Boolean.getBoolean(
@ -667,8 +720,12 @@ public class StunStack
else else
{ {
logger.finest("existing transaction not found"); logger.finest("existing transaction not found");
sTran = new StunServerTransaction(this, serverTid, sTran
event.getLocalAddress(), event.getRemoteAddress()); = new StunServerTransaction(
this,
serverTid,
ev.getLocalAddress(),
ev.getRemoteAddress());
// if there is an OOM error here, it will lead to // if there is an OOM error here, it will lead to
// NetAccessManager.handleFatalError that will stop the // NetAccessManager.handleFatalError that will stop the
@ -689,18 +746,18 @@ public class StunStack
//validate attributes that need validation. //validate attributes that need validation.
try try
{ {
validateRequestAttributes(event); validateRequestAttributes(ev);
} }
catch(Exception exc) catch(Exception exc)
{ {
//validation failed. log get lost. //validation failed. log get lost.
logger.log(Level.FINE, "Failed to validate msg: " + event, exc); logger.log(Level.FINE, "Failed to validate msg: " + ev, exc);
return; return;
} }
try try
{ {
eventDispatcher.fireMessageEvent(event); eventDispatcher.fireMessageEvent(ev);
} }
catch (Throwable t) catch (Throwable t)
{ {
@ -709,12 +766,14 @@ public class StunStack
logger.log(Level.INFO, "Received an invalid request.", t); logger.log(Level.INFO, "Received an invalid request.", t);
Throwable cause = t.getCause(); Throwable cause = t.getCause();
if(((t instanceof StunException) && if(((t instanceof StunException)
((StunException)t).getID() == && ((StunException) t).getID()
StunException.TRANSACTION_ALREADY_ANSWERED) || == StunException
(cause != null && (cause instanceof StunException) && .TRANSACTION_ALREADY_ANSWERED)
((StunException)cause).getID() == || ((cause instanceof StunException)
StunException.TRANSACTION_ALREADY_ANSWERED)) && ((StunException) cause).getID()
== StunException
.TRANSACTION_ALREADY_ANSWERED))
{ {
// do not try to send an error response since we will // do not try to send an error response since we will
// get another TRANSACTION_ALREADY_ANSWERED // get another TRANSACTION_ALREADY_ANSWERED
@ -723,53 +782,58 @@ public class StunStack
if(t instanceof IllegalArgumentException) if(t instanceof IllegalArgumentException)
{ {
error = MessageFactory.createBindingErrorResponse( error
= MessageFactory.createBindingErrorResponse(
ErrorCodeAttribute.BAD_REQUEST, ErrorCodeAttribute.BAD_REQUEST,
t.getMessage()); t.getMessage());
} }
else else
{ {
error = MessageFactory.createBindingErrorResponse( error
= MessageFactory.createBindingErrorResponse(
ErrorCodeAttribute.SERVER_ERROR, ErrorCodeAttribute.SERVER_ERROR,
"Oops! Something went wrong on our side :("); "Oops! Something went wrong on our side :(");
} }
try try
{ {
sendResponse(event.getTransactionID().getBytes(), sendResponse(
error, event.getLocalAddress(), serverTid.getBytes(),
event.getRemoteAddress()); error,
ev.getLocalAddress(),
ev.getRemoteAddress());
} }
catch(Exception exc) catch(Exception exc)
{ {
logger.log(Level.FINE, "Couldn't send a server error " logger.log(Level.FINE,
+ "response", exc); "Couldn't send a server error response",
exc);
} }
} }
} }
//response //response
else if(msg instanceof Response) else if(msg instanceof Response)
{ {
TransactionID tid = event.getTransactionID(); TransactionID tid = ev.getTransactionID();
StunClientTransaction tran = clientTransactions.remove(tid); StunClientTransaction tran = clientTransactions.remove(tid);
if(tran != null) if(tran != null)
{ {
tran.handleResponse(event); tran.handleResponse(ev);
} }
else else
{ {
//do nothing - just drop the phantom response. //do nothing - just drop the phantom response.
logger.fine("Dropped response - no matching client tran found" logger.fine(
+ " for tid " + tid + "\n" "Dropped response - no matching client tran found for"
+ "all tids in stock were " + " tid " + tid + "\n" + "all tids in stock were "
+ clientTransactions.keySet()); + clientTransactions.keySet());
} }
} }
// indication // indication
else if (msg instanceof Indication) else if (msg instanceof Indication)
{ {
eventDispatcher.fireMessageEvent(event); eventDispatcher.fireMessageEvent(ev);
} }
} }
@ -792,20 +856,24 @@ public class StunStack
{ {
eventDispatcher.removeAllListeners(); eventDispatcher.removeAllListeners();
Enumeration<TransactionID> tids = clientTransactions.keys(); for (Iterator<StunClientTransaction> i
while (tids.hasMoreElements()) = clientTransactions.values().iterator();
i.hasNext();)
{ {
TransactionID item = tids.nextElement(); StunClientTransaction tran = i.next();
StunClientTransaction tran = clientTransactions.remove(item);
i.remove();
if(tran != null) if(tran != null)
tran.cancel(); tran.cancel();
} }
tids = serverTransactions.keys(); for (Iterator<StunServerTransaction> i
while (tids.hasMoreElements()) = serverTransactions.values().iterator();
i.hasNext();)
{ {
TransactionID item = tids.nextElement(); StunServerTransaction tran = i.next();
StunServerTransaction tran = serverTransactions.remove(item);
i.remove();
if(tran != null) if(tran != null)
tran.expire(); tran.expire();
} }