validatedCandidates = new HashMap<>();
@@ -86,12 +86,12 @@ public class DefaultNominator
{
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;
- for(IceMediaStream stream : parentAgent.getStreams())
+ for (IceMediaStream stream : parentAgent.getStreams())
{
stream.addPairChangeListener(this);
stream.getCheckList().addStateChangeListener(this);
@@ -104,7 +104,7 @@ public class DefaultNominator
return;
}
- if(ev.getSource() instanceof CandidatePair)
+ if (ev.getSource() instanceof CandidatePair)
{
// STUN Usage for Consent Freshness is of no concern here.
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
// the component
- if(validPair.getParentComponent().getSelectedPair() != null)
+ if (validPair.getParentComponent().getSelectedPair() != null)
{
logger.fine(
"Keep-alive for pair: " + validPair.toShortString());
@@ -141,7 +141,8 @@ public class DefaultNominator
*/
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();
@@ -163,7 +164,7 @@ public class DefaultNominator
{
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)
&& (ev.getNewValue() == CandidatePairState.FAILED)))
{
@@ -172,14 +173,14 @@ public class DefaultNominator
IceMediaStream parentStream = parentComponent.getParentStream();
CheckList parentCheckList = parentStream.getCheckList();
- if(!parentCheckList.allChecksCompleted())
+ if (!parentCheckList.allChecksCompleted())
return;
- for(Component component : parentStream.getComponents())
+ for (Component component : parentStream.getComponents())
{
CandidatePair pair = parentStream.getValidPair(component);
- if(pair != null)
+ if (pair != null)
{
logger.info(
"Nominate (highest priority): "
@@ -215,7 +216,7 @@ public class DefaultNominator
private void strategyNominateFirstHostOrReflexiveValid(
PropertyChangeEvent evt)
{
- if(IceMediaStream.PROPERTY_PAIR_VALIDATED.equals(evt.getPropertyName()))
+ if (IceMediaStream.PROPERTY_PAIR_VALIDATED.equals(evt.getPropertyName()))
{
CandidatePair validPair = (CandidatePair) evt.getSource();
@@ -229,12 +230,12 @@ public class DefaultNominator
CandidateType.RELAYED_CANDIDATE);
boolean nominate = false;
- synchronized(validatedCandidates)
+ synchronized (validatedCandidates)
{
TimerTask task
= validatedCandidates.get(component.toShortString());
- if(isRelayed && task == null)
+ if (isRelayed && task == null)
{
/* armed a timer and see if a host or server reflexive pair
* gets nominated. Otherwise nominate the relayed candidate
@@ -247,10 +248,10 @@ public class DefaultNominator
timer.schedule(task, 0);
validatedCandidates.put(component.toShortString(), task);
}
- else if(!isRelayed)
+ else if (!isRelayed)
{
// host or server reflexive candidate pair
- if(task != null)
+ if (task != null)
{
task.cancel();
logger.info(
@@ -265,7 +266,7 @@ public class DefaultNominator
}
}
- if(nominate)
+ if (nominate)
parentAgent.nominate(validPair);
}
}
@@ -314,18 +315,24 @@ public class DefaultNominator
*/
public void propertyChange(PropertyChangeEvent evt)
{
- /* check list has running out of ordinary checks, see if all other
- * candidates are FAILED, in which case we nominate immediately
- * the relayed candidate
- */
+ // Make it clear that PROPERTY_CHECK_LIST_CHECKS is in use here.
+ if (!CheckList.PROPERTY_CHECK_LIST_CHECKS.equals(
+ 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();
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;
break;
@@ -365,7 +372,7 @@ public class DefaultNominator
{
Thread.sleep(WAIT_TIME);
}
- catch(InterruptedException e)
+ catch (InterruptedException e)
{
cancelled = true;
}
@@ -376,7 +383,7 @@ public class DefaultNominator
this);
validatedCandidates.remove(component.toShortString());
- if(cancelled)
+ if (cancelled)
return;
logger.info(
diff --git a/src/main/java/org/ice4j/ice/GoogleRelayedCandidate.java b/src/main/java/org/ice4j/ice/GoogleRelayedCandidate.java
index 5c6b81d..be5e199 100644
--- a/src/main/java/org/ice4j/ice/GoogleRelayedCandidate.java
+++ b/src/main/java/org/ice4j/ice/GoogleRelayedCandidate.java
@@ -191,9 +191,10 @@ public class GoogleRelayedCandidate
*
* @return the DatagramSocket associated with this
* Candidate
- * @see LocalCandidate#getIceSocketWrapper()
+ * @see LocalCandidate#getCandidateIceSocketWrapper()
*/
- public synchronized IceSocketWrapper getIceSocketWrapper()
+ @Override
+ public synchronized IceSocketWrapper getCandidateIceSocketWrapper()
{
if (socket == null)
{
diff --git a/src/main/java/org/ice4j/ice/HostCandidate.java b/src/main/java/org/ice4j/ice/HostCandidate.java
index d9cc77c..236c4d2 100644
--- a/src/main/java/org/ice4j/ice/HostCandidate.java
+++ b/src/main/java/org/ice4j/ice/HostCandidate.java
@@ -131,13 +131,12 @@ public class HostCandidate extends LocalCandidate
}
/**
- * Gets the DatagramSocket associated with this Candidate.
- *
- * @return the DatagramSocket associated with this
- * Candidate
- * @see LocalCandidate#getIceSocketWrapper()
+ * {@inheritDoc}
+ * SHOULD NOT be used outside ice4j. Only exposed for use in the
+ * org.ice4j.socket package.
*/
- public IceSocketWrapper getIceSocketWrapper()
+ @Override
+ public IceSocketWrapper getCandidateIceSocketWrapper()
{
return socket;
}
diff --git a/src/main/java/org/ice4j/ice/IceMediaStream.java b/src/main/java/org/ice4j/ice/IceMediaStream.java
index ea11e68..894293c 100644
--- a/src/main/java/org/ice4j/ice/IceMediaStream.java
+++ b/src/main/java/org/ice4j/ice/IceMediaStream.java
@@ -68,6 +68,19 @@ public class IceMediaStream
*/
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
* in the SDP description.
@@ -272,18 +285,6 @@ public class IceMediaStream
}
}
- /**
- * Returns the number of Components currently registered with this
- * stream.
- *
- * @return the number of Components currently registered with this
- * stream.
- */
- public int getStreamCount()
- {
- return getComponentCount();
- }
-
/**
* Returns a reference to the Agent that this stream belongs to.
*
@@ -569,12 +570,12 @@ public class IceMediaStream
{
synchronized(checkList)
{
- for( CandidatePair pair : checkList)
+ for (CandidatePair pair : checkList)
{
- if( pair.getLocalCandidate().getTransportAddress()
+ if (pair.getLocalCandidate().getTransportAddress()
.equals(localAddress)
&& pair.getRemoteCandidate().getTransportAddress()
- .equals(remoteAddress) )
+ .equals(remoteAddress))
{
return pair;
}
@@ -599,12 +600,12 @@ public class IceMediaStream
{
synchronized(checkList)
{
- for( CandidatePair pair : checkList)
+ for (CandidatePair pair : checkList)
{
LocalCandidate local = pair.getLocalCandidate();
RemoteCandidate remote = pair.getRemoteCandidate();
- if(local.getUfrag().equals(remoteUFrag)
+ if (local.getUfrag().equals(remoteUFrag)
&& remote.getUfrag().equals(localUFrag))
{
return pair;
@@ -625,7 +626,7 @@ public class IceMediaStream
synchronized (components)
{
- for(Component cmp : components.values())
+ for (Component cmp : components.values())
num += cmp.countLocalHostCandidates();
}
@@ -657,7 +658,7 @@ public class IceMediaStream
{
synchronized (validList)
{
- if(!validList.contains(pair))
+ if (!validList.contains(pair))
validList.add(pair);
}
@@ -678,7 +679,7 @@ public class IceMediaStream
{
synchronized(validList)
{
- for(CandidatePair pair : validList)
+ for (CandidatePair pair : validList)
{
if (pair.getFoundation().equals(foundation))
return true;
@@ -726,7 +727,7 @@ public class IceMediaStream
*/
protected boolean validListContainsAllComponents()
{
- for(Component cmp : getComponents())
+ for (Component cmp : getComponents())
{
if (getValidPair(cmp) == null)
{
@@ -774,9 +775,9 @@ public class IceMediaStream
*/
protected boolean allComponentsHaveSelected()
{
- for(Component component : getComponents())
+ for (Component component : getComponents())
{
- if(component.getSelectedPair() == null)
+ if (component.getSelectedPair() == null)
return false;
}
return true;
@@ -794,11 +795,11 @@ public class IceMediaStream
*/
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;
}
}
@@ -815,9 +816,9 @@ public class IceMediaStream
*/
public void addPairChangeListener(PropertyChangeListener l)
{
- synchronized(streamListeners)
+ synchronized (streamListeners)
{
- if(!streamListeners.contains(l))
+ if (!streamListeners.contains(l))
streamListeners.add(l);
}
}
@@ -830,7 +831,7 @@ public class IceMediaStream
*/
public void removePairStateChangeListener(PropertyChangeListener l)
{
- synchronized(streamListeners)
+ synchronized (streamListeners)
{
streamListeners.remove(l);
}
@@ -852,7 +853,7 @@ public class IceMediaStream
{
PropertyChangeListener[] ls;
- synchronized(streamListeners)
+ synchronized (streamListeners)
{
ls
= streamListeners.toArray(
@@ -862,7 +863,7 @@ public class IceMediaStream
PropertyChangeEvent ev
= new PropertyChangeEvent(source, propertyName, oldValue, newValue);
- for(PropertyChangeListener l : ls)
+ for (PropertyChangeListener l : ls)
l.propertyChange(ev);
}
@@ -910,18 +911,4 @@ public class IceMediaStream
{
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);
- }
-
}
diff --git a/src/main/java/org/ice4j/ice/LocalCandidate.java b/src/main/java/org/ice4j/ice/LocalCandidate.java
index 8e05090..b362b0d 100644
--- a/src/main/java/org/ice4j/ice/LocalCandidate.java
+++ b/src/main/java/org/ice4j/ice/LocalCandidate.java
@@ -108,8 +108,7 @@ public abstract class LocalCandidate
* Candidate
*
* @deprecated This should be used by the library only. Users of ice4j
- * should use {@link org.ice4j.ice.CandidatePair#getDatagramSocket()}
- * on the appropriate CandidatePair instead.
+ * should use {@link org.ice4j.ice.Component#getSocket()} instead.
*/
@Deprecated
public DatagramSocket getDatagramSocket()
@@ -126,37 +125,47 @@ public abstract class LocalCandidate
* Candidate
*
* @deprecated This should be used by the library only. Users of ice4j
- * should use {@link org.ice4j.ice.CandidatePair#getSocket()} on the
- * appropriate CandidatePair instead.
+ * should use {@link org.ice4j.ice.Component#getSocket()} instead.
*/
@Deprecated
public Socket getSocket()
{
- IceSocketWrapper wrapper = getIceSocketWrapper();
- return wrapper == null ? null : wrapper.getTCPSocket();
+ return null;
}
/**
- * Gets the IceSocketWrapper associated with this
- * Candidate.
- *
- * @return the IceSocketWrapper associated with this
- * Candidate
+ * @return the {@link IceSocketWrapper} instance of the {@link Component}
+ * which owns this {@link LocalCandidate}. Note that this IS NOT an
+ * instance specific to this {@link LocalCandidate}. See
+ * {@link #getCandidateIceSocketWrapper()}.
*/
- protected abstract IceSocketWrapper getIceSocketWrapper();
+ protected IceSocketWrapper getIceSocketWrapper()
+ {
+ return getParentComponent().getSocketWrapper();
+ }
/**
- * Gets the IceSocketWrapper associated with this
- * Candidate which is to be used for a specific remote address.
- * This default implementation ignores the remote address.
- *
- * @param remoteAddress the remote address for which to get a socket.
- * @return the IceSocketWrapper associated with this
- * Candidate which is to be used for a specific remote address.
+ * @return the {@link IceSocketWrapper} instance, if any, associated with
+ * this candidate. Note that this IS NOT the instance which should be used
+ * 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
+ * {@link #getIceSocketWrapper()}.
*/
- 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)
{
- IceSocketWrapper hostSocket = getIceSocketWrapper();
+ IceSocketWrapper hostSocket = getCandidateIceSocketWrapper();
if (hostSocket != null
&& hostSocket.getTCPSocket() != null)
@@ -323,7 +332,7 @@ public abstract class LocalCandidate
protected void free()
{
// Close the socket associated with this LocalCandidate.
- IceSocketWrapper socket = getIceSocketWrapper();
+ IceSocketWrapper socket = getCandidateIceSocketWrapper();
if (socket != null)
{
@@ -331,7 +340,7 @@ public abstract class LocalCandidate
if ((base == null)
|| (base == this)
- || (base.getIceSocketWrapper() != socket))
+ || (base.getCandidateIceSocketWrapper() != socket))
{
//remove our socket from the stack.
getStunStack().removeSocket(getTransportAddress());
diff --git a/src/main/java/org/ice4j/ice/PeerReflexiveCandidate.java b/src/main/java/org/ice4j/ice/PeerReflexiveCandidate.java
index 02ea7ab..9ad34f5 100644
--- a/src/main/java/org/ice4j/ice/PeerReflexiveCandidate.java
+++ b/src/main/java/org/ice4j/ice/PeerReflexiveCandidate.java
@@ -64,15 +64,11 @@ public class PeerReflexiveCandidate
}
/**
- * Returns the DatagramSocket associated with this
- * Candidate.
- *
- * @return the DatagramSocket associated with this
- * Candidate
- * @see LocalCandidate#getIceSocketWrapper()
+ * {@inheritDoc}
*/
- public IceSocketWrapper getIceSocketWrapper()
+ @Override
+ public IceSocketWrapper getCandidateIceSocketWrapper()
{
- return getBase().getIceSocketWrapper();
+ return getBase().getCandidateIceSocketWrapper();
}
}
diff --git a/src/main/java/org/ice4j/ice/RelayedCandidate.java b/src/main/java/org/ice4j/ice/RelayedCandidate.java
index 08a89c5..8140034 100644
--- a/src/main/java/org/ice4j/ice/RelayedCandidate.java
+++ b/src/main/java/org/ice4j/ice/RelayedCandidate.java
@@ -101,7 +101,7 @@ public class RelayedCandidate
* @return the RelayedCandidateDatagramSocket of this
* RelayedCandidate
*/
- public synchronized RelayedCandidateDatagramSocket
+ private synchronized RelayedCandidateDatagramSocket
getRelayedCandidateDatagramSocket()
{
if (relayedCandidateDatagramSocket == null)
@@ -127,9 +127,9 @@ public class RelayedCandidate
*
* @return the DatagramSocket associated with this
* Candidate
- * @see LocalCandidate#getIceSocketWrapper()
*/
- public synchronized IceSocketWrapper getIceSocketWrapper()
+ @Override
+ public synchronized IceSocketWrapper getCandidateIceSocketWrapper()
{
if (socket == null)
{
diff --git a/src/main/java/org/ice4j/ice/ServerReflexiveCandidate.java b/src/main/java/org/ice4j/ice/ServerReflexiveCandidate.java
index d0105f2..6dc21d5 100644
--- a/src/main/java/org/ice4j/ice/ServerReflexiveCandidate.java
+++ b/src/main/java/org/ice4j/ice/ServerReflexiveCandidate.java
@@ -104,16 +104,12 @@ public class ServerReflexiveCandidate
}
/**
- * Gets the DatagramSocket associated with this Candidate.
- *
- * @return the DatagramSocket associated with this
- * Candidate
- * @see LocalCandidate#getIceSocketWrapper()
+ * {@inheritDoc}
*/
@Override
- public IceSocketWrapper getIceSocketWrapper()
+ public IceSocketWrapper getCandidateIceSocketWrapper()
{
- return getBase().getIceSocketWrapper();
+ return getBase().getCandidateIceSocketWrapper();
}
/**
diff --git a/src/main/java/org/ice4j/ice/TcpHostCandidate.java b/src/main/java/org/ice4j/ice/TcpHostCandidate.java
index 8cd96d4..7d3254f 100644
--- a/src/main/java/org/ice4j/ice/TcpHostCandidate.java
+++ b/src/main/java/org/ice4j/ice/TcpHostCandidate.java
@@ -54,6 +54,23 @@ public class TcpHostCandidate
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)
{
sockets.add(socket);
@@ -83,16 +100,4 @@ public class TcpHostCandidate
super.free();
}
- @Override
- protected IceSocketWrapper getIceSocketWrapper(SocketAddress remoteAddress)
- {
- for (IceSocketWrapper socket : sockets)
- {
- if (socket.getTCPSocket().getRemoteSocketAddress()
- .equals(remoteAddress))
- return socket;
- }
-
- return null;
- }
}
diff --git a/src/main/java/org/ice4j/ice/UPNPCandidate.java b/src/main/java/org/ice4j/ice/UPNPCandidate.java
index 74646b3..6525d18 100644
--- a/src/main/java/org/ice4j/ice/UPNPCandidate.java
+++ b/src/main/java/org/ice4j/ice/UPNPCandidate.java
@@ -79,7 +79,7 @@ public class UPNPCandidate
{
}
- IceSocketWrapper socket = getIceSocketWrapper();
+ IceSocketWrapper socket = getCandidateIceSocketWrapper();
if(socket != null)
{
socket.close();
@@ -89,13 +89,19 @@ public class UPNPCandidate
}
/**
- * Gets the DatagramSocket associated with this Candidate.
- *
- * @return the DatagramSocket associated with this
- * Candidate
+ * {@inheritDoc}
*/
@Override
- public IceSocketWrapper getIceSocketWrapper()
+ public IceSocketWrapper getCandidateIceSocketWrapper()
+ {
+ return getBase().getCandidateIceSocketWrapper();
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ protected IceSocketWrapper getIceSocketWrapper()
{
return getBase().getIceSocketWrapper();
}
diff --git a/src/main/java/org/ice4j/ice/harvest/AbstractUdpListener.java b/src/main/java/org/ice4j/ice/harvest/AbstractUdpListener.java
index 3ef9840..ddab37e 100644
--- a/src/main/java/org/ice4j/ice/harvest/AbstractUdpListener.java
+++ b/src/main/java/org/ice4j/ice/harvest/AbstractUdpListener.java
@@ -391,7 +391,7 @@ public abstract class AbstractUdpListener
/**
* The remote address that is associated with this socket.
*/
- private SocketAddress remoteAddress;
+ private InetSocketAddress remoteAddress;
/**
* The flag which indicates that this DatagramSocket has been
@@ -406,7 +406,7 @@ public abstract class AbstractUdpListener
* new instance.
* @throws SocketException
*/
- public MySocket(SocketAddress remoteAddress)
+ MySocket(InetSocketAddress remoteAddress)
throws SocketException
{
// unbound
@@ -487,6 +487,45 @@ public abstract class AbstractUdpListener
return localAddress;
}
+ /**
+ * {@inheritDoc}
+ *
+ * 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}
+ *
+ * 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}
+ *
+ * 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}
*
diff --git a/src/main/java/org/ice4j/ice/harvest/GoogleTurnCandidateHarvest.java b/src/main/java/org/ice4j/ice/harvest/GoogleTurnCandidateHarvest.java
index d79badc..4e8e1aa 100644
--- a/src/main/java/org/ice4j/ice/harvest/GoogleTurnCandidateHarvest.java
+++ b/src/main/java/org/ice4j/ice/harvest/GoogleTurnCandidateHarvest.java
@@ -133,6 +133,14 @@ public class GoogleTurnCandidateHarvest
harvester.getStunStack().addSocket(
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);
}
}
diff --git a/src/main/java/org/ice4j/ice/harvest/GoogleTurnSSLCandidateHarvester.java b/src/main/java/org/ice4j/ice/harvest/GoogleTurnSSLCandidateHarvester.java
index eb51111..87d913d 100644
--- a/src/main/java/org/ice4j/ice/harvest/GoogleTurnSSLCandidateHarvester.java
+++ b/src/main/java/org/ice4j/ice/harvest/GoogleTurnSSLCandidateHarvester.java
@@ -121,7 +121,7 @@ public class GoogleTurnSSLCandidateHarvester
/**
* 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
* a "server" socket cannot connect to a destination with the same local
@@ -146,11 +146,11 @@ public class GoogleTurnSSLCandidateHarvester
if(sslHandshake(inputStream, outputStream))
{
Component parentComponent = hostCand.getParentComponent();
+ MultiplexingSocket multiplexing = new MultiplexingSocket(sock);
cand
= new HostCandidate(
- new IceTcpSocketWrapper(
- new MultiplexingSocket(sock)),
+ new IceTcpSocketWrapper(multiplexing),
parentComponent,
Transport.TCP);
parentComponent
@@ -158,6 +158,7 @@ public class GoogleTurnSSLCandidateHarvester
.getParentAgent()
.getStunStack()
.addSocket(cand.getStunSocket(null));
+ parentComponent.getComponentSocket().add(multiplexing);
}
}
catch (Exception e)
@@ -187,12 +188,12 @@ public class GoogleTurnSSLCandidateHarvester
/**
* Do the SSL handshake (send client certificate and wait for receive server
- * certificate). We explicitely need InputStream and
+ * certificate). We explicitly need InputStream and
* OutputStream because some Socket may redefine
* getInputStream()/getOutputStream() and we need the original stream.
*
* @param inputStream InputStream of the socket
- * @param outputStream OuputStream of the socket
+ * @param outputStream OutputStream of the socket
* @return true if the SSL handshake is done
* @throws IOException if something goes wrong
*/
diff --git a/src/main/java/org/ice4j/ice/harvest/HostCandidateHarvester.java b/src/main/java/org/ice4j/ice/harvest/HostCandidateHarvester.java
index 66e42d4..1dedbf2 100644
--- a/src/main/java/org/ice4j/ice/harvest/HostCandidateHarvester.java
+++ b/src/main/java/org/ice4j/ice/harvest/HostCandidateHarvester.java
@@ -418,6 +418,7 @@ public class HostCandidateHarvester
// checks. In case we have enabled STUN, we are going to use
// them as well while harvesting reflexive candidates.
createAndRegisterStunSocket(candidate);
+ component.getComponentSocket().add(sock);
}
}
}
@@ -569,8 +570,9 @@ public class HostCandidateHarvester
sock.setReuseAddress(true);
sock.bind(new InetSocketAddress(laddr, port));
IceSocketWrapper socket
- = new IceTcpServerSocketWrapper(sock,
- component);
+ = new IceTcpServerSocketWrapper(
+ new DelegatingServerSocket(sock),
+ component);
if(logger.isLoggable(Level.FINEST))
{
diff --git a/src/main/java/org/ice4j/ice/harvest/SinglePortUdpHarvester.java b/src/main/java/org/ice4j/ice/harvest/SinglePortUdpHarvester.java
index d9adfaa..accb4a5 100644
--- a/src/main/java/org/ice4j/ice/harvest/SinglePortUdpHarvester.java
+++ b/src/main/java/org/ice4j/ice/harvest/SinglePortUdpHarvester.java
@@ -18,18 +18,14 @@
package org.ice4j.ice.harvest;
import org.ice4j.*;
-import org.ice4j.attribute.*;
import org.ice4j.ice.*;
-import org.ice4j.message.*;
import org.ice4j.socket.*;
import org.ice4j.stack.*;
-import org.ice4j.util.*;
import java.io.*;
import java.net.*;
import java.util.*;
import java.util.concurrent.*;
-import java.util.logging.*;
import java.util.logging.Logger; // Disambiguation
/**
@@ -230,26 +226,27 @@ public class SinglePortUdpHarvester
* The collection of IceSocketWrappers that can potentially
* be used by the ice4j user to read/write from/to this candidate.
* The keys are the remote addresses for each socket.
- *
+ *
* There are wrappers over MultiplexedDatagramSockets over
* a corresponding socket in {@link #sockets}.
*/
private final Map candidateSockets
- = new HashMap<>();
+ = new HashMap<>();
/**
* The collection of DatagramSockets added to this candidate.
* The keys are the remote addresses for each socket.
- *
+ *
* These are the "raw" sockets, before any wrappers are added for
* the STUN stack or the user of ice4j.
*/
private final Map sockets
- = new HashMap<>();
+ = new HashMap<>();
/**
* Initializes a new MyCandidate instance with the given
* Component and the given local username fragment.
+ *
* @param component the Component for which this candidate will
* serve.
* @param ufrag the local ICE username fragment for this candidate (and
@@ -263,7 +260,7 @@ public class SinglePortUdpHarvester
/**
* {@inheritDoc}
- *
+ *
* Closes all sockets in use by this LocalCandidate.
*/
@Override
@@ -283,20 +280,21 @@ public class SinglePortUdpHarvester
StunStack stunStack = getStunStack();
for (Map.Entry e
- : sockets.entrySet())
+ : sockets.entrySet())
{
DatagramSocket socket = e.getValue();
if (stunStack != null)
{
TransportAddress localAddress
- = new TransportAddress(socket.getLocalAddress(),
- socket.getLocalPort(),
- Transport.UDP);
+ = new TransportAddress(socket.getLocalAddress(),
+ socket.getLocalPort(),
+ Transport.UDP);
TransportAddress remoteAddress
- = new TransportAddress((InetSocketAddress) e.getKey(),
+ = new TransportAddress(
+ (InetSocketAddress) e.getKey(),
- Transport.UDP);
+ Transport.UDP);
stunStack.removeSocket(localAddress, remoteAddress);
}
@@ -318,11 +316,12 @@ public class SinglePortUdpHarvester
/**
* Adds a new Socket to this candidate, which is associated
* with a particular remote address.
+ *
* @param socket the socket to add.
* @param remoteAddress the remote address for the socket.
*/
private synchronized void addSocket(DatagramSocket socket,
- InetSocketAddress remoteAddress)
+ InetSocketAddress remoteAddress)
throws IOException
{
if (freed)
@@ -337,16 +336,16 @@ public class SinglePortUdpHarvester
}
IceProcessingState state
- = component.getParentStream().getParentAgent().getState();
+ = component.getParentStream().getParentAgent().getState();
if (!IceProcessingState.WAITING.equals(state)
- && !IceProcessingState.RUNNING.equals(state))
+ && !IceProcessingState.RUNNING.equals(state))
{
throw new IOException(
- "Agent state is " + state + ". Cannot add socket.");
+ "Agent state is " + state + ". Cannot add socket.");
}
MultiplexingDatagramSocket multiplexing
- = new MultiplexingDatagramSocket(socket);
+ = new MultiplexingDatagramSocket(socket);
// Socket to add to the candidate
IceSocketWrapper candidateSocket
@@ -355,13 +354,15 @@ public class SinglePortUdpHarvester
// STUN-only filtered socket to add to the StunStack
IceSocketWrapper stunSocket
= new IceUdpSocketWrapper(
- multiplexing.getSocket(new StunDatagramPacketFilter()));
+ multiplexing.getSocket(new StunDatagramPacketFilter()));
component.getParentStream().getParentAgent().getStunStack()
- .addSocket(
- stunSocket,
- new TransportAddress(remoteAddress, Transport.UDP));
+ .addSocket(
+ stunSocket,
+ new TransportAddress(remoteAddress, Transport.UDP));
+ // TODO: maybe move this code to the candidates.
+ component.getComponentSocket().add(multiplexing);
// XXX is this necessary?
synchronized (candidateSockets)
@@ -375,14 +376,15 @@ public class SinglePortUdpHarvester
sockets.put(remoteAddress, socket);
}
}
-
/**
* {@inheritDoc}
*/
@Override
- public IceSocketWrapper getIceSocketWrapper(SocketAddress remoteAddress)
+ protected IceSocketWrapper getCandidateIceSocketWrapper(
+ SocketAddress remoteAddress)
{
return candidateSockets.get(remoteAddress);
}
+
}
}
diff --git a/src/main/java/org/ice4j/ice/harvest/StunCandidateHarvester.java b/src/main/java/org/ice4j/ice/harvest/StunCandidateHarvester.java
index 684f13f..db5390e 100644
--- a/src/main/java/org/ice4j/ice/harvest/StunCandidateHarvester.java
+++ b/src/main/java/org/ice4j/ice/harvest/StunCandidateHarvester.java
@@ -441,7 +441,7 @@ public class StunCandidateHarvester
*/
protected HostCandidate getHostCandidate(HostCandidate hostCand)
{
- HostCandidate cand = null;
+ HostCandidate cand;
// create a new TCP HostCandidate
if(hostCand.getTransport() == Transport.TCP)
@@ -450,12 +450,15 @@ public class StunCandidateHarvester
{
Socket sock = new Socket(stunServer.getAddress(),
stunServer.getPort());
- cand = new HostCandidate(new IceTcpSocketWrapper(
- new MultiplexingSocket(sock)),
- hostCand.getParentComponent(), Transport.TCP);
+ MultiplexingSocket multiplexing = new MultiplexingSocket(sock);
+ cand
+ = new HostCandidate(
+ new IceTcpSocketWrapper(multiplexing),
+ hostCand.getParentComponent(), Transport.TCP);
hostCand.getParentComponent().getParentStream().
getParentAgent().getStunStack().addSocket(
cand.getStunSocket(null));
+ hostCand.getParentComponent().getComponentSocket().add(multiplexing);
}
catch(Exception io)
{
diff --git a/src/main/java/org/ice4j/ice/harvest/TcpHarvester.java b/src/main/java/org/ice4j/ice/harvest/TcpHarvester.java
index 752f5f8..ecd8aa4 100644
--- a/src/main/java/org/ice4j/ice/harvest/TcpHarvester.java
+++ b/src/main/java/org/ice4j/ice/harvest/TcpHarvester.java
@@ -488,11 +488,11 @@ public class TcpHarvester
IceProcessingState state
= component.getParentStream().getParentAgent().getState();
- if (!IceProcessingState.WAITING.equals(state)
+ if (logger.isLoggable(Level.FINE)
+ && !IceProcessingState.WAITING.equals(state)
&& !IceProcessingState.RUNNING.equals(state))
{
- throw new IllegalStateException(
- "The associated Agent is in state " + state);
+ logger.fine("Adding a socket to an Agent in state " + state);
}
// Socket to add to the candidate
@@ -518,6 +518,10 @@ public class TcpHarvester
component.getParentStream().getParentAgent().getStunStack()
.addSocket(stunSocket);
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 candidate/component to close/free it.
}
diff --git a/src/main/java/org/ice4j/ice/harvest/TurnCandidateHarvest.java b/src/main/java/org/ice4j/ice/harvest/TurnCandidateHarvest.java
index 926cc45..47eb199 100644
--- a/src/main/java/org/ice4j/ice/harvest/TurnCandidateHarvest.java
+++ b/src/main/java/org/ice4j/ice/harvest/TurnCandidateHarvest.java
@@ -258,6 +258,8 @@ public class TurnCandidateHarvest
harvester.getStunStack().addSocket(
relayedCandidate.getStunSocket(null));
+ relayedCandidate.getParentComponent().getComponentSocket().add(
+ relayedCandidate.getCandidateIceSocketWrapper());
addCandidate(relayedCandidate);
}
}
diff --git a/src/main/java/org/ice4j/ice/harvest/UPNPHarvester.java b/src/main/java/org/ice4j/ice/harvest/UPNPHarvester.java
index a838445..80b0c5e 100644
--- a/src/main/java/org/ice4j/ice/harvest/UPNPHarvester.java
+++ b/src/main/java/org/ice4j/ice/harvest/UPNPHarvester.java
@@ -203,25 +203,27 @@ public class UPNPHarvester
* @param socket local socket
* @param externalIP external IP address
* @param port local port
- * @param cmp parent component
+ * @param component parent component
* @param device the UPnP gateway device
* @return a new UPNPCandidate instance which
* represents the specified TransportAddress
* @throws Exception if something goes wrong during candidate creation
*/
- public List createUPNPCandidate(IceSocketWrapper socket,
- String externalIP, int port, Component cmp, GatewayDevice device)
+ private List createUPNPCandidate(IceSocketWrapper socket,
+ String externalIP, int port, Component component, GatewayDevice device)
throws Exception
{
List ret = new ArrayList<>();
TransportAddress addr
= 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);
candidate.getStunStack().addSocket(stunSocket);
+ component.getComponentSocket().add(candidate.getCandidateIceSocketWrapper());
ret.add(candidate);
ret.add(base);
diff --git a/src/main/java/org/ice4j/socket/DelegatingDatagramSocket.java b/src/main/java/org/ice4j/socket/DelegatingDatagramSocket.java
index a141e09..cffbd91 100644
--- a/src/main/java/org/ice4j/socket/DelegatingDatagramSocket.java
+++ b/src/main/java/org/ice4j/socket/DelegatingDatagramSocket.java
@@ -662,6 +662,12 @@ public class DelegatingDatagramSocket
// after the first packet is received, the length is set to the size
// of the first packet and the second packet is truncated.
// 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();
p.setLength((data == null) ? 0 : (data.length - p.getOffset()));
diff --git a/src/main/java/org/ice4j/socket/IceTcpServerSocketWrapper.java b/src/main/java/org/ice4j/socket/IceTcpServerSocketWrapper.java
index d6a076b..5535dcf 100644
--- a/src/main/java/org/ice4j/socket/IceTcpServerSocketWrapper.java
+++ b/src/main/java/org/ice4j/socket/IceTcpServerSocketWrapper.java
@@ -195,6 +195,7 @@ public class IceTcpServerSocketWrapper
component.getParentStream().getParentAgent().
getStunStack().addSocket(
new IceTcpSocketWrapper(multiplexingSocket));
+ component.getComponentSocket().add(multiplexingSocket);
sockets.add(multiplexingSocket);
}
diff --git a/src/main/java/org/ice4j/socket/MergingDatagramSocket.java b/src/main/java/org/ice4j/socket/MergingDatagramSocket.java
new file mode 100644
index 0000000..af7235f
--- /dev/null
+++ b/src/main/java/org/ice4j/socket/MergingDatagramSocket.java
@@ -0,0 +1,1118 @@
+/*
+ * 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 org.ice4j.*;
+
+import java.io.*;
+import java.net.*;
+import java.util.*;
+import java.util.concurrent.*;
+import java.util.logging.*;
+import org.ice4j.util.Logger; //Disambiguation
+
+/**
+ * A {@link DatagramSocket} implementation which merges a set of sockets.
+ *
+ * It maintains a thread reading from each of the underlying sockets. Thus
+ * received datagrams are provided via the {@link #receive(DatagramPacket)}
+ * API, in the order in which they were originally received (or close to it,
+ * since the implementation is only based on timestamps).
+ *
+ * One of the underlying sockets is used as a delegate, and handles sending
+ * via {@link #send(DatagramPacket)} and calls to
+ * {@link #getLocalPort()}, {@link #getLocalAddress()} and
+ * {@link #getLocalSocketAddress()}.
+ *
+ * @author Boris Grozev
+ */
+public class MergingDatagramSocket
+ extends DatagramSocket
+{
+ /**
+ * 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());
+
+ /**
+ * Used to control access to {@link #socketContainers}.
+ */
+ private final Object socketContainersSyncRoot = new Object();
+
+ /**
+ * Stores the underlying sockets. Copy on write.
+ */
+ private SocketContainer[] socketContainers = new SocketContainer[0];
+
+ /**
+ * Calls to {@link #receive(java.net.DatagramPacket)} will wait on this
+ * object in case no packet is available for reading.
+ */
+ private final Object receiveLock = new Object();
+
+ /**
+ * If non-zero, {@link #receive(java.net.DatagramPacket)} will attempt to
+ * return within this many milliseconds, and will throw a
+ * {@link SocketTimeoutException} if no packet has been read.
+ */
+ private int soTimeout = 0;
+
+ /**
+ * The {@link SocketContainer} considered active, i.e. the one which should
+ * be used for sending.
+ */
+ protected SocketContainer active = null;
+
+ /**
+ * The flag which indicates whether this socket is closed.
+ */
+ private boolean closed = false;
+
+ /**
+ * The number of packets which were read from an underlying socket, but were
+ * discarded because they were not accepted by
+ * {@link #accept(DatagramPacket)}.
+ * Access to this field should be protected by {@link #receiveLock}.
+ */
+ private int numDiscardedPackets = 0;
+
+ /**
+ * The {@link Logger} used by {@link MergingDatagramSocket} instances.
+ */
+ private final Logger logger;
+
+ /**
+ * Initializes a new {@link MergingDatagramSocket} instance.
+ * @throws SocketException
+ */
+ public MergingDatagramSocket()
+ throws SocketException
+ {
+ this(null);
+ }
+
+ /**
+ * Initializes a new {@link MergingDatagramSocket} instance.
+ * @param levelDelegate the {@link Logger} instance which dictates the
+ * logging level for the new {@link MergingDatagramSocket} instance.
+ * @throws SocketException
+ */
+ public MergingDatagramSocket(Logger levelDelegate)
+ throws SocketException
+ {
+ logger = new Logger(classLogger, levelDelegate);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public boolean isClosed()
+ {
+ return closed;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public void close()
+ {
+ if (isClosed())
+ {
+ return;
+ }
+ closed = true;
+ logger.info("Closing.");
+
+ // XXX do we want to risk obtaining the lock here, or should we just
+ // let any thread in receive() find out about the close after it's next
+ // timeout?
+ synchronized (receiveLock)
+ {
+ receiveLock.notifyAll();
+ }
+
+ synchronized (socketContainersSyncRoot)
+ {
+ active = null;
+ for (SocketContainer container : socketContainers)
+ {
+ container.close(false);
+ }
+ socketContainers = new SocketContainer[0];
+ }
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public void setSoTimeout(int soTimeout)
+ {
+ this.soTimeout = soTimeout;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public int getSoTimeout()
+ {
+ return soTimeout;
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * The current implementation delegates to the first container, but this is
+ * subject to change.
+ *
+ * @param pkt the datagram to send.
+ * @throws IOException
+ */
+ @Override
+ public void send(DatagramPacket pkt)
+ throws IOException
+ {
+ SocketContainer active = getActiveSocket();
+ if (active != null)
+ {
+ active.send(pkt);
+ }
+ else
+ {
+ throw new IOException("No active socket.");
+ }
+ }
+
+ /**
+ * Adds a {@link DelegatingSocket} instance to this merging socket. Note
+ * that this will start a thread reading from the added socket.
+ * @param socket the socket to add.
+ */
+ public void add(DelegatingSocket socket)
+ {
+ Objects.requireNonNull(socket, "socket");
+ if (logger.isLoggable(Level.FINE))
+ {
+ logger.fine("Adding a DelegatingSocket instance: "
+ + socket.getLocalAddress());
+ }
+ doAdd(socket);
+ }
+
+ /**
+ * Adds the socket instance wrapped by {@code wrapper} to this merging
+ * socket. Note that this will start a thread reading from the added socket.
+ * @param wrapper the wrapper of the socket to add.
+ */
+ public void add(IceSocketWrapper wrapper)
+ {
+ Object socket = wrapper.getUDPSocket();
+ if (socket == null)
+ {
+ socket = wrapper.getTCPSocket();
+ }
+ doAdd(socket);
+ }
+
+ /**
+ * Adds a {@link DatagramSocket} instance to this merging socket. Note
+ * that this will start a thread reading from the added socket.
+ * @param socket the socket to add.
+ */
+ public void add(DatagramSocket socket)
+ {
+ Objects.requireNonNull(socket, "socket");
+ if (logger.isLoggable(Level.FINE))
+ {
+ logger.fine("Adding a DatagramSocket instance: "
+ + socket.getLocalAddress());
+ }
+ doAdd(socket);
+ }
+
+ /**
+ * Adds a socket (either a {@link DatagramSocket} or a
+ * {@link DelegatingSocket}) to the list of underlying sockets merged by
+ * this {@link MergingDatagramSocket}.
+ * @param socket the socket to add.
+ */
+ private void doAdd(Object socket)
+ {
+ Objects.requireNonNull(socket, "socket");
+
+ if (!(socket instanceof DelegatingSocket) &&
+ !(socket instanceof DatagramSocket))
+ {
+ throw new IllegalStateException("Socket type not supported: "
+ + socket.getClass().getName());
+ }
+
+ synchronized (socketContainersSyncRoot)
+ {
+ if (indexOf(socketContainers, socket) != -1)
+ {
+ logger.warning("Socket already added.");
+ return;
+ }
+
+ SocketContainer socketContainer;
+ if (socket instanceof DelegatingSocket)
+ {
+ socketContainer = new SocketContainer((DelegatingSocket) socket);
+ }
+ else
+ {
+ socketContainer = new SocketContainer((DatagramSocket) socket);
+ }
+
+ SocketContainer[] newSocketContainers
+ = new SocketContainer[socketContainers.length + 1];
+ System.arraycopy(socketContainers, 0,
+ newSocketContainers, 0,
+ socketContainers.length);
+ newSocketContainers[socketContainers.length] = socketContainer;
+
+ socketContainers = newSocketContainers;
+ }
+ }
+
+ /**
+ * Removes a specific {@link DatagramSocket} from the list of sockets
+ * merged by this {@link MergingDatagramSocket}.
+ * @param socket the {@link DatagramSocket} to remove.
+ */
+ public void remove(DatagramSocket socket)
+ {
+ doRemove(socket);
+ }
+
+ /**
+ * Removes a specific {@link DelegatingSocket} from the list of sockets
+ * merged by this {@link MergingDatagramSocket}.
+ * @param socket the {@link DelegatingSocket} to remove.
+ */
+ public void remove(DelegatingSocket socket)
+ {
+ doRemove(socket);
+ }
+
+ /**
+ * Removes a socket from the list of sockets merged by this
+ * {@link MergingDatagramSocket}.
+ * @param socket the socket to remove.
+ */
+ private void doRemove(Object socket)
+ {
+ SocketContainer socketContainer = null;
+
+ synchronized (socketContainersSyncRoot)
+ {
+ int i = indexOf(socketContainers, socket);
+ if (i > 0)
+ {
+ socketContainer = socketContainers[i];
+
+ SocketContainer[] newSockets
+ = new SocketContainer[socketContainers.length - 1];
+ if (i > 0)
+ {
+ System.arraycopy(socketContainers, 0,
+ newSockets, 0,
+ i);
+ }
+ if (i < socketContainers.length - 1)
+ {
+ System.arraycopy(socketContainers, i + 1,
+ newSockets, i,
+ socketContainers.length - i - 1);
+ }
+
+ socketContainers = newSockets;
+
+ if (socketContainer == active)
+ {
+ // TODO: proper selection of a new active socket
+ logger.warning(
+ "Removing the active socket. Won't be able to send "
+ + "until a new one is elected.");
+ active = null;
+ }
+ }
+ else
+ {
+ logger.severe("Cannot find socket to remove.");
+ }
+ }
+
+ if (logger.isLoggable(Level.FINE))
+ {
+ logger.fine("Removed: " + socketContainer);
+ }
+ if (socketContainer != null)
+ {
+ // We just removed it from the merging socket, so use remove=false
+ socketContainer.close(false);
+ }
+ }
+
+ /**
+ * Returns the index in {@link #socketContainers} of the
+ * {@link SocketContainer} with socket equal to {@code socket}, or -1 if
+ * such a {@link SocketContainer} doesn't exist.
+ *
+ * @param socket the {@link DatagramSocket} to get the index of.
+ * @return the index in {@link #socketContainers} of the
+ * {@link SocketContainer} with socket equal to {@code socket}, or -1 if
+ * such a {@link SocketContainer} doesn't exist.
+ */
+ private int indexOf(SocketContainer[] socketContainers, Object socket)
+ {
+ for (int i = 0; i < socketContainers.length; i++)
+ {
+ if (socketContainers[i].datagramSocket == socket ||
+ socketContainers[i].delegatingSocket == socket)
+ {
+ return i;
+ }
+ }
+ return -1;
+ }
+
+ /**
+ * TODO
+ */
+ protected SocketContainer getActiveSocket()
+ {
+ return this.active;
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * Delegates to the "active" socket, if one exists. Else returns
+ * {@code null}.
+ */
+ @Override
+ public InetAddress getLocalAddress()
+ {
+ SocketContainer activeSocket = getActiveSocket();
+ return activeSocket == null ? null : activeSocket.getLocalAddress();
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * Delegates to the "active" socket, if one exists. Else returns
+ * {@code 0}.
+ * TODO: should we return 0 (unbound) or -1 (closed) if there are no
+ * sockets?
+ */
+ @Override
+ public int getLocalPort()
+ {
+ SocketContainer activeSocket = getActiveSocket();
+ return activeSocket == null ? 0 : activeSocket.getLocalPort();
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * Delegates to the "active" socket, if one exists. Else returns
+ * {@code null}.
+ */
+ @Override
+ public SocketAddress getLocalSocketAddress()
+ {
+ SocketContainer activeSocket = getActiveSocket();
+ return
+ activeSocket == null ? null : activeSocket.getLocalSocketAddress();
+ }
+
+ /**
+ * Checks whether a particular {@link DatagramPacket}, received from one of
+ * the underlying sockets of thins merging socket, should be accepted and
+ * provided for reception from this {@link MergingDatagramSocket}.
+ * @param p the packet for which to decide whether to accept it or not.
+ * @return {@code true} iff {@code p} should be accepted.
+ */
+ protected boolean accept(DatagramPacket p)
+ {
+ // By default we accept all packets, and allow extending classes to
+ // override
+ return true;
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * Copies into {@code p} a packet already received from one of the
+ * underlying sockets. The socket is chosen on the base of the timestamp
+ * of the reception of the first packet in its queue (so that earlier
+ * packets are received first).
+ * @throws SocketTimeoutException if a socket timeout is set, and the
+ * call fails to receive a packet within the timeout.
+ * @throws SocketClosedException if the socket is closed while
+ */
+ @Override
+ public void receive(DatagramPacket p)
+ throws SocketTimeoutException,
+ SocketClosedException
+ {
+ long start = System.currentTimeMillis();
+ int soTimeout = this.soTimeout;
+
+ // We need to hold the lock while checking for an available packet,
+ // otherwise we might end up wait()-ing if a packet becomes available
+ // after our check.
+ // We keep the loop inside the lock, because this prevents us from
+ // having to re-obtain the lock after wait() returns. All operations
+ // inside the block are non-blocking, except for wait(), so we run no
+ // risk of causing a deadlock by doing so.
+ synchronized (receiveLock)
+ {
+ do
+ {
+ if (isClosed())
+ {
+ throw new SocketClosedException();
+ }
+
+ // Find the input socket with the oldest packet
+ SocketContainer[] socketContainers = this.socketContainers;
+ SocketContainer socketToReceiveFrom = null;
+ long firstTime = -1;
+ for (SocketContainer socketContainer : socketContainers)
+ {
+ long f = socketContainer.getFirstReceivedTime();
+ if (f > 0)
+ {
+ if (firstTime == -1 || firstTime > f)
+ {
+ firstTime = f;
+ socketToReceiveFrom = socketContainer;
+ }
+ }
+ }
+
+ // If a packet is available, receive it
+ if (socketToReceiveFrom != null)
+ {
+ socketToReceiveFrom.receive(p);
+
+ if (accept(p))
+ {
+ socketToReceiveFrom.accepted(p);
+ return;
+ }
+ else
+ {
+ numDiscardedPackets++;
+ if (numDiscardedPackets % 100 == 1)
+ {
+ logger.info("Discarded " + numDiscardedPackets
+ + " packets. Last remote address:"
+ + p.getSocketAddress());
+ }
+
+ // Go on and receive the next packet in p.
+ continue;
+ }
+ }
+ // Otherwise wait on receiveLock.
+ else
+ {
+ long waitTimeout = 500;
+ if (soTimeout > 0)
+ {
+ long remaining
+ = start + soTimeout
+ - System.currentTimeMillis();
+ if (remaining <= 0)
+ throw new SocketTimeoutException();
+
+ waitTimeout = Math.min(waitTimeout, remaining);
+ }
+ try
+ {
+ receiveLock.wait(waitTimeout);
+ }
+ catch (InterruptedException ie)
+ {
+ Thread.currentThread().interrupt();
+ // We haven't received a packet, but what else can we
+ // do?
+ return;
+ }
+ }
+ }
+ while (true);
+ }
+ }
+
+ /**
+ * Initializes the active socket of this {@link MergingDatagramSocket}.
+ * @param socketWrapper the {@link IceSocketWrapper} instance wrapping the
+ * actual socket that should be used. Used to find the correct
+ * {@link SocketContainer}
+ * @param remoteAddress the remote address which was selected by ICE and
+ * and which should be used as the target.
+ */
+ protected void initializeActive(IceSocketWrapper socketWrapper,
+ TransportAddress remoteAddress)
+ {
+ Object socket = socketWrapper.getTCPSocket();
+ if (socket == null)
+ {
+ socket = socketWrapper.getUDPSocket();
+ }
+
+ if (logger.isLoggable(Level.FINE))
+ {
+ logger.fine("Initializing the active container, socket=" + socket
+ + "; remote address=" + remoteAddress);
+ }
+
+ synchronized (socketContainersSyncRoot)
+ {
+ if (active != null)
+ {
+ // This means that we've received data before ICE completed.
+ // That is, the remote side sent application data, and our
+ // application invoked receive(). Though maybe unusual, this
+ // is not necessarily incorrect.
+ // Still, go on and replace the active socket with whatever
+ // ICE selected.
+ logger.warning("Active socket already initialized.");
+ }
+
+ SocketContainer newActive = null;
+ for (SocketContainer container : socketContainers)
+ {
+ if (socket == container.datagramSocket
+ || socket == container.delegatingSocket)
+ {
+ newActive = container;
+ break;
+ }
+ }
+
+ if (newActive == null)
+ {
+ logger.severe("No SocketContainer found!");
+ return;
+ }
+
+ newActive.remoteAddress = remoteAddress;
+ active = newActive;
+
+ }
+ }
+
+ /**
+ * Contains one of the sockets which this {@link MergingDatagramSocket}
+ * merges, and objects associated with the socket, including a thread
+ * which loops reading from it.
+ *
+ * The socket is either a {@link DatagramSocket} or a
+ * {@link DelegatingSocket} instance, stored in {@link #datagramSocket} or
+ * {@link #delegatingSocket} respectively. Exactly one of these fields must
+ * be null.
+ */
+ private class SocketContainer
+ {
+ /**
+ * Either the socket represented by this instance, if it is a {@link
+ * DatagramSocket} instance, or {@code null} if it is not.
+ */
+ private final DatagramSocket datagramSocket;
+
+ /**
+ * Either the socket represented by this instance, if it is a {@link
+ * DelegatingSocket} instance, or {@code null}if it is not.
+ */
+ private final DelegatingSocket delegatingSocket;
+
+ /**
+ * The queue to which packets received from this instance's socket are
+ * added.
+ */
+ private final ArrayBlockingQueue queue
+ = new ArrayBlockingQueue<>(100);
+
+ /**
+ * A pool of unused {@link Buffer} instances.
+ */
+ private final ArrayBlockingQueue pool
+ = new ArrayBlockingQueue<>(10);
+
+ /**
+ * A flag used to signal to {@link #thread} to finish.
+ */
+ private boolean closed = false;
+
+ /**
+ * The remote address of the last received packet.
+ * Note that this is updated only when a packet is received from this
+ * {@link SocketContainer} via {@link #receive(DatagramPacket)}, and
+ * not when a packet is received from the underlying socket by its
+ * read thread. This is in order to prevent poisoning of the remote
+ * address, since the verification of the address is performed by
+ * the {@link MergingDatagramSocket} after it invokes
+ * {@link #receive(DatagramPacket)}.
+ */
+ private SocketAddress remoteAddress = null;
+
+ /**
+ * The thread which reads packets from this instance's socket and adds
+ * them to {@link #queue}. If the queue is filled up, it will stop
+ * receiving packets and will block waiting for the queue accept.
+ */
+ private Thread thread;
+
+ /**
+ * Initializes a {@link SocketContainer} instance using a {@link
+ * DatagramSocket} as its socket.
+ *
+ * @param socket the socket.
+ */
+ SocketContainer(DelegatingSocket socket)
+ {
+ this.datagramSocket = null;
+ this.delegatingSocket = Objects.requireNonNull(socket, "socket");
+ init();
+ }
+
+ /**
+ * Initializes a {@link SocketContainer} instance using a {@link
+ * DatagramSocket} as its socket.
+ *
+ * @param socket the socket.
+ */
+ SocketContainer(DatagramSocket socket)
+ {
+ this.datagramSocket = Objects.requireNonNull(socket, "socket");
+ this.delegatingSocket = null;
+ init();
+ }
+
+ /**
+ * Initializes and starts the thread of this instance.
+ */
+ private void init()
+ {
+ thread = new Thread()
+ {
+ @Override
+ public void run()
+ {
+ runInReaderThread();
+ }
+ };
+ thread.setDaemon(true);
+ thread.setName("MergingDatagramSocket reader thread for: "
+ + getLocalSocketAddress() + " -> "
+ + getRemoteSocketAddress());
+
+ if (logger.isLoggable(Level.FINE))
+ {
+ logger.fine("Starting the thread for socket "
+ + getLocalSocketAddress() + " -> "
+ + getRemoteSocketAddress());
+ }
+ thread.start();
+ }
+
+ /**
+ * @return an unused {@link Buffer} instance.
+ */
+ private Buffer getFreeBuffer()
+ {
+ Buffer buffer = pool.poll();
+ if (buffer == null)
+ buffer = new Buffer();
+ buffer.reset();
+ return buffer;
+ }
+
+ /**
+ * Reads from the underlying socket and adds the read packets to {@link
+ * #queue}. Blocks if {@link #queue} is full.
+ */
+ private void runInReaderThread()
+ {
+ while (true)
+ {
+ if (closed || Thread.currentThread().isInterrupted())
+ break;
+
+ // Read from the underlying socket
+ Buffer buffer = getFreeBuffer();
+ try
+ {
+ if (!doReceive(buffer))
+ {
+ continue;
+ }
+ }
+ catch (IOException ioe)
+ {
+ logger.info("Failed to receive: " + ioe);
+ break;
+ }
+
+ if (closed || Thread.currentThread().isInterrupted())
+ break;
+
+ try
+ {
+ queue.put(buffer);
+ synchronized (receiveLock)
+ {
+ receiveLock.notifyAll();
+ }
+ }
+ catch (InterruptedException ie)
+ {
+ Thread.currentThread().interrupt();
+ }
+ }
+
+ // The receive thread is terminating, no reason to keep this
+ // container anymore.
+ close(true);
+
+ if (logger.isLoggable(Level.FINE))
+ {
+ logger.fine("Finished: " + toString());
+ }
+ }
+
+ /**
+ * Tries to receive a packet from the underlying socket into {@code
+ * buffer}.
+ *
+ * @param buffer the buffer into which to receive.
+ * @return {@code true} if the method succeeded, or {@code false} if the
+ * thread was interrupted or this {@link SocketContainer} was closed.
+ * @throws IOException if receiving failed due to an I/O error from the
+ * underlying socket.
+ */
+ private boolean doReceive(Buffer buffer)
+ throws IOException
+ {
+ while (true)
+ {
+ if (closed || Thread.currentThread().isInterrupted())
+ break;
+ try
+ {
+ if (datagramSocket != null)
+ {
+ datagramSocket.receive(buffer.pkt);
+ }
+ else
+ {
+ delegatingSocket.receive(buffer.pkt);
+ }
+
+ buffer.receivedTime = System.currentTimeMillis();
+
+ maybeUpdateActive();
+ return true;
+ }
+ catch (SocketTimeoutException ste)
+ {
+ // Ignore timeouts and loop.
+ }
+ }
+
+ return false;
+ }
+
+ /**
+ * Makes this {@link SocketContainer} the active socket container for
+ * this {@link MergingDatagramSocket}, if it isn't already the active
+ * socket.
+ */
+ private void maybeUpdateActive()
+ {
+ SocketContainer active = MergingDatagramSocket.this.active;
+ // Avoid obtaining the lock on every packet from the active socket.
+ // There is no harm if the value is overwritten before we obtain
+ // the lock.
+ if (active != this)
+ {
+ synchronized (socketContainersSyncRoot)
+ {
+ MergingDatagramSocket.this.active = this;
+ if (logger.isLoggable(Level.FINE))
+ {
+ logger.fine("Switching to new active socket: "
+ + this);
+ }
+ }
+ }
+ }
+
+ /**
+ * Copies a packet from this {@link SocketContainer}'s queue into
+ * {@code p}. Does not block.
+ *
+ * @param p the {@link DatagramPacket} to receive into.
+ */
+ private void receive(DatagramPacket p)
+ {
+ Buffer buffer = queue.poll();
+ if (buffer == null)
+ {
+ throw new IllegalStateException("Queue empty.");
+ }
+
+ byte[] dest = p.getData();
+ int destOffset = p.getOffset();
+ int len
+ = Math.min(
+ dest.length - destOffset,
+ buffer.pkt.getLength());
+
+ System.arraycopy(buffer.pkt.getData(), buffer.pkt.getOffset(),
+ dest, destOffset,
+ len);
+ p.setLength(len);
+ p.setSocketAddress(buffer.pkt.getSocketAddress());
+
+ pool.offer(buffer);
+ }
+
+ /**
+ * @return the time of reception of the first packet in the queue, or
+ * {@code -1} if the queue is empty.
+ */
+ private long getFirstReceivedTime()
+ {
+ Buffer nextBuffer = queue.peek();
+ if (nextBuffer != null)
+ {
+ return nextBuffer.receivedTime;
+ }
+ return -1;
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * Delegates to the underlying socket (either {@link #datagramSocket} or
+ * {@link #delegatingSocket}).
+ */
+ private InetAddress getLocalAddress()
+ {
+ return datagramSocket != null
+ ? datagramSocket.getLocalAddress()
+ : delegatingSocket.getLocalAddress();
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * Delegates to the underlying socket (either {@link #datagramSocket} or
+ * {@link #delegatingSocket}).
+ */
+ private int getLocalPort()
+ {
+ return datagramSocket != null
+ ? datagramSocket.getLocalPort()
+ : delegatingSocket.getLocalPort();
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * Delegates to the underlying socket (either {@link #datagramSocket} or
+ * {@link #delegatingSocket}).
+ */
+ public SocketAddress getLocalSocketAddress()
+ {
+ return datagramSocket != null
+ ? datagramSocket.getLocalSocketAddress()
+ : delegatingSocket.getLocalSocketAddress();
+ }
+
+ /**
+ * Returns a {@link String} representation of this {@link
+ * SocketContainer}.
+ */
+ public String toString()
+ {
+ if (datagramSocket != null)
+ {
+ return datagramSocket.getLocalSocketAddress()
+ + " -> " + remoteAddress;
+ }
+ else
+ {
+ return delegatingSocket.getLocalSocketAddress()
+ + " -> " + remoteAddress;
+ }
+ }
+
+ /**
+ * Sends a {@link DatagramPacket} through the underlying socket (either
+ * {@link #datagramSocket} or {@link #delegatingSocket}).
+ *
+ * @param pkt the packet to send.
+ */
+ private void send(DatagramPacket pkt)
+ throws IOException
+ {
+ // The application writing data doesn't necessarily know what
+ // remote address to use. Since this SocketContainer was selected
+ // to send the packet through, set the target accordingly.
+ setTarget(pkt);
+
+ if (datagramSocket != null)
+ {
+ datagramSocket.send(pkt);
+ }
+ else
+ {
+ delegatingSocket.send(pkt);
+ }
+ }
+
+ /**
+ * Sets the {@link SocketAddress} of {@code pkt} to the remote address
+ * that this {@link SocketContainer} should send packets to.
+ * @param pkt the packet for which to set the socket address.
+ */
+ private void setTarget(DatagramPacket pkt)
+ {
+ SocketAddress target;
+ // If the socket already has a remote address, use it. If this is
+ // the case, the DatagramPacket instance's remote address is likely
+ // to be ignored, anyway.
+ if (datagramSocket != null)
+ {
+ target = datagramSocket.getRemoteSocketAddress();
+ }
+ else
+ {
+ target = delegatingSocket.getRemoteSocketAddress();
+ }
+
+ // The socket doesn't always have a remote address (e.g. if it is
+ // an unconnected UDP socket from HostCandidateHarvester).
+ // In this case, we send to the source address of the last packet
+ // which was received and accepted, or to the address that was
+ // initialized via initializeActive (i.e. the address initially
+ // selected by ICE).
+ if (target == null)
+ {
+ target = this.remoteAddress;
+ }
+
+ pkt.setSocketAddress(target);
+ }
+
+ /**
+ * Notifies this {@link SocketContainer} that a particular
+ * {@link DatagramPacket} was received from it, and was accepted (as
+ * opposed to e.g. having been discarded due to its remote address not
+ * being authorized).
+ * @param pkt the accepted packet.
+ */
+ private void accepted(DatagramPacket pkt)
+ {
+ this.remoteAddress = pkt.getSocketAddress();
+ }
+
+ /**
+ * @return the underlying socket of this {@link SocketContainer}.
+ */
+ private Object getSocket()
+ {
+ return datagramSocket != null ? datagramSocket : delegatingSocket;
+ }
+
+ /**
+ * Closes this {@link SocketContainer}, stopping it's reading thread,
+ * and, if necessary removing it from the merging socket.
+ * @param remove whether to remove this container from the merging
+ * socket.
+ */
+ private void close(boolean remove)
+ {
+ if (closed)
+ {
+ return;
+ }
+ closed = true;
+
+ thread.interrupt();
+ if (remove)
+ {
+ MergingDatagramSocket.this.doRemove(getSocket());
+ }
+ }
+
+ /**
+ * Represents a {@link DatagramPacket} for the purposes of {@link
+ * SocketContainer}.
+ */
+ private class Buffer
+ {
+ /**
+ * The size of the buffer to allocate.
+ */
+ private static final int MAX_PACKET_SIZE = 1500;
+
+ /**
+ * The time at which this buffer was filled.
+ */
+ long receivedTime = -1;
+
+ /**
+ * The {@link DatagramPacket} wrapped by this {@link Buffer}.
+ */
+ DatagramPacket pkt
+ = new DatagramPacket(
+ new byte[MAX_PACKET_SIZE],
+ 0,
+ MAX_PACKET_SIZE);
+
+ /**
+ * Prepares this {@link Buffer} for reuse.
+ */
+ private void reset()
+ {
+ receivedTime = -1;
+
+ // We are going to receive from a socket into this packet. If
+ // the length is insufficient it is going to truncate the data.
+ // So reset it to what we know is the underlying byte[]'s
+ // length.
+ pkt.setLength(MAX_PACKET_SIZE);
+ }
+ }
+ }
+}
diff --git a/src/main/java/org/ice4j/socket/RelayedCandidateDatagramSocket.java b/src/main/java/org/ice4j/socket/RelayedCandidateDatagramSocket.java
index 1c45e27..63b327b 100644
--- a/src/main/java/org/ice4j/socket/RelayedCandidateDatagramSocket.java
+++ b/src/main/java/org/ice4j/socket/RelayedCandidateDatagramSocket.java
@@ -208,8 +208,8 @@ public class RelayedCandidateDatagramSocket
this);
DatagramSocket hostSocket
- = this.turnCandidateHarvest.hostCandidate.getIceSocketWrapper().
- getUDPSocket();
+ = this.turnCandidateHarvest.hostCandidate
+ .getCandidateIceSocketWrapper().getUDPSocket();
if (hostSocket instanceof MultiplexingDatagramSocket)
{
diff --git a/src/main/java/org/ice4j/socket/SocketClosedException.java b/src/main/java/org/ice4j/socket/SocketClosedException.java
new file mode 100644
index 0000000..a9c092e
--- /dev/null
+++ b/src/main/java/org/ice4j/socket/SocketClosedException.java
@@ -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");
+ }
+}
diff --git a/src/test/java/test/IcePseudoTcp.java b/src/test/java/test/IcePseudoTcp.java
index 76de9d6..5faa490 100755
--- a/src/test/java/test/IcePseudoTcp.java
+++ b/src/test/java/test/IcePseudoTcp.java
@@ -386,7 +386,7 @@ public class IcePseudoTcp
private static class LocalPseudoTcpJob extends Thread implements Runnable
{
- private DatagramSocket dgramSocket;
+ private DatagramSocket dgramSocket;
public LocalPseudoTcpJob(DatagramSocket socket)
throws UnknownHostException