1 /*
  2  * Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved.
  3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  4  *
  5  * This code is free software; you can redistribute it and/or modify it
  6  * under the terms of the GNU General Public License version 2 only, as
  7  * published by the Free Software Foundation.  Oracle designates this
  8  * particular file as subject to the "Classpath" exception as provided
  9  * by Oracle in the LICENSE file that accompanied this code.
 10  *
 11  * This code is distributed in the hope that it will be useful, but WITHOUT
 12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 14  * version 2 for more details (a copy is included in the LICENSE file that
 15  * accompanied this code).
 16  *
 17  * You should have received a copy of the GNU General Public License version
 18  * 2 along with this work; if not, write to the Free Software Foundation,
 19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 20  *
 21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 22  * or visit www.oracle.com if you need additional information or have any
 23  * questions.
 24  */
 25 
 26 package java.nio.channels;
 27 
 28 import java.io.IOException;
 29 import java.net.NetPermission;
 30 import java.net.ProtocolFamily;
 31 import java.net.ServerSocket;
 32 import java.net.SocketOption;
 33 import java.net.SocketAddress;
 34 import java.net.UnixDomainSocketAddress;
 35 import java.nio.channels.spi.AbstractSelectableChannel;
 36 import java.nio.channels.spi.SelectorProvider;
 37 import static java.util.Objects.requireNonNull;
 38 
 39 /**
 40  * A selectable channel for stream-oriented listening sockets.
 41  *
 42  * <p> A server-socket channel is created by invoking one of the {@code open}
 43  * methods of this class. The no-arg {@link #open() open} method opens a server-socket
 44  * channel for an <i>Internet protocol</i> socket. The {@link #open(ProtocolFamily)}
 45  * method is used to open a server-socket channel for a socket of a specified
 46  * protocol family. It is not possible to create a channel for an arbitrary,
 47  * pre-existing socket. A newly-created server-socket channel is open but not yet
 48  * bound. An attempt to invoke the {@link #accept() accept} method of an
 49  * unbound server-socket channel will cause a {@link NotYetBoundException}
 50  * to be thrown. A server-socket channel can be bound by invoking one of the
 51  * {@link #bind(java.net.SocketAddress, int) bind} methods defined by this class.
 52  *
 53  * <p> Socket options are configured using the {@link #setOption(SocketOption,Object)
 54  * setOption} method. Server-socket channels for <i>Internet protocol</i> sockets
 55  * support the following options:
 56  * <blockquote>
 57  * <table class="striped">
 58  * <caption style="display:none">Socket options</caption>
 59  * <thead>
 60  *   <tr>
 61  *     <th scope="col">Option Name</th>
 62  *     <th scope="col">Description</th>
 63  *   </tr>
 64  * </thead>
 65  * <tbody>
 66  *   <tr>
 67  *     <th scope="row"> {@link java.net.StandardSocketOptions#SO_RCVBUF SO_RCVBUF} </th>
 68  *     <td> The size of the socket receive buffer </td>
 69  *   </tr>
 70  *   <tr>
 71  *     <th scope="row"> {@link java.net.StandardSocketOptions#SO_REUSEADDR SO_REUSEADDR} </th>
 72  *     <td> Re-use address </td>
 73  *   </tr>
 74  * </tbody>
 75  * </table>
 76  * </blockquote>
 77  *
 78  * <p> Server-socket channels for <i>Unix domain</i> sockets support:
 79  * <blockquote>
 80  * <table class="striped">
 81  * <caption style="display:none">Socket options</caption>
 82  * <thead>
 83  *   <tr>
 84  *     <th scope="col">Option Name</th>
 85  *     <th scope="col">Description</th>
 86  *   </tr>
 87  * </thead>
 88  * <tbody>
 89  *   <tr>
 90  *     <th scope="row"> {@link java.net.StandardSocketOptions#SO_RCVBUF SO_RCVBUF} </th>
 91  *     <td> The size of the socket receive buffer </td>
 92  *   </tr>
 93  * </tbody>
 94  * </table>
 95  * </blockquote>
 96  *
 97  * <p> Additional (implementation specific) options may also be supported.
 98  *
 99  * <p> Server-socket channels are safe for use by multiple concurrent threads.
100  * </p>
101  *
102  * @author Mark Reinhold
103  * @author JSR-51 Expert Group
104  * @since 1.4
105  */
106 
107 public abstract class ServerSocketChannel
108     extends AbstractSelectableChannel
109     implements NetworkChannel
110 {
111 
112     /**
113      * Initializes a new instance of this class.
114      *
115      * @param  provider
116      *         The provider that created this channel
117      */
118     protected ServerSocketChannel(SelectorProvider provider) {
119         super(provider);
120     }
121 
122     /**
123      * Opens a server-socket channel for an <i>Internet protocol</i> socket.
124      *
125      * <p> The new channel is created by invoking the {@link
126      * java.nio.channels.spi.SelectorProvider#openServerSocketChannel
127      * openServerSocketChannel} method of the system-wide default {@link
128      * java.nio.channels.spi.SelectorProvider} object.
129      *
130      * <p> The new channel's socket is initially unbound; it must be bound to a
131      * specific address via one of its socket's {@link
132      * java.net.ServerSocket#bind(SocketAddress) bind} methods before
133      * connections can be accepted.  </p>
134      *
135      * @return  A new socket channel
136      *
137      * @throws  IOException
138      *          If an I/O error occurs
139      *
140      * @see     <a href="../../net/doc-files/net-properties.html#Ipv4IPv6">
141      *          java.net.preferIPv4Stack</a> system property
142      */
143     public static ServerSocketChannel open() throws IOException {
144         return SelectorProvider.provider().openServerSocketChannel();
145     }
146 
147     /**
148      * Opens a server-socket channel. The {@code family} parameter specifies the
149      * {@link ProtocolFamily protocol family} of the channel's socket.
150      *
151      * <p> The new channel is created by invoking the {@link
152      * java.nio.channels.spi.SelectorProvider#openServerSocketChannel(ProtocolFamily)
153      * openServerSocketChannel(ProtocolFamily)} method of the system-wide default {@link
154      * java.nio.channels.spi.SelectorProvider} object. </p>
155      *
156      * @param   family
157      *          The protocol family
158      *
159      * @return  A new socket channel
160      *
161      * @throws  UnsupportedOperationException
162      *          If the specified protocol family is not supported. For example,
163      *          suppose the parameter is specified as {@link
164      *          java.net.StandardProtocolFamily#INET6 StandardProtocolFamily.INET6}
165      *          but IPv6 is not enabled on the platform.
166      * @throws  IOException
167      *          If an I/O error occurs
168      *
169      * @see     <a href="../../net/doc-files/net-properties.html#Ipv4IPv6">
170      *          java.net.preferIPv4Stack</a> system property
171      *
172      * @since 15
173      */
174     public static ServerSocketChannel open(ProtocolFamily family) throws IOException {
175         return SelectorProvider.provider().openServerSocketChannel(requireNonNull(family));
176     }
177 
178     /**
179      * Returns an operation set identifying this channel's supported
180      * operations.
181      *
182      * <p> Server-socket channels only support the accepting of new
183      * connections, so this method returns {@link SelectionKey#OP_ACCEPT}.
184      * </p>
185      *
186      * @return  The valid-operation set
187      */
188     public final int validOps() {
189         return SelectionKey.OP_ACCEPT;
190     }
191 
192 
193     // -- ServerSocket-specific operations --
194 
195     /**
196      * Binds the channel's socket to a local address and configures the socket
197      * to listen for connections.
198      *
199      * <p> An invocation of this method is equivalent to the following:
200      * <blockquote><pre>
201      * bind(local, 0);
202      * </pre></blockquote>
203      *
204      * @param   local
205      *          The local address to bind the socket, or {@code null} to bind
206      *          to an automatically assigned socket address
207      *
208      * @return  This channel
209      *
210      * @throws  AlreadyBoundException               {@inheritDoc}
211      * @throws  UnsupportedAddressTypeException     {@inheritDoc}
212      * @throws  ClosedChannelException              {@inheritDoc}
213      * @throws  IOException                         {@inheritDoc}
214      * @throws  SecurityException
215      *          If a security manager has been installed and it denies the
216      *          operation
217      *
218      * @since 1.7
219      */
220     public final ServerSocketChannel bind(SocketAddress local)
221         throws IOException
222     {
223         return bind(local, 0);
224     }
225 
226     /**
227      * Binds the channel's socket to a local address and configures the socket to
228      * listen for connections.
229      *
230      * <p> This method is used to establish an association between the socket and
231      * a local address. For <i>Internet protocol</i> sockets, once an association
232      * is established then the socket remains bound until the channel is closed.
233      *
234      * <p> The {@code backlog} parameter is the maximum number of pending
235      * connections on the socket. Its exact semantics are implementation specific.
236      * In particular, an implementation may impose a maximum length or may choose
237      * to ignore the parameter altogther. If the {@code backlog} parameter has
238      * the value {@code 0}, or a negative value, then an implementation specific
239      * default is used.
240      *
241      * @apiNote
242      * Binding a server socket channel for a <i>Unix Domain</i> socket, creates a
243      * file corresponding to the file path in the {@link UnixDomainSocketAddress}.
244      * This file persists after the channel is closed, and must be removed before
245      * another socket can bind to the same name. Binding to a {@code null} address
246      * causes the socket to be <i>automatically</i> bound to some unique file
247      * in a system temporary location. The associated socket file also persists
248      * after the channel is closed. Its name can be obtained from the channel's
249      * local socket address.
250      *
251      * @implNote
252      * Each platform enforces an implementation specific, maximum length for the
253      * name of a <i>Unix Domain</i> socket. This limitation is enforced when a
254      * channel is bound. The maximum length is typically close to and generally
255      * not less than 100 bytes.
256      *
257      * @param   local
258      *          The address to bind the socket, or {@code null} to bind to
259      *          an automatically assigned socket address
260      * @param   backlog
261      *          The maximum number of pending connections
262      *
263      * @return  This channel
264      *
265      * @throws  AlreadyBoundException
266      *          If the socket is already bound
267      * @throws  UnsupportedAddressTypeException
268      *          If the type of the given address is not supported
269      * @throws  ClosedChannelException
270      *          If this channel is closed
271      * @throws  IOException
272      *          If some other I/O error occurs
273      * @throws  SecurityException
274      *          If a security manager has been installed and its {@link
275      *          SecurityManager#checkListen checkListen} method denies
276      *          the operation for an <i>Internet protocol</i> socket address,
277      *          or for a <i>Unix domain</i> socket address if it denies
278      *          {@link NetPermission}{@code("accessUnixDomainSocket")}.
279      *
280      * @since 1.7
281      */
282     public abstract ServerSocketChannel bind(SocketAddress local, int backlog)
283         throws IOException;
284 
285     /**
286      * @throws  UnsupportedOperationException           {@inheritDoc}
287      * @throws  IllegalArgumentException                {@inheritDoc}
288      * @throws  ClosedChannelException                  {@inheritDoc}
289      * @throws  IOException                             {@inheritDoc}
290      *
291      * @since 1.7
292      */
293     public abstract <T> ServerSocketChannel setOption(SocketOption<T> name, T value)
294         throws IOException;
295 
296     /**
297      * Retrieves a server socket associated with this channel.
298      *
299      * <p> The returned object will not declare any public methods that are not
300      * declared in the {@link java.net.ServerSocket} class.  </p>
301      *
302      * @return  A server socket associated with this channel
303      *
304      * @throws  UnsupportedOperationException
305      *          If the channel's socket is not an <i>Internet protocol</i> socket
306      */
307     public abstract ServerSocket socket();
308 
309     /**
310      * Accepts a connection made to this channel's socket.
311      *
312      * <p> If this channel is in non-blocking mode then this method will
313      * immediately return {@code null} if there are no pending connections.
314      * Otherwise it will block indefinitely until a new connection is available
315      * or an I/O error occurs.
316      *
317      * <p> The socket channel returned by this method, if any, will be in
318      * blocking mode regardless of the blocking mode of this channel.
319      *
320      * <p> If bound to an <i>Internet protocol</i> socket address, this method
321      * performs exactly the same security checks as the {@link
322      * java.net.ServerSocket#accept accept} method of the {@link java.net.ServerSocket}
323      * class.  That is, if a security manager has been installed then for each
324      * new connection this method verifies that the address and port number
325      * of the connection's remote endpoint are permitted by the security
326      * manager's {@link java.lang.SecurityManager#checkAccept checkAccept}
327      * method. If bound to a <i>Unix Domain</i> socket address, this method checks
328      * {@link NetPermission}{@code ("accessUnixDomainSocket")}.
329      *
330      * @return  The socket channel for the new connection,
331      *          or {@code null} if this channel is in non-blocking mode
332      *          and no connection is available to be accepted
333      *
334      * @throws  ClosedChannelException
335      *          If this channel is closed
336      *
337      * @throws  AsynchronousCloseException
338      *          If another thread closes this channel
339      *          while the accept operation is in progress
340      *
341      * @throws  ClosedByInterruptException
342      *          If another thread interrupts the current thread
343      *          while the accept operation is in progress, thereby
344      *          closing the channel and setting the current thread's
345      *          interrupt status
346      *
347      * @throws  NotYetBoundException
348      *          If this channel's socket has not yet been bound
349      *
350      * @throws  SecurityException
351      *          If a security manager has been installed
352      *          and it does not permit access to the remote endpoint
353      *          of the new connection
354      *
355      * @throws  IOException
356      *          If some other I/O error occurs
357      */
358     public abstract SocketChannel accept() throws IOException;
359 
360     /**
361      * {@inheritDoc}
362      *
363      * If there is a security manager set, its {@code checkConnect} method is
364      * called with the local address and {@code -1} as its arguments to see
365      * if the operation is allowed. If the operation is not allowed,
366      * a {@code SocketAddress} representing the
367      * {@link java.net.InetAddress#getLoopbackAddress loopback} address and the
368      * local port of the channel's socket is returned.
369      *
370      * <p> Where the channel is bound to a <i>Unix Domain</i> socket address, the socket
371      * address is a {@link UnixDomainSocketAddress}. If there is a security manager
372      * set, its {@link SecurityManager#checkPermission(java.security.Permission)
373      * checkPermission} method is called with {@link NetPermission}{@code
374      * ("accessUnixDomainSocket")}. If the operation is not allowed an unnamed
375      * {@link UnixDomainSocketAddress} is returned.
376      *
377      * @return  The {@code SocketAddress} that the socket is bound to, or the
378      *          {@code SocketAddress} representing the loopback address or empty
379      *          path if denied by the security manager, or {@code null} if the
380      *          channel's socket is not bound
381      *
382      * @throws  ClosedChannelException     {@inheritDoc}
383      * @throws  IOException                {@inheritDoc}
384      */
385     @Override
386     public abstract SocketAddress getLocalAddress() throws IOException;
387 }