From ef3acb3028471967ec0a0340e87b02e0c3418386 Mon Sep 17 00:00:00 2001 From: "lubomir.marinov" Date: Mon, 1 Feb 2010 19:34:56 +0000 Subject: [PATCH] Implements DatagramSocket multiplexing for the purposes of ICE. --- .../ice4j/socket/DatagramPacketFilter.java | 32 + .../socket/MultiplexedDatagramSocket.java | 626 ++++++++++++++++++ .../socket/MultiplexingDatagramSocket.java | 414 ++++++++++++ .../socket/StunDatagramPacketFilter.java | 50 ++ 4 files changed, 1122 insertions(+) create mode 100644 src/org/ice4j/socket/DatagramPacketFilter.java create mode 100644 src/org/ice4j/socket/MultiplexedDatagramSocket.java create mode 100644 src/org/ice4j/socket/MultiplexingDatagramSocket.java create mode 100644 src/org/ice4j/socket/StunDatagramPacketFilter.java diff --git a/src/org/ice4j/socket/DatagramPacketFilter.java b/src/org/ice4j/socket/DatagramPacketFilter.java new file mode 100644 index 0000000..d66bc40 --- /dev/null +++ b/src/org/ice4j/socket/DatagramPacketFilter.java @@ -0,0 +1,32 @@ +/* + * 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.net.*; + +/** + * Represents a filter which selects or deselects DatagramPackets. + * + * @author Lubomir Marinov + */ +public interface DatagramPacketFilter +{ + /** + * Determines whether a specific DatagramPacket is accepted by this + * filter i.e. whether the caller should include the specified + * DatagramPacket in a selection based on this filter. + * + * @param p the DatagramPacket which is to be checked whether it is + * accepted by this filter + * @return true if this filter accepts the specified + * DatagramPacket i.e. if the caller should include the specified + * DatagramPacket in a selection based on this filter; otherwise, + * false + */ + public boolean accept(DatagramPacket p); +} diff --git a/src/org/ice4j/socket/MultiplexedDatagramSocket.java b/src/org/ice4j/socket/MultiplexedDatagramSocket.java new file mode 100644 index 0000000..80fec39 --- /dev/null +++ b/src/org/ice4j/socket/MultiplexedDatagramSocket.java @@ -0,0 +1,626 @@ +/* + * 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.*; + +/** + * Represents a DatagramSocket which receives DatagramPackets + * selected by a DatagramPacketFilter from a + * MultiplexingDatagramSocket. The associated + * MultiplexingDatagramSocket is the actual DatagramSocket + * which reads the DatagramPackets from the network. The + * DatagramPackets received through the + * MultiplexedDatagramSocket will not be received through the + * associated MultiplexingDatagramSocket. + * + * @author Lubomir Marinov + */ +public class MultiplexedDatagramSocket + extends DatagramSocket +{ + + /** + * The DatagramPacketFilter which determines which + * DatagramPackets read from the network by {@link #multiplexing} + * are to be received through this instance. + */ + private final DatagramPacketFilter filter; + + /** + * The MultiplexingDatagramSocket which does the actual reading + * from the network and which forwards DatagramPackets accepted by + * {@link #filter} for receipt to this instance. + */ + private final MultiplexingDatagramSocket multiplexing; + + /** + * The list of DatagramPackets to be received through this + * DatagramSocket i.e. accepted by {@link #filter}. + */ + final List received + = new LinkedList(); + + /** + * Initializes a new MultiplexedDatagramSocket which is unbound and + * filters DatagramPackets away from a specific + * MultiplexingDatagramSocket using a specific + * DatagramPacketFilter. + * + * @param multiplexing the MultiplexingDatagramSocket which does + * the actual reading from the network and which forwards + * DatagramPackets accepted by the specified filter to the + * new instance + * @param filter the DatagramPacketFilter which determines which + * DatagramPackets read from the network by the specified + * multiplexing are to be received through the new instance + * @throws SocketException if the socket could not be opened + */ + MultiplexedDatagramSocket( + MultiplexingDatagramSocket multiplexing, + DatagramPacketFilter filter) + throws SocketException + { + /* + * Even if MultiplexingDatagramSocket allows MultiplexedDatagramSocket + * to perform bind, binding in the super will not execute correctly this + * early in the construction because the multiplexing field is not set + * yet. That is why MultiplexedDatagramSocket does not currently support + * bind at construction time. + */ + super((SocketAddress) null); + + if (multiplexing == null) + throw new NullPointerException("multiplexing"); + + this.multiplexing = multiplexing; + this.filter = filter; + } + + /** + * Binds this DatagramSocket to a specific address and port. + *

+ * If the address is null, then the system will pick up an + * ephemeral port and a valid local address to bind the socket. + *

+ * + * @param addr the address and port to bind to + * @throws SocketException if any error happens during the bind, or if the + * socket is already bound + * @throws SecurityException if a security manager exists and its + * checkListen method doesn't allow the operation + * @throws IllegalArgumentException if addr is a + * SocketAddress subclass not supported by this socket + * @see DatagramSocket#bind(SocketAddress) + */ + @Override + public void bind(SocketAddress addr) + throws SocketException + { + multiplexing.bind(addr); + } + + /** + * Closes this datagram socket. + *

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

+ * + * @see DatagramSocket#close() + */ + @Override + public void close() + { + multiplexing.close(this); + } + + /** + * Connects the socket to a remote address for this socket. When a socket is + * connected to a remote address, packets may only be sent to or received + * from that address. By default a datagram socket is not connected. + *

+ * If the remote destination to which the socket is connected does not + * exist, or is otherwise unreachable, and if an ICMP destination + * unreachable packet has been received for that address, then a subsequent + * call to {@link #send(DatagramPacket)} or {@link #receive(DatagramPacket)} + * may throw a PortUnreachableException. Note, there is no + * guarantee that the exception will be thrown. + *

+ * + * @param address the remote address for the socket + * @param port the remote port for the socket + * @throws IllegalArgumentException if the address is null, or the + * port is out of range + * @throws SecurityException if the caller is not allowed to send datagrams + * to and receive datagrams from the address and port + * @see DatagramSocket#connect(InetAddress, int) + */ + @Override + public void connect(InetAddress address, int port) + { + multiplexing.connect(address, port); + } + + /** + * Connects this socket to a remote socket address. + * + * @param addr the remote address + * @throws SocketException if the connect fails + * @throws IllegalArgumentException if addr is null or a + * SocketAddress subclass not supported by this socket + * @see DatagramSocket#connect(SocketAddress) + */ + @Override + public void connect(SocketAddress addr) + throws SocketException + { + multiplexing.connect(addr); + } + + /** + * Disconnects the socket. This does nothing if the socket is not connected. + * + * @see DatagramSocket#disconnect() + */ + @Override + public void disconnect() + { + multiplexing.disconnect(); + } + + /** + * Tests if SO_BROADCAST is enabled. + * + * @return a boolean indicating whether or not + * SO_BROADCAST is enabled + * @throws SocketException if there is an error in the underlying protocol, + * such as an UDP error + * @see DatagramSocket#getBroadcast() + */ + @Override + public boolean getBroadcast() + throws SocketException + { + return multiplexing.getBroadcast(); + } + + /** + * Returns the unique {@link DatagramChannel} object associated with this + * datagram socket, if any. + *

+ * A datagram socket will have a channel if, and only if, the channel itself + * was created via the {@link DatagramChannel#open()} method + *

+ * + * @return the datagram channel associated with this datagram socket, or + * null if this socket was not created for a channel + * @see DatagramSocket#getChannel() + */ + @Override + public DatagramChannel getChannel() + { + return multiplexing.getChannel(); + } + + /** + * Gets the DatagramPacketFilter which determines which + * DatagramPackets read from the network are to be received through + * this DatagramSocket. + * + * @return the DatagramPacketFilter which determines which + * DatagramPackets read from the network are to be received through + * this DatagramSocket + */ + public DatagramPacketFilter getFilter() + { + return filter; + } + + /** + * Returns the address to which this socket is connected. Returns + * null if the socket is not connected. + * + * @return the address to which this socket is connected + * @see DatagramSocket#getInetAddress() + */ + @Override + public InetAddress getInetAddress() + { + return multiplexing.getInetAddress(); + } + + /** + * Gets the local address to which the socket is bound. + *

+ * If there is a security manager, its checkConnect method is first + * called with the host address and -1 as its arguments to see if + * the operation is allowed. + * + * @return the local address to which the socket is bound, or an + * InetAddress representing any local address if either the socket + * is not bound, or the security manager checkConnect method does + * not allow the operation + * @see DatagramSocket#getLocalAddress() + */ + @Override + public InetAddress getLocalAddress() + { + return multiplexing.getLocalAddress(); + } + + /** + * Returns the port number on the local host to which this socket is bound. + * + * @return the port number on the local host to which this socket is bound + * @see DatagramSocket#getLocalPort() + */ + @Override + public int getLocalPort() + { + return multiplexing.getLocalPort(); + } + + /** + * Returns the address of the endpoint this socket is bound to, or + * null if it is not bound yet. + * + * @return a SocketAddress representing the local endpoint of this + * socket, or null if it is not bound yet + * @see DatagramSocket#getLocalSocketAddress() + */ + @Override + public SocketAddress getLocalSocketAddress() + { + return multiplexing.getLocalSocketAddress(); + } + + /** + * Returns the port for this socket. Returns -1 if the socket is + * not connected. + * + * @return the port to which this socket is connected + * @see DatagramSocket#getPort() + */ + @Override + public int getPort() + { + return multiplexing.getPort(); + } + + /** + * Gets the value of the SO_RCVBUF option for this + * DatagramSocket, that is the buffer size used by the platform for + * input on this DatagramSocket. + * + * @return the value of the SO_RCVBUF option for this + * DatagramSocket + * @throws SocketException if there is an error in the underlying protocol, + * such as an UDP error + * @see DatagramSocket#getReceiveBufferSize() + */ + @Override + public int getReceiveBufferSize() + throws SocketException + { + return multiplexing.getReceiveBufferSize(); + } + + /** + * Returns the address of the endpoint this socket is connected to, or + * null if it is unconnected. + * + * @return a SocketAddress representing the remote endpoint of this + * socket, or null if it is not connected yet + * @see DatagramSocket#getRemoteSocketAddress() + */ + @Override + public SocketAddress getRemoteSocketAddress() + { + return multiplexing.getRemoteSocketAddress(); + } + + /** + * Tests if SO_REUSEADDR is enabled. + * + * @return a boolean indicating whether or not + * SO_REUSEADDR is enabled + * @throws SocketException if there is an error in the underlying protocol, + * such as an UDP error + * @see DatagramSocket#getReuseAddress() + */ + @Override + public boolean getReuseAddress() + throws SocketException + { + return multiplexing.getReuseAddress(); + } + + /** + * Gets the value of the SO_SNDBUF option for this + * DatagramSocket, that is the buffer size used by the platform for + * output on this DatagramSocket. + * + * @return the value of the SO_SNDBUF option for this + * DatagramSocket + * @throws SocketException if there is an error in the underlying protocol, + * such as an UDP error + * @see DatagramSocket#getSendBufferSize() + */ + @Override + public int getSendBufferSize() + throws SocketException + { + return multiplexing.getSendBufferSize(); + } + + /** + * Retrieves setting for SO_TIMEOUT. Zero returned implies that + * the option is disabled (i.e., timeout of infinity). + * + * @return the setting for SO_TIMEOUT + * @throws SocketException if there is an error in the underlying protocol, + * such as an UDP error + * @see DatagramSocket#getSoTimeout() + */ + @Override + public int getSoTimeout() + throws SocketException + { + return multiplexing.getSoTimeout(); + } + + /** + * Gets the traffic class or type-of-service in the IP datagram header for + * packets sent from this DatagramSocket. + *

+ * As the underlying network implementation may ignore the traffic class or + * type-of-service set using {@link #setTrafficClass(int)} this method may + * return a different value than was previously set using the + * {@link #setTrafficClass(int)} method on this DatagramSocket. + *

+ * + * @return the traffic class or type-of-service already set + * @throws SocketException if there is an error obtaining the traffic class + * or type-of-service value + * @see DatagramSocket#getTrafficClass() + */ + @Override + public int getTrafficClass() + throws SocketException + { + return multiplexing.getTrafficClass(); + } + + /** + * Returns the binding state of the socket. + * + * @return true if the socket successfully bound to an address; + * otherwise, false + * @see DatagramSocket#isBound() + */ + @Override + public boolean isBound() + { + return multiplexing.isBound(); + } + + /** + * Returns whether the socket is closed or not. + * + * @return true if the socket has been closed; otherwise, + * false + * @see DatagramSocket#isClosed() + */ + @Override + public boolean isClosed() + { + return multiplexing.isClosed(); + } + + /** + * Returns the connection state of the socket. + * + * @return true if the socket successfully connected to a server; + * otherwise, false + * @see DatagramSocket#isConnected() + */ + @Override + public boolean isConnected() + { + return multiplexing.isConnected(); + } + + /** + * Receives a datagram packet from this socket. When this method returns, + * the DatagramPacket's buffer is filled with the data received. + * The datagram packet also contains the sender's IP address, and the port + * number on the sender's machine. + *

+ * This method blocks until a datagram is received. The length + * field of the datagram packet object contains the length of the received + * message. If the message is longer than the packet's length, the message + * is truncated. + *

+ *

+ * If there is a security manager, a packet cannot be received if the + * security manager's checkAccept method does not allow it. + *

+ * + * @param p the DatagramPacket into which to place the incoming + * data + * @throws IOException if an I/O error occurs + * @see DatagramSocket#receive(DatagramPacket) + */ + @Override + public void receive(DatagramPacket p) + throws IOException + { + multiplexing.receive(this, p); + } + + /** + * Sends a datagram packet from this socket. The DatagramPacket + * includes information indicating the data to be sent, its length, the IP + * address of the remote host, and the port number on the remote host. + *

+ * If there is a security manager, and the socket is not currently connected + * to a remote address, this method first performs some security checks. + * First, if p.getAddress().isMulticastAddress() is true, this + * method calls the security manager's checkMulticast method with + * p.getAddress() as its argument. If the evaluation of that + * expression is false, this method instead calls the security + * manager's checkConnect method with arguments + * p.getAddress().getHostAddress() and p.getPort(). Each + * call to a security manager method could result in a + * SecurityException if the operation is not allowed. + *

+ * + * @param p the DatagramPacket to be sent + * @throws IOException if an I/O error occurs + * @see DatagramSocket#send(DatagramPacket) + */ + @Override + public void send(DatagramPacket p) + throws IOException + { + multiplexing.send(p); + } + + /** + * Enables/disables SO_BROADCAST. + * + * @param on whether or not to have broadcast turned on + * @throws SocketException if there is an error in the underlying protocol, + * such as an UDP error + * @see DatagramSocket#setBroadcast(boolean) + */ + @Override + public void setBroadcast(boolean on) + throws SocketException + { + multiplexing.setBroadcast(on); + } + + /** + * Sets the SO_RCVBUF option to the specified value for this + * DatagramSocket. The SO_RCVBUF option is used by the + * network implementation as a hint to size the underlying network I/O + * buffers. The SO_RCVBUF setting may also be used by the network + * implementation to determine the maximum size of the packet that can be + * received on this socket. + *

+ * Because SO_RCVBUF is a hint, applications that want to verify + * what size the buffers were set to should call + * {@link #getReceiveBufferSize()}. + *

+ * + * @param size the size to which to set the receive buffer size. The value + * must be greater than zero + * @throws SocketException if there is an error in the underlying protocol, + * such as an UDP error + * @throws IllegalArgumentException if the value is zero or is negative + * @see DatagramSocket#setReceiveBufferSize(int) + */ + @Override + public void setReceiveBufferSize(int size) + throws SocketException + { + multiplexing.setReceiveBufferSize(size); + } + + /** + * Enables/disables the SO_REUSEADDR socket option. + * + * @param on whether to enable or disable the SO_REUSEADDR socket + * option + * @throws SocketException if an error occurs enabling or disabling the + * SO_RESUEADDR socket option, or the socket is closed + * @see DatagramSocket#setReuseAddress(boolean) + */ + @Override + public void setReuseAddress(boolean on) + throws SocketException + { + multiplexing.setReuseAddress(on); + } + + /** + * Sets the SO_SNDBUF option to the specified value for this + * DatagramSocket. The SO_SNDBUF option is used by the + * network implementation as a hint to size the underlying network I/O + * buffers. The SO_SNDBUF setting may also be used by the network + * implementation to determine the maximum size of the packet that can be + * sent on this socket. + *

+ * As SO_SNDBUF is a hint, applications that want to verify what + * size the buffer is should call {@link #getSendBufferSize()}. + *

+ *

+ * Increasing the buffer size may allow multiple outgoing packets to be + * queued by the network implementation when the send rate is high. + *

+ * + * @param size the size to which to set the send buffer size. The value must + * be greater than zero + * @throws SocketException if there is an error in the underlying protocol, + * such as an UDP error + * @throws IllegalArgumentException if the value is zero or is negative + * @see DatagramSocket#setSendBufferSize(int) + */ + @Override + public void setSendBufferSize(int size) + throws SocketException + { + multiplexing.setSendBufferSize(size); + } + + /** + * Enables/disables SO_TIMEOUT with the specified timeout, in + * milliseconds. With this option set to a non-zero timeout, a call to + * {@link #receive(DatagramPacket)} for this DatagramSocket will + * block for only this amount of time. If the timeout expires, a + * SocketTimeoutException is raised, though the + * DatagramSocket is still valid. The option must be enabled prior + * to entering the blocking operation to have effect. The timeout must be + * greater than zero. A timeout of zero is interpreted as an infinite + * timeout. + * + * @param timeout the specified timeout in milliseconds + * @throws SocketException if there is an error in the underlying protocol, + * such as an UDP error + * @see DatagramSocket#setSoTimeout(int) + */ + @Override + public void setSoTimeout(int timeout) + throws SocketException + { + multiplexing.setSoTimeout(timeout); + } + + /** + * Sets traffic class or type-of-service octet in the IP datagram header for + * datagrams sent from this DatagramSocket. As the underlying + * network implementation may ignore this value applications should consider + * it a hint. + * + * @param tc an int value for the bitset + * @throws SocketException if there is an error setting the traffic class or + * type-of-service + * @see DatagramSocket#setTrafficClass(int) + */ + @Override + public void setTrafficClass(int tc) + throws SocketException + { + multiplexing.setTrafficClass(tc); + } +} diff --git a/src/org/ice4j/socket/MultiplexingDatagramSocket.java b/src/org/ice4j/socket/MultiplexingDatagramSocket.java new file mode 100644 index 0000000..131d0ca --- /dev/null +++ b/src/org/ice4j/socket/MultiplexingDatagramSocket.java @@ -0,0 +1,414 @@ +/* + * ice4j, the OpenSource Java Solution for NAT and Firewall Traversal. + * Maintained by the SIP Communicator community (http://sip-communicator.org). + * + * Distributable under LGPL license. + * See terms of license at gnu.org. + */ +package org.ice4j.socket; + +import java.io.*; +import java.net.*; +import java.util.*; + +/** + * Represents a DatagramSocket which allows filtering + * DatagramPackets it reads from the network using + * DatagramPacketFilters so that the DatagramPackets do not + * get received through it but through associated + * MultiplexedDatagramSockets. + * + * @author Lubomir Marinov + */ +public class MultiplexingDatagramSocket + extends DatagramSocket +{ + + /** + * The constant which represents an empty array with + * MultiplexedDatagramSocket element type. Explicitly defined in + * order to reduce allocations. + */ + private static final MultiplexedDatagramSocket[] NO_SOCKETS + = new MultiplexedDatagramSocket[0]; + + /** + * The indicator which determines whether this DatagramSocket is + * currently reading from the network using + * {@link DatagramSocket#receive(DatagramPacket)}. When true, + * subsequent requests to read from the network will be blocked until the + * current read is finished. + */ + private boolean inReceive = false; + + /** + * The list of DatagramPackets to be received through this + * DatagramSocket i.e. not accepted by the DatagramFilters + * of {@link #sockets} at the time of the reading from the network. + */ + private final List received + = new LinkedList(); + + /** + * The Object which synchronizes the access to {@link #inReceive}. + */ + private final Object receiveSyncRoot = new Object(); + + /** + * The MultiplexedDatagramSockets filtering + * DatagramPackets away from this DatagramSocket. + */ + private MultiplexedDatagramSocket[] sockets = NO_SOCKETS; + + /** + * The Object which synchronizes the access to the {@link #sockets} + * field of this instance. + */ + private final Object socketsSyncRoot = new Object(); + + /** + * Initializes a new MultiplexingDatagramSocket instance which is + * to enable DatagramPacket filtering and binds it to any available + * port on the local host machine. The socket will be bound to the wildcard + * address, an IP address chosen by the kernel. + * + * @throws SocketException if the socket could not be opened, or the socket + * could not bind to the specified local port + * @see DatagramSocket#DatagramSocket() + */ + public MultiplexingDatagramSocket() + throws SocketException + { + super(); + } + + /** + * Initializes a new MultiplexingDatagramSocket instance which is + * to enable DatagramPacket filtering, bound to the specified local + * socket address. + *

+ * If the specified local socket address is null, creates an + * unbound socket. + *

+ * + * @param bindaddr local socket address to bind, or null for an + * unbound socket + * @throws SocketException if the socket could not be opened, or the socket + * could not bind to the specified local port + * @see DatagramSocket#DatagramSocket(SocketAddress) + */ + public MultiplexingDatagramSocket(SocketAddress bindaddr) + throws SocketException + { + super(bindaddr); + } + + /** + * Initializes a new MultiplexingDatagramSocket instance which is + * to enable DatagramPacket filtering and binds it to the specified + * port on the local host machine. The socket will be bound to the wildcard + * address, an IP address chosen by the kernel. + * + * @param port the port to bind the new socket to + * @throws SocketException if the socket could not be opened, or the socket + * could not bind to the specified local port + * @see DatagramSocket#DatagramSocket(int) + */ + public MultiplexingDatagramSocket(int port) + throws SocketException + { + super(port); + } + + /** + * Initializes a new MultiplexingDatagramSocket instance which is + * to enable DatagramPacket filtering, bound to the specified local + * address. The local port must be between 0 and 65535 inclusive. If the IP + * address is 0.0.0.0, the socket will be bound to the wildcard address, an + * IP address chosen by the kernel. + * + * @param port the local port to bind the new socket to + * @param laddr the local address to bind the new socket to + * @throws SocketException if the socket could not be opened, or the socket + * could not bind to the specified local port + * @see DatagramSocket#DatagramSocket(int, InetAddress) + */ + public MultiplexingDatagramSocket(int port, InetAddress laddr) + throws SocketException + { + super(port, laddr); + } + + /** + * Initializes a new DatagramPacket instance which is a clone of a + * specific DatagramPacket i.e. the properties of the clone + * DatagramPacket are clones of the specified + * DatagramPacket. + * + * @param p the DatagramPacket to clone + * @return a new DatagramPacket instance which is a clone of the + * specified DatagramPacket + */ + static DatagramPacket clone(DatagramPacket p) + { + synchronized (p) + { + byte[] pData = p.getData(); + byte[] cData = (pData == null) ? pData : pData.clone(); + + return + new DatagramPacket( + cData, + p.getOffset(), + p.getLength(), + p.getAddress(), + p.getPort()); + } + } + + /** + * Closes a specific MultiplexedDatagramSocket which filters + * DatagramPackets away from this DatagramSocket. + * + * @param multiplexed the MultiplexedDatagramSocket to close + */ + void close(MultiplexedDatagramSocket multiplexed) + { + synchronized (socketsSyncRoot) + { + int socketCount = sockets.length; + + for (int i = 0; i < socketCount; i++) + if (sockets[i].equals(multiplexed)) + { + if (socketCount == 1) + sockets = NO_SOCKETS; + else + { + MultiplexedDatagramSocket[] newSockets + = new MultiplexedDatagramSocket[socketCount - 1]; + + System.arraycopy(sockets, 0, newSockets, 0, i); + System + .arraycopy( + sockets, + i + 1, + newSockets, + i, + newSockets.length - i); + sockets = newSockets; + } + break; + } + } + } + + /** + * Copies the properties of a specific DatagramPacket to another + * DatagramPacket. The property values are not cloned. + * + * @param src the DatagramPacket which is to have its properties + * copied to dest + * @param dest the DatagramPacket which is to have its properties + * set to the value of the respective properties of src + */ + static void copy(DatagramPacket src, DatagramPacket dest) + { + synchronized (dest) + { + dest.setAddress(src.getAddress()); + dest.setData(src.getData(), src.getOffset(), src.getLength()); + dest.setPort(src.getPort()); + } + } + + /** + * Gets a MultiplexedDatagramSocket which filters + * DatagramPackets away from this DatagramSocket using a + * specific DatagramPacketFilter. If such a + * MultiplexedDatagramSocket does not exist in this instance, it is + * created. + * + * @param filter the DatagramPacketFilter to get a + * MultiplexedDatagramSocket for + * @return a MultiplexedDatagramSocket which filters + * DatagramPackets away from this DatagramSocket using the + * specified filter + * @throws SocketException if creating the + * MultiplexedDatagramSocket for the specified filter + * fails + */ + public MultiplexedDatagramSocket getSocket(DatagramPacketFilter filter) + throws SocketException + { + if (filter == null) + throw new NullPointerException("filter"); + + synchronized (socketsSyncRoot) + { + /* + * If a socket for the specified filter exists already, do not + * create a new one and return the existing. + */ + for (MultiplexedDatagramSocket socket : sockets) + if (filter.equals(socket.getFilter())) + return socket; + + // Create a new socket for the specified filter. + MultiplexedDatagramSocket socket + = new MultiplexedDatagramSocket(this, filter); + + // Remember the new socket. + int socketCount = sockets.length; + + if (socketCount == 0) + sockets = new MultiplexedDatagramSocket[] { socket }; + else + { + MultiplexedDatagramSocket[] newSockets + = new MultiplexedDatagramSocket[socketCount + 1]; + + System.arraycopy(sockets, 0, newSockets, 0, socketCount); + newSockets[socketCount] = socket; + sockets = newSockets; + } + + return socket; + } + } + + /** + * Receives a datagram packet from this socket. The DatagramPackets + * returned by this method do not match any of the + * DatagramPacketFilters of the MultiplexedDatagramSockets + * associated with this instance at the time of their receipt. When this + * method returns, the DatagramPacket's buffer is filled with the + * data received. The datagram packet also contains the sender's IP address, + * and the port number on the sender's machine. + *

+ * This method blocks until a datagram is received. The length + * field of the datagram packet object contains the length of the received + * message. If the message is longer than the packet's length, the message + * is truncated. + *

+ * + * @param p the DatagramPacket into which to place the incoming + * data + * @throws IOException if an I/O error occurs + * @see DatagramSocket#receive(DatagramPacket) + */ + @Override + public void receive(DatagramPacket p) + throws IOException + { + receive(received, p); + } + + /** + * Receives a DatagramPacket from a specific list of + * DatagramPackets if it is not empty or from the network if the + * specified list is empty. When this method returns, the + * DatagramPacket's buffer is filled with the data received. The + * datagram packet also contains the sender's IP address, and the port + * number on the sender's machine. + * + * @param received the list of previously received DatagramPacket + * from which the first is to be removed and returned if available + * @param p the DatagramPacket into which to place the incoming + * data + * @throws IOException if an I/O error occurs + */ + private void receive(List received, DatagramPacket p) + throws IOException + { + DatagramPacket r = null; + + do + { + boolean doReceive; + + synchronized (receiveSyncRoot) + { + if (received.isEmpty()) + { + if (inReceive) + { + doReceive = false; + try + { + receiveSyncRoot.wait(); + } + catch (InterruptedException iex) + { + continue; + } + } + else + { + doReceive = true; + inReceive = true; + } + } + else + { + doReceive = false; + r = received.remove(0); + } + } + if (doReceive) + { + try + { + super.receive(p); + + synchronized (receiveSyncRoot) + { + synchronized (socketsSyncRoot) + { + boolean accepted = false; + + for (MultiplexedDatagramSocket socket : sockets) + if (socket.getFilter().accept(p)) + { + socket.received.add(clone(p)); + accepted = true; + break; + } + + if (!accepted) + this.received.add(clone(p)); + } + } + } + finally + { + synchronized (receiveSyncRoot) + { + inReceive = false; + receiveSyncRoot.notifyAll(); + } + } + } + } + while (r == null); + + copy(r, p); + } + + /** + * Receives a DatagramPacket from this DatagramSocket upon + * request from a specific MultiplexedDatagramSocket. + * + * @param multiplexed the MultiplexedDatagramSocket which requests + * the receipt of a DatagramPacket from the network + * @param p the DatagramPacket to receive the data from the network + * @throws IOException if an I/O error occurs + */ + void receive( + MultiplexedDatagramSocket multiplexed, + DatagramPacket p) + throws IOException + { + receive(multiplexed.received, p); + } +} diff --git a/src/org/ice4j/socket/StunDatagramPacketFilter.java b/src/org/ice4j/socket/StunDatagramPacketFilter.java new file mode 100644 index 0000000..fac69fc --- /dev/null +++ b/src/org/ice4j/socket/StunDatagramPacketFilter.java @@ -0,0 +1,50 @@ +/* + * 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.net.*; + +/** + * Implements a DatagramPacketFilter which only accepts + * DatagramPackets which represent STUN messages. + * + * @author Lubomir Marinov + */ +public class StunDatagramPacketFilter + implements DatagramPacketFilter +{ + + /** + * Determines whether a specific DatagramPacket represents a STUN + * message. + * + * @param p the DatagramPacket which is to be checked whether it is + * a STUN message + * @return true if p represents a STUN message + */ + public boolean accept(DatagramPacket p) + { + /* + * All STUN messages MUST start with a 20-byte header followed by zero + * or more Attributes. + */ + if (p.getLength() >= 20) + { + /* + * The most significant 2 bits of every STUN message MUST be zeroes. + * This can be used to differentiate STUN packets from other + * protocols when STUN is multiplexed with other protocols on the + * same port. + */ + byte b0 = p.getData()[p.getOffset()]; + + return ((b0 & 0xC0) == 0); + } + return false; + } +}