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.
*
* @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

View File

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

View File

@ -41,6 +41,21 @@ import org.ice4j.stack.*;
*/
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.
*/
@ -93,7 +108,7 @@ public class Agent
/**
* 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
@ -111,7 +126,7 @@ public class 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
@ -208,7 +223,7 @@ public class Agent
/**
* 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
@ -237,6 +252,12 @@ public class Agent
*/
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.
*/
@ -266,15 +287,16 @@ public class Agent
if (StackProperties.getString(StackProperties.SOFTWARE) == null)
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;
/* no password in Google Talk dialect (at least libnice does not use
* one)
/*
* There is no password in the Google Talk dialect. (At least
* libnice does not use one.)
*/
password = "";
}
@ -374,12 +396,9 @@ public class Agent
* ufrag since it must be the same as username present in
* HTTP response
*/
if(localCand.getUfrag() != null)
{
continue;
}
if(localCand.getUfrag() == null)
localCand.setUfrag(generateGTalkUfrag());
localCand.setUfrag(generateGTalkUfrag());
}
}
@ -472,9 +491,10 @@ public class Agent
logger.fine("Candidate count in first harvest: " +
component.getLocalCandidateCount());
//Emil: because of trickle we now assign foundations, compute priorities
//and eliminate redundancies while adding candidates on a component.
// This means that we no longer need to do it here, where we did before.
// Emil: Because of trickle, we now assign foundations, compute
// priorities, and eliminate redundancies while adding candidates on a
// component. This means that we no longer need to do it here, where we
// did before.
//computeFoundations(component);
//component.prioritizeCandidates();
//component.eliminateRedundantCandidates();
@ -513,7 +533,7 @@ public class Agent
for (IceMediaStream stream : getStreams())
{
components.addAll( stream.getComponents());
components.addAll(stream.getComponents());
}
harvesters.harvest(components, trickleCallback);
@ -551,8 +571,10 @@ public class Agent
//trigger a check for those candidate pairs.
if(this.preDiscoveredPairsQueue.size() > 0)
{
logger.info("Trigger checks for pairs that were received " +
"before running state");
logger.info(
"Trigger checks for pairs that were received before "
+ "running state");
Iterator<CandidatePair> it = preDiscoveredPairsQueue.iterator();
while(it.hasNext())
@ -747,13 +769,11 @@ public class Agent
* @param component the component whose candidate foundations we'd like to
* compute and assign.
*/
private void computeFoundations(Component component)
{
List<LocalCandidate> candidates = component.getLocalCandidates();
for (Candidate<?> cand : candidates)
foundationsRegistry.assignFoundation(cand);
}
// private void computeFoundations(Component component)
// {
// for (Candidate<?> localCandidate : component.getLocalCandidates())
// foundationsRegistry.assignFoundation(localCandidate);
// }
/**
* 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=");
buff.append(getStreamCount()).append(" ice-pwd:")
.append(getLocalPassword());
buff.append(getStreamCount()).append(" ice-ufrag:")
.append(getLocalUfrag());
buff.append(getStreamCount()).append(" tie-breaker:")
.append(getTieBreaker());
buff.append(getStreamCount());
buff.append(" ice-pwd:").append(getLocalPassword());
buff.append(" ice-ufrag:").append(getLocalUfrag());
buff.append(" tie-breaker:").append(getTieBreaker());
buff.append("):\n");
for(IceMediaStream stream : getStreams())
buff.append(stream.toString()).append("\n");
buff.append(stream).append("\n");
return buff.toString();
}
@ -1154,8 +1172,7 @@ public class Agent
//in case we have already initialized our check lists we'd need to
//recompute pair priorities.
List<IceMediaStream> streams = getStreams();
for(IceMediaStream stream : streams)
for(IceMediaStream stream : getStreams())
{
CheckList list = stream.getCheckList();
@ -1205,16 +1222,13 @@ public class Agent
*/
public LocalCandidate findLocalCandidate(TransportAddress localAddress)
{
Collection<IceMediaStream> streamsCollection = mediaStreams.values();
for( IceMediaStream stream : streamsCollection)
for(IceMediaStream stream : mediaStreams.values())
{
LocalCandidate cnd = stream.findLocalCandidate(localAddress);
if(cnd != null)
return cnd;
}
return null;
}
@ -1229,24 +1243,25 @@ public class Agent
* <tt>localAddress</tt> if it belongs to any of this {@link Agent}'s
* streams or <tt>null</tt> if it doesn't.
*/
public LocalCandidate findLocalCandidate(TransportAddress localAddress,
String ufrag)
public LocalCandidate findLocalCandidate(
TransportAddress localAddress,
String ufrag)
{
Collection<IceMediaStream> streamsCollection = mediaStreams.values();
for(IceMediaStream stream : streamsCollection)
for(IceMediaStream stream : mediaStreams.values())
{
for(Component c : stream.getComponents())
{
for(LocalCandidate cnd : c.getLocalCandidates())
{
if(cnd != null && cnd.getUfrag() != null &&
cnd.getUfrag().equals(ufrag))
if(cnd != null
&& cnd.getUfrag() != null
&& cnd.getUfrag().equals(ufrag))
{
return cnd;
}
}
}
}
return null;
}
@ -1263,16 +1278,13 @@ public class Agent
*/
public RemoteCandidate findRemoteCandidate(TransportAddress remoteAddress)
{
Collection<IceMediaStream> streamsCollection = mediaStreams.values();
for( IceMediaStream stream : streamsCollection)
for(IceMediaStream stream : mediaStreams.values())
{
RemoteCandidate cnd = stream.findRemoteCandidate(remoteAddress);
if(cnd != null)
return cnd;
}
return null;
}
@ -1295,19 +1307,15 @@ public class Agent
{
synchronized(mediaStreams)
{
Collection<IceMediaStream> streamsCollection
= mediaStreams.values();
for (IceMediaStream stream : streamsCollection)
for (IceMediaStream stream : mediaStreams.values())
{
CandidatePair pair
= stream.findCandidatePair(localAddress, remoteAddress);
if( pair != null )
if (pair != null )
return pair;
}
}
return null;
}
@ -1327,19 +1335,15 @@ public class Agent
{
synchronized(mediaStreams)
{
Collection<IceMediaStream> streamsCollection
= mediaStreams.values();
for (IceMediaStream stream : streamsCollection)
for (IceMediaStream stream : mediaStreams.values())
{
CandidatePair pair
= stream.findCandidatePair(localUFrag, remoteUFrag);
if( pair != null )
if (pair != null )
return pair;
}
}
return null;
}
@ -1755,23 +1759,22 @@ public class Agent
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
&& ! StackProperties.getBoolean(
StackProperties.NO_KEEP_ALIVES, false))
&& !StackProperties.getBoolean(
StackProperties.NO_KEEP_ALIVES,
false))
{
// schedule STUN checks for selected candidates
scheduleSTUNKeepAlive();
scheduleStunKeepAlive();
}
if(compatibilityMode == CompatibilityMode.RFC5245)
{
if (compatibilityMode == CompatibilityMode.RFC5245)
scheduleTermination();
}
//print logs for the types of addresses we chose.
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)
{
stunKeepAliveThread = new StunKeepAliveThread();
stunKeepAliveThread
= new Thread()
{
@Override
public void run()
{
runInStunKeepAliveThread();
}
};
stunKeepAliveThread.setDaemon(true);
stunKeepAliveThread.setName("StunKeepAliveThread");
stunKeepAliveThread.start();
}
}
@ -2101,7 +2115,7 @@ public class Agent
shutdown = true;
//stop sending keep alives (STUN Binding Indications).
if(stunKeepAliveThread != null)
if (stunKeepAliveThread != null)
stunKeepAliveThread.interrupt();
//stop responding to STUN Binding Requests.
@ -2113,26 +2127,35 @@ public class Agent
*/
IceProcessingState state = getState();
if ( !IceProcessingState.FAILED.equals(state)
if (!IceProcessingState.FAILED.equals(state)
&& !IceProcessingState.TERMINATED.equals(state))
{
terminate(IceProcessingState.TERMINATED);
}
logger.info("remove streams");
// Free its IceMediaStreams, Components and Candidates.
for(IceMediaStream stream : getStreams())
boolean interrupted = false;
logger.info("remove streams");
for (IceMediaStream stream : getStreams())
{
try
{
removeStream(stream);
logger.info("remove stream " + stream.getName());
}
catch(Throwable t)
catch (Throwable t)
{
logger.info("remove stream failed: " + t);
logger.info(
"remove stream " + stream.getName() + " failed: " + t);
if (t instanceof InterruptedException)
interrupted = true;
else if (t instanceof ThreadDeath)
throw (ThreadDeath) t;
}
logger.info("remove stream " + stream.getName());
}
if (interrupted)
Thread.currentThread().interrupt();
getStunStack().shutDown();
@ -2173,63 +2196,30 @@ public class Agent
return compatibilityMode;
}
/**
* Thread that performs STUN keep-alive once ICE has COMPLETED.
*/
private class StunKeepAliveThread
extends Thread
{
/**
* Creates a new termination timer.
*/
private StunKeepAliveThread()
{
super("StunKeepAliveThread");
}
/**
* Thread entry to point.
*/
@Override
public synchronized void run()
{
runInStunKeepAliveThread();
}
}
/**
* Schedule STUN checks for selected pair.
*/
public void runInStunKeepAliveThread()
private void runInStunKeepAliveThread()
{
while(state == IceProcessingState.COMPLETED || state ==
IceProcessingState.TERMINATED)
while (runInStunKeepAliveThreadCondition())
{
if(shutdown)
break;
List<IceMediaStream> streams = getStreams();
for(IceMediaStream stream : streams)
for(IceMediaStream stream : getStreams())
{
List<Component> cmps = stream.getComponents();
for(Component cmp : cmps)
for(Component component : stream.getComponents())
{
CandidatePair pair = cmp.getSelectedPair();
CandidatePair pair = component.getSelectedPair();
if(pair != null)
{
if(compatibilityMode == CompatibilityMode.GTALK)
if(performConsentFreshness
|| (compatibilityMode
== CompatibilityMode.GTALK))
{
//apparently GTalk insists on seeing binding
//requests or else it believes we are dead
//Emil: I am not sure this is true. I think it would
//be enough for us to respond to their binding
//requests. At least that's how it seems to work for
//Chrome and WebRTC.
//TODO: check and maybe remove
connCheckClient.startCheckForPair(pair);
connCheckClient.startCheckForPair(
pair,
CONSENT_FRESHNESS_WAIT_INTERVAL,
CONSENT_FRESHNESS_WAIT_INTERVAL,
CONSENT_FRESHNESS_MAX_RETRANSMISSIONS);
}
else if(compatibilityMode == CompatibilityMode.RFC5245)
{
@ -2239,7 +2229,7 @@ public class Agent
}
}
if(shutdown)
if (!runInStunKeepAliveThreadCondition())
break;
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)
{
CandidatePair candidatePair = this.getSelectedPair(streamName);
if(candidatePair != null)
{
return candidatePair.getLocalCandidate();
}
return null;
CandidatePair candidatePair = getSelectedPair(streamName);
return
(candidatePair == null) ? null : candidatePair.getLocalCandidate();
}
/**
@ -2312,12 +2316,10 @@ public class Agent
*/
public RemoteCandidate getSelectedRemoteCandidate(String streamName)
{
CandidatePair candidatePair = this.getSelectedPair(streamName);
if(candidatePair != null)
{
return candidatePair.getRemoteCandidate();
}
return null;
CandidatePair candidatePair = getSelectedPair(streamName);
return
(candidatePair == null) ? null : candidatePair.getRemoteCandidate();
}
/**
@ -2367,8 +2369,8 @@ public class Agent
{
if(harvester.getClass().getName().endsWith(harvesterName))
{
harvestingTime = harvester.getHarvestStatistics()
.getHarvestDuration();
harvestingTime
= harvester.getHarvestStatistics().getHarvestDuration();
// There may be several harvester with the same class name.
// Thus, returns only an active one (if any).
if(harvestingTime != 0)
@ -2423,8 +2425,8 @@ public class Agent
for(CandidateHarvester harvester : harvesters)
{
harvestDuration += harvester
.getHarvestStatistics().getHarvestDuration();
harvestDuration
+= harvester.getHarvestStatistics().getHarvestDuration();
}
return harvestDuration;
@ -2444,10 +2446,34 @@ public class Agent
for(CandidateHarvester harvester : harvesters)
{
harvestCount += harvester
.getHarvestStatistics().getHarvestDuration();
harvestCount
+= harvester.getHarvestStatistics().getHarvestDuration();
}
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.
*
* @author Emil Ivov
* @author Lyubomir Marinov
*/
public class 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
* optimizing performance.
@ -94,6 +102,11 @@ public class CandidatePair
*/
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>
* to <tt>remoteCandidate</tt>.
@ -264,25 +277,32 @@ public class CandidatePair
this.state = newState;
if(newState != CandidatePairState.IN_PROGRESS)
if(newState == CandidatePairState.IN_PROGRESS)
{
if (tranID != null)
if (tranID == null)
{
throw new IllegalArgumentException(
"How could you have a transaction for a pair"
+ " that's not in the In-Progress state?");
"Putting a pair into the In-Progress state MUST be"
+ " accomapnied with the TransactionID of the"
+ " connectivity check.");
}
}
else
{
if (tranID == null)
throw new IllegalArgumentException("Putting a pair into the "
+"In-Progress state MUST be accomapnied with "
+"the TransactionID of the conn check.");
if (tranID != null)
{
throw new IllegalArgumentException(
"How could you have a transaction for a pair that's not"
+ " in the In-Progress state?");
}
}
this.connCheckTranID = tranID;
getParentComponent().getParentStream().firePairPropertyChange(
this, IceMediaStream.PROPERTY_PAIR_STATE_CHANGED,
oldState, newState);
this,
IceMediaStream.PROPERTY_PAIR_STATE_CHANGED,
oldState,
newState);
}
/**
@ -395,39 +415,32 @@ public class CandidatePair
long thisPri = getPriority();
long otherPri = candidatePair.getPriority();
return (thisPri < otherPri
? 1
: (thisPri==otherPri
? 0
: -1));
return (thisPri < otherPri) ? 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>false</tt> otherwise.
*
* @param targetPair the <tt>Object</tt> that we'd like to compare this
* target pair to.
*
* @param obj the <tt>Object</tt> that we'd like to compare this pair to.
* @return <tt>true</tt> if pairs have equal local and equal remote
* candidates and <tt>false</tt> otherwise.
*/
public boolean equals(Object targetPair)
@Override
public boolean equals(Object obj)
{
if (! (targetPair instanceof CandidatePair)
|| targetPair == null
|| !localCandidate.equals(((CandidatePair)targetPair)
.localCandidate)
|| !remoteCandidate.equals(((CandidatePair)targetPair)
.remoteCandidate))
if ((obj == null) || !(obj instanceof CandidatePair))
return false;
CandidatePair candidatePair = (CandidatePair) obj;
//DO NOT change this method to also depend on other pair properties
//because the Conn Check Client counts on it only using the candidates
//for comparisons.
return true;
return
localCandidate.equals(candidatePair.localCandidate)
&& remoteCandidate.equals(candidatePair.remoteCandidate);
}
/**
@ -435,12 +448,13 @@ public class CandidatePair
*
* @return a String representation of the object.
*/
@Override
public String toString()
{
return "CandidatePair (State=" + getState()
+ " Priority=" + getPriority()
+ "):\n\tLocalCandidate=" + getLocalCandidate()
+ "\n\tRemoteCandidate=" + getRemoteCandidate();
return
"CandidatePair (State=" + getState() + " Priority=" + getPriority()
+ "):\n\tLocalCandidate=" + getLocalCandidate()
+ "\n\tRemoteCandidate=" + getRemoteCandidate();
}
/**
@ -504,6 +518,7 @@ public class CandidatePair
* @see java.lang.Object#equals(java.lang.Object)
* @see java.lang.Object#hashCode()
*/
@Override
public boolean equals(Object obj)
{
return obj instanceof PairComparator;
@ -584,8 +599,11 @@ public class CandidatePair
public void nominate()
{
this.isNominated = true;
getParentComponent().getParentStream().firePairPropertyChange(this,
IceMediaStream.PROPERTY_PAIR_NOMINATED, false, true);
getParentComponent().getParentStream().firePairPropertyChange(
this,
IceMediaStream.PROPERTY_PAIR_NOMINATED,
false,
true);
}
/**
@ -619,7 +637,56 @@ public class CandidatePair
protected void validate()
{
this.isValid = true;
getParentComponent().getParentStream().firePairPropertyChange(this,
IceMediaStream.PROPERTY_PAIR_VALIDATED, false, true);
getParentComponent().getParentStream().firePairPropertyChange(
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
* an indication
*/
protected void sendBindingIndicationForPair(
CandidatePair candidatePair)
protected void sendBindingIndicationForPair(CandidatePair candidatePair)
{
LocalCandidate localCandidate = candidatePair.getLocalCandidate();
Indication indication = MessageFactory.createBindingIndication();
TransactionID tran = TransactionID.createNewTransactionID();
tran.setApplicationData(candidatePair);
try
{
TransportAddress localAddr = localCandidate.getBase().
getTransportAddress();
stunStack.sendIndication(
indication,
candidatePair
.getRemoteCandidate().getTransportAddress(),
localAddr);
indication,
candidatePair.getRemoteCandidate().getTransportAddress(),
localCandidate.getBase().getTransportAddress());
if(logger.isLoggable(Level.FINEST))
{
logger.finest(
@ -140,14 +131,15 @@ class ConnectivityCheckClient
catch (Exception ex)
{
IceSocketWrapper stunSocket = localCandidate.getStunSocket(null);
if(stunSocket != null)
{
logger.log(
Level.INFO,
"Failed to send " + indication
+ " through " + stunSocket.getLocalSocketAddress(),
ex);
stunSocket = null;
tran = null;
Level.INFO,
"Failed to send " + indication + " through "
+ stunSocket.getLocalSocketAddress(),
ex);
}
}
}
@ -165,6 +157,30 @@ class ConnectivityCheckClient
* failed for some reason.
*/
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();
//we don't need to do a canReach() verification here as it has been
@ -175,25 +191,23 @@ class ConnectivityCheckClient
if(parentAgent.getCompatibilityMode() == CompatibilityMode.GTALK)
{
/* Google Talk ICE dialect just need the username */
String localUserName = parentAgent.generateLocalUserName(
candidatePair.getRemoteCandidate(),
candidatePair.getLocalCandidate());
UsernameAttribute unameAttr =
AttributeFactory.createUsernameAttribute(localUserName);
String localUserName
= parentAgent.generateLocalUserName(
candidatePair.getRemoteCandidate(),
candidatePair.getLocalCandidate());
UsernameAttribute unameAttr
= AttributeFactory.createUsernameAttribute(localUserName);
request.addAttribute(unameAttr);
if (parentAgent.isControlling())
//if we are the controlling agent then we need to indicate our
//nominated pairs.
if (parentAgent.isControlling() && candidatePair.isNominated())
{
//if we are the controlling agent then we need to indicate our
//nominated pairs.
if(candidatePair.isNominated())
{
logger.fine("set useCandidateSent for " +
candidatePair.toShortString());
candidatePair.setUseCandidateSent();
}
logger.fine(
"set useCandidateSent for "
+ candidatePair.toShortString());
candidatePair.setUseCandidateSent();
}
}
else
@ -201,8 +215,8 @@ class ConnectivityCheckClient
//the priority we'd like the remote party to use for a peer
//reflexive candidate if one is discovered as a consequence of this
//check.
PriorityAttribute priority =
AttributeFactory.createPriorityAttribute(
PriorityAttribute priority
= AttributeFactory.createPriorityAttribute(
localCandidate.computePriorityForType(
CandidateType.PEER_REFLEXIVE_CANDIDATE));
@ -211,102 +225,102 @@ class ConnectivityCheckClient
//controlling controlled
if (parentAgent.isControlling())
{
request.addAttribute(AttributeFactory
.createIceControllingAttribute(parentAgent
.getTieBreaker()));
request.addAttribute(
AttributeFactory.createIceControllingAttribute(
parentAgent.getTieBreaker()));
//if we are the controlling agent then we need to indicate our
//nominated pairs.
if(candidatePair.isNominated())
{
logger.fine("Add USE-CANDIDATE in check for: " +
candidatePair.toShortString());
request.addAttribute(AttributeFactory
.createUseCandidateAttribute());
logger.fine(
"Add USE-CANDIDATE in check for: "
+ candidatePair.toShortString());
request.addAttribute(
AttributeFactory.createUseCandidateAttribute());
}
}
else
{
request.addAttribute(AttributeFactory
.createIceControlledAttribute(parentAgent
.getTieBreaker()));
request.addAttribute(
AttributeFactory.createIceControlledAttribute(
parentAgent.getTieBreaker()));
}
//credentials
String localUserName = parentAgent.generateLocalUserName(
candidatePair.getParentComponent().getParentStream().
getName());
String media
= candidatePair
.getParentComponent().getParentStream().getName();
String localUserName = parentAgent.generateLocalUserName(media);
if(localUserName == null)
return null;
UsernameAttribute unameAttr =
AttributeFactory.createUsernameAttribute(localUserName);
UsernameAttribute unameAttr
= AttributeFactory.createUsernameAttribute(localUserName);
request.addAttribute(unameAttr);
// TODO Also implement SASL prepare
MessageIntegrityAttribute msgIntegrity = AttributeFactory
.createMessageIntegrityAttribute(localUserName);
MessageIntegrityAttribute msgIntegrity
= AttributeFactory.createMessageIntegrityAttribute(
localUserName);
// when we will encode the MESSAGE-INTEGRITY attribute (thus
// generate the HMAC-SHA1 authentication), we need to know the
// remote key of the current stream, that why we pass the media
// name.
msgIntegrity.setMedia(
candidatePair.getParentComponent().getParentStream().
getName());
msgIntegrity.setMedia(media);
request.addAttribute(msgIntegrity);
}
TransactionID tran = TransactionID.createNewTransactionID();
tran.setApplicationData(candidatePair);
logger.fine("start check for " + candidatePair.toShortString()
+ " tid " + tran);
logger.fine(
"start check for " + candidatePair.toShortString() + " tid "
+ tran);
try
{
TransportAddress localAddr = localCandidate.getBase().
getTransportAddress();
tran
= stunStack.sendRequest(
request,
candidatePair
.getRemoteCandidate().getTransportAddress(),
localAddr,
localCandidate.getBase().getTransportAddress(),
this,
tran);
tran,
originalWiatIterval,
maxWaitInterval,
maxRetransmissions);
if(logger.isLoggable(Level.FINEST))
{
logger.finest(
"checking pair " + candidatePair
+ " with tran=" + tran);
"checking pair " + candidatePair + " tid " + tran);
}
}
catch (Exception ex)
{
tran = null;
IceSocketWrapper stunSocket = localCandidate.getStunSocket(null);
if(stunSocket != null)
{
String msg = "Failed to send " + request
+ " through " + stunSocket.getLocalSocketAddress();
String msg
= "Failed to send " + request + " through "
+ stunSocket.getLocalSocketAddress() + ".";
if((ex instanceof NoRouteToHostException) ||
(ex.getMessage() != null &&
ex.getMessage().equals("No route to host")))
if((ex instanceof NoRouteToHostException)
|| (ex.getMessage() != null
&& ex.getMessage().equals("No route to host")))
{
msg += " No route to host";
msg += " No route to host.";
ex = null;
}
logger.log(Level.INFO, msg, ex);
}
stunSocket = null;
tran = null;
}
return tran;
@ -318,17 +332,17 @@ class ConnectivityCheckClient
* to FAILED, or SUCCEDED, or rescheduling a check in case of a role
* conflict.
*
* @param evt the {@link StunResponseEvent} that contains the newly
* received response.
* @param ev the {@link StunResponseEvent} that contains the newly received
* response.
*/
public void processResponse(StunResponseEvent evt)
public void processResponse(StunResponseEvent ev)
{
CandidatePair checkedPair
= (CandidatePair) evt.getTransactionID().getApplicationData();
= (CandidatePair) ev.getTransactionID().getApplicationData();
//make sure that the response came from the right place.
if (parentAgent.getCompatibilityMode() == CompatibilityMode.RFC5245 &&
!checkSymmetricAddresses(evt))
if (parentAgent.getCompatibilityMode() == CompatibilityMode.RFC5245
&& !checkSymmetricAddresses(ev))
{
logger.fine("Received a non-symmetric response for pair: "
+ checkedPair.toShortString() + ". Failing");
@ -336,23 +350,27 @@ class ConnectivityCheckClient
+ checkedPair.toShortString() + ", failing");
checkedPair.setStateFailed();
}
//handle error responses.
else if(evt.getResponse().getMessageType()
== Response.BINDING_ERROR_RESPONSE)
else
{
if(! evt.getResponse().containsAttribute(Attribute.ERROR_CODE))
{
logger.fine("Received a malformed error response.");
return; //malformed error response
}
Response response = ev.getResponse();
char messageType = response.getMessageType();
processErrorResponse(evt);
}
//handle success responses.
else if(evt.getResponse().getMessageType()
== Response.BINDING_SUCCESS_RESPONSE)
{
processSuccessResponse(evt);
//handle error responses.
if(messageType== Response.BINDING_ERROR_RESPONSE)
{
if(!response.containsAttribute(Attribute.ERROR_CODE))
{
logger.fine("Received a malformed error response.");
return; //malformed error response
}
processErrorResponse(ev);
}
//handle success responses.
else if(messageType == Response.BINDING_SUCCESS_RESPONSE)
{
processSuccessResponse(ev);
}
}
//Regardless of whether the check was successful or failed, the
@ -375,7 +393,7 @@ class ConnectivityCheckClient
final CheckList checkList = stream.getCheckList();
if(stream.getParentAgent().getState().equals(
IceProcessingState.COMPLETED))
IceProcessingState.COMPLETED))
return;
//If all of the pairs in the check list are now either in the Failed or
@ -441,18 +459,18 @@ class ConnectivityCheckClient
/**
* 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();
Request request = evt.getRequest();
Response response = ev.getResponse();
Request request = ev.getRequest();
CandidatePair checkedPair
= (CandidatePair) evt.getTransactionID().getApplicationData();
= (CandidatePair) ev.getTransactionID().getApplicationData();
TransportAddress mappedAddress = null;
if(this.parentAgent.getCompatibilityMode() == CompatibilityMode.GTALK)
if(parentAgent.getCompatibilityMode() == CompatibilityMode.GTALK)
{
if(response.containsAttribute(Attribute.XOR_MAPPED_ADDRESS))
{
@ -504,10 +522,11 @@ class ConnectivityCheckClient
// XXX AddressAttribute always returns UDP based TransportAddress
if(checkedPair.getLocalCandidate().getTransport() == Transport.TCP)
{
mappedAddress = new TransportAddress(
mappedAddress.getAddress(),
mappedAddress.getPort(),
Transport.TCP);
mappedAddress
= new TransportAddress(
mappedAddress.getAddress(),
mappedAddress.getPort(),
Transport.TCP);
}
LocalCandidate validLocalCandidate = null;
@ -560,10 +579,12 @@ class ConnectivityCheckClient
priority = prioAttr.getPriority();
}
LocalCandidate peerReflexiveCandidate = new PeerReflexiveCandidate(
mappedAddress, checkedPair.getParentComponent(),
checkedPair.getLocalCandidate(),
priority);
LocalCandidate peerReflexiveCandidate
= new PeerReflexiveCandidate(
mappedAddress,
checkedPair.getParentComponent(),
checkedPair.getLocalCandidate(),
priority);
peerReflexiveCandidate.setBase(checkedPair.getLocalCandidate());
@ -571,7 +592,7 @@ class ConnectivityCheckClient
//candidates for the media stream, so that it would be available for
//updated offers.
checkedPair.getParentComponent().addLocalCandidate(
peerReflexiveCandidate);
peerReflexiveCandidate);
//However, the peer reflexive candidate is not paired with other
//remote candidates. This is not necessary; a valid pair will be
@ -590,35 +611,29 @@ class ConnectivityCheckClient
}
//check if the resulting valid pair was already in our check lists.
CandidatePair existingPair = parentAgent.findCandidatePair(
validLocalCandidate.getTransportAddress(),
validRemoteCandidate.getTransportAddress());
CandidatePair existingPair
= parentAgent.findCandidatePair(
validLocalCandidate.getTransportAddress(),
validRemoteCandidate.getTransportAddress());
// RFC 5245: 7.1.3.2.2. The agent constructs a candidate pair whose
// local candidate equals the mapped address of the response, and whose
// 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.
CandidatePair validPair;
if(existingPair != null)
{
validPair = existingPair;
}
else
{
validPair = new CandidatePair(validLocalCandidate,
validRemoteCandidate);
}
CandidatePair validPair
= (existingPair == null)
? new CandidatePair(validLocalCandidate, validRemoteCandidate)
: existingPair;
// we synchronize here because the same pair object can be
// processed (in another thread) in Agent's triggerCheck.
// A controlled agent select its pair here if the pair has
// useCandidateReceived as true (set in triggerCheck) or in t
// triggerCheck if the pair state is succeeded (set here). So be
// sure that if a binding response and a binding request (for
// the same check) from other peer come at the very same time,
// that we will trigger the nominationConfirmed (that will
// pass the pair as selected if it is the first time).
// we synchronize here because the same pair object can be processed (in
// another thread) in Agent's triggerCheck. A controlled agent select
// its pair here if the pair has useCandidateReceived as true (set in
// triggerCheck) or in triggerCheck if the pair state is succeeded (set
// here). So be sure that if a binding response and a binding request
// (for the same check) from other peer come at the very same time, that
// we will trigger the nominationConfirmed (that will pass the pair as
// as selected if it is the first time).
synchronized(checkedPair)
{
//The agent sets the state of the pair that *generated* the check to
@ -647,15 +662,16 @@ class ConnectivityCheckClient
= new Vector<CandidatePair>(parentStream.getCheckList());
for(CandidatePair pair : parentCheckList)
if ((pair.getState() == CandidatePairState.FROZEN) &&
(checkedPair.getFoundation().equals(pair.getFoundation())))
if ((pair.getState() == CandidatePairState.FROZEN)
&& checkedPair.getFoundation().equals(
pair.getFoundation()))
pair.setStateWaiting();
}
// The agent examines the check list for all other streams in turn
// If the check list is active, the agent changes the state of
// all Frozen pairs in that check list whose foundation matches a
// pair in the valid list under consideration to Waiting.
// The agent examines the check list for all other streams in turn. If
// the check list is active, the agent changes the state of all Frozen
// pairs in that check list whose foundation matches a pair in the valid
// list under consideration to Waiting.
List<IceMediaStream> allOtherStreams = parentAgent.getStreams();
allOtherStreams.remove(parentStream);
@ -669,8 +685,8 @@ class ConnectivityCheckClient
for(CandidatePair pair : checkList)
{
if (parentStream.validListContainsFoundation(
pair.getFoundation())
&& pair.getState() == CandidatePairState.FROZEN)
pair.getFoundation())
&& pair.getState() == CandidatePairState.FROZEN)
{
pair.setStateWaiting();
}
@ -705,22 +721,22 @@ class ConnectivityCheckClient
//CANDIDATE attribute in the Binding request, the valid pair generated
//from that check has its nominated flag set to true.
if((parentAgent.isControlling()
&& request.containsAttribute(Attribute.USE_CANDIDATE)) ||
((parentAgent.getCompatibilityMode() ==
CompatibilityMode.GTALK) &&
validPair.isNominated()))
//checkedPair.useCandidateSent()))
&& request.containsAttribute(Attribute.USE_CANDIDATE))
|| ((parentAgent.getCompatibilityMode()
== CompatibilityMode.GTALK)
&& validPair.isNominated()))
{
if(validPair.getParentComponent().getSelectedPair() == null)
{
logger.info("Nomination confirmed for pair: " +
validPair.toShortString());
logger.info(
"Nomination confirmed for pair: "
+ validPair.toShortString());
parentAgent.nominationConfirmed( validPair );
}
else
{
logger.fine("Keep alive for pair: " +
validPair.toShortString());
logger.fine(
"Keep alive for pair: " + validPair.toShortString());
}
}
//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
//Section 7.2.1.5, and may now result in setting the nominated flag for
//the pair learned from the original request.
else if(!parentAgent.isControlling() &&
checkedPair.useCandidateReceived() &&
!checkedPair.isNominated())
else if(!parentAgent.isControlling()
&& checkedPair.useCandidateReceived()
&& !checkedPair.isNominated())
{
if(checkedPair.getParentComponent().getSelectedPair() == null)
{
logger.info("Nomination confirmed for pair: " +
validPair.toShortString());
logger.info(
"Nomination confirmed for pair: "
+ validPair.toShortString());
parentAgent.nominationConfirmed( checkedPair );
}
else
{
logger.fine("Keep alive for pair: " +
validPair.toShortString());
logger.fine(
"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)
{
CandidatePair pair = ((CandidatePair)evt.getTransactionID()
.getApplicationData());
TransportAddress localAddr = pair.getLocalCandidate().getBase().
getTransportAddress();
CandidatePair pair
= ((CandidatePair) evt.getTransactionID().getApplicationData());
TransportAddress localAddr
= pair.getLocalCandidate().getBase().getTransportAddress();
boolean sym = localAddr.equals(evt.getLocalAddress())
&& pair.getRemoteCandidate().getTransportAddress()
.equals(evt.getRemoteAddress());
return sym;
return
localAddr.equals(evt.getLocalAddress())
&& pair.getRemoteCandidate().getTransportAddress().equals(
evt.getRemoteAddress());
}
/**
@ -785,15 +805,15 @@ class ConnectivityCheckClient
* reschedules the check, in all other cases sets the corresponding peer
* 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();
Request originalRequest = evt.getRequest();
Response response = ev.getResponse();
Request originalRequest = ev.getRequest();
ErrorCodeAttribute errorAttr = (ErrorCodeAttribute)response.
getAttribute(Attribute.ERROR_CODE);
ErrorCodeAttribute errorAttr
= (ErrorCodeAttribute) response.getAttribute(Attribute.ERROR_CODE);
// GTalk error code is not RFC3489/RFC5389 compliant
// example: 400 becomes 0x01 0x90 with GTalk
// RFC3489/RFC5389 gives 0x04 0x00
@ -801,16 +821,16 @@ class ConnectivityCheckClient
int co = errorAttr.getErrorNumber() & 0xff;
char errorCode = errorAttr.getErrorCode();
CandidatePair pair = ((CandidatePair)evt.getTransactionID()
.getApplicationData());
CandidatePair pair
= (CandidatePair) ev.getTransactionID().getApplicationData();
logger.finer("Received error code " + ((int) errorCode));
//RESOLVE ROLE_CONFLICTS
if(errorCode == ErrorCodeAttribute.ROLE_CONFLICT)
{
boolean wasControlling = originalRequest
.containsAttribute(Attribute.ICE_CONTROLLING);
boolean wasControlling
= originalRequest.containsAttribute(Attribute.ICE_CONTROLLING);
logger.finer("Swithing to isControlling=" + !wasControlling);
parentAgent.setControlling(!wasControlling);
@ -818,8 +838,9 @@ class ConnectivityCheckClient
pair.getParentComponent().getParentStream().getCheckList()
.scheduleTriggeredCheck(pair);
}
else if(parentAgent.getCompatibilityMode() == CompatibilityMode.GTALK &&
cl == 1 && co == 0xae) // STALE_CREDENTIALS (430)
else if(parentAgent.getCompatibilityMode() == CompatibilityMode.GTALK
&& cl == 1
&& co == 0xae) // STALE_CREDENTIALS (430)
{
// it may be an error due to remote peer that does not processed
// 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
* 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.
*/
public void processTimeout(StunTimeoutEvent event)
public void processTimeout(StunTimeoutEvent ev)
{
CandidatePair pair = ((CandidatePair)event.getTransactionID()
.getApplicationData());
CandidatePair pair
= (CandidatePair) ev.getTransactionID() .getApplicationData();
logger.info("timeout for pair: " + pair.toShortString() + ", failing.");
pair.setStateFailed();
updateCheckListAndTimerStates(pair);
@ -983,8 +1005,9 @@ class ConnectivityCheckClient
if(transactionID == null)
{
logger.info("Pair failed: " +
pairToCheck.toShortString());
logger.info(
"Pair failed: "
+ pairToCheck.toShortString());
pairToCheck.setStateFailed();
}
else
@ -1017,7 +1040,7 @@ class ConnectivityCheckClient
}
/**
* Stops and removes all PaceMakers.
* Stops and removes all <tt>PaceMaker</tt>s.
*/
public void stop()
{

View File

@ -21,8 +21,8 @@ public class DefaultNominator
/**
* The logger.
*/
private static Logger logger =
Logger.getLogger(DefaultNominator.class.getName());
private static final Logger logger
= Logger.getLogger(DefaultNominator.class.getName());
/**
* The Agent that created us.
@ -39,8 +39,8 @@ public class DefaultNominator
* Map that will remember association between validated relayed candidate
* and a timer. It is use with the NOMINATE_FIRST_HIGHEST_VALID strategy.
*/
private Map<String, TimerTask> validatedCandidates =
new HashMap<String, TimerTask>();
private final Map<String, TimerTask> validatedCandidates
= new HashMap<String, TimerTask>();
/**
* 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
* 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.
*/
public void propertyChange(PropertyChangeEvent evt)
public void propertyChange(PropertyChangeEvent ev)
{
if(Agent.PROPERTY_ICE_PROCESSING_STATE.equals(evt.getPropertyName()))
{
IceProcessingState newState = (IceProcessingState)evt.getNewValue();
String propertyName = ev.getPropertyName();
if(newState != IceProcessingState.RUNNING)
if(Agent.PROPERTY_ICE_PROCESSING_STATE.equals(propertyName))
{
if(ev.getNewValue() != IceProcessingState.RUNNING)
return;
List<IceMediaStream> streams = parentAgent.getStreams();
for(IceMediaStream stream : streams)
for(IceMediaStream stream : parentAgent.getStreams())
{
stream.addPairChangeListener(this);
stream.getCheckList().addStateChangeListener(this);
@ -81,33 +79,37 @@ public class DefaultNominator
}
if (!parentAgent.isControlling() //CONTROLLED agents cannot nominate
|| strategy == NominationStrategy.NONE)
|| strategy == NominationStrategy.NONE)
{
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
// the component
if(validPair.getParentComponent().getSelectedPair() != null)
{
logger.fine("Keep-alive for pair: " +
validPair.toShortString());
logger.fine(
"Keep-alive for pair: " + validPair.toShortString());
return;
}
}
if(strategy == NominationStrategy.NOMINATE_FIRST_VALID)
strategyNominateFirstValid(evt);
if (strategy == NominationStrategy.NOMINATE_FIRST_VALID)
strategyNominateFirstValid(ev);
else if (strategy == NominationStrategy.NOMINATE_HIGHEST_PRIO)
strategyNominateHighestPrio(evt);
else if (strategy ==
NominationStrategy.NOMINATE_FIRST_HOST_OR_REFLEXIVE_VALID)
strategyNominateFirstHostOrReflexiveValid(evt);
strategyNominateHighestPrio(ev);
else if (strategy
== NominationStrategy.NOMINATE_FIRST_HOST_OR_REFLEXIVE_VALID)
strategyNominateFirstHostOrReflexiveValid(ev);
}
/**
@ -133,18 +135,18 @@ public class DefaultNominator
* pairs in a check list to conclude before nominating the one with the
* 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}.
*/
private void strategyNominateHighestPrio(PropertyChangeEvent evt)
private void strategyNominateHighestPrio(PropertyChangeEvent ev)
{
String propName = evt.getPropertyName();
if(IceMediaStream.PROPERTY_PAIR_VALIDATED.equals(propName)
|| (IceMediaStream.PROPERTY_PAIR_STATE_CHANGED.equals(propName)
&& ((CandidatePairState)evt.getNewValue())
== CandidatePairState.FAILED))
String pname = ev.getPropertyName();
if(IceMediaStream.PROPERTY_PAIR_VALIDATED.equals(pname)
|| (IceMediaStream.PROPERTY_PAIR_STATE_CHANGED.equals(pname)
&& (ev.getNewValue() == CandidatePairState.FAILED)))
{
CandidatePair validPair = (CandidatePair)evt.getSource();
CandidatePair validPair = (CandidatePair) ev.getSource();
Component parentComponent = validPair.getParentComponent();
IceMediaStream parentStream = parentComponent.getParentStream();
CheckList parentCheckList = parentStream.getCheckList();
@ -152,15 +154,15 @@ public class DefaultNominator
if(!parentCheckList.allChecksCompleted())
return;
List<Component> components = parentStream.getComponents();
for(Component component : components)
for(Component component : parentStream.getComponents())
{
CandidatePair pair = parentStream.getValidPair(component);
if(pair != null)
{
logger.info("Nominate (highest priority): " +
validPair.toShortString());
logger.info(
"Nominate (highest priority): "
+ validPair.toShortString());
parentAgent.nominate(pair);
}
}
@ -194,21 +196,22 @@ public class DefaultNominator
{
if(IceMediaStream.PROPERTY_PAIR_VALIDATED.equals(evt.getPropertyName()))
{
CandidatePair validPair = (CandidatePair)evt.getSource();
CandidatePair validPair = (CandidatePair) evt.getSource();
TimerTask task = null;
boolean isRelayed =
(validPair.getLocalCandidate() instanceof RelayedCandidate) ||
validPair.getLocalCandidate().getType().equals(
CandidateType.RELAYED_CANDIDATE) ||
validPair.getRemoteCandidate().getType().equals(
CandidateType.RELAYED_CANDIDATE);
Component component = validPair.getParentComponent();
LocalCandidate localCandidate = validPair.getLocalCandidate();
boolean isRelayed
= (localCandidate instanceof RelayedCandidate)
|| localCandidate.getType().equals(
CandidateType.RELAYED_CANDIDATE)
|| validPair.getRemoteCandidate().getType().equals(
CandidateType.RELAYED_CANDIDATE);
boolean nominate = false;
synchronized(validatedCandidates)
{
task = validatedCandidates.get(
validPair.getParentComponent().toShortString());
TimerTask task
= validatedCandidates.get(component.toShortString());
if(isRelayed && task == null)
{
@ -221,9 +224,7 @@ public class DefaultNominator
logger.info("Wait timeout to nominate relayed candidate");
timer.schedule(task, 0);
validatedCandidates.put(
validPair.getParentComponent().toShortString(),
task);
validatedCandidates.put(component.toShortString(), task);
}
else if(!isRelayed)
{
@ -232,13 +233,13 @@ public class DefaultNominator
{
task.cancel();
logger.info(
"Found a better candidate pair to nominate for "
+ validPair.getParentComponent().
toShortString());
"Found a better candidate pair to nominate for "
+ component.toShortString());
}
logger.info("Nominate (first highest valid): " +
validPair.toShortString());
logger.info(
"Nominate (first highest valid): "
+ validPair.toShortString());
nominate = true;
}
}
@ -269,9 +270,9 @@ public class DefaultNominator
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.
@ -306,18 +307,20 @@ public class DefaultNominator
if(c != pair && c.getState() != CandidatePairState.FAILED)
{
allFailed = false;
break;
}
}
}
if(allFailed && ! pair.isNominated())
if(allFailed && !pair.isNominated())
{
// all other pairs are failed to do not waste time, cancel
// timer and nominate ourself (the relayed candidate).
this.cancel();
logger.info("Nominate (first highest valid): " +
pair.toShortString());
logger.info(
"Nominate (first highest valid): "
+ pair.toShortString());
parentAgent.nominate(pair);
}
}
@ -328,7 +331,7 @@ public class DefaultNominator
@Override
public boolean cancel()
{
canceled = true;
cancelled = true;
return super.cancel();
}
@ -343,23 +346,22 @@ public class DefaultNominator
}
catch(InterruptedException e)
{
canceled = true;
cancelled = true;
}
pair.getParentComponent().getParentStream().getCheckList().
removeChecksListener(this);
validatedCandidates.remove(
pair.getParentComponent().toShortString());
Component component = pair.getParentComponent();
if(canceled)
{
component.getParentStream().getCheckList().removeChecksListener(
this);
validatedCandidates.remove(component.toShortString());
if(cancelled)
return;
}
logger.info("Nominate (first highest valid): " +
pair.toShortString());
logger.info(
"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
parentAgent.nominate(pair);
}

View File

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

View File

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

View File

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

View File

@ -7,6 +7,7 @@
package org.ice4j.stack;
import java.io.*;
import java.util.concurrent.*;
import java.util.logging.*;
import org.ice4j.*;
@ -31,6 +32,7 @@ import org.ice4j.message.*;
*
* @author Emil Ivov.
* @author Pascal Mogeri (contributed configuration of client transactions).
* @author Lyubomir Marinov
*/
class StunClientTransaction
implements Runnable
@ -38,8 +40,8 @@ class StunClientTransaction
/**
* Our class logger.
*/
private static final Logger logger =
Logger.getLogger(StunClientTransaction.class.getName());
private static final Logger logger
= Logger.getLogger(StunClientTransaction.class.getName());
/**
* 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;
/**
* 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
* response is received after MAX_WAIT_INTERVAL milliseconds the request is
@ -54,25 +110,12 @@ class StunClientTransaction
*/
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
* request.
*/
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
* doubling its value.
@ -126,11 +169,6 @@ class StunClientTransaction
*/
private boolean cancelled = false;
/**
* The thread that this transaction runs in.
*/
private Thread retransmissionsThread = null;
/**
* Creates a client transaction.
*
@ -148,8 +186,12 @@ class StunClientTransaction
TransportAddress localAddress,
ResponseCollector responseCollector)
{
this(stackCallback, request, requestDestination, localAddress,
responseCollector, TransactionID.createNewTransactionID());
this(stackCallback,
request,
requestDestination,
localAddress,
responseCollector,
TransactionID.createNewTransactionID());
}
/**
@ -189,15 +231,12 @@ class StunClientTransaction
}
catch (StunException ex)
{
//Shouldn't happen so lets just through a runtime exception in
//case anything is real messed up
throw new IllegalArgumentException("The TransactionID class "
+"generated an invalid transaction ID");
//Shouldn't happen so lets just through a runtime exception in case
//anything is real messed up
throw new IllegalArgumentException(
"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()
{
retransmissionsThread.setName("ice4j.ClientTransaction");
nextWaitInterval = originalWaitInterval;
synchronized(this)
@ -245,14 +283,15 @@ class StunClientTransaction
//I wonder whether we should notify anyone that a
//retransmission has failed
logger.log(Level.INFO,
"A client tran retransmission failed", ex);
"A client tran retransmission failed",
ex);
}
}
//before stating that a transaction has timeout-ed we should first
//wait for a reception of the response
if(nextWaitInterval < maxWaitInterval)
nextWaitInterval *= 2;
nextWaitInterval *= 2;
waitFor(nextWaitInterval);
@ -280,13 +319,12 @@ class StunClientTransaction
void sendRequest()
throws IllegalArgumentException, IOException
{
logger.fine("sending STUN "
+ " tid " + transactionID
+ " from " + localAddress
+ " to " + requestDestination);
logger.fine(
"sending STUN " + " tid " + transactionID + " from "
+ localAddress + " to " + requestDestination);
sendRequest0();
retransmissionsThread.start();
retransmissionThreadPool.execute(this);
}
/**
@ -303,13 +341,14 @@ class StunClientTransaction
if(cancelled)
{
logger.finer("Trying to resend a cancelled transaction.");
return;
}
stackCallback.getNetAccessManager().sendMessage(
this.request,
localAddress,
requestDestination);
else
{
stackCallback.getNetAccessManager().sendMessage(
this.request,
localAddress,
requestDestination);
}
}
/**
@ -395,8 +434,8 @@ class StunClientTransaction
}
/**
* Init transaction duration/retransmission parameters.
* (Mostly, contributed by Pascal Maugeri).
* Init transaction duration/retransmission parameters. (Mostly contributed
* by Pascal Maugeri.)
*/
private void initTransactionConfiguration()
{
@ -405,7 +444,8 @@ class StunClientTransaction
= System.getProperty(StackProperties.MAX_CTRAN_RETRANSMISSIONS);
if(maxRetransmissionsStr != null
&& maxRetransmissionsStr.trim().length() > 0){
&& maxRetransmissionsStr.trim().length() > 0)
{
try
{
maxRetransmissions = Integer.parseInt(maxRetransmissionsStr);
@ -424,7 +464,8 @@ class StunClientTransaction
= System.getProperty(StackProperties.FIRST_CTRAN_RETRANS_AFTER);
if(originalWaitIntervalStr != null
&& originalWaitIntervalStr.trim().length() > 0){
&& originalWaitIntervalStr.trim().length() > 0)
{
try
{
originalWaitInterval
@ -444,7 +485,8 @@ class StunClientTransaction
= System.getProperty(StackProperties.MAX_CTRAN_RETRANS_TIMER);
if(maxWaitIntervalStr != null
&& maxWaitIntervalStr.trim().length() > 0){
&& maxWaitIntervalStr.trim().length() > 0)
{
try
{
maxWaitInterval = Integer.parseInt(maxWaitIntervalStr);

View File

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

View File

@ -344,19 +344,17 @@ public class StunStack
}
catch (IllegalArgumentException iaex)
{
throw
new StunException(
StunException.ILLEGAL_ARGUMENT,
"Failed to send STUN indication: " + indication,
iaex);
throw new StunException(
StunException.ILLEGAL_ARGUMENT,
"Failed to send STUN indication: " + indication,
iaex);
}
catch (IOException ioex)
{
throw
new StunException(
StunException.NETWORK_ERROR,
"Failed to send STUN indication: " + indication,
ioex);
throw new StunException(
StunException.NETWORK_ERROR,
"Failed to send STUN indication: " + indication,
ioex);
}
}
@ -402,24 +400,77 @@ public class StunStack
* @return the <tt>TransactionID</tt> of the <tt>StunClientTransaction</tt>
* 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
* 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)
throws IOException, IllegalArgumentException
public TransactionID sendRequest(Request request,
TransportAddress sendTo,
TransportAddress sendThrough,
ResponseCollector collector,
TransactionID transactionID)
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
= new StunClientTransaction(this, request, sendTo, sendThrough,
collector, transactionID);
= new StunClientTransaction(
this,
request,
sendTo,
sendThrough,
collector,
transactionID);
clientTransactions.put(clientTransaction.getTransactionID(),
clientTransaction);
if (originalWaitInterval > 0)
clientTransaction.originalWaitInterval = originalWaitInterval;
if (maxWaitInterval > 0)
clientTransaction.maxWaitInterval = maxWaitInterval;
if (maxRetransmissions >= 0)
clientTransaction.maxRetransmissions = maxRetransmissions;
clientTransactions.put(
clientTransaction.getTransactionID(),
clientTransaction);
clientTransaction.sendRequest();
@ -620,26 +671,27 @@ public class StunStack
/**
* 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))
logger.finest("Received a message on "
+ event.getLocalAddress()
+ " of type:"
+ (int)msg.getMessageType());
{
logger.finest(
"Received a message on " + ev.getLocalAddress()
+ " of type:" + (int) msg.getMessageType());
}
//request
if(msg instanceof Request)
{
logger.finest("parsing request");
TransactionID serverTid = event.getTransactionID();
TransactionID serverTid = ev.getTransactionID();
StunServerTransaction sTran = serverTransactions.get(serverTid);
if( sTran != null)
{
//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
logger.log(Level.WARNING,
"Failed to retransmit a stun response", ex);
"Failed to retransmit a stun response",
ex);
}
if(!Boolean.getBoolean(
@ -667,8 +720,12 @@ public class StunStack
else
{
logger.finest("existing transaction not found");
sTran = new StunServerTransaction(this, serverTid,
event.getLocalAddress(), event.getRemoteAddress());
sTran
= new StunServerTransaction(
this,
serverTid,
ev.getLocalAddress(),
ev.getRemoteAddress());
// if there is an OOM error here, it will lead to
// NetAccessManager.handleFatalError that will stop the
@ -689,18 +746,18 @@ public class StunStack
//validate attributes that need validation.
try
{
validateRequestAttributes(event);
validateRequestAttributes(ev);
}
catch(Exception exc)
{
//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;
}
try
{
eventDispatcher.fireMessageEvent(event);
eventDispatcher.fireMessageEvent(ev);
}
catch (Throwable t)
{
@ -709,12 +766,14 @@ public class StunStack
logger.log(Level.INFO, "Received an invalid request.", t);
Throwable cause = t.getCause();
if(((t instanceof StunException) &&
((StunException)t).getID() ==
StunException.TRANSACTION_ALREADY_ANSWERED) ||
(cause != null && (cause instanceof StunException) &&
((StunException)cause).getID() ==
StunException.TRANSACTION_ALREADY_ANSWERED))
if(((t instanceof StunException)
&& ((StunException) t).getID()
== StunException
.TRANSACTION_ALREADY_ANSWERED)
|| ((cause instanceof StunException)
&& ((StunException) cause).getID()
== StunException
.TRANSACTION_ALREADY_ANSWERED))
{
// do not try to send an error response since we will
// get another TRANSACTION_ALREADY_ANSWERED
@ -723,53 +782,58 @@ public class StunStack
if(t instanceof IllegalArgumentException)
{
error = MessageFactory.createBindingErrorResponse(
error
= MessageFactory.createBindingErrorResponse(
ErrorCodeAttribute.BAD_REQUEST,
t.getMessage());
}
else
{
error = MessageFactory.createBindingErrorResponse(
error
= MessageFactory.createBindingErrorResponse(
ErrorCodeAttribute.SERVER_ERROR,
"Oops! Something went wrong on our side :(");
}
try
{
sendResponse(event.getTransactionID().getBytes(),
error, event.getLocalAddress(),
event.getRemoteAddress());
sendResponse(
serverTid.getBytes(),
error,
ev.getLocalAddress(),
ev.getRemoteAddress());
}
catch(Exception exc)
{
logger.log(Level.FINE, "Couldn't send a server error "
+ "response", exc);
logger.log(Level.FINE,
"Couldn't send a server error response",
exc);
}
}
}
//response
else if(msg instanceof Response)
{
TransactionID tid = event.getTransactionID();
TransactionID tid = ev.getTransactionID();
StunClientTransaction tran = clientTransactions.remove(tid);
if(tran != null)
{
tran.handleResponse(event);
tran.handleResponse(ev);
}
else
{
//do nothing - just drop the phantom response.
logger.fine("Dropped response - no matching client tran found"
+ " for tid " + tid + "\n"
+ "all tids in stock were "
+ clientTransactions.keySet());
logger.fine(
"Dropped response - no matching client tran found for"
+ " tid " + tid + "\n" + "all tids in stock were "
+ clientTransactions.keySet());
}
}
// indication
else if (msg instanceof Indication)
{
eventDispatcher.fireMessageEvent(event);
eventDispatcher.fireMessageEvent(ev);
}
}
@ -792,20 +856,24 @@ public class StunStack
{
eventDispatcher.removeAllListeners();
Enumeration<TransactionID> tids = clientTransactions.keys();
while (tids.hasMoreElements())
for (Iterator<StunClientTransaction> i
= clientTransactions.values().iterator();
i.hasNext();)
{
TransactionID item = tids.nextElement();
StunClientTransaction tran = clientTransactions.remove(item);
StunClientTransaction tran = i.next();
i.remove();
if(tran != null)
tran.cancel();
}
tids = serverTransactions.keys();
while (tids.hasMoreElements())
for (Iterator<StunServerTransaction> i
= serverTransactions.values().iterator();
i.hasNext();)
{
TransactionID item = tids.nextElement();
StunServerTransaction tran = serverTransactions.remove(item);
StunServerTransaction tran = i.next();
i.remove();
if(tran != null)
tran.expire();
}