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);
}
} }
/** /**

View File

@ -296,7 +296,7 @@ public class CandidatePair
{ {
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

@ -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();
} }
@ -805,7 +808,7 @@ class ConnectivityCheckClient
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()

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<>();
@ -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();
@ -314,10 +315,16 @@ 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;

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.
* *
@ -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,7 +570,8 @@ 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(
new DelegatingServerSocket(sock),
component); 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,7 +226,7 @@ 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}.
*/ */
@ -240,7 +236,7 @@ public class SinglePortUdpHarvester
/** /**
* 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.
*/ */
@ -250,6 +246,7 @@ public class SinglePortUdpHarvester
/** /**
* 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
@ -294,7 +291,8 @@ public class SinglePortUdpHarvester
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);
@ -318,6 +316,7 @@ 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.
*/ */
@ -362,6 +361,8 @@ public class SinglePortUdpHarvester
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
= new HostCandidate(
new IceTcpSocketWrapper(multiplexing),
hostCand.getParentComponent(), Transport.TCP); 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");
}
}