1 /*
   2  * Copyright (c) 1995, 2021, 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.net;
  27 
  28 import java.io.FileDescriptor;
  29 import java.io.IOException;
  30 import java.io.InterruptedIOException;
  31 import java.nio.channels.ServerSocketChannel;
  32 import java.util.Objects;
  33 import java.util.Set;
  34 import java.util.Collections;
  35 
  36 import sun.security.util.SecurityConstants;
  37 import sun.net.PlatformSocketImpl;
  38 
  39 /**
  40  * This class implements server sockets. A server socket waits for
  41  * requests to come in over the network. It performs some operation
  42  * based on that request, and then possibly returns a result to the requester.
  43  * <p>
  44  * The actual work of the server socket is performed by an instance
  45  * of the {@code SocketImpl} class.
  46  *
  47  * <p> The {@code ServerSocket} class defines convenience
  48  * methods to set and get several socket options. This class also
  49  * defines the {@link #setOption(SocketOption, Object) setOption}
  50  * and {@link #getOption(SocketOption) getOption} methods to set
  51  * and query socket options.
  52  * A {@code ServerSocket} supports the following options:
  53  * <blockquote>
  54  * <table class="striped">
  55  * <caption style="display:none">Socket options</caption>
  56  * <thead>
  57  *   <tr>
  58  *     <th scope="col">Option Name</th>
  59  *     <th scope="col">Description</th>
  60  *   </tr>
  61  * </thead>
  62  * <tbody>
  63  *   <tr>
  64  *     <th scope="row"> {@link java.net.StandardSocketOptions#SO_RCVBUF SO_RCVBUF} </th>
  65  *     <td> The size of the socket receive buffer </td>
  66  *   </tr>
  67  *   <tr>
  68  *     <th scope="row"> {@link java.net.StandardSocketOptions#SO_REUSEADDR SO_REUSEADDR} </th>
  69  *     <td> Re-use address </td>
  70  *   </tr>
  71  * </tbody>
  72  * </table>
  73  * </blockquote>
  74  * Additional (implementation specific) options may also be supported.
  75  *
  76  * @see     java.net.SocketImpl
  77  * @see     java.nio.channels.ServerSocketChannel
  78  * @since   1.0
  79  */
  80 public class ServerSocket implements java.io.Closeable {
  81     /**
  82      * Various states of this socket.
  83      */
  84     private boolean created = false;
  85     private boolean bound = false;
  86     private boolean closed = false;
  87     private Object closeLock = new Object();
  88 
  89     /**
  90      * The implementation of this Socket.
  91      */
  92     private SocketImpl impl;
  93 
  94     /**
  95      * Creates a server socket with a user-specified {@code SocketImpl}.
  96      *
  97      * @param      impl an instance of a SocketImpl to use on the ServerSocket.
  98      *
  99      * @throws     NullPointerException if impl is {@code null}.
 100      *
 101      * @throws     SecurityException if a security manager is set and
 102      *             its {@code checkPermission} method doesn't allow
 103      *             {@code NetPermission("setSocketImpl")}.
 104      * @since 12
 105      */
 106     protected ServerSocket(SocketImpl impl) {
 107         Objects.requireNonNull(impl);
 108         checkPermission();
 109         this.impl = impl;
 110     }
 111 
 112     private static Void checkPermission() {
 113         @SuppressWarnings("removal")
 114         SecurityManager sm = System.getSecurityManager();
 115         if (sm != null) {
 116             sm.checkPermission(SecurityConstants.SET_SOCKETIMPL_PERMISSION);
 117         }
 118         return null;
 119     }
 120 
 121     /**
 122      * Creates an unbound server socket.
 123      *
 124      * @throws    IOException IO error when opening the socket.
 125      * @revised 1.4
 126      */
 127     public ServerSocket() throws IOException {
 128         setImpl();
 129     }
 130 
 131     /**
 132      * Creates a server socket, bound to the specified port. A port number
 133      * of {@code 0} means that the port number is automatically
 134      * allocated, typically from an ephemeral port range. This port
 135      * number can then be retrieved by calling {@link #getLocalPort getLocalPort}.
 136      * <p>
 137      * The maximum queue length for incoming connection indications (a
 138      * request to connect) is set to {@code 50}. If a connection
 139      * indication arrives when the queue is full, the connection is refused.
 140      * <p>
 141      * If the application has specified a server socket implementation
 142      * factory, that factory's {@code createSocketImpl} method is called to
 143      * create the actual socket implementation. Otherwise a system-default
 144      * socket implementation is created.
 145      * <p>
 146      * If there is a security manager,
 147      * its {@code checkListen} method is called
 148      * with the {@code port} argument
 149      * as its argument to ensure the operation is allowed.
 150      * This could result in a SecurityException.
 151      *
 152      *
 153      * @param      port  the port number, or {@code 0} to use a port
 154      *                   number that is automatically allocated.
 155      *
 156      * @throws     IOException  if an I/O error occurs when opening the socket.
 157      * @throws     SecurityException
 158      * if a security manager exists and its {@code checkListen}
 159      * method doesn't allow the operation.
 160      * @throws     IllegalArgumentException if the port parameter is outside
 161      *             the specified range of valid port values, which is between
 162      *             0 and 65535, inclusive.
 163      *
 164      * @see        java.net.SocketImpl
 165      * @see        SecurityManager#checkListen
 166      */
 167     public ServerSocket(int port) throws IOException {
 168         this(port, 50, null);
 169     }
 170 
 171     /**
 172      * Creates a server socket and binds it to the specified local port
 173      * number, with the specified backlog.
 174      * A port number of {@code 0} means that the port number is
 175      * automatically allocated, typically from an ephemeral port range.
 176      * This port number can then be retrieved by calling
 177      * {@link #getLocalPort getLocalPort}.
 178      * <p>
 179      * The maximum queue length for incoming connection indications (a
 180      * request to connect) is set to the {@code backlog} parameter. If
 181      * a connection indication arrives when the queue is full, the
 182      * connection is refused.
 183      * <p>
 184      * If the application has specified a server socket implementation
 185      * factory, that factory's {@code createSocketImpl} method is called to
 186      * create the actual socket implementation. Otherwise a system-default
 187      * socket implementation is created.
 188      * <p>
 189      * If there is a security manager,
 190      * its {@code checkListen} method is called
 191      * with the {@code port} argument
 192      * as its argument to ensure the operation is allowed.
 193      * This could result in a SecurityException.
 194      *
 195      * The {@code backlog} argument is the requested maximum number of
 196      * pending connections on the socket. Its exact semantics are implementation
 197      * specific. In particular, an implementation may impose a maximum length
 198      * or may choose to ignore the parameter altogether. The value provided
 199      * should be greater than {@code 0}. If it is less than or equal to
 200      * {@code 0}, then an implementation specific default will be used.
 201      *
 202      * @param      port     the port number, or {@code 0} to use a port
 203      *                      number that is automatically allocated.
 204      * @param      backlog  requested maximum length of the queue of incoming
 205      *                      connections.
 206      *
 207      * @throws     IOException  if an I/O error occurs when opening the socket.
 208      * @throws     SecurityException
 209      * if a security manager exists and its {@code checkListen}
 210      * method doesn't allow the operation.
 211      * @throws     IllegalArgumentException if the port parameter is outside
 212      *             the specified range of valid port values, which is between
 213      *             0 and 65535, inclusive.
 214      *
 215      * @see        java.net.SocketImpl
 216      * @see        SecurityManager#checkListen
 217      */
 218     public ServerSocket(int port, int backlog) throws IOException {
 219         this(port, backlog, null);
 220     }
 221 
 222     /**
 223      * Create a server with the specified port, listen backlog, and
 224      * local IP address to bind to.  The <i>bindAddr</i> argument
 225      * can be used on a multi-homed host for a ServerSocket that
 226      * will only accept connect requests to one of its addresses.
 227      * If <i>bindAddr</i> is null, it will default accepting
 228      * connections on any/all local addresses.
 229      * The port must be between 0 and 65535, inclusive.
 230      * A port number of {@code 0} means that the port number is
 231      * automatically allocated, typically from an ephemeral port range.
 232      * This port number can then be retrieved by calling
 233      * {@link #getLocalPort getLocalPort}.
 234      *
 235      * <P>If there is a security manager, this method
 236      * calls its {@code checkListen} method
 237      * with the {@code port} argument
 238      * as its argument to ensure the operation is allowed.
 239      * This could result in a SecurityException.
 240      *
 241      * The {@code backlog} argument is the requested maximum number of
 242      * pending connections on the socket. Its exact semantics are implementation
 243      * specific. In particular, an implementation may impose a maximum length
 244      * or may choose to ignore the parameter altogether. The value provided
 245      * should be greater than {@code 0}. If it is less than or equal to
 246      * {@code 0}, then an implementation specific default will be used.
 247      *
 248      * @param port  the port number, or {@code 0} to use a port
 249      *              number that is automatically allocated.
 250      * @param backlog requested maximum length of the queue of incoming
 251      *                connections.
 252      * @param bindAddr the local InetAddress the server will bind to
 253      *
 254      * @throws  SecurityException if a security manager exists and
 255      * its {@code checkListen} method doesn't allow the operation.
 256      *
 257      * @throws  IOException if an I/O error occurs when opening the socket.
 258      * @throws     IllegalArgumentException if the port parameter is outside
 259      *             the specified range of valid port values, which is between
 260      *             0 and 65535, inclusive.
 261      *
 262      * @see SocketOptions
 263      * @see SocketImpl
 264      * @see SecurityManager#checkListen
 265      * @since   1.1
 266      */
 267     public ServerSocket(int port, int backlog, InetAddress bindAddr) throws IOException {
 268         setImpl();
 269         if (port < 0 || port > 0xFFFF)
 270             throw new IllegalArgumentException(
 271                        "Port value out of range: " + port);
 272         if (backlog < 1)
 273           backlog = 50;
 274         try {
 275             bind(new InetSocketAddress(bindAddr, port), backlog);
 276         } catch(SecurityException e) {
 277             close();
 278             throw e;
 279         } catch(IOException e) {
 280             close();
 281             throw e;
 282         }
 283     }
 284 
 285     /**
 286      * Get the {@code SocketImpl} attached to this socket, creating
 287      * it if necessary.
 288      *
 289      * @return  the {@code SocketImpl} attached to that ServerSocket.
 290      * @throws SocketException if creation fails.
 291      * @since 1.4
 292      */
 293     SocketImpl getImpl() throws SocketException {
 294         if (!created)
 295             createImpl();
 296         return impl;
 297     }
 298 
 299     private void setImpl() {
 300         SocketImplFactory factory = ServerSocket.factory;
 301         if (factory != null) {
 302             impl = factory.createSocketImpl();
 303         } else {
 304             impl = SocketImpl.createPlatformSocketImpl(true);
 305         }
 306     }
 307 
 308     /**
 309      * Creates the socket implementation.
 310      *
 311      * @throws SocketException if creation fails
 312      * @since 1.4
 313      */
 314     void createImpl() throws SocketException {
 315         if (impl == null)
 316             setImpl();
 317         try {
 318             impl.create(true);
 319             created = true;
 320         } catch (IOException e) {
 321             throw new SocketException(e.getMessage());
 322         }
 323     }
 324 
 325     /**
 326      *
 327      * Binds the {@code ServerSocket} to a specific address
 328      * (IP address and port number).
 329      * <p>
 330      * If the address is {@code null}, then the system will pick up
 331      * an ephemeral port and a valid local address to bind the socket.
 332      *
 333      * @param   endpoint        The IP address and port number to bind to.
 334      * @throws  IOException if the bind operation fails, or if the socket
 335      *                     is already bound.
 336      * @throws  SecurityException       if a {@code SecurityManager} is present and
 337      * its {@code checkListen} method doesn't allow the operation.
 338      * @throws  IllegalArgumentException if endpoint is a
 339      *          SocketAddress subclass not supported by this socket
 340      * @since 1.4
 341      */
 342     public void bind(SocketAddress endpoint) throws IOException {
 343         bind(endpoint, 50);
 344     }
 345 
 346     /**
 347      *
 348      * Binds the {@code ServerSocket} to a specific address
 349      * (IP address and port number).
 350      * <p>
 351      * If the address is {@code null}, then the system will pick up
 352      * an ephemeral port and a valid local address to bind the socket.
 353      * <P>
 354      * The {@code backlog} argument is the requested maximum number of
 355      * pending connections on the socket. Its exact semantics are implementation
 356      * specific. In particular, an implementation may impose a maximum length
 357      * or may choose to ignore the parameter altogether. The value provided
 358      * should be greater than {@code 0}. If it is less than or equal to
 359      * {@code 0}, then an implementation specific default will be used.
 360      * @param   endpoint        The IP address and port number to bind to.
 361      * @param   backlog         requested maximum length of the queue of
 362      *                          incoming connections.
 363      * @throws  IOException if the bind operation fails, or if the socket
 364      *                     is already bound.
 365      * @throws  SecurityException       if a {@code SecurityManager} is present and
 366      * its {@code checkListen} method doesn't allow the operation.
 367      * @throws  IllegalArgumentException if endpoint is a
 368      *          SocketAddress subclass not supported by this socket
 369      * @since 1.4
 370      */
 371     public void bind(SocketAddress endpoint, int backlog) throws IOException {
 372         if (isClosed())
 373             throw new SocketException("Socket is closed");
 374         if (isBound())
 375             throw new SocketException("Already bound");
 376         if (endpoint == null)
 377             endpoint = new InetSocketAddress(0);
 378         if (!(endpoint instanceof InetSocketAddress epoint))
 379             throw new IllegalArgumentException("Unsupported address type");
 380         if (epoint.isUnresolved())
 381             throw new SocketException("Unresolved address");
 382         if (backlog < 1)
 383           backlog = 50;
 384         try {
 385             @SuppressWarnings("removal")
 386             SecurityManager security = System.getSecurityManager();
 387             if (security != null)
 388                 security.checkListen(epoint.getPort());
 389             getImpl().bind(epoint.getAddress(), epoint.getPort());
 390             getImpl().listen(backlog);
 391             bound = true;
 392         } catch(SecurityException e) {
 393             bound = false;
 394             throw e;
 395         } catch(IOException e) {
 396             bound = false;
 397             throw e;
 398         }
 399     }
 400 
 401     /**
 402      * Returns the local address of this server socket.
 403      * <p>
 404      * If the socket was bound prior to being {@link #close closed},
 405      * then this method will continue to return the local address
 406      * after the socket is closed.
 407      * <p>
 408      * If there is a security manager set, its {@code checkConnect} method is
 409      * called with the local address and {@code -1} as its arguments to see
 410      * if the operation is allowed. If the operation is not allowed,
 411      * the {@link InetAddress#getLoopbackAddress loopback} address is returned.
 412      *
 413      * @return  the address to which this socket is bound,
 414      *          or the loopback address if denied by the security manager,
 415      *          or {@code null} if the socket is unbound.
 416      *
 417      * @see SecurityManager#checkConnect
 418      */
 419     public InetAddress getInetAddress() {
 420         if (!isBound())
 421             return null;
 422         try {
 423             InetAddress in = getImpl().getInetAddress();
 424             @SuppressWarnings("removal")
 425             SecurityManager sm = System.getSecurityManager();
 426             if (sm != null)
 427                 sm.checkConnect(in.getHostAddress(), -1);
 428             return in;
 429         } catch (SecurityException e) {
 430             return InetAddress.getLoopbackAddress();
 431         } catch (SocketException e) {
 432             // nothing
 433             // If we're bound, the impl has been created
 434             // so we shouldn't get here
 435         }
 436         return null;
 437     }
 438 
 439     /**
 440      * Returns the port number on which this socket is listening.
 441      * <p>
 442      * If the socket was bound prior to being {@link #close closed},
 443      * then this method will continue to return the port number
 444      * after the socket is closed.
 445      *
 446      * @return  the port number to which this socket is listening or
 447      *          -1 if the socket is not bound yet.
 448      */
 449     public int getLocalPort() {
 450         if (!isBound())
 451             return -1;
 452         try {
 453             return getImpl().getLocalPort();
 454         } catch (SocketException e) {
 455             // nothing
 456             // If we're bound, the impl has been created
 457             // so we shouldn't get here
 458         }
 459         return -1;
 460     }
 461 
 462     /**
 463      * Returns the address of the endpoint this socket is bound to.
 464      * <p>
 465      * If the socket was bound prior to being {@link #close closed},
 466      * then this method will continue to return the address of the endpoint
 467      * after the socket is closed.
 468      * <p>
 469      * If there is a security manager set, its {@code checkConnect} method is
 470      * called with the local address and {@code -1} as its arguments to see
 471      * if the operation is allowed. If the operation is not allowed,
 472      * a {@code SocketAddress} representing the
 473      * {@link InetAddress#getLoopbackAddress loopback} address and the local
 474      * port to which the socket is bound is returned.
 475      *
 476      * @return a {@code SocketAddress} representing the local endpoint of
 477      *         this socket, or a {@code SocketAddress} representing the
 478      *         loopback address if denied by the security manager,
 479      *         or {@code null} if the socket is not bound yet.
 480      *
 481      * @see #getInetAddress()
 482      * @see #getLocalPort()
 483      * @see #bind(SocketAddress)
 484      * @see SecurityManager#checkConnect
 485      * @since 1.4
 486      */

 487     public SocketAddress getLocalSocketAddress() {
 488         if (!isBound())
 489             return null;
 490         return new InetSocketAddress(getInetAddress(), getLocalPort());
 491     }
 492 
 493     /**
 494      * Listens for a connection to be made to this socket and accepts
 495      * it. The method blocks until a connection is made.
 496      *
 497      * <p> For the system-default socket implementation at least, if a
 498      * {@linkplain Thread#isVirtual() virtual thread} blocked in {@code accept}
 499      * is {@linkplain Thread#interrupt() interrupted} then the socket is closed
 500      * and {@link SocketException} is thrown with the interrupt status set.
 501      *
 502      * <p> A new Socket {@code s} is created and, if there
 503      * is a security manager,
 504      * the security manager's {@code checkAccept} method is called
 505      * with {@code s.getInetAddress().getHostAddress()} and
 506      * {@code s.getPort()}
 507      * as its arguments to ensure the operation is allowed.
 508      * This could result in a SecurityException.
 509      *
 510      * @implNote
 511      * An instance of this class using a system-default {@code SocketImpl}
 512      * accepts sockets with a {@code SocketImpl} of the same type, regardless
 513      * of the {@linkplain Socket#setSocketImplFactory(SocketImplFactory)
 514      * client socket implementation factory}, if one has been set.
 515      *
 516      * @throws     IOException  if an I/O error occurs when waiting for a
 517      *               connection.
 518      * @throws     SecurityException  if a security manager exists and its
 519      *             {@code checkAccept} method doesn't allow the operation.
 520      * @throws     SocketTimeoutException if a timeout was previously set with setSoTimeout and
 521      *             the timeout has been reached.
 522      * @throws     java.nio.channels.IllegalBlockingModeException
 523      *             if this socket has an associated channel, the channel is in
 524      *             non-blocking mode, and there is no connection ready to be
 525      *             accepted
 526      *
 527      * @return the new Socket
 528      * @see SecurityManager#checkAccept
 529      * @revised 1.4
 530      */
 531     public Socket accept() throws IOException {
 532         if (isClosed())
 533             throw new SocketException("Socket is closed");
 534         if (!isBound())
 535             throw new SocketException("Socket is not bound yet");
 536         Socket s = new Socket((SocketImpl) null);
 537         implAccept(s);
 538         return s;
 539     }
 540 
 541     /**
 542      * Subclasses of ServerSocket use this method to override accept()
 543      * to return their own subclass of socket.  So a FooServerSocket
 544      * will typically hand this method a newly created, unbound, FooSocket.
 545      * On return from implAccept the FooSocket will be connected to a client.
 546      *
 547      * <p> The behavior of this method is unspecified when invoked with a
 548      * socket that is not newly created and unbound. Any socket options set
 549      * on the given socket prior to invoking this method may or may not be
 550      * preserved when the connection is accepted. It may not be possible to
 551      * accept a connection when this socket has a {@code SocketImpl} of one
 552      * type and the given socket has a {@code SocketImpl} of a completely
 553      * different type.
 554      *
 555      * @implNote
 556      * An instance of this class using a system-default {@code SocketImpl}
 557      * can accept a connection with a Socket using a {@code SocketImpl} of
 558      * the same type: {@code IOException} is thrown if the Socket is using
 559      * a custom {@code SocketImpl}. An instance of this class using a
 560      * custom {@code SocketImpl} cannot accept a connection with a Socket
 561      * using a system-default {@code SocketImpl}.
 562      *
 563      * @param s the Socket
 564      * @throws java.nio.channels.IllegalBlockingModeException
 565      *         if this socket has an associated channel,
 566      *         and the channel is in non-blocking mode
 567      * @throws IOException if an I/O error occurs when waiting
 568      *         for a connection, or if it is not possible for this socket
 569      *         to accept a connection with the given socket
 570      *
 571      * @since   1.1
 572      * @revised 1.4
 573      */
 574     protected final void implAccept(Socket s) throws IOException {
 575         SocketImpl si = s.impl;
 576 
 577         // Socket has no SocketImpl
 578         if (si == null) {
 579             si = implAccept();
 580             s.setImpl(si);
 581             s.postAccept();
 582             return;
 583         }
 584 
 585         // Socket has a SOCKS or HTTP SocketImpl, need delegate
 586         if (si instanceof DelegatingSocketImpl) {
 587             si = ((DelegatingSocketImpl) si).delegate();
 588             assert si instanceof PlatformSocketImpl;
 589         }
 590 
 591         // Accept connection with a platform or custom SocketImpl.
 592         // For the platform SocketImpl case:
 593         // - the connection is accepted with a new SocketImpl
 594         // - the SO_TIMEOUT socket option is copied to the new SocketImpl
 595         // - the Socket is connected to the new SocketImpl
 596         // - the existing/old SocketImpl is closed
 597         // For the custom SocketImpl case, the connection is accepted with the
 598         // existing custom SocketImpl.
 599         ensureCompatible(si);
 600         if (impl instanceof PlatformSocketImpl) {
 601             SocketImpl psi = platformImplAccept();
 602             si.copyOptionsTo(psi);
 603             s.setImpl(psi);
 604             si.closeQuietly();
 605         } else {
 606             s.impl = null; // temporarily break connection to impl
 607             try {
 608                 customImplAccept(si);
 609             } finally {
 610                 s.impl = si;  // restore connection to impl
 611             }
 612         }
 613         s.postAccept();
 614     }
 615 
 616     /**
 617      * Accepts a connection with a new SocketImpl.
 618      * @return the new SocketImpl
 619      */
 620     private SocketImpl implAccept() throws IOException {
 621         if (impl instanceof PlatformSocketImpl) {
 622             return platformImplAccept();
 623         } else {
 624             // custom server SocketImpl, client SocketImplFactory must be set
 625             SocketImplFactory factory = Socket.socketImplFactory();
 626             if (factory == null) {
 627                 throw new IOException("An instance of " + impl.getClass() +
 628                     " cannot accept connection with 'null' SocketImpl:" +
 629                     " client socket implementation factory not set");
 630             }
 631             SocketImpl si = factory.createSocketImpl();
 632             customImplAccept(si);
 633             return si;
 634         }
 635     }
 636 
 637     /**
 638      * Accepts a connection with a new platform SocketImpl.
 639      * @return the new platform SocketImpl
 640      */
 641     private SocketImpl platformImplAccept() throws IOException {
 642         assert impl instanceof PlatformSocketImpl;
 643 
 644         // create a new platform SocketImpl and accept the connection
 645         SocketImpl psi = SocketImpl.createPlatformSocketImpl(false);
 646         implAccept(psi);
 647         return psi;
 648     }
 649 
 650     /**
 651      * Accepts a new connection with the given custom SocketImpl.
 652      */
 653     private void customImplAccept(SocketImpl si) throws IOException {
 654         assert !(impl instanceof PlatformSocketImpl)
 655                 && !(si instanceof PlatformSocketImpl);
 656 
 657         si.reset();
 658         try {
 659             // custom SocketImpl may expect fd/address objects to be created
 660             si.fd = new FileDescriptor();
 661             si.address = new InetAddress();
 662             implAccept(si);
 663         } catch (Exception e) {
 664             si.reset();
 665             throw e;
 666         }
 667     }
 668 
 669     /**
 670      * Accepts a new connection so that the given SocketImpl is connected to
 671      * the peer. The SocketImpl and connection are closed if the connection is
 672      * denied by the security manager.
 673      * @throws IOException if an I/O error occurs
 674      * @throws SecurityException if the security manager's checkAccept method fails
 675      */
 676     private void implAccept(SocketImpl si) throws IOException {
 677         assert !(si instanceof DelegatingSocketImpl);
 678 
 679         // accept a connection
 680         try {
 681             impl.accept(si);
 682         } catch (SocketTimeoutException e) {
 683             throw e;
 684         } catch (InterruptedIOException e) {
 685             Thread thread = Thread.currentThread();
 686             if (thread.isVirtual() && thread.isInterrupted()) {
 687                 close();
 688                 throw new SocketException("Closed by interrupt");
 689             }
 690             throw e;
 691         }
 692 
 693         // check permission, close SocketImpl/connection if denied
 694         @SuppressWarnings("removal")
 695         SecurityManager sm = System.getSecurityManager();
 696         if (sm != null) {
 697             try {
 698                 sm.checkAccept(si.getInetAddress().getHostAddress(), si.getPort());
 699             } catch (SecurityException se) {
 700                 si.close();
 701                 throw se;
 702             }
 703         }
 704     }
 705 
 706     /**
 707      * Throws IOException if the server SocketImpl and the given client
 708      * SocketImpl are not both platform or custom SocketImpls.
 709      */
 710     private void ensureCompatible(SocketImpl si) throws IOException {
 711         if ((impl instanceof PlatformSocketImpl) != (si instanceof PlatformSocketImpl)) {
 712             throw new IOException("An instance of " + impl.getClass() +
 713                 " cannot accept a connection with an instance of " + si.getClass());
 714         }
 715     }
 716 
 717     /**
 718      * Closes this socket.
 719      *
 720      * Any thread currently blocked in {@link #accept()} will throw
 721      * a {@link SocketException}.
 722      *
 723      * <p> If this socket has an associated channel then the channel is closed
 724      * as well.
 725      *
 726      * @throws     IOException  if an I/O error occurs when closing the socket.
 727      * @revised 1.4
 728      */
 729     public void close() throws IOException {
 730         synchronized(closeLock) {
 731             if (isClosed())
 732                 return;
 733             if (created)
 734                 impl.close();
 735             closed = true;
 736         }
 737     }
 738 
 739     /**
 740      * Returns the unique {@link java.nio.channels.ServerSocketChannel} object
 741      * associated with this socket, if any.
 742      *
 743      * <p> A server socket will have a channel if, and only if, the channel
 744      * itself was created via the {@link
 745      * java.nio.channels.ServerSocketChannel#open ServerSocketChannel.open}
 746      * method.
 747      *
 748      * @return  the server-socket channel associated with this socket,
 749      *          or {@code null} if this socket was not created
 750      *          for a channel
 751      *
 752      * @since 1.4
 753      */
 754     public ServerSocketChannel getChannel() {
 755         return null;
 756     }
 757 
 758     /**
 759      * Returns the binding state of the ServerSocket.
 760      * <p>
 761      * If the socket was bound prior to being {@linkplain #close closed},
 762      * then this method will continue to return {@code true}
 763      * after the socket is closed.
 764      *
 765      * @return true if the ServerSocket successfully bound to an address
 766      * @since 1.4
 767      */
 768     public boolean isBound() {
 769         return bound;
 770     }
 771 
 772     /**
 773      * Returns the closed state of the ServerSocket.
 774      *
 775      * @return true if the socket has been closed
 776      * @since 1.4
 777      */
 778     public boolean isClosed() {
 779         synchronized(closeLock) {
 780             return closed;
 781         }
 782     }
 783 
 784     /**
 785      * Enable/disable {@link SocketOptions#SO_TIMEOUT SO_TIMEOUT} with the
 786      * specified timeout, in milliseconds.  With this option set to a positive
 787      * timeout value, a call to accept() for this ServerSocket
 788      * will block for only this amount of time.  If the timeout expires,
 789      * a <B>java.net.SocketTimeoutException</B> is raised, though the
 790      * ServerSocket is still valid. A timeout of zero is interpreted as an
 791      * infinite timeout.
 792      * The option <B>must</B> be enabled prior to entering the blocking
 793      * operation to have effect.
 794      *
 795      * @param timeout the specified timeout, in milliseconds
 796      * @throws  SocketException if there is an error in the underlying protocol,
 797      *          such as a TCP error
 798      * @throws  IllegalArgumentException  if {@code timeout} is negative
 799      * @since   1.1
 800      * @see #getSoTimeout()
 801      */
 802     public synchronized void setSoTimeout(int timeout) throws SocketException {
 803         if (isClosed())
 804             throw new SocketException("Socket is closed");
 805         if (timeout < 0)
 806             throw new IllegalArgumentException("timeout < 0");
 807         getImpl().setOption(SocketOptions.SO_TIMEOUT, timeout);
 808     }
 809 
 810     /**
 811      * Retrieve setting for {@link SocketOptions#SO_TIMEOUT SO_TIMEOUT}.
 812      * 0 returns implies that the option is disabled (i.e., timeout of infinity).
 813      * @return the {@link SocketOptions#SO_TIMEOUT SO_TIMEOUT} value
 814      * @throws    IOException if an I/O error occurs
 815      * @since   1.1
 816      * @see #setSoTimeout(int)
 817      */
 818     public synchronized int getSoTimeout() throws IOException {
 819         if (isClosed())
 820             throw new SocketException("Socket is closed");
 821         Object o = getImpl().getOption(SocketOptions.SO_TIMEOUT);
 822         /* extra type safety */
 823         if (o instanceof Integer) {
 824             return ((Integer) o).intValue();
 825         } else {
 826             return 0;
 827         }
 828     }
 829 
 830     /**
 831      * Enable/disable the {@link SocketOptions#SO_REUSEADDR SO_REUSEADDR}
 832      * socket option.
 833      * <p>
 834      * When a TCP connection is closed the connection may remain
 835      * in a timeout state for a period of time after the connection
 836      * is closed (typically known as the {@code TIME_WAIT} state
 837      * or {@code 2MSL} wait state).
 838      * For applications using a well known socket address or port
 839      * it may not be possible to bind a socket to the required
 840      * {@code SocketAddress} if there is a connection in the
 841      * timeout state involving the socket address or port.
 842      * <p>
 843      * Enabling {@link SocketOptions#SO_REUSEADDR SO_REUSEADDR} prior to
 844      * binding the socket using {@link #bind(SocketAddress)} allows the socket
 845      * to be bound even though a previous connection is in a timeout state.
 846      * <p>
 847      * When a {@code ServerSocket} is created the initial setting
 848      * of {@link SocketOptions#SO_REUSEADDR SO_REUSEADDR} is not defined.
 849      * Applications can use {@link #getReuseAddress()} to determine the initial
 850      * setting of {@link SocketOptions#SO_REUSEADDR SO_REUSEADDR}.
 851      * <p>
 852      * The behaviour when {@link SocketOptions#SO_REUSEADDR SO_REUSEADDR} is
 853      * enabled or disabled after a socket is bound (See {@link #isBound()})
 854      * is not defined.
 855      *
 856      * @param on  whether to enable or disable the socket option
 857      * @throws    SocketException if an error occurs enabling or
 858      *            disabling the {@link SocketOptions#SO_REUSEADDR SO_REUSEADDR}
 859      *            socket option, or the socket is closed.
 860      * @since 1.4
 861      * @see #getReuseAddress()
 862      * @see #bind(SocketAddress)
 863      * @see #isBound()
 864      * @see #isClosed()
 865      */
 866     public void setReuseAddress(boolean on) throws SocketException {
 867         if (isClosed())
 868             throw new SocketException("Socket is closed");
 869         getImpl().setOption(SocketOptions.SO_REUSEADDR, Boolean.valueOf(on));
 870     }
 871 
 872     /**
 873      * Tests if {@link SocketOptions#SO_REUSEADDR SO_REUSEADDR} is enabled.
 874      *
 875      * @return a {@code boolean} indicating whether or not
 876      *         {@link SocketOptions#SO_REUSEADDR SO_REUSEADDR} is enabled.
 877      * @throws    SocketException if there is an error
 878      * in the underlying protocol, such as a TCP error.
 879      * @since   1.4
 880      * @see #setReuseAddress(boolean)
 881      */
 882     public boolean getReuseAddress() throws SocketException {
 883         if (isClosed())
 884             throw new SocketException("Socket is closed");
 885         return ((Boolean) (getImpl().getOption(SocketOptions.SO_REUSEADDR))).booleanValue();
 886     }
 887 
 888     /**
 889      * Returns the implementation address and implementation port of
 890      * this socket as a {@code String}.
 891      * <p>
 892      * If there is a security manager set, and this socket is
 893      * {@linkplain #isBound bound}, its {@code checkConnect} method is
 894      * called with the local address and {@code -1} as its arguments to see
 895      * if the operation is allowed. If the operation is not allowed,
 896      * an {@code InetAddress} representing the
 897      * {@link InetAddress#getLoopbackAddress loopback} address is returned as
 898      * the implementation address.
 899      *
 900      * @return  a string representation of this socket.
 901      */
 902     @SuppressWarnings("removal")
 903     public String toString() {
 904         if (!isBound())
 905             return "ServerSocket[unbound]";
 906         InetAddress in;
 907         if (System.getSecurityManager() != null)
 908             in = getInetAddress();
 909         else
 910             in = impl.getInetAddress();
 911         return "ServerSocket[addr=" + in +
 912                 ",localport=" + impl.getLocalPort()  + "]";
 913     }
 914 
 915     /**
 916      * The factory for all server sockets.
 917      */
 918     private static volatile SocketImplFactory factory;
 919 
 920     /**
 921      * Sets the server socket implementation factory for the
 922      * application. The factory can be specified only once.
 923      * <p>
 924      * When an application creates a new server socket, the socket
 925      * implementation factory's {@code createSocketImpl} method is
 926      * called to create the actual socket implementation.
 927      * <p>
 928      * Passing {@code null} to the method is a no-op unless the factory
 929      * was already set.
 930      * <p>
 931      * If there is a security manager, this method first calls
 932      * the security manager's {@code checkSetFactory} method
 933      * to ensure the operation is allowed.
 934      * This could result in a SecurityException.
 935      *
 936      * @param      fac   the desired factory.
 937      * @throws     IOException  if an I/O error occurs when setting the
 938      *               socket factory.
 939      * @throws     SocketException  if the factory has already been defined.
 940      * @throws     SecurityException  if a security manager exists and its
 941      *             {@code checkSetFactory} method doesn't allow the operation.
 942      * @see        java.net.SocketImplFactory#createSocketImpl()
 943      * @see        SecurityManager#checkSetFactory
 944      * @deprecated Use a {@link javax.net.ServerSocketFactory} and subclass {@code ServerSocket}
 945      *    directly.
 946      *    <br> This method provided a way in early JDK releases to replace the
 947      *    system wide implementation of {@code ServerSocket}. It has been mostly
 948      *    obsolete since Java 1.4. If required, a {@code ServerSocket} can be
 949      *    created to use a custom implementation by extending {@code ServerSocket}
 950      *    and using the {@linkplain #ServerSocket(SocketImpl) protected
 951      *    constructor} that takes an {@linkplain SocketImpl implementation}
 952      *    as a parameter.
 953      */
 954     @Deprecated(since = "17")
 955     public static synchronized void setSocketFactory(SocketImplFactory fac) throws IOException {
 956         if (factory != null) {
 957             throw new SocketException("factory already defined");
 958         }
 959         @SuppressWarnings("removal")
 960         SecurityManager security = System.getSecurityManager();
 961         if (security != null) {
 962             security.checkSetFactory();
 963         }
 964         factory = fac;
 965     }
 966 
 967     /**
 968      * Sets a default proposed value for the
 969      * {@link SocketOptions#SO_RCVBUF SO_RCVBUF} option for sockets
 970      * accepted from this {@code ServerSocket}. The value actually set
 971      * in the accepted socket must be determined by calling
 972      * {@link Socket#getReceiveBufferSize()} after the socket
 973      * is returned by {@link #accept()}.
 974      * <p>
 975      * The value of {@link SocketOptions#SO_RCVBUF SO_RCVBUF} is used both to
 976      * set the size of the internal socket receive buffer, and to set the size
 977      * of the TCP receive window that is advertised to the remote peer.
 978      * <p>
 979      * It is possible to change the value subsequently, by calling
 980      * {@link Socket#setReceiveBufferSize(int)}. However, if the application
 981      * wishes to allow a receive window larger than 64K bytes, as defined by RFC1323
 982      * then the proposed value must be set in the ServerSocket <B>before</B>
 983      * it is bound to a local address. This implies, that the ServerSocket must be
 984      * created with the no-argument constructor, then setReceiveBufferSize() must
 985      * be called and lastly the ServerSocket is bound to an address by calling bind().
 986      * <p>
 987      * Failure to do this will not cause an error, and the buffer size may be set to the
 988      * requested value but the TCP receive window in sockets accepted from
 989      * this ServerSocket will be no larger than 64K bytes.
 990      *
 991      * @throws    SocketException if there is an error
 992      * in the underlying protocol, such as a TCP error.
 993      *
 994      * @param size the size to which to set the receive buffer
 995      * size. This value must be greater than 0.
 996      *
 997      * @throws    IllegalArgumentException if the
 998      * value is 0 or is negative.
 999      *
1000      * @since 1.4
1001      * @see #getReceiveBufferSize
1002      */
1003      public synchronized void setReceiveBufferSize (int size) throws SocketException {
1004         if (!(size > 0)) {
1005             throw new IllegalArgumentException("negative receive size");
1006         }
1007         if (isClosed())
1008             throw new SocketException("Socket is closed");
1009         getImpl().setOption(SocketOptions.SO_RCVBUF, size);
1010     }
1011 
1012     /**
1013      * Gets the value of the {@link SocketOptions#SO_RCVBUF SO_RCVBUF} option
1014      * for this {@code ServerSocket}, that is the proposed buffer size that
1015      * will be used for Sockets accepted from this {@code ServerSocket}.
1016      *
1017      * <p>Note, the value actually set in the accepted socket is determined by
1018      * calling {@link Socket#getReceiveBufferSize()}.
1019      * @return the value of the {@link SocketOptions#SO_RCVBUF SO_RCVBUF}
1020      *         option for this {@code Socket}.
1021      * @throws    SocketException if there is an error
1022      *            in the underlying protocol, such as a TCP error.
1023      * @see #setReceiveBufferSize(int)
1024      * @since 1.4
1025      */
1026     public synchronized int getReceiveBufferSize()
1027     throws SocketException{
1028         if (isClosed())
1029             throw new SocketException("Socket is closed");
1030         int result = 0;
1031         Object o = getImpl().getOption(SocketOptions.SO_RCVBUF);
1032         if (o instanceof Integer) {
1033             result = ((Integer)o).intValue();
1034         }
1035         return result;
1036     }
1037 
1038     /**
1039      * Sets performance preferences for this ServerSocket.
1040      *
1041      * <p> Sockets use the TCP/IP protocol by default.  Some implementations
1042      * may offer alternative protocols which have different performance
1043      * characteristics than TCP/IP.  This method allows the application to
1044      * express its own preferences as to how these tradeoffs should be made
1045      * when the implementation chooses from the available protocols.
1046      *
1047      * <p> Performance preferences are described by three integers
1048      * whose values indicate the relative importance of short connection time,
1049      * low latency, and high bandwidth.  The absolute values of the integers
1050      * are irrelevant; in order to choose a protocol the values are simply
1051      * compared, with larger values indicating stronger preferences.  If the
1052      * application prefers short connection time over both low latency and high
1053      * bandwidth, for example, then it could invoke this method with the values
1054      * {@code (1, 0, 0)}.  If the application prefers high bandwidth above low
1055      * latency, and low latency above short connection time, then it could
1056      * invoke this method with the values {@code (0, 1, 2)}.
1057      *
1058      * <p> Invoking this method after this socket has been bound
1059      * will have no effect. This implies that in order to use this capability
1060      * requires the socket to be created with the no-argument constructor.
1061      *
1062      * @param  connectionTime
1063      *         An {@code int} expressing the relative importance of a short
1064      *         connection time
1065      *
1066      * @param  latency
1067      *         An {@code int} expressing the relative importance of low
1068      *         latency
1069      *
1070      * @param  bandwidth
1071      *         An {@code int} expressing the relative importance of high
1072      *         bandwidth
1073      *
1074      * @since 1.5
1075      */
1076     public void setPerformancePreferences(int connectionTime,
1077                                           int latency,
1078                                           int bandwidth)
1079     {
1080         /* Not implemented yet */
1081     }
1082 
1083     /**
1084      * Sets the value of a socket option.
1085      *
1086      * @param <T> The type of the socket option value
1087      * @param name The socket option
1088      * @param value The value of the socket option. A value of {@code null}
1089      *              may be valid for some options.
1090      * @return this ServerSocket
1091      *
1092      * @throws UnsupportedOperationException if the server socket does not
1093      *         support the option.
1094      *
1095      * @throws IllegalArgumentException if the value is not valid for
1096      *         the option.
1097      *
1098      * @throws IOException if an I/O error occurs, or if the socket is closed.
1099      *
1100      * @throws NullPointerException if name is {@code null}
1101      *
1102      * @throws SecurityException if a security manager is set and if the socket
1103      *         option requires a security permission and if the caller does
1104      *         not have the required permission.
1105      *         {@link java.net.StandardSocketOptions StandardSocketOptions}
1106      *         do not require any security permission.
1107      *
1108      * @since 9
1109      */
1110     public <T> ServerSocket setOption(SocketOption<T> name, T value)
1111         throws IOException
1112     {
1113         Objects.requireNonNull(name);
1114         if (isClosed())
1115             throw new SocketException("Socket is closed");
1116         getImpl().setOption(name, value);
1117         return this;
1118     }
1119 
1120     /**
1121      * Returns the value of a socket option.
1122      *
1123      * @param <T> The type of the socket option value
1124      * @param name The socket option
1125      *
1126      * @return The value of the socket option.
1127      *
1128      * @throws UnsupportedOperationException if the server socket does not
1129      *         support the option.
1130      *
1131      * @throws IOException if an I/O error occurs, or if the socket is closed.
1132      *
1133      * @throws NullPointerException if name is {@code null}
1134      *
1135      * @throws SecurityException if a security manager is set and if the socket
1136      *         option requires a security permission and if the caller does
1137      *         not have the required permission.
1138      *         {@link java.net.StandardSocketOptions StandardSocketOptions}
1139      *         do not require any security permission.
1140      *
1141      * @since 9
1142      */
1143     public <T> T getOption(SocketOption<T> name) throws IOException {
1144         Objects.requireNonNull(name);
1145         if (isClosed())
1146             throw new SocketException("Socket is closed");
1147         return getImpl().getOption(name);
1148     }
1149 
1150     // cache of unmodifiable impl options. Possibly set racy, in impl we trust
1151     private volatile Set<SocketOption<?>> options;
1152 
1153     /**
1154      * Returns a set of the socket options supported by this server socket.
1155      *
1156      * This method will continue to return the set of options even after
1157      * the socket has been closed.
1158      *
1159      * @return A set of the socket options supported by this socket. This set
1160      *         may be empty if the socket's SocketImpl cannot be created.
1161      *
1162      * @since 9
1163      */
1164     public Set<SocketOption<?>> supportedOptions() {
1165         Set<SocketOption<?>> so = options;
1166         if (so != null)
1167             return so;
1168 
1169         try {
1170             SocketImpl impl = getImpl();
1171             options = Collections.unmodifiableSet(impl.supportedOptions());
1172         } catch (IOException e) {
1173             options = Collections.emptySet();
1174         }
1175         return options;
1176     }
1177 }
--- EOF ---