Merge pull request #88 from bgrozev/merging

Virtual socket layer
This commit is contained in:
bgrozev 2016-12-13 11:08:29 -06:00 committed by GitHub
commit 1cd1128b89
30 changed files with 1749 additions and 248 deletions

View File

@ -373,6 +373,11 @@ public class Agent
{ {
addCandidateHarvester(harvester); addCandidateHarvester(harvester);
} }
if (logger.isLoggable(Level.FINE))
{
logger.fine("Created a new Agent, ufrag=" + ufrag);
}
} }
/** /**
@ -756,9 +761,9 @@ public class Agent
*/ */
public void addStateChangeListener(PropertyChangeListener l) public void addStateChangeListener(PropertyChangeListener l)
{ {
synchronized(stateListeners) synchronized (stateListeners)
{ {
if(!stateListeners.contains(l)) if (!stateListeners.contains(l))
stateListeners.add(l); stateListeners.add(l);
} }
} }
@ -771,7 +776,7 @@ public class Agent
*/ */
public void removeStateChangeListener(PropertyChangeListener l) public void removeStateChangeListener(PropertyChangeListener l)
{ {
synchronized(stateListeners) synchronized (stateListeners)
{ {
stateListeners.remove(l); stateListeners.remove(l);
} }
@ -789,7 +794,7 @@ public class Agent
{ {
PropertyChangeListener[] stateListenersCopy; PropertyChangeListener[] stateListenersCopy;
synchronized(stateListeners) synchronized (stateListeners)
{ {
stateListenersCopy stateListenersCopy
= stateListeners.toArray(NO_STATE_CHANGE_LISTENERS); = stateListeners.toArray(NO_STATE_CHANGE_LISTENERS);
@ -803,7 +808,7 @@ public class Agent
PROPERTY_ICE_PROCESSING_STATE, PROPERTY_ICE_PROCESSING_STATE,
oldState, newState); oldState, newState);
for(PropertyChangeListener l : stateListenersCopy) for (PropertyChangeListener l : stateListenersCopy)
l.propertyChange(evt); l.propertyChange(evt);
} }
} }

View File

@ -290,13 +290,13 @@ public class CandidatePair
this.state = newState; this.state = newState;
if(newState == CandidatePairState.IN_PROGRESS) if (newState == CandidatePairState.IN_PROGRESS)
{ {
if (tranID == null) if (tranID == null)
{ {
throw new IllegalArgumentException( throw new IllegalArgumentException(
"Putting a pair into the In-Progress state MUST be" "Putting a pair into the In-Progress state MUST be"
+ " accomapnied with the TransactionID of the" + " accompanied with the TransactionID of the"
+ " connectivity check."); + " connectivity check.");
} }
} }
@ -722,7 +722,9 @@ public class CandidatePair
* <tt>CandidatePair</tt>. * <tt>CandidatePair</tt>.
* @return the UDP <tt>DatagramSocket</tt> (if any) for this * @return the UDP <tt>DatagramSocket</tt> (if any) for this
* <tt>CandidatePair</tt>. * <tt>CandidatePair</tt>.
* @deprecated use {@link Component#getSocket()} instead.
*/ */
@Deprecated
public DatagramSocket getDatagramSocket() public DatagramSocket getDatagramSocket()
{ {
IceSocketWrapper wrapper = getIceSocketWrapper(); IceSocketWrapper wrapper = getIceSocketWrapper();
@ -732,38 +734,22 @@ public class CandidatePair
/** /**
* Returns the TCP <tt>Socket</tt> (if any) for this <tt>CandidatePair</tt>. * Returns the TCP <tt>Socket</tt> (if any) for this <tt>CandidatePair</tt>.
* @return the TCP <tt>Socket</tt> (if any) for this <tt>CandidatePair</tt>. * @return the TCP <tt>Socket</tt> (if any) for this <tt>CandidatePair</tt>.
* @deprecated use {@link Component#getSocket()} instead.
*/ */
@Deprecated
public Socket getSocket() public Socket getSocket()
{ {
IceSocketWrapper wrapper = getIceSocketWrapper(); return null;
return wrapper == null ? null : wrapper.getTCPSocket();
} }
/** /**
* Returns the <tt>IceSocketWrapper</tt> for this <tt>CandidatePair</tt>. * Returns the <tt>IceSocketWrapper</tt> for this <tt>CandidatePair</tt>.
* @return the <tt>IceSocketWrapper</tt> for this <tt>CandidatePair</tt>. * @return the <tt>IceSocketWrapper</tt> for this <tt>CandidatePair</tt>.
* @deprecated use {@link Component#getSocket()} instead.
*/ */
@Deprecated
public IceSocketWrapper getIceSocketWrapper() public IceSocketWrapper getIceSocketWrapper()
{ {
LocalCandidate localCandidate = getLocalCandidate(); return getParentComponent().getSocketWrapper();
if (localCandidate == null)
{
return null;
}
LocalCandidate base = localCandidate.getBase();
if (base != null)
localCandidate = base;
RemoteCandidate remoteCandidate = getRemoteCandidate();
if (remoteCandidate != null)
{
SocketAddress remoteAddress
= remoteCandidate.getTransportAddress();
if (remoteAddress != null)
return localCandidate.getIceSocketWrapper(remoteAddress);
}
return localCandidate.getIceSocketWrapper();
} }
} }

View File

@ -17,10 +17,12 @@
*/ */
package org.ice4j.ice; package org.ice4j.ice;
import java.net.*;
import java.util.*; import java.util.*;
import java.util.logging.*; import java.util.logging.*;
import org.ice4j.*; import org.ice4j.*;
import org.ice4j.socket.*;
import org.ice4j.util.Logger; //Disambiguation import org.ice4j.util.Logger; //Disambiguation
/** /**
@ -119,7 +121,30 @@ public class Component
/** /**
* The {@link Logger} used by {@link Component} instances. * The {@link Logger} used by {@link Component} instances.
*/ */
private Logger logger; private final Logger logger;
/**
* The single {@link ComponentSocket} instance for this {@link Component},
* which will merge the multiple sockets from the candidate/pairs.
*/
private final ComponentSocket componentSocket;
/**
* The public view of {@link #componentSocket}, wrapped in a
* {@link MultiplexingDatagramSocket} for the convenience of users of the
* library.
* This is the instance which should be used by applications for
* reading/writing application data.
*/
private final MultiplexingDatagramSocket socket;
/**
* A wrapper around {@link #socket}, kept only to help preserve the old
* API (see {@link LocalCandidate#getIceSocketWrapper()} and
* {@link CandidatePair#getIceSocketWrapper()})
*/
@Deprecated
private final IceSocketWrapper socketWrapper;
/** /**
* Creates a new <tt>Component</tt> with the specified <tt>componentID</tt> * Creates a new <tt>Component</tt> with the specified <tt>componentID</tt>
@ -136,8 +161,20 @@ public class Component
this.componentID = componentID; this.componentID = componentID;
this.parentStream = mediaStream; this.parentStream = mediaStream;
logger Logger agentLogger = mediaStream.getParentAgent().getLogger();
= new Logger(classLogger, mediaStream.getParentAgent().getLogger());
try
{
componentSocket = new ComponentSocket(this, agentLogger);
socket = new MultiplexingDatagramSocket(componentSocket);
socketWrapper = new IceUdpSocketWrapper(socket);
}
catch (SocketException se)
{
throw new RuntimeException(se);
}
logger = new Logger(classLogger, agentLogger);
} }
/** /**
@ -779,6 +816,8 @@ public class Component
localCandidateIter.remove(); localCandidateIter.remove();
} }
} }
getComponentSocket().close();
} }
/** /**
@ -911,4 +950,31 @@ public class Component
return new Component(componentID, mediaStream); return new Component(componentID, mediaStream);
} }
/**
* @return the internal merging socket for this component. This is for
* ice4j use only.
* For reading/writing application data, use {@link #getSocket()}.
*/
public ComponentSocket getComponentSocket()
{
return componentSocket;
}
/**
* @return the socket for this {@link Component}, which should be used for
* reading/writing application data.
*/
public MultiplexingDatagramSocket getSocket()
{
return socket;
}
/**
* @return an {@link IceSocketWrapper} instance wrapping the socket for this
* candidate (see {@link #getComponentSocket()}).
*/
public IceSocketWrapper getSocketWrapper()
{
return socketWrapper;
}
} }

View File

