Adds support for Google's TCP candidates as well as Google TURN TCP and SSLTCP harvesters.

This commit is contained in:
seb 2011-07-20 15:05:19 +00:00
parent c91bfae9b0
commit 205df6ac70
44 changed files with 4077 additions and 547 deletions

View File

@ -38,7 +38,12 @@ public enum Transport
/** /**
* Represents an SCTP transport. * Represents an SCTP transport.
*/ */
SCTP("sctp"); SCTP("sctp"),
/**
* Represents an Google's SSL TCP transport.
*/
SSLTCP("ssltcp");
/** /**
* The name of this <tt>Transport</tt>. * The name of this <tt>Transport</tt>.

View File

@ -497,6 +497,20 @@ public class AttributeFactory
return attribute; return attribute;
} }
/**
* Create a DataAtttribute.
*
* @param data the data
* @return newly created DataAttribute
*/
public static DataAttribute createDataAttributeWithoutPadding(byte data[])
{
DataAttribute attribute = new DataAttribute(false);
attribute.setData(data);
return attribute;
}
/** /**
* Creates an IceControlledAttribute object with the specified tie-breaker * Creates an IceControlledAttribute object with the specified tie-breaker
* value * value

View File

@ -33,12 +33,28 @@ public class DataAttribute
*/ */
private byte data[] = null; private byte data[] = null;
/**
* Add padding.
*
* Some dialect does not add (and support) padding (GTalk).
*/
private boolean padding = true;
/** /**
* Constructor. * Constructor.
*/ */
protected DataAttribute () protected DataAttribute ()
{
this(true);
}
/**
* Constructor.
*/
protected DataAttribute (boolean padding)
{ {
super(DATA); super(DATA);
this.padding = padding;
} }
/** /**
@ -66,7 +82,7 @@ public class DataAttribute
{ {
char type = getAttributeType(); char type = getAttributeType();
byte binValue[] = new byte[HEADER_LENGTH + getDataLength() + byte binValue[] = new byte[HEADER_LENGTH + getDataLength() +
(getDataLength() % 4)]; (padding ? (getDataLength() % 4) : 0)];
//Type //Type
binValue[0] = (byte)(type >> 8); binValue[0] = (byte)(type >> 8);

View File

@ -316,8 +316,6 @@ public class Agent
IOException, IOException,
BindException BindException
{ {
SecureRandom random = new SecureRandom();
if(transport != Transport.UDP) if(transport != Transport.UDP)
{ {
throw new IllegalArgumentException( throw new IllegalArgumentException(
@ -350,13 +348,7 @@ public class Agent
continue; continue;
} }
String s = null; localCand.setUfrag(generateGTalkUfrag());
while(s == null || s.length() != 16)
{
s = new BigInteger(80, random).toString(32);
}
localCand.setUfrag(s);
} }
} }
@ -375,6 +367,23 @@ public class Agent
return component; return component;
} }
/**
* Generates Ufrag for GTalk mode.
*
* @return 16 bytes Ufrag
*/
public String generateGTalkUfrag()
{
SecureRandom random = new SecureRandom();
String s = null;
while(s == null || s.length() != 16)
{
s = new BigInteger(80, random).toString(32);
}
return s;
}
/** /**
* Uses all <tt>CandidateHarvester</tt>s currently registered with this * Uses all <tt>CandidateHarvester</tt>s currently registered with this
* <tt>Agent</tt> to obtain whatever addresses they can discover. * <tt>Agent</tt> to obtain whatever addresses they can discover.
@ -410,7 +419,14 @@ public class Agent
hostCandidateHarvester.harvest( hostCandidateHarvester.harvest(
component, component,
preferredPort, minPort, maxPort); preferredPort, minPort, maxPort, Transport.UDP);
if(compatibilityMode == CompatibilityMode.GTALK)
{
hostCandidateHarvester.harvest(
component,
preferredPort, minPort, maxPort, Transport.TCP);
}
//apply other harvesters here //apply other harvesters here
harvesters.harvest(component); harvesters.harvest(component);
@ -1815,10 +1831,21 @@ public class Agent
&& !IceProcessingState.TERMINATED.equals(state)) && !IceProcessingState.TERMINATED.equals(state))
terminate(IceProcessingState.TERMINATED); terminate(IceProcessingState.TERMINATED);
logger.info("remove streams");
// Free its IceMediaStreams, Components and Candidates. // Free its IceMediaStreams, Components and Candidates.
for(IceMediaStream stream : getStreams()) for(IceMediaStream stream : getStreams())
{
try
{
removeStream(stream); removeStream(stream);
} }
catch(Throwable t)
{
logger.info("remove stream failed: " + t);
}
logger.info("remove stream " + stream.getName());
}
}
/** /**
* Returns the current generation of this ICE Agent. A generation is an * Returns the current generation of this ICE Agent. A generation is an
@ -1907,12 +1934,13 @@ public class Agent
try try
{ {
Thread.sleep(5000); Thread.sleep(3000);
Thread.yield(); Thread.yield();
} }
catch(InterruptedException e) catch(InterruptedException e)
{ {
} }
} }
logger.info("KeepAliveThread ends");
} }
} }

View File

@ -380,11 +380,13 @@ public abstract class Candidate
*/ */
if(candidateType == CandidateType.HOST_CANDIDATE) if(candidateType == CandidateType.HOST_CANDIDATE)
{ {
priority += 1 * 1000; priority += 1 * 1000 -
(this.getBase().getTransport() == Transport.TCP ? 200 : 0);
} }
else if(candidateType == CandidateType.PEER_REFLEXIVE_CANDIDATE) else if(candidateType == CandidateType.PEER_REFLEXIVE_CANDIDATE)
{ {
priority += (long)(0.9 * 1000); priority += (long)(0.9 * 1000) -
(this.getBase().getTransport() == Transport.TCP ? 200 : 0);
} }
else if(candidateType == CandidateType.SERVER_REFLEXIVE_CANDIDATE) else if(candidateType == CandidateType.SERVER_REFLEXIVE_CANDIDATE)
{ {

View File

@ -7,10 +7,13 @@
*/ */
package org.ice4j.ice; package org.ice4j.ice;
import java.io.*;
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.*;
/** /**
* A component is a piece of a media stream requiring a single transport * A component is a piece of a media stream requiring a single transport
@ -226,6 +229,68 @@ public class Component
logger.info("Update remote candidate for " + toShortString() + ": " + logger.info("Update remote candidate for " + toShortString() + ": " +
candidate.getTransportAddress()); candidate.getTransportAddress());
if(candidate.getTransport() == Transport.TCP &&
parentStream.getParentAgent().getCompatibilityMode()
== CompatibilityMode.GTALK)
{
/* for TCP, create a new Candidate to each of remote
* TCP candidates
*/
try
{
for(LocalCandidate l : getLocalCandidates())
{
if(l.getTransport() != Transport.TCP ||
(l.getType() != CandidateType.LOCAL_CANDIDATE &&
l.getType() != CandidateType.HOST_CANDIDATE) ||
!(l.getIceSocketWrapper() instanceof
IceTcpServerSocketWrapper) ||
!l.getTransportAddress().canReach(
candidate.getTransportAddress()))
{
continue;
}
Socket sock = new MultiplexingSocket();
try
{
// if we use proxy (socks5, ...), the connect() timeout
// may not be respected
int timeout = sock.getSoTimeout();
sock.setSoTimeout(1000);
sock.connect(new InetSocketAddress(
candidate.getTransportAddress().getAddress(),
candidate.getTransportAddress().getPort()), 1000);
sock.setSoTimeout(timeout);
}
catch(Exception e)
{
logger.info("Failed to connect to " +
candidate.getTransportAddress());
sock.close();
sock = null;
continue;
}
LocalCandidate tmp =
new HostCandidate(new IceTcpSocketWrapper(sock),
this, Transport.TCP);
parentStream.getParentAgent().getStunStack().addSocket(
tmp.getStunSocket(null));
tmp.setUfrag(l.getUfrag());
synchronized(localCandidates)
{
localCandidates.add(tmp);
}
}
}
catch (IOException e)
{
logger.info("Create TCP client socket error: " + e);
}
}
synchronized(remoteUpdateCandidates) synchronized(remoteUpdateCandidates)
{ {
remoteUpdateCandidates.add(candidate); remoteUpdateCandidates.add(candidate);
@ -249,13 +314,21 @@ public class Component
for(LocalCandidate localCnd : localCnds) for(LocalCandidate localCnd : localCnds)
{ {
if(parentStream.getParentAgent().
getCompatibilityMode() == CompatibilityMode.GTALK &&
localCnd.getIceSocketWrapper() instanceof
IceTcpServerSocketWrapper)
{
continue;
}
for(Candidate remoteCnd : remoteUpdateCandidates) for(Candidate remoteCnd : remoteUpdateCandidates)
{ {
if(localCnd.canReach(remoteCnd)) if(localCnd.canReach(remoteCnd))
{ {
CandidatePair pair = new CandidatePair(localCnd, CandidatePair pair = new CandidatePair(localCnd,
remoteCnd); remoteCnd);
logger.info("new Pair added: " + pair.toShortString());
checkList.add(pair); checkList.add(pair);
} }
} }
@ -794,7 +867,6 @@ public class Component
*/ */
public Candidate findRemoteCandidate(TransportAddress remoteAddress) public Candidate findRemoteCandidate(TransportAddress remoteAddress)
{ {
for( Candidate remoteCnd : localCandidates) for( Candidate remoteCnd : localCandidates)
{ {
if(remoteCnd.getTransportAddress().equals(remoteAddress)) if(remoteCnd.getTransportAddress().equals(remoteAddress))

View File

@ -6,13 +6,13 @@
*/ */
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.attribute.*; import org.ice4j.attribute.*;
import org.ice4j.message.*; import org.ice4j.message.*;
import org.ice4j.socket.*;
import org.ice4j.stack.*; import org.ice4j.stack.*;
/** /**
@ -47,6 +47,12 @@ class ConnectivityCheckClient
*/ */
private final List<PaceMaker> paceMakers = new LinkedList<PaceMaker>(); private final List<PaceMaker> paceMakers = new LinkedList<PaceMaker>();
/**
* Timer that is used to let some seconds before a CheckList is considered
* as FAILED.
*/
private Map<String, Timer> timers = new HashMap<String, Timer>();
/** /**
* Creates a new <tt>ConnectivityCheckHandler</tt> setting * Creates a new <tt>ConnectivityCheckHandler</tt> setting
* <tt>parentAgent</tt> as the agent that will be used for retrieving * <tt>parentAgent</tt> as the agent that will be used for retrieving
@ -216,7 +222,8 @@ class ConnectivityCheckClient
} }
catch (Exception ex) catch (Exception ex)
{ {
DatagramSocket stunSocket = localCandidate.getStunSocket(null); IceSocketWrapper stunSocket = localCandidate.getStunSocket(null);
if(stunSocket != null)
logger.log( logger.log(
Level.INFO, Level.INFO,
"Failed to send " + request "Failed to send " + request
@ -288,7 +295,7 @@ class ConnectivityCheckClient
{ {
IceMediaStream stream IceMediaStream stream
= checkedPair.getParentComponent().getParentStream(); = checkedPair.getParentComponent().getParentStream();
CheckList checkList = stream.getCheckList(); final CheckList checkList = stream.getCheckList();
//If all of the pairs in the check list are now either in the Failed or //If all of the pairs in the check list are now either in the Failed or
//Succeeded state: //Succeeded state:
@ -315,9 +322,33 @@ class ConnectivityCheckClient
//media stream, the state of the check list is set to Failed. //media stream, the state of the check list is set to Failed.
if ( !stream.validListContainsAllComponents()) if ( !stream.validListContainsAllComponents())
{ {
logger.info("CheckList for stream " + stream.getName() + final String streamName = stream.getName();
" FAILED"); Timer timer = timers.get(streamName);
if(timer == null)
{
logger.info("CheckList will failed in a few seconds if no" +
"succeeded checks come");
TimerTask task = new TimerTask()
{
@Override
public void run()
{
if(checkList.getState() != CheckListState.COMPLETED)
{
logger.info("CheckList for stream " +
streamName + " FAILED");
checkList.setState(CheckListState.FAILED); checkList.setState(CheckListState.FAILED);
parentAgent.checkListStatesUpdated();
}
}
};
timer = new Timer();
timers.put(streamName, timer);
timer.schedule(task, 5000);
}
} }
//For each frozen check list, the agent groups together all of the //For each frozen check list, the agent groups together all of the
@ -395,6 +426,15 @@ class ConnectivityCheckClient
.getAddress(response.getTransactionID()); .getAddress(response.getTransactionID());
} }
// XXX AddressAttribute always returns UDP based TransportAddress
if(checkedPair.getLocalCandidate().getTransport() == Transport.TCP)
{
mappedAddress = new TransportAddress(
mappedAddress.getAddress(),
mappedAddress.getPort(),
Transport.TCP);
}
LocalCandidate validLocalCandidate = parentAgent LocalCandidate validLocalCandidate = parentAgent
.findLocalCandidate(mappedAddress); .findLocalCandidate(mappedAddress);
Candidate validRemoteCandidate = checkedPair.getRemoteCandidate(); Candidate validRemoteCandidate = checkedPair.getRemoteCandidate();
@ -483,12 +523,16 @@ class ConnectivityCheckClient
//same media stream and same foundation to Waiting. //same media stream and same foundation to Waiting.
IceMediaStream parentStream = checkedPair.getParentComponent() IceMediaStream parentStream = checkedPair.getParentComponent()
.getParentStream(); .getParentStream();
synchronized(this)
{
CheckList parentCheckList = parentStream.getCheckList(); CheckList parentCheckList = parentStream.getCheckList();
for(CandidatePair pair : parentCheckList) for(CandidatePair pair : parentCheckList)
if ((pair.getState() == CandidatePairState.FROZEN) && if ((pair.getState() == CandidatePairState.FROZEN) &&
(checkedPair.getFoundation().equals(pair.getFoundation()))) (checkedPair.getFoundation().equals(pair.getFoundation())))
pair.setStateWaiting(); pair.setStateWaiting();
}
// The agent examines the check list for all other streams in turn // The agent examines the check list for all other streams in turn
// If the check list is active, the agent changes the state of // If the check list is active, the agent changes the state of

View File

@ -32,11 +32,17 @@ public class GoogleRelayedCandidate
*/ */
private GoogleRelayedCandidateDatagramSocket relayedCandidateDatagramSocket; private GoogleRelayedCandidateDatagramSocket relayedCandidateDatagramSocket;
/**
* The <tt>RelayedCandidateSocket</tt> of this
* <tt>GoogleRelayedCandidate</tt>.
*/
private GoogleRelayedCandidateSocket relayedCandidateSocket = null;
/** /**
* The application-purposed <tt>DatagramSocket</tt> associated with this * The application-purposed <tt>DatagramSocket</tt> associated with this
* <tt>Candidate</tt>. * <tt>Candidate</tt>.
*/ */
private DatagramSocket socket; private IceSocketWrapper socket;
/** /**
* The <tt>GoogleTurnCandidateHarvest</tt> which has harvested this * The <tt>GoogleTurnCandidateHarvest</tt> which has harvested this
@ -97,7 +103,7 @@ public class GoogleRelayedCandidate
* @return the <tt>RelayedCandidateDatagramSocket</tt> of this * @return the <tt>RelayedCandidateDatagramSocket</tt> of this
* <tt>RelayedCandidate</tt> * <tt>RelayedCandidate</tt>
*/ */
public synchronized GoogleRelayedCandidateDatagramSocket private synchronized GoogleRelayedCandidateDatagramSocket
getRelayedCandidateDatagramSocket() getRelayedCandidateDatagramSocket()
{ {
if (relayedCandidateDatagramSocket == null) if (relayedCandidateDatagramSocket == null)
@ -118,25 +124,66 @@ public class GoogleRelayedCandidate
return relayedCandidateDatagramSocket; return relayedCandidateDatagramSocket;
} }
/**
* Gets the <tt>RelayedCandidateDatagramSocket</tt> of this
* <tt>RelayedCandidate</tt>.
* <p>
* <b>Note</b>: The method is part of the internal API of
* <tt>RelayedCandidate</tt> and <tt>TurnCandidateHarvest</tt> and is not
* intended for public use.
* </p>
*
* @return the <tt>RelayedCandidateDatagramSocket</tt> of this
* <tt>RelayedCandidate</tt>
*/
private synchronized GoogleRelayedCandidateSocket
getRelayedCandidateSocket()
{
if (relayedCandidateSocket == null)
{
try
{
relayedCandidateSocket
= new GoogleRelayedCandidateSocket(
this,
turnCandidateHarvest,
username);
}
catch (SocketException sex)
{
throw new UndeclaredThrowableException(sex);
}
}
return relayedCandidateSocket;
}
/** /**
* Gets the application-purposed <tt>DatagramSocket</tt> associated with * Gets the application-purposed <tt>DatagramSocket</tt> associated with
* this <tt>Candidate</tt>. * this <tt>Candidate</tt>.
* *
* @return the <tt>DatagramSocket</tt> associated with this * @return the <tt>DatagramSocket</tt> associated with this
* <tt>Candidate</tt> * <tt>Candidate</tt>
* @see LocalCandidate#getSocket() * @see LocalCandidate#getIceSocketWrapper()
*/ */
public synchronized DatagramSocket getSocket() public synchronized IceSocketWrapper getIceSocketWrapper()
{ {
if (socket == null) if (socket == null)
{ {
try try
{
if(getTransport() == Transport.UDP)
{ {
socket socket
= new MultiplexingDatagramSocket( = new IceUdpSocketWrapper(new MultiplexingDatagramSocket(
getRelayedCandidateDatagramSocket()); getRelayedCandidateDatagramSocket()));
} }
catch (SocketException sex) else if(getTransport() == Transport.TCP)
{
final Socket s = getRelayedCandidateSocket();
socket = new IceTcpSocketWrapper(new MultiplexingSocket(s));
}
}
catch (Exception sex)
{ {
throw new UndeclaredThrowableException(sex); throw new UndeclaredThrowableException(sex);
} }

View File

@ -33,7 +33,7 @@ public class HostCandidate extends LocalCandidate
* If this is a local candidate the field contains the socket that is * If this is a local candidate the field contains the socket that is
* actually associated with the candidate. * actually associated with the candidate.
*/ */
private final DatagramSocket socket; private final IceSocketWrapper socket;
/** /**
* Creates a HostCandidate for the specified transport address. * Creates a HostCandidate for the specified transport address.
@ -43,7 +43,7 @@ public class HostCandidate extends LocalCandidate
* @param parentComponent the <tt>Component</tt> that this candidate * @param parentComponent the <tt>Component</tt> that this candidate
* belongs to. * belongs to.
*/ */
public HostCandidate(DatagramSocket socket, public HostCandidate(IceSocketWrapper socket,
Component parentComponent) Component parentComponent)
{ {
super(new TransportAddress(socket.getLocalAddress(), super(new TransportAddress(socket.getLocalAddress(),
@ -55,6 +55,28 @@ public class HostCandidate extends LocalCandidate
setBase(this); setBase(this);
} }
/**
* Creates a HostCandidate for the specified transport address.
*
* @param socket the {@link DatagramSocket} that communication associated
* with this <tt>Candidate</tt> will be going through.
* @param parentComponent the <tt>Component</tt> that this candidate
* belongs to.
* @param transport transport protocol used
*/
public HostCandidate(IceSocketWrapper socket,
Component parentComponent,
Transport transport)
{
super(new TransportAddress(socket.getLocalAddress(),
socket.getLocalPort(), transport),
parentComponent,
CandidateType.HOST_CANDIDATE);
this.socket = socket;
setBase(this);
}
/** /**
* Creates a new <tt>StunDatagramPacketFilter</tt> which is to capture STUN * Creates a new <tt>StunDatagramPacketFilter</tt> which is to capture STUN
* messages and make them available to the <tt>DatagramSocket</tt> returned * messages and make them available to the <tt>DatagramSocket</tt> returned
@ -83,9 +105,9 @@ public class HostCandidate extends LocalCandidate
* *
* @return the <tt>DatagramSocket</tt> associated with this * @return the <tt>DatagramSocket</tt> associated with this
* <tt>Candidate</tt> * <tt>Candidate</tt>
* @see LocalCandidate#getSocket() * @see LocalCandidate#getIceSocketWrapper()
*/ */
public DatagramSocket getSocket() public IceSocketWrapper getIceSocketWrapper()
{ {
return socket; return socket;
} }

View File

@ -8,10 +8,13 @@
package org.ice4j.ice; package org.ice4j.ice;
import java.beans.*; import java.beans.*;
import java.io.*;
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.*;
/** /**
* The class represents a media stream from the ICE perspective, i.e. a * The class represents a media stream from the ICE perspective, i.e. a
@ -356,6 +359,30 @@ public class IceMediaStream
{ {
if(localCnd.canReach(remoteCnd)) if(localCnd.canReach(remoteCnd))
{ {
if(localCnd.getTransport() == Transport.TCP &&
parentAgent.getCompatibilityMode() ==
CompatibilityMode.GTALK)
{
/* for TCP, create a new Candidate (a new connection)
* to each of remote TCP candidates
*/
try
{
Socket sock = new MultiplexingSocket();
sock.connect(new InetSocketAddress(
remoteCnd.getTransportAddress().getAddress(),
remoteCnd.getTransportAddress().getPort()));
LocalCandidate tmp =
new HostCandidate(new IceTcpSocketWrapper(sock),
component);
tmp.setUfrag(localCnd.getUfrag());
localCnd = tmp;
}
catch (IOException e)
{
continue;
}
}
CandidatePair pair = new CandidatePair(localCnd, remoteCnd); CandidatePair pair = new CandidatePair(localCnd, remoteCnd);
checkList.add(pair); checkList.add(pair);

View File

@ -7,6 +7,7 @@
*/ */
package org.ice4j.ice; package org.ice4j.ice;
import java.io.*;
import java.net.*; import java.net.*;
import java.util.logging.*; import java.util.logging.*;
@ -54,12 +55,37 @@ public abstract class LocalCandidate
} }
/** /**
* Gets the <tt>DatagramSocket</tt> associated with this <tt>Candidate</tt>. * Gets the <tt>DatagramSocket</tt> associated with this
* <tt>Candidate</tt>.
* *
* @return the <tt>DatagramSocket</tt> associated with this * @return the <tt>DatagramSocket</tt> associated with this
* <tt>Candidate</tt> * <tt>Candidate</tt>
*/ */
public abstract DatagramSocket getSocket(); public DatagramSocket getDatagramSocket()
{
return getIceSocketWrapper().getUDPSocket();
}
/**
* Gets the <tt>Socket</tt> associated with this
* <tt>Candidate</tt>.
*
* @return the <tt>Socket</tt> associated with this
* <tt>Candidate</tt>
*/
public Socket getSocket()
{
return getIceSocketWrapper().getTCPSocket();
}
/**
* Gets the <tt>IceSocketWrapper</tt> associated with this
* <tt>Candidate</tt>.
*
* @return the <tt>IceSocketWrapper</tt> associated with this
* <tt>Candidate</tt>
*/
protected abstract IceSocketWrapper getIceSocketWrapper();
/** /**
* Creates if necessary and returns a <tt>DatagramSocket</tt> that would * Creates if necessary and returns a <tt>DatagramSocket</tt> that would
@ -74,12 +100,16 @@ public abstract class LocalCandidate
* and receiving STUN packets, while harvesting STUN candidates or * and receiving STUN packets, while harvesting STUN candidates or
* performing connectivity checks. * performing connectivity checks.
*/ */
public DatagramSocket getStunSocket(TransportAddress serverAddress) public IceSocketWrapper getStunSocket(TransportAddress serverAddress)
{ {
DatagramSocket hostSocket = getSocket(); IceSocketWrapper hostSocket = getIceSocketWrapper();
DatagramSocket stunSocket = null;
if (hostSocket instanceof MultiplexingDatagramSocket) if(hostSocket.getTCPSocket() != null)
{
Socket tcpSocket = hostSocket.getTCPSocket();
Socket tcpStunSocket = null;
if (tcpSocket instanceof MultiplexingSocket)
{ {
DatagramPacketFilter stunDatagramPacketFilter DatagramPacketFilter stunDatagramPacketFilter
= createStunDatagramPacketFilter(serverAddress); = createStunDatagramPacketFilter(serverAddress);
@ -87,8 +117,64 @@ public abstract class LocalCandidate
try try
{ {
stunSocket tcpStunSocket
= ((MultiplexingDatagramSocket) hostSocket) = ((MultiplexingSocket) tcpSocket)
.getSocket(stunDatagramPacketFilter);
}
catch (SocketException sex) //don't u just luv da name? ;)
{
logger.log(Level.SEVERE,
"Failed to acquire Socket"
+ " specific to STUN communication.",
sex);
exception = sex;
}
if (tcpStunSocket == null)
{
throw
new IllegalStateException(
"Failed to acquire Socket"
+ " specific to STUN communication",
exception);
}
}
else
{
throw
new IllegalStateException(
"The socket of "
+ getClass().getSimpleName()
+ " must be a MultiplexingSocket " +
"instance");
}
IceTcpSocketWrapper stunSocket = null;
try
{
stunSocket = new IceTcpSocketWrapper(tcpStunSocket);
}
catch(IOException e)
{
logger.info("Failed to create IceTcpSocketWrapper " + e);
}
return stunSocket;
}
else if(hostSocket.getUDPSocket() != null)
{
DatagramSocket udpSocket = hostSocket.getUDPSocket();
DatagramSocket udpStunSocket = null;
if (udpSocket instanceof MultiplexingDatagramSocket)
{
DatagramPacketFilter stunDatagramPacketFilter
= createStunDatagramPacketFilter(serverAddress);
Throwable exception = null;
try
{
udpStunSocket
= ((MultiplexingDatagramSocket) udpSocket)
.getSocket(stunDatagramPacketFilter); .getSocket(stunDatagramPacketFilter);
} }
catch (SocketException sex) //don't u just luv da name? ;) catch (SocketException sex) //don't u just luv da name? ;)
@ -99,7 +185,7 @@ public abstract class LocalCandidate
sex); sex);
exception = sex; exception = sex;
} }
if (stunSocket == null) if (udpStunSocket == null)
{ {
throw throw
new IllegalStateException( new IllegalStateException(
@ -114,9 +200,13 @@ public abstract class LocalCandidate
new IllegalStateException( new IllegalStateException(
"The socket of " "The socket of "
+ getClass().getSimpleName() + getClass().getSimpleName()
+ " must be a MultiplexingDatagramSocket instance"); + " must be a MultiplexingDatagramSocket " +
"instance");
} }
return stunSocket; return new IceUdpSocketWrapper(udpStunSocket);
}
return null;
} }
/** /**
@ -159,7 +249,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.
DatagramSocket socket = getSocket(); IceSocketWrapper socket = getIceSocketWrapper();
if (socket != null) if (socket != null)
{ {
@ -167,7 +257,7 @@ public abstract class LocalCandidate
if ((base == null) if ((base == null)
|| (base == this) || (base == this)
|| (base.getSocket() != socket)) || (base.getIceSocketWrapper() != socket))
{ {
//remove our socket from the stack. //remove our socket from the stack.
getStunStack().removeSocket(getTransportAddress()); getStunStack().removeSocket(getTransportAddress());

View File

@ -6,9 +6,8 @@
*/ */
package org.ice4j.ice; package org.ice4j.ice;
import java.net.*;
import org.ice4j.*; import org.ice4j.*;
import org.ice4j.socket.*;
/** /**
* Peer Reflexive Candidates are candidates whose IP address and port are a * Peer Reflexive Candidates are candidates whose IP address and port are a
@ -55,10 +54,10 @@ public class PeerReflexiveCandidate
* *
* @return the <tt>DatagramSocket</tt> associated with this * @return the <tt>DatagramSocket</tt> associated with this
* <tt>Candidate</tt> * <tt>Candidate</tt>
* @see LocalCandidate#getSocket() * @see LocalCandidate#getIceSocketWrapper()
*/ */
public DatagramSocket getSocket() public IceSocketWrapper getIceSocketWrapper()
{ {
return getBase().getSocket(); return getBase().getIceSocketWrapper();
} }
} }

View File

@ -36,7 +36,7 @@ public class RelayedCandidate
* The application-purposed <tt>DatagramSocket</tt> associated with this * The application-purposed <tt>DatagramSocket</tt> associated with this
* <tt>Candidate</tt>. * <tt>Candidate</tt>.
*/ */
private DatagramSocket socket; private IceSocketWrapper socket;
/** /**
* The <tt>TurnCandidateHarvest</tt> which has harvested this * The <tt>TurnCandidateHarvest</tt> which has harvested this
@ -114,17 +114,17 @@ 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#getSocket() * @see LocalCandidate#getIceSocketWrapper()
*/ */
public synchronized DatagramSocket getSocket() public synchronized IceSocketWrapper getIceSocketWrapper()
{ {
if (socket == null) if (socket == null)
{ {
try try
{ {
socket socket
= new MultiplexingDatagramSocket( = new IceUdpSocketWrapper(new MultiplexingDatagramSocket(
getRelayedCandidateDatagramSocket()); getRelayedCandidateDatagramSocket()));
} }
catch (SocketException sex) catch (SocketException sex)
{ {

View File

@ -7,9 +7,8 @@
*/ */
package org.ice4j.ice; package org.ice4j.ice;
import java.net.*;
import org.ice4j.*; import org.ice4j.*;
import org.ice4j.socket.*;
/** /**
* <tt>ServerReflexiveCandidate</tt>s are candidates whose IP address and port * <tt>ServerReflexiveCandidate</tt>s are candidates whose IP address and port
@ -56,10 +55,10 @@ public class ServerReflexiveCandidate
* *
* @return the <tt>DatagramSocket</tt> associated with this * @return the <tt>DatagramSocket</tt> associated with this
* <tt>Candidate</tt> * <tt>Candidate</tt>
* @see LocalCandidate#getSocket() * @see LocalCandidate#getIceSocketWrapper()
*/ */
public DatagramSocket getSocket() public IceSocketWrapper getIceSocketWrapper()
{ {
return getBase().getSocket(); return getBase().getIceSocketWrapper();
} }
} }

View File

@ -7,9 +7,8 @@
*/ */
package org.ice4j.ice; package org.ice4j.ice;
import java.net.*;
import org.ice4j.*; import org.ice4j.*;
import org.ice4j.socket.*;
import org.bitlet.weupnp.*; import org.bitlet.weupnp.*;
@ -67,7 +66,7 @@ public class UPNPCandidate
{ {
} }
DatagramSocket socket = getSocket(); IceSocketWrapper socket = getIceSocketWrapper();
if(socket != null) if(socket != null)
{ {
socket.close(); socket.close();
@ -83,8 +82,8 @@ public class UPNPCandidate
* <tt>Candidate</tt> * <tt>Candidate</tt>
*/ */
@Override @Override
public DatagramSocket getSocket() public IceSocketWrapper getIceSocketWrapper()
{ {
return getBase().getSocket(); return getBase().getIceSocketWrapper();
} }
} }

View File

@ -90,6 +90,15 @@ public class GoogleTurnCandidateHarvest
{ {
TransportAddress relayedAddress TransportAddress relayedAddress
= ((MappedAddressAttribute) attribute).getAddress(); = ((MappedAddressAttribute) attribute).getAddress();
if(harvester.stunServer.getTransport() == Transport.TCP)
{
relayedAddress = new TransportAddress(
relayedAddress.getAddress(),
harvester.stunServer.getPort(),
//relayedAddress.getPort() - 1,
Transport.TCP);
}
GoogleRelayedCandidate relayedCandidate GoogleRelayedCandidate relayedCandidate
= createRelayedCandidate( = createRelayedCandidate(
relayedAddress, relayedAddress,
@ -256,34 +265,6 @@ public class GoogleTurnCandidateHarvest
SEND_KEEP_ALIVE_MESSAGE_INTERVAL_NOT_SPECIFIED); SEND_KEEP_ALIVE_MESSAGE_INTERVAL_NOT_SPECIFIED);
} }
/**
* Sends a specific <tt>Request</tt> on behalf of a specific
* <tt>RelayedCandidateDatagramSocket</tt> to the TURN server associated
* with this <tt>GoogleTurnCandidateHarvest</tt>.
*
* @param relayedCandidateDatagramSocket the
* <tt>RelayedCandidateDatagramSocket</tt> which sends the specified
* <tt>Request</tt> and which is to be notified of the result
* @param request the <tt>Request</tt> to be sent to the TURN server
* associated with this <tt>TurnCandidateHarvest</tt>
* @return an array of <tt>byte</tt>s which represents the ID of the
* transaction with which the specified <tt>Request</tt> has been sent to
* the TURN server
* @throws StunException if anything goes wrong while sending the specified
* <tt>Request</tt>
*/
public byte[] sendRequest(
RelayedCandidateDatagramSocket relayedCandidateDatagramSocket,
Request request)
throws StunException
{
TransactionID transactionID = TransactionID.createNewTransactionID();
transactionID.setApplicationData(relayedCandidateDatagramSocket);
transactionID = sendRequest(request, false, transactionID);
return (transactionID == null) ? null : transactionID.getBytes();
}
/** /**
* Notifies this <tt>StunCandidateHarvest</tt> that a specific * Notifies this <tt>StunCandidateHarvest</tt> that a specific
* <tt>Request</tt> has either received an error <tt>Response</tt> or has * <tt>Request</tt> has either received an error <tt>Response</tt> or has
@ -317,7 +298,12 @@ public class GoogleTurnCandidateHarvest
*/ */
Object applicationData = transactionID.getApplicationData(); Object applicationData = transactionID.getApplicationData();
if ((applicationData instanceof RelayedCandidateDatagramSocket) if ((applicationData instanceof GoogleRelayedCandidateDatagramSocket)
&& ((RelayedCandidateDatagramSocket) applicationData)
.processErrorOrFailure(response, request))
return true;
else if ((applicationData instanceof
GoogleRelayedCandidateDatagramSocket)
&& ((RelayedCandidateDatagramSocket) applicationData) && ((RelayedCandidateDatagramSocket) applicationData)
.processErrorOrFailure(response, request)) .processErrorOrFailure(response, request))
return true; return true;
@ -381,9 +367,14 @@ public class GoogleTurnCandidateHarvest
*/ */
Object applicationData = transactionID.getApplicationData(); Object applicationData = transactionID.getApplicationData();
if (applicationData instanceof RelayedCandidateDatagramSocket) if (applicationData instanceof GoogleRelayedCandidateDatagramSocket)
{ {
((RelayedCandidateDatagramSocket) applicationData) ((GoogleRelayedCandidateDatagramSocket) applicationData)
.processSuccess(response, request);
}
else if (applicationData instanceof GoogleRelayedCandidateSocket)
{
((GoogleRelayedCandidateSocket) applicationData)
.processSuccess(response, request); .processSuccess(response, request);
} }
} }

View File

@ -0,0 +1,158 @@
/*
* ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
* Maintained by the SIP Communicator community (http://sip-communicator.org).
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package org.ice4j.ice.harvest;
import java.io.*;
import java.net.*;
import java.util.*;
import org.ice4j.*;
import org.ice4j.ice.*;
import org.ice4j.socket.*;
/**
* Implements a <tt>CandidateHarvester</tt> which gathers Google TURN SSLTCP
* dialect <tt>Candidate</tt>s for a specified {@link Component}.
*
* @author Sebastien Vincent
*/
public class GoogleTurnSSLCandidateHarvester
extends GoogleTurnCandidateHarvester
{
/**
* Data for the SSL server handshake.
*/
private static final byte SSL_SERVER_HANDSHAKE[] =
{
0x16, 0x03, 0x01, 0x00, 0x4a, 0x02, 0x00, 0x00,
0x46, 0x03, 0x01, 0x42, (byte)0x85, 0x45, (byte)0xa7, 0x27,
(byte)0xa9, 0x5d, (byte)0xa0, (byte)0xb3, (byte)0xc5, (byte)0xe7, 0x53,
(byte)0xda,
0x48, 0x2b, 0x3f, (byte)0xc6, 0x5a, (byte)0xca, (byte)0x89, (byte)0xc1,
0x58, 0x52, (byte)0xa1, 0x78, 0x3c, 0x5b, 0x17, 0x46,
0x00, (byte)0x85, 0x3f, 0x20, 0x0e, (byte)0xd3, 0x06, 0x72,
0x5b, 0x5b, 0x1b, 0x5f, 0x15, (byte)0xac, 0x13, (byte)0xf9,
(byte)0x88, 0x53, (byte)0x9d, (byte)0x9b, (byte)0xe8, 0x3d, 0x7b, 0x0c,
0x30, 0x32, 0x6e, 0x38, 0x4d, (byte)0xa2, 0x75, 0x57,
0x41, 0x6c, 0x34, 0x5c, 0x00, 0x04, 0x00
};
/**
* Data for the SSL client handshake.
*/
private static final byte SSL_CLIENT_HANDSHAKE[] =
{
(byte)0x80, 0x46, 0x01, 0x03, 0x01, 0x00, 0x2d, 0x00,
0x00, 0x00, 0x10, 0x01, 0x00, (byte)0x80, 0x03, 0x00,
(byte)0x80, 0x07, 0x00, (byte)0xc0, 0x06, 0x00, 0x40, 0x02,
0x00, (byte)0x80, 0x04, 0x00, (byte)0x80, 0x00, 0x00, 0x04,
0x00, (byte)0xfe, (byte)0xff, 0x00, 0x00, 0x0a, 0x00, (byte)0xfe,
(byte)0xfe, 0x00, 0x00, 0x09, 0x00, 0x00, 0x64, 0x00,
0x00, 0x62, 0x00, 0x00, 0x03, 0x00, 0x00, 0x06,
0x1f, 0x17, 0x0c, (byte)0xa6, 0x2f, 0x00, 0x78, (byte)0xfc,
0x46, 0x55, 0x2e, (byte)0xb1, (byte)0x83, 0x39, (byte)0xf1, (byte)0xea
};
/**
* Initializes a new <tt>GoogleTurnSSLCandidateHarvester</tt> instance which
* is to work with a specific Google TURN server.
*
* @param turnServer the <tt>TransportAddress</tt> of the TURN server the
* new instance is to work with
*/
public GoogleTurnSSLCandidateHarvester(TransportAddress turnServer)
{
this(turnServer, null);
}
/**
* Initializes a new <tt>GoogleTurnSSLCandidateHarvester</tt> instance which is
* to work with a specific TURN server using a specific username for the
* purposes of the STUN short-term credential mechanism.
*
* @param turnServer the <tt>TransportAddress</tt> of the TURN server the
* new instance is to work with
* @param shortTermCredentialUsername the username to be used by the new
* instance for the purposes of the STUN short-term credential mechanism or
* <tt>null</tt> if the use of the STUN short-term credential mechanism is
* not determined at the time of the construction of the new instance
*/
public GoogleTurnSSLCandidateHarvester(TransportAddress turnServer,
String shortTermCredentialUsername)
{
super(turnServer, shortTermCredentialUsername);
}
/**
* Creates a new <tt>GoogleTurnSSLCandidateHarvest</tt> instance which is to
* perform TURN harvesting of a specific <tt>HostCandidate</tt>.
*
* @param hostCandidate the <tt>HostCandidate</tt> for which harvesting is
* to be performed by the new <tt>TurnCandidateHarvest</tt> instance
* @return a new <tt>GoogleTurnSSLCandidateHarvest</tt> instance which is to
* perform TURN harvesting of the specified <tt>hostCandidate</tt>
* @see StunCandidateHarvester#createHarvest(HostCandidate)
*/
@Override
protected GoogleTurnCandidateHarvest createHarvest(
HostCandidate hostCandidate)
{
return new GoogleTurnCandidateHarvest(this, hostCandidate);
}
/**
* Returns the host candidate.
* For UDP it simply returns the candidate passed as paramter
*
* However for TCP, we cannot return the same hostCandidate because in Java
* a "server" socket cannot connect to a destination with the same local
* address/port (i.e. a Java Socket cannot act as both server/client).
*
* @param hostCand HostCandidate
* @return HostCandidate
*/
@Override
protected HostCandidate getHostCandidate(HostCandidate hostCand)
{
HostCandidate cand = null;
try
{
Socket sock = new Socket(stunServer.getAddress(),
stunServer.getPort());
OutputStream outputStream = sock.getOutputStream();
outputStream.write(SSL_CLIENT_HANDSHAKE);
InputStream inputStream = sock.getInputStream();
byte data[] = new byte[SSL_SERVER_HANDSHAKE.length];
inputStream.read(data);
outputStream = null;
inputStream = null;
if(Arrays.equals(data, SSL_SERVER_HANDSHAKE))
{
cand = new HostCandidate(new IceTcpSocketWrapper(
new MultiplexingSocket(sock)),
hostCand.getParentComponent(), Transport.TCP);
hostCand.getParentComponent().getParentStream().
getParentAgent().getStunStack().addSocket(
cand.getStunSocket(null));
}
else
return null;
}
catch(Exception io)
{
return null;
}
return cand;
}
}

View File

@ -47,24 +47,32 @@ public class HostCandidateHarvester
* @param minPort the port number where we should first try to bind before * @param minPort the port number where we should first try to bind before
* moving to the next one (i.e. <tt>minPort + 1</tt>) * moving to the next one (i.e. <tt>minPort + 1</tt>)
* @param maxPort the maximum port number where we should try binding * @param maxPort the maximum port number where we should try binding
* before giving up and throwinG an exception. * before giving up and throwing an exception.
* @param transport transport protocol used
* *
* @throws IllegalArgumentException if either <tt>minPort</tt> or * @throws IllegalArgumentException if either <tt>minPort</tt> or
* <tt>maxPort</tt> is not a valid port number or if <tt>minPort > * <tt>maxPort</tt> is not a valid port number, <tt>minPort >
* maxPort</tt>. * maxPort</tt> or if transport is not supported.
* @throws IOException if an error occurs while the underlying resolver lib * @throws IOException if an error occurs while the underlying resolver lib
* is using sockets. * is using sockets.
*/ */
public void harvest(Component component, public void harvest(Component component,
int preferredPort, int preferredPort,
int minPort, int minPort,
int maxPort) int maxPort,
Transport transport)
throws IllegalArgumentException, throws IllegalArgumentException,
IOException IOException
{ {
Enumeration<NetworkInterface> interfaces Enumeration<NetworkInterface> interfaces
= NetworkInterface.getNetworkInterfaces(); = NetworkInterface.getNetworkInterfaces();
if(transport != Transport.UDP && transport != Transport.TCP)
{
throw new IllegalArgumentException(
"Transport protocol not supported: " + transport);
}
boolean boundAtLeastOneSocket = false; boolean boundAtLeastOneSocket = false;
while (interfaces.hasMoreElements()) while (interfaces.hasMoreElements())
{ {
@ -83,13 +91,24 @@ public class HostCandidateHarvester
{ {
InetAddress addr = addresses.nextElement(); InetAddress addr = addresses.nextElement();
DatagramSocket sock; IceSocketWrapper sock = null;
try try
{
if(transport == Transport.UDP)
{ {
sock = createDatagramSocket( sock = createDatagramSocket(
addr, preferredPort, minPort, maxPort); addr, preferredPort, minPort, maxPort);
boundAtLeastOneSocket = true; boundAtLeastOneSocket = true;
} }
else if(transport == Transport.TCP)
{
if(addr instanceof Inet6Address)
continue;
sock = createServerSocket(addr, preferredPort, minPort,
maxPort, component);
boundAtLeastOneSocket = true;
}
}
catch(IOException exc) catch(IOException exc)
{ {
//there seems to be a problem with this particular address //there seems to be a problem with this particular address
@ -102,15 +121,25 @@ public class HostCandidateHarvester
+"\npreferredPort:" + preferredPort +"\npreferredPort:" + preferredPort
+"\nminPort:" + minPort +"\nminPort:" + minPort
+"\nmaxPort:" + maxPort +"\nmaxPort:" + maxPort
+"\nprotocol:" + transport
+"\nContinuing with next address"); +"\nContinuing with next address");
} }
continue; continue;
} }
HostCandidate candidate = new HostCandidate(sock, component); HostCandidate candidate = new HostCandidate(sock, component,
transport);
candidate.setVirtual(NetworkUtils.isInterfaceVirtual(iface)); candidate.setVirtual(NetworkUtils.isInterfaceVirtual(iface));
component.addLocalCandidate(candidate); component.addLocalCandidate(candidate);
if(transport == Transport.TCP)
{
/* have to wait a client connection to add a STUN socket
* to the StunStack
*/
continue;
}
//We are most certainly going to use all local host candidates //We are most certainly going to use all local host candidates
//for sending and receiving STUN connectivity checks. In case //for sending and receiving STUN connectivity checks. In case
//we have enabled STUN, we are going to use them as well while //we have enabled STUN, we are going to use them as well while
@ -130,6 +159,105 @@ public class HostCandidateHarvester
} }
} }
/**
* Creates a <tt>ServerSocket</tt> and binds it to the specified
* <tt>localAddress</tt> and a port in the range specified by the
* <tt>minPort</tt> and <tt>maxPort</tt> parameters.
*
* @param laddr the address that we'd like to bind the socket on.
* @param preferredPort the port number that we should try to bind to first.
* @param minPort the port number where we should first try to bind before
* moving to the next one (i.e. <tt>minPort + 1</tt>)
* @param maxPort the maximum port number where we should try binding
* before giving up and throwinG an exception.
*
* @return the newly created <tt>DatagramSocket</tt>.
*
* @throws IllegalArgumentException if either <tt>minPort</tt> or
* <tt>maxPort</tt> is not a valid port number or if <tt>minPort >
* maxPort</tt>.
* @throws IOException if an error occurs while the underlying resolver lib
* is using sockets.
* @throws BindException if we couldn't find a free port between
* <tt>minPort</tt> and <tt>maxPort</tt> before reaching the maximum allowed
* number of retries.
*/
private IceSocketWrapper createServerSocket(InetAddress laddr,
int preferredPort, int minPort, int maxPort,
Component component)
throws IllegalArgumentException,
IOException,
BindException
{
// make sure port numbers are valid
if (!NetworkUtils.isValidPortNumber(minPort)
|| !NetworkUtils.isValidPortNumber(maxPort))
{
throw new IllegalArgumentException("minPort (" + minPort
+ ") and maxPort (" + maxPort + ") "
+ "should be integers between 1024 and 65535.");
}
// make sure minPort comes before maxPort.
if (minPort > maxPort)
{
throw new IllegalArgumentException("minPort (" + minPort
+ ") should be less than or "
+ "equal to maxPort (" + maxPort + ")");
}
// if preferredPort is not in the allowed range, place it at min.
if (minPort > preferredPort || preferredPort > maxPort)
{
throw new IllegalArgumentException("preferredPort ("+preferredPort
+") must be between minPort (" + minPort
+ ") and maxPort (" + maxPort + ")");
}
int bindRetries = StackProperties.getInt(
StackProperties.BIND_RETRIES,
StackProperties.BIND_RETRIES_DEFAULT_VALUE);
int port = preferredPort;
for (int i = 0; i < bindRetries; i++)
{
try
{
ServerSocket sock = new ServerSocket();
sock.setReuseAddress(true);
sock.bind(new InetSocketAddress(laddr, port));
IceSocketWrapper socket
= new IceTcpServerSocketWrapper(sock,
component);
if(logger.isLoggable(Level.FINEST))
{
logger.log(
Level.FINEST,
"just bound to: " + sock.getLocalSocketAddress());
}
return socket;
}
catch (SocketException se)
{
logger.log(
Level.INFO,
"Retrying a bind because of a failure to bind to"
+ " address " + laddr
+ " and port " + port
+ " (" + se.getMessage() +")");
logger.log(Level.INFO, "", se);
}
port ++;
if (port > maxPort)
port = minPort;
}
throw new BindException("Not implemented");
}
/** /**
* Creates a <tt>DatagramSocket</tt> and binds it to the specified * Creates a <tt>DatagramSocket</tt> and binds it to the specified
* <tt>localAddress</tt> and a port in the range specified by the * <tt>localAddress</tt> and a port in the range specified by the
@ -160,7 +288,7 @@ public class HostCandidateHarvester
* <tt>minPort</tt> and <tt>maxPort</tt> before reaching the maximum allowed * <tt>minPort</tt> and <tt>maxPort</tt> before reaching the maximum allowed
* number of retries. * number of retries.
*/ */
private DatagramSocket createDatagramSocket(InetAddress laddr, private IceSocketWrapper createDatagramSocket(InetAddress laddr,
int preferredPort, int preferredPort,
int minPort, int minPort,
int maxPort) int maxPort)
@ -202,8 +330,9 @@ public class HostCandidateHarvester
{ {
try try
{ {
DatagramSocket sock IceSocketWrapper sock
= new MultiplexingDatagramSocket(port, laddr); = new IceUdpSocketWrapper(new
MultiplexingDatagramSocket(port, laddr));
if(logger.isLoggable(Level.FINEST)) if(logger.isLoggable(Level.FINEST))
{ {
@ -246,7 +375,7 @@ public class HostCandidateHarvester
*/ */
private void createAndRegisterStunSocket(HostCandidate candidate) private void createAndRegisterStunSocket(HostCandidate candidate)
{ {
DatagramSocket stunSocket = candidate.getStunSocket(null); IceSocketWrapper stunSocket = candidate.getStunSocket(null);
candidate.getStunStack().addSocket(stunSocket); candidate.getStunStack().addSocket(stunSocket);
} }

View File

@ -7,12 +7,14 @@
*/ */
package org.ice4j.ice.harvest; package org.ice4j.ice.harvest;
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.ice.*; import org.ice4j.ice.*;
import org.ice4j.security.*; import org.ice4j.security.*;
import org.ice4j.socket.*;
import org.ice4j.stack.*; import org.ice4j.stack.*;
/** /**
@ -217,7 +219,8 @@ public class StunCandidateHarvester
stunStack = component.getParentStream().getParentAgent().getStunStack(); stunStack = component.getParentStream().getParentAgent().getStunStack();
for (Candidate cand : component.getLocalCandidates()) for (Candidate cand : component.getLocalCandidates())
if (cand instanceof HostCandidate) if (cand instanceof HostCandidate &&
cand.getTransport() == stunServer.getTransport())
startResolvingCandidate((HostCandidate) cand); startResolvingCandidate((HostCandidate) cand);
waitForResolutionEnd(); waitForResolutionEnd();
@ -260,7 +263,12 @@ public class StunCandidateHarvester
if (!hostCand.getTransportAddress().canReach(stunServer)) if (!hostCand.getTransportAddress().canReach(stunServer))
return; return;
StunCandidateHarvest harvest = createHarvest(hostCand); HostCandidate cand = getHostCandidate(hostCand);
if(cand == null)
return;
StunCandidateHarvest harvest = createHarvest(cand);
if (harvest == null) if (harvest == null)
return; return;
@ -335,4 +343,47 @@ public class StunCandidateHarvester
: "STUN"; : "STUN";
return proto + " harvester for srvr: " + this.stunServer; return proto + " harvester for srvr: " + this.stunServer;
} }
/**
* Returns the host candidate.
* For UDP it simply returns the candidate passed as paramter
*
* However for TCP, we cannot return the same hostCandidate because in Java
* a "server" socket cannot connect to a destination with the same local
* address/port (i.e. a Java Socket cannot act as both server/client).
*
* @param hostCand HostCandidate
* @return HostCandidate
*/
protected HostCandidate getHostCandidate(HostCandidate hostCand)
{
HostCandidate cand = null;
// create a new TCP HostCandidate
if(hostCand.getTransport() == Transport.TCP)
{
try
{
Socket sock = new Socket(stunServer.getAddress(),
stunServer.getPort());
cand = new HostCandidate(new IceTcpSocketWrapper(
new MultiplexingSocket(sock)),
hostCand.getParentComponent(), Transport.TCP);
hostCand.getParentComponent().getParentStream().
getParentAgent().getStunStack().addSocket(
cand.getStunSocket(null));
}
catch(Exception io)
{
logger.info("Exception TCP client connect: " + io);
return null;
}
}
else
{
cand = hostCand;
}
return cand;
}
} }

View File

@ -130,8 +130,8 @@ public class UPNPHarvester
String externalIPAddress = device.getExternalIPAddress(); String externalIPAddress = device.getExternalIPAddress();
PortMappingEntry portMapping = new PortMappingEntry(); PortMappingEntry portMapping = new PortMappingEntry();
MultiplexingDatagramSocket socket = IceSocketWrapper socket = new IceUdpSocketWrapper(
new MultiplexingDatagramSocket(0, localAddress); new MultiplexingDatagramSocket(0, localAddress));
int port = socket.getLocalPort(); int port = socket.getLocalPort();
int externalPort = socket.getLocalPort(); int externalPort = socket.getLocalPort();
@ -199,7 +199,7 @@ public class UPNPHarvester
* 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(DatagramSocket socket, public List<LocalCandidate> createUPNPCandidate(IceSocketWrapper socket,
InetAddress localAddr, String externalIP, int port, Component cmp, InetAddress localAddr, String externalIP, int port, Component cmp,
GatewayDevice device) GatewayDevice device)
throws Exception throws Exception
@ -211,7 +211,7 @@ public class UPNPHarvester
HostCandidate base = new HostCandidate(socket, cmp); HostCandidate base = new HostCandidate(socket, cmp);
UPNPCandidate candidate = new UPNPCandidate(addr, base, cmp, device); UPNPCandidate candidate = new UPNPCandidate(addr, base, cmp, device);
DatagramSocket stunSocket = candidate.getStunSocket(null); IceSocketWrapper stunSocket = candidate.getStunSocket(null);
candidate.getStunStack().addSocket(stunSocket); candidate.getStunStack().addSocket(stunSocket);
ret.add(candidate); ret.add(candidate);

View File

@ -452,6 +452,24 @@ public abstract class Message
return length; return length;
} }
/**
* Returns the length of this message's body without padding.
* Some STUN/ICE dialect does not take into account padding (GTalk).
*
* @return the length of the data in this message.
*/
public char getDataLengthWithoutPadding()
{
char length = 0;
for (Attribute att : attributes.values())
{
int attLen = att.getDataLength() + Attribute.HEADER_LENGTH;
length += attLen;
}
return length;
}
/** /**
* Adds the specified attribute to this message. If an attribute with that * Adds the specified attribute to this message. If an attribute with that
* name was already added, it would be replaced. * name was already added, it would be replaced.
@ -794,6 +812,7 @@ public abstract class Message
//make sure we have everything necessary to encode a proper message //make sure we have everything necessary to encode a proper message
validateAttributePresentity(); validateAttributePresentity();
final char dataLength;
if(stunStack.getCompatibilityMode() == CompatibilityMode.GTALK) if(stunStack.getCompatibilityMode() == CompatibilityMode.GTALK)
{ {
/* Google Talk will return error response if it sees unknown /* Google Talk will return error response if it sees unknown
@ -804,9 +823,14 @@ public abstract class Message
if(getAttribute(Attribute.FINGERPRINT) != null) if(getAttribute(Attribute.FINGERPRINT) != null)
removeAttribute(Attribute.FINGERPRINT); removeAttribute(Attribute.FINGERPRINT);
dataLength = getDataLengthWithoutPadding();
}
else
{
dataLength = getDataLength();
} }
final char dataLength = getDataLength();
byte binMsg[] = new byte[HEADER_LENGTH + dataLength]; byte binMsg[] = new byte[HEADER_LENGTH + dataLength];
int offset = 0; int offset = 0;
@ -825,8 +849,7 @@ public abstract class Message
{ {
System.arraycopy(MAGIC_COOKIE, 0, binMsg, offset, 4); System.arraycopy(MAGIC_COOKIE, 0, binMsg, offset, 4);
offset += 4; offset += 4;
System.arraycopy(tranID, 0, binMsg, offset, System.arraycopy(tranID, 0, binMsg, offset, TRANSACTION_ID_LENGTH);
TRANSACTION_ID_LENGTH);
offset += TRANSACTION_ID_LENGTH; offset += TRANSACTION_ID_LENGTH;
} }
else else
@ -835,7 +858,6 @@ public abstract class Message
System.arraycopy(tranID, 0, binMsg, offset, System.arraycopy(tranID, 0, binMsg, offset,
RFC3489_TRANSACTION_ID_LENGTH); RFC3489_TRANSACTION_ID_LENGTH);
offset += RFC3489_TRANSACTION_ID_LENGTH; offset += RFC3489_TRANSACTION_ID_LENGTH;
} }
Iterator<Map.Entry<Character, Attribute>> iter Iterator<Map.Entry<Character, Attribute>> iter

View File

@ -658,7 +658,7 @@ public class MessageFactory
if (data != null && data.length > 0) if (data != null && data.length > 0)
{ {
DataAttribute dataAttribute = AttributeFactory DataAttribute dataAttribute = AttributeFactory
.createDataAttribute(data); .createDataAttributeWithoutPadding(data);
sendRequest.addAttribute(dataAttribute); sendRequest.addAttribute(dataAttribute);
} }
} }

View File

@ -0,0 +1,830 @@
/*
* ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
* Maintained by the SIP Communicator community (http://sip-communicator.org).
*
* Distributable under LGPL license. See terms of license at gnu.org.
*/
package org.ice4j.socket;
import java.io.*;
import java.nio.channels.*;
import java.net.*;
/**
* Implements a <tt>Socket</tt> which delegates its calls to a specific
* <tt>Socket</tt>.
*
* @author Sebastien Vincent
*/
public class DelegatingSocket
extends Socket
{
/**
* Delegate <tt>Socket</tt>.
*/
protected final Socket delegate;
/**
* InputStream for this socket.
*/
private InputStream inputStream = null;
/**
* OutputStream for this socket.
*/
private OutputStream outputStream = null;
/**
* Initializes a new <tt>DelegatingSocket</tt>.
*/
public DelegatingSocket()
{
delegate = null;
}
/**
* Initializes a new <tt>DelegatingSocket</tt>.
*
* @see Socket#Socket(InetAddress, int)
*/
public DelegatingSocket(InetAddress address, int port)
throws IOException
{
delegate = null;
}
/**
* Initializes a new <tt>DelegatingSocket</tt>.
*
* @see Socket#Socket(InetAddress, int, InetAddress, int)
*/
public DelegatingSocket(InetAddress address, int port,
InetAddress localAddr, int localPort)
throws IOException
{
delegate = null;
}
/**
* Initializes a new <tt>DelegatingSocket</tt>.
*
* @see Socket#Socket(Proxy)
*/
public DelegatingSocket(Proxy proxy)
{
delegate = null;
}
/**
* Initializes a new <tt>DelegatingSocket</tt>.
*
* @see Socket#Socket(SocketImpl)
*/
protected DelegatingSocket(SocketImpl impl)
throws SocketException
{
delegate = null;
}
/**
* Initializes a new <tt>DelegatingSocket</tt>.
*
* @see Socket#Socket(String, int)
*/
public DelegatingSocket(String host, int port)
throws UnknownHostException,
IOException
{
delegate = null;
}
/**
* Initializes a new <tt>DelegatingSocket</tt>.
*
* @see Socket#Socket(String, int, InetAddress, int)
*/
public DelegatingSocket(String host, int port, InetAddress localAddr,
int localPort)
{
delegate = null;
}
/**
* Initializes a new <tt>DelegatingSocket</tt>.
*
* @param socket delegating socket
*/
public DelegatingSocket(Socket socket)
{
super();
this.delegate = socket;
}
/**
* {@inheritDoc}
*/
public void bind(SocketAddress bindpoint) throws IOException
{
if (delegate != null)
{
delegate.bind(bindpoint);
}
else
{
super.bind(bindpoint);
}
}
/**
* {@inheritDoc}
*/
public void close() throws IOException
{
if (delegate != null)
{
delegate.close();
}
else
{
super.close();
}
}
/**
* {@inheritDoc}
*/
public void connect(SocketAddress endpoint) throws IOException
{
if (delegate != null)
{
delegate.connect(endpoint);
}
else
{
super.connect(endpoint);
}
}
/**
* {@inheritDoc}
*/
public void connect(SocketAddress endpoint, int timeout) throws IOException
{
if (delegate != null)
{
delegate.connect(endpoint, timeout);
}
else
{
super.connect(endpoint, timeout);
}
}
/**
* {@inheritDoc}
*/
public SocketChannel getChannel()
{
if (delegate != null)
{
return delegate.getChannel();
}
else
{
return super.getChannel();
}
}
/**
* {@inheritDoc}
*/
public InetAddress getInetAddress()
{
if (delegate != null)
{
return delegate.getInetAddress();
}
else
{
return super.getInetAddress();
}
}
/**
* {@inheritDoc}
*/
public InputStream getInputStream() throws IOException
{
if (delegate != null)
{
return delegate.getInputStream();
}
else
{
return super.getInputStream();
}
}
/**
* {@inheritDoc}
*/
public boolean getKeepAlive() throws SocketException
{
if (delegate != null)
{
return delegate.getKeepAlive();
}
else
{
return super.getKeepAlive();
}
}
/**
* {@inheritDoc}
*/
public InetAddress getLocalAddress()
{
if (delegate != null)
{
return delegate.getLocalAddress();
}
else
{
return super.getLocalAddress();
}
}
/**
* {@inheritDoc}
*/
public int getLocalPort()
{
if (delegate != null)
{
return delegate.getLocalPort();
}
else
{
return super.getLocalPort();
}
}
/**
* {@inheritDoc}
*/
public SocketAddress getLocalSocketAddress()
{
if (delegate != null)
{
return delegate.getLocalSocketAddress();
}
else
{
return super.getLocalSocketAddress();
}
}
/**
* {@inheritDoc}
*/
public boolean getOOBInline() throws SocketException
{
if (delegate != null)
{
return delegate.getOOBInline();
}
else
{
return super.getOOBInline();
}
}
/**
* {@inheritDoc}
*/
public OutputStream getOutputStream() throws IOException
{
if (delegate != null)
{
return delegate.getOutputStream();
}
else
{
return super.getOutputStream();
}
}
/**
* {@inheritDoc}
*/
public int getPort()
{
if (delegate != null)
{
return delegate.getPort();
}
else
{
return super.getPort();
}
}
/**
* {@inheritDoc}
*/
public int getReceiveBufferSize() throws SocketException
{
if (delegate != null)
{
return delegate.getReceiveBufferSize();
}
else
{
return super.getReceiveBufferSize();
}
}
/**
* {@inheritDoc}
*/
public SocketAddress getRemoteSocketAddress()
{
if (delegate != null)
{
return delegate.getRemoteSocketAddress();
}
else
{
return super.getRemoteSocketAddress();
}
}
/**
* {@inheritDoc}
*/
public boolean getReuseAddress() throws SocketException
{
if (delegate != null)
{
return delegate.getReuseAddress();
}
else
{
return super.getReuseAddress();
}
}
/**
* {@inheritDoc}
*/
public int getSendBufferSize() throws SocketException
{
if (delegate != null)
{
return delegate.getSendBufferSize();
}
else
{
return super.getSendBufferSize();
}
}
/**
* {@inheritDoc}
*/
public int getSoLinger() throws SocketException
{
if (delegate != null)
{
return delegate.getSoLinger();
}
else
{
return super.getSoLinger();
}
}
/**
* {@inheritDoc}
*/
public int getSoTimeout() throws SocketException
{
if (delegate != null)
{
return delegate.getSoTimeout();
}
else
{
return super.getSoTimeout();
}
}
/**
* {@inheritDoc}
*/
public boolean getTcpNoDelay() throws SocketException
{
if (delegate != null)
{
return delegate.getTcpNoDelay();
}
else
{
return super.getTcpNoDelay();
}
}
/**
* {@inheritDoc}
*/
public int getTrafficClass() throws SocketException
{
if (delegate != null)
{
return delegate.getTrafficClass();
}
else
{
return super.getTrafficClass();
}
}
/**
* {@inheritDoc}
*/
public boolean isBound()
{
if (delegate != null)
{
return delegate.isBound();
}
else
{
return super.isBound();
}
}
/**
* {@inheritDoc}
*/
public boolean isClosed()
{
if (delegate != null)
{
return delegate.isClosed();
}
else
{
return super.isClosed();
}
}
/**
* {@inheritDoc}
*/
public boolean isConnected()
{
if (delegate != null)
{
return delegate.isConnected();
}
else
{
return super.isConnected();
}
}
/**
* {@inheritDoc}
*/
public boolean isInputShutdown()
{
if (delegate != null)
{
return delegate.isInputShutdown();
}
else
{
return super.isInputShutdown();
}
}
/**
* {@inheritDoc}
*/
public boolean isOutputShutdown()
{
if (delegate != null)
{
return delegate.isOutputShutdown();
}
else
{
return super.isOutputShutdown();
}
}
/**
* {@inheritDoc}
*/
public void sendUrgentData(int data) throws IOException
{
if (delegate != null)
{
delegate.sendUrgentData(data);
}
else
{
super.sendUrgentData(data);
}
}
/**
* {@inheritDoc}
*/
public void setKeepAlive(boolean on) throws SocketException
{
if (delegate != null)
{
delegate.setKeepAlive(on);
}
else
{
super.setKeepAlive(on);
}
}
/**
* {@inheritDoc}
*/
public void setOOBInline(boolean on) throws SocketException
{
if (delegate != null)
{
delegate.setOOBInline(on);
}
else
{
super.setOOBInline(on);
}
}
/**
* {@inheritDoc}
*/
public void setPerformancePreferences(int connectionTime, int latency,
int bandwidth)
{
if (delegate != null)
{
delegate.setPerformancePreferences(connectionTime, bandwidth,
bandwidth);
}
else
{
super.setPerformancePreferences(connectionTime, latency, bandwidth);
}
}
/**
* {@inheritDoc}
*/
public void setReceiveBufferSize(int size) throws SocketException
{
if (delegate != null)
{
delegate.setReceiveBufferSize(size);
}
else
{
super.setReceiveBufferSize(size);
}
}
/**
* {@inheritDoc}
*/
public void setReuseAddress(boolean on) throws SocketException
{
if (delegate != null)
{
delegate.setReuseAddress(on);
}
else
{
super.setReuseAddress(on);
}
}
/**
* {@inheritDoc}
*/
public void setSendBufferSize(int size) throws SocketException
{
if (delegate != null)
{
delegate.setSendBufferSize(size);
}
else
{
super.setSendBufferSize(size);
}
}
/**
* {@inheritDoc}
*/
public void setSoLinger(boolean on, int linger) throws SocketException
{
if (delegate != null)
{
delegate.setSoLinger(on, linger);
}
else
{
super.setSoLinger(on, linger);
}
}
/**
* {@inheritDoc}
*/
public void setSoTimeout(int timeout) throws SocketException
{
if (delegate != null)
{
delegate.setSoTimeout(timeout);
}
else
{
super.setSoTimeout(timeout);
}
}
/**
* {@inheritDoc}
*/
public void setTcpNoDelay(boolean on) throws SocketException
{
if (delegate != null)
{
delegate.setTcpNoDelay(on);
}
else
{
super.setTcpNoDelay(on);
}
}
/**
* {@inheritDoc}
*/
public void setTrafficClass(int tc) throws SocketException
{
if (delegate != null)
{
delegate.setTrafficClass(tc);
}
else
{
super.setTrafficClass(tc);
}
}
/**
* {@inheritDoc}
*/
public void shutdownInput() throws IOException
{
if (delegate != null)
{
delegate.shutdownInput();
}
else
{
super.shutdownInput();
}
}
/**
* {@inheritDoc}
*/
public void shutdownOutput() throws IOException
{
if (delegate != null)
{
delegate.shutdownOutput();
}
else
{
super.shutdownOutput();
}
}
/**
* {@inheritDoc}
*/
public String toString()
{
if (delegate != null)
{
return delegate.toString();
}
else
{
return super.toString();
}
}
/**
* Send a datagram packet from this socket.
*
* @param p <tt>DatagramPacket</tt> to sent
* @throws IOException if something goes wrong during send
*/
public void send(DatagramPacket p) throws IOException
{
if (delegate != null && delegate instanceof DelegatingSocket)
{
((DelegatingSocket) delegate).send(p);
return;
}
if (outputStream == null)
{
outputStream = getOutputStream();
}
int len = p.getLength();
int off = p.getOffset();
byte data[] = new byte[len + 2];
data[0] = (byte) ((len >> 8) & 0xff);
data[1] = (byte) (len & 0xff);
System.arraycopy(p.getData(), off, data, 2, len);
outputStream.write(data, 0, len + 2);
data = null;
}
/**
* Receives a datagram packet from this socket. The <tt>DatagramPacket</tt>s
* returned by this method do not match any of the
* <tt>DatagramPacketFilter</tt>s of the <tt>MultiplexedSocket</tt>s
* associated with this instance at the time of their receipt. When this
* method returns, the <tt>DatagramPacket</tt>'s buffer is filled with the
* data received. The datagram packet also contains the sender's IP address,
* and the port number on the sender's machine.
* <p>
* This method blocks until a datagram is received. The <tt>length</tt>
* field of the datagram packet object contains the length of the received
* message. If the message is longer than the packet's length, the message
* is truncated.
* </p>
*
* @param p the <tt>DatagramPacket</tt> into which to place the incoming
* data
* @throws IOException if an I/O error occurs
* @see #receive(DatagramPacket)
*/
public void receive(DatagramPacket p) throws IOException
{
if (delegate != null && delegate instanceof DelegatingSocket)
{
((DelegatingSocket) delegate).receive(p);
return;
}
byte data[] = p.getData();
int len = 0;
if (inputStream == null)
{
inputStream = this.getInputStream();
}
inputStream.skip(2);
len = inputStream.read(data);
if (len > 0)
{
p.setData(data);
p.setLength(len);
p.setAddress(this.getInetAddress());
p.setPort(this.getPort());
}
else
{
throw new SocketException("Failed to receive data from socket");
}
}
/**
* Set original <tt>InputStream</tt>.
*
* @param inputStream <tt>InputStream</tt>
*/
public void setOriginalInputStream(InputStream inputStream)
{
if(this.inputStream == null && inputStream != null)
this.inputStream = inputStream;
}
}

View File

@ -9,15 +9,12 @@ package org.ice4j.socket;
import java.io.*; import java.io.*;
import java.net.*; import java.net.*;
import java.util.*;
import java.util.logging.*; import java.util.logging.*;
import org.ice4j.*; import org.ice4j.*;
import org.ice4j.attribute.*;
import org.ice4j.ice.*; import org.ice4j.ice.*;
import org.ice4j.ice.harvest.*; import org.ice4j.ice.harvest.*;
import org.ice4j.message.*; import org.ice4j.message.*;
import org.ice4j.stack.*;
/** /**
* Represents an application-purposed (as opposed to an ICE-specific) * Represents an application-purposed (as opposed to an ICE-specific)
@ -33,8 +30,6 @@ import org.ice4j.stack.*;
*/ */
public class GoogleRelayedCandidateDatagramSocket public class GoogleRelayedCandidateDatagramSocket
extends DatagramSocket extends DatagramSocket
implements MessageEventHandler,
ResponseCollector
{ {
/** /**
* The <tt>Logger</tt> used by the * The <tt>Logger</tt> used by the
@ -51,36 +46,12 @@ public class GoogleRelayedCandidateDatagramSocket
*/ */
private boolean closed = false; private boolean closed = false;
/**
* The <tt>DatagramPacket</tt>s which are to be received through this
* <tt>DatagramSocket</tt> upon calls to its
* {@link #receive(DatagramPacket)} method. They have been received from the
* TURN server in the form of Data indications.
*/
private final List<DatagramPacket> packetsToReceive
= new LinkedList<DatagramPacket>();
/**
* The <tt>DatagramSocket</tt>s which have been sent through this
* <tt>DatagramSocket</tt> using its {@link #send(DatagramPacket)} method
* and which are to be relayed through its associated TURN server in the
* form of Send indications.
*/
private final List<DatagramPacket> packetsToSend
= new LinkedList<DatagramPacket>();
/** /**
* The <tt>GoogleRelayedCandidate</tt> which uses this instance as the value * The <tt>GoogleRelayedCandidate</tt> which uses this instance as the value
* of its <tt>socket</tt> property. * of its <tt>socket</tt> property.
*/ */
private final GoogleRelayedCandidate relayedCandidate; private final GoogleRelayedCandidate relayedCandidate;
/**
* The <tt>Thread</tt> which is to send the {@link #packetsToSend} to the
* associated TURN server.
*/
private Thread sendThread;
/** /**
* The <tt>GoogleTurnCandidateHarvest</tt> which has harvested * The <tt>GoogleTurnCandidateHarvest</tt> which has harvested
* {@link #relayedCandidate}. * {@link #relayedCandidate}.
@ -88,9 +59,10 @@ public class GoogleRelayedCandidateDatagramSocket
private final GoogleTurnCandidateHarvest turnCandidateHarvest; private final GoogleTurnCandidateHarvest turnCandidateHarvest;
/** /**
* Username. * The <tt>GoogleTurnCandidateDelegage</tt> which will handle send/receive
* operations.
*/ */
private final String username; private final GoogleRelayedCandidateDelegate socketDelegate;
/** /**
* Initializes a new <tt>GoogleRelayedCandidateDatagramSocket</tt> instance * Initializes a new <tt>GoogleRelayedCandidateDatagramSocket</tt> instance
@ -114,17 +86,12 @@ public class GoogleRelayedCandidateDatagramSocket
{ {
super(/* bindaddr */ (SocketAddress) null); super(/* bindaddr */ (SocketAddress) null);
socketDelegate = new GoogleRelayedCandidateDelegate(
turnCandidateHarvest, username);
this.relayedCandidate = relayedCandidate; this.relayedCandidate = relayedCandidate;
this.turnCandidateHarvest = turnCandidateHarvest; this.turnCandidateHarvest = turnCandidateHarvest;
this.username = username;
this.turnCandidateHarvest logger.finest("Create new GoogleRelayedCandidateDatagramSocket");
.harvester
.getStunStack()
.addOldIndicationListener(
this.turnCandidateHarvest.hostCandidate
.getTransportAddress(),
this);
} }
/** /**
@ -142,17 +109,8 @@ public class GoogleRelayedCandidateDatagramSocket
else else
this.closed = true; this.closed = true;
} }
synchronized (packetsToReceive)
{ socketDelegate.close();
packetsToReceive.notifyAll();
}
synchronized (packetsToSend)
{
packetsToSend.notifyAll();
}
turnCandidateHarvest.harvester.getStunStack().removeIndicationListener(
turnCandidateHarvest.hostCandidate.getTransportAddress(),
this);
turnCandidateHarvest.close(this); turnCandidateHarvest.close(this);
} }
@ -224,107 +182,6 @@ public class GoogleRelayedCandidateDatagramSocket
return relayedCandidate; return relayedCandidate;
} }
/**
* Notifies this <tt>MessageEventHandler</tt> that a specific STUN message
* has been received, parsed and is ready for delivery.
* <tt>GoogleRelayedCandidateDatagramSocket</tt> handles STUN indications sent
* from the associated TURN server and received at the associated local
* <tt>TransportAddress</tt>.
*
* @param e a <tt>StunMessageEvent</tt> which encapsulates the received STUN
* message
*/
public void handleMessageEvent(StunMessageEvent e)
{
Message message = e.getMessage();
char messageType = message.getMessageType();
if (messageType != Message.OLD_DATA_INDICATION)
return;
if (!turnCandidateHarvest.hostCandidate.getTransportAddress().equals(
e.getLocalAddress()))
return;
// Is it from our TURN server?
if (!turnCandidateHarvest.harvester.stunServer.equals(
e.getRemoteAddress()))
return;
logger.finest("handle old DATA Indication");
/* as REMOTE-ADDRESS and XOR-PEER-ADDRESS has the same attribute type
* we cast it to XorPeerAddressAttribute but we do not apply XOR to get
* the address
*/
XorPeerAddressAttribute peerAddressAttribute
= (XorPeerAddressAttribute)
message.getAttribute(Attribute.REMOTE_ADDRESS);
if (peerAddressAttribute == null)
{
logger.info("peerAddressAttribute is null");
return;
}
DataAttribute dataAttribute
= (DataAttribute) message.getAttribute(Attribute.DATA);
if (dataAttribute == null)
{
logger.info("data is null");
return;
}
TransportAddress peerAddress
= peerAddressAttribute.getAddress();
if (peerAddress == null)
return;
byte[] data = dataAttribute.getData();
if (data == null)
return;
DatagramPacket packetToReceive;
try
{
packetToReceive
= new DatagramPacket(data, 0, data.length, peerAddress);
}
catch (SocketException sex)
{
packetToReceive = null;
}
if (packetToReceive != null)
{
synchronized (packetsToReceive)
{
packetsToReceive.add(packetToReceive);
packetsToReceive.notifyAll();
}
}
}
/**
* Notifies this <tt>GoogleRelayedCandidateDatagramSocket</tt> that a
* specific <tt>Request</tt> it has sent has either failed or received a
* STUN error <tt>Response</tt>.
*
* @param response the <tt>Response</tt> which responds to <tt>request</tt>
* @param request the <tt>Request</tt> sent by this instance to which
* <tt>response</tt> responds
* @return <tt>true</tt> if the failure or error condition has been handled
* and the caller should assume this instance has recovered from it;
* otherwise, <tt>false</tt>
*/
public boolean processErrorOrFailure(Response response, Request request)
{
return false;
}
/** /**
* Notifies this <tt>GoogleRelayedCandidateDatagramSocket</tt> that a * Notifies this <tt>GoogleRelayedCandidateDatagramSocket</tt> that a
* specific <tt>Request</tt> it has sent has received a STUN success * specific <tt>Request</tt> it has sent has received a STUN success
@ -336,6 +193,7 @@ public class GoogleRelayedCandidateDatagramSocket
*/ */
public void processSuccess(Response response, Request request) public void processSuccess(Response response, Request request)
{ {
socketDelegate.processSuccess(response, request);
} }
/** /**
@ -345,19 +203,7 @@ public class GoogleRelayedCandidateDatagramSocket
*/ */
public void processResponse(StunResponseEvent response) public void processResponse(StunResponseEvent response)
{ {
socketDelegate.processResponse(response);
}
/**
* Notifies this collector that no response had been received after repeated
* retransmissions of the original request (as described by rfc3489) and
* that the request should be considered unanswered.
*
* @param event the <tt>StunTimeoutEvent</tt> containing a reference to the
* transaction that has just failed.
*/
public void processTimeout(StunTimeoutEvent event)
{
} }
/** /**
@ -375,44 +221,7 @@ public class GoogleRelayedCandidateDatagramSocket
public void receive(DatagramPacket p) public void receive(DatagramPacket p)
throws IOException throws IOException
{ {
synchronized (packetsToReceive) socketDelegate.receive(p);
{
while (true)
{
/*
* According to the javadoc of DatagramSocket#close(), any
* thread currently blocked in #receive(DatagramPacket) upon
* this socket will throw a SocketException.
*/
if (closed)
{
throw
new SocketException(
GoogleRelayedCandidateDatagramSocket.class
.getSimpleName()
+ " has been closed.");
}
else if (packetsToReceive.isEmpty())
{
try
{
packetsToReceive.wait();
}
catch (InterruptedException iex)
{
}
continue;
}
else
{
DatagramPacket packetToReceive = packetsToReceive.remove(0);
MultiplexingDatagramSocket.copy(packetToReceive, p);
packetsToReceive.notifyAll();
break;
}
}
}
} }
/** /**
@ -428,150 +237,6 @@ public class GoogleRelayedCandidateDatagramSocket
public void send(DatagramPacket p) public void send(DatagramPacket p)
throws IOException throws IOException
{ {
synchronized (packetsToSend) socketDelegate.send(p);
{
if (closed)
{
throw
new IOException(
GoogleRelayedCandidateDatagramSocket.class.
getSimpleName() + " has been closed.");
}
else
{
packetsToSend.add(MultiplexingDatagramSocket.clone(p));
if (sendThread == null)
createSendThread();
else
packetsToSend.notifyAll();
}
}
}
/**
* Creates {@link #sendThread} which is to send {@link #packetsToSend} to
* the associated TURN server.
*/
private void createSendThread()
{
sendThread
= new Thread()
{
@Override
public void run()
{
try
{
runInSendThread();
}
finally
{
/*
* If sendThread is dying and there are packetsToSend,
* then spawn a new sendThread.
*/
synchronized (packetsToSend)
{
if (sendThread == Thread.currentThread())
sendThread = null;
if ((sendThread == null)
&& !closed
&& !packetsToSend.isEmpty())
createSendThread();
}
}
}
};
sendThread.start();
}
/**
* Runs in {@link #sendThread} to send {@link #packetsToSend} to the
* associated TURN server.
*/
private void runInSendThread()
{
synchronized (packetsToSend)
{
while (!closed)
{
if (packetsToSend.isEmpty())
{
try
{
packetsToSend.wait();
}
catch (InterruptedException iex)
{
}
continue;
}
int packetToSendCount = packetsToSend.size();
for (int packetToSendIndex = 0;
packetToSendIndex < packetToSendCount;
packetToSendIndex++)
{
DatagramPacket packetToSend = packetsToSend.remove(0);
TransportAddress peerAddress
= new TransportAddress(
packetToSend.getAddress(),
packetToSend.getPort(),
Transport.UDP);
byte[] pData = packetToSend.getData();
int pOffset = packetToSend.getOffset();
int pLength = packetToSend.getLength();
byte[] data;
if ((pOffset == 0) && (pLength == pData.length))
data = pData;
else
{
data = new byte[pLength];
System.arraycopy(pData, pOffset, data, 0, pLength);
}
byte[] transactionID
= TransactionID.createNewTransactionID().getBytes();
Request sendRequest
= MessageFactory.createSendRequest(username,
peerAddress,
data);
try
{
sendRequest.setTransactionID(transactionID);
turnCandidateHarvest.harvester.getStunStack().
sendRequest(sendRequest,
turnCandidateHarvest.harvester.stunServer,
turnCandidateHarvest.hostCandidate.
getTransportAddress(),
this);
}
catch(Exception e)
{
logger.fine("Failed to send TURN Send request: " + e);
}
}
/*
* If no packetToSend has been sent by the current iteration,
* then we must be waiting for some condition to change in order
* to be able to send.
*/
if (packetsToSend.size() == packetToSendCount)
{
try
{
packetsToSend.wait();
}
catch (InterruptedException iex)
{
}
}
}
}
} }
} }

View File

@ -0,0 +1,466 @@
/*
* ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
* Maintained by the SIP Communicator community (http://sip-communicator.org).
*
* Distributable under LGPL license. See terms of license at gnu.org.
*/
package org.ice4j.socket;
import java.io.*;
import java.net.*;
import java.util.*;
import java.util.logging.*;
import org.ice4j.*;
import org.ice4j.attribute.*;
import org.ice4j.ice.harvest.*;
import org.ice4j.message.*;
import org.ice4j.stack.*;
/**
* Google TURN delegate object that will handle GTalk TURN send/receive
* operations.
*
* @author Sebastien Vincent
*/
public class GoogleRelayedCandidateDelegate
implements MessageEventHandler,
ResponseCollector
{
/**
* The <tt>Logger</tt> used by the
* <tt>GoogleRelayedCandidateDatagramSocket</tt> class and its instances for
* logging output.
*/
private static final Logger logger = Logger
.getLogger(GoogleRelayedCandidateDelegate.class.getName());
/**
* The indicator which determines whether this instance has started
* executing or has executed its {@link #close()} method.
*/
private boolean closed = false;
/**
* The <tt>DatagramPacket</tt>s which are to be received through this
* <tt>DatagramSocket</tt> upon calls to its
* {@link #receive(DatagramPacket)} method. They have been received from the
* TURN server in the form of Data indications.
*/
private final List<DatagramPacket> packetsToReceive =
new LinkedList<DatagramPacket>();
/**
* The <tt>DatagramSocket</tt>s which have been sent through this
* <tt>DatagramSocket</tt> using its {@link #send(DatagramPacket)} method
* and which are to be relayed through its associated TURN server in the
* form of Send indications.
*/
private final List<DatagramPacket> packetsToSend =
new LinkedList<DatagramPacket>();
/**
* The <tt>Thread</tt> which is to send the {@link #packetsToSend} to the
* associated TURN server.
*/
private Thread sendThread;
/**
* The <tt>GoogleTurnCandidateHarvest</tt> which has harvested
* {@link #relayedCandidate}.
*/
private final GoogleTurnCandidateHarvest turnCandidateHarvest;
/**
* Username.
*/
private final String username;
/**
* Initializes a new <tt>GoogleRelayedCandidateDatagramSocket</tt> instance
* which is to be the <tt>socket</tt> of a specific
* <tt>RelayedCandidate</tt> harvested by a specific
* <tt>TurnCandidateHarvest</tt>.
*
* @param turnCandidateHarvest the <tt>TurnCandidateHarvest</tt> which has
* harvested <tt>relayedCandidate</tt>
* @param username username
* @throws SocketException if anything goes wrong while initializing the new
* <tt>GoogleRelayedCandidateDatagramSocket</tt> instance
*/
public GoogleRelayedCandidateDelegate(
GoogleTurnCandidateHarvest turnCandidateHarvest, String username)
throws SocketException
{
this.turnCandidateHarvest = turnCandidateHarvest;
this.username = username;
this.turnCandidateHarvest.harvester.getStunStack()
.addOldIndicationListener(
this.turnCandidateHarvest.hostCandidate.getTransportAddress(),
this);
}
/**
* Closes this datagram socket.
*
* @see DatagramSocket#close()
*/
public void close()
{
synchronized (this)
{
if (this.closed)
return;
else
this.closed = true;
}
synchronized (packetsToReceive)
{
packetsToReceive.notifyAll();
}
synchronized (packetsToSend)
{
packetsToSend.notifyAll();
}
turnCandidateHarvest.harvester.getStunStack().removeIndicationListener(
turnCandidateHarvest.hostCandidate.getTransportAddress(), this);
}
/**
* Notifies this <tt>MessageEventHandler</tt> that a specific STUN message
* has been received, parsed and is ready for delivery.
* <tt>GoogleRelayedCandidateDatagramSocket</tt> handles STUN indications
* sent from the associated TURN server and received at the associated local
* <tt>TransportAddress</tt>.
*
* @param e a <tt>StunMessageEvent</tt> which encapsulates the received STUN
* message
*/
public void handleMessageEvent(StunMessageEvent e)
{
Message message = e.getMessage();
char messageType = message.getMessageType();
if (messageType != Message.OLD_DATA_INDICATION)
return;
if (!turnCandidateHarvest.hostCandidate.getTransportAddress().equals(
e.getLocalAddress()))
return;
// Is it from our TURN server?
if (!turnCandidateHarvest.harvester.stunServer.equals(e
.getRemoteAddress()))
return;
logger.finest("handle old DATA Indication");
/*
* as REMOTE-ADDRESS and XOR-PEER-ADDRESS has the same attribute type we
* cast it to XorPeerAddressAttribute but we do not apply XOR to get the
* address
*/
XorPeerAddressAttribute peerAddressAttribute =
(XorPeerAddressAttribute) message
.getAttribute(Attribute.REMOTE_ADDRESS);
if (peerAddressAttribute == null)
{
logger.info("peerAddressAttribute is null");
return;
}
DataAttribute dataAttribute =
(DataAttribute) message.getAttribute(Attribute.DATA);
if (dataAttribute == null)
{
logger.info("data is null");
return;
}
TransportAddress peerAddress = peerAddressAttribute.getAddress();
if (peerAddress == null)
return;
byte[] data = dataAttribute.getData();
if (data == null)
return;
DatagramPacket packetToReceive;
try
{
packetToReceive =
new DatagramPacket(data, 0, data.length, peerAddress);
}
catch (SocketException sex)
{
packetToReceive = null;
}
if (packetToReceive != null)
{
synchronized (packetsToReceive)
{
packetsToReceive.add(packetToReceive);
packetsToReceive.notifyAll();
}
}
}
/**
* Notifies this <tt>GoogleRelayedCandidateDatagramSocket</tt> that a
* specific <tt>Request</tt> it has sent has either failed or received a
* STUN error <tt>Response</tt>.
*
* @param response the <tt>Response</tt> which responds to <tt>request</tt>
* @param request the <tt>Request</tt> sent by this instance to which
* <tt>response</tt> responds
* @return <tt>true</tt> if the failure or error condition has been handled
* and the caller should assume this instance has recovered from it;
* otherwise, <tt>false</tt>
*/
public boolean processErrorOrFailure(Response response, Request request)
{
return false;
}
/**
* Notifies this <tt>GoogleRelayedCandidateDatagramSocket</tt> that a
* specific <tt>Request</tt> it has sent has received a STUN success
* <tt>Response</tt>.
*
* @param response the <tt>Response</tt> which responds to <tt>request</tt>
* @param request the <tt>Request</tt> sent by this instance to which
* <tt>response</tt> responds
*/
public void processSuccess(Response response, Request request)
{
}
/**
* Dispatch the specified response.
*
* @param response the response to dispatch.
*/
public void processResponse(StunResponseEvent response)
{
}
/**
* Notifies this collector that no response had been received after repeated
* retransmissions of the original request (as described by rfc3489) and
* that the request should be considered unanswered.
*
* @param event the <tt>StunTimeoutEvent</tt> containing a reference to the
* transaction that has just failed.
*/
public void processTimeout(StunTimeoutEvent event)
{
}
/**
* Receives a datagram packet from this socket. When this method returns,
* the <tt>DatagramPacket</tt>'s buffer is filled with the data received.
* The datagram packet also contains the sender's IP address, and the port
* number on the sender's machine.
*
* @param p the <tt>DatagramPacket</tt> into which to place the incoming
* data
* @throws IOException if an I/O error occurs
* @see DatagramSocket#receive(DatagramPacket)
*/
public void receive(DatagramPacket p) throws IOException
{
synchronized (packetsToReceive)
{
while (true)
{
/*
* According to the javadoc of DatagramSocket#close(), any
* thread currently blocked in #receive(DatagramPacket) upon
* this socket will throw a SocketException.
*/
if (closed)
{
throw new SocketException(
GoogleRelayedCandidateDatagramSocket.class
.getSimpleName() + " has been closed.");
}
else if (packetsToReceive.isEmpty())
{
try
{
packetsToReceive.wait();
}
catch (InterruptedException iex)
{
}
continue;
}
else
{
DatagramPacket packetToReceive = packetsToReceive.remove(0);
MultiplexingDatagramSocket.copy(packetToReceive, p);
packetsToReceive.notifyAll();
break;
}
}
}
}
/**
* Sends a datagram packet from this socket. The <tt>DatagramPacket</tt>
* includes information indicating the data to be sent, its length, the IP
* address of the remote host, and the port number on the remote host.
*
* @param p the <tt>DatagramPacket</tt> to be sent
* @throws IOException if an I/O error occurs
* @see DatagramSocket#send(DatagramPacket)
*/
public void send(DatagramPacket p) throws IOException
{
synchronized (packetsToSend)
{
if (closed)
{
throw new IOException(
GoogleRelayedCandidateDatagramSocket.class.getSimpleName()
+ " has been closed.");
}
else
{
packetsToSend.add(MultiplexingDatagramSocket.clone(p));
if (sendThread == null)
createSendThread();
else
packetsToSend.notifyAll();
}
}
}
/**
* Creates {@link #sendThread} which is to send {@link #packetsToSend} to
* the associated TURN server.
*/
private void createSendThread()
{
sendThread = new Thread()
{
@Override
public void run()
{
try
{
runInSendThread();
}
finally
{
/*
* If sendThread is dying and there are packetsToSend, then
* spawn a new sendThread.
*/
synchronized (packetsToSend)
{
if (sendThread == Thread.currentThread())
sendThread = null;
if ((sendThread == null) && !closed
&& !packetsToSend.isEmpty())
createSendThread();
}
}
}
};
sendThread.start();
}
/**
* Runs in {@link #sendThread} to send {@link #packetsToSend} to the
* associated TURN server.
*/
private void runInSendThread()
{
synchronized (packetsToSend)
{
while (!closed)
{
if (packetsToSend.isEmpty())
{
try
{
packetsToSend.wait();
}
catch (InterruptedException iex)
{
}
continue;
}
int packetToSendCount = packetsToSend.size();
for (int packetToSendIndex = 0; packetToSendIndex < packetToSendCount; packetToSendIndex++)
{
DatagramPacket packetToSend = packetsToSend.remove(0);
TransportAddress peerAddress =
new TransportAddress(packetToSend.getAddress(),
packetToSend.getPort(), Transport.UDP);
byte[] pData = packetToSend.getData();
int pOffset = packetToSend.getOffset();
int pLength = packetToSend.getLength();
byte[] data;
if ((pOffset == 0) && (pLength == pData.length))
data = pData;
else
{
data = new byte[pLength];
System.arraycopy(pData, pOffset, data, 0, pLength);
}
byte[] transactionID =
TransactionID.createNewTransactionID().getBytes();
Request sendRequest =
MessageFactory.createSendRequest(username, peerAddress,
data);
try
{
sendRequest.setTransactionID(transactionID);
turnCandidateHarvest.harvester.getStunStack()
.sendRequest(
sendRequest,
turnCandidateHarvest.harvester.stunServer,
turnCandidateHarvest.hostCandidate
.getTransportAddress(), this);
}
catch (Exception e)
{
logger.fine("Failed to send TURN Send request: " + e);
}
}
/*
* If no packetToSend has been sent by the current iteration,
* then we must be waiting for some condition to change in order
* to be able to send.
*/
if (packetsToSend.size() == packetToSendCount)
{
try
{
packetsToSend.wait();
}
catch (InterruptedException iex)
{
}
}
}
}
}
}

View File

@ -0,0 +1,338 @@
/*
* ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
* Maintained by the SIP Communicator community (http://sip-communicator.org).
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package org.ice4j.socket;
import java.io.*;
import java.net.*;
import java.util.logging.*;
import org.ice4j.*;
import org.ice4j.ice.*;
import org.ice4j.ice.harvest.*;
import org.ice4j.message.*;
/**
* Represents an application-purposed (as opposed to an ICE-specific)
* <tt>Socket</tt> for a <tt>RelayedCandidate</tt> harvested by a
* <tt>TurnCandidateHarvest</tt> (and its associated
* <tt>TurnCandidateHarvester</tt>, of course).
* <tt>GoogleRelayedCandidateSocket</tt> is associated with a successful
* Allocation on a TURN server and implements sends and receives through it
* using TURN messages to and from that TURN server.
*
* @author Lyubomir Marinov
* @author Sebastien Vincent
*/
public class GoogleRelayedCandidateSocket
extends DelegatingSocket
{
/**
* The <tt>Logger</tt> used by the
* <tt>GoogleRelayedCandidateSocket</tt> class and its instances for
* logging output.
*/
private static final Logger logger
= Logger.getLogger(
GoogleRelayedCandidateSocket.class.getName());
/**
* The indicator which determines whether this instance has started
* executing or has executed its {@link #close()} method.
*/
private boolean closed = false;
/**
* The <tt>GoogleRelayedCandidate</tt> which uses this instance as the value
* of its <tt>socket</tt> property.
*/
private final GoogleRelayedCandidate relayedCandidate;
/**
* The <tt>GoogleTurnCandidateDelegage</tt> which will handle send/receive
* operations.
*/
private final GoogleRelayedCandidateDelegate socketDelegate;
/**
* The <tt>OutputStream</tt>.
*/
private TCPOutputStream outputStream = null;
/**
* Initializes a new <tt>GoogleRelayedCandidateSocket</tt> instance
* which is to be the <tt>socket</tt> of a specific
* <tt>RelayedCandidate</tt> harvested by a specific
* <tt>TurnCandidateHarvest</tt>.
*
* @param relayedCandidate the <tt>RelayedCandidate</tt> which is to use the
* new instance as the value of its <tt>socket</tt> property
* @param turnCandidateHarvest the <tt>TurnCandidateHarvest</tt> which has
* harvested <tt>relayedCandidate</tt>
* @param username username
* @throws SocketException if anything goes wrong while initializing the new
* <tt>GoogleRelayedCandidateSocket</tt> instance
*/
public GoogleRelayedCandidateSocket(
GoogleRelayedCandidate relayedCandidate,
GoogleTurnCandidateHarvest turnCandidateHarvest,
String username)
throws SocketException
{
super();
this.relayedCandidate = relayedCandidate;
socketDelegate = new GoogleRelayedCandidateDelegate(
turnCandidateHarvest, username);
logger.finest("Create new GoogleRelayedCandidateSocket");
}
/**
* Closes this datagram socket.
*
* @see Socket#close()
*/
@Override
public void close()
{
synchronized (this)
{
if (this.closed)
return;
else
this.closed = true;
}
socketDelegate.close();
}
/**
* Gets the local address to which the socket is bound.
* <tt>GoogleRelayedCandidateSocket</tt> returns the
* <tt>address</tt> of its <tt>localSocketAddress</tt>.
* <p>
* If there is a security manager, its <tt>checkConnect</tt> method is first
* called with the host address and <tt>-1</tt> as its arguments to see if
* the operation is allowed.
* </p>
*
* @return the local address to which the socket is bound, or an
* <tt>InetAddress</tt> representing any local address if either the socket
* is not bound, or the security manager <tt>checkConnect</tt> method does
* not allow the operation
* @see #getLocalSocketAddress()
* @see Socket#getLocalAddress()
*/
@Override
public InetAddress getLocalAddress()
{
return getLocalSocketAddress().getAddress();
}
/**
* Returns the port number on the local host to which this socket is bound.
* <tt>GoogleRelayedCandidateSocket</tt> returns the <tt>port</tt>
* of its <tt>localSocketAddress</tt>.
*
* @return the port number on the local host to which this socket is bound
* @see #getLocalSocketAddress()
* @see Socket#getLocalPort()
*/
@Override
public int getLocalPort()
{
return getLocalSocketAddress().getPort();
}
/**
* Returns the address of the endpoint this socket is bound to, or
* <tt>null</tt> if it is not bound yet. Since
* <tt>GoogleRelayedCandidateSocket</tt> represents an
* application-purposed <tt>Socket</tt> relaying data to and from a
* TURN server, the <tt>localSocketAddress</tt> is the
* <tt>transportAddress</tt> of the respective <tt>RelayedCandidate</tt>.
*
* @return a <tt>SocketAddress</tt> representing the local endpoint of this
* socket, or <tt>null</tt> if it is not bound yet
* @see Socket#getLocalSocketAddress()
*/
@Override
public InetSocketAddress getLocalSocketAddress()
{
return getRelayedCandidate().getTransportAddress();
}
/**
* Gets the <tt>RelayedCandidate</tt> which uses this instance as the value
* of its <tt>socket</tt> property.
*
* @return the <tt>RelayedCandidate</tt> which uses this instance as the
* value of its <tt>socket</tt> property
*/
public final GoogleRelayedCandidate getRelayedCandidate()
{
return relayedCandidate;
}
/**
* Notifies this <tt>GoogleRelayedCandidateSocket</tt> that a
* specific <tt>Request</tt> it has sent has received a STUN success
* <tt>Response</tt>.
*
* @param response the <tt>Response</tt> which responds to <tt>request</tt>
* @param request the <tt>Request</tt> sent by this instance to which
* <tt>response</tt> responds
*/
public void processSuccess(Response response, Request request)
{
socketDelegate.processSuccess(response, request);
}
/**
* Dispatch the specified response.
*
* @param response the response to dispatch.
*/
public void processResponse(StunResponseEvent response)
{
socketDelegate.processResponse(response);
}
/**
* Receives a datagram packet from this socket. When this method returns,
* the <tt>DatagramPacket</tt>'s buffer is filled with the data received.
* The datagram packet also contains the sender's IP address, and the port
* number on the sender's machine.
*
* @param p the <tt>DatagramPacket</tt> into which to place the incoming
* data
* @throws IOException if an I/O error occurs
*/
@Override
public void receive(DatagramPacket p)
throws IOException
{
socketDelegate.receive(p);
}
/**
* Sends a datagram packet from this socket. The <tt>DatagramPacket</tt>
* includes information indicating the data to be sent, its length, the IP
* address of the remote host, and the port number on the remote host.
*
* @param p the <tt>DatagramPacket</tt> to be sent
* @throws IOException if an I/O error occurs
*/
public void send(DatagramPacket p)
throws IOException
{
socketDelegate.send(p);
}
/**
* {@inheritDoc}
*/
@Override
public OutputStream getOutputStream()
throws IOException
{
if(outputStream == null)
{
CandidatePair pair =
relayedCandidate.getParentComponent().getSelectedPair();
if(pair.getLocalCandidate() == relayedCandidate)
{
TransportAddress target = pair.getRemoteCandidate().
getTransportAddress();
outputStream = new TCPOutputStream(target);
}
else
throw new IOException("TURN-TCP socket is not selected");
}
return outputStream;
}
/**
* TCP output stream for TCP socket. It is used to multiplex sockets and keep
* the <tt>OutputStream</tt> interface to users.
*
* @author Sebastien Vincent
*/
private class TCPOutputStream
extends OutputStream
{
/**
* Target transport address.
*/
private final TransportAddress target;
/**
* Initializes a new <tt>TCPOutputStream</tt>.
*
* @param target <tt>TransportAddress</tt>
*/
public TCPOutputStream(TransportAddress target)
{
this.target = target;
}
/**
* {@inheritDoc}
*/
@Override
public void close()
throws IOException
{
}
/**
* {@inheritDoc}
*/
@Override
public void flush()
throws IOException
{
}
/**
* {@inheritDoc}
*/
@Override
public void write(byte[] b)
throws IOException
{
write(b, 0, b.length);
}
/**
* {@inheritDoc}
*/
@Override
public void write(byte[] b, int off, int len)
throws IOException
{
DatagramPacket p = new DatagramPacket(
b,
off + 2,
len - 2,
target);
send(p);
}
/**
* {@inheritDoc}
*/
@Override
public void write(int arg0) throws IOException
{
// TODO Auto-generated method stub
}
}
}

View File

@ -0,0 +1,87 @@
/*
* ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
* Maintained by the SIP Communicator community (http://sip-communicator.org).
*
* Distributable under LGPL license. See terms of license at gnu.org.
*/
package org.ice4j.socket;
import java.io.*;
import java.net.*;
/**
* Abstract socket wrapper that define a socket that could be UDP, TCP...
*
* @author Sebastien Vincent
*/
public abstract class IceSocketWrapper
{
/**
* Sends a <tt>DatagramPacket</tt> from this socket
* It is a utility method to provide a common way to send for both
* UDP and TCP socket. If the underlying socket is a TCP ones, it is still
* possible to get the <tt>OutputStream</tt> and do stuff with it.
*
*
* @param p <tt>DatagramPacket</tt> to sent
* @throws IOException if something goes wrong
*/
public abstract void send(DatagramPacket p)
throws IOException;
/**
* Receives a <tt>DatagramPacket</tt> from this socket.
* It is a utility method to provide a common way to receive for both
* UDP and TCP socket. If the underlying socket is a TCP ones, it is still
* possible to get the <tt>InputStream</tt> and do stuff with it.
*
* @param p <tt>DatagramPacket</tt>
* @throws IOException if something goes wrong
*/
public abstract void receive(DatagramPacket p)
throws IOException;
/**
* Closes this socket.
*/
public abstract void close();
/**
* Get local address.
*
* @return local address
*/
public abstract InetAddress getLocalAddress();
/**
* Get local port.
*
* @return local port
*/
public abstract int getLocalPort();
/**
* Get socket address.
*
* @return socket address
*/
public abstract SocketAddress getLocalSocketAddress();
/**
* Returns Socket object if the delegate socket is a TCP ones, null
* otherwise.
*
* @return Socket object if the delegate socket is a TCP ones, null
* otherwise
*/
public abstract Socket getTCPSocket();
/**
* Returns DatagramSocket object if the delegate socket is a TCP ones, null
* otherwise.
*
* @return DatagramSocket object if the delegate socket is a TCP ones, null
* otherwise
*/
public abstract DatagramSocket getUDPSocket();
}

View File

@ -0,0 +1,198 @@
/*
* ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
* Maintained by the SIP Communicator community (http://sip-communicator.org).
*
* Distributable under LGPL license. See terms of license at gnu.org.
*/
package org.ice4j.socket;
import java.io.*;
import java.net.*;
import java.util.*;
import java.util.logging.*;
import org.ice4j.ice.*;
/**
* TCP Server Socket wrapper.
*
* @author Sebastien Vincent
*/
public class IceTcpServerSocketWrapper
extends IceSocketWrapper
{
/**
* The <tt>Logger</tt> used by the <tt>LocalCandidate</tt> class and its
* instances for logging output.
*/
private static final Logger logger
= Logger.getLogger(IceTcpServerSocketWrapper.class.getName());
/**
* Thread that will wait new connections.
*/
private Thread acceptThread = null;
/**
* The wrapped TCP ServerSocket.
*/
private final ServerSocket serverSocket;
/**
* If the socket is still listening.
*/
private boolean isRun = false;
/**
* STUN stack.
*/
private final Component component;
/**
* List of TCP client sockets.
*/
private final List<Socket> sockets = new ArrayList<Socket>();
/**
* Initializes a new <tt>IceTcpServerSocketWrapper</tt>.
*
* @param serverSocket TCP <tt>ServerSocket</tt>
* @param component related <tt>Component</tt>
*/
public IceTcpServerSocketWrapper(ServerSocket serverSocket,
Component component)
{
this.serverSocket = serverSocket;
this.component = component;
acceptThread = new ThreadAccept();
acceptThread.start();
}
/**
* {@inheritDoc}
*/
@Override
public void send(DatagramPacket p) throws IOException
{
/* Do nothing for the moment */
}
/**
* {@inheritDoc}
*/
@Override
public void receive(DatagramPacket p) throws IOException
{
/* Do nothing for the moment */
}
/**
* {@inheritDoc}
*/
@Override
public void close()
{
try
{
isRun = false;
serverSocket.close();
for(Socket s : sockets)
{
s.close();
}
}
catch(IOException e)
{
}
}
/**
* {@inheritDoc}
*/
@Override
public InetAddress getLocalAddress()
{
return serverSocket.getInetAddress();
}
/**
* {@inheritDoc}
*/
@Override
public int getLocalPort()
{
return serverSocket.getLocalPort();
}
/**
* {@inheritDoc}
*/
@Override
public SocketAddress getLocalSocketAddress()
{
return serverSocket.getLocalSocketAddress();
}
/**
* {@inheritDoc}
*/
@Override
public Socket getTCPSocket()
{
if(sockets.size() > 0)
{
return sockets.get(0);
}
return null;
}
/**
* {@inheritDoc}
*/
@Override
public DatagramSocket getUDPSocket()
{
return null;
}
/**
* Thread that will wait for new TCP connections.
*
* @author Sebastien Vincent
*/
private class ThreadAccept extends Thread
{
/**
* Thread entry point.
*/
@Override
public void run()
{
isRun = true;
while(isRun)
{
try
{
Socket tcpSocket = serverSocket.accept();
if(tcpSocket != null)
{
MultiplexingSocket multiplexingSocket =
new MultiplexingSocket(tcpSocket);
component.getParentStream().getParentAgent().
getStunStack().addSocket(
new IceTcpSocketWrapper(multiplexingSocket));
sockets.add(multiplexingSocket);
}
}
catch(IOException e)
{
logger.info("Failed to accept TCP socket " + e);
}
}
}
}
}

View File

@ -0,0 +1,168 @@
/*
* ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
* Maintained by the SIP Communicator community (http://sip-communicator.org).
*
* Distributable under LGPL license. See terms of license at gnu.org.
*/
package org.ice4j.socket;
import java.io.*;
import java.net.*;
/**
* TCP implementation of the <tt>IceSocketWrapper</tt>.
*
* @author Sebastien Vincent
*/
public class IceTcpSocketWrapper
extends IceSocketWrapper
{
/**
* Delegate TCP <tt>Socket</tt>.
*/
private final Socket socket;
/**
* InputStream for this socket.
*/
private InputStream inputStream = null;
/**
* OutputStream for this socket.
*/
private OutputStream outputStream = null;
/**
* Constructor.
*
* @param delegate delegate <tt>Socket</tt>
*
* @throws IOException if something goes wrong during initialization
*/
public IceTcpSocketWrapper(Socket delegate)
throws IOException
{
this.socket = delegate;
if(!(delegate instanceof DelegatingSocket))
{
inputStream = socket.getInputStream();
outputStream = socket.getOutputStream();
}
}
/**
* {@inheritDoc}
*/
@Override
public void send(DatagramPacket p)
throws IOException
{
if(socket instanceof DelegatingSocket)
{
((DelegatingSocket)socket).send(p);
return;
}
int len = p.getLength();
int off = p.getOffset();
byte data[] = new byte[len + 2];
data[0] = (byte)((len >> 8) & 0xff);
data[1] = (byte)(len & 0xff);
System.arraycopy(p.getData(), off, data, 2, len);
outputStream.write(data, 0, len + 2);
data = null;
}
/**
* {@inheritDoc}
*/
@Override
public void receive(DatagramPacket p) throws IOException
{
if(socket instanceof DelegatingSocket)
{
((DelegatingSocket)socket).receive(p);
return;
}
byte data[] = p.getData();
int len = 0;
inputStream.skip(2);
len = inputStream.read(data);
if(len > 0)
{
p.setData(data);
p.setLength(len);
p.setAddress(this.getLocalAddress());
p.setPort(this.getLocalPort());
}
data = null;
}
/**
* {@inheritDoc}
*/
@Override
public void close()
{
try
{
socket.close();
}
catch(IOException e)
{
}
}
/**
* {@inheritDoc}
*/
@Override
public InetAddress getLocalAddress()
{
return socket.getLocalAddress();
}
/**
* {@inheritDoc}
*/
@Override
public int getLocalPort()
{
return socket.getLocalPort();
}
/**
* {@inheritDoc}
*/
@Override
public SocketAddress getLocalSocketAddress()
{
return socket.getLocalSocketAddress();
}
/**
* Returns Socket object if the delegate socket is a TCP ones, null
* otherwise.
*
* @return Socket object if the delegate socket is a TCP ones, null
* otherwise
*/
public Socket getTCPSocket()
{
return socket;
}
/**
* Returns DatagramSocket object if the delegate socket is a TCP ones, null
* otherwise.
*
* @return DatagramSocket object if the delegate socket is a TCP ones, null
* otherwise
*/
public DatagramSocket getUDPSocket()
{
return null;
}
}

View File

@ -0,0 +1,112 @@
/*
* ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
* Maintained by the SIP Communicator community (http://sip-communicator.org).
*
* Distributable under LGPL license. See terms of license at gnu.org.
*/
package org.ice4j.socket;
import java.io.*;
import java.net.*;
/**
* UDP implementation of the <tt>IceSocketWrapper</tt>.
*
* @author Sebastien Vincent
*/
public class IceUdpSocketWrapper
extends IceSocketWrapper
{
/**
* Delegate UDP <tt>DatagramSocket</tt>.
*/
private final DatagramSocket socket;
/**
* Constructor.
*
* @param delegate delegate <tt>DatagramSocket</tt>
*/
public IceUdpSocketWrapper(DatagramSocket delegate)
{
this.socket = delegate;
}
/**
* {@inheritDoc}
*/
@Override
public void send(DatagramPacket p) throws IOException
{
socket.send(p);
}
/**
* {@inheritDoc}
*/
@Override
public void receive(DatagramPacket p) throws IOException
{
socket.receive(p);
}
/**
* {@inheritDoc}
*/
@Override
public void close()
{
socket.close();
}
/**
* {@inheritDoc}
*/
@Override
public InetAddress getLocalAddress()
{
return socket.getLocalAddress();
}
/**
* {@inheritDoc}
*/
@Override
public int getLocalPort()
{
return socket.getLocalPort();
}
/**
* {@inheritDoc}
*/
@Override
public SocketAddress getLocalSocketAddress()
{
return socket.getLocalSocketAddress();
}
/**
* Returns Socket object if the delegate socket is a TCP ones, null
* otherwise.
*
* @return Socket object if the delegate socket is a TCP ones, null
* otherwise
*/
public Socket getTCPSocket()
{
return null;
}
/**
* Returns DatagramSocket object if the delegate socket is a TCP ones, null
* otherwise.
*
* @return DatagramSocket object if the delegate socket is a TCP ones, null
* otherwise
*/
public DatagramSocket getUDPSocket()
{
return socket;
}
}

View File

@ -0,0 +1,137 @@
/*
* ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
* Maintained by the SIP Communicator community (http://sip-communicator.org).
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package org.ice4j.socket;
import java.io.*;
import java.net.*;
import java.util.*;
/**
* Represents a <tt>Socket</tt> which receives <tt>DatagramPacket</tt>s
* selected by a <tt>DatagramPacketFilter</tt> from a
* <tt>MultiplexingSocket</tt>. The associated
* <tt>MultiplexingSocket</tt> is the actual <tt>Socket</tt>
* which reads the <tt>DatagramPacket</tt>s from the network. The
* <tt>DatagramPacket</tt>s received through the
* <tt>MultiplexedSocket</tt> will not be received through the
* associated <tt>MultiplexingSocket</tt>.
*
* @author Sebastien Vincent
*/
public class MultiplexedSocket
extends DelegatingSocket
{
/**
* The <tt>DatagramPacketFilter</tt> which determines which
* <tt>DatagramPacket</tt>s read from the network by {@link #multiplexing}
* are to be received through this instance.
*/
private final DatagramPacketFilter filter;
/**
* The <tt>MultiplexingSocket</tt> which does the actual reading
* from the network and which forwards <tt>DatagramPacket</tt>s accepted by
* {@link #filter} for receipt to this instance.
*/
private final MultiplexingSocket multiplexing;
/**
* The list of <tt>DatagramPacket</tt>s to be received through this
* <tt>Socket</tt> i.e. accepted by {@link #filter}.
*/
final List<DatagramPacket> received = new LinkedList<DatagramPacket>();
/**
* Initializes a new <tt>MultiplexedSocket</tt> which is unbound and
* filters <tt>DatagramPacket</tt>s away from a specific
* <tt>MultiplexingSocket</tt> using a specific
* <tt>DatagramPacketFilter</tt>.
*
* @param multiplexing the <tt>MultiplexingSocket</tt> which does
* the actual reading from the network and which forwards
* <tt>DatagramPacket</tt>s accepted by the specified <tt>filter</tt> to the
* new instance
* @param filter the <tt>DatagramPacketFilter</tt> which determines which
* <tt>DatagramPacket</tt>s read from the network by the specified
* <tt>multiplexing</tt> are to be received through the new instance
* @throws SocketException if the socket could not be opened
*/
MultiplexedSocket(
MultiplexingSocket multiplexing,
DatagramPacketFilter filter)
throws SocketException
{
/*
* Even if MultiplexingSocket allows MultiplexedSocket
* to perform bind, binding in the super will not execute correctly this
* early in the construction because the multiplexing field is not set
* yet. That is why MultiplexeSocket does not currently support
* bind at construction time.
*/
super(multiplexing);
if (multiplexing == null)
throw new NullPointerException("multiplexing");
this.multiplexing = multiplexing;
this.filter = filter;
}
/**
* Closes this datagram socket.
* <p>
* Any thread currently blocked in {@link #receive(DatagramPacket)} upon
* this socket will throw a {@link SocketException}.
* </p>
*
* @see Socket#close()
*/
@Override
public void close()
{
multiplexing.close(this);
}
/**
* Gets the <tt>DatagramPacketFilter</tt> which determines which
* <tt>DatagramPacket</tt>s read from the network are to be received through
* this <tt>Socket</tt>.
*
* @return the <tt>DatagramPacketFilter</tt> which determines which
* <tt>DatagramPacket</tt>s read from the network are to be received through
* this <tt>Socket</tt>
*/
public DatagramPacketFilter getFilter()
{
return filter;
}
/**
* Receives a datagram packet from this socket. When this method returns,
* the <tt>DatagramPacket</tt>'s buffer is filled with the data received.
* The datagram packet also contains the sender's IP address, and the port
* number on the sender's machine.
* <p>
* This method blocks until a datagram is received. The <tt>length</tt>
* field of the datagram packet object contains the length of the received
* message. If the message is longer than the packet's length, the message
* is truncated.
* </p>
*
* @param p the <tt>DatagramPacket</tt> into which to place the incoming
* data
* @throws IOException if an I/O error occurs
* @see MultiplexingSocket#receive(DatagramPacket)
*/
@Override
public void receive(DatagramPacket p)
throws IOException
{
multiplexing.receive(this, p);
}
}

View File

@ -0,0 +1,515 @@
/*
* ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
* Maintained by the SIP Communicator community (http://sip-communicator.org).
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package org.ice4j.socket;
import java.io.*;
import java.net.*;
import java.util.*;
import java.util.logging.*;
/**
* Represents a <tt>Socket</tt> which allows filtering
* <tt>DatagramPacket</tt>s it reads from the network using
* <tt>DatagramPacketFilter</tt>s so that the <tt>DatagramPacket</tt>s do not
* get received through it but through associated <tt>MultiplexedSocket</tt>s.
*
* @author Sebastien Vincent
* @author Lyubomir Marinov
*/
public class MultiplexingSocket
extends DelegatingSocket
{
/**
* The <tt>Logger</tt> used by the <tt>MultiplexingSocket</tt> class
* and its instances for logging output.
*/
private static final Logger logger
= Logger.getLogger(MultiplexingSocket.class.getName());
/**
* The constant which represents an empty array with
* <tt>MultiplexedSocket</tt> element type. Explicitly defined in
* order to reduce allocations.
*/
private static final MultiplexedSocket[] NO_SOCKETS
= new MultiplexedSocket[0];
/**
* The indicator which determines whether this <tt>Socket</tt> is
* currently reading from the network using
* {@link #receive(DatagramPacket)}. When <tt>true</tt>,
* subsequent requests to read from the network will be blocked until the
* current read is finished.
*/
private boolean inReceive = false;
/**
* The list of <tt>DatagramPacket</tt>s to be received through this
* <tt>Socket</tt> i.e. not accepted by the <tt>DatagramFilter</tt>s
* of {@link #sockets} at the time of the reading from the network.
*/
private final List<DatagramPacket> received
= new LinkedList<DatagramPacket>();
/**
* Custom <tt>InputStream</tt> for this <tt>Socket</tt>.
*/
private final TCPInputStream inputStream = new TCPInputStream();
/**
* The <tt>Object</tt> which synchronizes the access to {@link #inReceive}.
*/
private final Object receiveSyncRoot = new Object();
/**
* The <tt>MultiplexedSocket</tt>s filtering <tt>DatagramPacket</tt>s
* away from this <tt>Socket</tt>.
*/
private MultiplexedSocket[] sockets = NO_SOCKETS;
/**
* The <tt>Object</tt> which synchronizes the access to the {@link #sockets}
* field of this instance.
*/
private final Object socketsSyncRoot = new Object();
/**
* Initializes a new <tt>MultiplexingSocket</tt> instance.
*
* @see Socket#Socket()
*/
public MultiplexingSocket()
{
super();
try
{
setTcpNoDelay(true);
}
catch(SocketException e)
{
logger.info("Cannot SO_TCPNODELAY");
}
}
/**
* Initializes a new <tt>MultiplexingSocket</tt> instance.
*
* @see Socket#Socket(InetAddress, int)
*/
public MultiplexingSocket(InetAddress address, int port)
throws IOException
{
super(address, port);
try
{
setTcpNoDelay(true);
}
catch(SocketException e)
{
logger.info("Cannot SO_TCPNODELAY");
}
}
/**
* Initializes a new <tt>MultiplexingSocket</tt> instance.
*
* @see Socket#Socket(InetAddress, int, InetAddress, int)
*/
public MultiplexingSocket(InetAddress address, int port,
InetAddress localAddr, int localPort)
throws IOException
{
super(address, port, localAddr, localPort);
try
{
setTcpNoDelay(true);
}
catch(SocketException e)
{
logger.info("Cannot SO_TCPNODELAY");
}
}
/**
* Initializes a new <tt>MultiplexingSocket</tt> instance.
*
* @see Socket#Socket(Proxy)
*/
public MultiplexingSocket(Proxy proxy)
{
super(proxy);
try
{
setTcpNoDelay(true);
}
catch(SocketException e)
{
logger.info("Cannot SO_TCPNODELAY");
}
}
/**
* Initializes a new <tt>MultiplexingSocket</tt> instance.
*
* @see Socket#Socket(SocketImpl)
*/
protected MultiplexingSocket(SocketImpl impl)
throws SocketException
{
super(impl);
try
{
setTcpNoDelay(true);
}
catch(SocketException e)
{
logger.info("Cannot SO_TCPNODELAY");
}
}
/**
* Initializes a new <tt>MultiplexingSocket</tt> instance.
*
* @see Socket#Socket(String, int)
*/
public MultiplexingSocket(String host, int port)
throws UnknownHostException,
IOException
{
super(host, port);
try
{
setTcpNoDelay(true);
}
catch(SocketException e)
{
logger.info("Cannot SO_TCPNODELAY");
}
}
/**
* Initializes a new <tt>MultiplexingSocket</tt> instance.
*
* @see Socket#Socket(String, int, InetAddress, int)
*/
public MultiplexingSocket(String host, int port,
InetAddress localAddr, int localPort)
{
super(host, port, localAddr, localPort);
try
{
setTcpNoDelay(true);
}
catch(SocketException e)
{
logger.info("Cannot SO_TCPNODELAY");
}
}
/**
* Initializes a new <tt>MultiplexingSocket</tt> instance.
*
* @param socket delegate socket
*/
public MultiplexingSocket(Socket socket)
{
super(socket);
try
{
setTcpNoDelay(true);
}
catch(SocketException e)
{
logger.info("Cannot SO_TCPNODELAY");
}
}
/**
* Receives a datagram packet from this socket. The <tt>DatagramPacket</tt>s
* returned by this method do not match any of the
* <tt>DatagramPacketFilter</tt>s of the <tt>MultiplexedDatagramSocket</tt>s
* associated with this instance at the time of their receipt. When this
* method returns, the <tt>DatagramPacket</tt>'s buffer is filled with the
* data received. The datagram packet also contains the sender's IP address,
* and the port number on the sender's machine.
* <p>
* This method blocks until a datagram is received. The <tt>length</tt>
* field of the datagram packet object contains the length of the received
* message. If the message is longer than the packet's length, the message
* is truncated.
* </p>
*
* @param p the <tt>DatagramPacket</tt> into which to place the incoming
* data
* @throws IOException if an I/O error occurs
* @see DelegatingSocket#receive(DatagramPacket)
*/
@Override
public void receive(DatagramPacket p)
throws IOException
{
try
{
setOriginalInputStream(super.getInputStream());
}
catch(Exception e)
{
}
receive(received, p);
}
/**
* Receives a <tt>DatagramPacket</tt> from this <tt>Socket</tt> upon
* request from a specific <tt>MultiplexedSocket</tt>.
*
* @param multiplexed the <tt>MultiplexedSocket</tt> which requests
* the receipt of a <tt>DatagramPacket</tt> from the network
* @param p the <tt>DatagramPacket</tt> to receive the data from the network
* @throws IOException if an I/O error occurs
*/
void receive(
MultiplexedSocket multiplexed,
DatagramPacket p)
throws IOException
{
try
{
setOriginalInputStream(super.getInputStream());
}
catch(Exception e)
{
}
receive(multiplexed.received, p);
}
/**
* Receives a <tt>DatagramPacket</tt> from a specific list of
* <tt>DatagramPacket</tt>s if it is not empty or from the network if the
* specified list is empty. When this method returns, the
* <tt>DatagramPacket</tt>'s buffer is filled with the data received. The
* datagram packet also contains the sender's IP address, and the port
* number on the sender's machine.
*
* @param received the list of previously received <tt>DatagramPacket</tt>
* from which the first is to be removed and returned if available
* @param p the <tt>DatagramPacket</tt> into which to place the incoming
* data
* @throws IOException if an I/O error occurs
*/
private void receive(List<DatagramPacket> received, DatagramPacket p)
throws IOException
{
DatagramPacket r = null;
do
{
boolean doReceive;
synchronized (receiveSyncRoot)
{
if (received.isEmpty())
{
if (inReceive)
{
doReceive = false;
try
{
receiveSyncRoot.wait();
}
catch (InterruptedException iex)
{
continue;
}
}
else
{
doReceive = true;
inReceive = true;
}
}
else
{
doReceive = false;
r = received.remove(0);
}
}
if (doReceive)
{
try
{
super.receive(p);
synchronized (receiveSyncRoot)
{
synchronized (socketsSyncRoot)
{
boolean accepted = false;
for (MultiplexedSocket socket : sockets)
if (socket.getFilter().accept(p))
{
socket.received.add(
MultiplexingDatagramSocket.clone(p));
accepted = true;
/*
* Emil: Don't break because we want all
* filtering sockets to get this.
*/
//break;
}
if (!accepted)
addReceivedPacket(p);
}
}
}
finally
{
synchronized (receiveSyncRoot)
{
inReceive = false;
receiveSyncRoot.notifyAll();
}
}
}
}
while (r == null);
MultiplexingDatagramSocket.copy(r, p);
}
/**
* Close socket.
*/
public void close()
{
try
{
super.close();
}
catch(IOException e)
{
}
}
/**
* Closes a specific <tt>MultiplexedSocket</tt> which filters
* <tt>DatagramPacket</tt>s away from this <tt>Socket</tt>.
*
* @param multiplexed the <tt>MultiplexedSocket</tt> to close
*/
void close(MultiplexedSocket multiplexed)
{
synchronized (socketsSyncRoot)
{
int socketCount = sockets.length;
for (int i = 0; i < socketCount; i++)
{
if (sockets[i].equals(multiplexed))
{
if (socketCount == 1)
sockets = NO_SOCKETS;
else
{
MultiplexedSocket[] newSockets
= new MultiplexedSocket[socketCount - 1];
System.arraycopy(sockets, 0, newSockets, 0, i);
System.arraycopy(
sockets, i + 1,
newSockets, i,
newSockets.length - i);
sockets = newSockets;
}
break;
}
}
}
}
/**
* Gets a <tt>MultiplexedDatagramSocket</tt> which filters
* <tt>DatagramPacket</tt>s away from this <tt>DatagramSocket</tt> using a
* specific <tt>DatagramPacketFilter</tt>. If such a
* <tt>MultiplexedDatagramSocket</tt> does not exist in this instance, it is
* created.
*
* @param filter the <tt>DatagramPacketFilter</tt> to get a
* <tt>MultiplexedDatagramSocket</tt> for
* @return a <tt>MultiplexedDatagramSocket</tt> which filters
* <tt>DatagramPacket</tt>s away from this <tt>DatagramSocket</tt> using the
* specified <tt>filter</tt>
* @throws SocketException if creating the
* <tt>MultiplexedDatagramSocket</tt> for the specified <tt>filter</tt>
* fails
*/
public MultiplexedSocket getSocket(DatagramPacketFilter filter)
throws SocketException
{
if (filter == null)
throw new NullPointerException("filter");
synchronized (socketsSyncRoot)
{
/*
* If a socket for the specified filter exists already, do not
* create a new one and return the existing.
*/
for (MultiplexedSocket socket : sockets)
if (filter.equals(socket.getFilter()))
return socket;
// Create a new socket for the specified filter.
MultiplexedSocket socket
= new MultiplexedSocket(this, filter);
// Remember the new socket.
int socketCount = sockets.length;
if (socketCount == 0)
sockets = new MultiplexedSocket[] { socket };
else
{
MultiplexedSocket[] newSockets
= new MultiplexedSocket[socketCount + 1];
System.arraycopy(sockets, 0, newSockets, 0, socketCount);
newSockets[socketCount] = socket;
sockets = newSockets;
}
return socket;
}
}
/**
* Add received packet.
*
* @param p <tt>DatagramPacket</tt>
*/
public void addReceivedPacket(DatagramPacket p)
{
byte data[] = p.getData();
int len = p.getLength();
byte newData[] = new byte[len];
System.arraycopy(data, p.getOffset(), newData, 0, len);
inputStream.addPacket(newData);
}
/**
* {@inheritDoc}
*/
public InputStream getInputStream()
throws IOException
{
return inputStream;
}
}

View File

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

View File

@ -0,0 +1,234 @@
/*
* ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
* Maintained by the SIP Communicator community (http://sip-communicator.org).
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package org.ice4j.socket;
import java.io.*;
import java.util.*;
/**
* TCP input stream for TCP socket. It is used to multiplex sockets and keep
* the <tt>InputStream</tt> interface to users.
*
* @author Sebastien Vincent
*/
public class TCPInputStream
extends InputStream
{
/**
* List of packets.
*/
private final List<byte[]> packets = new ArrayList<byte[]>();
/**
* Current packet being processed if any.
*/
private byte[] currentPacket = null;
/**
* Current offset.
*/
private int currentPacketOffset = 0;
/**
* Current packet length.
*/
private int currentPacketLength = 0;
/**
* Synchronization object for read operation.
*/
private final Object readSyncRoot = new Object();
/**
* Initializes a new <tt>TCPInputStream</tt>.
*/
public TCPInputStream()
{
}
/**
* {@inheritDoc}
*/
@Override
public int available()
{
return 0;
}
/**
* {@inheritDoc}
*/
@Override
public void close()
throws IOException
{
packets.clear();
currentPacket = null;
currentPacketOffset = 0;
}
/**
* {@inheritDoc}
*/
@Override
public void mark(int readLimit)
{
/* do nothing */
}
/**
* {@inheritDoc}
*/
@Override
public boolean markSupported()
{
return false;
}
/**
* {@inheritDoc}
*/
@Override
public int read(byte[] b)
{
return read(b, 0, b.length);
}
/**
* {@inheritDoc}
*/
@Override
public int read(byte[] b, int off, int len)
{
synchronized(readSyncRoot)
{
getNextPacket();
int length = currentPacketLength;
if(len < length)
{
length = len;
}
System.arraycopy(currentPacket, currentPacketOffset, b, off,
length);
currentPacketOffset += length;
currentPacketLength -= length;
if(currentPacketLength <= 0)
{
currentPacket = null;
currentPacketOffset = 0;
currentPacketLength = 0;
}
return length;
}
}
/**
* {@inheritDoc}
*/
@Override
public void reset()
throws IOException
{
if(!markSupported())
{
throw new IOException("TCPInputStream does not support reset()");
}
}
/**
* {@inheritDoc}
*/
@Override
public long skip(long n)
throws IOException
{
synchronized(readSyncRoot)
{
getNextPacket();
if(n > currentPacketLength)
{
n = currentPacketLength;
}
currentPacketOffset += n;
currentPacketLength -= n;
if(currentPacketLength <= 0)
{
currentPacket = null;
currentPacketOffset = 0;
currentPacketLength = 0;
}
return n;
}
}
/**
* {@inheritDoc}
*/
@Override
public int read()
throws IOException
{
//getNextPacket();
// TODO Auto-generated method stub
return 0;
}
/**
* Get next packet. It blocks if no packets are available.
*
* @return next packet
*/
private byte[] getNextPacket()
{
synchronized(packets)
{
if(packets.size() == 0)
{
try
{
packets.wait();
}
catch (InterruptedException iex)
{
}
}
if(currentPacket == null)
{
currentPacket = packets.remove(0);
currentPacketOffset = 0;
currentPacketLength = currentPacket.length;
}
}
return currentPacket;
}
/**
* Add packet to this <tt>InputStream</tt>.
*
* @param p packet bytes
*/
public void addPacket(byte[] p)
{
synchronized(packets)
{
this.packets.add(p);
packets.notifyAll();
}
}
}

View File

@ -11,6 +11,7 @@ import java.net.*;
import java.util.logging.*; import java.util.logging.*;
import org.ice4j.*; import org.ice4j.*;
import org.ice4j.socket.*;
/** /**
* The Network Access Point is the most outward part of the stack. It is * The Network Access Point is the most outward part of the stack. It is
@ -37,7 +38,7 @@ class Connector
/** /**
* The socket object that used by this access point to access the network. * The socket object that used by this access point to access the network.
*/ */
private DatagramSocket sock; private IceSocketWrapper sock;
/** /**
* The object that we use to lock socket operations (since the socket itself * The object that we use to lock socket operations (since the socket itself
@ -68,7 +69,7 @@ class Connector
* @param messageQueue the FIFO list where incoming messages should be queued * @param messageQueue the FIFO list where incoming messages should be queued
* @param errorHandler the instance to notify when errors occur. * @param errorHandler the instance to notify when errors occur.
*/ */
protected Connector(DatagramSocket socket, protected Connector(IceSocketWrapper socket,
MessageQueue messageQueue, MessageQueue messageQueue,
ErrorHandler errorHandler) ErrorHandler errorHandler)
{ {
@ -76,7 +77,8 @@ class Connector
this.messageQueue = messageQueue; this.messageQueue = messageQueue;
this.errorHandler = errorHandler; this.errorHandler = errorHandler;
this.listenAddress = new TransportAddress(socket.getLocalAddress(), this.listenAddress = new TransportAddress(socket.getLocalAddress(),
socket.getLocalPort(), Transport.UDP); socket.getLocalPort(), socket.getUDPSocket() != null ?
Transport.UDP : Transport.TCP);
} }
/** /**
@ -96,7 +98,7 @@ class Connector
* *
* @return the <tt>DatagramSocket</tt> associated with this AP. * @return the <tt>DatagramSocket</tt> associated with this AP.
*/ */
protected DatagramSocket getSocket() protected IceSocketWrapper getSocket()
{ {
return sock; return sock;
} }
@ -112,7 +114,7 @@ class Connector
{ {
try try
{ {
DatagramSocket localSock; IceSocketWrapper localSock;
synchronized (sockLock) synchronized (sockLock)
{ {
@ -126,7 +128,17 @@ class Connector
* Make sure localSock's receiveBufferSize is taken into * Make sure localSock's receiveBufferSize is taken into
* account including after it gets changed. * account including after it gets changed.
*/ */
int receiveBufferSize = localSock.getReceiveBufferSize(); int receiveBufferSize = 1500;
if(localSock.getTCPSocket() != null)
{
receiveBufferSize = localSock.getTCPSocket().
getReceiveBufferSize();
}
else if(localSock.getUDPSocket() != null)
{
receiveBufferSize = localSock.getUDPSocket().
getReceiveBufferSize();
}
if (packet == null) if (packet == null)
{ {
@ -173,7 +185,7 @@ class Connector
new TransportAddress( new TransportAddress(
packet.getAddress(), packet.getAddress(),
packet.getPort(), packet.getPort(),
Transport.UDP), listenAddress.getTransport()),
listenAddress); listenAddress);
messageQueue.add(rawMessage); messageQueue.add(rawMessage);

View File

@ -7,12 +7,12 @@
package org.ice4j.stack; package org.ice4j.stack;
import java.io.*; import java.io.*;
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.message.*; import org.ice4j.message.*;
import org.ice4j.socket.*;
/** /**
* Manages <tt>Connector</tt>s and <tt>MessageProcessor</tt> pooling. This class * Manages <tt>Connector</tt>s and <tt>MessageProcessor</tt> pooling. This class
@ -33,10 +33,27 @@ class NetAccessManager
= Logger.getLogger(NetAccessManager.class.getName()); = Logger.getLogger(NetAccessManager.class.getName());
/** /**
* All access points currently in use. The table maps * All access points currently in use with UDP. The table maps
* <tt>TransportAddress</tt>es to <tt>Connector</tt>s * <tt>TransportAddress</tt>es to <tt>Connector</tt>s.
*
* Due to the final hashCode() method of InetSocketAddress, TransportAddress
* cannot override and it causes problem to store both UDP and TCP address
* (i.e. 192.168.0.3:5000/tcp has the same hashcode as 192.168.0.3:5000/udp
* because InetSocketAddress does not take into account transport).
*/ */
private Hashtable<TransportAddress, Connector> netAccessPoints private Map<TransportAddress, Connector> netUDPAccessPoints
= new Hashtable<TransportAddress, Connector>();
/**
* All access points currently in use with TCP. The table maps
* <tt>TransportAddress</tt>es to <tt>Connector</tt>s.
*
* Due to the final hashCode() method of InetSocketAddress, TransportAddress
* cannot override and it causes problem to store both UDP and TCP address
* (i.e. 192.168.0.3:5000/tcp has the same hashcode as 192.168.0.3:5000/udp
* because InetSocketAddress does not take into account transport).
*/
private Map<TransportAddress, Connector> netTCPAccessPoints
= new Hashtable<TransportAddress, Connector>(); = new Hashtable<TransportAddress, Connector>();
/** /**
@ -179,20 +196,31 @@ class NetAccessManager
* *
* @param socket the socket that the access point should use. * @param socket the socket that the access point should use.
*/ */
protected void addSocket(DatagramSocket socket) protected void addSocket(IceSocketWrapper socket)
{ {
//no null check - let it through as a NullPointerException //no null check - let it through as a NullPointerException
TransportAddress localAddr TransportAddress localAddr
= new TransportAddress( = new TransportAddress(
socket.getLocalAddress(), socket.getLocalAddress(),
socket.getLocalPort(), socket.getLocalPort(),
Transport.UDP); socket.getUDPSocket() != null ? Transport.UDP :
Transport.TCP);
if (!netAccessPoints.containsKey(localAddr)) if (socket.getUDPSocket() != null &&
!netUDPAccessPoints.containsKey(localAddr))
{ {
Connector ap = new Connector(socket, messageQueue, this); Connector ap = new Connector(socket, messageQueue, this);
netAccessPoints.put(localAddr, ap); netUDPAccessPoints.put(localAddr, ap);
ap.start();
}
if (socket.getTCPSocket() != null &&
!netTCPAccessPoints.containsKey(localAddr))
{
Connector ap = new Connector(socket, messageQueue, this);
netTCPAccessPoints.put(localAddr, ap);
ap.start(); ap.start();
} }
} }
@ -204,7 +232,16 @@ class NetAccessManager
*/ */
protected void removeSocket(TransportAddress address) protected void removeSocket(TransportAddress address)
{ {
Connector ap = netAccessPoints.remove(address); Connector ap = null;
if(address.getTransport() == Transport.UDP)
{
ap = netUDPAccessPoints.remove(address);
}
else if(address.getTransport() == Transport.TCP)
{
ap = netTCPAccessPoints.remove(address);
}
if(ap != null) if(ap != null)
ap.stop(); ap.stop();
@ -306,7 +343,16 @@ class NetAccessManager
throws IOException, IllegalArgumentException throws IOException, IllegalArgumentException
{ {
byte[] bytes = stunMessage.encode(stunStack); byte[] bytes = stunMessage.encode(stunStack);
Connector ap = netAccessPoints.get(srcAddr); Connector ap = null;
if(srcAddr.getTransport() == Transport.UDP)
{
ap = netUDPAccessPoints.get(srcAddr);
}
else if(srcAddr.getTransport() == Transport.TCP)
{
ap = netTCPAccessPoints.get(srcAddr);
}
if (ap == null) if (ap == null)
{ {

View File

@ -19,6 +19,7 @@ import org.ice4j.attribute.*;
import org.ice4j.ice.*; import org.ice4j.ice.*;
import org.ice4j.message.*; import org.ice4j.message.*;
import org.ice4j.security.*; import org.ice4j.security.*;
import org.ice4j.socket.*;
/** /**
* The entry point to the Stun4J stack. The class is used to start, stop and * The entry point to the Stun4J stack. The class is used to start, stop and
@ -112,7 +113,7 @@ public class StunStack
* *
* @param sock The socket that the new access point should represent. * @param sock The socket that the new access point should represent.
*/ */
public void addSocket(DatagramSocket sock) public void addSocket(IceSocketWrapper sock)
{ {
netAccessManager.addSocket(sock); netAccessManager.addSocket(sock);
} }

View File

@ -7,7 +7,6 @@
package org.ice4j.stunclient; package org.ice4j.stunclient;
import java.io.*; import java.io.*;
import java.net.*;
import java.util.logging.*; import java.util.logging.*;
import org.ice4j.*; import org.ice4j.*;
@ -113,7 +112,7 @@ public class NetworkConfigurationDiscoveryProcess
* The <tt>DatagramSocket</tt> that we are going to be running the * The <tt>DatagramSocket</tt> that we are going to be running the
* discovery process through. * discovery process through.
*/ */
private DatagramSocket sock = null; private IceSocketWrapper sock = null;
/** /**
* The <tt>StunStack</tt> used by this instance for the purposes of STUN * The <tt>StunStack</tt> used by this instance for the purposes of STUN
@ -165,7 +164,8 @@ public class NetworkConfigurationDiscoveryProcess
public void start() public void start()
throws IOException, StunException throws IOException, StunException
{ {
sock = new SafeCloseDatagramSocket(localAddress); sock = new IceUdpSocketWrapper(
new SafeCloseDatagramSocket(localAddress));
stunStack.addSocket(sock); stunStack.addSocket(sock);

View File

@ -13,6 +13,7 @@ import java.util.logging.*;
import org.ice4j.*; import org.ice4j.*;
import org.ice4j.attribute.*; import org.ice4j.attribute.*;
import org.ice4j.message.*; import org.ice4j.message.*;
import org.ice4j.socket.*;
import org.ice4j.stack.*; import org.ice4j.stack.*;
/** /**
@ -86,7 +87,6 @@ public class SimpleAddressDetector
stunStack = new StunStack(); stunStack = new StunStack();
} }
/** /**
* Creates a listening point for the specified socket and attempts to * Creates a listening point for the specified socket and attempts to
* discover how its local address is NAT mapped. * discover how its local address is NAT mapped.
@ -97,7 +97,7 @@ public class SimpleAddressDetector
* @throws IOException if something fails along the way. * @throws IOException if something fails along the way.
* @throws BindException if we cannot bind the socket. * @throws BindException if we cannot bind the socket.
*/ */
public TransportAddress getMappingFor(DatagramSocket socket) public TransportAddress getMappingFor(IceSocketWrapper socket)
throws IOException, BindException throws IOException, BindException
{ {
TransportAddress localAddress = new TransportAddress( TransportAddress localAddress = new TransportAddress(

View File

@ -48,17 +48,17 @@ public class MessageEventDispatchingTest extends TestCase
/** /**
* The socket that the client is using. * The socket that the client is using.
*/ */
DatagramSocket clientSock = null; IceSocketWrapper clientSock = null;
/** /**
* The socket that the server is using * The socket that the server is using
*/ */
DatagramSocket serverSock = null; IceSocketWrapper serverSock = null;
/** /**
* The second server socket. * The second server socket.
*/ */
DatagramSocket serverSock2 = null; IceSocketWrapper serverSock2 = null;
/** /**
* The request that we will be sending in this test. * The request that we will be sending in this test.
@ -91,9 +91,12 @@ public class MessageEventDispatchingTest extends TestCase
stunStack = new StunStack(); stunStack = new StunStack();
clientSock = new SafeCloseDatagramSocket(clientAddress); clientSock = new IceUdpSocketWrapper(
serverSock = new SafeCloseDatagramSocket(serverAddress); new SafeCloseDatagramSocket(clientAddress));
serverSock2 = new SafeCloseDatagramSocket(serverAddress2); serverSock = new IceUdpSocketWrapper(
new SafeCloseDatagramSocket(serverAddress));
serverSock2 = new IceUdpSocketWrapper(
new SafeCloseDatagramSocket(serverAddress2));
stunStack.addSocket(clientSock); stunStack.addSocket(clientSock);
stunStack.addSocket(serverSock); stunStack.addSocket(serverSock);

View File

@ -6,7 +6,6 @@
*/ */
package org.ice4j; package org.ice4j;
import java.net.*;
import java.util.*; import java.util.*;
import junit.framework.*; import junit.framework.*;
@ -39,12 +38,12 @@ public class TransactionSupportTests extends TestCase
/** /**
* The socket the client uses in this test. * The socket the client uses in this test.
*/ */
DatagramSocket clientSock = null; IceSocketWrapper clientSock = null;
/** /**
* The socket the server uses in this test. * The socket the server uses in this test.
*/ */
DatagramSocket serverSock = null; IceSocketWrapper serverSock = null;
/** /**
* The <tt>StunStack</tt> used by this <tt>TransactionSupportTests</tt>. * The <tt>StunStack</tt> used by this <tt>TransactionSupportTests</tt>.
@ -81,8 +80,10 @@ public class TransactionSupportTests extends TestCase
{ {
super.setUp(); super.setUp();
clientSock = new SafeCloseDatagramSocket(clientAddress); clientSock = new IceUdpSocketWrapper(
serverSock = new SafeCloseDatagramSocket(serverAddress); new SafeCloseDatagramSocket(clientAddress));
serverSock = new IceUdpSocketWrapper(
new SafeCloseDatagramSocket(serverAddress));
stunStack = new StunStack(); stunStack = new StunStack();
stunStack.addSocket(clientSock); stunStack.addSocket(clientSock);

View File

@ -41,7 +41,7 @@ public class ShallowStackTest extends TestCase
private DatagramCollector dgramCollector = new DatagramCollector(); private DatagramCollector dgramCollector = new DatagramCollector();
private DatagramSocket localSock = null; private IceSocketWrapper localSock = null;
private DatagramSocket dummyServerSocket = null; private DatagramSocket dummyServerSocket = null;
@ -77,7 +77,8 @@ public class ShallowStackTest extends TestCase
stunStack = new StunStack(); stunStack = new StunStack();
//access point //access point
localSock = new SafeCloseDatagramSocket(localAddress); localSock = new IceUdpSocketWrapper(
new SafeCloseDatagramSocket(localAddress));
stunStack.addSocket(localSock); stunStack.addSocket(localSock);
//init the dummy server //init the dummy server

View File

@ -7,7 +7,6 @@
package org.ice4j.stunclient; package org.ice4j.stunclient;
import java.io.*; import java.io.*;
import java.net.*;
import java.util.*; import java.util.*;
import java.util.logging.*; import java.util.logging.*;
@ -45,7 +44,7 @@ public class ResponseSequenceServer
private final StunStack stunStack; private final StunStack stunStack;
private TransportAddress serverAddress = null; private TransportAddress serverAddress = null;
private DatagramSocket localSocket = null; private IceSocketWrapper localSocket = null;
/** /**
* Initializes a new <tt>ResponseSequenceServer</tt> instance with a * Initializes a new <tt>ResponseSequenceServer</tt> instance with a
@ -72,7 +71,8 @@ public class ResponseSequenceServer
public void start() public void start()
throws IOException, StunException throws IOException, StunException
{ {
localSocket = new SafeCloseDatagramSocket(serverAddress); localSocket = new IceUdpSocketWrapper(
new SafeCloseDatagramSocket(serverAddress));
stunStack.addSocket(localSocket); stunStack.addSocket(localSocket);
stunStack.addRequestListener(serverAddress, this); stunStack.addRequestListener(serverAddress, this);