From 205df6ac70227ceabd3a80f5df53f39aab6810d0 Mon Sep 17 00:00:00 2001 From: seb Date: Wed, 20 Jul 2011 15:05:19 +0000 Subject: [PATCH] Adds support for Google's TCP candidates as well as Google TURN TCP and SSLTCP harvesters. --- src/org/ice4j/Transport.java | 7 +- src/org/ice4j/attribute/AttributeFactory.java | 14 + src/org/ice4j/attribute/DataAttribute.java | 20 +- src/org/ice4j/ice/Agent.java | 52 +- src/org/ice4j/ice/Candidate.java | 6 +- src/org/ice4j/ice/Component.java | 78 +- .../ice4j/ice/ConnectivityCheckClient.java | 66 +- src/org/ice4j/ice/GoogleRelayedCandidate.java | 63 +- src/org/ice4j/ice/HostCandidate.java | 32 +- src/org/ice4j/ice/IceMediaStream.java | 27 + src/org/ice4j/ice/LocalCandidate.java | 158 +++- src/org/ice4j/ice/PeerReflexiveCandidate.java | 9 +- src/org/ice4j/ice/RelayedCandidate.java | 10 +- .../ice4j/ice/ServerReflexiveCandidate.java | 9 +- src/org/ice4j/ice/UPNPCandidate.java | 9 +- .../harvest/GoogleTurnCandidateHarvest.java | 53 +- .../harvest/GoogleTurnCandidateHarvester.java | 2 +- .../GoogleTurnSSLCandidateHarvester.java | 158 ++++ .../ice/harvest/HostCandidateHarvester.java | 157 +++- .../ice/harvest/StunCandidateHarvester.java | 55 +- src/org/ice4j/ice/harvest/UPNPHarvester.java | 8 +- src/org/ice4j/message/Message.java | 36 +- src/org/ice4j/message/MessageFactory.java | 2 +- src/org/ice4j/socket/DelegatingSocket.java | 830 ++++++++++++++++++ .../GoogleRelayedCandidateDatagramSocket.java | 359 +------- .../GoogleRelayedCandidateDelegate.java | 466 ++++++++++ .../socket/GoogleRelayedCandidateSocket.java | 338 +++++++ src/org/ice4j/socket/IceSocketWrapper.java | 87 ++ .../socket/IceTcpServerSocketWrapper.java | 198 +++++ src/org/ice4j/socket/IceTcpSocketWrapper.java | 168 ++++ src/org/ice4j/socket/IceUdpSocketWrapper.java | 112 +++ src/org/ice4j/socket/MultiplexedSocket.java | 137 +++ src/org/ice4j/socket/MultiplexingSocket.java | 515 +++++++++++ .../RelayedCandidateDatagramSocket.java | 3 +- src/org/ice4j/socket/TCPInputStream.java | 234 +++++ src/org/ice4j/stack/Connector.java | 26 +- src/org/ice4j/stack/NetAccessManager.java | 70 +- src/org/ice4j/stack/StunStack.java | 3 +- .../NetworkConfigurationDiscoveryProcess.java | 6 +- .../stunclient/SimpleAddressDetector.java | 4 +- .../ice4j/MessageEventDispatchingTest.java | 15 +- test/org/ice4j/TransactionSupportTests.java | 11 +- test/org/ice4j/stack/ShallowStackTest.java | 5 +- .../stunclient/ResponseSequenceServer.java | 6 +- 44 files changed, 4077 insertions(+), 547 deletions(-) create mode 100644 src/org/ice4j/ice/harvest/GoogleTurnSSLCandidateHarvester.java create mode 100644 src/org/ice4j/socket/DelegatingSocket.java create mode 100644 src/org/ice4j/socket/GoogleRelayedCandidateDelegate.java create mode 100644 src/org/ice4j/socket/GoogleRelayedCandidateSocket.java create mode 100644 src/org/ice4j/socket/IceSocketWrapper.java create mode 100644 src/org/ice4j/socket/IceTcpServerSocketWrapper.java create mode 100644 src/org/ice4j/socket/IceTcpSocketWrapper.java create mode 100644 src/org/ice4j/socket/IceUdpSocketWrapper.java create mode 100644 src/org/ice4j/socket/MultiplexedSocket.java create mode 100644 src/org/ice4j/socket/MultiplexingSocket.java create mode 100644 src/org/ice4j/socket/TCPInputStream.java diff --git a/src/org/ice4j/Transport.java b/src/org/ice4j/Transport.java index 05ad973..de0b6b4 100644 --- a/src/org/ice4j/Transport.java +++ b/src/org/ice4j/Transport.java @@ -38,7 +38,12 @@ public enum Transport /** * Represents an SCTP transport. */ - SCTP("sctp"); + SCTP("sctp"), + + /** + * Represents an Google's SSL TCP transport. + */ + SSLTCP("ssltcp"); /** * The name of this Transport. diff --git a/src/org/ice4j/attribute/AttributeFactory.java b/src/org/ice4j/attribute/AttributeFactory.java index d1d984a..07e88e9 100644 --- a/src/org/ice4j/attribute/AttributeFactory.java +++ b/src/org/ice4j/attribute/AttributeFactory.java @@ -497,6 +497,20 @@ public class AttributeFactory 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 * value diff --git a/src/org/ice4j/attribute/DataAttribute.java b/src/org/ice4j/attribute/DataAttribute.java index d91517d..2effdec 100644 --- a/src/org/ice4j/attribute/DataAttribute.java +++ b/src/org/ice4j/attribute/DataAttribute.java @@ -33,12 +33,28 @@ public class DataAttribute */ private byte data[] = null; + /** + * Add padding. + * + * Some dialect does not add (and support) padding (GTalk). + */ + private boolean padding = true; + /** * Constructor. */ protected DataAttribute () + { + this(true); + } + + /** + * Constructor. + */ + protected DataAttribute (boolean padding) { super(DATA); + this.padding = padding; } /** @@ -66,10 +82,10 @@ public class DataAttribute { char type = getAttributeType(); byte binValue[] = new byte[HEADER_LENGTH + getDataLength() + - (getDataLength() % 4)]; + (padding ? (getDataLength() % 4) : 0)]; //Type - binValue[0] = (byte)(type>>8); + binValue[0] = (byte)(type >> 8); binValue[1] = (byte)(type & 0x00FF); //Length diff --git a/src/org/ice4j/ice/Agent.java b/src/org/ice4j/ice/Agent.java index 13ecddf..83f157a 100644 --- a/src/org/ice4j/ice/Agent.java +++ b/src/org/ice4j/ice/Agent.java @@ -316,8 +316,6 @@ public class Agent IOException, BindException { - SecureRandom random = new SecureRandom(); - if(transport != Transport.UDP) { throw new IllegalArgumentException( @@ -350,13 +348,7 @@ public class Agent continue; } - String s = null; - while(s == null || s.length() != 16) - { - s = new BigInteger(80, random).toString(32); - } - - localCand.setUfrag(s); + localCand.setUfrag(generateGTalkUfrag()); } } @@ -375,6 +367,23 @@ public class Agent 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 CandidateHarvesters currently registered with this * Agent to obtain whatever addresses they can discover. @@ -410,7 +419,14 @@ public class Agent hostCandidateHarvester.harvest( 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 harvesters.harvest(component); @@ -1815,9 +1831,20 @@ public class Agent && !IceProcessingState.TERMINATED.equals(state)) terminate(IceProcessingState.TERMINATED); + logger.info("remove streams"); // Free its IceMediaStreams, Components and Candidates. for(IceMediaStream stream : getStreams()) - removeStream(stream); + { + try + { + removeStream(stream); + } + catch(Throwable t) + { + logger.info("remove stream failed: " + t); + } + logger.info("remove stream " + stream.getName()); + } } /** @@ -1907,12 +1934,13 @@ public class Agent try { - Thread.sleep(5000); + Thread.sleep(3000); Thread.yield(); } catch(InterruptedException e) { } } + logger.info("KeepAliveThread ends"); } } diff --git a/src/org/ice4j/ice/Candidate.java b/src/org/ice4j/ice/Candidate.java index cefe625..2efb645 100644 --- a/src/org/ice4j/ice/Candidate.java +++ b/src/org/ice4j/ice/Candidate.java @@ -380,11 +380,13 @@ public abstract class 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) { - priority += (long)(0.9 * 1000); + priority += (long)(0.9 * 1000) - + (this.getBase().getTransport() == Transport.TCP ? 200 : 0); } else if(candidateType == CandidateType.SERVER_REFLEXIVE_CANDIDATE) { diff --git a/src/org/ice4j/ice/Component.java b/src/org/ice4j/ice/Component.java index 565be15..6311913 100644 --- a/src/org/ice4j/ice/Component.java +++ b/src/org/ice4j/ice/Component.java @@ -7,10 +7,13 @@ */ package org.ice4j.ice; +import java.io.*; +import java.net.*; import java.util.*; import java.util.logging.*; import org.ice4j.*; +import org.ice4j.socket.*; /** * 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() + ": " + 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) { remoteUpdateCandidates.add(candidate); @@ -249,13 +314,21 @@ public class Component for(LocalCandidate localCnd : localCnds) { + if(parentStream.getParentAgent(). + getCompatibilityMode() == CompatibilityMode.GTALK && + localCnd.getIceSocketWrapper() instanceof + IceTcpServerSocketWrapper) + { + continue; + } + for(Candidate remoteCnd : remoteUpdateCandidates) { if(localCnd.canReach(remoteCnd)) { CandidatePair pair = new CandidatePair(localCnd, remoteCnd); - + logger.info("new Pair added: " + pair.toShortString()); checkList.add(pair); } } @@ -444,7 +517,7 @@ public class Component public String toShortString() { StringBuffer buff - = new StringBuffer(parentStream.getName()); + = new StringBuffer(parentStream.getName()); buff.append("."); buff.append(componentID); @@ -794,7 +867,6 @@ public class Component */ public Candidate findRemoteCandidate(TransportAddress remoteAddress) { - for( Candidate remoteCnd : localCandidates) { if(remoteCnd.getTransportAddress().equals(remoteAddress)) diff --git a/src/org/ice4j/ice/ConnectivityCheckClient.java b/src/org/ice4j/ice/ConnectivityCheckClient.java index e2b8089..1d693de 100644 --- a/src/org/ice4j/ice/ConnectivityCheckClient.java +++ b/src/org/ice4j/ice/ConnectivityCheckClient.java @@ -6,13 +6,13 @@ */ package org.ice4j.ice; -import java.net.*; import java.util.*; import java.util.logging.*; import org.ice4j.*; import org.ice4j.attribute.*; import org.ice4j.message.*; +import org.ice4j.socket.*; import org.ice4j.stack.*; /** @@ -47,6 +47,12 @@ class ConnectivityCheckClient */ private final List paceMakers = new LinkedList(); + /** + * Timer that is used to let some seconds before a CheckList is considered + * as FAILED. + */ + private Map timers = new HashMap(); + /** * Creates a new ConnectivityCheckHandler setting * parentAgent as the agent that will be used for retrieving @@ -216,8 +222,9 @@ class ConnectivityCheckClient } catch (Exception ex) { - DatagramSocket stunSocket = localCandidate.getStunSocket(null); - logger.log( + IceSocketWrapper stunSocket = localCandidate.getStunSocket(null); + if(stunSocket != null) + logger.log( Level.INFO, "Failed to send " + request + " through " + stunSocket.getLocalSocketAddress(), @@ -288,7 +295,7 @@ class ConnectivityCheckClient { IceMediaStream stream = 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 //Succeeded state: @@ -315,9 +322,33 @@ class ConnectivityCheckClient //media stream, the state of the check list is set to Failed. if ( !stream.validListContainsAllComponents()) { - logger.info("CheckList for stream " + stream.getName() + - " FAILED"); - checkList.setState(CheckListState.FAILED); + final String streamName = stream.getName(); + 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); + 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 @@ -395,6 +426,15 @@ class ConnectivityCheckClient .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 .findLocalCandidate(mappedAddress); Candidate validRemoteCandidate = checkedPair.getRemoteCandidate(); @@ -483,12 +523,16 @@ class ConnectivityCheckClient //same media stream and same foundation to Waiting. IceMediaStream parentStream = checkedPair.getParentComponent() .getParentStream(); - CheckList parentCheckList = parentStream.getCheckList(); - for(CandidatePair pair : parentCheckList) - if ((pair.getState() == CandidatePairState.FROZEN) && + synchronized(this) + { + CheckList parentCheckList = parentStream.getCheckList(); + + for(CandidatePair pair : parentCheckList) + if ((pair.getState() == CandidatePairState.FROZEN) && (checkedPair.getFoundation().equals(pair.getFoundation()))) - pair.setStateWaiting(); + pair.setStateWaiting(); + } // The agent examines the check list for all other streams in turn // If the check list is active, the agent changes the state of diff --git a/src/org/ice4j/ice/GoogleRelayedCandidate.java b/src/org/ice4j/ice/GoogleRelayedCandidate.java index c94d229..dde63c6 100644 --- a/src/org/ice4j/ice/GoogleRelayedCandidate.java +++ b/src/org/ice4j/ice/GoogleRelayedCandidate.java @@ -32,11 +32,17 @@ public class GoogleRelayedCandidate */ private GoogleRelayedCandidateDatagramSocket relayedCandidateDatagramSocket; + /** + * The RelayedCandidateSocket of this + * GoogleRelayedCandidate. + */ + private GoogleRelayedCandidateSocket relayedCandidateSocket = null; + /** * The application-purposed DatagramSocket associated with this * Candidate. */ - private DatagramSocket socket; + private IceSocketWrapper socket; /** * The GoogleTurnCandidateHarvest which has harvested this @@ -97,7 +103,7 @@ public class GoogleRelayedCandidate * @return the RelayedCandidateDatagramSocket of this * RelayedCandidate */ - public synchronized GoogleRelayedCandidateDatagramSocket + private synchronized GoogleRelayedCandidateDatagramSocket getRelayedCandidateDatagramSocket() { if (relayedCandidateDatagramSocket == null) @@ -118,25 +124,66 @@ public class GoogleRelayedCandidate return relayedCandidateDatagramSocket; } + /** + * Gets the RelayedCandidateDatagramSocket of this + * RelayedCandidate. + *

+ * Note: The method is part of the internal API of + * RelayedCandidate and TurnCandidateHarvest and is not + * intended for public use. + *

+ * + * @return the RelayedCandidateDatagramSocket of this + * RelayedCandidate + */ + 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 DatagramSocket associated with * this Candidate. * * @return the DatagramSocket associated with this * Candidate - * @see LocalCandidate#getSocket() + * @see LocalCandidate#getIceSocketWrapper() */ - public synchronized DatagramSocket getSocket() + public synchronized IceSocketWrapper getIceSocketWrapper() { if (socket == null) { try { - socket - = new MultiplexingDatagramSocket( - getRelayedCandidateDatagramSocket()); + if(getTransport() == Transport.UDP) + { + socket + = new IceUdpSocketWrapper(new MultiplexingDatagramSocket( + getRelayedCandidateDatagramSocket())); + } + else if(getTransport() == Transport.TCP) + { + final Socket s = getRelayedCandidateSocket(); + socket = new IceTcpSocketWrapper(new MultiplexingSocket(s)); + } } - catch (SocketException sex) + catch (Exception sex) { throw new UndeclaredThrowableException(sex); } diff --git a/src/org/ice4j/ice/HostCandidate.java b/src/org/ice4j/ice/HostCandidate.java index 4e50c69..f22f1d3 100644 --- a/src/org/ice4j/ice/HostCandidate.java +++ b/src/org/ice4j/ice/HostCandidate.java @@ -33,7 +33,7 @@ public class HostCandidate extends LocalCandidate * If this is a local candidate the field contains the socket that is * actually associated with the candidate. */ - private final DatagramSocket socket; + private final IceSocketWrapper socket; /** * Creates a HostCandidate for the specified transport address. @@ -43,8 +43,8 @@ public class HostCandidate extends LocalCandidate * @param parentComponent the Component that this candidate * belongs to. */ - public HostCandidate(DatagramSocket socket, - Component parentComponent) + public HostCandidate(IceSocketWrapper socket, + Component parentComponent) { super(new TransportAddress(socket.getLocalAddress(), socket.getLocalPort(), Transport.UDP), @@ -55,6 +55,28 @@ public class HostCandidate extends LocalCandidate setBase(this); } + /** + * Creates a HostCandidate for the specified transport address. + * + * @param socket the {@link DatagramSocket} that communication associated + * with this Candidate will be going through. + * @param parentComponent the Component 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 StunDatagramPacketFilter which is to capture STUN * messages and make them available to the DatagramSocket returned @@ -83,9 +105,9 @@ public class HostCandidate extends LocalCandidate * * @return the DatagramSocket associated with this * Candidate - * @see LocalCandidate#getSocket() + * @see LocalCandidate#getIceSocketWrapper() */ - public DatagramSocket getSocket() + public IceSocketWrapper getIceSocketWrapper() { return socket; } diff --git a/src/org/ice4j/ice/IceMediaStream.java b/src/org/ice4j/ice/IceMediaStream.java index 8a37360..131009f 100644 --- a/src/org/ice4j/ice/IceMediaStream.java +++ b/src/org/ice4j/ice/IceMediaStream.java @@ -8,10 +8,13 @@ package org.ice4j.ice; import java.beans.*; +import java.io.*; +import java.net.*; import java.util.*; import java.util.logging.*; import org.ice4j.*; +import org.ice4j.socket.*; /** * 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.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); checkList.add(pair); diff --git a/src/org/ice4j/ice/LocalCandidate.java b/src/org/ice4j/ice/LocalCandidate.java index a9fe8c9..1d22036 100644 --- a/src/org/ice4j/ice/LocalCandidate.java +++ b/src/org/ice4j/ice/LocalCandidate.java @@ -7,6 +7,7 @@ */ package org.ice4j.ice; +import java.io.*; import java.net.*; import java.util.logging.*; @@ -54,12 +55,37 @@ public abstract class LocalCandidate } /** - * Gets the DatagramSocket associated with this Candidate. + * Gets the DatagramSocket associated with this + * Candidate. * * @return the DatagramSocket associated with this * Candidate */ - public abstract DatagramSocket getSocket(); + public DatagramSocket getDatagramSocket() + { + return getIceSocketWrapper().getUDPSocket(); + } + + /** + * Gets the Socket associated with this + * Candidate. + * + * @return the Socket associated with this + * Candidate + */ + public Socket getSocket() + { + return getIceSocketWrapper().getTCPSocket(); + } + + /** + * Gets the IceSocketWrapper associated with this + * Candidate. + * + * @return the IceSocketWrapper associated with this + * Candidate + */ + protected abstract IceSocketWrapper getIceSocketWrapper(); /** * Creates if necessary and returns a DatagramSocket that would @@ -74,49 +100,113 @@ public abstract class LocalCandidate * and receiving STUN packets, while harvesting STUN candidates or * performing connectivity checks. */ - public DatagramSocket getStunSocket(TransportAddress serverAddress) + public IceSocketWrapper getStunSocket(TransportAddress serverAddress) { - DatagramSocket hostSocket = getSocket(); - DatagramSocket stunSocket = null; + IceSocketWrapper hostSocket = getIceSocketWrapper(); - if (hostSocket instanceof MultiplexingDatagramSocket) + if(hostSocket.getTCPSocket() != null) { - DatagramPacketFilter stunDatagramPacketFilter - = createStunDatagramPacketFilter(serverAddress); - Throwable exception = null; + Socket tcpSocket = hostSocket.getTCPSocket(); + Socket tcpStunSocket = null; - try + if (tcpSocket instanceof MultiplexingSocket) { - stunSocket - = ((MultiplexingDatagramSocket) hostSocket) - .getSocket(stunDatagramPacketFilter); + DatagramPacketFilter stunDatagramPacketFilter + = createStunDatagramPacketFilter(serverAddress); + Throwable exception = null; + + try + { + tcpStunSocket + = ((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); + } } - catch (SocketException sex) //don't u just luv da name? ;) - { - logger.log(Level.SEVERE, - "Failed to acquire DatagramSocket" - + " specific to STUN communication.", - sex); - exception = sex; - } - if (stunSocket == null) + else { throw new IllegalStateException( - "Failed to acquire DatagramSocket" - + " specific to STUN communication", - exception); + "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 + else if(hostSocket.getUDPSocket() != null) { - throw - new IllegalStateException( - "The socket of " - + getClass().getSimpleName() - + " must be a MultiplexingDatagramSocket instance"); + DatagramSocket udpSocket = hostSocket.getUDPSocket(); + DatagramSocket udpStunSocket = null; + + if (udpSocket instanceof MultiplexingDatagramSocket) + { + DatagramPacketFilter stunDatagramPacketFilter + = createStunDatagramPacketFilter(serverAddress); + Throwable exception = null; + + try + { + udpStunSocket + = ((MultiplexingDatagramSocket) udpSocket) + .getSocket(stunDatagramPacketFilter); + } + catch (SocketException sex) //don't u just luv da name? ;) + { + logger.log(Level.SEVERE, + "Failed to acquire DatagramSocket" + + " specific to STUN communication.", + sex); + exception = sex; + } + if (udpStunSocket == null) + { + throw + new IllegalStateException( + "Failed to acquire DatagramSocket" + + " specific to STUN communication", + exception); + } + } + else + { + throw + new IllegalStateException( + "The socket of " + + getClass().getSimpleName() + + " must be a MultiplexingDatagramSocket " + + "instance"); + } + return new IceUdpSocketWrapper(udpStunSocket); } - return stunSocket; + + return null; } /** @@ -159,7 +249,7 @@ public abstract class LocalCandidate protected void free() { // Close the socket associated with this LocalCandidate. - DatagramSocket socket = getSocket(); + IceSocketWrapper socket = getIceSocketWrapper(); if (socket != null) { @@ -167,7 +257,7 @@ public abstract class LocalCandidate if ((base == null) || (base == this) - || (base.getSocket() != socket)) + || (base.getIceSocketWrapper() != socket)) { //remove our socket from the stack. getStunStack().removeSocket(getTransportAddress()); diff --git a/src/org/ice4j/ice/PeerReflexiveCandidate.java b/src/org/ice4j/ice/PeerReflexiveCandidate.java index 8bf3b92..1f0983a 100644 --- a/src/org/ice4j/ice/PeerReflexiveCandidate.java +++ b/src/org/ice4j/ice/PeerReflexiveCandidate.java @@ -6,9 +6,8 @@ */ package org.ice4j.ice; -import java.net.*; - import org.ice4j.*; +import org.ice4j.socket.*; /** * Peer Reflexive Candidates are candidates whose IP address and port are a @@ -55,10 +54,10 @@ public class PeerReflexiveCandidate * * @return the DatagramSocket associated with this * Candidate - * @see LocalCandidate#getSocket() + * @see LocalCandidate#getIceSocketWrapper() */ - public DatagramSocket getSocket() + public IceSocketWrapper getIceSocketWrapper() { - return getBase().getSocket(); + return getBase().getIceSocketWrapper(); } } diff --git a/src/org/ice4j/ice/RelayedCandidate.java b/src/org/ice4j/ice/RelayedCandidate.java index 616c503..4b724db 100644 --- a/src/org/ice4j/ice/RelayedCandidate.java +++ b/src/org/ice4j/ice/RelayedCandidate.java @@ -36,7 +36,7 @@ public class RelayedCandidate * The application-purposed DatagramSocket associated with this * Candidate. */ - private DatagramSocket socket; + private IceSocketWrapper socket; /** * The TurnCandidateHarvest which has harvested this @@ -114,17 +114,17 @@ public class RelayedCandidate * * @return the DatagramSocket associated with this * Candidate - * @see LocalCandidate#getSocket() + * @see LocalCandidate#getIceSocketWrapper() */ - public synchronized DatagramSocket getSocket() + public synchronized IceSocketWrapper getIceSocketWrapper() { if (socket == null) { try { socket - = new MultiplexingDatagramSocket( - getRelayedCandidateDatagramSocket()); + = new IceUdpSocketWrapper(new MultiplexingDatagramSocket( + getRelayedCandidateDatagramSocket())); } catch (SocketException sex) { diff --git a/src/org/ice4j/ice/ServerReflexiveCandidate.java b/src/org/ice4j/ice/ServerReflexiveCandidate.java index 5b13a41..8fd34cb 100644 --- a/src/org/ice4j/ice/ServerReflexiveCandidate.java +++ b/src/org/ice4j/ice/ServerReflexiveCandidate.java @@ -7,9 +7,8 @@ */ package org.ice4j.ice; -import java.net.*; - import org.ice4j.*; +import org.ice4j.socket.*; /** * ServerReflexiveCandidates are candidates whose IP address and port @@ -56,10 +55,10 @@ public class ServerReflexiveCandidate * * @return the DatagramSocket associated with this * Candidate - * @see LocalCandidate#getSocket() + * @see LocalCandidate#getIceSocketWrapper() */ - public DatagramSocket getSocket() + public IceSocketWrapper getIceSocketWrapper() { - return getBase().getSocket(); + return getBase().getIceSocketWrapper(); } } diff --git a/src/org/ice4j/ice/UPNPCandidate.java b/src/org/ice4j/ice/UPNPCandidate.java index 9ce429f..d06c303 100644 --- a/src/org/ice4j/ice/UPNPCandidate.java +++ b/src/org/ice4j/ice/UPNPCandidate.java @@ -7,9 +7,8 @@ */ package org.ice4j.ice; -import java.net.*; - import org.ice4j.*; +import org.ice4j.socket.*; import org.bitlet.weupnp.*; @@ -67,7 +66,7 @@ public class UPNPCandidate { } - DatagramSocket socket = getSocket(); + IceSocketWrapper socket = getIceSocketWrapper(); if(socket != null) { socket.close(); @@ -83,8 +82,8 @@ public class UPNPCandidate * Candidate */ @Override - public DatagramSocket getSocket() + public IceSocketWrapper getIceSocketWrapper() { - return getBase().getSocket(); + return getBase().getIceSocketWrapper(); } } diff --git a/src/org/ice4j/ice/harvest/GoogleTurnCandidateHarvest.java b/src/org/ice4j/ice/harvest/GoogleTurnCandidateHarvest.java index c3f374b..a5a0633 100644 --- a/src/org/ice4j/ice/harvest/GoogleTurnCandidateHarvest.java +++ b/src/org/ice4j/ice/harvest/GoogleTurnCandidateHarvest.java @@ -90,6 +90,15 @@ public class GoogleTurnCandidateHarvest { TransportAddress relayedAddress = ((MappedAddressAttribute) attribute).getAddress(); + + if(harvester.stunServer.getTransport() == Transport.TCP) + { + relayedAddress = new TransportAddress( + relayedAddress.getAddress(), + harvester.stunServer.getPort(), + //relayedAddress.getPort() - 1, + Transport.TCP); + } GoogleRelayedCandidate relayedCandidate = createRelayedCandidate( relayedAddress, @@ -256,34 +265,6 @@ public class GoogleTurnCandidateHarvest SEND_KEEP_ALIVE_MESSAGE_INTERVAL_NOT_SPECIFIED); } - /** - * Sends a specific Request on behalf of a specific - * RelayedCandidateDatagramSocket to the TURN server associated - * with this GoogleTurnCandidateHarvest. - * - * @param relayedCandidateDatagramSocket the - * RelayedCandidateDatagramSocket which sends the specified - * Request and which is to be notified of the result - * @param request the Request to be sent to the TURN server - * associated with this TurnCandidateHarvest - * @return an array of bytes which represents the ID of the - * transaction with which the specified Request has been sent to - * the TURN server - * @throws StunException if anything goes wrong while sending the specified - * Request - */ - 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 StunCandidateHarvest that a specific * Request has either received an error Response or has @@ -317,10 +298,15 @@ public class GoogleTurnCandidateHarvest */ 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) + .processErrorOrFailure(response, request)) + return true; return super.processErrorOrFailure(response, request, transactionID); } @@ -381,9 +367,14 @@ public class GoogleTurnCandidateHarvest */ 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); } } diff --git a/src/org/ice4j/ice/harvest/GoogleTurnCandidateHarvester.java b/src/org/ice4j/ice/harvest/GoogleTurnCandidateHarvester.java index 015a102..8b37c89 100644 --- a/src/org/ice4j/ice/harvest/GoogleTurnCandidateHarvester.java +++ b/src/org/ice4j/ice/harvest/GoogleTurnCandidateHarvester.java @@ -21,7 +21,7 @@ public class GoogleTurnCandidateHarvester { /** * Initializes a new GoogleTurnCandidateHarvester instance which - * is to work with a specific GoogleTURN server. + * is to work with a specific Google TURN server. * * @param turnServer the TransportAddress of the TURN server the * new instance is to work with diff --git a/src/org/ice4j/ice/harvest/GoogleTurnSSLCandidateHarvester.java b/src/org/ice4j/ice/harvest/GoogleTurnSSLCandidateHarvester.java new file mode 100644 index 0000000..cda3022 --- /dev/null +++ b/src/org/ice4j/ice/harvest/GoogleTurnSSLCandidateHarvester.java @@ -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 CandidateHarvester which gathers Google TURN SSLTCP + * dialect Candidates 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 GoogleTurnSSLCandidateHarvester instance which + * is to work with a specific Google TURN server. + * + * @param turnServer the TransportAddress of the TURN server the + * new instance is to work with + */ + public GoogleTurnSSLCandidateHarvester(TransportAddress turnServer) + { + this(turnServer, null); + } + + /** + * Initializes a new GoogleTurnSSLCandidateHarvester 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 TransportAddress 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 + * null 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 GoogleTurnSSLCandidateHarvest instance which is to + * perform TURN harvesting of a specific HostCandidate. + * + * @param hostCandidate the HostCandidate for which harvesting is + * to be performed by the new TurnCandidateHarvest instance + * @return a new GoogleTurnSSLCandidateHarvest instance which is to + * perform TURN harvesting of the specified hostCandidate + * @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; + } +} diff --git a/src/org/ice4j/ice/harvest/HostCandidateHarvester.java b/src/org/ice4j/ice/harvest/HostCandidateHarvester.java index 69db97c..15df60e 100644 --- a/src/org/ice4j/ice/harvest/HostCandidateHarvester.java +++ b/src/org/ice4j/ice/harvest/HostCandidateHarvester.java @@ -47,24 +47,32 @@ public class HostCandidateHarvester * @param minPort the port number where we should first try to bind before * moving to the next one (i.e. minPort + 1) * @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 minPort or - * maxPort is not a valid port number or if minPort > - * maxPort. + * maxPort is not a valid port number, minPort > + * maxPort or if transport is not supported. * @throws IOException if an error occurs while the underlying resolver lib * is using sockets. */ public void harvest(Component component, int preferredPort, int minPort, - int maxPort) + int maxPort, + Transport transport) throws IllegalArgumentException, IOException { Enumeration interfaces = NetworkInterface.getNetworkInterfaces(); + if(transport != Transport.UDP && transport != Transport.TCP) + { + throw new IllegalArgumentException( + "Transport protocol not supported: " + transport); + } + boolean boundAtLeastOneSocket = false; while (interfaces.hasMoreElements()) { @@ -83,12 +91,23 @@ public class HostCandidateHarvester { InetAddress addr = addresses.nextElement(); - DatagramSocket sock; + IceSocketWrapper sock = null; try { - sock = createDatagramSocket( - addr, preferredPort, minPort, maxPort); - boundAtLeastOneSocket = true; + if(transport == Transport.UDP) + { + sock = createDatagramSocket( + addr, preferredPort, minPort, maxPort); + boundAtLeastOneSocket = true; + } + else if(transport == Transport.TCP) + { + if(addr instanceof Inet6Address) + continue; + sock = createServerSocket(addr, preferredPort, minPort, + maxPort, component); + boundAtLeastOneSocket = true; + } } catch(IOException exc) { @@ -102,15 +121,25 @@ public class HostCandidateHarvester +"\npreferredPort:" + preferredPort +"\nminPort:" + minPort +"\nmaxPort:" + maxPort + +"\nprotocol:" + transport +"\nContinuing with next address"); } continue; } - HostCandidate candidate = new HostCandidate(sock, component); + HostCandidate candidate = new HostCandidate(sock, component, + transport); candidate.setVirtual(NetworkUtils.isInterfaceVirtual(iface)); 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 //for sending and receiving STUN connectivity checks. In case //we have enabled STUN, we are going to use them as well while @@ -130,6 +159,105 @@ public class HostCandidateHarvester } } + /** + * Creates a ServerSocket and binds it to the specified + * localAddress and a port in the range specified by the + * minPort and maxPort 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. minPort + 1) + * @param maxPort the maximum port number where we should try binding + * before giving up and throwinG an exception. + * + * @return the newly created DatagramSocket. + * + * @throws IllegalArgumentException if either minPort or + * maxPort is not a valid port number or if minPort > + * maxPort. + * @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 + * minPort and maxPort 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 DatagramSocket and binds it to the specified * localAddress and a port in the range specified by the @@ -160,7 +288,7 @@ public class HostCandidateHarvester * minPort and maxPort before reaching the maximum allowed * number of retries. */ - private DatagramSocket createDatagramSocket(InetAddress laddr, + private IceSocketWrapper createDatagramSocket(InetAddress laddr, int preferredPort, int minPort, int maxPort) @@ -202,8 +330,9 @@ public class HostCandidateHarvester { try { - DatagramSocket sock - = new MultiplexingDatagramSocket(port, laddr); + IceSocketWrapper sock + = new IceUdpSocketWrapper(new + MultiplexingDatagramSocket(port, laddr)); if(logger.isLoggable(Level.FINEST)) { @@ -231,7 +360,7 @@ public class HostCandidateHarvester } throw new BindException("Could not bind to any port between " - + minPort + " and " + (port -1)); + + minPort + " and " + (port - 1)); } /** @@ -246,7 +375,7 @@ public class HostCandidateHarvester */ private void createAndRegisterStunSocket(HostCandidate candidate) { - DatagramSocket stunSocket = candidate.getStunSocket(null); + IceSocketWrapper stunSocket = candidate.getStunSocket(null); candidate.getStunStack().addSocket(stunSocket); } diff --git a/src/org/ice4j/ice/harvest/StunCandidateHarvester.java b/src/org/ice4j/ice/harvest/StunCandidateHarvester.java index a698496..b37e425 100644 --- a/src/org/ice4j/ice/harvest/StunCandidateHarvester.java +++ b/src/org/ice4j/ice/harvest/StunCandidateHarvester.java @@ -7,12 +7,14 @@ */ package org.ice4j.ice.harvest; +import java.net.*; import java.util.*; import java.util.logging.*; import org.ice4j.*; import org.ice4j.ice.*; import org.ice4j.security.*; +import org.ice4j.socket.*; import org.ice4j.stack.*; /** @@ -217,7 +219,8 @@ public class StunCandidateHarvester stunStack = component.getParentStream().getParentAgent().getStunStack(); for (Candidate cand : component.getLocalCandidates()) - if (cand instanceof HostCandidate) + if (cand instanceof HostCandidate && + cand.getTransport() == stunServer.getTransport()) startResolvingCandidate((HostCandidate) cand); waitForResolutionEnd(); @@ -260,7 +263,12 @@ public class StunCandidateHarvester if (!hostCand.getTransportAddress().canReach(stunServer)) return; - StunCandidateHarvest harvest = createHarvest(hostCand); + HostCandidate cand = getHostCandidate(hostCand); + + if(cand == null) + return; + + StunCandidateHarvest harvest = createHarvest(cand); if (harvest == null) return; @@ -335,4 +343,47 @@ public class StunCandidateHarvester : "STUN"; 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; + } } diff --git a/src/org/ice4j/ice/harvest/UPNPHarvester.java b/src/org/ice4j/ice/harvest/UPNPHarvester.java index 41f5420..62a4437 100644 --- a/src/org/ice4j/ice/harvest/UPNPHarvester.java +++ b/src/org/ice4j/ice/harvest/UPNPHarvester.java @@ -130,8 +130,8 @@ public class UPNPHarvester String externalIPAddress = device.getExternalIPAddress(); PortMappingEntry portMapping = new PortMappingEntry(); - MultiplexingDatagramSocket socket = - new MultiplexingDatagramSocket(0, localAddress); + IceSocketWrapper socket = new IceUdpSocketWrapper( + new MultiplexingDatagramSocket(0, localAddress)); int port = socket.getLocalPort(); int externalPort = socket.getLocalPort(); @@ -199,7 +199,7 @@ public class UPNPHarvester * represents the specified TransportAddress * @throws Exception if something goes wrong during candidate creation */ - public List createUPNPCandidate(DatagramSocket socket, + public List createUPNPCandidate(IceSocketWrapper socket, InetAddress localAddr, String externalIP, int port, Component cmp, GatewayDevice device) throws Exception @@ -211,7 +211,7 @@ public class UPNPHarvester HostCandidate base = new HostCandidate(socket, cmp); UPNPCandidate candidate = new UPNPCandidate(addr, base, cmp, device); - DatagramSocket stunSocket = candidate.getStunSocket(null); + IceSocketWrapper stunSocket = candidate.getStunSocket(null); candidate.getStunStack().addSocket(stunSocket); ret.add(candidate); diff --git a/src/org/ice4j/message/Message.java b/src/org/ice4j/message/Message.java index f25ca2f..3e434aa 100644 --- a/src/org/ice4j/message/Message.java +++ b/src/org/ice4j/message/Message.java @@ -452,6 +452,24 @@ public abstract class Message 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 * 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 validateAttributePresentity(); + final char dataLength; if(stunStack.getCompatibilityMode() == CompatibilityMode.GTALK) { /* Google Talk will return error response if it sees unknown @@ -804,15 +823,20 @@ public abstract class Message if(getAttribute(Attribute.FINGERPRINT) != null) removeAttribute(Attribute.FINGERPRINT); + + dataLength = getDataLengthWithoutPadding(); + } + else + { + dataLength = getDataLength(); } - final char dataLength = getDataLength(); byte binMsg[] = new byte[HEADER_LENGTH + dataLength]; int offset = 0; // STUN Message Type - binMsg[offset++] = (byte)(getMessageType()>>8); - binMsg[offset++] = (byte)(getMessageType()&0xFF); + binMsg[offset++] = (byte)(getMessageType() >> 8); + binMsg[offset++] = (byte)(getMessageType() & 0xFF); // Message Length final int messageLengthOffset = offset; @@ -825,17 +849,15 @@ public abstract class Message { System.arraycopy(MAGIC_COOKIE, 0, binMsg, offset, 4); offset += 4; - System.arraycopy(tranID, 0, binMsg, offset, - TRANSACTION_ID_LENGTH); + System.arraycopy(tranID, 0, binMsg, offset, TRANSACTION_ID_LENGTH); offset += TRANSACTION_ID_LENGTH; } else { /* RFC3489 behavior */ System.arraycopy(tranID, 0, binMsg, offset, - RFC3489_TRANSACTION_ID_LENGTH); + RFC3489_TRANSACTION_ID_LENGTH); offset += RFC3489_TRANSACTION_ID_LENGTH; - } Iterator> iter diff --git a/src/org/ice4j/message/MessageFactory.java b/src/org/ice4j/message/MessageFactory.java index 4fe78c7..0d700a7 100644 --- a/src/org/ice4j/message/MessageFactory.java +++ b/src/org/ice4j/message/MessageFactory.java @@ -658,7 +658,7 @@ public class MessageFactory if (data != null && data.length > 0) { DataAttribute dataAttribute = AttributeFactory - .createDataAttribute(data); + .createDataAttributeWithoutPadding(data); sendRequest.addAttribute(dataAttribute); } } diff --git a/src/org/ice4j/socket/DelegatingSocket.java b/src/org/ice4j/socket/DelegatingSocket.java new file mode 100644 index 0000000..39dfa9f --- /dev/null +++ b/src/org/ice4j/socket/DelegatingSocket.java @@ -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 Socket which delegates its calls to a specific + * Socket. + * + * @author Sebastien Vincent + */ +public class DelegatingSocket + extends Socket +{ + /** + * Delegate Socket. + */ + protected final Socket delegate; + + /** + * InputStream for this socket. + */ + private InputStream inputStream = null; + + /** + * OutputStream for this socket. + */ + private OutputStream outputStream = null; + + /** + * Initializes a new DelegatingSocket. + */ + public DelegatingSocket() + { + delegate = null; + } + + /** + * Initializes a new DelegatingSocket. + * + * @see Socket#Socket(InetAddress, int) + */ + public DelegatingSocket(InetAddress address, int port) + throws IOException + { + delegate = null; + } + + /** + * Initializes a new DelegatingSocket. + * + * @see Socket#Socket(InetAddress, int, InetAddress, int) + */ + public DelegatingSocket(InetAddress address, int port, + InetAddress localAddr, int localPort) + throws IOException + { + delegate = null; + } + + /** + * Initializes a new DelegatingSocket. + * + * @see Socket#Socket(Proxy) + */ + public DelegatingSocket(Proxy proxy) + { + delegate = null; + } + + /** + * Initializes a new DelegatingSocket. + * + * @see Socket#Socket(SocketImpl) + */ + protected DelegatingSocket(SocketImpl impl) + throws SocketException + { + delegate = null; + } + + /** + * Initializes a new DelegatingSocket. + * + * @see Socket#Socket(String, int) + */ + public DelegatingSocket(String host, int port) + throws UnknownHostException, + IOException + { + delegate = null; + } + + /** + * Initializes a new DelegatingSocket. + * + * @see Socket#Socket(String, int, InetAddress, int) + */ + public DelegatingSocket(String host, int port, InetAddress localAddr, + int localPort) + { + delegate = null; + } + + /** + * Initializes a new DelegatingSocket. + * + * @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 DatagramPacket 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 DatagramPackets + * returned by this method do not match any of the + * DatagramPacketFilters of the MultiplexedSockets + * associated with this instance at the time of their receipt. When this + * method returns, the DatagramPacket'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. + *

+ * This method blocks until a datagram is received. The length + * 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. + *

+ * + * @param p the DatagramPacket 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 InputStream. + * + * @param inputStream InputStream + */ + public void setOriginalInputStream(InputStream inputStream) + { + if(this.inputStream == null && inputStream != null) + this.inputStream = inputStream; + } +} diff --git a/src/org/ice4j/socket/GoogleRelayedCandidateDatagramSocket.java b/src/org/ice4j/socket/GoogleRelayedCandidateDatagramSocket.java index c471dcf..8412296 100644 --- a/src/org/ice4j/socket/GoogleRelayedCandidateDatagramSocket.java +++ b/src/org/ice4j/socket/GoogleRelayedCandidateDatagramSocket.java @@ -9,15 +9,12 @@ 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.*; import org.ice4j.ice.harvest.*; import org.ice4j.message.*; -import org.ice4j.stack.*; /** * Represents an application-purposed (as opposed to an ICE-specific) @@ -33,8 +30,6 @@ import org.ice4j.stack.*; */ public class GoogleRelayedCandidateDatagramSocket extends DatagramSocket - implements MessageEventHandler, - ResponseCollector { /** * The Logger used by the @@ -51,36 +46,12 @@ public class GoogleRelayedCandidateDatagramSocket */ private boolean closed = false; - /** - * The DatagramPackets which are to be received through this - * DatagramSocket 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 packetsToReceive - = new LinkedList(); - - /** - * The DatagramSockets which have been sent through this - * DatagramSocket 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 packetsToSend - = new LinkedList(); - /** * The GoogleRelayedCandidate which uses this instance as the value * of its socket property. */ private final GoogleRelayedCandidate relayedCandidate; - /** - * The Thread which is to send the {@link #packetsToSend} to the - * associated TURN server. - */ - private Thread sendThread; - /** * The GoogleTurnCandidateHarvest which has harvested * {@link #relayedCandidate}. @@ -88,9 +59,10 @@ public class GoogleRelayedCandidateDatagramSocket private final GoogleTurnCandidateHarvest turnCandidateHarvest; /** - * Username. + * The GoogleTurnCandidateDelegage which will handle send/receive + * operations. */ - private final String username; + private final GoogleRelayedCandidateDelegate socketDelegate; /** * Initializes a new GoogleRelayedCandidateDatagramSocket instance @@ -114,17 +86,12 @@ public class GoogleRelayedCandidateDatagramSocket { super(/* bindaddr */ (SocketAddress) null); + socketDelegate = new GoogleRelayedCandidateDelegate( + turnCandidateHarvest, username); this.relayedCandidate = relayedCandidate; this.turnCandidateHarvest = turnCandidateHarvest; - this.username = username; - this.turnCandidateHarvest - .harvester - .getStunStack() - .addOldIndicationListener( - this.turnCandidateHarvest.hostCandidate - .getTransportAddress(), - this); + logger.finest("Create new GoogleRelayedCandidateDatagramSocket"); } /** @@ -142,17 +109,8 @@ public class GoogleRelayedCandidateDatagramSocket else this.closed = true; } - synchronized (packetsToReceive) - { - packetsToReceive.notifyAll(); - } - synchronized (packetsToSend) - { - packetsToSend.notifyAll(); - } - turnCandidateHarvest.harvester.getStunStack().removeIndicationListener( - turnCandidateHarvest.hostCandidate.getTransportAddress(), - this); + + socketDelegate.close(); turnCandidateHarvest.close(this); } @@ -224,107 +182,6 @@ public class GoogleRelayedCandidateDatagramSocket return relayedCandidate; } - /** - * Notifies this MessageEventHandler that a specific STUN message - * has been received, parsed and is ready for delivery. - * GoogleRelayedCandidateDatagramSocket handles STUN indications sent - * from the associated TURN server and received at the associated local - * TransportAddress. - * - * @param e a StunMessageEvent 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 GoogleRelayedCandidateDatagramSocket that a - * specific Request it has sent has either failed or received a - * STUN error Response. - * - * @param response the Response which responds to request - * @param request the Request sent by this instance to which - * response responds - * @return true if the failure or error condition has been handled - * and the caller should assume this instance has recovered from it; - * otherwise, false - */ - public boolean processErrorOrFailure(Response response, Request request) - { - return false; - } - /** * Notifies this GoogleRelayedCandidateDatagramSocket that a * specific Request it has sent has received a STUN success @@ -336,6 +193,7 @@ public class GoogleRelayedCandidateDatagramSocket */ public void processSuccess(Response response, Request request) { + socketDelegate.processSuccess(response, request); } /** @@ -345,19 +203,7 @@ public class GoogleRelayedCandidateDatagramSocket */ 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 StunTimeoutEvent containing a reference to the - * transaction that has just failed. - */ - public void processTimeout(StunTimeoutEvent event) - { + socketDelegate.processResponse(response); } /** @@ -375,44 +221,7 @@ public class GoogleRelayedCandidateDatagramSocket 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; - } - } - } + socketDelegate.receive(p); } /** @@ -428,150 +237,6 @@ public class GoogleRelayedCandidateDatagramSocket 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) - { - } - } - } - } + socketDelegate.send(p); } } \ No newline at end of file diff --git a/src/org/ice4j/socket/GoogleRelayedCandidateDelegate.java b/src/org/ice4j/socket/GoogleRelayedCandidateDelegate.java new file mode 100644 index 0000000..0a4b20b --- /dev/null +++ b/src/org/ice4j/socket/GoogleRelayedCandidateDelegate.java @@ -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 Logger used by the + * GoogleRelayedCandidateDatagramSocket 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 DatagramPackets which are to be received through this + * DatagramSocket 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 packetsToReceive = + new LinkedList(); + + /** + * The DatagramSockets which have been sent through this + * DatagramSocket 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 packetsToSend = + new LinkedList(); + + /** + * The Thread which is to send the {@link #packetsToSend} to the + * associated TURN server. + */ + private Thread sendThread; + + /** + * The GoogleTurnCandidateHarvest which has harvested + * {@link #relayedCandidate}. + */ + private final GoogleTurnCandidateHarvest turnCandidateHarvest; + + /** + * Username. + */ + private final String username; + + /** + * Initializes a new GoogleRelayedCandidateDatagramSocket instance + * which is to be the socket of a specific + * RelayedCandidate harvested by a specific + * TurnCandidateHarvest. + * + * @param turnCandidateHarvest the TurnCandidateHarvest which has + * harvested relayedCandidate + * @param username username + * @throws SocketException if anything goes wrong while initializing the new + * GoogleRelayedCandidateDatagramSocket 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 MessageEventHandler that a specific STUN message + * has been received, parsed and is ready for delivery. + * GoogleRelayedCandidateDatagramSocket handles STUN indications + * sent from the associated TURN server and received at the associated local + * TransportAddress. + * + * @param e a StunMessageEvent 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 GoogleRelayedCandidateDatagramSocket that a + * specific Request it has sent has either failed or received a + * STUN error Response. + * + * @param response the Response which responds to request + * @param request the Request sent by this instance to which + * response responds + * @return true if the failure or error condition has been handled + * and the caller should assume this instance has recovered from it; + * otherwise, false + */ + public boolean processErrorOrFailure(Response response, Request request) + { + return false; + } + + /** + * Notifies this GoogleRelayedCandidateDatagramSocket that a + * specific Request it has sent has received a STUN success + * Response. + * + * @param response the Response which responds to request + * @param request the Request sent by this instance to which + * response 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 StunTimeoutEvent 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 DatagramPacket'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 DatagramPacket 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 DatagramPacket + * 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 DatagramPacket 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) + { + } + } + } + } + } +} diff --git a/src/org/ice4j/socket/GoogleRelayedCandidateSocket.java b/src/org/ice4j/socket/GoogleRelayedCandidateSocket.java new file mode 100644 index 0000000..7b69824 --- /dev/null +++ b/src/org/ice4j/socket/GoogleRelayedCandidateSocket.java @@ -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) + * Socket for a RelayedCandidate harvested by a + * TurnCandidateHarvest (and its associated + * TurnCandidateHarvester, of course). + * GoogleRelayedCandidateSocket 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 Logger used by the + * GoogleRelayedCandidateSocket 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 GoogleRelayedCandidate which uses this instance as the value + * of its socket property. + */ + private final GoogleRelayedCandidate relayedCandidate; + + /** + * The GoogleTurnCandidateDelegage which will handle send/receive + * operations. + */ + private final GoogleRelayedCandidateDelegate socketDelegate; + + /** + * The OutputStream. + */ + private TCPOutputStream outputStream = null; + + /** + * Initializes a new GoogleRelayedCandidateSocket instance + * which is to be the socket of a specific + * RelayedCandidate harvested by a specific + * TurnCandidateHarvest. + * + * @param relayedCandidate the RelayedCandidate which is to use the + * new instance as the value of its socket property + * @param turnCandidateHarvest the TurnCandidateHarvest which has + * harvested relayedCandidate + * @param username username + * @throws SocketException if anything goes wrong while initializing the new + * GoogleRelayedCandidateSocket 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. + * GoogleRelayedCandidateSocket returns the + * address of its localSocketAddress. + *

+ * If there is a security manager, its checkConnect method is first + * called with the host address and -1 as its arguments to see if + * the operation is allowed. + *

+ * + * @return the local address to which the socket is bound, or an + * InetAddress representing any local address if either the socket + * is not bound, or the security manager checkConnect 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. + * GoogleRelayedCandidateSocket returns the port + * of its localSocketAddress. + * + * @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 + * null if it is not bound yet. Since + * GoogleRelayedCandidateSocket represents an + * application-purposed Socket relaying data to and from a + * TURN server, the localSocketAddress is the + * transportAddress of the respective RelayedCandidate. + * + * @return a SocketAddress representing the local endpoint of this + * socket, or null if it is not bound yet + * @see Socket#getLocalSocketAddress() + */ + @Override + public InetSocketAddress getLocalSocketAddress() + { + return getRelayedCandidate().getTransportAddress(); + } + + /** + * Gets the RelayedCandidate which uses this instance as the value + * of its socket property. + * + * @return the RelayedCandidate which uses this instance as the + * value of its socket property + */ + public final GoogleRelayedCandidate getRelayedCandidate() + { + return relayedCandidate; + } + + /** + * Notifies this GoogleRelayedCandidateSocket that a + * specific Request it has sent has received a STUN success + * Response. + * + * @param response the Response which responds to request + * @param request the Request sent by this instance to which + * response 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 DatagramPacket'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 DatagramPacket 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 DatagramPacket + * 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 DatagramPacket 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 OutputStream interface to users. + * + * @author Sebastien Vincent + */ + private class TCPOutputStream + extends OutputStream + { + /** + * Target transport address. + */ + private final TransportAddress target; + + /** + * Initializes a new TCPOutputStream. + * + * @param target TransportAddress + */ + 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 + } + } +} \ No newline at end of file diff --git a/src/org/ice4j/socket/IceSocketWrapper.java b/src/org/ice4j/socket/IceSocketWrapper.java new file mode 100644 index 0000000..17897f4 --- /dev/null +++ b/src/org/ice4j/socket/IceSocketWrapper.java @@ -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 DatagramPacket 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 OutputStream and do stuff with it. + * + * + * @param p DatagramPacket to sent + * @throws IOException if something goes wrong + */ + public abstract void send(DatagramPacket p) + throws IOException; + + /** + * Receives a DatagramPacket 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 InputStream and do stuff with it. + * + * @param p DatagramPacket + * @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(); +} diff --git a/src/org/ice4j/socket/IceTcpServerSocketWrapper.java b/src/org/ice4j/socket/IceTcpServerSocketWrapper.java new file mode 100644 index 0000000..86c50bb --- /dev/null +++ b/src/org/ice4j/socket/IceTcpServerSocketWrapper.java @@ -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 Logger used by the LocalCandidate 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 sockets = new ArrayList(); + + /** + * Initializes a new IceTcpServerSocketWrapper. + * + * @param serverSocket TCP ServerSocket + * @param component related Component + */ + 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); + } + } + } + } +} diff --git a/src/org/ice4j/socket/IceTcpSocketWrapper.java b/src/org/ice4j/socket/IceTcpSocketWrapper.java new file mode 100644 index 0000000..48a5dbf --- /dev/null +++ b/src/org/ice4j/socket/IceTcpSocketWrapper.java @@ -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 IceSocketWrapper. + * + * @author Sebastien Vincent + */ +public class IceTcpSocketWrapper + extends IceSocketWrapper +{ + /** + * Delegate TCP Socket. + */ + private final Socket socket; + + /** + * InputStream for this socket. + */ + private InputStream inputStream = null; + + /** + * OutputStream for this socket. + */ + private OutputStream outputStream = null; + + /** + * Constructor. + * + * @param delegate delegate Socket + * + * @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; + } +} diff --git a/src/org/ice4j/socket/IceUdpSocketWrapper.java b/src/org/ice4j/socket/IceUdpSocketWrapper.java new file mode 100644 index 0000000..c59fa4b --- /dev/null +++ b/src/org/ice4j/socket/IceUdpSocketWrapper.java @@ -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 IceSocketWrapper. + * + * @author Sebastien Vincent + */ +public class IceUdpSocketWrapper + extends IceSocketWrapper +{ + /** + * Delegate UDP DatagramSocket. + */ + private final DatagramSocket socket; + + /** + * Constructor. + * + * @param delegate delegate DatagramSocket + */ + 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; + } +} diff --git a/src/org/ice4j/socket/MultiplexedSocket.java b/src/org/ice4j/socket/MultiplexedSocket.java new file mode 100644 index 0000000..560bd90 --- /dev/null +++ b/src/org/ice4j/socket/MultiplexedSocket.java @@ -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 Socket which receives DatagramPackets + * selected by a DatagramPacketFilter from a + * MultiplexingSocket. The associated + * MultiplexingSocket is the actual Socket + * which reads the DatagramPackets from the network. The + * DatagramPackets received through the + * MultiplexedSocket will not be received through the + * associated MultiplexingSocket. + * + * @author Sebastien Vincent + */ +public class MultiplexedSocket + extends DelegatingSocket +{ + /** + * The DatagramPacketFilter which determines which + * DatagramPackets read from the network by {@link #multiplexing} + * are to be received through this instance. + */ + private final DatagramPacketFilter filter; + + /** + * The MultiplexingSocket which does the actual reading + * from the network and which forwards DatagramPackets accepted by + * {@link #filter} for receipt to this instance. + */ + private final MultiplexingSocket multiplexing; + + /** + * The list of DatagramPackets to be received through this + * Socket i.e. accepted by {@link #filter}. + */ + final List received = new LinkedList(); + + /** + * Initializes a new MultiplexedSocket which is unbound and + * filters DatagramPackets away from a specific + * MultiplexingSocket using a specific + * DatagramPacketFilter. + * + * @param multiplexing the MultiplexingSocket which does + * the actual reading from the network and which forwards + * DatagramPackets accepted by the specified filter to the + * new instance + * @param filter the DatagramPacketFilter which determines which + * DatagramPackets read from the network by the specified + * multiplexing 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. + *

+ * Any thread currently blocked in {@link #receive(DatagramPacket)} upon + * this socket will throw a {@link SocketException}. + *

+ * + * @see Socket#close() + */ + @Override + public void close() + { + multiplexing.close(this); + } + + /** + * Gets the DatagramPacketFilter which determines which + * DatagramPackets read from the network are to be received through + * this Socket. + * + * @return the DatagramPacketFilter which determines which + * DatagramPackets read from the network are to be received through + * this Socket + */ + public DatagramPacketFilter getFilter() + { + return filter; + } + + /** + * Receives a datagram packet from this socket. When this method returns, + * the DatagramPacket'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. + *

+ * This method blocks until a datagram is received. The length + * 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. + *

+ * + * @param p the DatagramPacket 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); + } +} diff --git a/src/org/ice4j/socket/MultiplexingSocket.java b/src/org/ice4j/socket/MultiplexingSocket.java new file mode 100644 index 0000000..b6ae4b8 --- /dev/null +++ b/src/org/ice4j/socket/MultiplexingSocket.java @@ -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 Socket which allows filtering + * DatagramPackets it reads from the network using + * DatagramPacketFilters so that the DatagramPackets do not + * get received through it but through associated MultiplexedSockets. + * + * @author Sebastien Vincent + * @author Lyubomir Marinov + */ +public class MultiplexingSocket + extends DelegatingSocket +{ + /** + * The Logger used by the MultiplexingSocket 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 + * MultiplexedSocket element type. Explicitly defined in + * order to reduce allocations. + */ + private static final MultiplexedSocket[] NO_SOCKETS + = new MultiplexedSocket[0]; + + /** + * The indicator which determines whether this Socket is + * currently reading from the network using + * {@link #receive(DatagramPacket)}. When true, + * subsequent requests to read from the network will be blocked until the + * current read is finished. + */ + private boolean inReceive = false; + + /** + * The list of DatagramPackets to be received through this + * Socket i.e. not accepted by the DatagramFilters + * of {@link #sockets} at the time of the reading from the network. + */ + private final List received + = new LinkedList(); + + /** + * Custom InputStream for this Socket. + */ + private final TCPInputStream inputStream = new TCPInputStream(); + + /** + * The Object which synchronizes the access to {@link #inReceive}. + */ + private final Object receiveSyncRoot = new Object(); + + /** + * The MultiplexedSockets filtering DatagramPackets + * away from this Socket. + */ + private MultiplexedSocket[] sockets = NO_SOCKETS; + + /** + * The Object which synchronizes the access to the {@link #sockets} + * field of this instance. + */ + private final Object socketsSyncRoot = new Object(); + + /** + * Initializes a new MultiplexingSocket instance. + * + * @see Socket#Socket() + */ + public MultiplexingSocket() + { + super(); + try + { + setTcpNoDelay(true); + } + catch(SocketException e) + { + logger.info("Cannot SO_TCPNODELAY"); + } + } + + /** + * Initializes a new MultiplexingSocket 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 MultiplexingSocket 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 MultiplexingSocket 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 MultiplexingSocket 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 MultiplexingSocket 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 MultiplexingSocket 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 MultiplexingSocket 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 DatagramPackets + * returned by this method do not match any of the + * DatagramPacketFilters of the MultiplexedDatagramSockets + * associated with this instance at the time of their receipt. When this + * method returns, the DatagramPacket'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. + *

+ * This method blocks until a datagram is received. The length + * 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. + *

+ * + * @param p the DatagramPacket 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 DatagramPacket from this Socket upon + * request from a specific MultiplexedSocket. + * + * @param multiplexed the MultiplexedSocket which requests + * the receipt of a DatagramPacket from the network + * @param p the DatagramPacket 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 DatagramPacket from a specific list of + * DatagramPackets if it is not empty or from the network if the + * specified list is empty. When this method returns, the + * DatagramPacket'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 DatagramPacket + * from which the first is to be removed and returned if available + * @param p the DatagramPacket into which to place the incoming + * data + * @throws IOException if an I/O error occurs + */ + private void receive(List 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 MultiplexedSocket which filters + * DatagramPackets away from this Socket. + * + * @param multiplexed the MultiplexedSocket 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 MultiplexedDatagramSocket which filters + * DatagramPackets away from this DatagramSocket using a + * specific DatagramPacketFilter. If such a + * MultiplexedDatagramSocket does not exist in this instance, it is + * created. + * + * @param filter the DatagramPacketFilter to get a + * MultiplexedDatagramSocket for + * @return a MultiplexedDatagramSocket which filters + * DatagramPackets away from this DatagramSocket using the + * specified filter + * @throws SocketException if creating the + * MultiplexedDatagramSocket for the specified filter + * 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 DatagramPacket + */ + 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; + } +} diff --git a/src/org/ice4j/socket/RelayedCandidateDatagramSocket.java b/src/org/ice4j/socket/RelayedCandidateDatagramSocket.java index b84490d..870f644 100644 --- a/src/org/ice4j/socket/RelayedCandidateDatagramSocket.java +++ b/src/org/ice4j/socket/RelayedCandidateDatagramSocket.java @@ -200,7 +200,8 @@ public class RelayedCandidateDatagramSocket this); DatagramSocket hostSocket - = this.turnCandidateHarvest.hostCandidate.getSocket(); + = this.turnCandidateHarvest.hostCandidate.getIceSocketWrapper(). + getUDPSocket(); if (hostSocket instanceof MultiplexingDatagramSocket) { diff --git a/src/org/ice4j/socket/TCPInputStream.java b/src/org/ice4j/socket/TCPInputStream.java new file mode 100644 index 0000000..f44c333 --- /dev/null +++ b/src/org/ice4j/socket/TCPInputStream.java @@ -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 InputStream interface to users. + * + * @author Sebastien Vincent + */ +public class TCPInputStream + extends InputStream +{ + /** + * List of packets. + */ + private final List packets = new ArrayList(); + + /** + * 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 TCPInputStream. + */ + 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 InputStream. + * + * @param p packet bytes + */ + public void addPacket(byte[] p) + { + synchronized(packets) + { + this.packets.add(p); + packets.notifyAll(); + } + } +} diff --git a/src/org/ice4j/stack/Connector.java b/src/org/ice4j/stack/Connector.java index 8f0029d..b5d476b 100644 --- a/src/org/ice4j/stack/Connector.java +++ b/src/org/ice4j/stack/Connector.java @@ -11,6 +11,7 @@ import java.net.*; import java.util.logging.*; import org.ice4j.*; +import org.ice4j.socket.*; /** * 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. */ - private DatagramSocket sock; + private IceSocketWrapper sock; /** * 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 errorHandler the instance to notify when errors occur. */ - protected Connector(DatagramSocket socket, + protected Connector(IceSocketWrapper socket, MessageQueue messageQueue, ErrorHandler errorHandler) { @@ -76,7 +77,8 @@ class Connector this.messageQueue = messageQueue; this.errorHandler = errorHandler; 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 DatagramSocket associated with this AP. */ - protected DatagramSocket getSocket() + protected IceSocketWrapper getSocket() { return sock; } @@ -112,7 +114,7 @@ class Connector { try { - DatagramSocket localSock; + IceSocketWrapper localSock; synchronized (sockLock) { @@ -126,7 +128,17 @@ class Connector * Make sure localSock's receiveBufferSize is taken into * 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) { @@ -173,7 +185,7 @@ class Connector new TransportAddress( packet.getAddress(), packet.getPort(), - Transport.UDP), + listenAddress.getTransport()), listenAddress); messageQueue.add(rawMessage); diff --git a/src/org/ice4j/stack/NetAccessManager.java b/src/org/ice4j/stack/NetAccessManager.java index 08494cd..4e8810f 100644 --- a/src/org/ice4j/stack/NetAccessManager.java +++ b/src/org/ice4j/stack/NetAccessManager.java @@ -7,12 +7,12 @@ package org.ice4j.stack; import java.io.*; -import java.net.*; import java.util.*; import java.util.logging.*; import org.ice4j.*; import org.ice4j.message.*; +import org.ice4j.socket.*; /** * Manages Connectors and MessageProcessor pooling. This class @@ -33,10 +33,27 @@ class NetAccessManager = Logger.getLogger(NetAccessManager.class.getName()); /** - * All access points currently in use. The table maps - * TransportAddresses to Connectors + * All access points currently in use with UDP. The table maps + * TransportAddresses to Connectors. + * + * 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 netAccessPoints + private Map netUDPAccessPoints + = new Hashtable(); + + /** + * All access points currently in use with TCP. The table maps + * TransportAddresses to Connectors. + * + * 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 netTCPAccessPoints = new Hashtable(); /** @@ -153,13 +170,13 @@ class NetAccessManager //make sure nothing's left and notify user removeSocket(ap.getListenAddress()); - logger.log(Level.WARNING, "Removing connector:"+ ap, error); + logger.log(Level.WARNING, "Removing connector:" + ap, error); } else if( callingThread instanceof MessageProcessor ) { MessageProcessor mp = (MessageProcessor)callingThread; logger.log( Level.WARNING, "A message processor has unexpectedly " - +"stopped. AP:" + mp, error); + + "stopped. AP:" + mp, error); //make sure the guy's dead. mp.stop(); @@ -179,20 +196,31 @@ class NetAccessManager * * @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 TransportAddress localAddr = new TransportAddress( socket.getLocalAddress(), 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); - 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(); } } @@ -204,7 +232,16 @@ class NetAccessManager */ 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) ap.stop(); @@ -306,7 +343,16 @@ class NetAccessManager throws IOException, IllegalArgumentException { 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) { diff --git a/src/org/ice4j/stack/StunStack.java b/src/org/ice4j/stack/StunStack.java index 48a4fcd..a4489f5 100644 --- a/src/org/ice4j/stack/StunStack.java +++ b/src/org/ice4j/stack/StunStack.java @@ -19,6 +19,7 @@ import org.ice4j.attribute.*; import org.ice4j.ice.*; import org.ice4j.message.*; import org.ice4j.security.*; +import org.ice4j.socket.*; /** * 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. */ - public void addSocket(DatagramSocket sock) + public void addSocket(IceSocketWrapper sock) { netAccessManager.addSocket(sock); } diff --git a/src/org/ice4j/stunclient/NetworkConfigurationDiscoveryProcess.java b/src/org/ice4j/stunclient/NetworkConfigurationDiscoveryProcess.java index ebd1b5d..77d966a 100644 --- a/src/org/ice4j/stunclient/NetworkConfigurationDiscoveryProcess.java +++ b/src/org/ice4j/stunclient/NetworkConfigurationDiscoveryProcess.java @@ -7,7 +7,6 @@ package org.ice4j.stunclient; import java.io.*; -import java.net.*; import java.util.logging.*; import org.ice4j.*; @@ -113,7 +112,7 @@ public class NetworkConfigurationDiscoveryProcess * The DatagramSocket that we are going to be running the * discovery process through. */ - private DatagramSocket sock = null; + private IceSocketWrapper sock = null; /** * The StunStack used by this instance for the purposes of STUN @@ -165,7 +164,8 @@ public class NetworkConfigurationDiscoveryProcess public void start() throws IOException, StunException { - sock = new SafeCloseDatagramSocket(localAddress); + sock = new IceUdpSocketWrapper( + new SafeCloseDatagramSocket(localAddress)); stunStack.addSocket(sock); diff --git a/src/org/ice4j/stunclient/SimpleAddressDetector.java b/src/org/ice4j/stunclient/SimpleAddressDetector.java index 3e5776e..9f4837c 100644 --- a/src/org/ice4j/stunclient/SimpleAddressDetector.java +++ b/src/org/ice4j/stunclient/SimpleAddressDetector.java @@ -13,6 +13,7 @@ import java.util.logging.*; import org.ice4j.*; import org.ice4j.attribute.*; import org.ice4j.message.*; +import org.ice4j.socket.*; import org.ice4j.stack.*; /** @@ -86,7 +87,6 @@ public class SimpleAddressDetector stunStack = new StunStack(); } - /** * Creates a listening point for the specified socket and attempts to * discover how its local address is NAT mapped. @@ -97,7 +97,7 @@ public class SimpleAddressDetector * @throws IOException if something fails along the way. * @throws BindException if we cannot bind the socket. */ - public TransportAddress getMappingFor(DatagramSocket socket) + public TransportAddress getMappingFor(IceSocketWrapper socket) throws IOException, BindException { TransportAddress localAddress = new TransportAddress( diff --git a/test/org/ice4j/MessageEventDispatchingTest.java b/test/org/ice4j/MessageEventDispatchingTest.java index d9b0c99..68f2e58 100644 --- a/test/org/ice4j/MessageEventDispatchingTest.java +++ b/test/org/ice4j/MessageEventDispatchingTest.java @@ -48,17 +48,17 @@ public class MessageEventDispatchingTest extends TestCase /** * The socket that the client is using. */ - DatagramSocket clientSock = null; + IceSocketWrapper clientSock = null; /** * The socket that the server is using */ - DatagramSocket serverSock = null; + IceSocketWrapper serverSock = null; /** * The second server socket. */ - DatagramSocket serverSock2 = null; + IceSocketWrapper serverSock2 = null; /** * The request that we will be sending in this test. @@ -91,9 +91,12 @@ public class MessageEventDispatchingTest extends TestCase stunStack = new StunStack(); - clientSock = new SafeCloseDatagramSocket(clientAddress); - serverSock = new SafeCloseDatagramSocket(serverAddress); - serverSock2 = new SafeCloseDatagramSocket(serverAddress2); + clientSock = new IceUdpSocketWrapper( + new SafeCloseDatagramSocket(clientAddress)); + serverSock = new IceUdpSocketWrapper( + new SafeCloseDatagramSocket(serverAddress)); + serverSock2 = new IceUdpSocketWrapper( + new SafeCloseDatagramSocket(serverAddress2)); stunStack.addSocket(clientSock); stunStack.addSocket(serverSock); diff --git a/test/org/ice4j/TransactionSupportTests.java b/test/org/ice4j/TransactionSupportTests.java index bb7b267..0f285f9 100644 --- a/test/org/ice4j/TransactionSupportTests.java +++ b/test/org/ice4j/TransactionSupportTests.java @@ -6,7 +6,6 @@ */ package org.ice4j; -import java.net.*; import java.util.*; import junit.framework.*; @@ -39,12 +38,12 @@ public class TransactionSupportTests extends TestCase /** * The socket the client uses in this test. */ - DatagramSocket clientSock = null; + IceSocketWrapper clientSock = null; /** * The socket the server uses in this test. */ - DatagramSocket serverSock = null; + IceSocketWrapper serverSock = null; /** * The StunStack used by this TransactionSupportTests. @@ -81,8 +80,10 @@ public class TransactionSupportTests extends TestCase { super.setUp(); - clientSock = new SafeCloseDatagramSocket(clientAddress); - serverSock = new SafeCloseDatagramSocket(serverAddress); + clientSock = new IceUdpSocketWrapper( + new SafeCloseDatagramSocket(clientAddress)); + serverSock = new IceUdpSocketWrapper( + new SafeCloseDatagramSocket(serverAddress)); stunStack = new StunStack(); stunStack.addSocket(clientSock); diff --git a/test/org/ice4j/stack/ShallowStackTest.java b/test/org/ice4j/stack/ShallowStackTest.java index edaa12f..203fc43 100644 --- a/test/org/ice4j/stack/ShallowStackTest.java +++ b/test/org/ice4j/stack/ShallowStackTest.java @@ -41,7 +41,7 @@ public class ShallowStackTest extends TestCase private DatagramCollector dgramCollector = new DatagramCollector(); - private DatagramSocket localSock = null; + private IceSocketWrapper localSock = null; private DatagramSocket dummyServerSocket = null; @@ -77,7 +77,8 @@ public class ShallowStackTest extends TestCase stunStack = new StunStack(); //access point - localSock = new SafeCloseDatagramSocket(localAddress); + localSock = new IceUdpSocketWrapper( + new SafeCloseDatagramSocket(localAddress)); stunStack.addSocket(localSock); //init the dummy server diff --git a/test/org/ice4j/stunclient/ResponseSequenceServer.java b/test/org/ice4j/stunclient/ResponseSequenceServer.java index ed4913a..bda4c95 100644 --- a/test/org/ice4j/stunclient/ResponseSequenceServer.java +++ b/test/org/ice4j/stunclient/ResponseSequenceServer.java @@ -7,7 +7,6 @@ package org.ice4j.stunclient; import java.io.*; -import java.net.*; import java.util.*; import java.util.logging.*; @@ -45,7 +44,7 @@ public class ResponseSequenceServer private final StunStack stunStack; private TransportAddress serverAddress = null; - private DatagramSocket localSocket = null; + private IceSocketWrapper localSocket = null; /** * Initializes a new ResponseSequenceServer instance with a @@ -72,7 +71,8 @@ public class ResponseSequenceServer public void start() throws IOException, StunException { - localSocket = new SafeCloseDatagramSocket(serverAddress); + localSocket = new IceUdpSocketWrapper( + new SafeCloseDatagramSocket(serverAddress)); stunStack.addSocket(localSocket); stunStack.addRequestListener(serverAddress, this);