From 15d69b316c34300f785357dc0db1df1a77305d27 Mon Sep 17 00:00:00 2001 From: Ingo Bauersachs Date: Mon, 8 Nov 2021 21:05:54 +0100 Subject: [PATCH] Remove ServerSocketChannel muxing that used private JDK api Closes #239 --- .../ice/harvest/AbstractTcpListener.java | 178 +-- .../org/ice4j/pseudotcp/PseudoTCPBase.java | 2 +- .../socket/MuxServerSocketChannelFactory.java | 167 +-- .../org/ice4j/socket/jdk8/DatagramBuffer.java | 79 -- .../jdk8/DelegatingServerSocketChannel.java | 217 ---- .../socket/jdk8/DelegatingSocketChannel.java | 216 ---- .../ice4j/socket/jdk8/MuxServerSocket.java | 56 - .../socket/jdk8/MuxServerSocketChannel.java | 298 ----- .../ice4j/socket/jdk8/MuxingServerSocket.java | 56 - .../jdk8/MuxingServerSocketChannel.java | 1125 ----------------- .../socket/jdk8/PreReadSocketChannel.java | 108 -- .../org/ice4j/socket/jdk8/Timestamped.java | 66 - .../jdk8/MuxServerSocketChannelTest.java | 32 - 13 files changed, 20 insertions(+), 2580 deletions(-) delete mode 100644 src/main/java/org/ice4j/socket/jdk8/DatagramBuffer.java delete mode 100644 src/main/java/org/ice4j/socket/jdk8/DelegatingServerSocketChannel.java delete mode 100644 src/main/java/org/ice4j/socket/jdk8/DelegatingSocketChannel.java delete mode 100644 src/main/java/org/ice4j/socket/jdk8/MuxServerSocket.java delete mode 100644 src/main/java/org/ice4j/socket/jdk8/MuxServerSocketChannel.java delete mode 100644 src/main/java/org/ice4j/socket/jdk8/MuxingServerSocket.java delete mode 100644 src/main/java/org/ice4j/socket/jdk8/MuxingServerSocketChannel.java delete mode 100644 src/main/java/org/ice4j/socket/jdk8/PreReadSocketChannel.java delete mode 100644 src/main/java/org/ice4j/socket/jdk8/Timestamped.java delete mode 100644 src/test/java/org/ice4j/socket/jdk8/MuxServerSocketChannelTest.java diff --git a/src/main/java/org/ice4j/ice/harvest/AbstractTcpListener.java b/src/main/java/org/ice4j/ice/harvest/AbstractTcpListener.java index c331efc..82c3a3f 100644 --- a/src/main/java/org/ice4j/ice/harvest/AbstractTcpListener.java +++ b/src/main/java/org/ice4j/ice/harvest/AbstractTcpListener.java @@ -19,7 +19,6 @@ package org.ice4j.ice.harvest; import org.ice4j.*; import org.ice4j.ice.*; -import org.ice4j.message.*; import org.ice4j.socket.*; import java.io.*; @@ -61,7 +60,15 @@ public abstract class AbstractTcpListener */ static void closeNoExceptions(Channel channel) { - MuxServerSocketChannelFactory.closeNoExceptions(channel); + try + { + channel.close(); + } + catch (IOException ioe) + { + // The whole idea of the method is to close a specific Channel + // without caring about any possible IOException. + } } /** @@ -75,7 +82,6 @@ public abstract class AbstractTcpListener private static List getLocalAddresses( int port, List interfaces) - throws IOException { List addresses = new LinkedList<>(); @@ -101,83 +107,6 @@ public abstract class AbstractTcpListener return addresses; } - /** - * Determines whether a specific {@link DatagramPacket} is the first - * expected (i.e. supported) to be received from an accepted - * {@link SocketChannel} by this {@link AbstractTcpListener}. This is true - * if it is contains the hard-coded SSL client handshake ( - * {@link GoogleTurnSSLCandidateHarvester#SSL_CLIENT_HANDSHAKE}), or - * a STUN Binding Request. - * - * @param p the {@code DatagramPacket} to examine - * @return {@code true} if {@code p} looks like the first - * {@code DatagramPacket} expected to be received from an accepted - * {@code SocketChannel} by this {@code TcpHarvester}; - * otherwise, {@code false} - */ - private static boolean isFirstDatagramPacket(DatagramPacket p) - { - int len = p.getLength(); - boolean b = false; - - if (len > 0) - { - byte[] buf = p.getData(); - int off = p.getOffset(); - - // Check for Google TURN SSLTCP - final byte[] googleTurnSslTcp - = GoogleTurnSSLCandidateHarvester.SSL_CLIENT_HANDSHAKE; - - if (len >= googleTurnSslTcp.length) - { - b = true; - for (int i = 0, iEnd = googleTurnSslTcp.length, j = off; - i < iEnd; - i++, j++) - { - if (googleTurnSslTcp[i] != buf[j]) - { - b = false; - break; - } - } - } - - // nothing found, lets check for stun binding requests - if (!b) - { - // 2 bytes uint16 length - // STUN Binding request: - // 2 bits 00 - // 14 bits STUN Messsage Type - // 2 bytes Message Length - // 4 bytes Magic Cookie - - // RFC 5389: For example, a Binding request has class=0b00 - // (request) and method=0b000000000001 (Binding) and is encoded - // into the first 16 bits as 0x0001. - if (len >= 10 && buf[off + 2] == 0 && buf[off + 3] == 1) - { - final byte[] magicCookie = Message.MAGIC_COOKIE; - - b = true; - for (int i = 0, iEnd = magicCookie.length, j = off + 6; - i < iEnd; - i++, j++) - { - if (magicCookie[i] != buf[j]) - { - b = false; - break; - } - } - } - } - } - return b; - } - /** * The thread which accepts TCP connections from the sockets in * {@link #serverSocketChannels}. @@ -218,12 +147,6 @@ public abstract class AbstractTcpListener private final List serverSocketChannels = new LinkedList<>(); - /** - * The object used to synchronize access to the collection of sessions that - * the implementation of this class uses. - */ - protected final Object sessionsSyncRoot = new Object(); - /** * Initializes a new TcpHarvester, which is to * listen on port number port on all IP addresses on all available @@ -432,21 +355,7 @@ public abstract class AbstractTcpListener throws IOException { ServerSocketChannel channel = MuxServerSocketChannelFactory - .openAndBindMuxServerSocketChannel( - /* properties */ null, - address, - /* backlog */ 0, - new DatagramPacketFilter() - { - /** - * {@inheritDoc} - */ - @Override - public boolean accept(DatagramPacket p) - { - return isFirstDatagramPacket(p); - } - }); + .openAndBindServerSocketChannel(null, address, 0); serverSocketChannels.add(channel); } @@ -457,8 +366,6 @@ public abstract class AbstractTcpListener * @param ufrag the local username fragment for the session. * @param pushback the first "datagram" (RFC4571-framed), already read from * the socket's stream. - * @throws IllegalStateException - * @throws IOException */ protected abstract void acceptSession( Socket socket, String ufrag, DatagramPacket pushback) @@ -598,7 +505,9 @@ public abstract class AbstractTcpListener selector.close(); } catch (IOException ioe) - {} + { + // ignore + } } } @@ -613,11 +522,6 @@ public abstract class AbstractTcpListener */ public final SocketChannel channel; - /** - * The time the channel was last found to be active. - */ - long lastActive = System.currentTimeMillis(); - /** * The buffer which stores the data so far read from the channel. */ @@ -783,11 +687,8 @@ public abstract class AbstractTcpListener { /** * Initializes a new ReadThread. - * - * @throws IOException if the selector to be used fails to open. */ public ReadThread() - throws IOException { setName("TcpHarvester ReadThread"); setDaemon(true); @@ -821,50 +722,6 @@ public abstract class AbstractTcpListener } } - /** - * Closes any inactive channels registered with {@link #readSelector}. - * A channel is considered inactive if it hasn't been available for - * reading for - * {@link MuxServerSocketChannelFactory#SOCKET_CHANNEL_READ_TIMEOUT} - * milliseconds. - */ - private void cleanup() - { - long now = System.currentTimeMillis(); - - for (SelectionKey key : readSelector.keys()) - { - // An invalid key specifies that either the channel was closed - // (in which case we do not have to do anything else to it) or - // that we no longer control the channel (i.e. we do not want to - // do anything else to it). - if (!key.isValid()) - continue; - - ChannelDesc channelDesc = (ChannelDesc) key.attachment(); - - if (channelDesc == null) - continue; - - long lastActive = channelDesc.lastActive; - - if (lastActive != -1 - && now - lastActive - > MuxServerSocketChannelFactory - .SOCKET_CHANNEL_READ_TIMEOUT) - { - // De-register from the Selector. - key.cancel(); - - SocketChannel channel = channelDesc.channel; - - logger.info("Read timeout for socket: " + channel.socket()); - - closeNoExceptions(channel); - } - } - } - /** * Tries to read, without blocking, from channel to its * buffer. If after reading the buffer is filled, handles the data in @@ -915,8 +772,6 @@ public abstract class AbstractTcpListener if (read == -1) throw new IOException("End of stream!"); - else if (read > 0) - channel.lastActive = System.currentTimeMillis(); if (!channel.buffer.hasRemaining()) { @@ -1102,9 +957,6 @@ public abstract class AbstractTcpListener break; } - // clean up stale channels - cleanup(); - checkForNewChannels(); for (SelectionKey key : readSelector.keys()) @@ -1164,7 +1016,9 @@ public abstract class AbstractTcpListener readSelector.close(); } catch (IOException ioe) - {} + { + // ignore + } } } } diff --git a/src/main/java/org/ice4j/pseudotcp/PseudoTCPBase.java b/src/main/java/org/ice4j/pseudotcp/PseudoTCPBase.java index bde8547..b09d7e8 100755 --- a/src/main/java/org/ice4j/pseudotcp/PseudoTCPBase.java +++ b/src/main/java/org/ice4j/pseudotcp/PseudoTCPBase.java @@ -1960,7 +1960,7 @@ public class PseudoTCPBase options_specified.add(kind); } - if (options_specified.indexOf(TCP_OPT_WND_SCALE) == -1)//options_specified.size() - 1) + if (!options_specified.contains(TCP_OPT_WND_SCALE)) { logger.log(Level.WARNING, "Peer doesn't support window scaling"); if (getM_rwnd_scale() > 0) diff --git a/src/main/java/org/ice4j/socket/MuxServerSocketChannelFactory.java b/src/main/java/org/ice4j/socket/MuxServerSocketChannelFactory.java index 978b17b..b29bd85 100644 --- a/src/main/java/org/ice4j/socket/MuxServerSocketChannelFactory.java +++ b/src/main/java/org/ice4j/socket/MuxServerSocketChannelFactory.java @@ -18,11 +18,9 @@ package org.ice4j.socket; import java.io.*; -import java.lang.reflect.*; import java.net.*; import java.nio.channels.*; import java.util.*; -import java.util.logging.*; /** * If supported by the runtime, initializes {@link ServerSocketChannel}s which @@ -33,19 +31,6 @@ import java.util.logging.*; */ public class MuxServerSocketChannelFactory { - /** - * The {@code Logger} used by the {@code MuxServerSocketChannelFactory} - * class (and its instances) to print debug information. - */ - private static final Logger logger - = Logger.getLogger(MuxServerSocketChannelFactory.class.getName()); - - /** - * The reflection of the {@code openAndBind} method of the - * {@code MuxServerSocketChannel} class. - */ - private static final Method OPEN_AND_BIND_METHOD; - /** * The maximum number of milliseconds to wait for an accepted * {@code SocketChannel} to provide incoming/readable data before it is @@ -56,158 +41,12 @@ public class MuxServerSocketChannelFactory /** * The name of the {@code boolean} property of the {@code socket} property * of the {@code ServerSocketChannel} returned by - * {@link #openAndBindMuxServerSocketChannel(Map, SocketAddress, int, - * DatagramPacketFilter)} which specifies the value of the - * {@code SO_REUSEADDR} socket option. + * {@link #openAndBindServerSocketChannel(Map, SocketAddress, int)} which + * specifies the value of the {@code SO_REUSEADDR} socket option. */ public static final String SOCKET_REUSE_ADDRESS_PROPERTY_NAME = "socket.reuseAddress"; - static - { - Class clazz; - - try - { - clazz - = Class.forName("org.ice4j.socket.jdk8.MuxServerSocketChannel"); - } - catch (ClassNotFoundException cnfex) - { - // The class cannot be located probably because ICE4J was not built - // on JDK 8. - clazz = null; - logger.warning( - "ICE4J does not support sharing of listening endpoints" - + " (probably because it was not built on JDK 8)."); - } - catch (LinkageError lerr) - { - // The linkage fails probably because ICE4J was built on JDK 8 but - // is not run on JDK 8. - clazz = null; - logger.warning( - "ICE4J does not support sharing of listening endpoints" - + " (probably because it is not running on JDK 8)."); - } - - Method method; - - if (clazz == null) - { - method = null; - } - else - { - try - { - method - = clazz.getDeclaredMethod( - "openAndBind", - Map.class, - SocketAddress.class, - int.class, - DatagramPacketFilter.class); - } - catch (NoSuchMethodException nsmex) - { - throw new RuntimeException(nsmex); - } - } - OPEN_AND_BIND_METHOD = method; - } - - /** - * Closes a {@code Channel} and swallows any {@link IOException}. - * - * @param channel the {@code Channel} to close - */ - public static void closeNoExceptions(Channel channel) - { - try - { - channel.close(); - } - catch (IOException ioe) - { - // The whole idea of the method is to close a specific Channel - // without caring about any possible IOException. - } - } - - /** - * Opens and binds a new {@code MuxServerSocketChannel} instance if - * supported by the runtime. If there are other (existing) - * {@code MuxServerSocketChannel} open and bound on the specified listening - * {@code endpoint}, the new instance will share it with them. If the - * sharing of listening endpoints is not supported by the runtime, falls - * back to {@link #openAndBindServerSocketChannel(Map, SocketAddress, int)}. - * - * @param properties a {@code Map} of the values to be assigned to - * properties of the underlying {@link ServerSocketChannel} which is to - * actually listen on the specified {@code endpoint}. If the new instance is - * not the first to open and bind the specified {@code endpoint}, the - * {@code properties} and their respective values may not be used. - * @param endpoint the IP and port the new instance is to bind to - * @param backlog the requested maximum number of pending incoming - * connections to be queued. If the new instance is not the first to open - * and bind the specified {@code endpoint}, the value may not be used. - * @param filter the {@code DatagramPacketFilter} to demultiplex (i.e. - * recognize) the content meant for the new instance - * @return a new {@code MuxServerSocketChannel} instance open and bound on - * the specified listening {@code endpoint} - * @throws IOException if an I/O error occurs - */ - public static ServerSocketChannel openAndBindMuxServerSocketChannel( - Map properties, - SocketAddress endpoint, - int backlog, - DatagramPacketFilter filter) - throws IOException - { - Method method = OPEN_AND_BIND_METHOD; - - if (method == null) - { - return - openAndBindServerSocketChannel(properties, endpoint, backlog); - } - else - { - try - { - return - (ServerSocketChannel) - method.invoke( - null, - properties, endpoint, backlog, filter); - } - catch (IllegalAccessException iaex) - { - IllegalAccessError iaerr - = new IllegalAccessError(iaex.getMessage()); - - iaerr.initCause(iaex); - throw iaerr; - } - catch (InvocationTargetException itex) - { - Throwable cause = itex.getCause(); - - if (cause == null) - throw new RuntimeException(itex); - else if (cause instanceof Error) - throw (Error) cause; - else if (cause instanceof IOException) - throw (IOException) cause; - else if (cause instanceof RuntimeException) - throw (RuntimeException) cause; - else - throw new RuntimeException(cause); - } - } - } - /** * Opens and binds a new {@code ServerSocketChannel} instance. * @@ -251,7 +90,7 @@ public class MuxServerSocketChannelFactory else if (value instanceof Boolean) on = (Boolean) value; else - on = Boolean.valueOf(value.toString()); + on = Boolean.parseBoolean(value.toString()); socket.setReuseAddress(on); } diff --git a/src/main/java/org/ice4j/socket/jdk8/DatagramBuffer.java b/src/main/java/org/ice4j/socket/jdk8/DatagramBuffer.java deleted file mode 100644 index 52dfa34..0000000 --- a/src/main/java/org/ice4j/socket/jdk8/DatagramBuffer.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * ice4j, the OpenSource Java Solution for NAT and Firewall Traversal. - * - * Copyright @ 2015 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.jdk8; - -import java.net.*; -import java.nio.*; - -/** - * Associates a {@link ByteBuffer} with a {@link DatagramPacket} so that the - * {@code ByteBuffer} may be used for writing into a {@code byte} array and the - * {@code DatagramPacket} may be used for reading from the same {@code byte} - * array. - * - * @author Lyubomir Marinov - */ -class DatagramBuffer - extends Timestamped -{ - /** - * The {@code DatagramPacket} which is associated with the - * {@link ByteBuffer} {@link #o} and shares its {@code data} with. - */ - private final DatagramPacket datagramPacket; - - /** - * Initializes a new {@code DatagramBuffer} instance with a specific - * capacity of {@code byte}s shared between a {@code ByteBuffer} and a - * {@code DatagramPacket}. - * - * @param capacity the maximum number of {@code byte}s to be written into - * and read from the new instance - */ - public DatagramBuffer(int capacity) - { - super(ByteBuffer.allocate(capacity)); - - datagramPacket - = new DatagramPacket(o.array(), /* offset */ 0, /* length */ 0); - } - - /** - * Gets the {@code ByteBuffer} (view) of this instance. - * - * @return the {@code ByteBuffer} (view) of this instance - */ - public ByteBuffer getByteBuffer() - { - return o; - } - - /** - * Gets the {@code DatagramPacket} (view) of this instance. The - * {@code length} of the {@code DatagramPacket} equals the {@code position} - * of the {@code ByteBuffer} so that the {@code byte}s written into the - * {@code ByteBuffer} may be read from the {@code DatagramPacket}. - * - * @return the {@code DatagramPacket} (view) of this instance - */ - public DatagramPacket getDatagramPacket() - { - datagramPacket.setLength(getByteBuffer().position()); - return datagramPacket; - } -} diff --git a/src/main/java/org/ice4j/socket/jdk8/DelegatingServerSocketChannel.java b/src/main/java/org/ice4j/socket/jdk8/DelegatingServerSocketChannel.java deleted file mode 100644 index 7720124..0000000 --- a/src/main/java/org/ice4j/socket/jdk8/DelegatingServerSocketChannel.java +++ /dev/null @@ -1,217 +0,0 @@ -/* - * ice4j, the OpenSource Java Solution for NAT and Firewall Traversal. - * - * Copyright @ 2018 - present 8x8, Inc. - * - * 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.jdk8; - -import java.io.*; -import java.lang.reflect.*; -import java.nio.channels.*; -import java.util.logging.*; - -import org.ice4j.socket.*; - -import sun.nio.ch.*; - -/** - * Implements a {@code ServerSocketChannel} which delegates (its method calls) - * to another {@code ServerSocketChannel}. In other words, the former wraps the - * latter. - * - * @author Lyubomir Marinov - */ -class DelegatingServerSocketChannel - extends BaseDelegatingServerSocketChannel - implements SelChImpl -{ - /** - * The {@link Logger} used by the {@link DelegatingServerSocketChannel} - * class and its instances for logging output. - */ - private static final java.util.logging.Logger classLogger - = java.util.logging.Logger.getLogger( - DelegatingServerSocketChannel.class.getName()); - - /** - * The view of {@link #delegate} as a SelChImpl interface instance - * required by {@link Selector} and related functionality. - */ - protected final SelChImpl delegateAsSelChImpl; - - /** - * The translateAndSetInterestOps method available in java 8. - */ - private final Method translateAndSetInterestOpsMethod; - - /** - * The translateInterestOps method available in java 11. - */ - private final Method translateInterestOpsMethod; - - /** - * Initializes a new {@code DelegatingServerSocketChannel} instance which is - * to delegate (its method calls) to a specific {@code ServerSocketChannel}. - * - * @param delegate the {@code ServerSocketChannel} the new instance is to - * delegate (its method calls) to - */ - public DelegatingServerSocketChannel(T delegate) - { - super(delegate); - - delegateAsSelChImpl - = (delegate instanceof SelChImpl) ? (SelChImpl) delegate : null; - - Method method; - try - { - method = SelChImpl.class.getMethod( - "translateAndSetInterestOps", - Integer.TYPE, SelectionKeyImpl.class); - } - catch(NoSuchMethodException e) - { - method = null; - } - translateAndSetInterestOpsMethod = method; - - try - { - method = SelChImpl.class.getMethod( - "translateInterestOps", Integer.TYPE); - } - catch(NoSuchMethodException e) - { - method = null; - - } - translateInterestOpsMethod = method; - - if (translateInterestOpsMethod == null - && translateAndSetInterestOpsMethod == null) - { - classLogger.log( - Level.SEVERE, "Cannot find translateInterestOps " + - "or translateAndSetInterestOps!"); - } - } - - /** - * {@inheritDoc} - * - * Forwards to {@link #delegate}. - */ - @Override - public FileDescriptor getFD() - { - return delegateAsSelChImpl.getFD(); - } - - /** - * {@inheritDoc} - * - * Forwards to {@link #delegate}. - */ - @Override - public int getFDVal() - { - return delegateAsSelChImpl.getFDVal(); - } - - /** - * {@inheritDoc} - * - * Forwards to {@link #delegate}. - */ - @Override - public void kill() - throws IOException - { - delegateAsSelChImpl.kill(); - } - - /** - * {@inheritDoc} - * - * Forwards to {@link #delegate}. - */ - @SuppressWarnings("unused") - public void translateAndSetInterestOps(int ops, SelectionKeyImpl sk) - { - try - { - if (translateAndSetInterestOpsMethod != null) - { - translateAndSetInterestOpsMethod.invoke( - delegateAsSelChImpl, ops, sk); - } - } - catch(IllegalAccessException | InvocationTargetException e) - { - classLogger.log( - Level.SEVERE, - "Cannot execute method translateAndSetInterestOpsMethod", e); - } - } - - /** - * {@inheritDoc} - * - * Forwards to {@link #delegate}. - */ - @SuppressWarnings("unused") - public int translateInterestOps(int ops) - { - try - { - if (translateInterestOpsMethod != null) - { - return (Integer) translateInterestOpsMethod.invoke( - delegateAsSelChImpl, ops); - } - } - catch(IllegalAccessException | InvocationTargetException e) - { - classLogger.log( - Level.SEVERE, - "Cannot execute method translateInterestOpsMethod", e); - } - - return 0; - } - - /** - * {@inheritDoc} - * - * Forwards to {@link #delegate}. - */ - @Override - public boolean translateAndSetReadyOps(int ops, SelectionKeyImpl sk) - { - return delegateAsSelChImpl.translateAndSetReadyOps(ops, sk); - } - - /** - * {@inheritDoc} - * - * Forwards to {@link #delegate}. - */ - @Override - public boolean translateAndUpdateReadyOps(int ops, SelectionKeyImpl sk) - { - return delegateAsSelChImpl.translateAndUpdateReadyOps(ops, sk); - } -} diff --git a/src/main/java/org/ice4j/socket/jdk8/DelegatingSocketChannel.java b/src/main/java/org/ice4j/socket/jdk8/DelegatingSocketChannel.java deleted file mode 100644 index a63dd3d..0000000 --- a/src/main/java/org/ice4j/socket/jdk8/DelegatingSocketChannel.java +++ /dev/null @@ -1,216 +0,0 @@ -/* - * ice4j, the OpenSource Java Solution for NAT and Firewall Traversal. - * - * Copyright @ 2018 - present 8x8, Inc. - * - * 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.jdk8; - -import java.io.*; -import java.lang.reflect.*; -import java.nio.channels.*; -import java.util.logging.*; - -import org.ice4j.socket.*; - -import sun.nio.ch.*; - -/** - * Implements a {@code SocketChannel} which delegates (its method calls) to - * another {@code SocketChannel}. In other words, the former wraps the latter. - * - * @author Lyubomir Marinov - */ -class DelegatingSocketChannel - extends BaseDelegatingSocketChannel - implements SelChImpl -{ - /** - * The {@link Logger} used by the {@link DelegatingSocketChannel} - * class and its instances for logging output. - */ - private static final java.util.logging.Logger classLogger - = java.util.logging.Logger.getLogger( - DelegatingSocketChannel.class.getName()); - - /** - * The view of {@link #delegate} as a SelChImpl interface instance - * required by {@link Selector} and related functionality. - */ - protected final SelChImpl delegateAsSelChImpl; - - /** - * The translateAndSetInterestOps method available in java 8. - */ - private final Method translateAndSetInterestOpsMethod; - - /** - * The translateInterestOps method available in java 11. - */ - private final Method translateInterestOpsMethod; - - /** - * Initializes a new {@code DelegatingSocketChannel} instance which is to - * delegate (its method calls) to a specific {@code SocketChannel}. - * - * @param delegate the {@code SocketChannel} the new instance is to delegate - * (its method calls) to - */ - public DelegatingSocketChannel(T delegate) - { - super(delegate); - - delegateAsSelChImpl - = (delegate instanceof SelChImpl) ? (SelChImpl) delegate : null; - - Method method; - try - { - method = SelChImpl.class.getMethod( - "translateAndSetInterestOps", - Integer.TYPE, SelectionKeyImpl.class); - } - catch(NoSuchMethodException e) - { - method = null; - - } - translateAndSetInterestOpsMethod = method; - - try - { - method = SelChImpl.class.getMethod( - "translateInterestOps", Integer.TYPE); - } - catch(NoSuchMethodException e) - { - method = null; - } - translateInterestOpsMethod = method; - - if (translateInterestOpsMethod == null - && translateAndSetInterestOpsMethod == null) - { - classLogger.log( - Level.SEVERE, "Cannot find translateInterestOps " + - "or translateAndSetInterestOps!"); - } - } - - /** - * {@inheritDoc} - * - * Forwards to {@link #delegate}. - */ - @Override - public FileDescriptor getFD() - { - return delegateAsSelChImpl.getFD(); - } - - /** - * {@inheritDoc} - * - * Forwards to {@link #delegate}. - */ - @Override - public int getFDVal() - { - return delegateAsSelChImpl.getFDVal(); - } - - /** - * {@inheritDoc} - * - * Forwards to {@link #delegate}. - */ - @Override - public void kill() - throws IOException - { - delegateAsSelChImpl.kill(); - } - - /** - * {@inheritDoc} - * - * Forwards to {@link #delegate}. - */ - @SuppressWarnings("unused") - public void translateAndSetInterestOps(int ops, SelectionKeyImpl sk) - { - try - { - if (translateAndSetInterestOpsMethod != null) - { - translateAndSetInterestOpsMethod.invoke( - delegateAsSelChImpl, ops, sk); - } - } - catch(IllegalAccessException | InvocationTargetException e) - { - classLogger.log( - Level.SEVERE, - "Cannot execute method translateAndSetInterestOpsMethod", e); - } - } - - /** - * {@inheritDoc} - * - * Forwards to {@link #delegate}. - */ - @SuppressWarnings("unused") - public int translateInterestOps(int ops) - { - try - { - if (translateInterestOpsMethod != null) - { - return (Integer) translateInterestOpsMethod.invoke( - delegateAsSelChImpl, ops); - } - } - catch(IllegalAccessException | InvocationTargetException e) - { - classLogger.log( - Level.SEVERE, - "Cannot execute method translateInterestOpsMethod", e); - } - - return 0; - } - - /** - * {@inheritDoc} - * - * Forwards to {@link #delegate}. - */ - @Override - public boolean translateAndSetReadyOps(int ops, SelectionKeyImpl sk) - { - return delegateAsSelChImpl.translateAndSetReadyOps(ops, sk); - } - - /** - * {@inheritDoc} - * - * Forwards to {@link #delegate}. - */ - @Override - public boolean translateAndUpdateReadyOps(int ops, SelectionKeyImpl sk) - { - return delegateAsSelChImpl.translateAndUpdateReadyOps(ops, sk); - } -} diff --git a/src/main/java/org/ice4j/socket/jdk8/MuxServerSocket.java b/src/main/java/org/ice4j/socket/jdk8/MuxServerSocket.java deleted file mode 100644 index 80508a8..0000000 --- a/src/main/java/org/ice4j/socket/jdk8/MuxServerSocket.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * ice4j, the OpenSource Java Solution for NAT and Firewall Traversal. - * - * Copyright @ 2015 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.jdk8; - -import java.io.*; -import java.net.*; -import java.util.*; - -import org.ice4j.socket.*; - -/** - * Represents a {@link ServerSocket} associated with a - * {@code MuxServerSocketChannel}. - * - * @author Lyubomir Marinov - */ -class MuxServerSocket - extends DelegatingServerSocket -{ - /** - * Initializes a new {@code MuxServerSocket} instance which delegates (its - * method calls) to a specific {@code MuxingServerSocket} and is associated - * with a specific {@code MuxServerSocketChannel}. - * - * @param delegate the {@code MuxingServerSocket} the new instance is to - * delegate (its method calls) to. Technically, it is the {@code socket} of - * the {@code delegate} of {@code channel}. - * @param channel the {@code MuxServerSocketChannel} associated with the new - * instance - * @throws IOException if an I/O error occurs - */ - public MuxServerSocket( - MuxingServerSocket delegate, - MuxServerSocketChannel channel) - throws IOException - { - super( - Objects.requireNonNull(delegate, "delegate"), - Objects.requireNonNull(channel, "channel")); - } -} diff --git a/src/main/java/org/ice4j/socket/jdk8/MuxServerSocketChannel.java b/src/main/java/org/ice4j/socket/jdk8/MuxServerSocketChannel.java deleted file mode 100644 index d7e9e77..0000000 --- a/src/main/java/org/ice4j/socket/jdk8/MuxServerSocketChannel.java +++ /dev/null @@ -1,298 +0,0 @@ -/* - * ice4j, the OpenSource Java Solution for NAT and Firewall Traversal. - * - * Copyright @ 2015 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.jdk8; - -import java.io.*; -import java.net.*; -import java.nio.channels.*; -import java.util.*; -import org.ice4j.socket.*; - -/** - * Implements a {@link ServerSocketChannel} which is capable of sharing its - * listening endpoint with multiple others like it. - * - * @author Lyubomir Marinov - */ -public class MuxServerSocketChannel - extends DelegatingServerSocketChannel -{ - /** - * Opens and binds a new {@code MuxServerSocketChannel} instance. If there - * are other (existing) {@code MuxServerSocketChannel} open and bound on the - * specified listening {@code endpoint}, the new instance will share it with - * them. - * - * @param properties a {@code Map} of the values to be assigned to - * properties of the underlying {@link ServerSocketChannel} which is to - * actually listen on the specified {@code endpoint}. If the new instance is - * not the first to open and bind the specified {@code endpoint}, the - * {@code properties} and their respective values may not be used. - * @param endpoint the IP and port the new instance is to bind to - * @param backlog the requested maximum number of pending incoming - * connections to be queued. If the new instance is not the first to open - * and bind the specified {@code endpoint}, the value may not be used. - * @param filter the {@code DatagramPacketFilter} to demultiplex (i.e. - * recognize) the content meant for the new instance - * @return a new {@code MuxServerSocketChannel} instance open and bound on - * the specified listening {@code endpoint} - * @throws IOException if an I/O error occurs - */ - public static MuxServerSocketChannel openAndBind( - Map properties, - SocketAddress endpoint, - int backlog, - DatagramPacketFilter filter) - throws IOException - { - return - MuxingServerSocketChannel.openAndBind( - properties, - endpoint, - backlog, - filter); - } - - /** - * The (ordered) list (i.e. queue) of SocketChannels to be returned - * by {@link #accept()}. - */ - private final Queue> acceptQ - = new LinkedList<>(); - - /** - * The {@code DatagramPacketFilter} which demultiplexes - * {@code SocketChannel}s accepted by the associated - * {@code MuxingServerSocketChannel}. - */ - protected final DatagramPacketFilter filter; - - /** - * The Object which synchronizes the access to the state of this - * MuxServerSocketChannel such as {@link #acceptQ}. - */ - private final Object syncRoot = new Object(); - - /** - * Initializes a new {@code MuxServerSocketChannel} instance which is to - * demultiplex {@link SocketChannel}s accepted by a specific - * {@link MuxingServerSocketChannel} using a specific - * {@link DatagramPacketFilter}. The new instance shares the listening - * endpoint of {@code delegate} with any other associated - * {@code MuxServerSocketChannel}s. - * - * @param delegate the {@code MuxingServerSocketChannel} which is actually - * open and bound to a listening endpoint and accepts {@code SocketChannel}s - * to be filtered by associated - * {@code MuxServerSocketChannel}s - * @param filter the {@code DatagramPacketFilter} which is to demultiplex - * {@code SocketChannel}s accepted by {@code delegate} - */ - protected MuxServerSocketChannel( - MuxingServerSocketChannel delegate, - DatagramPacketFilter filter) - { - super(Objects.requireNonNull(delegate, "delegate")); - - this.filter = Objects.requireNonNull(filter, "filter"); - } - - /** - * {@inheritDoc} - */ - @Override - public SocketChannel accept() - throws IOException - { - SocketChannel accepted = null; - boolean interrupted = false; - - // Pop a SocketChannel from acceptQ. - try - { - do - { - if (!isOpen()) - { - throw new ClosedChannelException(); - } - else if (!isBound()) - { - throw new NotYetBoundException(); - } - else - { - synchronized (syncRoot) - { - Timestamped timestamped = acceptQ.poll(); - - if (timestamped == null) - { - if (isBlocking()) - { - try - { - syncRoot.wait(); - } - catch (InterruptedException ie) - { - interrupted = true; - } - } - else - { - break; - } - } - else if ((accepted = timestamped.o).isOpen()) - { - // Allow the MuxServerSocketChannel class and/or its - // super(s) to have a final say on the accepted - // SocketChannel such as wrapping it into a suitable - // specialization of DelegatingSocketChannel. - accepted = implAccept(accepted); - if (accepted != null) - break; - } - } - } - } - while (true); - } - finally - { - // Restore the interrupted state of the current thread if we've - // cleared it in the loop above. - if (interrupted) - Thread.currentThread().interrupt(); - } - return accepted; - } - - /** - * Weeds out abandoned {@code SocketChannels} from {@link #acceptQ} i.e. - * which were classified/filtered into this {@code MuxServerSocketChannel} - * but were not accepted (out of it) for a long time. - * - * @param now the (system) time in milliseconds at which the method is - * invoked - */ - void closeAbandonedSocketChannels(long now) - { - synchronized (syncRoot) - { - Collection> chs = acceptQ; - - if (!chs.isEmpty()) - { - for (Iterator> i = chs.iterator(); - i.hasNext();) - { - Timestamped ch = i.next(); - - if (now - ch.timestamp - >= MuxingServerSocketChannel - .SOCKET_CHANNEL_READ_TIMEOUT) - { - i.remove(); - MuxingServerSocketChannel.closeNoExceptions(ch.o); - } - } - } - } - } - - /** - * Determines whether the {@link #filter} of this instance accepts a - * specific {@code SocketChannel} from which a specific - * {@code DatagramPacket} has been read and, if it does, queues the - * {@code channel} to be accepted through this instance. - * - * @param p the {@code DatagramPacket} which has been read from - * {@code channel} and which is to be analyzed by the {@code filter} of this - * instance - * @param channel the {@code SocketChannel} from which {@code p} has been - * read and which is to be queued for acceptance through this instance if - * the {@code filter} accepts {@code p} - * @return {@code true} if the {@code filter} of this instance accepts - * {@code p} and {@code channel} was queued for acceptance through this - * instance; otherwise, {@code false} - */ - protected boolean filterAccept(DatagramPacket p, SocketChannel channel) - { - return - filter.accept(p) && qAccept(new PreReadSocketChannel(p, channel)); - } - - /** - * {@inheritDoc} - * - * Adjusts the blocking mode of {@link #delegate}. - */ - @Override - protected void implConfigureBlocking(boolean block) - throws IOException - { - // If at least one MuxServerSocketChannel is configured as non-blocking, - // then MuxingServerSocketChannel has to be configured as non-blocking - // as well. - if (!block) - delegate.configureBlocking(block); - } - - /** - * {@inheritDoc} - * - * Associates a {@link MuxServerSocket} with this - * {@code MuxServerSocketChannel}. - */ - @Override - protected MuxServerSocket implSocket(ServerSocket socket) - throws IOException - { - return new MuxServerSocket((MuxingServerSocket) socket, this); - } - - /** - * Queues a {@link SocketChannel} for acceptance through this instance. - * - * @param channel the {@code SocketChannel} to queue for acceptance through - * this instance - * @return {@code true} if {@code channel} was queued for acceptance through - * this instance; otherwise, {@code false} - */ - boolean qAccept(SocketChannel channel) - { - boolean b; - - synchronized (syncRoot) - { - if (acceptQ.offer( - new Timestamped<>(channel, System.currentTimeMillis()))) - { - syncRoot.notifyAll(); - b = true; - } - else - { - b = false; - } - } - return b; - } -} diff --git a/src/main/java/org/ice4j/socket/jdk8/MuxingServerSocket.java b/src/main/java/org/ice4j/socket/jdk8/MuxingServerSocket.java deleted file mode 100644 index 667a3ec..0000000 --- a/src/main/java/org/ice4j/socket/jdk8/MuxingServerSocket.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * ice4j, the OpenSource Java Solution for NAT and Firewall Traversal. - * - * Copyright @ 2015 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.jdk8; - -import java.io.*; -import java.net.*; -import java.util.*; - -import org.ice4j.socket.*; - -/** - * Represents a {@link ServerSocket} associated with a - * {@code MuxingServerSocketChannel}. - * - * @author Lyubomir Marinov - */ -class MuxingServerSocket - extends DelegatingServerSocket -{ - /** - * Initializes a new {@code MuxingServerSocket} instance which delegates - * (its method calls) to a specific {@code ServerSocket} and is associated - * with a specific {@code MuxingServerSocketChannel}. - * - * @param delegate the {@code ServerSocket} the new instance is to delegate - * (its method calls) to. Technically, it is the {@code socket} of the - * {@code delegate} of {@code channel}. - * @param channel the {@code MuxingServerSocketChannel} associated with the - * new instance - * @throws IOException if an I/O error occurs - */ - public MuxingServerSocket( - ServerSocket delegate, - MuxingServerSocketChannel channel) - throws IOException - { - super( - Objects.requireNonNull(delegate, "delegate"), - Objects.requireNonNull(channel, "channel")); - } -} diff --git a/src/main/java/org/ice4j/socket/jdk8/MuxingServerSocketChannel.java b/src/main/java/org/ice4j/socket/jdk8/MuxingServerSocketChannel.java deleted file mode 100644 index dcf2ca7..0000000 --- a/src/main/java/org/ice4j/socket/jdk8/MuxingServerSocketChannel.java +++ /dev/null @@ -1,1125 +0,0 @@ -/* - * ice4j, the OpenSource Java Solution for NAT and Firewall Traversal. - * - * Copyright @ 2015 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.jdk8; - -import java.io.*; -import java.net.*; -import java.nio.*; -import java.nio.channels.*; -import java.util.*; -import java.util.function.*; -import org.ice4j.ice.harvest.*; -import org.ice4j.socket.*; - -/** - * Shares a listening endpoint (i.e. an open and bound - * {@link ServerSocketChannel}) among multiple {@code MuxServerSocketChannel}s. - * Accepted {@link SocketChannel}s are demultiplexed based on - * {@link DatagramPacketFilter}s and dispatched for acceptance through matching - * {@code MuxServerSocketChannel}s. - * - * @author Lyubomir Marinov - */ -class MuxingServerSocketChannel - extends DelegatingServerSocketChannel -{ - /** - * Reference to 0.0.0.0 IPv4 or 0::0 IPv6 address for "wildcard" matching - * purposes. - */ - private static final InetAddress ANY_LOCAL_ADDRESS; - - /** - * The {@code Selector} which waits for incoming network connections on all - * {@link #muxingServerSocketChannels}. - */ - private static Selector acceptSelector; - - /** - * The {@code Thread} which waits for and accepts incoming network - * connections on all {@link #muxingServerSocketChannels}. - */ - private static Thread acceptThread; - - /** - * The (global) list of existing MixingServerSocketChannels. - */ - private static final List - muxingServerSocketChannels - = new LinkedList<>(); - - /** - * The maximum number of milliseconds to wait in a - * {@link Selector#select(long)}. The timeout should be a precaution though - * i.e. (1) it should better not be necessary and (2) it should be long - * enough to not unnecessarily hurt the performance of the application. - */ - private static final int SELECTOR_SELECT_TIMEOUT - = MuxServerSocketChannelFactory.SOCKET_CHANNEL_READ_TIMEOUT; - - /** - * The maximum number of milliseconds to wait for an accepted - * {@code SocketChannel} to provide incoming/readable data before it is - * considered abandoned by the client. - */ - static final int SOCKET_CHANNEL_READ_TIMEOUT - = MuxServerSocketChannelFactory.SOCKET_CHANNEL_READ_TIMEOUT; - - /** - * The maximum number of {@code byte}s to be read from - * {@link SocketChannel}s accepted by {@link MuxingServerSocketChannel}s in - * order to demultiplex (i.e. filter) them into - * {@code MuxServerSocketChannel}s. - */ - private static final int SOCKET_CHANNEL_READ_CAPACITY - = Math.max( - GoogleTurnSSLCandidateHarvester.SSL_CLIENT_HANDSHAKE.length, - Math.max( - HttpDemuxFilter.REQUEST_METHOD_MAX_LENGTH + 1 /* SP */, - HttpDemuxFilter.TLS_MIN_LENGTH)); - - static - { - try - { - ANY_LOCAL_ADDRESS = InetAddress.getByName("::"); - } - catch (UnknownHostException e) - { - throw new RuntimeException(e); - } - } - - /** - * Adds a specific {@code MuxingServerSocketChannel} to the (global) list of - * existing {@code MuxingServerSocketChannel}s and schedules acceptance of - * incoming network connections on it. - * - * @param channel the {@code MuxingServerSocketChannel} to add to the - * (global) list of existing {@code MuxingServerSocketChannel}s and to - * schedule for acceptance of incoming network connections - * @throws IOException if an I/O error occurs - */ - private static void addMuxingServerSocketChannel( - MuxingServerSocketChannel channel) - throws IOException - { - synchronized (muxingServerSocketChannels) - { - muxingServerSocketChannels.add(channel); - muxingServerSocketChannels.notifyAll(); - - scheduleAccept(channel); - } - } - - /** - * Closes a {@code Channel} and swallows any {@link IOException}. - * - * @param channel the {@code Channel} to close - */ - public static void closeNoExceptions(Channel channel) - { - MuxServerSocketChannelFactory.closeNoExceptions(channel); - } - - /** - * Finds the first open {@code MuxingServerSocketChannel} in the (global) - * list of existing {@code MuxingServerSocketChannel}s which is bound to a - * specific local {@link SocketAddress}. - * - * @param localAddr the local {@code SocketAddress} on which the bound - * {@code MuxingServerSocketChannel} is to be found - * @return the first open {@code MuxingServerSocketChannel} in the (global) - * list of existing {@code MuxingServerSocketChannel}s which is bound to the - * specified {@code localAddr} or {@code null} - */ - private static MuxingServerSocketChannel findMuxingServerSocketChannel( - SocketAddress localAddr) - { - MuxingServerSocketChannel channel = null; - - synchronized (muxingServerSocketChannels) - { - Iterator i - = muxingServerSocketChannels.iterator(); - - while (i.hasNext()) - { - MuxingServerSocketChannel aChannel = i.next(); - - if (aChannel.isOpen()) - { - SocketAddress aLocalAddr; - - try - { - aLocalAddr = aChannel.getLocalAddress(); - } - catch (ClosedChannelException cce) - { - i.remove(); - aLocalAddr = null; - } - catch (IOException ioe) - { - aLocalAddr = null; - } - - boolean matches - = aLocalAddr != null && aLocalAddr.equals(localAddr); - - // If not the same address, let's see if the cached one is - // an "anyLocalAddress" and if so let's consider it a match. - if (!matches - && aLocalAddr instanceof InetSocketAddress - && localAddr instanceof InetSocketAddress) - { - InetSocketAddress aLocalInetAddr - = (InetSocketAddress) aLocalAddr; - InetSocketAddress localInetAddr - = (InetSocketAddress) localAddr; - - matches - = aLocalInetAddr.getAddress() - .equals(ANY_LOCAL_ADDRESS) - && aLocalInetAddr.getPort() - == localInetAddr.getPort(); - } - - if (matches) - { - channel = aChannel; - // The whole idea of using (1) a List for - // muxingServerSocketChannels instead of a Map and (2) - // an Iterator to loop over muxingServerSocketChannels - // is to aggressively clean up. Anyway, break as soon as - // possible in order to improve the execution speed and - // because there is an attempt to clean - // muxingServerSocketChannels up upon closing. - break; - } - } - else - { - i.remove(); - } - } - } - return channel; - } - - /** - * If {@link #acceptSelector} exists and is open, try to close it and do not - * throw an IOException. - */ - private static void maybeCloseAcceptSelector() - { - if (acceptSelector != null) - { - if (acceptSelector.isOpen()) - { - try - { - acceptSelector.close(); - } - catch (IOException ioe) - { - // I don't know what to do about any IOException during - // Selector#close() even if I log it. - } - } - acceptSelector = null; - } - } - - /** - * Opens and binds a new {@code MuxServerSocketChannel} instance. If there - * are other (existing) {@code MuxServerSocketChannel} open and bound on the - * specified listening {@code endpoint}, the new instance will share it with - * them. - * - * @param properties a {@code Map} of the values to be assigned to - * properties of the underlying {@link ServerSocketChannel} which is to - * actually listen on the specified {@code endpoint}. If the new instance is - * not the first to open and bind the specified {@code endpoint}, the - * {@code properties} and their respective values may not be used. - * @param endpoint the IP and port the new instance is to bind to - * @param backlog the requested maximum number of pending incoming - * connections to be queued. If the new instance is not the first to open - * and bind the specified {@code endpoint}, the value may not be used. - * @param filter the {@code DatagramPacketFilter} to demultiplex (i.e. - * recognize) the content meant for the new instance - * @return a new {@code MuxServerSocketChannel} instance open and bound on - * the specified listening {@code endpoint} - * @throws IOException if an I/O error occurs - */ - public static MuxServerSocketChannel openAndBind( - Map properties, - SocketAddress endpoint, - int backlog, - DatagramPacketFilter filter) - throws IOException - { - // The restriction(s) on filter are imposed by MuxingServerSocketChannel - // and MuxServerSocketChannel. Assert that they are satisfied as early - // as possible though because it does not make sense to bind a - // ServerSocketChannel and initialize a new MuxingServerSocketChannel - // instance otherwise. - Objects.requireNonNull(filter, "filter"); - - MuxingServerSocketChannel muxingChannel; - - synchronized (muxingServerSocketChannels) - { - muxingChannel = findMuxingServerSocketChannel(endpoint); - if (muxingChannel == null) - { - ServerSocketChannel channel - = MuxServerSocketChannelFactory - .openAndBindServerSocketChannel( - properties, - endpoint, - backlog); - - muxingChannel = new MuxingServerSocketChannel(channel); - addMuxingServerSocketChannel(muxingChannel); - } - } - - return muxingChannel.createMuxServerSocketChannel(filter); - } - - /** - * Runs in {@link #acceptThread} and waits for and accepts incoming network - * connections on all {@link #muxingServerSocketChannels}. - */ - private static void runInAcceptThread() - { - runInSelectorThread( - /* syncRoot */ muxingServerSocketChannels, - /* threadSupplier */ new Supplier() - { - @Override - public Thread get() - { - return MuxingServerSocketChannel.acceptThread; - } - }, - /* selectorSupplier */ new Supplier() - { - @Override - public Selector get() - { - return MuxingServerSocketChannel.acceptSelector; - } - }, - /* selectionKeyOps */ SelectionKey.OP_ACCEPT, - /* channels */ muxingServerSocketChannels, - /* predicate */ new BiPredicate() - { - @Override - public boolean test( - MuxingServerSocketChannel ch, - SelectionKey sk) - { - try - { - // The idea is that all muxingServerSocketChannels - // are non-blocking. - ch.accept(); - } - catch (IOException ioe) - { - // If ioe is a ClosedChannelException signalling - // that ch is closed, it will be handled at the end - // of the loop by removing ch from - // muxingServerSocketChannels. - } - - return false; - } - }); - } - - /** - * Continually tests a {@link Predicate} on a set of - * {@link SelectableChannel}s. - * - * @param syncRoot the {@code Object} to synchronize the access to - * {@code threadSupplier}, {@code selectorSupplier}, {@code channels}, and - * {@code predicate}. It should be notified whenever the values supplied by - * {@code threadSupplier}, {@code selectorSupplier}, and {@code channels} - * change. - * @param threadSupplier the {@link Supplier} which is to supply the - * {@code Thread} in which the method is supposed to be running. If the - * returned value differs from the {@code Thread} in which the method is - * actually running (i.e. {@link Thread#currentThread()}, the method - * returns. In other words, {@code threadSupplier} is one of the ways to - * break out of the loop implemented by the method. The - * {@code threadSupplier} is called on while {@code syncRoot} is acquired. - * @param selectorSupplier the {@code Supplier} which is to supply the - * {@code Selector} on which the method is to await changes in the states of - * {@code channels} in order to begin a subsequent loop iteration. If the - * returned {@code Selector} is not open, the method returns. In other - * words, {@code selectorSupplier} is another way to break out of the loop - * implemented by the method. The {@code selectorSupplier} is called on - * while {@code syncRoot} is acquired. - * @param selectionKeyOps the {@link SelectionKey} operation-set bits which - * identify the states of {@code channels} whose changes trigger new loop - * iterations - * @param channels the (set of) {@code SelectableChannel}s on each of which - * {@code predicate} is to be continually tested. A loop iteration is - * triggered when at least one of {@code channels} has a state identified by - * {@code selectionKeyOps} changes. - * @param predicate the {@code Predicate} which is to be continually tested - * on {@code channels}. A loop iteration is triggered when at least one of - * {@code channels} has a state identified by {@code selectionKeyOps} - * changes. {@link BiPredicate#test(Object, Object)} is supplied with an - * element of {@code channels} and its (automatically) associated - * {@code SelectionKey} in the {@code Selector} returned by - * {@code selectorSupplier}. The {@code SelectionKey} is provided in case, - * for example, the implementation of {@code predicate} chooses to associate - * additional state with the {@code SelectableChannel} (through - * {@link SelectionKey#attach(Object)}) available throughout the whole loop. - * @param the element type of {@code channels} - */ - private static void runInSelectorThread( - Object syncRoot, - Supplier threadSupplier, - Supplier selectorSupplier, - int selectionKeyOps, - Iterable channels, - BiPredicate predicate) - { - // The timeout to use when invoking Selector#select(long) on sel (i.e. - // the Selector supplied by selectorSupplier). It purpose is twofold: - // (1) to not wait too long in Selector#select() (hence - // SELECTOR_SELECT_TIMEOUT) and (2) to weed out abandoned channels - // (hence SOCKET_CHANNEL_READ_TIMEOUT). - final int selSelectTimeout - = Math.min(SELECTOR_SELECT_TIMEOUT, SOCKET_CHANNEL_READ_TIMEOUT); - - do - { - Selector sel; - boolean select = false; - - synchronized (syncRoot) - { - if (!Thread.currentThread().equals(threadSupplier.get())) - break; - - sel = selectorSupplier.get(); - if (sel == null || !sel.isOpen()) - break; - - for (Iterator i = channels.iterator(); i.hasNext();) - { - T ch = i.next(); - boolean remove = false; - - if (ch.isOpen()) - { - SelectionKey sk = ch.keyFor(sel); - - if (sk == null) - { - // Make sure that all (SelectableChannels in) - // channels are registered with (the Selector) sel. - try - { - sk = ch.register(sel, selectionKeyOps); - } - catch (ClosedChannelException cce) - { - // The cce will be handled at the end of the - // loop by removing ch from channels. - } - } - if (sk != null && sk.isValid()) - { - remove = predicate.test(ch, sk); - if (remove) - sk.cancel(); - } - } - - if (remove || !ch.isOpen()) - i.remove(); - else - select = true; - } - - // We've invoked the predicate on all (SelectableChannels in) - // channels. - sel.selectedKeys().clear(); - - // If there are no SelectableChannels in channels, we will wait - // until there are. - if (!select) - { - // We're going to wait bellow and continue with the next - // iteration of the loop afterwards. Don't hold onto sel - // while waiting (because it's unnecessary). - sel = null; - - try - { - syncRoot.wait(); - } - catch (InterruptedException ie) - { - // I don't know that we care about the interrupted state - // of the current thread because the method - // runInSelectorThread() is (or at least should be) - // pretty much the whole execution of the current thread - // that could potentially care about the interrupted - // state and it doesn't (or at least shouldn't). - } - continue; - } - } - - // Wait for a new change in the state(s) of at least one element of - // channels. (The value of the local variable select is guaranteed - // to be true here.) - try - { - // Even if no element of channels has its state(s) changed, do - // wake up after selSelectTimeout milliseconds in order to weed - // out abandoned channels. - sel.select(selSelectTimeout); - } - catch (ClosedSelectorException cse) - { - break; - } - catch (IOException ioe) - { - // Well, we're selecting from multiple SelectableChannels so - // we're not sure what the IOException signals here. - } - } - while (true); - } - - /** - * Schedules a specific {@code MuxingServerSocketChannel} for acceptance of - * incoming network connections in {@link #acceptThread}. - * - * @param channel the {@code MuxingServerSocketChannel} to schedule for - * acceptance of incoming network connections in {@code acceptThread} - * @throws IOException if an I/O error occurs - */ - private static void scheduleAccept(MuxingServerSocketChannel channel) - throws IOException - { - synchronized (muxingServerSocketChannels) - { - if (acceptThread == null) - { - // acceptSelector - maybeCloseAcceptSelector(); - try - { - acceptSelector = channel.provider().openSelector(); - } - catch (IOException ioe) - { - acceptSelector = Selector.open(); - } - - // acceptThread - acceptThread - = new Thread() - { - @Override - public void run() - { - try - { - runInAcceptThread(); - } - finally - { - synchronized (muxingServerSocketChannels) - { - if (Thread.currentThread().equals( - acceptThread)) - { - // acceptThread - acceptThread = null; - // acceptSelector - maybeCloseAcceptSelector(); - } - } - } - } - }; - acceptThread.setDaemon(true); - acceptThread.setName( - MuxingServerSocketChannel.class.getName() - + ".acceptThread"); - acceptThread.start(); - } - else - { - // Notify acceptThread that a new MuxingServerSocketChannel - // (e.g. channel) may have been added. - Selector sel = MuxingServerSocketChannel.acceptSelector; - - if (sel != null) - sel.wakeup(); - } - } - - // We might as well expedite the acceptance from - // muxingServerSocketChannel i.e. not wait for acceptThread and - // explicitly cause an accept iteration. - channel.accept(); - } - - /** - * The list of MuxServerSocketChannels created by and delegating to - * this instance. - */ - private final List muxServerSocketChannels - = new ArrayList<>(); - - /** - * The list of {@code SocketChannel}s which have been accepted by this - * {@code MuxingServerSocketChannel}, are being read from, and have not been - * accepted by the {@link DatagramPacketFilter} of any - * {@link MuxServerSocketChannel} yet. - */ - private final Queue readQ = new LinkedList<>(); - - /** - * The {@code Selector} which waits for incoming packets on all - * {@code SocketChannel}s in {@link #readQ}. - */ - private final Selector readSelector; - - /** - * The {@code Thread} which waits for incoming packets on and reads them - * from all {@code SocketChannel}s in {@link #readQ}. - */ - private Thread readThread; - - /** - * The Object which synchronizes the access to the state of this - * MuxingServerSocketChannel such as - * {@link #muxServerSocketChannels} and {@link #readQ}. - */ - private final Object syncRoot = new Object(); - - /** - * Initializes a new {@code MuxingServerSocketChannel} instance which is to - * share the listening endpoint of a specific {@link ServerSocketChannel} - * among multiple {@code MuxServerSocketChannel}s. - * - * @param delegate the {@code ServerSocketChannel} for which the new - * instance is to provide listening endpoint sharing - * @throws IOException if an I/O error occurs - */ - public MuxingServerSocketChannel(ServerSocketChannel delegate) - throws IOException - { - super(Objects.requireNonNull(delegate, "delegate")); - - // If at least one MuxServerSocketChannel is configured as non-blocking, - // then MuxingServerSocketChannel (i.e. delegate) has to be configured - // as non-blocking as well. - configureBlocking(false); - - readSelector = provider().openSelector(); - } - - /** - * {@inheritDoc} - */ - @Override - public SocketChannel accept() - throws IOException - { - SocketChannel ch = super.accept(); - - // Weeds out abandoned SocketChannels which were classified/filtered - // into MuxServerSocketChannel but were not accepted (out of it) for a - // long time. The accept() method of MuxingServerSocketChannel is a - // suitable place to do that because it is periodically invoked (by the - // runInAcceptThread() method) on a clock (in addition to network - // activity, of course). - closeAbandonedSocketChannels(); - - return ch; - } - - /** - * Adds a specific {@code MuxServerSocketChannel} to the list of - * {@code MuxServerSocketChannel}s created by and delegating to this - * instance. - * - * @param channel the {@code MuxServerSocketChannel} to add - */ - protected void addMuxServerSocketChannel(MuxServerSocketChannel channel) - { - synchronized (syncRoot) - { - muxServerSocketChannels.add(channel); - syncRoot.notifyAll(); - - // Wake readThread up in case a SocketChannel from readQ is accepted - // by the filter of the newly-added MuxServerSocketChannel. - scheduleRead(/* channel */ null); - } - } - - /** - * Weed out {@code SocketChannel}s which were classified/filtered into - * {@code MuxServerSocketChannel} but were not accepted (out of it) for a - * long time. - */ - private void closeAbandonedSocketChannels() - { - synchronized (syncRoot) - { - Collection chs = muxServerSocketChannels; - - if (!chs.isEmpty()) - { - long now = System.currentTimeMillis(); - - for (MuxServerSocketChannel ch : chs) - ch.closeAbandonedSocketChannels(now); - } - } - } - - /** - * Initializes a new {@code MuxServerSocketChannel} instance which is to - * delegate to this instance and is to demultiplex incoming network - * connections and packets using a specific {@link DatagramPacketFilter}. - * - * @param filter the {@code DatagramPacketFilter} to be used by the new - * {@code MuxServerSocketChannel} instance to demultiplex incoming network - * connections and packets - * @return a new {@code MuxServerSocketChannel} instance which delegates to - * this instance and demultiplexes incoming network connections and packets - * using the specified {@code filter} - */ - protected MuxServerSocketChannel createMuxServerSocketChannel( - DatagramPacketFilter filter) - { - // A MuxServerSocketChannel with no filter does not make sense. It - // cannot be a fallback because DatagramPacketFilters (i.e. - // MuxServerSocketChannels) have no priorities. It cannot be a catch all - // because a SocketChannel (i.e. Socket) may be accepted by a single - // MuxServerSocketChannel only. - Objects.requireNonNull(filter, "filter"); - - MuxServerSocketChannel channel; - - synchronized (syncRoot) - { - for (Iterator i - = muxServerSocketChannels.iterator(); - i.hasNext();) - { - MuxServerSocketChannel aChannel = i.next(); - - if (aChannel.isOpen()) - { - DatagramPacketFilter aFilter = aChannel.filter; - - // The implementations of Object#equals(Object) should be - // symmetric but they are written by humans so there is room - // for errors. - if (filter.equals(aFilter) || aFilter.equals(filter)) - { - // A SocketChannel (i.e. Socket) may be accepted by a - // single MuxServerSocketChannel only. - throw new IllegalArgumentException("filter"); - } - } - else - { - i.remove(); - } - } - - channel = new MuxServerSocketChannel(this, filter); - addMuxServerSocketChannel(channel); - } - - muxServerSocketChannelAdded(channel); - - return channel; - } - - /** - * Determines whether any of the {@code MuxServerSocketChannel}s created by - * and delegating to this instance demultiplexes (i.e. recognizes) a - * specific {@link SocketChannel} based on a specific {@link DatagramPacket} - * read from it and will make it available for acceptance. - * - * @param p the {@code DatagramPacket} read from {@code channel} which is to - * be analyzed by the {@code MuxServerSocketChannel}s created by and - * delegating to this instance - * @param channel the {@code SocketChannel} from which {@code p} was read - * and which is to possibly be demultiplexed into a - * {@code MuxServerSocketChannel} - * @return {@code true} if one of the {@code MuxServerSocketChannel}s - * created by and delegating to this instance demultiplexed the specified - * {@code channel}; otherwise, {@code false} - */ - private boolean filterAccept(DatagramPacket p, SocketChannel channel) - { - boolean b = false; - - for (Iterator i - = muxServerSocketChannels.iterator(); - i.hasNext();) - { - MuxServerSocketChannel muxChannel = i.next(); - - if (muxChannel.isOpen()) - { - try - { - b = muxChannel.filterAccept(p, channel); - if (b) - break; - } - catch (Throwable t) - { - // The implementation of DatagramPacketFilter is external to - // MuxingServerSocketChannel and we do not want the failure - // of one DatagramPacketFilter to kill the whole - // MuxingServerSocketChannel. - if (t instanceof InterruptedException) - Thread.currentThread().interrupt(); - else if (t instanceof ThreadDeath) - throw (ThreadDeath) t; - } - } - else - { - i.remove(); - } - } - return b; - } - - /** - * {@inheritDoc} - * - * Queues a {@link SocketChannel} accepted by this instance for reading so - * that it may later on be demultiplexed into a - * {@code MuxServerSocketChannel}. - */ - @Override - protected SocketChannel implAccept(SocketChannel accepted) - throws IOException - { - synchronized (syncRoot) - { - if (accepted != null && accepted.isOpen()) - { - accepted.configureBlocking(false); - - // If there is only one (open) MuxServerSocketChannel, it is - // inefficient to read from it in a separate thread and then - // either deliver the accepted to the MuxServerSocketChannel or - // close the accepted. The situation is pretty much like no - // functionality enabled by MuxServerSocketChannel is needed: - // whoever has invoked accept() on this ServerSocketChannel is - // going to read from the accepted and either figure out that it - // is in an expected format or close it. - MuxServerSocketChannel oneAndOnly = null; - - for (MuxServerSocketChannel ch : muxServerSocketChannels) - { - if (ch.isOpen()) - { - if (oneAndOnly == null) - { - oneAndOnly = ch; - } - else - { - oneAndOnly = null; - break; - } - } - } - if (oneAndOnly != null && oneAndOnly.qAccept(accepted)) - { - // It shouldn't matter much whether null or accepted is - // returned. It sounds reasonable to return null from the - // standpoint that accepted was classified/filtered into a - // MuxServerSocketChannel and, consequently, this - // MuxingServerSocketChannel no longer possesses it. - return null; - } - - // There are multiple (open) MuxServerSocketChannels (or none - // but then the situation is weird and it's more easily handled - // as the situation with multiple) and this instance is to read - // from accepted in orde to determine where it's to be - // classified/filtered. - readQ.add(accepted); - syncRoot.notifyAll(); - - scheduleRead(accepted); - } - } - - return accepted; - } - - /** - * {@inheritDoc} - * - * Associates a {@link MuxingServerSocket} with this - * {@code MuxingServerSocketChannel}. - */ - @Override - protected MuxingServerSocket implSocket(ServerSocket socket) - throws IOException - { - return new MuxingServerSocket(socket, this); - } - - /** - * Attempts to read from a specific {@link SocketChannel} into a specific - * {@link ByteBuffer} without throwing an {@link IOException} if the reading - * from the {@code channel} fails or there is insufficient room in - * {@code buf} to write into. - * - * @param channel the {@code SocketChannel} to read from - * @param buf the {@code ByteBuffer} to write into - * @return the number of {@code byte}s read from {@code channel} and written - * into {@code buf} or {@code -1} if {@code channel} has reached the end of - * its stream - */ - protected int maybeRead(SocketChannel channel, ByteBuffer buf) - { - int read; - - if (buf.remaining() > 0) - { - try - { - read = channel.read(buf); - } - catch (IOException ioe) - { - // If ioe is a ClosedChannelException signalling that the - // specified channel is closed, it will be handled by the method - // caller (by removing channel from readQ). - read = 0; - } - } - else - { - read = 0; - } - return read; - } - - /** - * Notifies this MixingServerSocketChannel that a specific - * MuxServerSocketChannel was added to - * {@link #muxServerSocketChannels}. - * - * @param channel the added MuxServerSocketChannel - */ - protected void muxServerSocketChannelAdded(MuxServerSocketChannel channel) - { - } - - /** - * Runs in {@link #readThread} and reads from all {@link SocketChannel}s in - * {@link #readQ} and serves them for demultiplexing to - * {@link #muxServerSocketChannels}. - */ - protected void runInReadThread() - { - runInSelectorThread( - /* syncRoot */ syncRoot, - /* threadSupplier */ new Supplier() - { - @Override - public Thread get() - { - return readThread; - } - }, - /* selectorSupplier */ new Supplier() - { - @Override - public Selector get() - { - return readSelector; - } - }, - /* selectionKeyOps */ SelectionKey.OP_READ, - /* channels */ readQ, - /* predicate */ new BiPredicate() - { - @Override - public boolean test(SocketChannel ch, SelectionKey sk) - { - return testRunInReadThreadPredicate(ch, sk); - } - }); - } - - /** - * Queues a specific {@link SocketChannel} to be read and demultiplexed into - * a {@code MuxServerSocketChannel}. - * - * @param channel the {@code SocketChannel} to queue for reading and - * demultiplexing - */ - protected void scheduleRead(SocketChannel channel) - { - synchronized (syncRoot) - { - if (readThread == null) - { - // readThread - readThread - = new Thread() - { - @Override - public void run() - { - try - { - runInReadThread(); - } - finally - { - synchronized (syncRoot) - { - if (Thread.currentThread().equals( - readThread)) - { - readThread = null; - } - } - } - } - }; - readThread.setDaemon(true); - readThread.setName( - MuxingServerSocketChannel.class.getName() - + ".readThread"); - readThread.start(); - } - else - { - // Notify readThread that a new SocketChannel (e.g. channel) may - // have been added. - Selector sel = this.readSelector; - - if (sel != null) - sel.wakeup(); - } - } - } - - /** - * Implements {@link BiPredicate#test(Object, Object)} of the - * {@code BiPredicate} utilized by {@link #runInReadThread()}. The method is - * defined explicitly for the purposes of reducing excessive indentation and - * bettering readability. Reads from {@code ch} and attempts to - * classify/filter it into a {@link MuxServerSocketChannel} for acceptance. - * If {@code ch} has not provided readable data within - * {@link #SOCKET_CHANNEL_READ_TIMEOUT}, it is forcibly closed. - * - * @param ch the {@code SocketChannel} to read from and to classify/filter - * into a {@code MuxServerSocketChannel} for acceptance - * @param sk the {@code SelectionKey} associated with {@code ch} in the - * {@code Selector} which awaits changes in the state(s) of {@code ch} - * @return {@code true} if {@code ch} is to no longer be tested; otherwise, - * {@code false} - */ - private boolean testRunInReadThreadPredicate( - SocketChannel ch, - SelectionKey sk) - { - // Try to read from ch. - DatagramBuffer db = (DatagramBuffer) sk.attachment(); - - if (db == null) - { - db = new DatagramBuffer(SOCKET_CHANNEL_READ_CAPACITY); - sk.attach(db); - } - - int read = maybeRead(ch, db.getByteBuffer()); - - // Try to filter ch (into a MuxServerSocketChannel). - if (ch.isOpen()) - { - // Maintain a record of when the SocketChannel last provided - // readable data in order to weed out abandoned ones. - long now = System.currentTimeMillis(); - - if (read > 0 || db.timestamp == -1) - db.timestamp = now; - - DatagramPacket p = db.getDatagramPacket(); - int len = p.getLength(); - - if (len > 0) - { - if (filterAccept(p, ch)) - { - // A MuxServerSocketChannel has accepted ch so this - // MuxingServerSocketChannel is no longer responsible for - // ch. - return true; - } - else if (len >= SOCKET_CHANNEL_READ_CAPACITY) - { - // This MuxingServerSocketChannel has read from ch as much - // as it will ever read and no existing - // MuxServerSocketChannel has accepted ch. There is no point - // in waiting anymore. - closeNoExceptions(ch); - // Allow this MuxingServerSocketChannel to clean ch up. - return false; - } - } - - if (read <= 0 && now - db.timestamp >= SOCKET_CHANNEL_READ_TIMEOUT) - { - // It appears ch has been abandoned by the client. - closeNoExceptions(ch); - return false; - } - } - - return false; - } -} diff --git a/src/main/java/org/ice4j/socket/jdk8/PreReadSocketChannel.java b/src/main/java/org/ice4j/socket/jdk8/PreReadSocketChannel.java deleted file mode 100644 index 8dcc7dc..0000000 --- a/src/main/java/org/ice4j/socket/jdk8/PreReadSocketChannel.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - * ice4j, the OpenSource Java Solution for NAT and Firewall Traversal. - * - * Copyright @ 2015 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.jdk8; - -import java.io.*; -import java.net.*; -import java.nio.*; -import java.nio.channels.*; - -/** - * Prepends a {@link DatagramPacket} to a {@link SocketChannel}. In other words, - * enables looking ahead at the {@code byte}s of a {@code SocketChannel}. - * - * @author Lyubomir Marinov - */ -class PreReadSocketChannel - extends DelegatingSocketChannel -{ - /** - * The {@link DatagramPacket} which is to be prepended to the - * {@link SocketChannel} which is the {@link #delegate} of this - * {@link DelegatingSocketChannel}. - */ - private final DatagramPacket preRead; - - /** - * Initializes a new {@code PreReadSocketChannel} instance which is to - * prepend a specific {@link DatagramPacket} to a specific - * {@link SocketChannel}. - * - * @param preRead the {@code DatagramPacket} to prepend to {@code delegate} - * @param delegate the {@code SocketChannel} to prepend {@code preRead} to - */ - public PreReadSocketChannel(DatagramPacket preRead, SocketChannel delegate) - { - super(delegate); - - this.preRead = preRead; - } - - /** - * {@inheritDoc} - * - * Reads from {@link #preRead} first (until it is fully read) and then - * continues with the {@code super} implementation. - */ - @Override - public int read(ByteBuffer dst) - throws IOException - { - synchronized (preRead) - { - int len = preRead.getLength(); - int read; - - if (len > 0) - { - int toRead = Math.min(len, dst.remaining()); - - if (toRead > 0) - { - byte[] buf = preRead.getData(); - int off = preRead.getOffset(); - - dst.put(buf, off, toRead); - read = toRead; - preRead.setData(buf, off + read, len - read); - } - else - { - read = 0; - } - } - else - { - read = 0; - } - - if (read == 0) - { - read = super.read(dst); - } - else if (dst.hasRemaining()) - { - int superRead = super.read(dst); - - if (superRead > 0) - read += superRead; - } - return read; - } - } -} diff --git a/src/main/java/org/ice4j/socket/jdk8/Timestamped.java b/src/main/java/org/ice4j/socket/jdk8/Timestamped.java deleted file mode 100644 index a46d2e1..0000000 --- a/src/main/java/org/ice4j/socket/jdk8/Timestamped.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * ice4j, the OpenSource Java Solution for NAT and Firewall Traversal. - * - * Copyright @ 2015 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.jdk8; - -/** - * Represents an {@code Object} with a timestamp. - * - * @param the type of the {@code Object} which has a timestamp (associated) - * @author Lyubomir Marinov - */ -class Timestamped -{ - /** - * The {@code Object} associated with {@link #timestamp}. - */ - final T o; - - /** - * The timestamp (in milliseconds) associated with {@link #o}. - */ - long timestamp; - - /** - * Initializes a new {@code Timestamped} instance with a specific - * {@code Object} and a default timestamp (value). - * - * @param o the {@code Object} to associate with a timestamp - */ - public Timestamped(T o) - { - this(o, -1); - } - - /** - * Initializes a new {@code Timestamped} instance with a specific - * {@code Object} and a specific timestamp (value). - * - * @param o the {@code Object} to associate with {@code timestamp} - * @param timestamp the timestamp (in milliseconds) to associate with - * {@code o} - */ - public Timestamped(T o, long timestamp) - { - // It makes no sense to associate a timestamp with a null. - if (o == null) - throw new NullPointerException("o"); - - this.o = o; - this.timestamp = timestamp; - } -} diff --git a/src/test/java/org/ice4j/socket/jdk8/MuxServerSocketChannelTest.java b/src/test/java/org/ice4j/socket/jdk8/MuxServerSocketChannelTest.java deleted file mode 100644 index 809cbc0..0000000 --- a/src/test/java/org/ice4j/socket/jdk8/MuxServerSocketChannelTest.java +++ /dev/null @@ -1,32 +0,0 @@ -package org.ice4j.socket.jdk8; - -import static org.junit.jupiter.api.Assertions.*; - -import java.io.IOException; -import java.net.InetSocketAddress; -import java.net.SocketAddress; - -import org.junit.jupiter.api.*; - -public class MuxServerSocketChannelTest -{ - @Disabled - @Test - void testOpenAndBindReuseWhenBindingToAllInterfacesFirst() - throws IOException - { - SocketAddress allInterfaces = new InetSocketAddress("::", 4443); - SocketAddress oneInterface = new InetSocketAddress("localhost", 4443); - - MuxServerSocketChannel channelForAllInterfaces = - MuxServerSocketChannel - .openAndBind(null, allInterfaces, 0, p -> false); - - MuxServerSocketChannel channelForOneInterface = - MuxServerSocketChannel - .openAndBind(null, oneInterface, 0, p -> false); - - assertEquals(channelForAllInterfaces.getFDVal(), - channelForOneInterface.getFDVal()); - } -}