From 446607e5d74f4dec785b5ed5691a44251c7aa9e2 Mon Sep 17 00:00:00 2001 From: "lubomir.marinov" Date: Fri, 1 May 2015 07:58:40 +0000 Subject: [PATCH] Allows a listening endpoint to be shared among multiple protocols (e.g. ICE-TCP, HTTP). --- .../harvest/MultiplexingTcpHostHarvester.java | 575 +++---- .../ice4j/socket/DelegatingServerSocket.java | 279 ++++ .../socket/DelegatingServerSocketChannel.java | 321 ++++ src/org/ice4j/socket/DelegatingSocket.java | 29 +- .../ice4j/socket/DelegatingSocketChannel.java | 404 +++++ src/org/ice4j/socket/HttpDemuxFilter.java | 267 ++++ src/org/ice4j/socket/IceTcpSocketWrapper.java | 2 +- .../ice4j/socket/MuxServerSocketChannel.java | 1323 +++++++++++++++++ .../ice4j/socket/PreReadSocketChannel.java | 97 ++ 9 files changed, 3030 insertions(+), 267 deletions(-) create mode 100644 src/org/ice4j/socket/DelegatingServerSocket.java create mode 100644 src/org/ice4j/socket/DelegatingServerSocketChannel.java create mode 100644 src/org/ice4j/socket/DelegatingSocketChannel.java create mode 100644 src/org/ice4j/socket/HttpDemuxFilter.java create mode 100644 src/org/ice4j/socket/MuxServerSocketChannel.java create mode 100644 src/org/ice4j/socket/PreReadSocketChannel.java diff --git a/src/org/ice4j/ice/harvest/MultiplexingTcpHostHarvester.java b/src/org/ice4j/ice/harvest/MultiplexingTcpHostHarvester.java index 1a00f3a..a304cab 100644 --- a/src/org/ice4j/ice/harvest/MultiplexingTcpHostHarvester.java +++ b/src/org/ice4j/ice/harvest/MultiplexingTcpHostHarvester.java @@ -32,6 +32,7 @@ import org.ice4j.socket.*; * to the appropriate Component. * * @author Boris Grozev + * @author Lyubomir Marinov */ public class MultiplexingTcpHostHarvester extends CandidateHarvester @@ -49,11 +50,14 @@ public class MultiplexingTcpHostHarvester private static final int PURGE_INTERVAL = 20; /** - * Channels which we have failed to read from after at least - * READ_TIMEOUT milliseconds will be considered failed and will - * be closed. + * Closes a {@code Channel} and swallows any {@link IOException}. + * + * @param channel the {@code Channel} to close */ - private static final int READ_TIMEOUT = 10000; + static void closeNoExceptions(Channel channel) + { + MuxServerSocketChannel.closeNoExceptions(channel); + } /** * Returns a list of all addresses on the interfaces in interfaces @@ -67,7 +71,6 @@ public class MultiplexingTcpHostHarvester int port, List interfaces) throws IOException - { List addresses = new LinkedList(); @@ -193,8 +196,8 @@ public class MultiplexingTcpHostHarvester throws IOException { this(port, - Collections.list(NetworkInterface.getNetworkInterfaces()), - ssltcp); + Collections.list(NetworkInterface.getNetworkInterfaces()), + ssltcp); } /** @@ -257,7 +260,6 @@ public class MultiplexingTcpHostHarvester boolean useIPv6 = !StackProperties.getBoolean( StackProperties.DISABLE_IPv6, false); - boolean useIPv6LinkLocal = !StackProperties.getBoolean( StackProperties.DISABLE_LINK_LOCAL_ADDRESSES, false); @@ -267,6 +269,7 @@ public class MultiplexingTcpHostHarvester = StackProperties.getStringArray(StackProperties.ALLOWED_ADDRESSES, ";"); InetAddress[] allowedAddresses = null; + if (allowedAddressesStr != null) { allowedAddresses = new InetAddress[allowedAddressesStr.length]; @@ -282,6 +285,7 @@ public class MultiplexingTcpHostHarvester = StackProperties.getStringArray(StackProperties.BLOCKED_ADDRESSES, ";"); InetAddress[] blockedAddresses = null; + if (blockedAddressesStr != null) { blockedAddresses = new InetAddress[blockedAddressesStr.length]; @@ -317,6 +321,7 @@ public class MultiplexingTcpHostHarvester if (allowedAddresses != null) { boolean found = false; + for (InetAddress allowedAddress : allowedAddresses) { if (allowedAddress.equals(address)) @@ -325,7 +330,6 @@ public class MultiplexingTcpHostHarvester break; } } - if (!found) { logger.info("Not using " + address +" for TCP candidates, " @@ -337,6 +341,7 @@ public class MultiplexingTcpHostHarvester if (blockedAddresses != null) { boolean found = false; + for (InetAddress blockedAddress : blockedAddresses) { if (blockedAddress.equals(address)) @@ -345,7 +350,6 @@ public class MultiplexingTcpHostHarvester break; } } - if (found) { logger.info("Not using " + address + " for TCP candidates, " @@ -601,11 +605,25 @@ public class MultiplexingTcpHostHarvester { for (TransportAddress transportAddress : localAddresses) { - ServerSocketChannel channel = ServerSocketChannel.open(); - ServerSocket socket = channel.socket(); - socket.bind( - new InetSocketAddress(transportAddress.getAddress(), - transportAddress.getPort())); + ServerSocketChannel channel + = MuxServerSocketChannel.openAndBind( + /* properties */ null, + new InetSocketAddress( + transportAddress.getAddress(), + transportAddress.getPort()), + /* backlog */ 0, + new DatagramPacketFilter() + { + /** + * {@inheritDoc} + */ + @Override + public boolean accept(DatagramPacket p) + { + return isFirstDatagramPacket(p); + } + }); + serverSocketChannels.add(channel); } @@ -616,6 +634,85 @@ public class MultiplexingTcpHostHarvester readThread.start(); } + /** + * Determines whether a specific {@link DatagramPacket} is the first + * expected (i.e. supported) to be received from an accepted + * {@link SocketChannel} by this {@code MultiplexingTcpHostHarvester}. If + * {@link #ssltcp} signals that Google TURN SSLTCP is to be expected, then + * {@code p} must be + * {@link GoogleTurnSSLCandidateHarvester#SSL_CLIENT_HANDSHAKE}. Otherwise, + * it must be a STUN Binding request packetized for TCP. + * + * @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 MultiplexingTcpHostHarvester}; + * otherwise, {@code false} + */ + private boolean isFirstDatagramPacket(DatagramPacket p) + { + int len = p.getLength(); + boolean b = false; + + if (len > 0) + { + byte[] buf = p.getData(); + int off = p.getOffset(); + + if (ssltcp) + { + // 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; + } + } + } + } + else + { + // 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; + } + /** * Removes entries from {@link #components} for which the * WeakReference has been cleared. @@ -663,7 +760,7 @@ public class MultiplexingTcpHostHarvester /** * Initializes a new AcceptThread. */ - private AcceptThread() + public AcceptThread() throws IOException { setName("MultiplexingTcpHostHarvester AcceptThread"); @@ -691,85 +788,91 @@ public class MultiplexingTcpHostHarvester @Override public void run() { - while (true) + do { - int readyChannels; if (close) { break; } - try + IOException exception = null; + List channelsToAdd + = new LinkedList(); + // Allow to go on, so we can quit if closed. + long selectTimeout = 3000; + + for (SelectionKey key : selector.keys()) { - // Allow to go on, so we can quit if closed - readyChannels = selector.select(3000); + if (key.isValid()) + { + SocketChannel channel; + boolean acceptable = key.isAcceptable(); + + try + { + channel + = ((ServerSocketChannel) key.channel()) + .accept(); + } + catch (IOException ioe) + { + exception = ioe; + break; + } + + // Add the accepted channel to newChannels to allow the + // 'read' thread to it up. + if (channel != null) + { + channelsToAdd.add(channel); + } + else if (acceptable) + { + // The SelectionKey reported the channel as + // acceptable but channel#accept() did not accept a + // non-null SocketChannel. Give the channel a little + // time to get its act together. + selectTimeout = 100; + } + } } - catch (IOException ioe) + // We accepted from all serverSocketChannels. + selector.selectedKeys().clear(); + + if (!channelsToAdd.isEmpty()) { - logger.info("Failed to select an accept-ready socket: " - + ioe); + synchronized (newChannels) + { + newChannels.addAll(channelsToAdd); + } + notifyReadThread(); + } + + if (exception != null) + { + logger.info( + "Failed to accept a socket, which should have been" + + " ready to accept: " + exception); break; } - if (readyChannels > 0) - { - IOException exception = null; - List channelsToAdd - = new LinkedList(); - - for (SelectionKey key : selector.selectedKeys()) - { - SocketChannel channel; - if (key.isAcceptable()) - { - try - { - channel = ((ServerSocketChannel) - key.channel()).accept(); - } - catch (IOException ioe) - { - exception = ioe; - break; - } - - // Add the accepted socket to newChannels, so - // the 'read' thread can pick it up. - channelsToAdd.add(channel); - } - } - selector.selectedKeys().clear(); - - if (!channelsToAdd.isEmpty()) - { - synchronized (newChannels) - { - newChannels.addAll(channelsToAdd); - } - notifyReadThread(); - } - - if (exception != null) - { - logger.info("Failed to accept a socket, which" - + "should have been ready to accept: " - + exception); - break; - } - } - } // while(true) - - //now clean up and exit - for (ServerSocketChannel serverSocketChannel : serverSocketChannels) - { try { - serverSocketChannel.close(); + // Allow to go on, so we can quit if closed. + selector.select(selectTimeout); } catch (IOException ioe) { + logger.info( + "Failed to select an accept-ready socket: " + ioe); + break; } } + while (true); + + //now clean up and exit + for (ServerSocketChannel serverSocketChannel : serverSocketChannels) + closeNoExceptions(serverSocketChannel); try { @@ -780,6 +883,48 @@ public class MultiplexingTcpHostHarvester } } + /** + * Contains a SocketChannel that ReadThread is reading + * from. + */ + private static class ChannelDesc + { + /** + * The actual SocketChannel. + */ + 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. + */ + ByteBuffer buffer = null; + + /** + * Whether or not the initial "pseudo" SSL handshake has been read. + */ + boolean sslHandshakeRead = false; + + /** + * The value of the RFC4571 "length" field read from the channel, or + * -1 if it hasn't been read (yet). + */ + int length = -1; + + /** + * Initializes a new ChannelDesc with the given channel. + * @param channel the channel. + */ + public ChannelDesc(SocketChannel channel) + { + this.channel = channel; + } + } + /** * An IceSocketWrapper implementation which allows a * DatagramPacket to be pushed back and received on the first call @@ -810,8 +955,8 @@ public class MultiplexingTcpHostHarvester * @param datagramPacket the DatagramPacket which will be used * on the first call to {@link #receive(java.net.DatagramPacket)} */ - private PushBackIceSocketWrapper(IceSocketWrapper wrappedWrapper, - DatagramPacket datagramPacket) + public PushBackIceSocketWrapper(IceSocketWrapper wrappedWrapper, + DatagramPacket datagramPacket) { this.wrapped = wrappedWrapper; this.datagramPacket = datagramPacket; @@ -910,19 +1055,12 @@ public class MultiplexingTcpHostHarvester private class ReadThread extends Thread { - /** - * Contains the SocketChanels that we are currently reading - * from. - */ - private final List channels - = new LinkedList(); - /** * Initializes a new ReadThread. * * @throws IOException if the selector to be used fails to open. */ - private ReadThread() + public ReadThread() throws IOException { setName("MultiplexingTcpHostHarvester ReadThread"); @@ -942,20 +1080,16 @@ public class MultiplexingTcpHostHarvester try { channel.configureBlocking(false); - channel.register(readSelector, SelectionKey.OP_READ); + channel.register( + readSelector, + SelectionKey.OP_READ, + new ChannelDesc(channel)); } catch (IOException ioe) { logger.info("Failed to register channel: " + ioe); - try - { - channel.close(); - } - catch (IOException ioe2) - {} + closeNoExceptions(channel); } - - channels.add(new ChannelDesc(channel)); } newChannels.clear(); } @@ -969,35 +1103,35 @@ public class MultiplexingTcpHostHarvester { long now = System.currentTimeMillis(); - for (Iterator i = channels.iterator(); - i.hasNext();) + for (SelectionKey key : readSelector.keys()) { - ChannelDesc channelDesc = i.next(); + // 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; - if (channelDesc.lastActive != -1 - && now - channelDesc.lastActive > READ_TIMEOUT) + ChannelDesc channelDesc = (ChannelDesc) key.attachment(); + + if (channelDesc == null) + continue; + + long lastActive = channelDesc.lastActive; + + if (lastActive != -1 + && now - lastActive + > MuxServerSocketChannel + .SOCKET_CHANNEL_READ_TIMEOUT) { - i.remove(); - logger.info("Read timeout for socket: " - + channelDesc.channel.socket()); + // De-register from the Selector. + key.cancel(); - // De-register from the selector - for (SelectionKey key : readSelector.keys()) - { - if (key.channel().equals(channelDesc.channel)) - { - key.cancel(); - } - } + SocketChannel channel = channelDesc.channel; - try - { - channelDesc.channel.close(); - } - catch (IOException ioe) - { - logger.info("Failed to close channel: " + ioe); - } + logger.info("Read timeout for socket: " + channel.socket()); + + closeNoExceptions(channel); } } } @@ -1029,6 +1163,7 @@ public class MultiplexingTcpHostHarvester { TransportAddress transportAddress = candidate.getTransportAddress(); + if (candidate instanceof TcpHostCandidate && Transport.TCP.equals(transportAddress.getTransport()) && localPort == transportAddress.getPort() @@ -1040,25 +1175,6 @@ public class MultiplexingTcpHostHarvester return null; } - /** - * Finds the ChannelDesc in {@link #channels} whose - * channel is channel. - * - * @param channel the channel to search for. - * @return the ChannelDesc in {@link #channels} whose - * channel is channel - */ - private ChannelDesc findChannelDesc(SelectableChannel channel) - { - for (ChannelDesc channelDesc : channels) - { - if (channelDesc.channel.equals(channel)) - return channelDesc; - } - - return null; - } - /** * Makes socket available to component and pushes back * datagramPacket into the STUN socket. @@ -1073,17 +1189,18 @@ public class MultiplexingTcpHostHarvester { IceProcessingState state = component.getParentStream().getParentAgent().getState(); + if (!IceProcessingState.WAITING.equals(state) && !IceProcessingState.RUNNING.equals(state)) { - logger.info("Not adding a socket to an ICE agent with state " - + state); + logger.info( + "Not adding a socket to an ICE agent with state " + + state); return; } // Socket to add to the candidate IceSocketWrapper candidateSocket = null; - // STUN-only filtered socket to add to the StunStack IceSocketWrapper stunSocket = null; @@ -1124,7 +1241,6 @@ public class MultiplexingTcpHostHarvester catch (IOException ioe) {} } - } /** @@ -1152,8 +1268,7 @@ public class MultiplexingTcpHostHarvester * channel, which is to be canceled in case no further * reading is required from the channel. */ - private void readFromChannel(ChannelDesc channel, - SelectionKey key) + private void readFromChannel(ChannelDesc channel, SelectionKey key) { if (channel.buffer == null) { @@ -1162,8 +1277,8 @@ public class MultiplexingTcpHostHarvester if (ssltcp && !channel.sslHandshakeRead) { channel.buffer - = ByteBuffer.allocate( - GoogleTurnSSLCandidateHarvester + = ByteBuffer.allocate( + GoogleTurnSSLCandidateHarvester .SSL_CLIENT_HANDSHAKE.length); } else if (channel.length == -1) @@ -1178,10 +1293,12 @@ public class MultiplexingTcpHostHarvester try { - if (channel.channel.read(channel.buffer) == -1) - { - throw new IOException("Socket closed."); - } + int read = channel.channel.read(channel.buffer); + + if (read == -1) + throw new IOException("End of stream!"); + else if (read > 0) + channel.lastActive = System.currentTimeMillis(); if (!channel.buffer.hasRemaining()) { @@ -1189,7 +1306,7 @@ public class MultiplexingTcpHostHarvester if (ssltcp && !channel.sslHandshakeRead) { byte[] bytesRead - = new byte[GoogleTurnSSLCandidateHarvester + = new byte[GoogleTurnSSLCandidateHarvester .SSL_CLIENT_HANDSHAKE.length]; channel.buffer.flip(); @@ -1214,11 +1331,11 @@ public class MultiplexingTcpHostHarvester throw new IOException("Expected a pseudo ssl" + " handshake, but received something else."); } - } else if (channel.length == -1) { channel.buffer.flip(); + int fb = channel.buffer.get(); int sb = channel.buffer.get(); @@ -1231,6 +1348,7 @@ public class MultiplexingTcpHostHarvester else { byte[] bytesRead = new byte[channel.length]; + channel.buffer.flip(); channel.buffer.get(bytesRead); @@ -1248,16 +1366,20 @@ public class MultiplexingTcpHostHarvester } UsernameAttribute usernameAttribute - = (UsernameAttribute) + = (UsernameAttribute) stunMessage.getAttribute(Attribute.USERNAME); + if (usernameAttribute == null) + { throw new IOException( "No USERNAME attribute present."); + } String usernameString - = new String(usernameAttribute.getUsername()); + = new String(usernameAttribute.getUsername()); String localUfrag = usernameString.split(":")[0]; Component component = getComponent(localUfrag); + if (component == null) throw new IOException("No component found."); @@ -1271,44 +1393,31 @@ public class MultiplexingTcpHostHarvester // Construct a DatagramPacket from the just-read packet // which is to be pushed back DatagramPacket p - = new DatagramPacket(bytesRead, - bytesRead.length); + = new DatagramPacket(bytesRead, bytesRead.length); Socket socket = channel.channel.socket(); + p.setAddress(socket.getInetAddress()); p.setPort(socket.getPort()); handSocketToComponent(socket, component, p); - - // Successfully accepted, we don't need it anymore. - channels.remove(channel); } } } catch (IOException ioe) { - logger.info("Failed to handle TCP socket " - + channel.channel.socket() + ": " + ioe); - channels.remove(channel); + logger.info( + "Failed to handle TCP socket " + + channel.channel.socket() + ": " + ioe); key.cancel(); - try - { - channel.channel.close(); - } - catch (IOException ioe2) - {} + closeNoExceptions(channel.channel); } catch (StunException se) { - logger.info("Failed to handle TCP socket " - + channel.channel.socket() + ": " + se); - channels.remove(channel); + logger.info( + "Failed to handle TCP socket " + + channel.channel.socket() + ": " + se); key.cancel(); - try - { - channel.channel.close(); - } - catch (IOException ioe) - {} + closeNoExceptions(channel.channel); } } @@ -1318,11 +1427,7 @@ public class MultiplexingTcpHostHarvester @Override public void run() { - Set selectedKeys; - int readyChannels = 0; - SelectableChannel selectedChannel; - - while (true) + do { synchronized (MultiplexingTcpHostHarvester.this) { @@ -1335,63 +1440,57 @@ public class MultiplexingTcpHostHarvester checkForNewChannels(); + for (SelectionKey key : readSelector.keys()) + { + if (key.isValid()) + { + ChannelDesc channelDesc + = (ChannelDesc) key.attachment(); + + readFromChannel(channelDesc, key); + } + } + // We read from all SocketChannels. + readSelector.selectedKeys().clear(); + try { - readyChannels = readSelector.select(READ_TIMEOUT / 2); + readSelector.select( + MuxServerSocketChannel.SOCKET_CHANNEL_READ_TIMEOUT + / 2); } catch (IOException ioe) { logger.info("Failed to select a read-ready channel."); } - - if (readyChannels > 0) - { - selectedKeys = readSelector.selectedKeys(); - for (SelectionKey key : selectedKeys) - { - if (key.isReadable()) - { - selectedChannel = key.channel(); - - ChannelDesc channelDesc - = findChannelDesc(selectedChannel); - channelDesc.lastActive = System.currentTimeMillis(); - - readFromChannel(channelDesc, key); - } - } - selectedKeys.clear(); - } - } //while(true) + } + while (true); //we are all done, clean up. synchronized (newChannels) { for (SocketChannel channel : newChannels) { - try - { - channel.close(); - } - catch (IOException ioe) - {} + closeNoExceptions(channel); } newChannels.clear(); } - for (ChannelDesc channelDesc : channels) + for (SelectionKey key : readSelector.keys()) { - try - { - channelDesc.channel.close(); - } - catch (IOException ioe) + // 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()) { + Channel channel = key.channel(); + + if (channel.isOpen()) + closeNoExceptions(channel); } } - channels.clear(); - try { readSelector.close(); @@ -1399,47 +1498,5 @@ public class MultiplexingTcpHostHarvester catch (IOException ioe) {} } - - /** - * Contains a SocketChannel that ReadThread is - * reading from. - */ - private class ChannelDesc - { - /** - * The actual SocketChannel. - */ - private final SocketChannel channel; - - /** - * The time the channel was last found to be active. - */ - private long lastActive = System.currentTimeMillis(); - - /** - * The buffer which stores the data so far read from the channel. - */ - ByteBuffer buffer = null; - - /** - * Whether or not the initial "pseudo" SSL handshake has been read. - */ - boolean sslHandshakeRead = false; - - /** - * The value of the RFC4571 "length" field read from the channel, or - * -1 if it hasn't (yet) been read. - */ - int length = -1; - - /** - * Initializes a new ChannelDesc with the given channel. - * @param channel the channel. - */ - private ChannelDesc(SocketChannel channel) - { - this.channel = channel; - } - } } } diff --git a/src/org/ice4j/socket/DelegatingServerSocket.java b/src/org/ice4j/socket/DelegatingServerSocket.java new file mode 100644 index 0000000..2146051 --- /dev/null +++ b/src/org/ice4j/socket/DelegatingServerSocket.java @@ -0,0 +1,279 @@ +/* + * ice4j, the OpenSource Java Solution for NAT and Firewall Traversal. + * Maintained by the SIP Communicator community (http://sip-communicator.org). + * + * Distributable under LGPL license. See terms of license at gnu.org. + */ +package org.ice4j.socket; + +import java.io.*; +import java.net.*; +import java.nio.channels.*; + +/** + * Implements a {@code ServerSocket} which delegates (its method calls) to + * another {@code ServerSocket}. In other words, the former wraps the latter. + * + * @author Lyubomir Marinov + */ +public class DelegatingServerSocket + extends ServerSocket +{ + /** + * The {@link ServerSocketChannel} of this instance. If {@code null}, the + * one of the {@link #delegate} is used. + */ + protected final ServerSocketChannel channel; + + /** + * The {@link ServerSocket} this instance delegates (its method calls) to. + */ + protected final ServerSocket delegate; + + /** + * Initializes a new {@code DelegatingServerSocket} instance which is to + * delegate (its method calls) to a specific {@link ServerSocket}. + * + * @param delegate the {@code ServerSocket} the new instance is to delegate + * (it method calls) to + * @throws IOException + */ + public DelegatingServerSocket(ServerSocket delegate) + throws IOException + { + this(delegate, delegate.getChannel()); + } + + /** + * Initializes a new {@code DelegatingServerSocket} instance which is to + * delegate (its method calls) to a specific {@link ServerSocket} and is to + * report a specific {@link ServerSocketChannel}. + * + * @param delegate the {@code ServerSocket} the new instance is to delegate + * (it method calls) to + * @param channel the {@code ServerSocketChannel} to be reported by the new + * instance or {@code null} to report the one of {@code delegate} + * @throws IOException + */ + public DelegatingServerSocket( + ServerSocket delegate, + ServerSocketChannel channel) + throws IOException + { + this.delegate = delegate; + this.channel = channel; + } + + /** + * {@inheritDoc} + * + * Forwards to {@link #delegate}. + */ + @Override + public Socket accept() + throws IOException + { + return delegate.accept(); + } + + /** + * {@inheritDoc} + * + * Forwards to {@link #delegate}. + */ + @Override + public void bind(SocketAddress endpoint) + throws IOException + { + delegate.bind(endpoint); + } + + /** + * {@inheritDoc} + * + * Forwards to {@link #delegate}. + */ + @Override + public void bind(SocketAddress endpoint, int backlog) + throws IOException + { + delegate.bind(endpoint, backlog); + } + + /** + * {@inheritDoc} + * + * Forwards to {@link #delegate}. + */ + @Override + public void close() + throws IOException + { + delegate.close(); + } + + /** + * {@inheritDoc} + * + * If {@link #channel} is not {@code null}, returns it. Otherwise, forwards + * to {@link #delegate}. + */ + @Override + public ServerSocketChannel getChannel() + { + ServerSocketChannel channel = this.channel; + + return (channel == null) ? delegate.getChannel() : channel; + } + + /** + * {@inheritDoc} + * + * Forwards to {@link #delegate}. + */ + @Override + public InetAddress getInetAddress() + { + return delegate.getInetAddress(); + } + + /** + * {@inheritDoc} + * + * Forwards to {@link #delegate}. + */ + @Override + public int getLocalPort() + { + return delegate.getLocalPort(); + } + + /** + * {@inheritDoc} + * + * Forwards to {@link #delegate}. + */ + @Override + public SocketAddress getLocalSocketAddress() + { + return delegate.getLocalSocketAddress(); + } + + /** + * {@inheritDoc} + * + * Forwards to {@link #delegate}. + */ + @Override + public int getReceiveBufferSize() + throws SocketException + { + return delegate.getReceiveBufferSize(); + } + + /** + * {@inheritDoc} + * + * Forwards to {@link #delegate}. + */ + @Override + public boolean getReuseAddress() + throws SocketException + { + return delegate.getReuseAddress(); + } + + /** + * {@inheritDoc} + * + * Forwards to {@link #delegate}. + */ + @Override + public int getSoTimeout() + throws IOException + { + return delegate.getSoTimeout(); + } + + /** + * {@inheritDoc} + * + * Forwards to {@link #delegate}. + */ + @Override + public boolean isBound() + { + return delegate.isBound(); + } + + /** + * {@inheritDoc} + * + * Forwards to {@link #delegate}. + */ + @Override + public boolean isClosed() + { + return delegate.isClosed(); + } + + /** + * {@inheritDoc} + * + * Forwards to {@link #delegate}. + */ + @Override + public void setPerformancePreferences(int connectionTime, + int latency, + int bandwidth) + { + delegate.setPerformancePreferences(connectionTime, latency, bandwidth); + } + + /** + * {@inheritDoc} + * + * Forwards to {@link #delegate}. + */ + @Override + public void setReceiveBufferSize(int size) + throws SocketException + { + delegate.setReceiveBufferSize(size); + } + + /** + * {@inheritDoc} + * + * Forwards to {@link #delegate}. + */ + @Override + public void setReuseAddress(boolean on) + throws SocketException + { + delegate.setReuseAddress(on); + } + + /** + * {@inheritDoc} + * + * Forwards to {@link #delegate}. + */ + @Override + public void setSoTimeout(int timeout) + throws SocketException + { + delegate.setSoTimeout(timeout); + } + + /** + * {@inheritDoc} + * + * Forwards to {@link #delegate}. + */ + @Override + public String toString() + { + return delegate.toString(); + } +} diff --git a/src/org/ice4j/socket/DelegatingServerSocketChannel.java b/src/org/ice4j/socket/DelegatingServerSocketChannel.java new file mode 100644 index 0000000..80bd498 --- /dev/null +++ b/src/org/ice4j/socket/DelegatingServerSocketChannel.java @@ -0,0 +1,321 @@ +/* + * ice4j, the OpenSource Java Solution for NAT and Firewall Traversal. + * Maintained by the SIP Communicator community (http://sip-communicator.org). + * + * Distributable under LGPL license. See terms of license at gnu.org. + */ +package org.ice4j.socket; + +import java.io.*; +import java.net.*; +import java.nio.channels.*; +import java.util.*; + +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 + */ +public class DelegatingServerSocketChannel + extends ServerSocketChannel + implements SelChImpl +{ + /** + * The {@link ServerSocketChannel} this instance delegates (its method + * calls) to. + */ + protected final T delegate; + + /** + * The view of {@link #delegate} as a SelChImpl interface instance + * required by {@link Selector} and related functionality. + */ + protected final SelChImpl delegateAsSelChImpl; + + /** + * The {@code ServerSocket} to be reported by this instance. + */ + private ServerSocket socket; + + /** + * The Object which synchronizes the access to {@link #socket}. + */ + private final Object socketSyncRoot = new Object(); + + /** + * 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.provider()); + + this.delegate = delegate; + + delegateAsSelChImpl + = (delegate instanceof SelChImpl) ? (SelChImpl) delegate : null; + } + + /** + * {@inheritDoc} + * + * Forwards to {@link #delegate}. + */ + @Override + public SocketChannel accept() + throws IOException + { + SocketChannel channel = delegate.accept(); + + return (channel == null) ? null : implAccept(channel); + } + + /** + * {@inheritDoc} + * + * Forwards to {@link #delegate} and returns {@code this}. + */ + @Override + public ServerSocketChannel bind(SocketAddress local, int backlog) + throws IOException + { + delegate.bind(local, backlog); + return this; + } + + /** + * {@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 SocketAddress getLocalAddress() + throws IOException + { + return delegate.getLocalAddress(); + } + + /** + * {@inheritDoc} + * + * Forwards to {@link #delegate}. + */ + @Override + public U getOption(SocketOption name) + throws IOException + { + return delegate.getOption(name); + } + + /** + * Allows extenders to optionally configure (e.g. wrap) a + * SocketChannel which has been accepted by {@link #delegate} and + * before it is returned by {@link #accept()}. + * + * @param accepted the SocketChannel accepted by delegate + * @return the SocketChannel to be returned by {@link #accept()} + * (in place of accepted) + * @throws IOException if an I/O error occurs + */ + protected SocketChannel implAccept(SocketChannel accepted) + throws IOException + { + return accepted; + } + + /** + * {@inheritDoc} + * + * Forwards to {@link #delegate}. + */ + @Override + protected void implCloseSelectableChannel() + throws IOException + { + delegate.close(); + } + + /** + * {@inheritDoc} + * + * Forwards to {@link #delegate}. + */ + @Override + protected void implConfigureBlocking(boolean block) + throws IOException + { + delegate.configureBlocking(block); + } + + /** + * Allows extenders to optionally configure (e.g. wrap) the + * {@code ServerSocket} of {@link #delegate} and before it is returned by + * {@link #socket()}. + * + * @param socket the {@code ServerSocket} of {@code delegate} + * @return the {@code ServerSocket} to be returned by {@link #socket()} (in + * place of {@code socket}) + * @throws IOException if an I/O error occurs + */ + protected ServerSocket implSocket(ServerSocket socket) + throws IOException + { + return new DelegatingServerSocket(socket, this); + } + + /** + * Determines whether this {@code DelegatingServerSocketChannel} is bound. + * + * @return {@code true} if this instancei bound; otherwise, {@code false} + */ + public boolean isBound() + { + try + { + return getLocalAddress() != null; + } + catch (IOException ioe) + { + return false; + } + } + + /** + * {@inheritDoc} + * + * Forwards to {@link #delegate}. + */ + @Override + public void kill() + throws IOException + { + delegateAsSelChImpl.kill(); + } + + /** + * {@inheritDoc} + * + * Forwards to {@link #delegate} and returns {@code this}. + */ + @Override + public ServerSocketChannel setOption(SocketOption name, U value) + throws IOException + { + delegate.setOption(name, value); + return this; + } + + /** + * {@inheritDoc} + * + * Allows wrapping the {@code socket} of {@link #delegate}. + */ + @Override + public ServerSocket socket() + { + ServerSocket socket = delegate.socket(); + + synchronized (socketSyncRoot) + { + if (this.socket == null) + { + if (socket != null) + { + try + { + this.socket = implSocket(socket); + } + catch (IOException ioe) + { + throw new RuntimeException(ioe); + } + } + } + else if (socket == null) + { + this.socket = null; + } + else + { + // TODO For the sake of completeness, maybe check that the + // value of this.socket still delegates to the latest value of + // socket. However, the value of socket is very likely final so + // do not bother with it at the time of this writing. + } + return this.socket; + } + } + + /** + * {@inheritDoc} + * + * Forwards to {@link #delegate}. + */ + @Override + public Set> supportedOptions() + { + return delegate.supportedOptions(); + } + + /** + * {@inheritDoc} + * + * Forwards to {@link #delegate}. + */ + @Override + public void translateAndSetInterestOps(int ops, SelectionKeyImpl sk) + { + delegateAsSelChImpl.translateAndSetInterestOps(ops, sk); + } + + /** + * {@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/org/ice4j/socket/DelegatingSocket.java b/src/org/ice4j/socket/DelegatingSocket.java index df3a74f..8cea650 100644 --- a/src/org/ice4j/socket/DelegatingSocket.java +++ b/src/org/ice4j/socket/DelegatingSocket.java @@ -208,10 +208,25 @@ public class DelegatingSocket this.delegate = delegate; this.channel = channel; - delegateAsDelegatingSocket - = (delegate instanceof DelegatingSocket) - ? (DelegatingSocket) delegate - : null; + if (delegate instanceof DelegatingSocket) + { + // FIXME DelegatingSocketChannel was in need of a Socket which wraps + // another Socket and reports a specific SocketChannel. Since + // DelegatingSocket does that, DelegatingSocketChannel used it. + // Unfortunately, it turned out after much debugging that + // DelegatingSocket has the additional function of flagging where + // UDP packets sent over TCP are to be framed. As a temporary fix, + // do not treat the sockets of DelegatingSocketChannel as + // DelegatingSockets. + if (channel instanceof DelegatingSocketChannel) + delegateAsDelegatingSocket = null; + else + delegateAsDelegatingSocket = (DelegatingSocket) delegate; + } + else + { + delegateAsDelegatingSocket = null; + } } /** @@ -708,11 +723,11 @@ public class DelegatingSocket // Else, sends the packet to the final socket (outputStream). outputStream.write(p.getData(), p.getOffset(), p.getLength()); - InetSocketAddress localAddress - = (InetSocketAddress) super.getLocalSocketAddress(); - if (DelegatingDatagramSocket.logNonStun(++nbSentPackets)) { + InetSocketAddress localAddress + = (InetSocketAddress) super.getLocalSocketAddress(); + StunStack.logPacketToPcap( p, true, diff --git a/src/org/ice4j/socket/DelegatingSocketChannel.java b/src/org/ice4j/socket/DelegatingSocketChannel.java new file mode 100644 index 0000000..b50bb8b --- /dev/null +++ b/src/org/ice4j/socket/DelegatingSocketChannel.java @@ -0,0 +1,404 @@ +/* + * ice4j, the OpenSource Java Solution for NAT and Firewall Traversal. + * Maintained by the SIP Communicator community (http://sip-communicator.org). + * + * Distributable under LGPL license. See terms of license at gnu.org. + */ +package org.ice4j.socket; + +import java.io.*; +import java.net.*; +import java.nio.*; +import java.nio.channels.*; +import java.util.*; + +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 + */ +public class DelegatingSocketChannel + extends SocketChannel + implements SelChImpl +{ + /** + * The {@link SocketChannel} this instance delegates (its method calls) to. + */ + protected final T delegate; + + /** + * The view of {@link #delegate} as a SelChImpl interface instance + * required by {@link Selector} and related functionality. + */ + protected final SelChImpl delegateAsSelChImpl; + + /** + * The {@code Socket} to be reported by this instance. + */ + private Socket socket; + + /** + * The Object which synchronizes the access to {@link #socket}. + */ + private final Object socketSyncRoot = new Object(); + + /** + * 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.provider()); + + this.delegate = delegate; + + delegateAsSelChImpl + = (delegate instanceof SelChImpl) ? (SelChImpl) delegate : null; + } + + /** + * {@inheritDoc} + * + * Forwards to {@link #delegate} and returns {@code this}. + */ + @Override + public SocketChannel bind(SocketAddress local) + throws IOException + { + delegate.bind(local); + return this; + } + + /** + * {@inheritDoc} + * + * Forwards to {@link #delegate}. + */ + @Override + public boolean connect(SocketAddress remote) + throws IOException + { + return delegate.connect(remote); + } + + /** + * {@inheritDoc} + * + * Forwards to {@link #delegate}. + */ + @Override + public boolean finishConnect() + throws IOException + { + return delegate.finishConnect(); + } + + /** + * {@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 SocketAddress getLocalAddress() + throws IOException + { + return delegate.getLocalAddress(); + } + + /** + * {@inheritDoc} + * + * Forwards to {@link #delegate}. + */ + @Override + public U getOption(SocketOption name) + throws IOException + { + return delegate.getOption(name); + } + + /** + * {@inheritDoc} + * + * Forwards to {@link #delegate}. + */ + @Override + public SocketAddress getRemoteAddress() + throws IOException + { + return delegate.getRemoteAddress(); + } + + /** + * {@inheritDoc} + * + * Forwards to {@link #delegate}. + */ + @Override + protected void implCloseSelectableChannel() + throws IOException + { + delegate.close(); + } + + /** + * {@inheritDoc} + * + * Forwards to {@link #delegate}. + */ + @Override + protected void implConfigureBlocking(boolean block) + throws IOException + { + delegate.configureBlocking(block); + } + + /** + * Allows extenders to optionally configure (e.g. wrap) the {@code Socket} + * of {@link #delegate} and before it is returned by {@link #socket()}. + * + * @param socket the {@code Socket} of {@code delegate} + * @return the {@code Socket} to be returned by {@link #socket()} (in place + * of {@code socket}) + * @throws IOException if an I/O error occurs + */ + protected Socket implSocket(Socket socket) + throws IOException + { + return new DelegatingSocket(socket, this); + } + + /** + * {@inheritDoc} + * + * Forwards to {@link #delegate}. + */ + @Override + public boolean isConnected() + { + return delegate.isConnected(); + } + + /** + * {@inheritDoc} + * + * Forwards to {@link #delegate}. + */ + @Override + public boolean isConnectionPending() + { + return delegate.isConnectionPending(); + } + + /** + * {@inheritDoc} + * + * Forwards to {@link #delegate}. + */ + @Override + public void kill() + throws IOException + { + delegateAsSelChImpl.kill(); + } + + /** + * {@inheritDoc} + * + * Forwards to {@link #delegate}. + */ + @Override + public int read(ByteBuffer dst) + throws IOException + { + return delegate.read(dst); + } + + /** + * {@inheritDoc} + * + * Forwards to {@link #delegate}. + */ + @Override + public long read(ByteBuffer[] dsts, int offset, int length) + throws IOException + { + return delegate.read(dsts, offset, length); + } + + /** + * {@inheritDoc} + * + * Forwards to {@link #delegate} and returns {@code this}. + */ + @Override + public SocketChannel setOption(SocketOption name, U value) + throws IOException + { + delegate.setOption(name, value); + return this; + } + + /** + * {@inheritDoc} + * + * Forwards to {@link #delegate} and returns {@code this}. + */ + @Override + public SocketChannel shutdownInput() + throws IOException + { + delegate.shutdownInput(); + return this; + } + + /** + * {@inheritDoc} + * + * Forwards to {@link #delegate} and returns {@code this}. + */ + @Override + public SocketChannel shutdownOutput() + throws IOException + { + delegate.shutdownOutput(); + return this; + } + + /** + * {@inheritDoc} + * + * Allows wrapping the {@code socket} of {@link #delegate}. + */ + @Override + public Socket socket() + { + Socket socket = delegate.socket(); + + synchronized (socketSyncRoot) + { + if (this.socket == null) + { + if (socket != null) + { + try + { + this.socket = implSocket(socket); + } + catch (IOException ioe) + { + throw new RuntimeException(ioe); + } + } + } + else if (socket == null) + { + this.socket = null; + } + else + { + // TODO For the sake of completeness, maybe check that the + // value of this.socket still delegates to the latest value of + // socket. However, the value of socket is very likely final so + // do not bother with it at the time of this writing. + } + return this.socket; + } + } + + /** + * {@inheritDoc} + * + * Forwards to {@link #delegate}. + */ + @Override + public Set> supportedOptions() + { + return delegate.supportedOptions(); + } + + /** + * {@inheritDoc} + * + * Forwards to {@link #delegate}. + */ + @Override + public void translateAndSetInterestOps(int ops, SelectionKeyImpl sk) + { + delegateAsSelChImpl.translateAndSetInterestOps(ops, sk); + } + + /** + * {@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); + } + + /** + * {@inheritDoc} + * + * Forwards to {@link #delegate}. + */ + @Override + public int write(ByteBuffer src) + throws IOException + { + return delegate.write(src); + } + + /** + * {@inheritDoc} + * + * Forwards to {@link #delegate}. + */ + @Override + public long write(ByteBuffer[] srcs, int offset, int length) + throws IOException + { + return delegate.write(srcs, offset, length); + } +} diff --git a/src/org/ice4j/socket/HttpDemuxFilter.java b/src/org/ice4j/socket/HttpDemuxFilter.java new file mode 100644 index 0000000..14560cc --- /dev/null +++ b/src/org/ice4j/socket/HttpDemuxFilter.java @@ -0,0 +1,267 @@ +/* + * Jitsi Videobridge, OpenSource video conferencing. + * + * Distributable under LGPL license. + * See terms of license at gnu.org. + */ +package org.ice4j.socket; + +import java.net.*; +import java.nio.charset.*; + +import org.ice4j.ice.harvest.*; + +/** + * Implements a {@link DatagramPacketFilter} which allows demultiplexing HTTP(S) + * out of {@link MuxServerSocketChannel}. Accepts HTTP, SSL v2, and TLS. Rejects + * Google TURN SSLTCP. + * + * @author Lyubomir Marinov + */ +public class HttpDemuxFilter + implements DatagramPacketFilter +{ + /** + * The US-ASCII {@code byte}s of {@link #REQUEST_METHOD_STRINGS}. Explicitly + * defined for the purposes of performance. + */ + private static byte[][] REQUEST_METHOD_BYTES; + + /** + * The maximum US-ASCII character with which an element of + * {@link #REQUEST_METHOD_STRINGS} starts. + */ + private static final char REQUEST_METHOD_MAX_CHAR; + + /** + * The maximum length in {@code byte}s of a US-ASCII representation of an + * HTTP request method supported by the class {@code HttpDemuxFilter}. + */ + public static final int REQUEST_METHOD_MAX_LENGTH; + + /** + * The minimum US-ASCII character with which an element of + * {@link #REQUEST_METHOD_STRINGS} starts. + */ + private static final char REQUEST_METHOD_MIN_CHAR; + + /** + * The HTTP request methods recognized by the class {@code HttpDemuxFilter}. + */ + private static String[] REQUEST_METHOD_STRINGS + = { + "CONNECT", + "DELETE", + "GET", + "HEAD", + "MOVE", + "OPTIONS", + "POST", + "PRI", + "PROXY", + "PUT", + "TRACE" + }; + + /** + * The minimum number of bytes required by the class {@code HttpDemuxFilter} + * in order to declare that (the data of) a specific {@link DatagramPacket} + * represents TLS. + */ + public static final int TLS_MIN_LENGTH = 11; + + static + { + // Gather statistics about the supported HTTP request methods in order + // to speed up the analysis of DatagramPackets later on. + char maxChar = 'A'; + int maxLength = Integer.MAX_VALUE; + char minChar = 'Z'; + Charset ascii = Charset.forName("US-ASCII"); + + REQUEST_METHOD_BYTES = new byte[REQUEST_METHOD_STRINGS.length][]; + for (int i = 0; i < REQUEST_METHOD_STRINGS.length; i++) + { + String s = REQUEST_METHOD_STRINGS[i]; + + if (s != null && s.length() != 0) + { + char ch = s.charAt(0); + byte[] bytes = s.getBytes(ascii); + int length = bytes.length; + + if (maxChar < ch) + maxChar = ch; + if (maxLength < length) + maxLength = length; + if (minChar > ch) + minChar = ch; + + REQUEST_METHOD_BYTES[i] = bytes; + } + else + { + REQUEST_METHOD_BYTES[i] = new byte[0]; + } + } + REQUEST_METHOD_MAX_CHAR = maxChar; + REQUEST_METHOD_MAX_LENGTH = maxLength; + REQUEST_METHOD_MIN_CHAR = minChar; + } + + /** + * Determines whether a specific {@link DatagramPacket} looks like the + * beginning of HTTP(S) client communication. Accepts HTTP, SSL v2, and + * TLS. Rejects Google TURN SSLTCP. + * + * @param p the {@code DatagramPacket} to analyze + * @return {@code true} if {@code p} looks like the beginning of HTTP(S) + * client communication; otherwise, {@code false} + */ + @Override + public boolean accept(DatagramPacket p) + { + int len = p.getLength(); + boolean accept = false; + + if (len > 0) + { + byte[] buf = p.getData(); + int off = p.getOffset(); + // The first bytes of HTTP, SSL v2, and TCP are different so quickly + // determine which one of the three is possible and, respectively, + // which two of the three are impossible. + int b0 = 0xFF & buf[off]; + boolean http, sslv2, tls; + + if (b0 == 22 /* TLS handshake */) + { + http = false; + sslv2 = false; + tls = true; + } + else if (b0 > 0x80 /* SSL v2 client hello */) + { + http = false; + sslv2 = true; + tls = false; + } + else + { + http = true; + sslv2 = false; + tls = false; + } + + // HTTP + if (http) + { + // Request-Line = Method SP Request-URI SP HTTP-Version CRLF + // HTTP-Version = "HTTP" "/" 1*DIGIT "." 1*DIGIT + if (b0 >= REQUEST_METHOD_MIN_CHAR + && b0 <= REQUEST_METHOD_MAX_CHAR + && len >= REQUEST_METHOD_MAX_LENGTH + 1 /* SP */) + { + // Match a supported HTTP request method. + for (byte[] bytes : REQUEST_METHOD_BYTES) + { + int length = bytes.length; + + if (buf[off + length] == ' ' /* SP */) + { + boolean equals = true; + + for (int i = 1, j = off + 1; i < length; i++, j++) + { + if (bytes[i] != buf[j]) + { + equals = false; + break; + } + } + if (equals) + { + accept = true; + break; + } + } + } + } + // Only one of HTTP, SSL v2, and TCP was deemed possible by + // looking at the first byte. If p didn't look like HTTP here, + // then it will not look like SSL v2 or TLS. + return accept; + } + + // HTTPS + if (tls) + { + // 1 byte ContentType type = handshake(22) + // 2 bytes ProtocolVersion version = { major(3) , minor<1..3> } + // 2 bytes uint16 length + // 1 byte HandshakeType msg_type = client_hello(1) + // 3 bytes uint24 length + // 2 bytes ProtocolVersion client_version + if (len >= TLS_MIN_LENGTH + && /* major */ (0xFF & buf[off + 1]) == 3) + { + int minor = 0xFF & buf[off + 2]; + + if (1 <= minor + && minor <= 3 + && /* msg_type */ (0xFF & buf[off + 5]) + == /* client_hello */ 1 + && /* major */ (0xFF & buf[off + 9]) == 3) + { + minor = 0xFF & buf[off + 10]; + if (1 <= minor && minor <= 3) + accept = true; + } + } + // Only one of HTTP, SSL v2, and TCP was deemed possible by + // looking at the first byte. If p didn't look like TLS here, + // then it will not look like HTTP or SSL v2. + return accept; + } + if (sslv2) + { + final byte[] googleTurnSslTcp + = GoogleTurnSSLCandidateHarvester.SSL_CLIENT_HANDSHAKE; + + // 2 bytes uint15 length + // 1 byte uint8 msg_type = 1 + // 2 bytes Version version + if (len > 5 + && len >= googleTurnSslTcp.length + && /* msg_type */ (0xFF & buf[off + 2]) == 1 + && /* major */ (0xFF & buf[off + 3]) == 3) + { + int minor = 0xFF & buf[off + 4]; + + if (1 <= minor && minor <= 3) + { + // Reject Google TURN SSLTCP. + boolean equals = true; + + for (int i = 0, iEnd = googleTurnSslTcp.length, j = off; + i < iEnd; + i++, j++) + { + if (googleTurnSslTcp[i] != buf[j]) + { + equals = false; + break; + } + } + accept = !equals; + } + } + // Only one of HTTP, SSL v2, and TCP was deemed possible by + // looking at the first byte. If p didn't look like SSL v2 here, + // then it will not look like HTTP or TLS. + return accept; + } + } + return accept; + } +} diff --git a/src/org/ice4j/socket/IceTcpSocketWrapper.java b/src/org/ice4j/socket/IceTcpSocketWrapper.java index 4463a0c..18772f7 100644 --- a/src/org/ice4j/socket/IceTcpSocketWrapper.java +++ b/src/org/ice4j/socket/IceTcpSocketWrapper.java @@ -50,7 +50,7 @@ public class IceTcpSocketWrapper { socket = delegate; - if(delegate instanceof DelegatingSocket) + if (delegate instanceof DelegatingSocket) { inputStream = null; outputStream = null; diff --git a/src/org/ice4j/socket/MuxServerSocketChannel.java b/src/org/ice4j/socket/MuxServerSocketChannel.java new file mode 100644 index 0000000..5a0d8a0 --- /dev/null +++ b/src/org/ice4j/socket/MuxServerSocketChannel.java @@ -0,0 +1,1323 @@ +/* + * ice4j, the OpenSource Java Solution for NAT and Firewall Traversal. + * Maintained by the SIP Communicator community (http://sip-communicator.org). + * + * Distributable under LGPL license. See terms of license at gnu.org. + */ +package org.ice4j.socket; + +import java.io.*; +import java.net.*; +import java.nio.*; +import java.nio.channels.*; +import java.util.*; + +import org.ice4j.ice.harvest.*; + +/** + * 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 +{ + /** + * 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)); + + /** + * 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. + */ + public static final int SOCKET_CHANNEL_READ_TIMEOUT = 15 * 1000; + + /** + * The name of the boolean property of the socket property + * of the ServerSocketChannel returned by {@link #openAndBind(Map, + * SocketAddress, int, DatagramPacketFilter)} which specifies the value of + * the SO_REUSEADDR socket option. + */ + public static final String SOCKET_REUSE_ADDRESS_PROPERTY_NAME + = "socket.reuseAddress"; + + /** + * Asserts that t is not null by throwing a + * NullPointerException if it is. + * + * @param t the Object to assert that it is not null + * @param message the (detail) message of the NullPointerException + * to be thrown if t is null + * @param the type of t + * @return t + * @throws NullPointerException if t is null. The (detail) + * message of the NullPointerException is message + */ + public static T assertIsNotNull(T t, String message) + throws NullPointerException + { + if (t == null) + throw new NullPointerException(message); + else + return t; + } + + /** + * 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) + { + } + } + + /** + * 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(assertIsNotNull(delegate, "delegate")); + + this.filter = assertIsNotNull(filter, "filter"); + } + + /** + * {@inheritDoc} + */ + @Override + public SocketChannel accept() + throws IOException + { + SocketChannel accepted; + + // Pop a SocketChannel from acceptQ. + do + { + if (!isOpen()) + { + throw new ClosedChannelException(); + } + else if (!isBound()) + { + throw new NotYetBoundException(); + } + else + { + synchronized (syncRoot) + { + accepted = acceptQ.poll(); + if (accepted == null) + { + if (isBlocking()) + { + try + { + syncRoot.wait(); + } + catch (InterruptedException ie) + { + } + } + else + { + break; + } + } + else if (accepted.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); + return accepted; + } + + /** + * 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) + { + boolean b; + + if (filter.accept(p)) + b = qAccept(new PreReadSocketChannel(p, channel)); + else + b = false; + return b; + } + + /** + * {@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} + */ + private boolean qAccept(SocketChannel channel) + { + boolean b; + + synchronized (syncRoot) + { + if (acceptQ.offer(channel)) + { + syncRoot.notifyAll(); + b = true; + } + else + { + b = false; + } + } + return b; + } + + /** + * 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 reader from the same + * {@code byte} array. + */ + private static class DatagramBuffer + { + /** + * The {@code ByteBuffer} which is associated with + * {@link #datagramPacket} and shares its backing {@code array} with. + */ + private final ByteBuffer byteBuffer; + + /** + * The {@code DatagramPacket} which is associated with + * {@link #byteBuffer} and shares its {@code data} with. + */ + private final DatagramPacket datagramPacket; + + /** + * The latest/last time in milliseconds at which {@code byte}s were + * written into this {@code DatagramBuffer}. + */ + long timestamp = -1; + + /** + * 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) + { + byteBuffer = ByteBuffer.allocate(capacity); + datagramPacket + = new DatagramPacket( + byteBuffer.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 byteBuffer; + } + + /** + * 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(byteBuffer.position()); + return datagramPacket; + } + } + + /** + * Represents a {@link ServerSocket} associated with a + * {@code MuxingServerSocketChannel}. + */ + protected static 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( + assertIsNotNull(delegate, "delegate"), + assertIsNotNull(channel, "channel")); + } + } + + /** + * 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. + */ + protected static class MuxingServerSocketChannel + extends DelegatingServerSocketChannel + { + /** + * 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(); + + /** + * 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); + } + } + + /** + * 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; + } + if (aLocalAddr != null && aLocalAddr.equals(localAddr)) + { + 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) + { + } + } + 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. + assertIsNotNull(filter, "filter"); + + MuxingServerSocketChannel muxingChannel; + + synchronized (muxingServerSocketChannels) + { + muxingChannel = findMuxingServerSocketChannel(endpoint); + if (muxingChannel == null) + { + ServerSocketChannel channel = ServerSocketChannel.open(); + // Apply the specified properties. + ServerSocket socket = channel.socket(); + + if (properties != null && !properties.isEmpty()) + { + for (Map.Entry property + : properties.entrySet()) + { + String name = property.getKey(); + + if (SOCKET_REUSE_ADDRESS_PROPERTY_NAME.equals(name)) + { + Object value = property.getValue(); + boolean on; + + if (value == null) + on = false; + else if (value instanceof Boolean) + on = ((Boolean) value).booleanValue(); + else + on = Boolean.valueOf(value.toString()); + + socket.setReuseAddress(on); + } + } + } + + socket.bind(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() + { + do + { + Selector sel; + boolean select = false; + + synchronized (muxingServerSocketChannels) + { + if (!Thread.currentThread().equals(acceptThread)) + break; + + sel = MuxingServerSocketChannel.acceptSelector; + if (!sel.isOpen()) + break; + + // Accept from all muxingServerSocketChannels. + for (Iterator i + = muxingServerSocketChannels.iterator(); + i.hasNext();) + { + MuxingServerSocketChannel ch = i.next(); + + if (ch.isOpen()) + { + try + { + 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. + } + + // Make sure all muxingServerSocketChannels are + // registered with acceptSelector. + if (ch.isOpen() && ch.keyFor(sel) == null) + { + try + { + ch.register(sel, SelectionKey.OP_ACCEPT); + } + catch (ClosedChannelException cce) + { + // The cce will be handled at the end of the + // loop by removing ch from + // muxingServerSocketChannels. + } + } + } + + if (ch.isOpen()) + select = true; + else + i.remove(); + } + // We've accepted from all muxingServerSocketChannels. + sel.selectedKeys().clear(); + + // If there are no muxingServerSocketChannels, we will wait + // until there are. + if (!select) + { + try + { + muxingServerSocketChannels.wait(); + } + catch (InterruptedException ie) + { + } + continue; + } + } + + // Wait for a new iteration of acceptance. + if (select) + { + try + { + sel.select(); + } + 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(assertIsNotNull(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(); + } + + /** + * 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); + } + } + + /** + * 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. + assertIsNotNull(filter, "filter"); + + MuxServerSocketChannel channel; + + synchronized (syncRoot) + { + Iterator i + = muxServerSocketChannels.iterator(); + + while (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); + + 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() + { + do + { + Selector sel; + boolean select = false; + + synchronized (syncRoot) + { + if (!Thread.currentThread().equals(readThread)) + break; + + sel = this.readSelector; + if (!sel.isOpen()) + break; + + for (Iterator i = readQ.iterator(); + i.hasNext();) + { + SocketChannel ch = i.next(); + boolean remove = false; + + if (ch.isOpen()) + { + SelectionKey sk = ch.keyFor(sel); + + if (sk == null) + { + // Make sure that all SocketChannels in readQ + // are registered with readSelector. + try + { + sk = ch.register(sel, SelectionKey.OP_READ); + } + catch (ClosedChannelException cce) + { + // The cce will be handled at the end of the + // loop by removing ch from readQ. + } + } + if (sk != null && sk.isValid()) + { + // 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 pkt = db.getDatagramPacket(); + + if (pkt.getLength() > 0 + && filterAccept(pkt, ch)) + { + sk.cancel(); + remove = true; + } + else if (read <= 0 + && now - db.timestamp + > SOCKET_CHANNEL_READ_TIMEOUT) + { + // The SocketChannel appears to have + // been abandoned by the client. + closeNoExceptions(ch); + } + } + } + } + + if (remove || !ch.isOpen()) + i.remove(); + else + select = true; + } + // We've read from all SocketChannels in readQ. + sel.selectedKeys().clear(); + + // If there are no SocketChannels in readQ, we will wait + // until there are. + if (!select) + { + try + { + syncRoot.wait(); + } + catch (InterruptedException ie) + { + } + continue; + } + } + + // Wait for a new iteration of acceptance. + if (select) + { + try + { + sel.select(); + } + 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); + } + + /** + * 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(); + } + } + } + } + + /** + * Represents a {@link ServerSocket} associated with a + * {@code MuxServerSocketChannel}. + */ + public static 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( + assertIsNotNull(delegate, "delegate"), + assertIsNotNull(channel, "channel")); + } + } +} diff --git a/src/org/ice4j/socket/PreReadSocketChannel.java b/src/org/ice4j/socket/PreReadSocketChannel.java new file mode 100644 index 0000000..c75dbfa --- /dev/null +++ b/src/org/ice4j/socket/PreReadSocketChannel.java @@ -0,0 +1,97 @@ +/* + * ice4j, the OpenSource Java Solution for NAT and Firewall Traversal. + * Maintained by the SIP Communicator community (http://sip-communicator.org). + * + * Distributable under LGPL license. See terms of license at gnu.org. + */ +package org.ice4j.socket; + +import java.io.*; +import java.net.*; +import java.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 + */ +public 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 DatagrapPacket} 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; + } + } +}