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

View File

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

View File

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

View File

@ -20,6 +20,7 @@ import org.ice4j.stack.*;
* will be handling their responses or lack thereof. * will be handling their responses or lack thereof.
* *
* @author Emil Ivov * @author Emil Ivov
* @author Lubomir Marinov
*/ */
class ConnectivityCheckClient class ConnectivityCheckClient
implements ResponseCollector implements ResponseCollector
@ -81,7 +82,7 @@ class ConnectivityCheckClient
*/ */
private void startChecks(CheckList checkList) private void startChecks(CheckList checkList)
{ {
PaceMaker paceMaker = new PaceMaker(this, checkList); PaceMaker paceMaker = new PaceMaker(checkList);
synchronized (paceMakers) synchronized (paceMakers)
{ {
@ -108,7 +109,7 @@ class ConnectivityCheckClient
//we don't need to do a canReach() verification here as it has been //we don't need to do a canReach() verification here as it has been
//already verified during the gathering process. //already verified during the gathering process.
DatagramSocket stunSocket DatagramSocket stunSocket
= candidatePair.getLocalCandidate() .getStunSocket(null); = candidatePair.getLocalCandidate().getStunSocket(null);
Request request = MessageFactory.createBindingRequest(); Request request = MessageFactory.createBindingRequest();
@ -165,7 +166,7 @@ class ConnectivityCheckClient
if(logger.isLoggable(Level.FINEST)) if(logger.isLoggable(Level.FINEST))
logger.finest("checking pair " + candidatePair + " with tran=" logger.finest("checking pair " + candidatePair + " with tran="
+ tran.toString()); + tran);
return tran; return tran;
} }
@ -191,15 +192,15 @@ class ConnectivityCheckClient
*/ */
public void processResponse(StunResponseEvent evt) public void processResponse(StunResponseEvent evt)
{ {
CandidatePair checkedPair
= ((CandidatePair)evt.getTransactionID().getApplicationData());
//make sure that the response came from the right place. //make sure that the response came from the right place.
if (!checkSymmetricAddresses(evt)) if (!checkSymmetricAddresses(evt))
{ {
CandidatePair pair = ((CandidatePair)evt.getTransactionID() logger.fine("Received a non-symmetric response for pair: "
.getApplicationData()); + checkedPair +". Failing");
checkedPair.setStateFailed();
logger.fine("Received a non-symmetric response for pair: "+ pair
+". Failing");
pair.setStateFailed();
} }
//handle error responses. //handle error responses.
else if(evt.getResponse().getMessageType() else if(evt.getResponse().getMessageType()
@ -213,16 +214,13 @@ class ConnectivityCheckClient
processErrorResponse(evt); processErrorResponse(evt);
} }
//handle error responses. //handle success responses.
else if(evt.getResponse().getMessageType() else if(evt.getResponse().getMessageType()
== Response.BINDING_SUCCESS_RESPONSE) == Response.BINDING_SUCCESS_RESPONSE)
{ {
processSuccessResponse(evt); processSuccessResponse(evt);
} }
CandidatePair checkedPair = ((CandidatePair)evt.getTransactionID()
.getApplicationData());
//Regardless of whether the check was successful or failed, the //Regardless of whether the check was successful or failed, the
//completion of the transaction may require updating of check list and //completion of the transaction may require updating of check list and
//timer states. //timer states.
@ -435,7 +433,7 @@ class ConnectivityCheckClient
//CANDIDATE attribute in the Binding request, the valid pair generated //CANDIDATE attribute in the Binding request, the valid pair generated
//from that check has its nominated flag set to true. //from that check has its nominated flag set to true.
if(parentAgent.isControlling() if(parentAgent.isControlling()
&& request.containsAttribute(Attribute.USE_CANDIDATE)) && request.containsAttribute(Attribute.USE_CANDIDATE))
{ {
parentAgent.nominationConfirmed( validPair ); parentAgent.nominationConfirmed( validPair );
} }
@ -447,7 +445,6 @@ class ConnectivityCheckClient
else if(checkedPair.useCandidateReceived() else if(checkedPair.useCandidateReceived()
&& ! checkedPair.isNominated()) && ! checkedPair.isNominated())
parentAgent.nominationConfirmed( checkedPair ); parentAgent.nominationConfirmed( checkedPair );
} }
/** /**
@ -495,16 +492,17 @@ class ConnectivityCheckClient
Response response = evt.getResponse(); Response response = evt.getResponse();
Request originalRequest = evt.getRequest(); Request originalRequest = evt.getRequest();
ErrorCodeAttribute errorCode = (ErrorCodeAttribute)response char errorCode
.getAttribute(Attribute.ERROR_CODE); = ((ErrorCodeAttribute) response.getAttribute(Attribute.ERROR_CODE))
.getErrorCode();
CandidatePair pair = ((CandidatePair)evt.getTransactionID() CandidatePair pair = ((CandidatePair)evt.getTransactionID()
.getApplicationData()); .getApplicationData());
logger.finer("Received error code " + (int)errorCode.getErrorCode()); logger.finer("Received error code " + ((int) errorCode));
//RESOLVE ROLE_CONFLICTS //RESOLVE ROLE_CONFLICTS
if(errorCode.getErrorCode() == ErrorCodeAttribute.ROLE_CONFLICT) if(errorCode == ErrorCodeAttribute.ROLE_CONFLICT)
{ {
boolean wasControlling = originalRequest boolean wasControlling = originalRequest
.containsAttribute(Attribute.ICE_CONTROLLING); .containsAttribute(Attribute.ICE_CONTROLLING);
@ -514,8 +512,6 @@ class ConnectivityCheckClient
pair.getParentComponent().getParentStream().getCheckList() pair.getParentComponent().getParentStream().getCheckList()
.scheduleTriggeredCheck(pair); .scheduleTriggeredCheck(pair);
return;
} }
else else
{ {
@ -543,23 +539,17 @@ class ConnectivityCheckClient
updateCheckListAndTimerStates(pair); updateCheckListAndTimerStates(pair);
} }
/** /**
* The thread that actually sends the checks for a particular check list * The thread that actually sends the checks for a particular check list
* in the pace defined in RFC 5245. * 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 * Indicates whether this <tt>Thread</tt> should still be running.
* this point.
*/ */
public boolean isRunning = true; boolean running = true;
/**
* The {@link ConnectivityCheckClient} that created us.
*/
private final ConnectivityCheckClient parentClient;
/** /**
* The {@link CheckList} that this <tt>PaceMaker</tt> will be running * The {@link CheckList} that this <tt>PaceMaker</tt> will be running
@ -568,20 +558,26 @@ class ConnectivityCheckClient
private final CheckList checkList; private final CheckList checkList;
/** /**
* Creates a new {@link PaceMaker} for the specified * Creates a new {@link PaceMaker} for this
* <tt>parentClient</tt> * <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 * @param checkList the {@link CheckList} that we'll be sending checks
* for * for
*/ */
public PaceMaker(ConnectivityCheckClient parentClient, public PaceMaker(CheckList checkList)
CheckList checkList)
{ {
super("ICE PaceMaker:" + parentClient.parentAgent.getLocalUfrag()); super("ICE PaceMaker: " + parentAgent.getLocalUfrag());
this.parentClient = parentClient;
this.checkList = checkList; 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() private long getNextWaitInterval()
{ {
int activeCheckLists = parentClient int activeCheckLists = parentAgent.getActiveCheckListCount();
.parentAgent.getActiveCheckListCount();
if (activeCheckLists < 1) if (activeCheckLists < 1)
{ {
@ -603,7 +598,7 @@ class ConnectivityCheckClient
activeCheckLists = 1; 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 * Agent#calculateTa()} method and using either the trigger check queue
* or the regular check lists. * or the regular check lists.
*/ */
@Override
public synchronized void run() public synchronized void run()
{ {
while(isRunning) try
{ {
long waitFor = getNextWaitInterval(); while(running)
if(waitFor > 0)
{ {
//waitFor will be 0 for the first check since we won't have long waitFor = getNextWaitInterval();
//any active check lists at that point yet.
try if(waitFor > 0)
{ {
wait(waitFor); /*
} * waitFor will be 0 for the first check since we won't
catch (InterruptedException e) * have any active check lists at that point yet.
{ */
logger.log(Level.FINER, "PaceMake got interrupted", e); try
{
wait(waitFor);
}
catch (InterruptedException e)
{
logger.log(Level.FINER, "PaceMake got interrupted", e);
}
if (!running)
break;
} }
if (!isRunning) CandidatePair pairToCheck = checkList.popTriggeredCheck();
break;
//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);
} }
finally
List<PaceMaker> parentClientPaceMakers = parentClient.paceMakers;
synchronized (parentClientPaceMakers)
{ {
parentClientPaceMakers.remove(this); synchronized (paceMakers)
{
paceMakers.remove(this);
}
} }
} }
} }
@ -686,7 +694,7 @@ class ConnectivityCheckClient
{ {
PaceMaker paceMaker = paceMakersIter.next(); PaceMaker paceMaker = paceMakersIter.next();
paceMaker.isRunning = false; paceMaker.running = false;
synchronized(paceMaker) synchronized(paceMaker)
{ {
paceMaker.notify(); paceMaker.notify();

View File

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

View File

@ -440,8 +440,7 @@ public class StunCandidateHarvest
if (retryRequest != null) if (retryRequest != null)
{ {
longTermCredentialSession.addAttributes(retryRequest); retryRequestTransactionID = sendRequest(retryRequest, false);
retryRequestTransactionID = sendRequest(retryRequest);
} }
return (retryRequestTransactionID != null); return (retryRequestTransactionID != null);
} }
@ -764,13 +763,24 @@ public class StunCandidateHarvest
* Sends a specific <tt>Request</tt> to the STUN server associated with this * Sends a specific <tt>Request</tt> to the STUN server associated with this
* <tt>StunCandidateHarvest</tt>. * <tt>StunCandidateHarvest</tt>.
* *
* @param request * @param request the <tt>Request</tt> to send to the STUN server associated
* @return * with this <tt>StunCandidateHarvest</tt>
* @throws StunException * @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 throws StunException
{ {
if (!firstRequest && (longTermCredentialSession != null))
longTermCredentialSession.addAttributes(request);
StunStack stunStack = harvester.stunStack; StunStack stunStack = harvester.stunStack;
TransportAddress stunServer = harvester.stunServer; TransportAddress stunServer = harvester.stunServer;
TransportAddress hostCandidateTransportAddress TransportAddress hostCandidateTransportAddress
@ -853,7 +863,7 @@ public class StunCandidateHarvest
// Short-Term Credential Mechanism // Short-Term Credential Mechanism
addShortTermCredentialAttributes(requestToStartResolvingCandidate); addShortTermCredentialAttributes(requestToStartResolvingCandidate);
sendRequest(requestToStartResolvingCandidate); sendRequest(requestToStartResolvingCandidate, true);
return true; return true;
} }
else else

View File

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