From 12a4ef19a0fb5d5daac3946e4841f57c4cee8f15 Mon Sep 17 00:00:00 2001 From: Boris Grozev Date: Mon, 7 Nov 2016 14:49:00 -0600 Subject: [PATCH 01/29] feat: Adds MergingDatagramSocket. --- .../ice4j/socket/MergingDatagramSocket.java | 809 ++++++++++++++++++ 1 file changed, 809 insertions(+) create mode 100644 src/main/java/org/ice4j/socket/MergingDatagramSocket.java diff --git a/src/main/java/org/ice4j/socket/MergingDatagramSocket.java b/src/main/java/org/ice4j/socket/MergingDatagramSocket.java new file mode 100644 index 0000000..59f99b9 --- /dev/null +++ b/src/main/java/org/ice4j/socket/MergingDatagramSocket.java @@ -0,0 +1,809 @@ +/* + * ice4j, the OpenSource Java Solution for NAT and Firewall Traversal. + * + * Copyright @ 2015-2016 Atlassian Pty Ltd + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.ice4j.socket; + +import java.io.*; +import java.net.*; +import java.util.*; +import java.util.concurrent.*; +import java.util.logging.*; + +/** + * A {@link DatagramSocket} implementation which merges a set of sockets. + * + * It maintains a thread reading from each of the underlying sockets. Thus + * received datagrams are provided via the {@link #receive(DatagramPacket)} + * API, in the order in which they were originally received (or close to it, + * since the implementation is only based on timestamps). + * + * One of the underlying sockets is used as a delegate, and handles sending + * via {@link #send(DatagramPacket)} and calls to + * {@link #getLocalPort()}, {@link #getLocalAddress()} and + * {@link #getLocalSocketAddress()}. + * + * Currently the delegate is just the first socket, but the intention is to + * allow it to change dynamically. + * + * @author Boris Grozev + */ +public class MergingDatagramSocket + extends DatagramSocket +{ + /** + * The {@link Logger} used by the {@link MergingDatagramSocket} class and + * its instances for logging output. + */ + private static final Logger logger + = Logger.getLogger(MergingDatagramSocket.class.getName()); + + /** + * Used to control access to {@link #socketContainers}. + */ + private final Object socketContainersSyncRoot = new Object(); + + /** + * Stores the underlying sockets. Copy on write. + */ + private SocketContainer[] socketContainers = new SocketContainer[0]; + + /** + * Calls to {@link #receive(java.net.DatagramPacket)} will wait on this + * object in case no packet is available for reading. + */ + private final Object receiveLock = new Object(); + + /** + * If non-zero, {@link #receive(java.net.DatagramPacket)} will attempt to + * return within this many milliseconds, and will throw a + * {@link SocketTimeoutException} if no packet has been read. + */ + private int soTimeout = 0; + + /** + * Initializes a new {@link MergingDatagramSocket} instance. + * @throws SocketException + */ + public MergingDatagramSocket() + throws SocketException + {} + + /** + * {@inheritDoc} + */ + @Override + public void setSoTimeout(int soTimeout) + { + this.soTimeout = soTimeout; + } + + /** + * {@inheritDoc} + */ + @Override + public int getSoTimeout() + { + return soTimeout; + } + + /** + * {@inheritDoc} + *

+ * The current implementation delegates to the first container, but this is + * subject to change. + * + * @param pkt the datagram to send. + * @throws IOException + */ + @Override + public void send(DatagramPacket pkt) + throws IOException + { + SocketContainer[] socketContainers = this.socketContainers; + if (socketContainers != null && socketContainers.length > 0 + && socketContainers[0] != null) + { + socketContainers[0].send(pkt); + } + else + { + throw new IOException("No sockets."); + } + + } + + /** + * Adds a {@link DelegatingSocket} instance to this merging socket. Note + * that this will start a thread reading from the added socket. + * @param socket the socket to add. + */ + public void add(DelegatingSocket socket) + { + Objects.requireNonNull(socket, "socket"); + if (logger.isLoggable(Level.FINE)) + { + logger.fine("Adding a DelegatingSocket instance: " + + socket.getLocalAddress()); + } + doAdd(socket); + } + + /** + * Adds a {@link DatagramSocket} instance to this merging socket. Note + * that this will start a thread reading from the added socket. + * @param socket the socket to add. + */ + public void add(DatagramSocket socket) + { + Objects.requireNonNull(socket, "socket"); + if (logger.isLoggable(Level.FINE)) + { + logger.fine("Adding a DatagramSocket instance: " + + socket.getLocalAddress()); + } + doAdd(socket); + } + + /** + * Adds a socket (either a {@link DatagramSocket} or a + * {@link DelegatingSocket}) to the list of underlying sockets merged by + * this {@link MergingDatagramSocket}. + * @param socket the socket to add. + */ + private void doAdd(Object socket) + { + if (!(socket instanceof DelegatingSocket) && + !(socket instanceof DatagramSocket)) + { + logger.severe("Unsupported class: " + + (socket == null ? "null" : socket.getClass())); + return; + } + + synchronized (socketContainersSyncRoot) + { + if (indexOf(socketContainers, socket) != -1) + { + logger.warning("Socket already added."); + return; + } + + SocketContainer socketContainer; + if (socket instanceof DelegatingSocket) + { + socketContainer = new SocketContainer((DelegatingSocket) socket); + } + else + { + socketContainer = new SocketContainer((DatagramSocket) socket); + } + + SocketContainer[] newSocketContainers + = new SocketContainer[socketContainers.length + 1]; + System.arraycopy(socketContainers, 0, + newSocketContainers, 0, + socketContainers.length); + newSocketContainers[socketContainers.length] = socketContainer; + + socketContainers = newSocketContainers; + } + } + + /** + * Removes a specific {@link DatagramSocket} from the list of sockets + * merged by this {@link MergingDatagramSocket}. + * @param socket the {@link DatagramSocket} to remove. + */ + public void remove(DatagramSocket socket) + { + doRemove(socket); + } + + /** + * Removes a specific {@link DelegatingSocket} from the list of sockets + * merged by this {@link MergingDatagramSocket}. + * @param socket the {@link DelegatingSocket} to remove. + */ + public void remove(DelegatingSocket socket) + { + doRemove(socket); + } + + /** + * Removes a socket from the list of sockets merged by this + * {@link MergingDatagramSocket}. + * @param socket the socket to remove. + */ + private void doRemove(Object socket) + { + SocketContainer socketContainer = null; + + synchronized (socketContainersSyncRoot) + { + int i = indexOf(socketContainers, socket); + if (i > 0) + { + socketContainer = socketContainers[i]; + + SocketContainer[] newSockets + = new SocketContainer[socketContainers.length - 1]; + if (i > 0) + { + System.arraycopy(socketContainers, 0, + newSockets, 0, + i); + } + if (i < socketContainers.length - 1) + { + System.arraycopy(socketContainers, i + 1, + newSockets, i, + socketContainers.length - i - 1); + } + + socketContainers = newSockets; + } + else + { + logger.severe("Cannot find socket to remove."); + } + } + + if (logger.isLoggable(Level.FINE)) + { + logger.fine("Removed: " + socketContainer); + } + if (socketContainer != null) + { + // Stop the reading thread. + // TODO: do we want to interrupt the thread here? This will not + // help unless we set a soTimeout > 0 + socketContainer.closed = true; + } + } + + /** + * Returns the index in {@link #socketContainers} of the + * {@link SocketContainer} with socket equal to {@code socket}, or -1 if + * such a {@link SocketContainer} doesn't exist. + * + * @param socket the {@link DatagramSocket} to get the index of. + * @return the index in {@link #socketContainers} of the + * {@link SocketContainer} with socket equal to {@code socket}, or -1 if + * such a {@link SocketContainer} doesn't exist. + */ + private int indexOf(SocketContainer[] socketContainers, Object socket) + { + for (int i = 0; i < socketContainers.length; i++) + { + if (socketContainers[i].datagramSocket == socket || + socketContainers[i].delegatingSocket == socket) + { + return i; + } + } + return -1; + } + + /** + * TODO + */ + private SocketContainer getActiveSocket() + { + //TODO switch dynamically. + SocketContainer[] socketContainers = this.socketContainers; + if (socketContainers != null && socketContainers.length > 0) + { + return socketContainers[0]; + } + return null; + } + + /** + * {@inheritDoc} + *

+ * Delegates to the "active" socket, if one exists. Else returns + * {@code null}. + */ + @Override + public InetAddress getLocalAddress() + { + SocketContainer activeSocket = getActiveSocket(); + return activeSocket == null ? null : activeSocket.getLocalAddress(); + } + + /** + * {@inheritDoc} + *

+ * Delegates to the "active" socket, if one exists. Else returns + * {@code 0}. + * TODO: should we return 0 (unbound) or -1 (closed) if there are no + * sockets? + */ + @Override + public int getLocalPort() + { + SocketContainer activeSocket = getActiveSocket(); + return activeSocket == null ? 0 : activeSocket.getLocalPort(); + } + + /** + * {@inheritDoc} + *

+ * Delegates to the "active" socket, if one exists. Else returns + * {@code null}. + */ + @Override + public SocketAddress getLocalSocketAddress() + { + SocketContainer activeSocket = getActiveSocket(); + return + activeSocket == null ? null : activeSocket.getLocalSocketAddress(); + } + + /** + * {@inheritDoc} + *

+ * Copies into {@code p} a packet already received from one of the + * underlying sockets. The socket is chosen on the base of the timestamp + * of the reception of the first packet in its queue (so that earlier + * packets are received first). + */ + @Override + public void receive(DatagramPacket p) + throws SocketTimeoutException + { + long start = System.currentTimeMillis(); + int soTimeout = this.soTimeout; + + // We need to hold the lock while checking for an available packet, + // otherwise we might end up wait()-ing if a packet becomes available + // after our check. + // We keep the loop inside the lock, because this prevents us from + // having to re-obtain the lock after wait() returns. All operations + // inside the block are non-blocking, except for wait(), so we run no + // risk of causing a deadlock by doing so. + synchronized (receiveLock) + { + do + { + // Find the input socket with the oldest packet + SocketContainer[] socketContainers = this.socketContainers; + SocketContainer socketToReceiveFrom = null; + long firstTime = -1; + for (SocketContainer socketContainer : socketContainers) + { + long f = socketContainer.getFirstReceivedTime(); + if (f > 0) + { + if (firstTime == -1 || firstTime > f) + { + firstTime = f; + socketToReceiveFrom = socketContainer; + } + } + } + + // If a packet is available read it + if (socketToReceiveFrom != null) + { + socketToReceiveFrom.receive(p); + return; + } + // Otherwise wait on receiveLock. + else + { + try + { + if (soTimeout > 0) + { + long remaining + = start + soTimeout + - System.currentTimeMillis(); + if (remaining <= 0) + throw new SocketTimeoutException(); + + receiveLock.wait(remaining); + } + else + { + receiveLock.wait(); + } + } + catch (InterruptedException ie) + { + Thread.currentThread().interrupt(); + // We haven't received a packet, but what else can we + // do? + return; + } + } + } + while (true); + } + } + + /** + * Contains one of the sockets which this {@link MergingDatagramSocket} + * merges, and objects associated with the socket, including a thread + * which loops reading from it. + * + * The socket is either a {@link DatagramSocket} or a + * {@link DelegatingSocket} instance, stored in {@link #datagramSocket} or + * {@link #delegatingSocket} respectively. Exactly one of these fields must + * be null. + */ + private class SocketContainer + { + /** + * Either the socket represented by this instance, if it is a {@link + * DatagramSocket} instance, or {@code null} if it is not. + */ + private final DatagramSocket datagramSocket; + + /** + * Either the socket represented by this instance, if it is a {@link + * DelegatingSocket} instance, or {@code null}if it is not. + */ + private final DelegatingSocket delegatingSocket; + + /** + * The queue to which packets received from this instance's socket are + * added. + */ + private final ArrayBlockingQueue queue + = new ArrayBlockingQueue<>(100); + + /** + * A pool of unused {@link Buffer} instances. + */ + private final ArrayBlockingQueue pool + = new ArrayBlockingQueue<>(10); + + /** + * A flag used to signal to {@link #thread} to finish. + */ + private boolean closed = false; + + /** + * The remote address of the last received packet. + */ + private SocketAddress remoteAddress = null; + + /** + * The thread which reads packets from this instance's socket and adds + * them to {@link #queue}. If the queue is filled up, it will stop + * receiving packets and will block waiting for the queue accept. + */ + private Thread thread; + + /** + * Initializes a {@link SocketContainer} instance using a {@link + * DatagramSocket} as its socket. + * + * @param socket the socket. + */ + SocketContainer(DelegatingSocket socket) + { + this.datagramSocket = null; + this.delegatingSocket = Objects.requireNonNull(socket, "socket"); + init(); + } + + /** + * Initializes a {@link SocketContainer} instance using a {@link + * DatagramSocket} as its socket. + * + * @param socket the socket. + */ + SocketContainer(DatagramSocket socket) + { + this.datagramSocket = Objects.requireNonNull(socket, "socket"); + this.delegatingSocket = null; + init(); + } + + /** + * Initializes and starts the thread of this instance. + */ + private void init() + { + thread = new Thread() + { + @Override + public void run() + { + runInReaderThread(); + } + }; + thread.setDaemon(true); + thread.setName("MergingDatagramSocket reader thread for: " + + getLocalSocketAddress() + " -> " + + getRemoteSocketAddress()); + + if (logger.isLoggable(Level.FINE)) + { + logger.fine("Starting the thread for socket " + + getLocalSocketAddress() + " -> " + + getRemoteSocketAddress()); + } + thread.start(); + } + + /** + * @return an unused {@link Buffer} instance. + */ + private Buffer getFreeBuffer() + { + Buffer buffer = pool.poll(); + if (buffer == null) + buffer = new Buffer(); + buffer.reset(); + return buffer; + } + + /** + * Reads from the underlying socket and adds the read packets to {@link + * #queue}. Blocks if {@link #queue} is full. + */ + private void runInReaderThread() + { + while (true) + { + if (closed || Thread.currentThread().isInterrupted()) + break; + + // Read from the underlying socket + Buffer buffer = getFreeBuffer(); + try + { + if (!doReceive(buffer)) + { + continue; + } + } + catch (IOException ioe) + { + logger.severe("Failed to receive: " + ioe); + break; + } + + if (closed || Thread.currentThread().isInterrupted()) + break; + + try + { + queue.put(buffer); + synchronized (receiveLock) + { + receiveLock.notifyAll(); + } + } + catch (InterruptedException ie) + { + Thread.currentThread().interrupt(); + } + } + + if (logger.isLoggable(Level.FINE)) + { + logger.fine("Finished: " + toString()); + } + } + + /** + * Tries to receive a packet from the underlying socket into {@code + * buffer}. + * + * @param buffer the buffer into which to receive. + * @return {@code true} if the method succeeded, or {@code false} if the + * thread was interrupted or this {@link SocketContainer} was closed. + * @throws IOException if receiving failed due to an I/O error from the + * underlying socket. + */ + private boolean doReceive(Buffer buffer) + throws IOException + { + while (true) + { + if (closed || Thread.currentThread().isInterrupted()) + break; + try + { + if (datagramSocket != null) + { + datagramSocket.receive(buffer.pkt); + } + else + { + delegatingSocket.receive(buffer.pkt); + } + + buffer.receivedTime = System.currentTimeMillis(); + remoteAddress = buffer.pkt.getSocketAddress(); + return true; + } + catch (SocketTimeoutException ste) + { + // Ignore timeouts and loop. + } + } + + return false; + } + + /** + * Copies a packet from this {@link SocketContainer}'s queue into + * {@code p}. Does not block. + * + * @param p the {@link DatagramPacket} to receive into. + */ + private void receive(DatagramPacket p) + { + Buffer buffer = queue.poll(); + if (buffer == null) + { + throw new IllegalStateException("Queue empty."); + } + + byte[] dest = p.getData(); + int destOffset = p.getOffset(); + int len + = Math.min( + dest.length - destOffset, + buffer.pkt.getLength()); + + System.arraycopy(buffer.pkt.getData(), buffer.pkt.getOffset(), + dest, destOffset, + len); + p.setLength(len); + p.setSocketAddress(buffer.pkt.getSocketAddress()); + + pool.offer(buffer); + } + + /** + * @return the time of reception of the first packet in the queue, or + * {@code -1} if the queue is empty. + */ + private long getFirstReceivedTime() + { + Buffer nextBuffer = queue.peek(); + if (nextBuffer != null) + { + return nextBuffer.receivedTime; + } + return -1; + } + + /** + * {@inheritDoc} + *

+ * Delegates to the underlying socket (either {@link #datagramSocket} or + * {@link #delegatingSocket}). + */ + private InetAddress getLocalAddress() + { + return datagramSocket != null + ? datagramSocket.getLocalAddress() + : delegatingSocket.getLocalAddress(); + } + + /** + * {@inheritDoc} + *

+ * Delegates to the underlying socket (either {@link #datagramSocket} or + * {@link #delegatingSocket}). + */ + private int getLocalPort() + { + return datagramSocket != null + ? datagramSocket.getLocalPort() + : delegatingSocket.getLocalPort(); + } + + /** + * {@inheritDoc} + *

+ * Delegates to the underlying socket (either {@link #datagramSocket} or + * {@link #delegatingSocket}). + */ + public SocketAddress getLocalSocketAddress() + { + return datagramSocket != null + ? datagramSocket.getLocalSocketAddress() + : delegatingSocket.getLocalSocketAddress(); + + } + + /** + * Returns a {@link String} representation of this {@link + * SocketContainer}. + */ + public String toString() + { + if (datagramSocket != null) + { + return datagramSocket.getLocalSocketAddress() + + " -> " + remoteAddress; + } + else + { + return delegatingSocket.getLocalSocketAddress() + + " -> " + remoteAddress; + } + } + + /** + * Sends a {@link DatagramPacket} through the underlying socket (either + * {@link #datagramSocket} or {@link #delegatingSocket}). + * + * @param pkt the packet to send. + */ + private void send(DatagramPacket pkt) + throws IOException + { + if (datagramSocket != null) + { + datagramSocket.send(pkt); + } + else + { + delegatingSocket.send(pkt); + } + } + + /** + * Represents a {@link DatagramPacket} for the purposes of {@link + * SocketContainer}. + */ + private class Buffer + { + /** + * The size of the buffer to allocate. + */ + private static final int MAX_PACKET_SIZE = 1500; + + /** + * The time at which this buffer was filled. + */ + long receivedTime = -1; + + /** + * The {@link DatagramPacket} wrapped by this {@link Buffer}. + */ + DatagramPacket pkt + = new DatagramPacket( + new byte[MAX_PACKET_SIZE], + 0, + MAX_PACKET_SIZE); + + /** + * Prepares this {@link Buffer} for reuse. + */ + private void reset() + { + receivedTime = -1; + + // We are going to receive from a socket into this packet. If + // the length is insufficient it is going to truncate the data. + // So reset it to what we know is the underlying byte[]'s + // length. + pkt.setLength(MAX_PACKET_SIZE); + } + } + } +} From aafe00397416b8e2d005ff9ad5c36fe08babefe9 Mon Sep 17 00:00:00 2001 From: Boris Grozev Date: Tue, 8 Nov 2016 16:00:50 -0600 Subject: [PATCH 02/29] docs: Adds a comment. --- .../java/org/ice4j/socket/DelegatingDatagramSocket.java | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/main/java/org/ice4j/socket/DelegatingDatagramSocket.java b/src/main/java/org/ice4j/socket/DelegatingDatagramSocket.java index a141e09..cffbd91 100644 --- a/src/main/java/org/ice4j/socket/DelegatingDatagramSocket.java +++ b/src/main/java/org/ice4j/socket/DelegatingDatagramSocket.java @@ -662,6 +662,12 @@ public class DelegatingDatagramSocket // after the first packet is received, the length is set to the size // of the first packet and the second packet is truncated. // http://docs.oracle.com/javase/6/docs/api/java/net/DatagramSocket.html + // + // XXX(boris): I think the above is wrong. I don't interpret the + // API description this way, and testing on a couple of different + // environments shows that DatagramSocket.receive() grows the + // packet's length to as much as much as the array (and offset) + // would allow. I am leaving the code because it seems harmless. byte[] data = p.getData(); p.setLength((data == null) ? 0 : (data.length - p.getOffset())); From 44ca871888e8cb7e4031076232d74f5f5ac4cdcd Mon Sep 17 00:00:00 2001 From: Boris Grozev Date: Mon, 14 Nov 2016 11:14:38 -0600 Subject: [PATCH 03/29] style: Makes the logger field final. --- src/main/java/org/ice4j/ice/Component.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/ice4j/ice/Component.java b/src/main/java/org/ice4j/ice/Component.java index cac8432..ad45f11 100644 --- a/src/main/java/org/ice4j/ice/Component.java +++ b/src/main/java/org/ice4j/ice/Component.java @@ -119,7 +119,7 @@ public class Component /** * The {@link Logger} used by {@link Component} instances. */ - private Logger logger; + private final Logger logger; /** * Creates a new Component with the specified componentID From 2718728e927346ffc5d20fdd231bb72c72c3e017 Mon Sep 17 00:00:00 2001 From: Boris Grozev Date: Thu, 17 Nov 2016 13:28:14 -0600 Subject: [PATCH 04/29] feat: Adds an ENABLE_VIRTUAL_SOCKET_LAYER property and a MergingDatagramSocket instance for each Component. --- src/main/java/org/ice4j/StackProperties.java | 13 ++++ src/main/java/org/ice4j/ice/Agent.java | 15 +++++ src/main/java/org/ice4j/ice/Component.java | 62 ++++++++++++++++++++ 3 files changed, 90 insertions(+) diff --git a/src/main/java/org/ice4j/StackProperties.java b/src/main/java/org/ice4j/StackProperties.java index da5b11d..13fe0b5 100644 --- a/src/main/java/org/ice4j/StackProperties.java +++ b/src/main/java/org/ice4j/StackProperties.java @@ -232,6 +232,19 @@ public class StackProperties public static final String USE_DYNAMIC_HOST_HARVESTER = "org.ice4j.ice.harvest.USE_DYNAMIC_HOST_HARVESTER"; + /** + * The name of the property which specifies whether the virtual socket + * layer should be enabled. + * WARNING: enabling the virtual socket layer will break applications which + * use sockets from specific {@code CandidatePair}s in subtle and + * potentially hard to debug ways. This should only be used by applications + * that specifically want to use the virtual socket layer (i.e. use the + * socket instance provided by the {@code Component}, and not a specific + * {@code CandidatePair}). + */ + public static final String ENABLE_VIRTUAL_SOCKET_LAYER + = "org.ice4j.ice.harvest.ENABLE_VIRTUAL_SOCKET_LAYER"; + /** * Returns the String value of the specified property (minus all * encompassing whitespaces)and null in case no property value was mapped diff --git a/src/main/java/org/ice4j/ice/Agent.java b/src/main/java/org/ice4j/ice/Agent.java index 09ebef7..1ece7ae 100644 --- a/src/main/java/org/ice4j/ice/Agent.java +++ b/src/main/java/org/ice4j/ice/Agent.java @@ -114,6 +114,15 @@ public class Agent public static final String PROPERTY_ICE_PROCESSING_STATE = "IceProcessingState"; + /** + * The flag which indicates whether the virtual socket layer should be + * enabled or not. + */ + public static boolean ENABLE_VIRTUAL_SOCKET_LAYER + = StackProperties.getBoolean( + StackProperties.ENABLE_VIRTUAL_SOCKET_LAYER, + false); + /** * The LinkedHashMap used to store the media streams * This map preserves the insertion order of the media streams. @@ -373,6 +382,12 @@ public class Agent { addCandidateHarvester(harvester); } + + if (logger.isLoggable(Level.FINE)) + { + logger.fine("Created a new Agent, ufrag=" + ufrag + + ", VSL=" + ENABLE_VIRTUAL_SOCKET_LAYER); + } } /** diff --git a/src/main/java/org/ice4j/ice/Component.java b/src/main/java/org/ice4j/ice/Component.java index ad45f11..e268ab4 100644 --- a/src/main/java/org/ice4j/ice/Component.java +++ b/src/main/java/org/ice4j/ice/Component.java @@ -17,10 +17,12 @@ */ package org.ice4j.ice; +import java.net.*; import java.util.*; import java.util.logging.*; import org.ice4j.*; +import org.ice4j.socket.*; import org.ice4j.util.Logger; //Disambiguation /** @@ -121,6 +123,20 @@ public class Component */ private final Logger logger; + /** + * The {@link MergingDatagramSocket} instance which, if the virtual socket + * layer is enabled (see + * {@link StackProperties#ENABLE_VIRTUAL_SOCKET_LAYER}), will serve as the + * single socket instance for this {@link Component}, merging received + * packets from all of its candidates. + */ + private final MergingDatagramSocket mergingDatagramSocket; + + /** + * A wrapper around {@link #mergingDatagramSocket}. + */ + private final IceUdpSocketWrapper mergingDatagramSocketWrapper; + /** * Creates a new Component with the specified componentID * as a child of the specified IceMediaStream. @@ -136,6 +152,27 @@ public class Component this.componentID = componentID; this.parentStream = mediaStream; + if (Agent.ENABLE_VIRTUAL_SOCKET_LAYER) + { + try + { + mergingDatagramSocket = new MergingDatagramSocket(); + mergingDatagramSocketWrapper + = new IceUdpSocketWrapper( + new MultiplexingDatagramSocket( + mergingDatagramSocket)); + } + catch (SocketException se) + { + throw new RuntimeException(se); + } + } + else + { + mergingDatagramSocket = null; + mergingDatagramSocketWrapper = null; + } + logger = new Logger(classLogger, mediaStream.getParentAgent().getLogger()); } @@ -911,4 +948,29 @@ public class Component return new Component(componentID, mediaStream); } + /** + * @return the single socket for this {@link Component} which should be + * used for reading and writing data, if the virtual socket layer is enabled + * (see {@link StackProperties#ENABLE_VIRTUAL_SOCKET_LAYER}), and + * {@code null} if it is not enabled. + */ + public MergingDatagramSocket getSocket() + { + return mergingDatagramSocket; + } + + /** + * @return an {@link IceSocketWrapper} instance wrapping the socket for this + * candidate (see {@link #getSocket()}), if the virtual socket layer is + * enabled (see {@link StackProperties#ENABLE_VIRTUAL_SOCKET_LAYER}), or + * {@code null} if it is not enabled. + * @deprecated Use {@link #getSocket()} directly. This is only introduced + * to ease the transition of applications which are already written to use + * a {@link IceSocketWrapper} instance. + */ + @Deprecated + public IceSocketWrapper getSocketWrapper() + { + return mergingDatagramSocketWrapper; + } } From 25b0cfdc30ff02610a416ce6da343e7612eaf74c Mon Sep 17 00:00:00 2001 From: Boris Grozev Date: Mon, 21 Nov 2016 15:44:33 -0600 Subject: [PATCH 05/29] feat: Adds socket from the single-port and TCP harvesters to the Component. --- .../java/org/ice4j/ice/harvest/SinglePortUdpHarvester.java | 6 ++++++ src/main/java/org/ice4j/ice/harvest/TcpHarvester.java | 7 +++++++ 2 files changed, 13 insertions(+) diff --git a/src/main/java/org/ice4j/ice/harvest/SinglePortUdpHarvester.java b/src/main/java/org/ice4j/ice/harvest/SinglePortUdpHarvester.java index d9adfaa..e910cac 100644 --- a/src/main/java/org/ice4j/ice/harvest/SinglePortUdpHarvester.java +++ b/src/main/java/org/ice4j/ice/harvest/SinglePortUdpHarvester.java @@ -362,6 +362,12 @@ public class SinglePortUdpHarvester stunSocket, new TransportAddress(remoteAddress, Transport.UDP)); + // TODO: maybe move this code to the candidates. + MergingDatagramSocket componentSocket = component.getSocket(); + if (componentSocket != null) + { + componentSocket.add(multiplexing); + } // XXX is this necessary? synchronized (candidateSockets) diff --git a/src/main/java/org/ice4j/ice/harvest/TcpHarvester.java b/src/main/java/org/ice4j/ice/harvest/TcpHarvester.java index 752f5f8..d38fc88 100644 --- a/src/main/java/org/ice4j/ice/harvest/TcpHarvester.java +++ b/src/main/java/org/ice4j/ice/harvest/TcpHarvester.java @@ -518,6 +518,13 @@ public class TcpHarvester component.getParentStream().getParentAgent().getStunStack() .addSocket(stunSocket); candidate.addSocket(candidateSocket); + + // TODO: Maybe move this code to the candidate. + MergingDatagramSocket componentSocket = component.getSocket(); + if (componentSocket != null) + { + componentSocket.add(multiplexing); + } // the socket is not our responsibility anymore. It is up to // the candidate/component to close/free it. } From f08feea70706f4a1c49953fa11abfd75e295b60d Mon Sep 17 00:00:00 2001 From: Boris Grozev Date: Mon, 21 Nov 2016 15:58:09 -0600 Subject: [PATCH 06/29] feat: Uses the last active socket to send data through. --- .../ice4j/socket/MergingDatagramSocket.java | 52 +++++++++++++++++-- 1 file changed, 47 insertions(+), 5 deletions(-) diff --git a/src/main/java/org/ice4j/socket/MergingDatagramSocket.java b/src/main/java/org/ice4j/socket/MergingDatagramSocket.java index 59f99b9..e1ab5e8 100644 --- a/src/main/java/org/ice4j/socket/MergingDatagramSocket.java +++ b/src/main/java/org/ice4j/socket/MergingDatagramSocket.java @@ -74,6 +74,12 @@ public class MergingDatagramSocket */ private int soTimeout = 0; + /** + * The {@link SocketContainer} considered active, i.e. the one which should + * be used for sending. + */ + private SocketContainer active = null; + /** * Initializes a new {@link MergingDatagramSocket} instance. * @throws SocketException @@ -113,15 +119,14 @@ public class MergingDatagramSocket public void send(DatagramPacket pkt) throws IOException { - SocketContainer[] socketContainers = this.socketContainers; - if (socketContainers != null && socketContainers.length > 0 - && socketContainers[0] != null) + SocketContainer active = this.active; + if (active != null) { - socketContainers[0].send(pkt); + active.send(pkt); } else { - throw new IOException("No sockets."); + throw new IOException("No active socket."); } } @@ -200,6 +205,9 @@ public class MergingDatagramSocket newSocketContainers[socketContainers.length] = socketContainer; socketContainers = newSocketContainers; + + if (active == null) + active = socketContainer; } } @@ -255,6 +263,13 @@ public class MergingDatagramSocket } socketContainers = newSockets; + + // Until we receive data on one of the other sockets, use the + // first one as the active socket. + if (socketContainer == active) + { + active = newSockets.length == 0 ? null : newSockets[0]; + } } else { @@ -634,6 +649,8 @@ public class MergingDatagramSocket buffer.receivedTime = System.currentTimeMillis(); remoteAddress = buffer.pkt.getSocketAddress(); + + maybeUpdateActive(); return true; } catch (SocketTimeoutException ste) @@ -645,6 +662,31 @@ public class MergingDatagramSocket return false; } + /** + * Makes this {@link SocketContainer} the active socket container for + * this {@link MergingDatagramSocket}, if it isn't already the active + * socket. + */ + private void maybeUpdateActive() + { + SocketContainer active = MergingDatagramSocket.this.active; + // Avoid obtaining the lock on every packet from the active socket. + // There is no harm if the value is overwritten before we obtain + // the lock. + if (active != this) + { + synchronized (socketContainersSyncRoot) + { + MergingDatagramSocket.this.active = this; + if (logger.isLoggable(Level.FINE)) + { + logger.warning("Switching to new active socket: " + + this); + } + } + } + } + /** * Copies a packet from this {@link SocketContainer}'s queue into * {@code p}. Does not block. From f19dbc1984e7a987669412580af7f79608d7af67 Mon Sep 17 00:00:00 2001 From: Boris Grozev Date: Mon, 21 Nov 2016 15:59:13 -0600 Subject: [PATCH 07/29] doc: Notes that the VSL is experimental. --- src/main/java/org/ice4j/StackProperties.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main/java/org/ice4j/StackProperties.java b/src/main/java/org/ice4j/StackProperties.java index 13fe0b5..2904cd2 100644 --- a/src/main/java/org/ice4j/StackProperties.java +++ b/src/main/java/org/ice4j/StackProperties.java @@ -241,6 +241,7 @@ public class StackProperties * that specifically want to use the virtual socket layer (i.e. use the * socket instance provided by the {@code Component}, and not a specific * {@code CandidatePair}). + * This is currently EXPERIMENTAL. */ public static final String ENABLE_VIRTUAL_SOCKET_LAYER = "org.ice4j.ice.harvest.ENABLE_VIRTUAL_SOCKET_LAYER"; From eaceca57ac83b691c70543241bcfa03d51282467 Mon Sep 17 00:00:00 2001 From: Boris Grozev Date: Mon, 28 Nov 2016 11:17:18 -0600 Subject: [PATCH 08/29] feat: Allows to add sockets to a completed agent. --- .../java/org/ice4j/ice/harvest/TcpHarvester.java | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/ice4j/ice/harvest/TcpHarvester.java b/src/main/java/org/ice4j/ice/harvest/TcpHarvester.java index d38fc88..5a3c455 100644 --- a/src/main/java/org/ice4j/ice/harvest/TcpHarvester.java +++ b/src/main/java/org/ice4j/ice/harvest/TcpHarvester.java @@ -491,8 +491,18 @@ public class TcpHarvester if (!IceProcessingState.WAITING.equals(state) && !IceProcessingState.RUNNING.equals(state)) { - throw new IllegalStateException( - "The associated Agent is in state " + state); + // If we are using the VSL, we can still make use of the socket. + // Otherwise, we have no use for it, so we better close it (and + // log a warning) early. + if (!Agent.ENABLE_VIRTUAL_SOCKET_LAYER) + { + throw new IllegalStateException( + "The associated Agent is in state " + state); + } + else if (logger.isLoggable(Level.FINE)) + { + logger.fine("Adding a socket to an Agent in state " + state); + } } // Socket to add to the candidate From 3ddb19ff2c6610b614b69b36cf79e87fe0b608f8 Mon Sep 17 00:00:00 2001 From: Boris Grozev Date: Mon, 28 Nov 2016 13:34:49 -0600 Subject: [PATCH 09/29] fix: Updates getActiveSocket. --- .../java/org/ice4j/socket/MergingDatagramSocket.java | 10 ++-------- 1 file changed, 2 insertions(+), 8 deletions(-) diff --git a/src/main/java/org/ice4j/socket/MergingDatagramSocket.java b/src/main/java/org/ice4j/socket/MergingDatagramSocket.java index e1ab5e8..2c0c30c 100644 --- a/src/main/java/org/ice4j/socket/MergingDatagramSocket.java +++ b/src/main/java/org/ice4j/socket/MergingDatagramSocket.java @@ -119,7 +119,7 @@ public class MergingDatagramSocket public void send(DatagramPacket pkt) throws IOException { - SocketContainer active = this.active; + SocketContainer active = getActiveSocket(); if (active != null) { active.send(pkt); @@ -318,13 +318,7 @@ public class MergingDatagramSocket */ private SocketContainer getActiveSocket() { - //TODO switch dynamically. - SocketContainer[] socketContainers = this.socketContainers; - if (socketContainers != null && socketContainers.length > 0) - { - return socketContainers[0]; - } - return null; + return this.active; } /** From 91858ba6a3c08d0b46c45efe3f6d485d13f8717f Mon Sep 17 00:00:00 2001 From: Boris Grozev Date: Mon, 28 Nov 2016 14:05:40 -0600 Subject: [PATCH 10/29] feat: Removes the VIRTUAL_SOCKET_LAYER flag, enabling it by default. --- src/main/java/org/ice4j/StackProperties.java | 14 ------- src/main/java/org/ice4j/ice/Agent.java | 12 +----- src/main/java/org/ice4j/ice/Component.java | 38 ++++++------------- .../ice/harvest/SinglePortUdpHarvester.java | 6 +-- .../org/ice4j/ice/harvest/TcpHarvester.java | 23 +++-------- 5 files changed, 19 insertions(+), 74 deletions(-) diff --git a/src/main/java/org/ice4j/StackProperties.java b/src/main/java/org/ice4j/StackProperties.java index 2904cd2..da5b11d 100644 --- a/src/main/java/org/ice4j/StackProperties.java +++ b/src/main/java/org/ice4j/StackProperties.java @@ -232,20 +232,6 @@ public class StackProperties public static final String USE_DYNAMIC_HOST_HARVESTER = "org.ice4j.ice.harvest.USE_DYNAMIC_HOST_HARVESTER"; - /** - * The name of the property which specifies whether the virtual socket - * layer should be enabled. - * WARNING: enabling the virtual socket layer will break applications which - * use sockets from specific {@code CandidatePair}s in subtle and - * potentially hard to debug ways. This should only be used by applications - * that specifically want to use the virtual socket layer (i.e. use the - * socket instance provided by the {@code Component}, and not a specific - * {@code CandidatePair}). - * This is currently EXPERIMENTAL. - */ - public static final String ENABLE_VIRTUAL_SOCKET_LAYER - = "org.ice4j.ice.harvest.ENABLE_VIRTUAL_SOCKET_LAYER"; - /** * Returns the String value of the specified property (minus all * encompassing whitespaces)and null in case no property value was mapped diff --git a/src/main/java/org/ice4j/ice/Agent.java b/src/main/java/org/ice4j/ice/Agent.java index 1ece7ae..1c6fe8b 100644 --- a/src/main/java/org/ice4j/ice/Agent.java +++ b/src/main/java/org/ice4j/ice/Agent.java @@ -114,15 +114,6 @@ public class Agent public static final String PROPERTY_ICE_PROCESSING_STATE = "IceProcessingState"; - /** - * The flag which indicates whether the virtual socket layer should be - * enabled or not. - */ - public static boolean ENABLE_VIRTUAL_SOCKET_LAYER - = StackProperties.getBoolean( - StackProperties.ENABLE_VIRTUAL_SOCKET_LAYER, - false); - /** * The LinkedHashMap used to store the media streams * This map preserves the insertion order of the media streams. @@ -385,8 +376,7 @@ public class Agent if (logger.isLoggable(Level.FINE)) { - logger.fine("Created a new Agent, ufrag=" + ufrag - + ", VSL=" + ENABLE_VIRTUAL_SOCKET_LAYER); + logger.fine("Created a new Agent, ufrag=" + ufrag); } } diff --git a/src/main/java/org/ice4j/ice/Component.java b/src/main/java/org/ice4j/ice/Component.java index e268ab4..0c771e8 100644 --- a/src/main/java/org/ice4j/ice/Component.java +++ b/src/main/java/org/ice4j/ice/Component.java @@ -124,9 +124,7 @@ public class Component private final Logger logger; /** - * The {@link MergingDatagramSocket} instance which, if the virtual socket - * layer is enabled (see - * {@link StackProperties#ENABLE_VIRTUAL_SOCKET_LAYER}), will serve as the + * The {@link MergingDatagramSocket} instance which will serve as the * single socket instance for this {@link Component}, merging received * packets from all of its candidates. */ @@ -152,25 +150,17 @@ public class Component this.componentID = componentID; this.parentStream = mediaStream; - if (Agent.ENABLE_VIRTUAL_SOCKET_LAYER) + try { - try - { - mergingDatagramSocket = new MergingDatagramSocket(); - mergingDatagramSocketWrapper - = new IceUdpSocketWrapper( - new MultiplexingDatagramSocket( - mergingDatagramSocket)); - } - catch (SocketException se) - { - throw new RuntimeException(se); - } + mergingDatagramSocket = new MergingDatagramSocket(); + mergingDatagramSocketWrapper + = new IceUdpSocketWrapper( + new MultiplexingDatagramSocket( + mergingDatagramSocket)); } - else + catch (SocketException se) { - mergingDatagramSocket = null; - mergingDatagramSocketWrapper = null; + throw new RuntimeException(se); } logger @@ -950,9 +940,7 @@ public class Component /** * @return the single socket for this {@link Component} which should be - * used for reading and writing data, if the virtual socket layer is enabled - * (see {@link StackProperties#ENABLE_VIRTUAL_SOCKET_LAYER}), and - * {@code null} if it is not enabled. + * used for reading and writing data. */ public MergingDatagramSocket getSocket() { @@ -961,12 +949,10 @@ public class Component /** * @return an {@link IceSocketWrapper} instance wrapping the socket for this - * candidate (see {@link #getSocket()}), if the virtual socket layer is - * enabled (see {@link StackProperties#ENABLE_VIRTUAL_SOCKET_LAYER}), or - * {@code null} if it is not enabled. + * candidate (see {@link #getSocket()}). * @deprecated Use {@link #getSocket()} directly. This is only introduced * to ease the transition of applications which are already written to use - * a {@link IceSocketWrapper} instance. + * an {@link IceSocketWrapper} instance. */ @Deprecated public IceSocketWrapper getSocketWrapper() diff --git a/src/main/java/org/ice4j/ice/harvest/SinglePortUdpHarvester.java b/src/main/java/org/ice4j/ice/harvest/SinglePortUdpHarvester.java index e910cac..be9e25c 100644 --- a/src/main/java/org/ice4j/ice/harvest/SinglePortUdpHarvester.java +++ b/src/main/java/org/ice4j/ice/harvest/SinglePortUdpHarvester.java @@ -363,11 +363,7 @@ public class SinglePortUdpHarvester new TransportAddress(remoteAddress, Transport.UDP)); // TODO: maybe move this code to the candidates. - MergingDatagramSocket componentSocket = component.getSocket(); - if (componentSocket != null) - { - componentSocket.add(multiplexing); - } + component.getSocket().add(multiplexing); // XXX is this necessary? synchronized (candidateSockets) diff --git a/src/main/java/org/ice4j/ice/harvest/TcpHarvester.java b/src/main/java/org/ice4j/ice/harvest/TcpHarvester.java index 5a3c455..07ba748 100644 --- a/src/main/java/org/ice4j/ice/harvest/TcpHarvester.java +++ b/src/main/java/org/ice4j/ice/harvest/TcpHarvester.java @@ -488,21 +488,11 @@ public class TcpHarvester IceProcessingState state = component.getParentStream().getParentAgent().getState(); - if (!IceProcessingState.WAITING.equals(state) + if (logger.isLoggable(Level.FINE) + && !IceProcessingState.WAITING.equals(state) && !IceProcessingState.RUNNING.equals(state)) { - // If we are using the VSL, we can still make use of the socket. - // Otherwise, we have no use for it, so we better close it (and - // log a warning) early. - if (!Agent.ENABLE_VIRTUAL_SOCKET_LAYER) - { - throw new IllegalStateException( - "The associated Agent is in state " + state); - } - else if (logger.isLoggable(Level.FINE)) - { - logger.fine("Adding a socket to an Agent in state " + state); - } + logger.fine("Adding a socket to an Agent in state " + state); } // Socket to add to the candidate @@ -530,11 +520,8 @@ public class TcpHarvester candidate.addSocket(candidateSocket); // TODO: Maybe move this code to the candidate. - MergingDatagramSocket componentSocket = component.getSocket(); - if (componentSocket != null) - { - componentSocket.add(multiplexing); - } + component.getSocket().add(multiplexing); + // the socket is not our responsibility anymore. It is up to // the candidate/component to close/free it. } From 15a2df1e597ab41f26b392257ba8547647ab71cb Mon Sep 17 00:00:00 2001 From: Boris Grozev Date: Mon, 28 Nov 2016 16:11:24 -0600 Subject: [PATCH 11/29] feat: Splits the API to obtain sockets for a candidate/candidate pair. The public-facing API returns the socket instance for the associated Component, while the internal API (getCandidateIceSocket) returns the internal socket instance for the candidate. --- .../java/org/ice4j/ice/CandidatePair.java | 30 +++-------- .../org/ice4j/ice/GoogleRelayedCandidate.java | 5 +- .../java/org/ice4j/ice/HostCandidate.java | 11 ++-- .../java/org/ice4j/ice/LocalCandidate.java | 48 ++++++++--------- .../org/ice4j/ice/PeerReflexiveCandidate.java | 12 ++--- .../java/org/ice4j/ice/RelayedCandidate.java | 6 +-- .../ice4j/ice/ServerReflexiveCandidate.java | 10 ++-- .../java/org/ice4j/ice/TcpHostCandidate.java | 12 ----- .../java/org/ice4j/ice/UPNPCandidate.java | 18 ++++--- .../ice/harvest/SinglePortUdpHarvester.java | 52 ++++++++----------- .../RelayedCandidateDatagramSocket.java | 4 +- src/test/java/test/IcePseudoTcp.java | 2 +- 12 files changed, 85 insertions(+), 125 deletions(-) diff --git a/src/main/java/org/ice4j/ice/CandidatePair.java b/src/main/java/org/ice4j/ice/CandidatePair.java index 902e804..f0a165f 100644 --- a/src/main/java/org/ice4j/ice/CandidatePair.java +++ b/src/main/java/org/ice4j/ice/CandidatePair.java @@ -722,7 +722,9 @@ public class CandidatePair * CandidatePair. * @return the UDP DatagramSocket (if any) for this * CandidatePair. + * @deprecated use {@link Component#getSocket()} instead. */ + @Deprecated public DatagramSocket getDatagramSocket() { IceSocketWrapper wrapper = getIceSocketWrapper(); @@ -732,38 +734,22 @@ public class CandidatePair /** * Returns the TCP Socket (if any) for this CandidatePair. * @return the TCP Socket (if any) for this CandidatePair. + * @deprecated use {@link Component#getSocket()} instead. */ + @Deprecated public Socket getSocket() { - IceSocketWrapper wrapper = getIceSocketWrapper(); - return wrapper == null ? null : wrapper.getTCPSocket(); + return null; } /** * Returns the IceSocketWrapper for this CandidatePair. * @return the IceSocketWrapper for this CandidatePair. + * @deprecated use {@link Component#getSocket()} instead. */ + @Deprecated public IceSocketWrapper getIceSocketWrapper() { - LocalCandidate localCandidate = getLocalCandidate(); - if (localCandidate == null) - { - return null; - } - - LocalCandidate base = localCandidate.getBase(); - if (base != null) - localCandidate = base; - - RemoteCandidate remoteCandidate = getRemoteCandidate(); - if (remoteCandidate != null) - { - SocketAddress remoteAddress - = remoteCandidate.getTransportAddress(); - if (remoteAddress != null) - return localCandidate.getIceSocketWrapper(remoteAddress); - } - - return localCandidate.getIceSocketWrapper(); + return getParentComponent().getSocketWrapper(); } } diff --git a/src/main/java/org/ice4j/ice/GoogleRelayedCandidate.java b/src/main/java/org/ice4j/ice/GoogleRelayedCandidate.java index 5c6b81d..9a97198 100644 --- a/src/main/java/org/ice4j/ice/GoogleRelayedCandidate.java +++ b/src/main/java/org/ice4j/ice/GoogleRelayedCandidate.java @@ -191,9 +191,10 @@ public class GoogleRelayedCandidate * * @return the DatagramSocket associated with this * Candidate - * @see LocalCandidate#getIceSocketWrapper() + * @see LocalCandidate#getCandidateIceSocketWrapper() */ - public synchronized IceSocketWrapper getIceSocketWrapper() + @Override + protected synchronized IceSocketWrapper getCandidateIceSocketWrapper() { if (socket == null) { diff --git a/src/main/java/org/ice4j/ice/HostCandidate.java b/src/main/java/org/ice4j/ice/HostCandidate.java index d9cc77c..236c4d2 100644 --- a/src/main/java/org/ice4j/ice/HostCandidate.java +++ b/src/main/java/org/ice4j/ice/HostCandidate.java @@ -131,13 +131,12 @@ public class HostCandidate extends LocalCandidate } /** - * Gets the DatagramSocket associated with this Candidate. - * - * @return the DatagramSocket associated with this - * Candidate - * @see LocalCandidate#getIceSocketWrapper() + * {@inheritDoc} + * SHOULD NOT be used outside ice4j. Only exposed for use in the + * org.ice4j.socket package. */ - public IceSocketWrapper getIceSocketWrapper() + @Override + public IceSocketWrapper getCandidateIceSocketWrapper() { return socket; } diff --git a/src/main/java/org/ice4j/ice/LocalCandidate.java b/src/main/java/org/ice4j/ice/LocalCandidate.java index 8e05090..560938c 100644 --- a/src/main/java/org/ice4j/ice/LocalCandidate.java +++ b/src/main/java/org/ice4j/ice/LocalCandidate.java @@ -108,8 +108,7 @@ public abstract class LocalCandidate * Candidate * * @deprecated This should be used by the library only. Users of ice4j - * should use {@link org.ice4j.ice.CandidatePair#getDatagramSocket()} - * on the appropriate CandidatePair instead. + * should use {@link org.ice4j.ice.Component#getSocket()} instead. */ @Deprecated public DatagramSocket getDatagramSocket() @@ -126,39 +125,34 @@ public abstract class LocalCandidate * Candidate * * @deprecated This should be used by the library only. Users of ice4j - * should use {@link org.ice4j.ice.CandidatePair#getSocket()} on the - * appropriate CandidatePair instead. + * should use {@link org.ice4j.ice.Component#getSocket()} instead. */ @Deprecated public Socket getSocket() { - IceSocketWrapper wrapper = getIceSocketWrapper(); - return wrapper == null ? null : wrapper.getTCPSocket(); + return null; } /** - * Gets the IceSocketWrapper associated with this - * Candidate. - * - * @return the IceSocketWrapper associated with this - * Candidate + * @return the {@link IceSocketWrapper} instance of the {@link Component} + * which owns this {@link LocalCandidate}. Note that this IS NOT an + * instance specific to this {@link LocalCandidate}. See + * {@link #getCandidateIceSocketWrapper()}. */ - protected abstract IceSocketWrapper getIceSocketWrapper(); - - /** - * Gets the IceSocketWrapper associated with this - * Candidate which is to be used for a specific remote address. - * This default implementation ignores the remote address. - * - * @param remoteAddress the remote address for which to get a socket. - * @return the IceSocketWrapper associated with this - * Candidate which is to be used for a specific remote address. - */ - protected IceSocketWrapper getIceSocketWrapper(SocketAddress remoteAddress) + protected IceSocketWrapper getIceSocketWrapper() { - return getIceSocketWrapper(); + return getParentComponent().getSocketWrapper(); } + /** + * @return the {@link IceSocketWrapper} instance, if any, associated with + * this candidate. Note that this IS NOT the instance which should be used + * for reading and writing by the application, and SHOULD NOT be used from + * outside ice4j (even if a subclass exposes it as public). Also see + * {@link #getIceSocketWrapper()}. + */ + protected abstract IceSocketWrapper getCandidateIceSocketWrapper(); + /** * Creates if necessary and returns a DatagramSocket that would * capture all STUN packets arriving on this candidate's socket. If the @@ -174,7 +168,7 @@ public abstract class LocalCandidate */ public IceSocketWrapper getStunSocket(TransportAddress serverAddress) { - IceSocketWrapper hostSocket = getIceSocketWrapper(); + IceSocketWrapper hostSocket = getCandidateIceSocketWrapper(); if (hostSocket != null && hostSocket.getTCPSocket() != null) @@ -323,7 +317,7 @@ public abstract class LocalCandidate protected void free() { // Close the socket associated with this LocalCandidate. - IceSocketWrapper socket = getIceSocketWrapper(); + IceSocketWrapper socket = getCandidateIceSocketWrapper(); if (socket != null) { @@ -331,7 +325,7 @@ public abstract class LocalCandidate if ((base == null) || (base == this) - || (base.getIceSocketWrapper() != socket)) + || (base.getCandidateIceSocketWrapper() != socket)) { //remove our socket from the stack. getStunStack().removeSocket(getTransportAddress()); diff --git a/src/main/java/org/ice4j/ice/PeerReflexiveCandidate.java b/src/main/java/org/ice4j/ice/PeerReflexiveCandidate.java index 02ea7ab..9ad34f5 100644 --- a/src/main/java/org/ice4j/ice/PeerReflexiveCandidate.java +++ b/src/main/java/org/ice4j/ice/PeerReflexiveCandidate.java @@ -64,15 +64,11 @@ public class PeerReflexiveCandidate } /** - * Returns the DatagramSocket associated with this - * Candidate. - * - * @return the DatagramSocket associated with this - * Candidate - * @see LocalCandidate#getIceSocketWrapper() + * {@inheritDoc} */ - public IceSocketWrapper getIceSocketWrapper() + @Override + public IceSocketWrapper getCandidateIceSocketWrapper() { - return getBase().getIceSocketWrapper(); + return getBase().getCandidateIceSocketWrapper(); } } diff --git a/src/main/java/org/ice4j/ice/RelayedCandidate.java b/src/main/java/org/ice4j/ice/RelayedCandidate.java index 08a89c5..9adf723 100644 --- a/src/main/java/org/ice4j/ice/RelayedCandidate.java +++ b/src/main/java/org/ice4j/ice/RelayedCandidate.java @@ -101,7 +101,7 @@ public class RelayedCandidate * @return the RelayedCandidateDatagramSocket of this * RelayedCandidate */ - public synchronized RelayedCandidateDatagramSocket + private synchronized RelayedCandidateDatagramSocket getRelayedCandidateDatagramSocket() { if (relayedCandidateDatagramSocket == null) @@ -127,9 +127,9 @@ public class RelayedCandidate * * @return the DatagramSocket associated with this * Candidate - * @see LocalCandidate#getIceSocketWrapper() */ - public synchronized IceSocketWrapper getIceSocketWrapper() + @Override + protected synchronized IceSocketWrapper getCandidateIceSocketWrapper() { if (socket == null) { diff --git a/src/main/java/org/ice4j/ice/ServerReflexiveCandidate.java b/src/main/java/org/ice4j/ice/ServerReflexiveCandidate.java index d0105f2..6dc21d5 100644 --- a/src/main/java/org/ice4j/ice/ServerReflexiveCandidate.java +++ b/src/main/java/org/ice4j/ice/ServerReflexiveCandidate.java @@ -104,16 +104,12 @@ public class ServerReflexiveCandidate } /** - * Gets the DatagramSocket associated with this Candidate. - * - * @return the DatagramSocket associated with this - * Candidate - * @see LocalCandidate#getIceSocketWrapper() + * {@inheritDoc} */ @Override - public IceSocketWrapper getIceSocketWrapper() + public IceSocketWrapper getCandidateIceSocketWrapper() { - return getBase().getIceSocketWrapper(); + return getBase().getCandidateIceSocketWrapper(); } /** diff --git a/src/main/java/org/ice4j/ice/TcpHostCandidate.java b/src/main/java/org/ice4j/ice/TcpHostCandidate.java index 8cd96d4..2b70642 100644 --- a/src/main/java/org/ice4j/ice/TcpHostCandidate.java +++ b/src/main/java/org/ice4j/ice/TcpHostCandidate.java @@ -83,16 +83,4 @@ public class TcpHostCandidate super.free(); } - @Override - protected IceSocketWrapper getIceSocketWrapper(SocketAddress remoteAddress) - { - for (IceSocketWrapper socket : sockets) - { - if (socket.getTCPSocket().getRemoteSocketAddress() - .equals(remoteAddress)) - return socket; - } - - return null; - } } diff --git a/src/main/java/org/ice4j/ice/UPNPCandidate.java b/src/main/java/org/ice4j/ice/UPNPCandidate.java index 74646b3..95589e2 100644 --- a/src/main/java/org/ice4j/ice/UPNPCandidate.java +++ b/src/main/java/org/ice4j/ice/UPNPCandidate.java @@ -79,7 +79,7 @@ public class UPNPCandidate { } - IceSocketWrapper socket = getIceSocketWrapper(); + IceSocketWrapper socket = getCandidateIceSocketWrapper(); if(socket != null) { socket.close(); @@ -89,13 +89,19 @@ public class UPNPCandidate } /** - * Gets the DatagramSocket associated with this Candidate. - * - * @return the DatagramSocket associated with this - * Candidate + * {@inheritDoc} */ @Override - public IceSocketWrapper getIceSocketWrapper() + protected IceSocketWrapper getCandidateIceSocketWrapper() + { + return getBase().getCandidateIceSocketWrapper(); + } + + /** + * {@inheritDoc} + */ + @Override + protected IceSocketWrapper getIceSocketWrapper() { return getBase().getIceSocketWrapper(); } diff --git a/src/main/java/org/ice4j/ice/harvest/SinglePortUdpHarvester.java b/src/main/java/org/ice4j/ice/harvest/SinglePortUdpHarvester.java index be9e25c..9ffb0bc 100644 --- a/src/main/java/org/ice4j/ice/harvest/SinglePortUdpHarvester.java +++ b/src/main/java/org/ice4j/ice/harvest/SinglePortUdpHarvester.java @@ -230,26 +230,27 @@ public class SinglePortUdpHarvester * The collection of IceSocketWrappers that can potentially * be used by the ice4j user to read/write from/to this candidate. * The keys are the remote addresses for each socket. - * + *

* There are wrappers over MultiplexedDatagramSockets over * a corresponding socket in {@link #sockets}. */ private final Map candidateSockets - = new HashMap<>(); + = new HashMap<>(); /** * The collection of DatagramSockets added to this candidate. * The keys are the remote addresses for each socket. - * + *

* These are the "raw" sockets, before any wrappers are added for * the STUN stack or the user of ice4j. */ private final Map sockets - = new HashMap<>(); + = new HashMap<>(); /** * Initializes a new MyCandidate instance with the given * Component and the given local username fragment. + * * @param component the Component for which this candidate will * serve. * @param ufrag the local ICE username fragment for this candidate (and @@ -263,7 +264,7 @@ public class SinglePortUdpHarvester /** * {@inheritDoc} - * + *

* Closes all sockets in use by this LocalCandidate. */ @Override @@ -283,20 +284,21 @@ public class SinglePortUdpHarvester StunStack stunStack = getStunStack(); for (Map.Entry e - : sockets.entrySet()) + : sockets.entrySet()) { DatagramSocket socket = e.getValue(); if (stunStack != null) { TransportAddress localAddress - = new TransportAddress(socket.getLocalAddress(), - socket.getLocalPort(), - Transport.UDP); + = new TransportAddress(socket.getLocalAddress(), + socket.getLocalPort(), + Transport.UDP); TransportAddress remoteAddress - = new TransportAddress((InetSocketAddress) e.getKey(), + = new TransportAddress( + (InetSocketAddress) e.getKey(), - Transport.UDP); + Transport.UDP); stunStack.removeSocket(localAddress, remoteAddress); } @@ -318,11 +320,12 @@ public class SinglePortUdpHarvester /** * Adds a new Socket to this candidate, which is associated * with a particular remote address. + * * @param socket the socket to add. * @param remoteAddress the remote address for the socket. */ private synchronized void addSocket(DatagramSocket socket, - InetSocketAddress remoteAddress) + InetSocketAddress remoteAddress) throws IOException { if (freed) @@ -337,16 +340,16 @@ public class SinglePortUdpHarvester } IceProcessingState state - = component.getParentStream().getParentAgent().getState(); + = component.getParentStream().getParentAgent().getState(); if (!IceProcessingState.WAITING.equals(state) - && !IceProcessingState.RUNNING.equals(state)) + && !IceProcessingState.RUNNING.equals(state)) { throw new IOException( - "Agent state is " + state + ". Cannot add socket."); + "Agent state is " + state + ". Cannot add socket."); } MultiplexingDatagramSocket multiplexing - = new MultiplexingDatagramSocket(socket); + = new MultiplexingDatagramSocket(socket); // Socket to add to the candidate IceSocketWrapper candidateSocket @@ -355,12 +358,12 @@ public class SinglePortUdpHarvester // STUN-only filtered socket to add to the StunStack IceSocketWrapper stunSocket = new IceUdpSocketWrapper( - multiplexing.getSocket(new StunDatagramPacketFilter())); + multiplexing.getSocket(new StunDatagramPacketFilter())); component.getParentStream().getParentAgent().getStunStack() - .addSocket( - stunSocket, - new TransportAddress(remoteAddress, Transport.UDP)); + .addSocket( + stunSocket, + new TransportAddress(remoteAddress, Transport.UDP)); // TODO: maybe move this code to the candidates. component.getSocket().add(multiplexing); @@ -377,14 +380,5 @@ public class SinglePortUdpHarvester sockets.put(remoteAddress, socket); } } - - /** - * {@inheritDoc} - */ - @Override - public IceSocketWrapper getIceSocketWrapper(SocketAddress remoteAddress) - { - return candidateSockets.get(remoteAddress); - } } } diff --git a/src/main/java/org/ice4j/socket/RelayedCandidateDatagramSocket.java b/src/main/java/org/ice4j/socket/RelayedCandidateDatagramSocket.java index 1c45e27..63b327b 100644 --- a/src/main/java/org/ice4j/socket/RelayedCandidateDatagramSocket.java +++ b/src/main/java/org/ice4j/socket/RelayedCandidateDatagramSocket.java @@ -208,8 +208,8 @@ public class RelayedCandidateDatagramSocket this); DatagramSocket hostSocket - = this.turnCandidateHarvest.hostCandidate.getIceSocketWrapper(). - getUDPSocket(); + = this.turnCandidateHarvest.hostCandidate + .getCandidateIceSocketWrapper().getUDPSocket(); if (hostSocket instanceof MultiplexingDatagramSocket) { diff --git a/src/test/java/test/IcePseudoTcp.java b/src/test/java/test/IcePseudoTcp.java index 76de9d6..5faa490 100755 --- a/src/test/java/test/IcePseudoTcp.java +++ b/src/test/java/test/IcePseudoTcp.java @@ -386,7 +386,7 @@ public class IcePseudoTcp private static class LocalPseudoTcpJob extends Thread implements Runnable { - private DatagramSocket dgramSocket; + private DatagramSocket dgramSocket; public LocalPseudoTcpJob(DatagramSocket socket) throws UnknownHostException From c378329b8c1a7a5376a8a3fb71528f806936eef1 Mon Sep 17 00:00:00 2001 From: Boris Grozev Date: Tue, 29 Nov 2016 10:53:03 -0600 Subject: [PATCH 12/29] feat: Returns the known socket address for sockets from the single-port mode. --- .../ice/harvest/AbstractUdpListener.java | 43 ++++++++++++++++++- 1 file changed, 41 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/ice4j/ice/harvest/AbstractUdpListener.java b/src/main/java/org/ice4j/ice/harvest/AbstractUdpListener.java index 3ef9840..ddab37e 100644 --- a/src/main/java/org/ice4j/ice/harvest/AbstractUdpListener.java +++ b/src/main/java/org/ice4j/ice/harvest/AbstractUdpListener.java @@ -391,7 +391,7 @@ public abstract class AbstractUdpListener /** * The remote address that is associated with this socket. */ - private SocketAddress remoteAddress; + private InetSocketAddress remoteAddress; /** * The flag which indicates that this DatagramSocket has been @@ -406,7 +406,7 @@ public abstract class AbstractUdpListener * new instance. * @throws SocketException */ - public MySocket(SocketAddress remoteAddress) + MySocket(InetSocketAddress remoteAddress) throws SocketException { // unbound @@ -487,6 +487,45 @@ public abstract class AbstractUdpListener return localAddress; } + /** + * {@inheritDoc} + *

+ * This {@link DatagramSocket} will only allow packets from the + * remote address that it has, so we consider it connected to this + * address. + */ + @Override + public SocketAddress getRemoteSocketAddress() + { + return remoteAddress; + } + + /** + * {@inheritDoc} + *

+ * This {@link DatagramSocket} will only allow packets from the + * remote address that it has, so we consider it connected to this + * address. + */ + @Override + public InetAddress getInetAddress() + { + return remoteAddress.getAddress(); + } + + /** + * {@inheritDoc} + *

+ * This {@link DatagramSocket} will only allow packets from the + * remote address that it has, so we consider it connected to this + * address. + */ + @Override + public int getPort() + { + return remoteAddress.getPort(); + } + /** * {@inheritDoc} * From 82544254c4940943e93da600184f372e4f50ab30 Mon Sep 17 00:00:00 2001 From: Boris Grozev Date: Tue, 29 Nov 2016 12:54:52 -0600 Subject: [PATCH 13/29] feat: Adds candidates' sockets to the component's merging socket. --- .../org/ice4j/ice/GoogleRelayedCandidate.java | 2 +- .../java/org/ice4j/ice/RelayedCandidate.java | 2 +- .../java/org/ice4j/ice/UPNPCandidate.java | 2 +- .../harvest/GoogleTurnCandidateHarvest.java | 8 +++++++ .../GoogleTurnSSLCandidateHarvester.java | 11 +++++----- .../ice/harvest/HostCandidateHarvester.java | 6 +++-- .../ice/harvest/StunCandidateHarvester.java | 11 ++++++---- .../ice/harvest/TurnCandidateHarvest.java | 2 ++ .../org/ice4j/ice/harvest/UPNPHarvester.java | 12 +++++----- .../socket/IceTcpServerSocketWrapper.java | 1 + .../ice4j/socket/MergingDatagramSocket.java | 22 ++++++++++++++++--- 11 files changed, 57 insertions(+), 22 deletions(-) diff --git a/src/main/java/org/ice4j/ice/GoogleRelayedCandidate.java b/src/main/java/org/ice4j/ice/GoogleRelayedCandidate.java index 9a97198..be5e199 100644 --- a/src/main/java/org/ice4j/ice/GoogleRelayedCandidate.java +++ b/src/main/java/org/ice4j/ice/GoogleRelayedCandidate.java @@ -194,7 +194,7 @@ public class GoogleRelayedCandidate * @see LocalCandidate#getCandidateIceSocketWrapper() */ @Override - protected synchronized IceSocketWrapper getCandidateIceSocketWrapper() + public synchronized IceSocketWrapper getCandidateIceSocketWrapper() { if (socket == null) { diff --git a/src/main/java/org/ice4j/ice/RelayedCandidate.java b/src/main/java/org/ice4j/ice/RelayedCandidate.java index 9adf723..8140034 100644 --- a/src/main/java/org/ice4j/ice/RelayedCandidate.java +++ b/src/main/java/org/ice4j/ice/RelayedCandidate.java @@ -129,7 +129,7 @@ public class RelayedCandidate * Candidate */ @Override - protected synchronized IceSocketWrapper getCandidateIceSocketWrapper() + public synchronized IceSocketWrapper getCandidateIceSocketWrapper() { if (socket == null) { diff --git a/src/main/java/org/ice4j/ice/UPNPCandidate.java b/src/main/java/org/ice4j/ice/UPNPCandidate.java index 95589e2..6525d18 100644 --- a/src/main/java/org/ice4j/ice/UPNPCandidate.java +++ b/src/main/java/org/ice4j/ice/UPNPCandidate.java @@ -92,7 +92,7 @@ public class UPNPCandidate * {@inheritDoc} */ @Override - protected IceSocketWrapper getCandidateIceSocketWrapper() + public IceSocketWrapper getCandidateIceSocketWrapper() { return getBase().getCandidateIceSocketWrapper(); } diff --git a/src/main/java/org/ice4j/ice/harvest/GoogleTurnCandidateHarvest.java b/src/main/java/org/ice4j/ice/harvest/GoogleTurnCandidateHarvest.java index d79badc..215717e 100644 --- a/src/main/java/org/ice4j/ice/harvest/GoogleTurnCandidateHarvest.java +++ b/src/main/java/org/ice4j/ice/harvest/GoogleTurnCandidateHarvest.java @@ -133,6 +133,14 @@ public class GoogleTurnCandidateHarvest harvester.getStunStack().addSocket( relayedCandidate.getStunSocket(null)); + // Make the relayed candidate's socket available for reading + // by the component. + IceSocketWrapper candidateSocket + = relayedCandidate.getCandidateIceSocketWrapper(); + + Component component = relayedCandidate.getParentComponent(); + component.getSocket().add(candidateSocket); + addCandidate(relayedCandidate); } } diff --git a/src/main/java/org/ice4j/ice/harvest/GoogleTurnSSLCandidateHarvester.java b/src/main/java/org/ice4j/ice/harvest/GoogleTurnSSLCandidateHarvester.java index eb51111..18639f1 100644 --- a/src/main/java/org/ice4j/ice/harvest/GoogleTurnSSLCandidateHarvester.java +++ b/src/main/java/org/ice4j/ice/harvest/GoogleTurnSSLCandidateHarvester.java @@ -121,7 +121,7 @@ public class GoogleTurnSSLCandidateHarvester /** * Returns the host candidate. - * For UDP it simply returns the candidate passed as paramter + * For UDP it simply returns the candidate passed as parameter * * However for TCP, we cannot return the same hostCandidate because in Java * a "server" socket cannot connect to a destination with the same local @@ -146,11 +146,11 @@ public class GoogleTurnSSLCandidateHarvester if(sslHandshake(inputStream, outputStream)) { Component parentComponent = hostCand.getParentComponent(); + MultiplexingSocket multiplexing = new MultiplexingSocket(sock); cand = new HostCandidate( - new IceTcpSocketWrapper( - new MultiplexingSocket(sock)), + new IceTcpSocketWrapper(multiplexing), parentComponent, Transport.TCP); parentComponent @@ -158,6 +158,7 @@ public class GoogleTurnSSLCandidateHarvester .getParentAgent() .getStunStack() .addSocket(cand.getStunSocket(null)); + parentComponent.getSocket().add(multiplexing); } } catch (Exception e) @@ -187,12 +188,12 @@ public class GoogleTurnSSLCandidateHarvester /** * Do the SSL handshake (send client certificate and wait for receive server - * certificate). We explicitely need InputStream and + * certificate). We explicitly need InputStream and * OutputStream because some Socket may redefine * getInputStream()/getOutputStream() and we need the original stream. * * @param inputStream InputStream of the socket - * @param outputStream OuputStream of the socket + * @param outputStream OutputStream of the socket * @return true if the SSL handshake is done * @throws IOException if something goes wrong */ diff --git a/src/main/java/org/ice4j/ice/harvest/HostCandidateHarvester.java b/src/main/java/org/ice4j/ice/harvest/HostCandidateHarvester.java index 66e42d4..5a7b93a 100644 --- a/src/main/java/org/ice4j/ice/harvest/HostCandidateHarvester.java +++ b/src/main/java/org/ice4j/ice/harvest/HostCandidateHarvester.java @@ -418,6 +418,7 @@ public class HostCandidateHarvester // checks. In case we have enabled STUN, we are going to use // them as well while harvesting reflexive candidates. createAndRegisterStunSocket(candidate); + component.getSocket().add(sock); } } } @@ -569,8 +570,9 @@ public class HostCandidateHarvester sock.setReuseAddress(true); sock.bind(new InetSocketAddress(laddr, port)); IceSocketWrapper socket - = new IceTcpServerSocketWrapper(sock, - component); + = new IceTcpServerSocketWrapper( + new DelegatingServerSocket(sock), + component); if(logger.isLoggable(Level.FINEST)) { diff --git a/src/main/java/org/ice4j/ice/harvest/StunCandidateHarvester.java b/src/main/java/org/ice4j/ice/harvest/StunCandidateHarvester.java index 684f13f..3503ffa 100644 --- a/src/main/java/org/ice4j/ice/harvest/StunCandidateHarvester.java +++ b/src/main/java/org/ice4j/ice/harvest/StunCandidateHarvester.java @@ -441,7 +441,7 @@ public class StunCandidateHarvester */ protected HostCandidate getHostCandidate(HostCandidate hostCand) { - HostCandidate cand = null; + HostCandidate cand; // create a new TCP HostCandidate if(hostCand.getTransport() == Transport.TCP) @@ -450,12 +450,15 @@ public class StunCandidateHarvester { Socket sock = new Socket(stunServer.getAddress(), stunServer.getPort()); - cand = new HostCandidate(new IceTcpSocketWrapper( - new MultiplexingSocket(sock)), - hostCand.getParentComponent(), Transport.TCP); + MultiplexingSocket multiplexing = new MultiplexingSocket(sock); + cand + = new HostCandidate( + new IceTcpSocketWrapper(multiplexing), + hostCand.getParentComponent(), Transport.TCP); hostCand.getParentComponent().getParentStream(). getParentAgent().getStunStack().addSocket( cand.getStunSocket(null)); + hostCand.getParentComponent().getSocket().add(multiplexing); } catch(Exception io) { diff --git a/src/main/java/org/ice4j/ice/harvest/TurnCandidateHarvest.java b/src/main/java/org/ice4j/ice/harvest/TurnCandidateHarvest.java index 926cc45..cb237c4 100644 --- a/src/main/java/org/ice4j/ice/harvest/TurnCandidateHarvest.java +++ b/src/main/java/org/ice4j/ice/harvest/TurnCandidateHarvest.java @@ -258,6 +258,8 @@ public class TurnCandidateHarvest harvester.getStunStack().addSocket( relayedCandidate.getStunSocket(null)); + relayedCandidate.getParentComponent().getSocket().add( + relayedCandidate.getCandidateIceSocketWrapper()); addCandidate(relayedCandidate); } } diff --git a/src/main/java/org/ice4j/ice/harvest/UPNPHarvester.java b/src/main/java/org/ice4j/ice/harvest/UPNPHarvester.java index a838445..8ae0677 100644 --- a/src/main/java/org/ice4j/ice/harvest/UPNPHarvester.java +++ b/src/main/java/org/ice4j/ice/harvest/UPNPHarvester.java @@ -203,25 +203,27 @@ public class UPNPHarvester * @param socket local socket * @param externalIP external IP address * @param port local port - * @param cmp parent component + * @param component parent component * @param device the UPnP gateway device * @return a new UPNPCandidate instance which * represents the specified TransportAddress * @throws Exception if something goes wrong during candidate creation */ - public List createUPNPCandidate(IceSocketWrapper socket, - String externalIP, int port, Component cmp, GatewayDevice device) + private List createUPNPCandidate(IceSocketWrapper socket, + String externalIP, int port, Component component, GatewayDevice device) throws Exception { List ret = new ArrayList<>(); TransportAddress addr = new TransportAddress(externalIP, port, Transport.UDP); - HostCandidate base = new HostCandidate(socket, cmp); + HostCandidate base = new HostCandidate(socket, component); - UPNPCandidate candidate = new UPNPCandidate(addr, base, cmp, device); + UPNPCandidate candidate + = new UPNPCandidate(addr, base, component, device); IceSocketWrapper stunSocket = candidate.getStunSocket(null); candidate.getStunStack().addSocket(stunSocket); + component.getSocket().add(candidate.getCandidateIceSocketWrapper()); ret.add(candidate); ret.add(base); diff --git a/src/main/java/org/ice4j/socket/IceTcpServerSocketWrapper.java b/src/main/java/org/ice4j/socket/IceTcpServerSocketWrapper.java index d6a076b..3a38d7d 100644 --- a/src/main/java/org/ice4j/socket/IceTcpServerSocketWrapper.java +++ b/src/main/java/org/ice4j/socket/IceTcpServerSocketWrapper.java @@ -195,6 +195,7 @@ public class IceTcpServerSocketWrapper component.getParentStream().getParentAgent(). getStunStack().addSocket( new IceTcpSocketWrapper(multiplexingSocket)); + component.getSocket().add(multiplexingSocket); sockets.add(multiplexingSocket); } diff --git a/src/main/java/org/ice4j/socket/MergingDatagramSocket.java b/src/main/java/org/ice4j/socket/MergingDatagramSocket.java index 2c0c30c..9075444 100644 --- a/src/main/java/org/ice4j/socket/MergingDatagramSocket.java +++ b/src/main/java/org/ice4j/socket/MergingDatagramSocket.java @@ -147,6 +147,21 @@ public class MergingDatagramSocket doAdd(socket); } + /** + * Adds the socket instance wrapped by {@code wrapper} to this merging + * socket. Note that this will start a thread reading from the added socket. + * @param wrapper the wrapper of the socket to add. + */ + public void add(IceSocketWrapper wrapper) + { + Object socket = wrapper.getUDPSocket(); + if (socket == null) + { + socket = wrapper.getTCPSocket(); + } + doAdd(socket); + } + /** * Adds a {@link DatagramSocket} instance to this merging socket. Note * that this will start a thread reading from the added socket. @@ -171,12 +186,13 @@ public class MergingDatagramSocket */ private void doAdd(Object socket) { + Objects.requireNonNull(socket, "socket"); + if (!(socket instanceof DelegatingSocket) && !(socket instanceof DatagramSocket)) { - logger.severe("Unsupported class: " - + (socket == null ? "null" : socket.getClass())); - return; + throw new IllegalStateException("Socket type not supported: " + + socket.getClass().getName()); } synchronized (socketContainersSyncRoot) From 67f301eebc8d5ee7dd21b858d1ff5d0c09807f66 Mon Sep 17 00:00:00 2001 From: Boris Grozev Date: Tue, 29 Nov 2016 16:12:11 -0600 Subject: [PATCH 14/29] feat: Implements MergingDatagramSocket#close(). --- src/main/java/org/ice4j/ice/Component.java | 2 + .../ice4j/socket/MergingDatagramSocket.java | 74 +++++++++++++++---- .../ice4j/socket/SocketClosedException.java | 37 ++++++++++ 3 files changed, 97 insertions(+), 16 deletions(-) create mode 100644 src/main/java/org/ice4j/socket/SocketClosedException.java diff --git a/src/main/java/org/ice4j/ice/Component.java b/src/main/java/org/ice4j/ice/Component.java index 0c771e8..9ffdc2e 100644 --- a/src/main/java/org/ice4j/ice/Component.java +++ b/src/main/java/org/ice4j/ice/Component.java @@ -806,6 +806,8 @@ public class Component localCandidateIter.remove(); } } + + getSocket().close(); } /** diff --git a/src/main/java/org/ice4j/socket/MergingDatagramSocket.java b/src/main/java/org/ice4j/socket/MergingDatagramSocket.java index 9075444..7b1d179 100644 --- a/src/main/java/org/ice4j/socket/MergingDatagramSocket.java +++ b/src/main/java/org/ice4j/socket/MergingDatagramSocket.java @@ -80,6 +80,11 @@ public class MergingDatagramSocket */ private SocketContainer active = null; + /** + * The flag which indicates whether this socket is closed. + */ + private boolean closed = false; + /** * Initializes a new {@link MergingDatagramSocket} instance. * @throws SocketException @@ -88,6 +93,37 @@ public class MergingDatagramSocket throws SocketException {} + /** + * {@inheritDoc} + */ + @Override + public boolean isClosed() + { + return closed; + } + + /** + * {@inheritDoc} + */ + @Override + public void close() + { + if (isClosed()) + { + return; + } + + // TODO: close all containers + + closed = true; + // XXX do we want to risk obtaining the lock here, or should we just + // let any thread in find out about the close after it's next timeout? + synchronized (receiveLock) + { + receiveLock.notifyAll(); + } + } + /** * {@inheritDoc} */ @@ -128,7 +164,6 @@ public class MergingDatagramSocket { throw new IOException("No active socket."); } - } /** @@ -386,10 +421,14 @@ public class MergingDatagramSocket * underlying sockets. The socket is chosen on the base of the timestamp * of the reception of the first packet in its queue (so that earlier * packets are received first). + * @throws SocketTimeoutException if a socket timeout is set, and the + * call fails to receive a packet within the timeout. + * @throws SocketClosedException if the socket is closed while */ @Override public void receive(DatagramPacket p) - throws SocketTimeoutException + throws SocketTimeoutException, + SocketClosedException { long start = System.currentTimeMillis(); int soTimeout = this.soTimeout; @@ -405,6 +444,11 @@ public class MergingDatagramSocket { do { + if (isClosed()) + { + throw new SocketClosedException(); + } + // Find the input socket with the oldest packet SocketContainer[] socketContainers = this.socketContainers; SocketContainer socketToReceiveFrom = null; @@ -431,22 +475,20 @@ public class MergingDatagramSocket // Otherwise wait on receiveLock. else { + long waitTimeout = 500; + if (soTimeout > 0) + { + long remaining + = start + soTimeout + - System.currentTimeMillis(); + if (remaining <= 0) + throw new SocketTimeoutException(); + + waitTimeout = Math.min(waitTimeout, remaining); + } try { - if (soTimeout > 0) - { - long remaining - = start + soTimeout - - System.currentTimeMillis(); - if (remaining <= 0) - throw new SocketTimeoutException(); - - receiveLock.wait(remaining); - } - else - { - receiveLock.wait(); - } + receiveLock.wait(waitTimeout); } catch (InterruptedException ie) { diff --git a/src/main/java/org/ice4j/socket/SocketClosedException.java b/src/main/java/org/ice4j/socket/SocketClosedException.java new file mode 100644 index 0000000..a9c092e --- /dev/null +++ b/src/main/java/org/ice4j/socket/SocketClosedException.java @@ -0,0 +1,37 @@ +/* + * ice4j, the OpenSource Java Solution for NAT and Firewall Traversal. + * + * Copyright @ 2015-2016 Atlassian Pty Ltd + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.ice4j.socket; + +import java.net.*; + +/** + * An exception that indicates that a socket is closed. + */ +public class SocketClosedException + extends SocketException +{ + /** + * Initializes a new {@link SocketClosedException}. + */ + public SocketClosedException() + { + // Keep the same message as the one used by jdk, since existing code + // might be matching against the string. + super("Socket closed"); + } +} From ff6eeb343ee9b840abf953f06fa3687c052ffdd5 Mon Sep 17 00:00:00 2001 From: Boris Grozev Date: Tue, 29 Nov 2016 16:29:45 -0600 Subject: [PATCH 15/29] feat: Closes all socket containers when the the merging socket closes. --- .../ice4j/socket/MergingDatagramSocket.java | 51 ++++++++++++++++--- 1 file changed, 44 insertions(+), 7 deletions(-) diff --git a/src/main/java/org/ice4j/socket/MergingDatagramSocket.java b/src/main/java/org/ice4j/socket/MergingDatagramSocket.java index 7b1d179..e994feb 100644 --- a/src/main/java/org/ice4j/socket/MergingDatagramSocket.java +++ b/src/main/java/org/ice4j/socket/MergingDatagramSocket.java @@ -112,16 +112,22 @@ public class MergingDatagramSocket { return; } - - // TODO: close all containers - closed = true; + // XXX do we want to risk obtaining the lock here, or should we just // let any thread in find out about the close after it's next timeout? synchronized (receiveLock) { receiveLock.notifyAll(); } + + synchronized (socketContainersSyncRoot) + { + for (SocketContainer container : socketContainers) + { + doRemove(container.getSocket()); + } + } } /** @@ -334,10 +340,8 @@ public class MergingDatagramSocket } if (socketContainer != null) { - // Stop the reading thread. - // TODO: do we want to interrupt the thread here? This will not - // help unless we set a soTimeout > 0 - socketContainer.closed = true; + // We just removed it from the merging socket, so use remove=false + socketContainer.close(false); } } @@ -665,6 +669,10 @@ public class MergingDatagramSocket } } + // The receive thread is terminating, no reason to keep this + // container anymore. + close(true); + if (logger.isLoggable(Level.FINE)) { logger.fine("Finished: " + toString()); @@ -860,6 +868,35 @@ public class MergingDatagramSocket } } + /** + * @return the underlying socket of this {@link SocketContainer}. + */ + private Object getSocket() + { + return datagramSocket != null ? datagramSocket : delegatingSocket; + } + + /** + * Closes this {@link SocketContainer}, stopping it's reading thread, + * and, if necessary removing it from the merging socket. + * @param remove whether to remove this container from the merging + * socket. + */ + private void close(boolean remove) + { + if (closed && !remove) + { + return; + } + closed = true; + + thread.interrupt(); + if (remove) + { + MergingDatagramSocket.this.doRemove(getSocket()); + } + } + /** * Represents a {@link DatagramPacket} for the purposes of {@link * SocketContainer}. From 6603ac3c28b45433fb9a52deb4a1c754ca7e5a1b Mon Sep 17 00:00:00 2001 From: Boris Grozev Date: Wed, 30 Nov 2016 10:44:36 -0600 Subject: [PATCH 16/29] cleanup: Removes an unused and confusing method. --- src/main/java/org/ice4j/ice/IceMediaStream.java | 12 ------------ 1 file changed, 12 deletions(-) diff --git a/src/main/java/org/ice4j/ice/IceMediaStream.java b/src/main/java/org/ice4j/ice/IceMediaStream.java index ea11e68..bf7826b 100644 --- a/src/main/java/org/ice4j/ice/IceMediaStream.java +++ b/src/main/java/org/ice4j/ice/IceMediaStream.java @@ -272,18 +272,6 @@ public class IceMediaStream } } - /** - * Returns the number of Components currently registered with this - * stream. - * - * @return the number of Components currently registered with this - * stream. - */ - public int getStreamCount() - { - return getComponentCount(); - } - /** * Returns a reference to the Agent that this stream belongs to. * From d0afb0a55b12352264718bc6f7d48a8401822d25 Mon Sep 17 00:00:00 2001 From: Boris Grozev Date: Wed, 30 Nov 2016 10:51:55 -0600 Subject: [PATCH 17/29] style: Field order, whitespace, spelling. --- src/main/java/org/ice4j/ice/Agent.java | 10 +-- .../java/org/ice4j/ice/CandidatePair.java | 4 +- .../ice4j/ice/ConnectivityCheckClient.java | 57 ++++++++-------- .../java/org/ice4j/ice/DefaultNominator.java | 52 +++++++-------- .../java/org/ice4j/ice/IceMediaStream.java | 65 +++++++++---------- 5 files changed, 95 insertions(+), 93 deletions(-) diff --git a/src/main/java/org/ice4j/ice/Agent.java b/src/main/java/org/ice4j/ice/Agent.java index 1c6fe8b..59be43b 100644 --- a/src/main/java/org/ice4j/ice/Agent.java +++ b/src/main/java/org/ice4j/ice/Agent.java @@ -761,9 +761,9 @@ public class Agent */ public void addStateChangeListener(PropertyChangeListener l) { - synchronized(stateListeners) + synchronized (stateListeners) { - if(!stateListeners.contains(l)) + if (!stateListeners.contains(l)) stateListeners.add(l); } } @@ -776,7 +776,7 @@ public class Agent */ public void removeStateChangeListener(PropertyChangeListener l) { - synchronized(stateListeners) + synchronized (stateListeners) { stateListeners.remove(l); } @@ -794,7 +794,7 @@ public class Agent { PropertyChangeListener[] stateListenersCopy; - synchronized(stateListeners) + synchronized (stateListeners) { stateListenersCopy = stateListeners.toArray(NO_STATE_CHANGE_LISTENERS); @@ -808,7 +808,7 @@ public class Agent PROPERTY_ICE_PROCESSING_STATE, oldState, newState); - for(PropertyChangeListener l : stateListenersCopy) + for (PropertyChangeListener l : stateListenersCopy) l.propertyChange(evt); } } diff --git a/src/main/java/org/ice4j/ice/CandidatePair.java b/src/main/java/org/ice4j/ice/CandidatePair.java index f0a165f..03a54b8 100644 --- a/src/main/java/org/ice4j/ice/CandidatePair.java +++ b/src/main/java/org/ice4j/ice/CandidatePair.java @@ -290,13 +290,13 @@ public class CandidatePair this.state = newState; - if(newState == CandidatePairState.IN_PROGRESS) + if (newState == CandidatePairState.IN_PROGRESS) { if (tranID == null) { throw new IllegalArgumentException( "Putting a pair into the In-Progress state MUST be" - + " accomapnied with the TransactionID of the" + + " accompanied with the TransactionID of the" + " connectivity check."); } } diff --git a/src/main/java/org/ice4j/ice/ConnectivityCheckClient.java b/src/main/java/org/ice4j/ice/ConnectivityCheckClient.java index 196e643..3aad967 100644 --- a/src/main/java/org/ice4j/ice/ConnectivityCheckClient.java +++ b/src/main/java/org/ice4j/ice/ConnectivityCheckClient.java @@ -175,7 +175,7 @@ class ConnectivityCheckClient indication, candidatePair.getRemoteCandidate().getTransportAddress(), localCandidate.getBase().getTransportAddress()); - if(logger.isLoggable(Level.FINEST)) + if (logger.isLoggable(Level.FINEST)) { logger.finest( "sending binding indication to pair " + candidatePair); @@ -185,7 +185,7 @@ class ConnectivityCheckClient { IceSocketWrapper stunSocket = localCandidate.getStunSocket(null); - if(stunSocket != null) + if (stunSocket != null) { logger.log( Level.INFO, @@ -282,7 +282,7 @@ class ConnectivityCheckClient .getParentComponent().getParentStream().getName(); String localUserName = parentAgent.generateLocalUserName(media); - if(localUserName == null) + if (localUserName == null) return null; UsernameAttribute unameAttr @@ -322,7 +322,7 @@ class ConnectivityCheckClient originalWaitInterval, maxWaitInterval, maxRetransmissions); - if(logger.isLoggable(Level.FINEST)) + if (logger.isLoggable(Level.FINEST)) { logger.finest( "checking pair " + candidatePair + " tid " + tran); @@ -334,13 +334,13 @@ class ConnectivityCheckClient IceSocketWrapper stunSocket = localCandidate.getStunSocket(null); - if(stunSocket != null) + if (stunSocket != null) { String msg = "Failed to send " + request + " through " + stunSocket.getLocalSocketAddress() + "."; - if((ex instanceof NoRouteToHostException) + if ((ex instanceof NoRouteToHostException) || (ex.getMessage() != null && ex.getMessage().equals("No route to host"))) { @@ -383,9 +383,9 @@ class ConnectivityCheckClient char messageType = response.getMessageType(); //handle error responses. - if(messageType == Response.BINDING_ERROR_RESPONSE) + if (messageType == Response.BINDING_ERROR_RESPONSE) { - if(!response.containsAttribute(Attribute.ERROR_CODE)) + if (!response.containsAttribute(Attribute.ERROR_CODE)) { logger.fine("Received a malformed error response."); return; //malformed error response @@ -394,7 +394,7 @@ class ConnectivityCheckClient processErrorResponse(ev); } //handle success responses. - else if(messageType == Response.BINDING_SUCCESS_RESPONSE) + else if (messageType == Response.BINDING_SUCCESS_RESPONSE) { processSuccessResponse(ev); } @@ -419,12 +419,12 @@ class ConnectivityCheckClient = checkedPair.getParentComponent().getParentStream(); final CheckList checkList = stream.getCheckList(); - if(stream.getParentAgent().getState().isEstablished()) + if (stream.getParentAgent().getState().isEstablished()) return; //If all of the pairs in the check list are now either in the Failed or //Succeeded state: - if(checkList.allChecksCompleted()) + if (checkList.allChecksCompleted()) { //If there is not a pair in the valid list for each component of the //media stream, the state of the check list is set to Failed. @@ -433,7 +433,7 @@ class ConnectivityCheckClient final String streamName = stream.getName(); Timer timer = timers.get(streamName); - if(timer == null) + if (timer == null) { logger.info("CheckList will failed in a few seconds if no" + "succeeded checks come"); @@ -443,7 +443,7 @@ class ConnectivityCheckClient @Override public void run() { - if(checkList.getState() != CheckListState.COMPLETED) + if (checkList.getState() != CheckListState.COMPLETED) { logger.info("CheckList for stream " + streamName + " FAILED"); @@ -471,7 +471,7 @@ class ConnectivityCheckClient { CheckList anotherCheckList = anotherStream.getCheckList(); - if(anotherCheckList.isFrozen()) + if (anotherCheckList.isFrozen()) { anotherCheckList.computeInitialCheckListPairStates(); startChecks(anotherCheckList); @@ -609,8 +609,11 @@ class ConnectivityCheckClient //Succeeded. Note that, the pair which *generated* the check may be //different than the valid pair constructed above if (checkedPair.getParentComponent().getSelectedPair() == null) + { logger.info("Pair succeeded: " + checkedPair.toShortString() - + ". Local ufrag " + parentAgent.getLocalUfrag()); + + ". Local ufrag " + + parentAgent.getLocalUfrag()); + } checkedPair.setStateSucceeded(); } @@ -627,12 +630,12 @@ class ConnectivityCheckClient IceMediaStream parentStream = checkedPair.getParentComponent().getParentStream(); - synchronized(this) + synchronized (this) { Vector parentCheckList = new Vector<>(parentStream.getCheckList()); - for(CandidatePair pair : parentCheckList) + for (CandidatePair pair : parentCheckList) { if (pair.getState() == CandidatePairState.FROZEN && checkedPair.getFoundation().equals( @@ -699,7 +702,7 @@ class ConnectivityCheckClient if (parentAgent.isControlling() && request.containsAttribute(Attribute.USE_CANDIDATE)) { - if(validPair.getParentComponent().getSelectedPair() == null) + if (validPair.getParentComponent().getSelectedPair() == null) { logger.info("Nomination confirmed for pair: " + validPair.toShortString() @@ -721,7 +724,7 @@ class ConnectivityCheckClient && checkedPair.useCandidateReceived() && !checkedPair.isNominated()) { - if(checkedPair.getParentComponent().getSelectedPair() == null) + if (checkedPair.getParentComponent().getSelectedPair() == null) { logger.info( "Nomination confirmed for pair: " @@ -800,12 +803,12 @@ class ConnectivityCheckClient logger.finer("Received error code " + ((int) errorCode)); //RESOLVE ROLE_CONFLICTS - if(errorCode == ErrorCodeAttribute.ROLE_CONFLICT) + if (errorCode == ErrorCodeAttribute.ROLE_CONFLICT) { boolean wasControlling = originalRequest.containsAttribute(Attribute.ICE_CONTROLLING); - logger.finer("Swithing to isControlling=" + !wasControlling); + logger.finer("Switching to isControlling=" + !wasControlling); parentAgent.setControlling(!wasControlling); pair.getParentComponent().getParentStream().getCheckList() @@ -916,7 +919,7 @@ class ConnectivityCheckClient { long waitFor = getNextWaitInterval(); - if(waitFor > 0) + if (waitFor > 0) { /* * waitFor will be 0 for the first check since we won't @@ -939,10 +942,10 @@ class ConnectivityCheckClient CandidatePair pairToCheck = checkList.popTriggeredCheck(); //if there are no triggered checks, go for an ordinary one. - if(pairToCheck == null) + if (pairToCheck == null) pairToCheck = checkList.getNextOrdinaryPairToCheck(); - if(pairToCheck != null) + if (pairToCheck != null) { /* * Since we suspect that it is possible to @@ -956,7 +959,7 @@ class ConnectivityCheckClient TransactionID transactionID = startCheckForPair(pairToCheck); - if(transactionID == null) + if (transactionID == null) { logger.info( "Pair failed: " @@ -983,7 +986,7 @@ class ConnectivityCheckClient { synchronized (paceMakers) { - synchronized(this) + synchronized (this) { paceMakers.remove(this); } @@ -1005,7 +1008,7 @@ class ConnectivityCheckClient { PaceMaker paceMaker = paceMakersIter.next(); - synchronized(paceMaker) + synchronized (paceMaker) { paceMaker.running = false; paceMaker.notify(); diff --git a/src/main/java/org/ice4j/ice/DefaultNominator.java b/src/main/java/org/ice4j/ice/DefaultNominator.java index 0229d21..21e113c 100644 --- a/src/main/java/org/ice4j/ice/DefaultNominator.java +++ b/src/main/java/org/ice4j/ice/DefaultNominator.java @@ -52,7 +52,7 @@ public class DefaultNominator /** * Map that will remember association between validated relayed candidate - * and a timer. It is use with the NOMINATE_FIRST_HIGHEST_VALID strategy. + * and a timer. It is used with the NOMINATE_FIRST_HIGHEST_VALID strategy. */ private final Map validatedCandidates = new HashMap<>(); @@ -86,12 +86,12 @@ public class DefaultNominator { String propertyName = ev.getPropertyName(); - if(Agent.PROPERTY_ICE_PROCESSING_STATE.equals(propertyName)) + if (Agent.PROPERTY_ICE_PROCESSING_STATE.equals(propertyName)) { - if(ev.getNewValue() != IceProcessingState.RUNNING) + if (ev.getNewValue() != IceProcessingState.RUNNING) return; - for(IceMediaStream stream : parentAgent.getStreams()) + for (IceMediaStream stream : parentAgent.getStreams()) { stream.addPairChangeListener(this); stream.getCheckList().addStateChangeListener(this); @@ -104,7 +104,7 @@ public class DefaultNominator return; } - if(ev.getSource() instanceof CandidatePair) + if (ev.getSource() instanceof CandidatePair) { // STUN Usage for Consent Freshness is of no concern here. if (IceMediaStream.PROPERTY_PAIR_CONSENT_FRESHNESS_CHANGED.equals( @@ -115,7 +115,7 @@ public class DefaultNominator // do not nominate pair if there is currently a selected pair for // the component - if(validPair.getParentComponent().getSelectedPair() != null) + if (validPair.getParentComponent().getSelectedPair() != null) { logger.fine( "Keep-alive for pair: " + validPair.toShortString()); @@ -141,7 +141,8 @@ public class DefaultNominator */ private void strategyNominateFirstValid(PropertyChangeEvent evt) { - if(IceMediaStream.PROPERTY_PAIR_VALIDATED.equals(evt.getPropertyName())) + if (IceMediaStream.PROPERTY_PAIR_VALIDATED + .equals(evt.getPropertyName())) { CandidatePair validPair = (CandidatePair)evt.getSource(); @@ -163,7 +164,7 @@ public class DefaultNominator { String pname = ev.getPropertyName(); - if(IceMediaStream.PROPERTY_PAIR_VALIDATED.equals(pname) + if (IceMediaStream.PROPERTY_PAIR_VALIDATED.equals(pname) || (IceMediaStream.PROPERTY_PAIR_STATE_CHANGED.equals(pname) && (ev.getNewValue() == CandidatePairState.FAILED))) { @@ -172,14 +173,14 @@ public class DefaultNominator IceMediaStream parentStream = parentComponent.getParentStream(); CheckList parentCheckList = parentStream.getCheckList(); - if(!parentCheckList.allChecksCompleted()) + if (!parentCheckList.allChecksCompleted()) return; - for(Component component : parentStream.getComponents()) + for (Component component : parentStream.getComponents()) { CandidatePair pair = parentStream.getValidPair(component); - if(pair != null) + if (pair != null) { logger.info( "Nominate (highest priority): " @@ -215,7 +216,7 @@ public class DefaultNominator private void strategyNominateFirstHostOrReflexiveValid( PropertyChangeEvent evt) { - if(IceMediaStream.PROPERTY_PAIR_VALIDATED.equals(evt.getPropertyName())) + if (IceMediaStream.PROPERTY_PAIR_VALIDATED.equals(evt.getPropertyName())) { CandidatePair validPair = (CandidatePair) evt.getSource(); @@ -229,12 +230,12 @@ public class DefaultNominator CandidateType.RELAYED_CANDIDATE); boolean nominate = false; - synchronized(validatedCandidates) + synchronized (validatedCandidates) { TimerTask task = validatedCandidates.get(component.toShortString()); - if(isRelayed && task == null) + if (isRelayed && task == null) { /* armed a timer and see if a host or server reflexive pair * gets nominated. Otherwise nominate the relayed candidate @@ -247,10 +248,10 @@ public class DefaultNominator timer.schedule(task, 0); validatedCandidates.put(component.toShortString(), task); } - else if(!isRelayed) + else if (!isRelayed) { // host or server reflexive candidate pair - if(task != null) + if (task != null) { task.cancel(); logger.info( @@ -265,7 +266,7 @@ public class DefaultNominator } } - if(nominate) + if (nominate) parentAgent.nominate(validPair); } } @@ -314,18 +315,17 @@ public class DefaultNominator */ public void propertyChange(PropertyChangeEvent evt) { - /* check list has running out of ordinary checks, see if all other - * candidates are FAILED, in which case we nominate immediately - * the relayed candidate - */ + // check list has running out of ordinary checks, see if all other + // candidates are FAILED, in which case we nominate immediately + // the relayed candidate CheckList checkList = (CheckList)evt.getSource(); boolean allFailed = true; - synchronized(checkList) + synchronized (checkList) { - for(CandidatePair c : checkList) + for (CandidatePair c : checkList) { - if(c != pair && c.getState() != CandidatePairState.FAILED) + if (c != pair && c.getState() != CandidatePairState.FAILED) { allFailed = false; break; @@ -365,7 +365,7 @@ public class DefaultNominator { Thread.sleep(WAIT_TIME); } - catch(InterruptedException e) + catch (InterruptedException e) { cancelled = true; } @@ -376,7 +376,7 @@ public class DefaultNominator this); validatedCandidates.remove(component.toShortString()); - if(cancelled) + if (cancelled) return; logger.info( diff --git a/src/main/java/org/ice4j/ice/IceMediaStream.java b/src/main/java/org/ice4j/ice/IceMediaStream.java index bf7826b..894293c 100644 --- a/src/main/java/org/ice4j/ice/IceMediaStream.java +++ b/src/main/java/org/ice4j/ice/IceMediaStream.java @@ -68,6 +68,19 @@ public class IceMediaStream */ public static final String PROPERTY_PAIR_VALIDATED = "PairValidated"; + /** + * Use builder pattern to provide an immutable IceMediaStream instance. + * + * @param name the name of the media stream + * @param parentAgent the agent that is handling the session that this + * media stream is a part of + * @return IceMediaStream + */ + public static IceMediaStream build(Agent parentAgent, String name) + { + return new IceMediaStream(parentAgent, name); + } + /** * The name of this media stream. The name is equal to the value specified * in the SDP description. @@ -557,12 +570,12 @@ public class IceMediaStream { synchronized(checkList) { - for( CandidatePair pair : checkList) + for (CandidatePair pair : checkList) { - if( pair.getLocalCandidate().getTransportAddress() + if (pair.getLocalCandidate().getTransportAddress() .equals(localAddress) && pair.getRemoteCandidate().getTransportAddress() - .equals(remoteAddress) ) + .equals(remoteAddress)) { return pair; } @@ -587,12 +600,12 @@ public class IceMediaStream { synchronized(checkList) { - for( CandidatePair pair : checkList) + for (CandidatePair pair : checkList) { LocalCandidate local = pair.getLocalCandidate(); RemoteCandidate remote = pair.getRemoteCandidate(); - if(local.getUfrag().equals(remoteUFrag) + if (local.getUfrag().equals(remoteUFrag) && remote.getUfrag().equals(localUFrag)) { return pair; @@ -613,7 +626,7 @@ public class IceMediaStream synchronized (components) { - for(Component cmp : components.values()) + for (Component cmp : components.values()) num += cmp.countLocalHostCandidates(); } @@ -645,7 +658,7 @@ public class IceMediaStream { synchronized (validList) { - if(!validList.contains(pair)) + if (!validList.contains(pair)) validList.add(pair); } @@ -666,7 +679,7 @@ public class IceMediaStream { synchronized(validList) { - for(CandidatePair pair : validList) + for (CandidatePair pair : validList) { if (pair.getFoundation().equals(foundation)) return true; @@ -714,7 +727,7 @@ public class IceMediaStream */ protected boolean validListContainsAllComponents() { - for(Component cmp : getComponents()) + for (Component cmp : getComponents()) { if (getValidPair(cmp) == null) { @@ -762,9 +775,9 @@ public class IceMediaStream */ protected boolean allComponentsHaveSelected() { - for(Component component : getComponents()) + for (Component component : getComponents()) { - if(component.getSelectedPair() == null) + if (component.getSelectedPair() == null) return false; } return true; @@ -782,11 +795,11 @@ public class IceMediaStream */ protected CandidatePair getValidPair(Component component) { - synchronized(validList) + synchronized (validList) { - for(CandidatePair pair : validList) + for (CandidatePair pair : validList) { - if(pair.getParentComponent() == component) + if (pair.getParentComponent() == component) return pair; } } @@ -803,9 +816,9 @@ public class IceMediaStream */ public void addPairChangeListener(PropertyChangeListener l) { - synchronized(streamListeners) + synchronized (streamListeners) { - if(!streamListeners.contains(l)) + if (!streamListeners.contains(l)) streamListeners.add(l); } } @@ -818,7 +831,7 @@ public class IceMediaStream */ public void removePairStateChangeListener(PropertyChangeListener l) { - synchronized(streamListeners) + synchronized (streamListeners) { streamListeners.remove(l); } @@ -840,7 +853,7 @@ public class IceMediaStream { PropertyChangeListener[] ls; - synchronized(streamListeners) + synchronized (streamListeners) { ls = streamListeners.toArray( @@ -850,7 +863,7 @@ public class IceMediaStream PropertyChangeEvent ev = new PropertyChangeEvent(source, propertyName, oldValue, newValue); - for(PropertyChangeListener l : ls) + for (PropertyChangeListener l : ls) l.propertyChange(ev); } @@ -898,18 +911,4 @@ public class IceMediaStream { return remotePassword; } - - /** - * Use builder pattern to provide an immutable IceMediaStream instance. - * - * @param name the name of the media stream - * @param parentAgent the agent that is handling the session that this - * media stream is a part of - * @return IceMediaStream - */ - public static IceMediaStream build(Agent parentAgent, String name) - { - return new IceMediaStream(parentAgent, name); - } - } From 633f05b4e5bffc2baa7225ab685f1e1e078c788b Mon Sep 17 00:00:00 2001 From: Boris Grozev Date: Wed, 30 Nov 2016 15:17:33 -0600 Subject: [PATCH 18/29] feat: Verifies the remove address of packets passed on to the application. --- src/main/java/org/ice4j/ice/Component.java | 2 +- .../java/org/ice4j/ice/ComponentSocket.java | 161 ++++++++++++++++++ .../ice4j/socket/MergingDatagramSocket.java | 49 +++++- 3 files changed, 207 insertions(+), 5 deletions(-) create mode 100644 src/main/java/org/ice4j/ice/ComponentSocket.java diff --git a/src/main/java/org/ice4j/ice/Component.java b/src/main/java/org/ice4j/ice/Component.java index 9ffdc2e..e8147b6 100644 --- a/src/main/java/org/ice4j/ice/Component.java +++ b/src/main/java/org/ice4j/ice/Component.java @@ -152,7 +152,7 @@ public class Component try { - mergingDatagramSocket = new MergingDatagramSocket(); + mergingDatagramSocket = new ComponentSocket(this); mergingDatagramSocketWrapper = new IceUdpSocketWrapper( new MultiplexingDatagramSocket( diff --git a/src/main/java/org/ice4j/ice/ComponentSocket.java b/src/main/java/org/ice4j/ice/ComponentSocket.java new file mode 100644 index 0000000..6760320 --- /dev/null +++ b/src/main/java/org/ice4j/ice/ComponentSocket.java @@ -0,0 +1,161 @@ +/* + * ice4j, the OpenSource Java Solution for NAT and Firewall Traversal. + * + * Copyright @ 2015-2016 Atlassian Pty Ltd + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.ice4j.ice; + +import org.ice4j.socket.*; + +import java.beans.*; +import java.net.*; +import java.util.*; +import java.util.concurrent.*; +import java.util.logging.*; + +/** + * Extends {@link MergingDatagramSocket} with functionality specific to + * an ICE {@link Component}. + */ +class ComponentSocket + extends MergingDatagramSocket + implements PropertyChangeListener +{ + /** + * The {@link Logger} used by the {@link MergingDatagramSocket} class and + * its instances for logging output. + */ + private static final Logger logger + = Logger.getLogger(MergingDatagramSocket.class.getName()); + + /** + * Controls access to {@link #authorizedAddresses}. + */ + private final Object authorizedAddressesSyncRoot = new Object(); + + /** + * The set of remote addresses, which this socket is allowed to receive + * from. These should be the addresses which we have confirmed (e.g. by + * having received a STUN message with correct authentication fields). + */ + private Set authorizedAddresses + = Collections.newSetFromMap( + new ConcurrentHashMap()); + + /** + * The owning {@link Component}. + */ + private Component component; + + /** + * Initializes a new {@link MergingDatagramSocket} instance. + * @throws SocketException + */ + ComponentSocket(Component component) + throws SocketException + { + this.component = component; + component.getParentStream().addPairChangeListener(this); + } + + /** + * {@inheritDoc} + *

+ * Verifies that the source of the packet is an authorized remote address. + */ + protected boolean accept(DatagramPacket p) + { + return authorizedAddresses.contains(p.getSocketAddress()); + } + + /** + * Adds a specific address to the list of authorized remote addresses. + * @param address the address to add. + */ + private void addAuthorizedAddress(SocketAddress address) + { + synchronized (authorizedAddressesSyncRoot) + { + if (authorizedAddresses.contains(address)) + { + return; + } + + logger.info("Adding allowed address: " + address); + + Set newSet + = Collections.newSetFromMap( + new ConcurrentHashMap()); + newSet.addAll(authorizedAddresses); + newSet.add(address); + + authorizedAddresses = newSet; + } + } + + /** + * {@inheritDoc} + *

+ * Handles property change events coming from ICE pairs. + * @param event + */ + @Override + public void propertyChange(PropertyChangeEvent event) + { + String propertyName = event.getPropertyName(); + if (!(event.getSource() instanceof CandidatePair)) + { + return; + } + + CandidatePair pair = (CandidatePair) event.getSource(); + if (!pair.getParentComponent().equals(component)) + { + // Events are fired by the IceMediaStream, which might have + // multiple components. Make sure that we only handle events for + // our own component. + return; + } + + if (IceMediaStream.PROPERTY_PAIR_STATE_CHANGED.equals( + propertyName)) + { + CandidatePairState newState + = (CandidatePairState) event.getNewValue(); + + if (CandidatePairState.SUCCEEDED.equals(newState)) + { + addAuthorizedAddress( + pair.getRemoteCandidate().getTransportAddress()); + } + } + } + + /** + * {@inheritDoc} + */ + @Override + public void close() + { + try + { + super.close(); + } + finally + { + component = null; + } + } +} diff --git a/src/main/java/org/ice4j/socket/MergingDatagramSocket.java b/src/main/java/org/ice4j/socket/MergingDatagramSocket.java index e994feb..ae50d50 100644 --- a/src/main/java/org/ice4j/socket/MergingDatagramSocket.java +++ b/src/main/java/org/ice4j/socket/MergingDatagramSocket.java @@ -78,13 +78,22 @@ public class MergingDatagramSocket * The {@link SocketContainer} considered active, i.e. the one which should * be used for sending. */ - private SocketContainer active = null; + protected SocketContainer active = null; /** * The flag which indicates whether this socket is closed. */ private boolean closed = false; + /** + * The number of packets which were read from an underlying socket, but were + * discarded because they were not accepted by + * {@link #accept(DatagramPacket)}. + * Access to this field should be protected by {@link #receiveLock}. + */ + private int numDiscardedPackets = 0; + + /** * Initializes a new {@link MergingDatagramSocket} instance. * @throws SocketException @@ -108,6 +117,7 @@ public class MergingDatagramSocket @Override public void close() { + logger.info("Closing."); if (isClosed()) { return; @@ -371,7 +381,7 @@ public class MergingDatagramSocket /** * TODO */ - private SocketContainer getActiveSocket() + protected SocketContainer getActiveSocket() { return this.active; } @@ -418,6 +428,20 @@ public class MergingDatagramSocket activeSocket == null ? null : activeSocket.getLocalSocketAddress(); } + /** + * Checks whether a particular {@link DatagramPacket}, received from one of + * the underlying sockets of thins merging socket, should be accepted and + * provided for reception from this {@link MergingDatagramSocket}. + * @param p the packet for which to decide whether to accept it or not. + * @return {@code true} iff {@code p} should be accepted. + */ + protected boolean accept(DatagramPacket p) + { + // By default we accept all packets, and allow extending classes to + // override + return true; + } + /** * {@inheritDoc} *

@@ -470,11 +494,28 @@ public class MergingDatagramSocket } } - // If a packet is available read it + // If a packet is available, receive it if (socketToReceiveFrom != null) { socketToReceiveFrom.receive(p); - return; + + if (accept(p)) + { + return; + } + else + { + numDiscardedPackets++; + if (numDiscardedPackets % 100 == 1) + { + logger.info("Discarded " + numDiscardedPackets + + " packets. Last remote address:" + + p.getSocketAddress()); + } + + // Go on and receive the next packet in p. + continue; + } } // Otherwise wait on receiveLock. else From dae6d32875d756e41761bb9b5190bb82c7b0a0dc Mon Sep 17 00:00:00 2001 From: Boris Grozev Date: Wed, 30 Nov 2016 15:30:42 -0600 Subject: [PATCH 19/29] cleanup: Cleaner closing of MergingDatagramSocket. --- src/main/java/org/ice4j/socket/MergingDatagramSocket.java | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/ice4j/socket/MergingDatagramSocket.java b/src/main/java/org/ice4j/socket/MergingDatagramSocket.java index ae50d50..0e8b6d6 100644 --- a/src/main/java/org/ice4j/socket/MergingDatagramSocket.java +++ b/src/main/java/org/ice4j/socket/MergingDatagramSocket.java @@ -117,15 +117,16 @@ public class MergingDatagramSocket @Override public void close() { - logger.info("Closing."); if (isClosed()) { return; } closed = true; + logger.info("Closing."); // XXX do we want to risk obtaining the lock here, or should we just - // let any thread in find out about the close after it's next timeout? + // let any thread in receive() find out about the close after it's next + // timeout? synchronized (receiveLock) { receiveLock.notifyAll(); @@ -135,8 +136,9 @@ public class MergingDatagramSocket { for (SocketContainer container : socketContainers) { - doRemove(container.getSocket()); + container.close(false); } + socketContainers = new SocketContainer[0]; } } From b4a5e2eb83c1ee700219d662f26da6d795bef33c Mon Sep 17 00:00:00 2001 From: Boris Grozev Date: Thu, 1 Dec 2016 12:01:10 -0600 Subject: [PATCH 20/29] refactor: Refactors the Component's socket API. --- src/main/java/org/ice4j/ice/Component.java | 59 ++++++++++++------- .../java/org/ice4j/ice/ComponentSocket.java | 3 +- .../harvest/GoogleTurnCandidateHarvest.java | 2 +- .../GoogleTurnSSLCandidateHarvester.java | 2 +- .../ice/harvest/HostCandidateHarvester.java | 2 +- .../ice/harvest/SinglePortUdpHarvester.java | 6 +- .../ice/harvest/StunCandidateHarvester.java | 2 +- .../org/ice4j/ice/harvest/TcpHarvester.java | 2 +- .../ice/harvest/TurnCandidateHarvest.java | 2 +- .../org/ice4j/ice/harvest/UPNPHarvester.java | 2 +- .../socket/IceTcpServerSocketWrapper.java | 2 +- 11 files changed, 48 insertions(+), 36 deletions(-) diff --git a/src/main/java/org/ice4j/ice/Component.java b/src/main/java/org/ice4j/ice/Component.java index e8147b6..a306fd3 100644 --- a/src/main/java/org/ice4j/ice/Component.java +++ b/src/main/java/org/ice4j/ice/Component.java @@ -124,16 +124,27 @@ public class Component private final Logger logger; /** - * The {@link MergingDatagramSocket} instance which will serve as the - * single socket instance for this {@link Component}, merging received - * packets from all of its candidates. + * The single {@link ComponentSocket} instance for this {@link Component}, + * which will merge the multiple sockets from the candidate/pairs. */ - private final MergingDatagramSocket mergingDatagramSocket; + private final ComponentSocket componentSocket; /** - * A wrapper around {@link #mergingDatagramSocket}. + * The public view of {@link #componentSocket}, wrapped in a + * {@link MultiplexingDatagramSocket} for the convenience of users of the + * library. + * This is the instance which should be used by applications for + * reading/writing application data. */ - private final IceUdpSocketWrapper mergingDatagramSocketWrapper; + private final MultiplexingDatagramSocket socket; + + /** + * A wrapper around {@link #socket}, kept only to help preserve the old + * API (see {@link LocalCandidate#getIceSocketWrapper()} and + * {@link CandidatePair#getIceSocketWrapper()}) + */ + @Deprecated + private final IceSocketWrapper socketWrapper; /** * Creates a new Component with the specified componentID @@ -152,11 +163,9 @@ public class Component try { - mergingDatagramSocket = new ComponentSocket(this); - mergingDatagramSocketWrapper - = new IceUdpSocketWrapper( - new MultiplexingDatagramSocket( - mergingDatagramSocket)); + componentSocket = new ComponentSocket(this); + socket = new MultiplexingDatagramSocket(componentSocket); + socketWrapper = new IceUdpSocketWrapper(socket); } catch (SocketException se) { @@ -807,7 +816,7 @@ public class Component } } - getSocket().close(); + getComponentSocket().close(); } /** @@ -941,24 +950,30 @@ public class Component } /** - * @return the single socket for this {@link Component} which should be - * used for reading and writing data. + * @return the internal merging socket for this component. This is for + * ice4j use only. + * For reading/writing application data, use {@link #getSocket()}. */ - public MergingDatagramSocket getSocket() + public ComponentSocket getComponentSocket() { - return mergingDatagramSocket; + return componentSocket; + } + + /** + * @return the socket for this {@link Component}, which should be used for + * reading/writing application data. + */ + public MultiplexingDatagramSocket getSocket() + { + return socket; } /** * @return an {@link IceSocketWrapper} instance wrapping the socket for this - * candidate (see {@link #getSocket()}). - * @deprecated Use {@link #getSocket()} directly. This is only introduced - * to ease the transition of applications which are already written to use - * an {@link IceSocketWrapper} instance. + * candidate (see {@link #getComponentSocket()}). */ - @Deprecated public IceSocketWrapper getSocketWrapper() { - return mergingDatagramSocketWrapper; + return socketWrapper; } } diff --git a/src/main/java/org/ice4j/ice/ComponentSocket.java b/src/main/java/org/ice4j/ice/ComponentSocket.java index 6760320..4ff2267 100644 --- a/src/main/java/org/ice4j/ice/ComponentSocket.java +++ b/src/main/java/org/ice4j/ice/ComponentSocket.java @@ -29,7 +29,7 @@ import java.util.logging.*; * Extends {@link MergingDatagramSocket} with functionality specific to * an ICE {@link Component}. */ -class ComponentSocket +public class ComponentSocket extends MergingDatagramSocket implements PropertyChangeListener { @@ -155,6 +155,7 @@ class ComponentSocket } finally { + component.getParentStream().removePairStateChangeListener(this); component = null; } } diff --git a/src/main/java/org/ice4j/ice/harvest/GoogleTurnCandidateHarvest.java b/src/main/java/org/ice4j/ice/harvest/GoogleTurnCandidateHarvest.java index 215717e..4e8e1aa 100644 --- a/src/main/java/org/ice4j/ice/harvest/GoogleTurnCandidateHarvest.java +++ b/src/main/java/org/ice4j/ice/harvest/GoogleTurnCandidateHarvest.java @@ -139,7 +139,7 @@ public class GoogleTurnCandidateHarvest = relayedCandidate.getCandidateIceSocketWrapper(); Component component = relayedCandidate.getParentComponent(); - component.getSocket().add(candidateSocket); + component.getComponentSocket().add(candidateSocket); addCandidate(relayedCandidate); } diff --git a/src/main/java/org/ice4j/ice/harvest/GoogleTurnSSLCandidateHarvester.java b/src/main/java/org/ice4j/ice/harvest/GoogleTurnSSLCandidateHarvester.java index 18639f1..87d913d 100644 --- a/src/main/java/org/ice4j/ice/harvest/GoogleTurnSSLCandidateHarvester.java +++ b/src/main/java/org/ice4j/ice/harvest/GoogleTurnSSLCandidateHarvester.java @@ -158,7 +158,7 @@ public class GoogleTurnSSLCandidateHarvester .getParentAgent() .getStunStack() .addSocket(cand.getStunSocket(null)); - parentComponent.getSocket().add(multiplexing); + parentComponent.getComponentSocket().add(multiplexing); } } catch (Exception e) diff --git a/src/main/java/org/ice4j/ice/harvest/HostCandidateHarvester.java b/src/main/java/org/ice4j/ice/harvest/HostCandidateHarvester.java index 5a7b93a..1dedbf2 100644 --- a/src/main/java/org/ice4j/ice/harvest/HostCandidateHarvester.java +++ b/src/main/java/org/ice4j/ice/harvest/HostCandidateHarvester.java @@ -418,7 +418,7 @@ public class HostCandidateHarvester // checks. In case we have enabled STUN, we are going to use // them as well while harvesting reflexive candidates. createAndRegisterStunSocket(candidate); - component.getSocket().add(sock); + component.getComponentSocket().add(sock); } } } diff --git a/src/main/java/org/ice4j/ice/harvest/SinglePortUdpHarvester.java b/src/main/java/org/ice4j/ice/harvest/SinglePortUdpHarvester.java index 9ffb0bc..c0df2e3 100644 --- a/src/main/java/org/ice4j/ice/harvest/SinglePortUdpHarvester.java +++ b/src/main/java/org/ice4j/ice/harvest/SinglePortUdpHarvester.java @@ -18,18 +18,14 @@ package org.ice4j.ice.harvest; import org.ice4j.*; -import org.ice4j.attribute.*; import org.ice4j.ice.*; -import org.ice4j.message.*; import org.ice4j.socket.*; import org.ice4j.stack.*; -import org.ice4j.util.*; import java.io.*; import java.net.*; import java.util.*; import java.util.concurrent.*; -import java.util.logging.*; import java.util.logging.Logger; // Disambiguation /** @@ -366,7 +362,7 @@ public class SinglePortUdpHarvester new TransportAddress(remoteAddress, Transport.UDP)); // TODO: maybe move this code to the candidates. - component.getSocket().add(multiplexing); + component.getComponentSocket().add(multiplexing); // XXX is this necessary? synchronized (candidateSockets) diff --git a/src/main/java/org/ice4j/ice/harvest/StunCandidateHarvester.java b/src/main/java/org/ice4j/ice/harvest/StunCandidateHarvester.java index 3503ffa..db5390e 100644 --- a/src/main/java/org/ice4j/ice/harvest/StunCandidateHarvester.java +++ b/src/main/java/org/ice4j/ice/harvest/StunCandidateHarvester.java @@ -458,7 +458,7 @@ public class StunCandidateHarvester hostCand.getParentComponent().getParentStream(). getParentAgent().getStunStack().addSocket( cand.getStunSocket(null)); - hostCand.getParentComponent().getSocket().add(multiplexing); + hostCand.getParentComponent().getComponentSocket().add(multiplexing); } catch(Exception io) { diff --git a/src/main/java/org/ice4j/ice/harvest/TcpHarvester.java b/src/main/java/org/ice4j/ice/harvest/TcpHarvester.java index 07ba748..ecd8aa4 100644 --- a/src/main/java/org/ice4j/ice/harvest/TcpHarvester.java +++ b/src/main/java/org/ice4j/ice/harvest/TcpHarvester.java @@ -520,7 +520,7 @@ public class TcpHarvester candidate.addSocket(candidateSocket); // TODO: Maybe move this code to the candidate. - component.getSocket().add(multiplexing); + component.getComponentSocket().add(multiplexing); // the socket is not our responsibility anymore. It is up to // the candidate/component to close/free it. diff --git a/src/main/java/org/ice4j/ice/harvest/TurnCandidateHarvest.java b/src/main/java/org/ice4j/ice/harvest/TurnCandidateHarvest.java index cb237c4..47eb199 100644 --- a/src/main/java/org/ice4j/ice/harvest/TurnCandidateHarvest.java +++ b/src/main/java/org/ice4j/ice/harvest/TurnCandidateHarvest.java @@ -258,7 +258,7 @@ public class TurnCandidateHarvest harvester.getStunStack().addSocket( relayedCandidate.getStunSocket(null)); - relayedCandidate.getParentComponent().getSocket().add( + relayedCandidate.getParentComponent().getComponentSocket().add( relayedCandidate.getCandidateIceSocketWrapper()); addCandidate(relayedCandidate); } diff --git a/src/main/java/org/ice4j/ice/harvest/UPNPHarvester.java b/src/main/java/org/ice4j/ice/harvest/UPNPHarvester.java index 8ae0677..80b0c5e 100644 --- a/src/main/java/org/ice4j/ice/harvest/UPNPHarvester.java +++ b/src/main/java/org/ice4j/ice/harvest/UPNPHarvester.java @@ -223,7 +223,7 @@ public class UPNPHarvester = new UPNPCandidate(addr, base, component, device); IceSocketWrapper stunSocket = candidate.getStunSocket(null); candidate.getStunStack().addSocket(stunSocket); - component.getSocket().add(candidate.getCandidateIceSocketWrapper()); + component.getComponentSocket().add(candidate.getCandidateIceSocketWrapper()); ret.add(candidate); ret.add(base); diff --git a/src/main/java/org/ice4j/socket/IceTcpServerSocketWrapper.java b/src/main/java/org/ice4j/socket/IceTcpServerSocketWrapper.java index 3a38d7d..5535dcf 100644 --- a/src/main/java/org/ice4j/socket/IceTcpServerSocketWrapper.java +++ b/src/main/java/org/ice4j/socket/IceTcpServerSocketWrapper.java @@ -195,7 +195,7 @@ public class IceTcpServerSocketWrapper component.getParentStream().getParentAgent(). getStunStack().addSocket( new IceTcpSocketWrapper(multiplexingSocket)); - component.getSocket().add(multiplexingSocket); + component.getComponentSocket().add(multiplexingSocket); sockets.add(multiplexingSocket); } From d5410b922bb385beb5c9c4812ee80acb43f58e0d Mon Sep 17 00:00:00 2001 From: Boris Grozev Date: Tue, 6 Dec 2016 11:57:32 -0600 Subject: [PATCH 21/29] feat: Adds accessors for candidatates' sockets when they have more than one. --- src/main/java/org/ice4j/ice/LocalCandidate.java | 15 +++++++++++++++ .../java/org/ice4j/ice/TcpHostCandidate.java | 17 +++++++++++++++++ .../ice/harvest/SinglePortUdpHarvester.java | 10 ++++++++++ 3 files changed, 42 insertions(+) diff --git a/src/main/java/org/ice4j/ice/LocalCandidate.java b/src/main/java/org/ice4j/ice/LocalCandidate.java index 560938c..b362b0d 100644 --- a/src/main/java/org/ice4j/ice/LocalCandidate.java +++ b/src/main/java/org/ice4j/ice/LocalCandidate.java @@ -153,6 +153,21 @@ public abstract class LocalCandidate */ protected abstract IceSocketWrapper getCandidateIceSocketWrapper(); + /** + * @return the {@link IceSocketWrapper} instance for this candidate, + * associated with a particular remote address. + * @param remoteAddress the remote address for which to return an + * associated socket. + */ + protected IceSocketWrapper getCandidateIceSocketWrapper( + SocketAddress remoteAddress) + { + // The default implementation just refers to the method which doesn't + // involve a remove address. Extenders which support multiple instances + // mapped by remote address should override. + return getCandidateIceSocketWrapper(); + } + /** * Creates if necessary and returns a DatagramSocket that would * capture all STUN packets arriving on this candidate's socket. If the diff --git a/src/main/java/org/ice4j/ice/TcpHostCandidate.java b/src/main/java/org/ice4j/ice/TcpHostCandidate.java index 2b70642..7d3254f 100644 --- a/src/main/java/org/ice4j/ice/TcpHostCandidate.java +++ b/src/main/java/org/ice4j/ice/TcpHostCandidate.java @@ -54,6 +54,23 @@ public class TcpHostCandidate super(transportAddress, parentComponent); } + /** + * {@inheritDoc} + */ + @Override + protected IceSocketWrapper getCandidateIceSocketWrapper( + SocketAddress remoteAddress) + { + for (IceSocketWrapper socket : sockets) + { + if (socket.getTCPSocket().getRemoteSocketAddress() + .equals(remoteAddress)) + return socket; + } + + return null; + } + public void addSocket(IceSocketWrapper socket) { sockets.add(socket); diff --git a/src/main/java/org/ice4j/ice/harvest/SinglePortUdpHarvester.java b/src/main/java/org/ice4j/ice/harvest/SinglePortUdpHarvester.java index c0df2e3..accb4a5 100644 --- a/src/main/java/org/ice4j/ice/harvest/SinglePortUdpHarvester.java +++ b/src/main/java/org/ice4j/ice/harvest/SinglePortUdpHarvester.java @@ -376,5 +376,15 @@ public class SinglePortUdpHarvester sockets.put(remoteAddress, socket); } } + /** + * {@inheritDoc} + */ + @Override + protected IceSocketWrapper getCandidateIceSocketWrapper( + SocketAddress remoteAddress) + { + return candidateSockets.get(remoteAddress); + } + } } From 9a2fe509d4a6080d43ef7208a911a0841efeb123 Mon Sep 17 00:00:00 2001 From: Boris Grozev Date: Tue, 6 Dec 2016 12:38:45 -0600 Subject: [PATCH 22/29] feat: Initializes the active socket ...when ICE nominates a pair. Sets the correct target for packets sent through MergingDatagramSocket. --- .../java/org/ice4j/ice/ComponentSocket.java | 40 ++++- .../ice4j/socket/MergingDatagramSocket.java | 139 ++++++++++++++++-- 2 files changed, 165 insertions(+), 14 deletions(-) diff --git a/src/main/java/org/ice4j/ice/ComponentSocket.java b/src/main/java/org/ice4j/ice/ComponentSocket.java index 4ff2267..bffde11 100644 --- a/src/main/java/org/ice4j/ice/ComponentSocket.java +++ b/src/main/java/org/ice4j/ice/ComponentSocket.java @@ -17,6 +17,7 @@ */ package org.ice4j.ice; +import org.ice4j.*; import org.ice4j.socket.*; import java.beans.*; @@ -59,6 +60,12 @@ public class ComponentSocket */ private Component component; + /** + * Whether we have invoked {@link #initializeActive}. + */ + private boolean initializedActive = false; + + /** * Initializes a new {@link MergingDatagramSocket} instance. * @throws SocketException @@ -129,8 +136,7 @@ public class ComponentSocket return; } - if (IceMediaStream.PROPERTY_PAIR_STATE_CHANGED.equals( - propertyName)) + if (IceMediaStream.PROPERTY_PAIR_STATE_CHANGED.equals(propertyName)) { CandidatePairState newState = (CandidatePairState) event.getNewValue(); @@ -141,6 +147,36 @@ public class ComponentSocket pair.getRemoteCandidate().getTransportAddress()); } } + else if (IceMediaStream.PROPERTY_PAIR_NOMINATED.equals(propertyName)) + { + if (initializedActive) + { + return; + } + initializedActive = true; + + // Find the remote address and the correct socket to be used by + // the pair. + LocalCandidate localCandidate = pair.getLocalCandidate(); + LocalCandidate base = localCandidate.getBase(); + if (base != null) + localCandidate = base; + + TransportAddress remoteAddress = null; + RemoteCandidate remoteCandidate = pair.getRemoteCandidate(); + if (remoteCandidate != null) + { + remoteAddress = remoteCandidate.getTransportAddress(); + } + + // The local candidate may have more than one associated socket. + // Make sure we get the one for the remote address that we are + // going to use. + IceSocketWrapper socketWrapper + = localCandidate.getCandidateIceSocketWrapper(remoteAddress); + + initializeActive(socketWrapper, remoteAddress); + } } /** diff --git a/src/main/java/org/ice4j/socket/MergingDatagramSocket.java b/src/main/java/org/ice4j/socket/MergingDatagramSocket.java index 0e8b6d6..098289a 100644 --- a/src/main/java/org/ice4j/socket/MergingDatagramSocket.java +++ b/src/main/java/org/ice4j/socket/MergingDatagramSocket.java @@ -17,6 +17,8 @@ */ package org.ice4j.socket; +import org.ice4j.*; + import java.io.*; import java.net.*; import java.util.*; @@ -36,9 +38,6 @@ import java.util.logging.*; * {@link #getLocalPort()}, {@link #getLocalAddress()} and * {@link #getLocalSocketAddress()}. * - * Currently the delegate is just the first socket, but the intention is to - * allow it to change dynamically. - * * @author Boris Grozev */ public class MergingDatagramSocket @@ -134,6 +133,7 @@ public class MergingDatagramSocket synchronized (socketContainersSyncRoot) { + active = null; for (SocketContainer container : socketContainers) { container.close(false); @@ -274,9 +274,6 @@ public class MergingDatagramSocket newSocketContainers[socketContainers.length] = socketContainer; socketContainers = newSocketContainers; - - if (active == null) - active = socketContainer; } } @@ -333,11 +330,13 @@ public class MergingDatagramSocket socketContainers = newSockets; - // Until we receive data on one of the other sockets, use the - // first one as the active socket. if (socketContainer == active) { - active = newSockets.length == 0 ? null : newSockets[0]; + // TODO: proper selection of a new active socket + logger.warning( + "Removing the active socket. Won't be able to send " + + "until a new one is elected."); + active = null; } } else @@ -503,6 +502,7 @@ public class MergingDatagramSocket if (accept(p)) { + socketToReceiveFrom.accepted(p); return; } else @@ -550,6 +550,65 @@ public class MergingDatagramSocket } } + /** + * Initializes the active socket of this {@link MergingDatagramSocket}. + * @param socketWrapper the {@link IceSocketWrapper} instance wrapping the + * actual socket that should be used. Used to find the correct + * {@link SocketContainer} + * @param remoteAddress the remote address which was selected by ICE and + * and which should be used as the target. + */ + protected void initializeActive(IceSocketWrapper socketWrapper, + TransportAddress remoteAddress) + { + Object socket = socketWrapper.getTCPSocket(); + if (socket == null) + { + socket = socketWrapper.getUDPSocket(); + } + + if (logger.isLoggable(Level.FINE)) + { + logger.fine("Initializing the active container, socket=" + socket + + "; remote address=" + remoteAddress); + } + + synchronized (socketContainersSyncRoot) + { + if (active != null) + { + // This means that we've received data before ICE completed. + // That is, the remote side sent application data, and our + // application invoked receive(). Though maybe unusual, this + // is not necessarily incorrect. + // Still, go on and replace the active socket with whatever + // ICE selected. + logger.warning("Active socket already initialized."); + } + + SocketContainer newActive = null; + for (SocketContainer container : socketContainers) + { + if (socket == container.datagramSocket + || socket == container.delegatingSocket) + { + newActive = container; + break; + } + } + + if (newActive == null) + { + logger.severe("No SocketContainer found!"); + return; + } + + newActive.remoteAddress = remoteAddress; + active = newActive; + + } + } + /** * Contains one of the sockets which this {@link MergingDatagramSocket} * merges, and objects associated with the socket, including a thread @@ -594,6 +653,13 @@ public class MergingDatagramSocket /** * The remote address of the last received packet. + * Note that this is updated only when a packet is received from this + * {@link SocketContainer} via {@link #receive(DatagramPacket)}, and + * not when a packet is received from the underlying socket by its + * read thread. This is in order to prevent poisoning of the remote + * address, since the verification of the address is performed by + * the {@link MergingDatagramSocket} after it invokes + * {@link #receive(DatagramPacket)}. */ private SocketAddress remoteAddress = null; @@ -751,7 +817,6 @@ public class MergingDatagramSocket } buffer.receivedTime = System.currentTimeMillis(); - remoteAddress = buffer.pkt.getSocketAddress(); maybeUpdateActive(); return true; @@ -783,7 +848,7 @@ public class MergingDatagramSocket MergingDatagramSocket.this.active = this; if (logger.isLoggable(Level.FINE)) { - logger.warning("Switching to new active socket: " + logger.fine("Switching to new active socket: " + this); } } @@ -871,7 +936,6 @@ public class MergingDatagramSocket return datagramSocket != null ? datagramSocket.getLocalSocketAddress() : delegatingSocket.getLocalSocketAddress(); - } /** @@ -901,6 +965,11 @@ public class MergingDatagramSocket private void send(DatagramPacket pkt) throws IOException { + // The application writing data doesn't necessarily know what + // remote address to use. Since this SocketContainer was selected + // to send the packet through, set the target accordingly. + setTarget(pkt); + if (datagramSocket != null) { datagramSocket.send(pkt); @@ -911,6 +980,52 @@ public class MergingDatagramSocket } } + /** + * Sets the {@link SocketAddress} of {@code pkt} to the remote address + * that this {@link SocketContainer} should send packets to. + * @param pkt the packet for which to set the socket address. + */ + private void setTarget(DatagramPacket pkt) + { + SocketAddress target; + // If the socket already has a remote address, use it. If this is + // the case, the DatagramPacket instance's remote address is likely + // to be ignored, anyway. + if (datagramSocket != null) + { + target = datagramSocket.getRemoteSocketAddress(); + } + else + { + target = delegatingSocket.getRemoteSocketAddress(); + } + + // The socket doesn't always have a remote address (e.g. if it is + // an unconnected UDP socket from HostCandidateHarvester). + // In this case, we send to the source address of the last packet + // which was received and accepted, or to the address that was + // initialized via initializeActive (i.e. the address initially + // selected by ICE). + if (target == null) + { + target = this.remoteAddress; + } + + pkt.setSocketAddress(target); + } + + /** + * Notifies this {@link SocketContainer} that a particular + * {@link DatagramPacket} was received from it, and was accepted (as + * opposed to e.g. having been discarded due to its remote address not + * being authorized). + * @param pkt the accepted packet. + */ + private void accepted(DatagramPacket pkt) + { + this.remoteAddress = pkt.getSocketAddress(); + } + /** * @return the underlying socket of this {@link SocketContainer}. */ From 75e8948f4b666eb88a20b3d21b64c033d832fcce Mon Sep 17 00:00:00 2001 From: Boris Grozev Date: Fri, 9 Dec 2016 09:01:44 -0600 Subject: [PATCH 23/29] log: Uses the parent Agent's log level. --- src/main/java/org/ice4j/ice/Component.java | 7 ++--- .../java/org/ice4j/ice/ComponentSocket.java | 16 +++++++++--- .../ice4j/socket/MergingDatagramSocket.java | 26 ++++++++++++++++--- 3 files changed, 39 insertions(+), 10 deletions(-) diff --git a/src/main/java/org/ice4j/ice/Component.java b/src/main/java/org/ice4j/ice/Component.java index a306fd3..2c720b9 100644 --- a/src/main/java/org/ice4j/ice/Component.java +++ b/src/main/java/org/ice4j/ice/Component.java @@ -161,9 +161,11 @@ public class Component this.componentID = componentID; this.parentStream = mediaStream; + Logger agentLogger = mediaStream.getParentAgent().getLogger(); + try { - componentSocket = new ComponentSocket(this); + componentSocket = new ComponentSocket(this, agentLogger); socket = new MultiplexingDatagramSocket(componentSocket); socketWrapper = new IceUdpSocketWrapper(socket); } @@ -172,8 +174,7 @@ public class Component throw new RuntimeException(se); } - logger - = new Logger(classLogger, mediaStream.getParentAgent().getLogger()); + logger = new Logger(classLogger, agentLogger); } /** diff --git a/src/main/java/org/ice4j/ice/ComponentSocket.java b/src/main/java/org/ice4j/ice/ComponentSocket.java index bffde11..ae4c85f 100644 --- a/src/main/java/org/ice4j/ice/ComponentSocket.java +++ b/src/main/java/org/ice4j/ice/ComponentSocket.java @@ -24,7 +24,7 @@ import java.beans.*; import java.net.*; import java.util.*; import java.util.concurrent.*; -import java.util.logging.*; +import org.ice4j.util.*; //Disambiguation /** * Extends {@link MergingDatagramSocket} with functionality specific to @@ -38,8 +38,9 @@ public class ComponentSocket * The {@link Logger} used by the {@link MergingDatagramSocket} class and * its instances for logging output. */ - private static final Logger logger - = Logger.getLogger(MergingDatagramSocket.class.getName()); + private static final java.util.logging.Logger classLogger + = java.util.logging.Logger.getLogger + (MergingDatagramSocket.class.getName()); /** * Controls access to {@link #authorizedAddresses}. @@ -65,15 +66,22 @@ public class ComponentSocket */ private boolean initializedActive = false; + /** + * The {@link Logger} used by {@link MergingDatagramSocket} instances. + */ + private final Logger logger; /** * Initializes a new {@link MergingDatagramSocket} instance. * @throws SocketException */ - ComponentSocket(Component component) + ComponentSocket(Component component, Logger levelDelegate) throws SocketException { + super(levelDelegate); + this.component = component; + this.logger = new Logger(classLogger, levelDelegate); component.getParentStream().addPairChangeListener(this); } diff --git a/src/main/java/org/ice4j/socket/MergingDatagramSocket.java b/src/main/java/org/ice4j/socket/MergingDatagramSocket.java index 098289a..1027ae1 100644 --- a/src/main/java/org/ice4j/socket/MergingDatagramSocket.java +++ b/src/main/java/org/ice4j/socket/MergingDatagramSocket.java @@ -24,6 +24,7 @@ import java.net.*; import java.util.*; import java.util.concurrent.*; import java.util.logging.*; +import org.ice4j.util.Logger; //Disambiguation /** * A {@link DatagramSocket} implementation which merges a set of sockets. @@ -47,8 +48,9 @@ public class MergingDatagramSocket * The {@link Logger} used by the {@link MergingDatagramSocket} class and * its instances for logging output. */ - private static final Logger logger - = Logger.getLogger(MergingDatagramSocket.class.getName()); + private static final java.util.logging.Logger classLogger + = java.util.logging.Logger.getLogger( + MergingDatagramSocket.class.getName()); /** * Used to control access to {@link #socketContainers}. @@ -92,6 +94,10 @@ public class MergingDatagramSocket */ private int numDiscardedPackets = 0; + /** + * The {@link Logger} used by {@link MergingDatagramSocket} instances. + */ + private final Logger logger; /** * Initializes a new {@link MergingDatagramSocket} instance. @@ -99,7 +105,21 @@ public class MergingDatagramSocket */ public MergingDatagramSocket() throws SocketException - {} + { + this(null); + } + + /** + * Initializes a new {@link MergingDatagramSocket} instance. + * @param levelDelegate the {@link Logger} instance which dictates the + * logging level for the new {@link MergingDatagramSocket} instance. + * @throws SocketException + */ + public MergingDatagramSocket(Logger levelDelegate) + throws SocketException + { + logger = new Logger(classLogger, levelDelegate); + } /** * {@inheritDoc} From cb2856a8ae6e8e4cb8314f4bda9802ba15cbd0a7 Mon Sep 17 00:00:00 2001 From: Boris Grozev Date: Fri, 9 Dec 2016 09:10:22 -0600 Subject: [PATCH 24/29] log: Reduces logging. --- src/main/java/org/ice4j/socket/MergingDatagramSocket.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/ice4j/socket/MergingDatagramSocket.java b/src/main/java/org/ice4j/socket/MergingDatagramSocket.java index 1027ae1..af7235f 100644 --- a/src/main/java/org/ice4j/socket/MergingDatagramSocket.java +++ b/src/main/java/org/ice4j/socket/MergingDatagramSocket.java @@ -777,7 +777,7 @@ public class MergingDatagramSocket } catch (IOException ioe) { - logger.severe("Failed to receive: " + ioe); + logger.info("Failed to receive: " + ioe); break; } @@ -1062,7 +1062,7 @@ public class MergingDatagramSocket */ private void close(boolean remove) { - if (closed && !remove) + if (closed) { return; } From d0587e99e6bc6d499021ad72ae791a73e812a3ee Mon Sep 17 00:00:00 2001 From: Boris Grozev Date: Fri, 9 Dec 2016 10:07:06 -0600 Subject: [PATCH 25/29] doc: Make it clear that a particular property name is used. --- src/main/java/org/ice4j/ice/DefaultNominator.java | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/main/java/org/ice4j/ice/DefaultNominator.java b/src/main/java/org/ice4j/ice/DefaultNominator.java index 21e113c..2000851 100644 --- a/src/main/java/org/ice4j/ice/DefaultNominator.java +++ b/src/main/java/org/ice4j/ice/DefaultNominator.java @@ -315,6 +315,13 @@ public class DefaultNominator */ public void propertyChange(PropertyChangeEvent evt) { + // Make it clear that PROPERTY_CHECK_LIST_CHECKS is in use here. + if (!CheckList.PROPERTY_CHECK_LIST_CHECKS.equals( + evt.getPropertyName())) + { + return; + } + // check list has running out of ordinary checks, see if all other // candidates are FAILED, in which case we nominate immediately // the relayed candidate From 9c8d22a5bd009aa8465376be84a86bf31f5477cf Mon Sep 17 00:00:00 2001 From: Boris Grozev Date: Mon, 12 Dec 2016 13:34:54 -0600 Subject: [PATCH 26/29] fix: Uses a regular HashSet. --- src/main/java/org/ice4j/ice/ComponentSocket.java | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/src/main/java/org/ice4j/ice/ComponentSocket.java b/src/main/java/org/ice4j/ice/ComponentSocket.java index ae4c85f..117b725 100644 --- a/src/main/java/org/ice4j/ice/ComponentSocket.java +++ b/src/main/java/org/ice4j/ice/ComponentSocket.java @@ -52,9 +52,7 @@ public class ComponentSocket * from. These should be the addresses which we have confirmed (e.g. by * having received a STUN message with correct authentication fields). */ - private Set authorizedAddresses - = Collections.newSetFromMap( - new ConcurrentHashMap()); + private Set authorizedAddresses = new HashSet<>(); /** * The owning {@link Component}. @@ -110,9 +108,7 @@ public class ComponentSocket logger.info("Adding allowed address: " + address); - Set newSet - = Collections.newSetFromMap( - new ConcurrentHashMap()); + Set newSet = new HashSet<>(); newSet.addAll(authorizedAddresses); newSet.add(address); From 6d6f4710e00fe04ea126d988e031771cc14aaea4 Mon Sep 17 00:00:00 2001 From: Boris Grozev Date: Mon, 12 Dec 2016 13:49:21 -0600 Subject: [PATCH 27/29] fix: Only initializes propertyName if needed. --- src/main/java/org/ice4j/ice/ComponentSocket.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/ice4j/ice/ComponentSocket.java b/src/main/java/org/ice4j/ice/ComponentSocket.java index 117b725..171ce9f 100644 --- a/src/main/java/org/ice4j/ice/ComponentSocket.java +++ b/src/main/java/org/ice4j/ice/ComponentSocket.java @@ -125,7 +125,6 @@ public class ComponentSocket @Override public void propertyChange(PropertyChangeEvent event) { - String propertyName = event.getPropertyName(); if (!(event.getSource() instanceof CandidatePair)) { return; @@ -140,6 +139,7 @@ public class ComponentSocket return; } + String propertyName = event.getPropertyName(); if (IceMediaStream.PROPERTY_PAIR_STATE_CHANGED.equals(propertyName)) { CandidatePairState newState From 7cac0e50a7fb55ca0e7fb2ae7d65a17cbff85570 Mon Sep 17 00:00:00 2001 From: Boris Grozev Date: Mon, 12 Dec 2016 13:53:42 -0600 Subject: [PATCH 28/29] fix: Moves the initializedActive update to after the actual call to initializeActive(). Synchronizes access. --- .../java/org/ice4j/ice/ComponentSocket.java | 60 +++++++++++-------- 1 file changed, 34 insertions(+), 26 deletions(-) diff --git a/src/main/java/org/ice4j/ice/ComponentSocket.java b/src/main/java/org/ice4j/ice/ComponentSocket.java index 171ce9f..f52b6ee 100644 --- a/src/main/java/org/ice4j/ice/ComponentSocket.java +++ b/src/main/java/org/ice4j/ice/ComponentSocket.java @@ -23,7 +23,6 @@ import org.ice4j.socket.*; import java.beans.*; import java.net.*; import java.util.*; -import java.util.concurrent.*; import org.ice4j.util.*; //Disambiguation /** @@ -64,6 +63,11 @@ public class ComponentSocket */ private boolean initializedActive = false; + /** + * Used to synchronize access to {@link #initializedActive}. + */ + private final Object initializedActiveSyncRoot = new Object(); + /** * The {@link Logger} used by {@link MergingDatagramSocket} instances. */ @@ -153,33 +157,37 @@ public class ComponentSocket } else if (IceMediaStream.PROPERTY_PAIR_NOMINATED.equals(propertyName)) { - if (initializedActive) + synchronized (initializedActiveSyncRoot) { - return; + if (initializedActive) + { + return; + } + + // Find the remote address and the correct socket to be used by + // the pair. + LocalCandidate localCandidate = pair.getLocalCandidate(); + LocalCandidate base = localCandidate.getBase(); + if (base != null) + localCandidate = base; + + TransportAddress remoteAddress = null; + RemoteCandidate remoteCandidate = pair.getRemoteCandidate(); + if (remoteCandidate != null) + { + remoteAddress = remoteCandidate.getTransportAddress(); + } + + // The local candidate may have more than one associated socket. + // Make sure we get the one for the remote address that we are + // going to use. + IceSocketWrapper socketWrapper + = localCandidate + .getCandidateIceSocketWrapper(remoteAddress); + + initializeActive(socketWrapper, remoteAddress); + initializedActive = true; } - initializedActive = true; - - // Find the remote address and the correct socket to be used by - // the pair. - LocalCandidate localCandidate = pair.getLocalCandidate(); - LocalCandidate base = localCandidate.getBase(); - if (base != null) - localCandidate = base; - - TransportAddress remoteAddress = null; - RemoteCandidate remoteCandidate = pair.getRemoteCandidate(); - if (remoteCandidate != null) - { - remoteAddress = remoteCandidate.getTransportAddress(); - } - - // The local candidate may have more than one associated socket. - // Make sure we get the one for the remote address that we are - // going to use. - IceSocketWrapper socketWrapper - = localCandidate.getCandidateIceSocketWrapper(remoteAddress); - - initializeActive(socketWrapper, remoteAddress); } } From 9adab9094f9df331d29f5b9d0dd87e11aeb53275 Mon Sep 17 00:00:00 2001 From: Boris Grozev Date: Mon, 12 Dec 2016 13:59:55 -0600 Subject: [PATCH 29/29] style: Fixes a typo. --- src/main/java/org/ice4j/ice/DefaultNominator.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/ice4j/ice/DefaultNominator.java b/src/main/java/org/ice4j/ice/DefaultNominator.java index 2000851..077cd88 100644 --- a/src/main/java/org/ice4j/ice/DefaultNominator.java +++ b/src/main/java/org/ice4j/ice/DefaultNominator.java @@ -322,7 +322,7 @@ public class DefaultNominator return; } - // check list has running out of ordinary checks, see if all other + // check list has run out of ordinary checks, see if all other // candidates are FAILED, in which case we nominate immediately // the relayed candidate CheckList checkList = (CheckList)evt.getSource();