Fixes what looks like a race condition related to the starting of a connectivity check on a Candidate pair and processing its Response.

This commit is contained in:
lubomir.marinov 2010-07-01 02:39:19 +00:00
parent f15437c37b
commit 9495fe541a
7 changed files with 163 additions and 135 deletions

View File

@ -45,6 +45,15 @@ public class Agent
*/
public static final int DEFAULT_TERMINATION_DELAY = 3000;
/**
* The constant which defines an empty array with element type
* <tt>PropertyChangeListener</tt> and represents the fact that there are no
* <tt>IceProcessingState</tt> change listeners added to an <tt>Agent</tt>
* (using {@link #addStateChangeListener(PropertyChangeListener)}.
*/
private static final PropertyChangeListener[] NO_STATE_CHANGE_LISTENERS
= new PropertyChangeListener[0];
/**
* The <tt>Logger</tt> used by the <tt>Agent</tt>
* class and its instances for logging output.
@ -177,8 +186,8 @@ public class Agent
* Contains {@link PropertyChangeListener}s registered with this {@link
* Agent} and following its changes of state.
*/
private List<PropertyChangeListener> stateListeners
= new LinkedList<PropertyChangeListener>();
private final List<PropertyChangeListener> stateListeners
= new LinkedList<PropertyChangeListener>();
/**
* The thread that we use for moving from COMPLETED into a TERMINATED state.
@ -371,7 +380,7 @@ public class Agent
* have exchanged their media descriptions. Determining whether the actual
* process has started is important, for example, when determining whether
* a remote address we've just discovered is peer reflexive or not.
* If CE has started and we don't know about the address then we should
* If ICE has started and we don't know about the address then we should
* add it to the list of candidates. Otherwise we should hold to it until
* it does and check later.
* <p>
@ -437,21 +446,19 @@ public class Agent
private void fireStateChange(IceProcessingState oldState,
IceProcessingState newState)
{
List<PropertyChangeListener> listenersCopy;
PropertyChangeListener[] stateListenersCopy;
synchronized(stateListeners)
{
listenersCopy
= new LinkedList<PropertyChangeListener>(stateListeners);
stateListenersCopy
= stateListeners.toArray(NO_STATE_CHANGE_LISTENERS);
}
PropertyChangeEvent evt = new PropertyChangeEvent(
this, PROPERTY_ICE_PROCESSING_STATE, oldState, newState);
for(PropertyChangeListener l : listenersCopy)
{
for(PropertyChangeListener l : stateListenersCopy)
l.propertyChange(evt);
}
}
/**
@ -1013,7 +1020,7 @@ public class Agent
// valid pair to true.
nominationConfirmed( triggerPair );
//the above maye have caused us to exit, and so we need to
//the above may have caused us to exit, and so we need to
//make the call below in order to make sure that we update
//ICE processing state.
checkListStatesUpdated();
@ -1030,7 +1037,6 @@ public class Agent
= knownPair.getConnectivityCheckTransaction();
StunStack.getInstance().cancelTransaction(checkTransaction);
}
}
else
@ -1161,14 +1167,14 @@ public class Agent
for(IceMediaStream stream : streams)
{
CheckList checkList = stream.getCheckList();
if(checkList.getState() == CheckListState.RUNNING)
CheckListState checkListState = stream.getCheckList().getState();
if(checkListState == CheckListState.RUNNING)
{
allListsEnded = false;
break;
}
else if(stream.getCheckList().getState()
== CheckListState.COMPLETED)
else if(checkListState == CheckListState.COMPLETED)
{
atLeastOneListSucceeded = true;
}
@ -1376,19 +1382,23 @@ public class Agent
*/
public synchronized void run()
{
long waitFor = Integer.getInteger(
long terminationDelay = Integer.getInteger(
StackProperties.TERMINATION_DELAY,
DEFAULT_TERMINATION_DELAY);
try
if (terminationDelay >= 0)
{
wait(waitFor);
}
catch (Exception e)
{
logger.log(Level.FINEST, "Interrupted while waiting. Will "
+"speed up termination", e);
try
{
wait(terminationDelay);
}
catch (InterruptedException iex)
{
logger.log(
Level.FINEST, "Interrupted while waiting. Will "
+"speed up termination",
iex);
}
}
parentAgent.terminate(IceProcessingState.TERMINATED);

View File

@ -177,7 +177,7 @@ public class CandidatePair
/**
* Sets the <tt>CandidatePairState</tt> of this pair to
* {@link CandidatePairState#FAILED}. This method should only be called by
* the ice agent, during the execution of the ICE procedures.
* the ICE agent, during the execution of the ICE procedures.
*/
public void setStateFailed()
{
@ -187,7 +187,7 @@ public class CandidatePair
/**
* Sets the <tt>CandidatePairState</tt> of this pair to
* {@link CandidatePairState#FROZEN}. This method should only be called by
* the ice agent, during the execution of the ICE procedures.
* the ICE agent, during the execution of the ICE procedures.
*/
public void setStateFrozen()
{
@ -197,7 +197,7 @@ public class CandidatePair
/**
* Sets the <tt>CandidatePairState</tt> of this pair to
* {@link CandidatePairState#FROZEN}. This method should only be called by
* the ice agent, during the execution of the ICE procedures.
* the ICE agent, during the execution of the ICE procedures.
*
* @param tranID the {@link TransactionID} that we are using for the
* connectivity check in case we are entering the <tt>In-Progress</tt>
@ -211,7 +211,7 @@ public class CandidatePair
/**
* Sets the <tt>CandidatePairState</tt> of this pair to
* {@link CandidatePairState#SUCCEEDED}. This method should only be called
* by the ice agent, during the execution of the ICE procedures.
* by the ICE agent, during the execution of the ICE procedures.
*/
public void setStateSucceeded()
{
@ -221,7 +221,7 @@ public class CandidatePair
/**
* Sets the <tt>CandidatePairState</tt> of this pair to
* {@link CandidatePairState#WAITING}. This method should only be called by
* the ice agent, during the execution of the ICE procedures.
* the ICE agent, during the execution of the ICE procedures.
*/
public void setStateWaiting()
{
@ -248,6 +248,7 @@ public class CandidatePair
throws IllegalArgumentException
{
CandidatePairState oldState = this.state;
this.state = newState;
if(newState != CandidatePairState.IN_PROGRESS)
@ -264,7 +265,6 @@ public class CandidatePair
+"In-Progress state MUST be accomapnied with "
+"the TransactionID of the conn check.");
}
this.connCheckTranID = tranID;
getParentComponent().getParentStream().firePairPropertyChange(

View File

@ -126,7 +126,6 @@ public class CheckList
if(triggeredCheckQueue.size() > 0)
return triggeredCheckQueue.remove(0);
}
return null;
}

View File

@ -20,6 +20,7 @@ import org.ice4j.stack.*;
* will be handling their responses or lack thereof.
*
* @author Emil Ivov
* @author Lubomir Marinov
*/
class ConnectivityCheckClient
implements ResponseCollector
@ -81,7 +82,7 @@ class ConnectivityCheckClient
*/
private void startChecks(CheckList checkList)
{
PaceMaker paceMaker = new PaceMaker(this, checkList);
PaceMaker paceMaker = new PaceMaker(checkList);
synchronized (paceMakers)
{
@ -108,7 +109,7 @@ class ConnectivityCheckClient
//we don't need to do a canReach() verification here as it has been
//already verified during the gathering process.
DatagramSocket stunSocket
= candidatePair.getLocalCandidate() .getStunSocket(null);
= candidatePair.getLocalCandidate().getStunSocket(null);
Request request = MessageFactory.createBindingRequest();
@ -165,7 +166,7 @@ class ConnectivityCheckClient
if(logger.isLoggable(Level.FINEST))
logger.finest("checking pair " + candidatePair + " with tran="
+ tran.toString());
+ tran);
return tran;
}
@ -191,15 +192,15 @@ class ConnectivityCheckClient
*/
public void processResponse(StunResponseEvent evt)
{
CandidatePair checkedPair
= ((CandidatePair)evt.getTransactionID().getApplicationData());
//make sure that the response came from the right place.
if (!checkSymmetricAddresses(evt))
{
CandidatePair pair = ((CandidatePair)evt.getTransactionID()
.getApplicationData());
logger.fine("Received a non-symmetric response for pair: "+ pair
+". Failing");
pair.setStateFailed();
logger.fine("Received a non-symmetric response for pair: "
+ checkedPair +". Failing");
checkedPair.setStateFailed();
}
//handle error responses.
else if(evt.getResponse().getMessageType()
@ -213,16 +214,13 @@ class ConnectivityCheckClient
processErrorResponse(evt);
}
//handle error responses.
//handle success responses.
else if(evt.getResponse().getMessageType()
== Response.BINDING_SUCCESS_RESPONSE)
{
processSuccessResponse(evt);
}
CandidatePair checkedPair = ((CandidatePair)evt.getTransactionID()
.getApplicationData());
//Regardless of whether the check was successful or failed, the
//completion of the transaction may require updating of check list and
//timer states.
@ -435,7 +433,7 @@ 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))
&& request.containsAttribute(Attribute.USE_CANDIDATE))
{
parentAgent.nominationConfirmed( validPair );
}
@ -447,7 +445,6 @@ class ConnectivityCheckClient
else if(checkedPair.useCandidateReceived()
&& ! checkedPair.isNominated())
parentAgent.nominationConfirmed( checkedPair );
}
/**
@ -495,16 +492,17 @@ class ConnectivityCheckClient
Response response = evt.getResponse();
Request originalRequest = evt.getRequest();
ErrorCodeAttribute errorCode = (ErrorCodeAttribute)response
.getAttribute(Attribute.ERROR_CODE);
char errorCode
= ((ErrorCodeAttribute) response.getAttribute(Attribute.ERROR_CODE))
.getErrorCode();
CandidatePair pair = ((CandidatePair)evt.getTransactionID()
.getApplicationData());
logger.finer("Received error code " + (int)errorCode.getErrorCode());
logger.finer("Received error code " + ((int) errorCode));
//RESOLVE ROLE_CONFLICTS
if(errorCode.getErrorCode() == ErrorCodeAttribute.ROLE_CONFLICT)
if(errorCode == ErrorCodeAttribute.ROLE_CONFLICT)
{
boolean wasControlling = originalRequest
.containsAttribute(Attribute.ICE_CONTROLLING);
@ -514,8 +512,6 @@ class ConnectivityCheckClient
pair.getParentComponent().getParentStream().getCheckList()
.scheduleTriggeredCheck(pair);
return;
}
else
{
@ -543,23 +539,17 @@ class ConnectivityCheckClient
updateCheckListAndTimerStates(pair);
}
/**
* The thread that actually sends the checks for a particular check list
* in the pace defined in RFC 5245.
*/
private static class PaceMaker extends Thread
private class PaceMaker
extends Thread
{
/**
* Indicates whether this thread is still running. Not really used at
* this point.
* Indicates whether this <tt>Thread</tt> should still be running.
*/
public boolean isRunning = true;
/**
* The {@link ConnectivityCheckClient} that created us.
*/
private final ConnectivityCheckClient parentClient;
boolean running = true;
/**
* The {@link CheckList} that this <tt>PaceMaker</tt> will be running
@ -568,20 +558,26 @@ class ConnectivityCheckClient
private final CheckList checkList;
/**
* Creates a new {@link PaceMaker} for the specified
* <tt>parentClient</tt>
* Creates a new {@link PaceMaker} for this
* <tt>ConnectivityCheckClient</tt>.
*
* @param parentClient the {@link ConnectivityCheckClient} that who's
* checks we are going to run.
* @param checkList the {@link CheckList} that we'll be sending checks
* for
*/
public PaceMaker(ConnectivityCheckClient parentClient,
CheckList checkList)
public PaceMaker(CheckList checkList)
{
super("ICE PaceMaker:" + parentClient.parentAgent.getLocalUfrag());
this.parentClient = parentClient;
super("ICE PaceMaker: " + parentAgent.getLocalUfrag());
this.checkList = checkList;
/*
* Because PaceMaker does not seem to be a daemon at least on Ubuntu
* in the run-sample target and it looks like it should be from the
* standpoint of the application, explicitly tell it to be a daemon.
* Otherwise, it could prevent the application from exiting because
* of a problem in the ICE implementation.
*/
setDaemon(true);
}
/**
@ -593,8 +589,7 @@ class ConnectivityCheckClient
*/
private long getNextWaitInterval()
{
int activeCheckLists = parentClient
.parentAgent.getActiveCheckListCount();
int activeCheckLists = parentAgent.getActiveCheckListCount();
if (activeCheckLists < 1)
{
@ -603,7 +598,7 @@ class ConnectivityCheckClient
activeCheckLists = 1;
}
return parentClient.parentAgent.calculateTa() * activeCheckLists;
return parentAgent.calculateTa() * activeCheckLists;
}
/**
@ -611,64 +606,77 @@ class ConnectivityCheckClient
* Agent#calculateTa()} method and using either the trigger check queue
* or the regular check lists.
*/
@Override
public synchronized void run()
{
while(isRunning)
try
{
long waitFor = getNextWaitInterval();
if(waitFor > 0)
while(running)
{
//waitFor will be 0 for the first check since we won't have
//any active check lists at that point yet.
try
long waitFor = getNextWaitInterval();
if(waitFor > 0)
{
wait(waitFor);
}
catch (InterruptedException e)
{
logger.log(Level.FINER, "PaceMake got interrupted", e);
/*
* waitFor will be 0 for the first check since we won't
* have any active check lists at that point yet.
*/
try
{
wait(waitFor);
}
catch (InterruptedException e)
{
logger.log(Level.FINER, "PaceMake got interrupted", e);
}
if (!running)
break;
}
if (!isRunning)
break;
CandidatePair pairToCheck = checkList.popTriggeredCheck();
//if there are no triggered checks, go for an ordinary one.
if(pairToCheck == null)
pairToCheck = checkList.getNextOrdinaryPairToCheck();
if(pairToCheck != null)
{
/*
* Since we suspect that it is possible to
* startCheckForPair, processSuccessResponse and only
* then setStateInProgress, we'll synchronize. The
* synchronization root is the one of the
* CandidatePair#setState method.
*/
synchronized (pairToCheck)
{
TransactionID transactionID
= startCheckForPair(pairToCheck);
if(transactionID == null)
pairToCheck.setStateFailed();
else
pairToCheck.setStateInProgress(transactionID);
}
}
else
{
/*
* We are done sending checks for this list. We'll set
* its final state in either the processResponse(),
* processTimeout() or processFailure() method.
*/
logger.finest("will skip a check beat.");
}
}
CandidatePair pairToCheck = checkList.popTriggeredCheck();
TransactionID transactionID = null;
//if there are no triggered checks, go for an ordinary one.
if(pairToCheck == null)
{
pairToCheck = checkList.getNextOrdinaryPairToCheck();
}
if(pairToCheck != null)
{
transactionID = parentClient.startCheckForPair(pairToCheck);
}
else
{
//we are done sending checks for this list. we'll set its
//final state in either the processResponse()
//processTimeout() or processFailure() method.
logger.finest("will skip a check beat.");
continue;
}
if(transactionID == null)
pairToCheck.setStateFailed();
else
pairToCheck.setStateInProgress(transactionID);
}
List<PaceMaker> parentClientPaceMakers = parentClient.paceMakers;
synchronized (parentClientPaceMakers)
finally
{
parentClientPaceMakers.remove(this);
synchronized (paceMakers)
{
paceMakers.remove(this);
}
}
}
}
@ -686,7 +694,7 @@ class ConnectivityCheckClient
{
PaceMaker paceMaker = paceMakersIter.next();
paceMaker.isRunning = false;
paceMaker.running = false;
synchronized(paceMaker)
{
paceMaker.notify();

View File

@ -517,7 +517,6 @@ public class IceMediaStream
public CandidatePair findCandidatePair(TransportAddress localAddress,
TransportAddress remoteAddress)
{
synchronized(checkList)
{
for( CandidatePair pair : checkList)
@ -531,7 +530,6 @@ public class IceMediaStream
}
}
}
return null;
}

View File

@ -440,8 +440,7 @@ public class StunCandidateHarvest
if (retryRequest != null)
{
longTermCredentialSession.addAttributes(retryRequest);
retryRequestTransactionID = sendRequest(retryRequest);
retryRequestTransactionID = sendRequest(retryRequest, false);
}
return (retryRequestTransactionID != null);
}
@ -764,13 +763,24 @@ public class StunCandidateHarvest
* Sends a specific <tt>Request</tt> to the STUN server associated with this
* <tt>StunCandidateHarvest</tt>.
*
* @param request
* @return
* @throws StunException
* @param request the <tt>Request</tt> to send to the STUN server associated
* with this <tt>StunCandidateHarvest</tt>
* @param firstRequest <tt>true</tt> if the specified <tt>request</tt>
* should be sent as the first request in the terms of STUN; otherwise,
* <tt>false</tt>
* @return the <tt>TransactionID</tt> of the STUN client transaction through
* which the specified <tt>Request</tt> has been sent to the STUN server
* associated with this <tt>StunCandidateHarvest</tt>
* @throws StunException if anything goes wrong while sending the specified
* <tt>Request</tt> to the STUN server associated with this
* <tt>StunCandidateHarvest</tt>
*/
protected TransactionID sendRequest(Request request)
protected TransactionID sendRequest(Request request, boolean firstRequest)
throws StunException
{
if (!firstRequest && (longTermCredentialSession != null))
longTermCredentialSession.addAttributes(request);
StunStack stunStack = harvester.stunStack;
TransportAddress stunServer = harvester.stunServer;
TransportAddress hostCandidateTransportAddress
@ -853,7 +863,7 @@ public class StunCandidateHarvest
// Short-Term Credential Mechanism
addShortTermCredentialAttributes(requestToStartResolvingCandidate);
sendRequest(requestToStartResolvingCandidate);
sendRequest(requestToStartResolvingCandidate, true);
return true;
}
else

View File

@ -6,7 +6,6 @@
*/
package org.ice4j.stack;
import java.io.*;
import java.net.*;
import java.util.*;
@ -270,9 +269,13 @@ class NetAccessManager
byte[] bytes = stunMessage.encode();
Connector ap = netAccessPoints.get(srcAddr);
if(ap == null)
throw new IllegalArgumentException(
"The specified access point had not been installed.");
if (ap == null)
{
throw
new IllegalArgumentException(
"No socket has been added for source address: "
+ srcAddr);
}
ap.sendMessage(bytes, remoteAddr);
}