@ -0,0 +1,210 @@
/*
* ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
*
* Copyright @ 2015-2016 Atlassian Pty Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.ice4j.ice;
import org.ice4j.*;
import org.ice4j.socket.*;
import java.beans.*;
import java.net.*;
import java.util.*;
import org.ice4j.util.*; //Disambiguation
/**
* Extends {@link MergingDatagramSocket} with functionality specific to
* an ICE {@link Component}.
*/
public class ComponentSocket
extends MergingDatagramSocket
implements PropertyChangeListener
{
/**
* The {@link Logger} used by the {@link MergingDatagramSocket} class and
* its instances for logging output.
*/
private static final java.util.logging.Logger classLogger
= java.util.logging.Logger.getLogger
(MergingDatagramSocket.class.getName());
/**
* Controls access to {@link #authorizedAddresses}.
*/
private final Object authorizedAddressesSyncRoot = new Object();
/**
* The set of remote addresses, which this socket is allowed to receive
* from. These should be the addresses which we have confirmed (e.g. by
* having received a STUN message with correct authentication fields).
*/
private Set<SocketAddress> authorizedAddresses = new HashSet<>();
/**
* The owning {@link Component}.
*/
private Component component;
/**
* Whether we have invoked {@link #initializeActive}.
*/
private boolean initializedActive = false;
/**
* Used to synchronize access to {@link #initializedActive}.
*/
private final Object initializedActiveSyncRoot = new Object();
/**
* The {@link Logger} used by {@link MergingDatagramSocket} instances.
*/
private final Logger logger;
/**
* Initializes a new {@link MergingDatagramSocket} instance.
* @throws SocketException
*/
ComponentSocket(Component component, Logger levelDelegate)
throws SocketException
{
super(levelDelegate);
this.component = component;
this.logger = new Logger(classLogger, levelDelegate);
component.getParentStream().addPairChangeListener(this);
}
/**
* {@inheritDoc}
* </p>
* Verifies that the source of the packet is an authorized remote address.
*/
protected boolean accept(DatagramPacket p)
{
return authorizedAddresses.contains(p.getSocketAddress());
}
/**
* Adds a specific address to the list of authorized remote addresses.
* @param address the address to add.
*/
private void addAuthorizedAddress(SocketAddress address)
{
synchronized (authorizedAddressesSyncRoot)
{
if (authorizedAddresses.contains(address))
{
return;
}
logger.info("Adding allowed address: " + address);
Set<SocketAddress> newSet = new HashSet<>();
newSet.addAll(authorizedAddresses);
newSet.add(address);
authorizedAddresses = newSet;
}
}
/**
* {@inheritDoc}
* </p>
* Handles property change events coming from ICE pairs.
* @param event
*/
@Override
public void propertyChange(PropertyChangeEvent event)
{
if (!(event.getSource() instanceof CandidatePair))
{
return;
}
CandidatePair pair = (CandidatePair) event.getSource();
if (!pair.getParentComponent().equals(component))
{
// Events are fired by the IceMediaStream, which might have
// multiple components. Make sure that we only handle events for
// our own component.
return;
}
String propertyName = event.getPropertyName();
if (IceMediaStream.PROPERTY_PAIR_STATE_CHANGED.equals(propertyName))
{
CandidatePairState newState
= (CandidatePairState) event.getNewValue();
if (CandidatePairState.SUCCEEDED.equals(newState))
{
addAuthorizedAddress(
pair.getRemoteCandidate().getTransportAddress());
}
}
else if (IceMediaStream.PROPERTY_PAIR_NOMINATED.equals(propertyName))
{
synchronized (initializedActiveSyncRoot)
{
if (initializedActive)
{
return;
}
// Find the remote address and the correct socket to be used by
// the pair.
LocalCandidate localCandidate = pair.getLocalCandidate();
LocalCandidate base = localCandidate.getBase();
if (base != null)
localCandidate = base;
TransportAddress remoteAddress = null;
RemoteCandidate remoteCandidate = pair.getRemoteCandidate();
if (remoteCandidate != null)
{
remoteAddress = remoteCandidate.getTransportAddress();
}
// The local candidate may have more than one associated socket.
// Make sure we get the one for the remote address that we are
// going to use.
IceSocketWrapper socketWrapper
= localCandidate
.getCandidateIceSocketWrapper(remoteAddress);
initializeActive(socketWrapper, remoteAddress);
initializedActive = true;
}
}
}
/**
* {@inheritDoc}
*/
@Override
public void close()
{
try
{
super.close();
}
finally
{
component.getParentStream().removePairStateChangeListener(this);
component = null;
}
}
}

View File

@ -175,7 +175,7 @@ class ConnectivityCheckClient
indication, indication,
candidatePair.getRemoteCandidate().getTransportAddress(), candidatePair.getRemoteCandidate().getTransportAddress(),
localCandidate.getBase().getTransportAddress()); localCandidate.getBase().getTransportAddress());
if(logger.isLoggable(Level.FINEST)) if (logger.isLoggable(Level.FINEST))
{ {
logger.finest( logger.finest(
"sending binding indication to pair " + candidatePair); "sending binding indication to pair " + candidatePair);
@ -185,7 +185,7 @@ class ConnectivityCheckClient
{ {
IceSocketWrapper stunSocket = localCandidate.getStunSocket(null); IceSocketWrapper stunSocket = localCandidate.getStunSocket(null);
if(stunSocket != null) if (stunSocket != null)
{ {
logger.log( logger.log(
Level.INFO, Level.INFO,
@ -282,7 +282,7 @@ class ConnectivityCheckClient
.getParentComponent().getParentStream().getName(); .getParentComponent().getParentStream().getName();
String localUserName = parentAgent.generateLocalUserName(media); String localUserName = parentAgent.generateLocalUserName(media);
if(localUserName == null) if (localUserName == null)
return null; return null;
UsernameAttribute unameAttr UsernameAttribute unameAttr
@ -322,7 +322,7 @@ class ConnectivityCheckClient
originalWaitInterval, originalWaitInterval,
maxWaitInterval, maxWaitInterval,
maxRetransmissions); maxRetransmissions);
if(logger.isLoggable(Level.FINEST)) if (logger.isLoggable(Level.FINEST))
{ {
logger.finest( logger.finest(
"checking pair " + candidatePair + " tid " + tran); "checking pair " + candidatePair + " tid " + tran);
@ -334,13 +334,13 @@ class ConnectivityCheckClient
IceSocketWrapper stunSocket = localCandidate.getStunSocket(null); IceSocketWrapper stunSocket = localCandidate.getStunSocket(null);
if(stunSocket != null) if (stunSocket != null)
{ {
String msg String msg
= "Failed to send " + request + " through " = "Failed to send " + request + " through "
+ stunSocket.getLocalSocketAddress() + "."; + stunSocket.getLocalSocketAddress() + ".";
if((ex instanceof NoRouteToHostException) if ((ex instanceof NoRouteToHostException)
|| (ex.getMessage() != null || (ex.getMessage() != null
&& ex.getMessage().equals("No route to host"))) && ex.getMessage().equals("No route to host")))
{ {
@ -383,9 +383,9 @@ class ConnectivityCheckClient
char messageType = response.getMessageType(); char messageType = response.getMessageType();
//handle error responses. //handle error responses.
if(messageType == Response.BINDING_ERROR_RESPONSE) if (messageType == Response.BINDING_ERROR_RESPONSE)
{ {
if(!response.containsAttribute(Attribute.ERROR_CODE)) if (!response.containsAttribute(Attribute.ERROR_CODE))
{ {
logger.fine("Received a malformed error response."); logger.fine("Received a malformed error response.");
return; //malformed error response return; //malformed error response
@ -394,7 +394,7 @@ class ConnectivityCheckClient
processErrorResponse(ev); processErrorResponse(ev);
} }
//handle success responses. //handle success responses.
else if(messageType == Response.BINDING_SUCCESS_RESPONSE) else if (messageType == Response.BINDING_SUCCESS_RESPONSE)
{ {
processSuccessResponse(ev); processSuccessResponse(ev);
} }
@ -419,12 +419,12 @@ class ConnectivityCheckClient
= checkedPair.getParentComponent().getParentStream(); = checkedPair.getParentComponent().getParentStream();
final CheckList checkList = stream.getCheckList(); final CheckList checkList = stream.getCheckList();
if(stream.getParentAgent().getState().isEstablished()) if (stream.getParentAgent().getState().isEstablished())
return; return;
//If all of the pairs in the check list are now either in the Failed or //If all of the pairs in the check list are now either in the Failed or
//Succeeded state: //Succeeded state:
if(checkList.allChecksCompleted()) if (checkList.allChecksCompleted())
{ {
//If there is not a pair in the valid list for each component of the //If there is not a pair in the valid list for each component of the
//media stream, the state of the check list is set to Failed. //media stream, the state of the check list is set to Failed.
@ -433,7 +433,7 @@ class ConnectivityCheckClient
final String streamName = stream.getName(); final String streamName = stream.getName();
Timer timer = timers.get(streamName); Timer timer = timers.get(streamName);
if(timer == null) if (timer == null)
{ {
logger.info("CheckList will failed in a few seconds if no" + logger.info("CheckList will failed in a few seconds if no" +
"succeeded checks come"); "succeeded checks come");
@ -443,7 +443,7 @@ class ConnectivityCheckClient
@Override @Override
public void run() public void run()
{ {
if(checkList.getState() != CheckListState.COMPLETED) if (checkList.getState() != CheckListState.COMPLETED)
{ {
logger.info("CheckList for stream " + logger.info("CheckList for stream " +
streamName + " FAILED"); streamName + " FAILED");
@ -471,7 +471,7 @@ class ConnectivityCheckClient
{ {
CheckList anotherCheckList = anotherStream.getCheckList(); CheckList anotherCheckList = anotherStream.getCheckList();
if(anotherCheckList.isFrozen()) if (anotherCheckList.isFrozen())
{ {
anotherCheckList.computeInitialCheckListPairStates(); anotherCheckList.computeInitialCheckListPairStates();
startChecks(anotherCheckList); startChecks(anotherCheckList);
@ -609,8 +609,11 @@ class ConnectivityCheckClient
//Succeeded. Note that, the pair which *generated* the check may be //Succeeded. Note that, the pair which *generated* the check may be
//different than the valid pair constructed above //different than the valid pair constructed above
if (checkedPair.getParentComponent().getSelectedPair() == null) if (checkedPair.getParentComponent().getSelectedPair() == null)
{
logger.info("Pair succeeded: " + checkedPair.toShortString() logger.info("Pair succeeded: " + checkedPair.toShortString()
+ ". Local ufrag " + parentAgent.getLocalUfrag()); + ". Local ufrag "
+ parentAgent.getLocalUfrag());
}
checkedPair.setStateSucceeded(); checkedPair.setStateSucceeded();
} }
@ -627,12 +630,12 @@ class ConnectivityCheckClient
IceMediaStream parentStream IceMediaStream parentStream
= checkedPair.getParentComponent().getParentStream(); = checkedPair.getParentComponent().getParentStream();
synchronized(this) synchronized (this)
{ {
Vector<CandidatePair> parentCheckList Vector<CandidatePair> parentCheckList
= new Vector<>(parentStream.getCheckList()); = new Vector<>(parentStream.getCheckList());
for(CandidatePair pair : parentCheckList) for (CandidatePair pair : parentCheckList)
{ {
if (pair.getState() == CandidatePairState.FROZEN if (pair.getState() == CandidatePairState.FROZEN
&& checkedPair.getFoundation().equals( && checkedPair.getFoundation().equals(
@ -699,7 +702,7 @@ class ConnectivityCheckClient
if (parentAgent.isControlling() if (parentAgent.isControlling()
&& request.containsAttribute(Attribute.USE_CANDIDATE)) && request.containsAttribute(Attribute.USE_CANDIDATE))
{ {
if(validPair.getParentComponent().getSelectedPair() == null) if (validPair.getParentComponent().getSelectedPair() == null)
{ {
logger.info("Nomination confirmed for pair: " logger.info("Nomination confirmed for pair: "
+ validPair.toShortString() + validPair.toShortString()
@ -721,7 +724,7 @@ class ConnectivityCheckClient
&& checkedPair.useCandidateReceived() && checkedPair.useCandidateReceived()
&& !checkedPair.isNominated()) && !checkedPair.isNominated())
{ {
if(checkedPair.getParentComponent().getSelectedPair() == null) if (checkedPair.getParentComponent().getSelectedPair() == null)
{ {
logger.info( logger.info(
"Nomination confirmed for pair: " "Nomination confirmed for pair: "
@ -800,12 +803,12 @@ class ConnectivityCheckClient
logger.finer("Received error code " + ((int) errorCode)); logger.finer("Received error code " + ((int) errorCode));
//RESOLVE ROLE_CONFLICTS //RESOLVE ROLE_CONFLICTS
if(errorCode == ErrorCodeAttribute.ROLE_CONFLICT) if (errorCode == ErrorCodeAttribute.ROLE_CONFLICT)
{ {
boolean wasControlling boolean wasControlling
= originalRequest.containsAttribute(Attribute.ICE_CONTROLLING); = originalRequest.containsAttribute(Attribute.ICE_CONTROLLING);
logger.finer("Swithing to isControlling=" + !wasControlling); logger.finer("Switching to isControlling=" + !wasControlling);
parentAgent.setControlling(!wasControlling); parentAgent.setControlling(!wasControlling);
pair.getParentComponent().getParentStream().getCheckList() pair.getParentComponent().getParentStream().getCheckList()
@ -916,7 +919,7 @@ class ConnectivityCheckClient
{ {
long waitFor = getNextWaitInterval(); long waitFor = getNextWaitInterval();
if(waitFor > 0) if (waitFor > 0)
{ {
/* /*
* waitFor will be 0 for the first check since we won't * waitFor will be 0 for the first check since we won't
@ -939,10 +942,10 @@ class ConnectivityCheckClient
CandidatePair pairToCheck = checkList.popTriggeredCheck(); CandidatePair pairToCheck = checkList.popTriggeredCheck();
//if there are no triggered checks, go for an ordinary one. //if there are no triggered checks, go for an ordinary one.
if(pairToCheck == null) if (pairToCheck == null)
pairToCheck = checkList.getNextOrdinaryPairToCheck(); pairToCheck = checkList.getNextOrdinaryPairToCheck();
if(pairToCheck != null) if (pairToCheck != null)
{ {
/* /*
* Since we suspect that it is possible to * Since we suspect that it is possible to
@ -956,7 +959,7 @@ class ConnectivityCheckClient
TransactionID transactionID TransactionID transactionID
= startCheckForPair(pairToCheck); = startCheckForPair(pairToCheck);
if(transactionID == null) if (transactionID == null)
{ {
logger.info( logger.info(
"Pair failed: " "Pair failed: "
@ -983,7 +986,7 @@ class ConnectivityCheckClient
{ {
synchronized (paceMakers) synchronized (paceMakers)
{ {
synchronized(this) synchronized (this)
{ {
paceMakers.remove(this); paceMakers.remove(this);
} }
@ -1005,7 +1008,7 @@ class ConnectivityCheckClient
{ {
PaceMaker paceMaker = paceMakersIter.next(); PaceMaker paceMaker = paceMakersIter.next();
synchronized(paceMaker) synchronized (paceMaker)
{ {
paceMaker.running = false; paceMaker.running = false;
paceMaker.notify(); paceMaker.notify();

View File

@ -52,7 +52,7 @@ public class DefaultNominator
/** /**
* Map that will remember association between validated relayed candidate * Map that will remember association between validated relayed candidate
* and a timer. It is use with the NOMINATE_FIRST_HIGHEST_VALID strategy. * and a timer. It is used with the NOMINATE_FIRST_HIGHEST_VALID strategy.
*/ */
private final Map<String, TimerTask> validatedCandidates = new HashMap<>(); private final Map<String, TimerTask> validatedCandidates = new HashMap<>();
@ -86,12 +86,12 @@ public class DefaultNominator
{ {
String propertyName = ev.getPropertyName(); String propertyName = ev.getPropertyName();
if(Agent.PROPERTY_ICE_PROCESSING_STATE.equals(propertyName)) if (Agent.PROPERTY_ICE_PROCESSING_STATE.equals(propertyName))
{ {
if(ev.getNewValue() != IceProcessingState.RUNNING) if (ev.getNewValue() != IceProcessingState.RUNNING)
return; return;
for(IceMediaStream stream : parentAgent.getStreams()) for (IceMediaStream stream : parentAgent.getStreams())
{ {
stream.addPairChangeListener(this); stream.addPairChangeListener(this);
stream.getCheckList().addStateChangeListener(this); stream.getCheckList().addStateChangeListener(this);
@ -104,7 +104,7 @@ public class DefaultNominator
return; return;
} }
if(ev.getSource() instanceof CandidatePair) if (ev.getSource() instanceof CandidatePair)
{ {
// STUN Usage for Consent Freshness is of no concern here. // STUN Usage for Consent Freshness is of no concern here.
if (IceMediaStream.PROPERTY_PAIR_CONSENT_FRESHNESS_CHANGED.equals( if (IceMediaStream.PROPERTY_PAIR_CONSENT_FRESHNESS_CHANGED.equals(
@ -115,7 +115,7 @@ public class DefaultNominator
// do not nominate pair if there is currently a selected pair for // do not nominate pair if there is currently a selected pair for
// the component // the component
if(validPair.getParentComponent().getSelectedPair() != null) if (validPair.getParentComponent().getSelectedPair() != null)
{ {
logger.fine( logger.fine(
"Keep-alive for pair: " + validPair.toShortString()); "Keep-alive for pair: " + validPair.toShortString());
@ -141,7 +141,8 @@ public class DefaultNominator
*/ */
private void strategyNominateFirstValid(PropertyChangeEvent evt) private void strategyNominateFirstValid(PropertyChangeEvent evt)
{ {
if(IceMediaStream.PROPERTY_PAIR_VALIDATED.equals(evt.getPropertyName())) if (IceMediaStream.PROPERTY_PAIR_VALIDATED
.equals(evt.getPropertyName()))
{ {
CandidatePair validPair = (CandidatePair)evt.getSource(); CandidatePair validPair = (CandidatePair)evt.getSource();
@ -163,7 +164,7 @@ public class DefaultNominator
{ {
String pname = ev.getPropertyName(); String pname = ev.getPropertyName();
if(IceMediaStream.PROPERTY_PAIR_VALIDATED.equals(pname) if (IceMediaStream.PROPERTY_PAIR_VALIDATED.equals(pname)
|| (IceMediaStream.PROPERTY_PAIR_STATE_CHANGED.equals(pname) || (IceMediaStream.PROPERTY_PAIR_STATE_CHANGED.equals(pname)
&& (ev.getNewValue() == CandidatePairState.FAILED))) && (ev.getNewValue() == CandidatePairState.FAILED)))
{ {
@ -172,14 +173,14 @@ public class DefaultNominator
IceMediaStream parentStream = parentComponent.getParentStream(); IceMediaStream parentStream = parentComponent.getParentStream();
CheckList parentCheckList = parentStream.getCheckList(); CheckList parentCheckList = parentStream.getCheckList();
if(!parentCheckList.allChecksCompleted()) if (!parentCheckList.allChecksCompleted())
return; return;
for(Component component : parentStream.getComponents()) for (Component component : parentStream.getComponents())
{ {
CandidatePair pair = parentStream.getValidPair(component); CandidatePair pair = parentStream.getValidPair(component);
if(pair != null) if (pair != null)
{ {
logger.info( logger.info(
"Nominate (highest priority): " "Nominate (highest priority): "
@ -215,7 +216,7 @@ public class DefaultNominator
private void strategyNominateFirstHostOrReflexiveValid( private void strategyNominateFirstHostOrReflexiveValid(
PropertyChangeEvent evt) PropertyChangeEvent evt)
{ {
if(IceMediaStream.PROPERTY_PAIR_VALIDATED.equals(evt.getPropertyName())) if (IceMediaStream.PROPERTY_PAIR_VALIDATED.equals(evt.getPropertyName()))
{ {
CandidatePair validPair = (CandidatePair) evt.getSource(); CandidatePair validPair = (CandidatePair) evt.getSource();
@ -229,12 +230,12 @@ public class DefaultNominator
CandidateType.RELAYED_CANDIDATE); CandidateType.RELAYED_CANDIDATE);
boolean nominate = false; boolean nominate = false;
synchronized(validatedCandidates) synchronized (validatedCandidates)
{ {
TimerTask task TimerTask task
= validatedCandidates.get(component.toShortString()); = validatedCandidates.get(component.toShortString());
if(isRelayed && task == null) if (isRelayed && task == null)
{ {
/* armed a timer and see if a host or server reflexive pair /* armed a timer and see if a host or server reflexive pair
* gets nominated. Otherwise nominate the relayed candidate * gets nominated. Otherwise nominate the relayed candidate
@ -247,10 +248,10 @@ public class DefaultNominator
timer.schedule(task, 0); timer.schedule(task, 0);
validatedCandidates.put(component.toShortString(), task); validatedCandidates.put(component.toShortString(), task);
} }
else if(!isRelayed) else if (!isRelayed)
{ {
// host or server reflexive candidate pair // host or server reflexive candidate pair
if(task != null) if (task != null)
{ {
task.cancel(); task.cancel();
logger.info( logger.info(
@ -265,7 +266,7 @@ public class DefaultNominator
} }
} }
if(nominate) if (nominate)
parentAgent.nominate(validPair); parentAgent.nominate(validPair);
} }
} }
@ -314,18 +315,24 @@ public class DefaultNominator
*/ */
public void propertyChange(PropertyChangeEvent evt) public void propertyChange(PropertyChangeEvent evt)
{ {
/* check list has running out of ordinary checks, see if all other // Make it clear that PROPERTY_CHECK_LIST_CHECKS is in use here.
* candidates are FAILED, in which case we nominate immediately if (!CheckList.PROPERTY_CHECK_LIST_CHECKS.equals(
* the relayed candidate evt.getPropertyName()))
*/ {
return;
}
// check list has run out of ordinary checks, see if all other
// candidates are FAILED, in which case we nominate immediately
// the relayed candidate
CheckList checkList = (CheckList)evt.getSource(); CheckList checkList = (CheckList)evt.getSource();
boolean allFailed = true; boolean allFailed = true;
synchronized(checkList) synchronized (checkList)
{ {
for(CandidatePair c : checkList) for (CandidatePair c : checkList)
{ {
if(c != pair && c.getState() != CandidatePairState.FAILED) if (c != pair && c.getState() != CandidatePairState.FAILED)
{ {
allFailed = false; allFailed = false;
break; break;
@ -365,7 +372,7 @@ public class DefaultNominator
{ {
Thread.sleep(WAIT_TIME); Thread.sleep(WAIT_TIME);
} }
catch(InterruptedException e) catch (InterruptedException e)
{ {
cancelled = true; cancelled = true;
} }
@ -376,7 +383,7 @@ public class DefaultNominator
this); this);
validatedCandidates.remove(component.toShortString()); validatedCandidates.remove(component.toShortString());
if(cancelled) if (cancelled)
return; return;
logger.info( logger.info(

View File

@ -191,9 +191,10 @@ public class GoogleRelayedCandidate
* *
* @return the <tt>DatagramSocket</tt> associated with this * @return the <tt>DatagramSocket</tt> associated with this
* <tt>Candidate</tt> * <tt>Candidate</tt>
* @see LocalCandidate#getIceSocketWrapper() * @see LocalCandidate#getCandidateIceSocketWrapper()
*/ */
public synchronized IceSocketWrapper getIceSocketWrapper() @Override
public synchronized IceSocketWrapper getCandidateIceSocketWrapper()
{ {
if (socket == null) if (socket == null)
{ {

View File

@ -131,13 +131,12 @@ public class HostCandidate extends LocalCandidate
} }
/** /**
* Gets the <tt>DatagramSocket</tt> associated with this <tt>Candidate</tt>. * {@inheritDoc}
* * SHOULD NOT be used outside ice4j. Only exposed for use in the
* @return the <tt>DatagramSocket</tt> associated with this * org.ice4j.socket package.
* <tt>Candidate</tt>
* @see LocalCandidate#getIceSocketWrapper()
*/ */
public IceSocketWrapper getIceSocketWrapper() @Override
public IceSocketWrapper getCandidateIceSocketWrapper()
{ {
return socket; return socket;
} }

View File

@ -68,6 +68,19 @@ public class IceMediaStream
*/ */
public static final String PROPERTY_PAIR_VALIDATED = "PairValidated"; public static final String PROPERTY_PAIR_VALIDATED = "PairValidated";
/**
* Use builder pattern to provide an immutable IceMediaStream instance.
*
* @param name the name of the media stream
* @param parentAgent the agent that is handling the session that this
* media stream is a part of
* @return IceMediaStream
*/
public static IceMediaStream build(Agent parentAgent, String name)
{
return new IceMediaStream(parentAgent, name);
}
/** /**
* The name of this media stream. The name is equal to the value specified * The name of this media stream. The name is equal to the value specified
* in the SDP description. * in the SDP description.
@ -272,18 +285,6 @@ public class IceMediaStream
} }
} }
/**
* Returns the number of <tt>Component</tt>s currently registered with this
* stream.
*
* @return the number of <tt>Component</tt>s currently registered with this
* stream.
*/
public int getStreamCount()
{
return getComponentCount();
}
/** /**
* Returns a reference to the <tt>Agent</tt> that this stream belongs to. * Returns a reference to the <tt>Agent</tt> that this stream belongs to.
* *
@ -569,12 +570,12 @@ public class IceMediaStream
{ {
synchronized(checkList) synchronized(checkList)
{ {
for( CandidatePair pair : checkList) for (CandidatePair pair : checkList)
{ {
if( pair.getLocalCandidate().getTransportAddress() if (pair.getLocalCandidate().getTransportAddress()
.equals(localAddress) .equals(localAddress)
&& pair.getRemoteCandidate().getTransportAddress() && pair.getRemoteCandidate().getTransportAddress()
.equals(remoteAddress) ) .equals(remoteAddress))
{ {
return pair; return pair;
} }
@ -599,12 +600,12 @@ public class IceMediaStream
{ {
synchronized(checkList) synchronized(checkList)
{ {
for( CandidatePair pair : checkList) for (CandidatePair pair : checkList)
{ {
LocalCandidate local = pair.getLocalCandidate(); LocalCandidate local = pair.getLocalCandidate();
RemoteCandidate remote = pair.getRemoteCandidate(); RemoteCandidate remote = pair.getRemoteCandidate();
if(local.getUfrag().equals(remoteUFrag) if (local.getUfrag().equals(remoteUFrag)
&& remote.getUfrag().equals(localUFrag)) && remote.getUfrag().equals(localUFrag))
{ {
return pair; return pair;
@ -625,7 +626,7 @@ public class IceMediaStream
synchronized (components) synchronized (components)
{ {
for(Component cmp : components.values()) for (Component cmp : components.values())
num += cmp.countLocalHostCandidates(); num += cmp.countLocalHostCandidates();
} }
@ -657,7 +658,7 @@ public class IceMediaStream
{ {
synchronized (validList) synchronized (validList)
{ {
if(!validList.contains(pair)) if (!validList.contains(pair))
validList.add(pair); validList.add(pair);
} }
@ -678,7 +679,7 @@ public class IceMediaStream
{ {
synchronized(validList) synchronized(validList)
{ {
for(CandidatePair pair : validList) for (CandidatePair pair : validList)
{ {
if (pair.getFoundation().equals(foundation)) if (pair.getFoundation().equals(foundation))
return true; return true;
@ -726,7 +727,7 @@ public class IceMediaStream
*/ */
protected boolean validListContainsAllComponents() protected boolean validListContainsAllComponents()
{ {
for(Component cmp : getComponents()) for (Component cmp : getComponents())
{ {
if (getValidPair(cmp) == null) if (getValidPair(cmp) == null)
{ {
@ -774,9 +775,9 @@ public class IceMediaStream
*/ */
protected boolean allComponentsHaveSelected() protected boolean allComponentsHaveSelected()
{ {
for(Component component : getComponents()) for (Component component : getComponents())
{ {
if(component.getSelectedPair() == null) if (component.getSelectedPair() == null)
return false; return false;
} }
return true; return true;
@ -794,11 +795,11 @@ public class IceMediaStream
*/ */
protected CandidatePair getValidPair(Component component) protected CandidatePair getValidPair(Component component)
{ {
synchronized(validList) synchronized (validList)
{ {
for(CandidatePair pair : validList) for (CandidatePair pair : validList)
{ {
if(pair.getParentComponent() == component) if (pair.getParentComponent() == component)
return pair; return pair;
} }
} }
@ -815,9 +816,9 @@ public class IceMediaStream
*/ */
public void addPairChangeListener(PropertyChangeListener l) public void addPairChangeListener(PropertyChangeListener l)
{ {
synchronized(streamListeners) synchronized (streamListeners)
{ {
if(!streamListeners.contains(l)) if (!streamListeners.contains(l))
streamListeners.add(l); streamListeners.add(l);
} }
} }
@ -830,7 +831,7 @@ public class IceMediaStream
*/ */
public void removePairStateChangeListener(PropertyChangeListener l) public void removePairStateChangeListener(PropertyChangeListener l)
{ {
synchronized(streamListeners) synchronized (streamListeners)
{ {
streamListeners.remove(l); streamListeners.remove(l);
} }
@ -852,7 +853,7 @@ public class IceMediaStream
{ {
PropertyChangeListener[] ls; PropertyChangeListener[] ls;
synchronized(streamListeners) synchronized (streamListeners)
{ {
ls ls
= streamListeners.toArray( = streamListeners.toArray(
@ -862,7 +863,7 @@ public class IceMediaStream
PropertyChangeEvent ev PropertyChangeEvent ev
= new PropertyChangeEvent(source, propertyName, oldValue, newValue); = new PropertyChangeEvent(source, propertyName, oldValue, newValue);
for(PropertyChangeListener l : ls) for (PropertyChangeListener l : ls)
l.propertyChange(ev); l.propertyChange(ev);
} }
@ -910,18 +911,4 @@ public class IceMediaStream
{ {
return remotePassword; return remotePassword;
} }
/**
* Use builder pattern to provide an immutable IceMediaStream instance.
*
* @param name the name of the media stream
* @param parentAgent the agent that is handling the session that this
* media stream is a part of
* @return IceMediaStream
*/
public static IceMediaStream build(Agent parentAgent, String name)
{
return new IceMediaStream(parentAgent, name);
}
} }

View File

@ -108,8 +108,7 @@ public abstract class LocalCandidate
* <tt>Candidate</tt> * <tt>Candidate</tt>
* *
* @deprecated This should be used by the library only. Users of ice4j * @deprecated This should be used by the library only. Users of ice4j
* should use {@link org.ice4j.ice.CandidatePair#getDatagramSocket()} * should use {@link org.ice4j.ice.Component#getSocket()} instead.
* on the appropriate <tt>CandidatePair</tt> instead.
*/ */
@Deprecated @Deprecated
public DatagramSocket getDatagramSocket() public DatagramSocket getDatagramSocket()
@ -126,37 +125,47 @@ public abstract class LocalCandidate
* <tt>Candidate</tt> * <tt>Candidate</tt>
* *
* @deprecated This should be used by the library only. Users of ice4j * @deprecated This should be used by the library only. Users of ice4j
* should use {@link org.ice4j.ice.CandidatePair#getSocket()} on the * should use {@link org.ice4j.ice.Component#getSocket()} instead.
* appropriate <tt>CandidatePair</tt> instead.
*/ */
@Deprecated @Deprecated
public Socket getSocket() public Socket getSocket()
{ {
IceSocketWrapper wrapper = getIceSocketWrapper(); return null;
return wrapper == null ? null : wrapper.getTCPSocket();
} }
/** /**
* Gets the <tt>IceSocketWrapper</tt> associated with this * @return the {@link IceSocketWrapper} instance of the {@link Component}
* <tt>Candidate</tt>. * which owns this {@link LocalCandidate}. Note that this IS NOT an
* * instance specific to this {@link LocalCandidate}. See
* @return the <tt>IceSocketWrapper</tt> associated with this * {@link #getCandidateIceSocketWrapper()}.
* <tt>Candidate</tt>
*/ */
protected abstract IceSocketWrapper getIceSocketWrapper(); protected IceSocketWrapper getIceSocketWrapper()
{
return getParentComponent().getSocketWrapper();
}
/** /**
* Gets the <tt>IceSocketWrapper</tt> associated with this * @return the {@link IceSocketWrapper} instance, if any, associated with
* <tt>Candidate</tt> which is to be used for a specific remote address. * this candidate. Note that this IS NOT the instance which should be used
* This default implementation ignores the remote address. * for reading and writing by the application, and SHOULD NOT be used from
* * outside ice4j (even if a subclass exposes it as public). Also see
* @param remoteAddress the remote address for which to get a socket. * {@link #getIceSocketWrapper()}.
* @return the <tt>IceSocketWrapper</tt> associated with this
* <tt>Candidate</tt> which is to be used for a specific remote address.
*/ */
protected IceSocketWrapper getIceSocketWrapper(SocketAddress remoteAddress) protected abstract IceSocketWrapper getCandidateIceSocketWrapper();
/**
* @return the {@link IceSocketWrapper} instance for this candidate,
* associated with a particular remote address.
* @param remoteAddress the remote address for which to return an
* associated socket.
*/
protected IceSocketWrapper getCandidateIceSocketWrapper(
SocketAddress remoteAddress)
{ {
return getIceSocketWrapper(); // The default implementation just refers to the method which doesn't
// involve a remove address. Extenders which support multiple instances
// mapped by remote address should override.
return getCandidateIceSocketWrapper();
} }
/** /**
@ -174,7 +183,7 @@ public abstract class LocalCandidate
*/ */
public IceSocketWrapper getStunSocket(TransportAddress serverAddress) public IceSocketWrapper getStunSocket(TransportAddress serverAddress)
{ {
IceSocketWrapper hostSocket = getIceSocketWrapper(); IceSocketWrapper hostSocket = getCandidateIceSocketWrapper();
if (hostSocket != null if (hostSocket != null
&& hostSocket.getTCPSocket() != null) && hostSocket.getTCPSocket() != null)
@ -323,7 +332,7 @@ public abstract class LocalCandidate
protected void free() protected void free()
{ {
// Close the socket associated with this LocalCandidate. // Close the socket associated with this LocalCandidate.
IceSocketWrapper socket = getIceSocketWrapper(); IceSocketWrapper socket = getCandidateIceSocketWrapper();
if (socket != null) if (socket != null)
{ {
@ -331,7 +340,7 @@ public abstract class LocalCandidate
if ((base == null) if ((base == null)
|| (base == this) || (base == this)
|| (base.getIceSocketWrapper() != socket)) || (base.getCandidateIceSocketWrapper() != socket))
{ {
//remove our socket from the stack. //remove our socket from the stack.
getStunStack().removeSocket(getTransportAddress()); getStunStack().removeSocket(getTransportAddress());

View File

@ -64,15 +64,11 @@ public class PeerReflexiveCandidate
} }
/** /**
* Returns the <tt>DatagramSocket</tt> associated with this * {@inheritDoc}
* <tt>Candidate</tt>.
*
* @return the <tt>DatagramSocket</tt> associated with this
* <tt>Candidate</tt>
* @see LocalCandidate#getIceSocketWrapper()
*/ */
public IceSocketWrapper getIceSocketWrapper() @Override
public IceSocketWrapper getCandidateIceSocketWrapper()
{ {
return getBase().getIceSocketWrapper(); return getBase().getCandidateIceSocketWrapper();
} }
} }

View File

@ -101,7 +101,7 @@ public class RelayedCandidate
* @return the <tt>RelayedCandidateDatagramSocket</tt> of this * @return the <tt>RelayedCandidateDatagramSocket</tt> of this
* <tt>RelayedCandidate</tt> * <tt>RelayedCandidate</tt>
*/ */
public synchronized RelayedCandidateDatagramSocket private synchronized RelayedCandidateDatagramSocket
getRelayedCandidateDatagramSocket() getRelayedCandidateDatagramSocket()
{ {
if (relayedCandidateDatagramSocket == null) if (relayedCandidateDatagramSocket == null)
@ -127,9 +127,9 @@ public class RelayedCandidate
* *
* @return the <tt>DatagramSocket</tt> associated with this * @return the <tt>DatagramSocket</tt> associated with this
* <tt>Candidate</tt> * <tt>Candidate</tt>
* @see LocalCandidate#getIceSocketWrapper()
*/ */
public synchronized IceSocketWrapper getIceSocketWrapper() @Override
public synchronized IceSocketWrapper getCandidateIceSocketWrapper()
{ {
if (socket == null) if (socket == null)
{ {

View File

@ -104,16 +104,12 @@ public class ServerReflexiveCandidate
} }
/** /**
* Gets the <tt>DatagramSocket</tt> associated with this <tt>Candidate</tt>. * {@inheritDoc}
*
* @return the <tt>DatagramSocket</tt> associated with this
* <tt>Candidate</tt>
* @see LocalCandidate#getIceSocketWrapper()
*/ */
@Override @Override
public IceSocketWrapper getIceSocketWrapper() public IceSocketWrapper getCandidateIceSocketWrapper()
{ {
return getBase().getIceSocketWrapper(); return getBase().getCandidateIceSocketWrapper();
} }
/** /**

View File

@ -54,6 +54,23 @@ public class TcpHostCandidate
super(transportAddress, parentComponent); super(transportAddress, parentComponent);
} }
/**
* {@inheritDoc}
*/
@Override
protected IceSocketWrapper getCandidateIceSocketWrapper(
SocketAddress remoteAddress)
{
for (IceSocketWrapper socket : sockets)
{
if (socket.getTCPSocket().getRemoteSocketAddress()
.equals(remoteAddress))
return socket;
}
return null;
}
public void addSocket(IceSocketWrapper socket) public void addSocket(IceSocketWrapper socket)
{ {
sockets.add(socket); sockets.add(socket);
@ -83,16 +100,4 @@ public class TcpHostCandidate
super.free(); super.free();
} }
@Override
protected IceSocketWrapper getIceSocketWrapper(SocketAddress remoteAddress)
{
for (IceSocketWrapper socket : sockets)
{
if (socket.getTCPSocket().getRemoteSocketAddress()
.equals(remoteAddress))
return socket;
}
return null;
}
} }

View File

@ -79,7 +79,7 @@ public class UPNPCandidate
{ {
} }
IceSocketWrapper socket = getIceSocketWrapper(); IceSocketWrapper socket = getCandidateIceSocketWrapper();
if(socket != null) if(socket != null)
{ {
socket.close(); socket.close();
@ -89,13 +89,19 @@ public class UPNPCandidate
} }
/** /**
* Gets the <tt>DatagramSocket</tt> associated with this <tt>Candidate</tt>. * {@inheritDoc}
*
* @return the <tt>DatagramSocket</tt> associated with this
* <tt>Candidate</tt>
*/ */
@Override @Override
public IceSocketWrapper getIceSocketWrapper() public IceSocketWrapper getCandidateIceSocketWrapper()
{
return getBase().getCandidateIceSocketWrapper();
}
/**
* {@inheritDoc}
*/
@Override
protected IceSocketWrapper getIceSocketWrapper()
{ {
return getBase().getIceSocketWrapper(); return getBase().getIceSocketWrapper();
} }

View File

@ -391,7 +391,7 @@ public abstract class AbstractUdpListener
/** /**
* The remote address that is associated with this socket. * The remote address that is associated with this socket.
*/ */
private SocketAddress remoteAddress; private InetSocketAddress remoteAddress;
/** /**
* The flag which indicates that this <tt>DatagramSocket</tt> has been * The flag which indicates that this <tt>DatagramSocket</tt> has been
@ -406,7 +406,7 @@ public abstract class AbstractUdpListener
* new instance. * new instance.
* @throws SocketException * @throws SocketException
*/ */
public MySocket(SocketAddress remoteAddress) MySocket(InetSocketAddress remoteAddress)
throws SocketException throws SocketException
{ {
// unbound // unbound
@ -487,6 +487,45 @@ public abstract class AbstractUdpListener
return localAddress; return localAddress;
} }
/**
* {@inheritDoc}
* </p>
* This {@link DatagramSocket} will only allow packets from the
* remote address that it has, so we consider it connected to this
* address.
*/
@Override
public SocketAddress getRemoteSocketAddress()
{
return remoteAddress;
}
/**
* {@inheritDoc}
* </p>
* This {@link DatagramSocket} will only allow packets from the
* remote address that it has, so we consider it connected to this
* address.
*/
@Override
public InetAddress getInetAddress()
{
return remoteAddress.getAddress();
}
/**
* {@inheritDoc}
* </p>
* This {@link DatagramSocket} will only allow packets from the
* remote address that it has, so we consider it connected to this
* address.
*/
@Override
public int getPort()
{
return remoteAddress.getPort();
}
/** /**
* {@inheritDoc} * {@inheritDoc}
* *

View File

@ -133,6 +133,14 @@ public class GoogleTurnCandidateHarvest
harvester.getStunStack().addSocket( harvester.getStunStack().addSocket(
relayedCandidate.getStunSocket(null)); relayedCandidate.getStunSocket(null));
// Make the relayed candidate's socket available for reading
// by the component.
IceSocketWrapper candidateSocket
= relayedCandidate.getCandidateIceSocketWrapper();
Component component = relayedCandidate.getParentComponent();
component.getComponentSocket().add(candidateSocket);
addCandidate(relayedCandidate); addCandidate(relayedCandidate);
} }
} }

View File

@ -121,7 +121,7 @@ public class GoogleTurnSSLCandidateHarvester
/** /**
* Returns the host candidate. * Returns the host candidate.
* For UDP it simply returns the candidate passed as paramter * For UDP it simply returns the candidate passed as parameter
* *
* However for TCP, we cannot return the same hostCandidate because in Java * However for TCP, we cannot return the same hostCandidate because in Java
* a "server" socket cannot connect to a destination with the same local * a "server" socket cannot connect to a destination with the same local
@ -146,11 +146,11 @@ public class GoogleTurnSSLCandidateHarvester
if(sslHandshake(inputStream, outputStream)) if(sslHandshake(inputStream, outputStream))
{ {
Component parentComponent = hostCand.getParentComponent(); Component parentComponent = hostCand.getParentComponent();
MultiplexingSocket multiplexing = new MultiplexingSocket(sock);
cand cand
= new HostCandidate( = new HostCandidate(
new IceTcpSocketWrapper( new IceTcpSocketWrapper(multiplexing),
new MultiplexingSocket(sock)),
parentComponent, parentComponent,
Transport.TCP); Transport.TCP);
parentComponent parentComponent
@ -158,6 +158,7 @@ public class GoogleTurnSSLCandidateHarvester
.getParentAgent() .getParentAgent()
.getStunStack() .getStunStack()
.addSocket(cand.getStunSocket(null)); .addSocket(cand.getStunSocket(null));
parentComponent.getComponentSocket().add(multiplexing);
} }
} }
catch (Exception e) catch (Exception e)
@ -187,12 +188,12 @@ public class GoogleTurnSSLCandidateHarvester
/** /**
* Do the SSL handshake (send client certificate and wait for receive server * Do the SSL handshake (send client certificate and wait for receive server
* certificate). We explicitely need <tt>InputStream</tt> and * certificate). We explicitly need <tt>InputStream</tt> and
* <tt>OutputStream</tt> because some <tt>Socket</tt> may redefine * <tt>OutputStream</tt> because some <tt>Socket</tt> may redefine
* getInputStream()/getOutputStream() and we need the original stream. * getInputStream()/getOutputStream() and we need the original stream.
* *
* @param inputStream <tt>InputStream</tt> of the socket * @param inputStream <tt>InputStream</tt> of the socket
* @param outputStream <tt>OuputStream</tt> of the socket * @param outputStream <tt>OutputStream</tt> of the socket
* @return true if the SSL handshake is done * @return true if the SSL handshake is done
* @throws IOException if something goes wrong * @throws IOException if something goes wrong
*/ */

View File

@ -418,6 +418,7 @@ public class HostCandidateHarvester
// checks. In case we have enabled STUN, we are going to use // checks. In case we have enabled STUN, we are going to use
// them as well while harvesting reflexive candidates. // them as well while harvesting reflexive candidates.
createAndRegisterStunSocket(candidate); createAndRegisterStunSocket(candidate);
component.getComponentSocket().add(sock);
} }
} }
} }
@ -569,8 +570,9 @@ public class HostCandidateHarvester
sock.setReuseAddress(true); sock.setReuseAddress(true);
sock.bind(new InetSocketAddress(laddr, port)); sock.bind(new InetSocketAddress(laddr, port));
IceSocketWrapper socket IceSocketWrapper socket
= new IceTcpServerSocketWrapper(sock, = new IceTcpServerSocketWrapper(
component); new DelegatingServerSocket(sock),
component);
if(logger.isLoggable(Level.FINEST)) if(logger.isLoggable(Level.FINEST))
{ {

View File

@ -18,18 +18,14 @@
package org.ice4j.ice.harvest; package org.ice4j.ice.harvest;
import org.ice4j.*; import org.ice4j.*;
import org.ice4j.attribute.*;
import org.ice4j.ice.*; import org.ice4j.ice.*;
import org.ice4j.message.*;
import org.ice4j.socket.*; import org.ice4j.socket.*;
import org.ice4j.stack.*; import org.ice4j.stack.*;
import org.ice4j.util.*;
import java.io.*; import java.io.*;
import java.net.*; import java.net.*;
import java.util.*; import java.util.*;
import java.util.concurrent.*; import java.util.concurrent.*;
import java.util.logging.*;
import java.util.logging.Logger; // Disambiguation import java.util.logging.Logger; // Disambiguation
/** /**
@ -230,26 +226,27 @@ public class SinglePortUdpHarvester
* The collection of <tt>IceSocketWrapper</tt>s that can potentially * The collection of <tt>IceSocketWrapper</tt>s that can potentially
* be used by the ice4j user to read/write from/to this candidate. * be used by the ice4j user to read/write from/to this candidate.
* The keys are the remote addresses for each socket. * The keys are the remote addresses for each socket.
* * <p>
* There are wrappers over <tt>MultiplexedDatagramSocket</tt>s over * There are wrappers over <tt>MultiplexedDatagramSocket</tt>s over
* a corresponding socket in {@link #sockets}. * a corresponding socket in {@link #sockets}.
*/ */
private final Map<SocketAddress, IceSocketWrapper> candidateSockets private final Map<SocketAddress, IceSocketWrapper> candidateSockets
= new HashMap<>(); = new HashMap<>();
/** /**
* The collection of <tt>DatagramSocket</tt>s added to this candidate. * The collection of <tt>DatagramSocket</tt>s added to this candidate.
* The keys are the remote addresses for each socket. * The keys are the remote addresses for each socket.
* * <p>
* These are the "raw" sockets, before any wrappers are added for * These are the "raw" sockets, before any wrappers are added for
* the STUN stack or the user of ice4j. * the STUN stack or the user of ice4j.
*/ */
private final Map<SocketAddress, DatagramSocket> sockets private final Map<SocketAddress, DatagramSocket> sockets
= new HashMap<>(); = new HashMap<>();
/** /**
* Initializes a new <tt>MyCandidate</tt> instance with the given * Initializes a new <tt>MyCandidate</tt> instance with the given
* <tt>Component</tt> and the given local username fragment. * <tt>Component</tt> and the given local username fragment.
*
* @param component the <tt>Component</tt> for which this candidate will * @param component the <tt>Component</tt> for which this candidate will
* serve. * serve.
* @param ufrag the local ICE username fragment for this candidate (and * @param ufrag the local ICE username fragment for this candidate (and
@ -263,7 +260,7 @@ public class SinglePortUdpHarvester
/** /**
* {@inheritDoc} * {@inheritDoc}
* * <p>
* Closes all sockets in use by this <tt>LocalCandidate</tt>. * Closes all sockets in use by this <tt>LocalCandidate</tt>.
*/ */
@Override @Override
@ -283,20 +280,21 @@ public class SinglePortUdpHarvester
StunStack stunStack = getStunStack(); StunStack stunStack = getStunStack();
for (Map.Entry<SocketAddress, DatagramSocket> e for (Map.Entry<SocketAddress, DatagramSocket> e
: sockets.entrySet()) : sockets.entrySet())
{ {
DatagramSocket socket = e.getValue(); DatagramSocket socket = e.getValue();
if (stunStack != null) if (stunStack != null)
{ {
TransportAddress localAddress TransportAddress localAddress
= new TransportAddress(socket.getLocalAddress(), = new TransportAddress(socket.getLocalAddress(),
socket.getLocalPort(), socket.getLocalPort(),
Transport.UDP); Transport.UDP);
TransportAddress remoteAddress TransportAddress remoteAddress
= new TransportAddress((InetSocketAddress) e.getKey(), = new TransportAddress(
(InetSocketAddress) e.getKey(),
Transport.UDP); Transport.UDP);
stunStack.removeSocket(localAddress, remoteAddress); stunStack.removeSocket(localAddress, remoteAddress);
} }
@ -318,11 +316,12 @@ public class SinglePortUdpHarvester
/** /**
* Adds a new <tt>Socket</tt> to this candidate, which is associated * Adds a new <tt>Socket</tt> to this candidate, which is associated
* with a particular remote address. * with a particular remote address.
*
* @param socket the socket to add. * @param socket the socket to add.
* @param remoteAddress the remote address for the socket. * @param remoteAddress the remote address for the socket.
*/ */
private synchronized void addSocket(DatagramSocket socket, private synchronized void addSocket(DatagramSocket socket,
InetSocketAddress remoteAddress) InetSocketAddress remoteAddress)
throws IOException throws IOException
{ {
if (freed) if (freed)
@ -337,16 +336,16 @@ public class SinglePortUdpHarvester
} }
IceProcessingState state IceProcessingState state
= component.getParentStream().getParentAgent().getState(); = component.getParentStream().getParentAgent().getState();
if (!IceProcessingState.WAITING.equals(state) if (!IceProcessingState.WAITING.equals(state)
&& !IceProcessingState.RUNNING.equals(state)) && !IceProcessingState.RUNNING.equals(state))
{ {
throw new IOException( throw new IOException(
"Agent state is " + state + ". Cannot add socket."); "Agent state is " + state + ". Cannot add socket.");
} }
MultiplexingDatagramSocket multiplexing MultiplexingDatagramSocket multiplexing
= new MultiplexingDatagramSocket(socket); = new MultiplexingDatagramSocket(socket);
// Socket to add to the candidate // Socket to add to the candidate
IceSocketWrapper candidateSocket IceSocketWrapper candidateSocket
@ -355,13 +354,15 @@ public class SinglePortUdpHarvester
// STUN-only filtered socket to add to the StunStack // STUN-only filtered socket to add to the StunStack
IceSocketWrapper stunSocket IceSocketWrapper stunSocket
= new IceUdpSocketWrapper( = new IceUdpSocketWrapper(
multiplexing.getSocket(new StunDatagramPacketFilter())); multiplexing.getSocket(new StunDatagramPacketFilter()));
component.getParentStream().getParentAgent().getStunStack() component.getParentStream().getParentAgent().getStunStack()
.addSocket( .addSocket(
stunSocket, stunSocket,
new TransportAddress(remoteAddress, Transport.UDP)); new TransportAddress(remoteAddress, Transport.UDP));
// TODO: maybe move this code to the candidates.
component.getComponentSocket().add(multiplexing);
// XXX is this necessary? // XXX is this necessary?
synchronized (candidateSockets) synchronized (candidateSockets)
@ -375,14 +376,15 @@ public class SinglePortUdpHarvester
sockets.put(remoteAddress, socket); sockets.put(remoteAddress, socket);
} }
} }
/** /**
* {@inheritDoc} * {@inheritDoc}
*/ */
@Override @Override
public IceSocketWrapper getIceSocketWrapper(SocketAddress remoteAddress) protected IceSocketWrapper getCandidateIceSocketWrapper(
SocketAddress remoteAddress)
{ {
return candidateSockets.get(remoteAddress); return candidateSockets.get(remoteAddress);
} }
} }
} }

View File

@ -441,7 +441,7 @@ public class StunCandidateHarvester
*/ */
protected HostCandidate getHostCandidate(HostCandidate hostCand) protected HostCandidate getHostCandidate(HostCandidate hostCand)
{ {
HostCandidate cand = null; HostCandidate cand;
// create a new TCP HostCandidate // create a new TCP HostCandidate
if(hostCand.getTransport() == Transport.TCP) if(hostCand.getTransport() == Transport.TCP)
@ -450,12 +450,15 @@ public class StunCandidateHarvester
{ {
Socket sock = new Socket(stunServer.getAddress(), Socket sock = new Socket(stunServer.getAddress(),
stunServer.getPort()); stunServer.getPort());
cand = new HostCandidate(new IceTcpSocketWrapper( MultiplexingSocket multiplexing = new MultiplexingSocket(sock);
new MultiplexingSocket(sock)), cand
hostCand.getParentComponent(), Transport.TCP); = new HostCandidate(
new IceTcpSocketWrapper(multiplexing),
hostCand.getParentComponent(), Transport.TCP);
hostCand.getParentComponent().getParentStream(). hostCand.getParentComponent().getParentStream().
getParentAgent().getStunStack().addSocket( getParentAgent().getStunStack().addSocket(
cand.getStunSocket(null)); cand.getStunSocket(null));
hostCand.getParentComponent().getComponentSocket().add(multiplexing);
} }
catch(Exception io) catch(Exception io)
{ {

View File

@ -488,11 +488,11 @@ public class TcpHarvester
IceProcessingState state IceProcessingState state
= component.getParentStream().getParentAgent().getState(); = component.getParentStream().getParentAgent().getState();
if (!IceProcessingState.WAITING.equals(state) if (logger.isLoggable(Level.FINE)
&& !IceProcessingState.WAITING.equals(state)
&& !IceProcessingState.RUNNING.equals(state)) && !IceProcessingState.RUNNING.equals(state))
{ {
throw new IllegalStateException( logger.fine("Adding a socket to an Agent in state " + state);
"The associated Agent is in state " + state);
} }
// Socket to add to the candidate // Socket to add to the candidate
@ -518,6 +518,10 @@ public class TcpHarvester
component.getParentStream().getParentAgent().getStunStack() component.getParentStream().getParentAgent().getStunStack()
.addSocket(stunSocket); .addSocket(stunSocket);
candidate.addSocket(candidateSocket); candidate.addSocket(candidateSocket);
// TODO: Maybe move this code to the candidate.
component.getComponentSocket().add(multiplexing);
// the socket is not our responsibility anymore. It is up to // the socket is not our responsibility anymore. It is up to
// the candidate/component to close/free it. // the candidate/component to close/free it.
} }

View File

@ -258,6 +258,8 @@ public class TurnCandidateHarvest
harvester.getStunStack().addSocket( harvester.getStunStack().addSocket(
relayedCandidate.getStunSocket(null)); relayedCandidate.getStunSocket(null));
relayedCandidate.getParentComponent().getComponentSocket().add(
relayedCandidate.getCandidateIceSocketWrapper());
addCandidate(relayedCandidate); addCandidate(relayedCandidate);
} }
} }

View File

@ -203,25 +203,27 @@ public class UPNPHarvester
* @param socket local socket * @param socket local socket
* @param externalIP external IP address * @param externalIP external IP address
* @param port local port * @param port local port
* @param cmp parent component * @param component parent component
* @param device the UPnP gateway device * @param device the UPnP gateway device
* @return a new <tt>UPNPCandidate</tt> instance which * @return a new <tt>UPNPCandidate</tt> instance which
* represents the specified <tt>TransportAddress</tt> * represents the specified <tt>TransportAddress</tt>
* @throws Exception if something goes wrong during candidate creation * @throws Exception if something goes wrong during candidate creation
*/ */
public List<LocalCandidate> createUPNPCandidate(IceSocketWrapper socket, private List<LocalCandidate> createUPNPCandidate(IceSocketWrapper socket,
String externalIP, int port, Component cmp, GatewayDevice device) String externalIP, int port, Component component, GatewayDevice device)
throws Exception throws Exception
{ {
List<LocalCandidate> ret = new ArrayList<>(); List<LocalCandidate> ret = new ArrayList<>();
TransportAddress addr TransportAddress addr
= new TransportAddress(externalIP, port, Transport.UDP); = new TransportAddress(externalIP, port, Transport.UDP);
HostCandidate base = new HostCandidate(socket, cmp); HostCandidate base = new HostCandidate(socket, component);
UPNPCandidate candidate = new UPNPCandidate(addr, base, cmp, device); UPNPCandidate candidate
= new UPNPCandidate(addr, base, component, device);
IceSocketWrapper stunSocket = candidate.getStunSocket(null); IceSocketWrapper stunSocket = candidate.getStunSocket(null);
candidate.getStunStack().addSocket(stunSocket); candidate.getStunStack().addSocket(stunSocket);
component.getComponentSocket().add(candidate.getCandidateIceSocketWrapper());
ret.add(candidate); ret.add(candidate);
ret.add(base); ret.add(base);

View File

@ -662,6 +662,12 @@ public class DelegatingDatagramSocket
// after the first packet is received, the length is set to the size // after the first packet is received, the length is set to the size
// of the first packet and the second packet is truncated. // of the first packet and the second packet is truncated.
// http://docs.oracle.com/javase/6/docs/api/java/net/DatagramSocket.html // http://docs.oracle.com/javase/6/docs/api/java/net/DatagramSocket.html
//
// XXX(boris): I think the above is wrong. I don't interpret the
// API description this way, and testing on a couple of different
// environments shows that DatagramSocket.receive() grows the
// packet's length to as much as much as the array (and offset)
// would allow. I am leaving the code because it seems harmless.
byte[] data = p.getData(); byte[] data = p.getData();
p.setLength((data == null) ? 0 : (data.length - p.getOffset())); p.setLength((data == null) ? 0 : (data.length - p.getOffset()));

View File

@ -195,6 +195,7 @@ public class IceTcpServerSocketWrapper
component.getParentStream().getParentAgent(). component.getParentStream().getParentAgent().
getStunStack().addSocket( getStunStack().addSocket(
new IceTcpSocketWrapper(multiplexingSocket)); new IceTcpSocketWrapper(multiplexingSocket));
component.getComponentSocket().add(multiplexingSocket);
sockets.add(multiplexingSocket); sockets.add(multiplexingSocket);
} }

File diff suppressed because it is too large Load Diff

View File

@ -208,8 +208,8 @@ public class RelayedCandidateDatagramSocket
this); this);
DatagramSocket hostSocket DatagramSocket hostSocket
= this.turnCandidateHarvest.hostCandidate.getIceSocketWrapper(). = this.turnCandidateHarvest.hostCandidate
getUDPSocket(); .getCandidateIceSocketWrapper().getUDPSocket();
if (hostSocket instanceof MultiplexingDatagramSocket) if (hostSocket instanceof MultiplexingDatagramSocket)
{ {

View File

@ -0,0 +1,37 @@
/*
* ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
*
* Copyright @ 2015-2016 Atlassian Pty Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.ice4j.socket;
import java.net.*;
/**
* An exception that indicates that a socket is closed.
*/
public class SocketClosedException
extends SocketException
{
/**
* Initializes a new {@link SocketClosedException}.
*/
public SocketClosedException()
{
// Keep the same message as the one used by jdk, since existing code
// might be matching against the string.
super("Socket closed");
}
}

View File

@ -386,7 +386,7 @@ public class IcePseudoTcp
private static class LocalPseudoTcpJob extends Thread implements Runnable private static class LocalPseudoTcpJob extends Thread implements Runnable
{ {
private DatagramSocket dgramSocket; private DatagramSocket dgramSocket;
public LocalPseudoTcpJob(DatagramSocket socket) public LocalPseudoTcpJob(DatagramSocket socket)
throws UnknownHostException throws UnknownHostException