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.nio.channels.ServerSocketChannel;
  31 import java.util.Objects;
  32 import java.util.Set;
  33 import java.util.Collections;
  34 
  35 import sun.security.util.SecurityConstants;
  36 import sun.net.PlatformSocketImpl;
  37 
  38 /**
  39  * This class implements server sockets. A server socket waits for
  40  * requests to come in over the network. It performs some operation
  41  * based on that request, and then possibly returns a result to the requester.
  42  * <p>
  43  * The actual work of the server socket is performed by an instance
  44  * of the {@code SocketImpl} class.
  45  *
  46  * <p> The {@code ServerSocket} class defines convenience
  47  * methods to set and get several socket options. This class also
  48  * defines the {@link #setOption(SocketOption, Object) setOption}
  49  * and {@link #getOption(SocketOption) getOption} methods to set
  50  * and query socket options.
  51  * A {@code ServerSocket} supports the following options:
  52  * <blockquote>
  53  * <table class="striped">
  54  * <caption style="display:none">Socket options</caption>
  55  * <thead>
  56  *   <tr>
  57  *     <th scope="col">Option Name</th>
  58  *     <th scope="col">Description</th>
  59  *   </tr>
  60  * </thead>
  61  * <tbody>
  62  *   <tr>
  63  *     <th scope="row"> {@link java.net.StandardSocketOptions#SO_RCVBUF SO_RCVBUF} </th>
  64  *     <td> The size of the socket receive buffer </td>
  65  *   </tr>
  66  *   <tr>
  67  *     <th scope="row"> {@link java.net.StandardSocketOptions#SO_REUSEADDR SO_REUSEADDR} </th>
  68  *     <td> Re-use address </td>
  69  *   </tr>
  70  * </tbody>
  71  * </table>
  72  * </blockquote>
  73  * Additional (implementation specific) options may also be supported.
  74  *
  75  * @see     java.net.SocketImpl
  76  * @see     java.nio.channels.ServerSocketChannel
  77  * @since   1.0
  78  */
  79 public class ServerSocket implements java.io.Closeable {
  80     /**
  81      * Various states of this socket.
  82      */
  83     private boolean created = false;
  84     private boolean bound = false;
  85     private boolean closed = false;
  86     private Object closeLock = new Object();
  87 
  88     /**
  89      * The implementation of this Socket.
  90      */
  91     private SocketImpl impl;
  92 
  93     /**
  94      * Creates a server socket with a user-specified {@code SocketImpl}.
  95      *
  96      * @param      impl an instance of a SocketImpl to use on the ServerSocket.
  97      *
  98      * @throws     NullPointerException if impl is {@code null}.
  99      *
 100      * @throws     SecurityException if a security manager is set and
 101      *             its {@code checkPermission} method doesn't allow
 102      *             {@code NetPermission("setSocketImpl")}.
 103      * @since 12
 104      */
 105     protected ServerSocket(SocketImpl impl) {
 106         Objects.requireNonNull(impl);
 107         checkPermission();
 108         this.impl = impl;
 109     }
 110 
 111     private static Void checkPermission() {
 112         @SuppressWarnings("removal")
 113         SecurityManager sm = System.getSecurityManager();
 114         if (sm != null) {
 115             sm.checkPermission(SecurityConstants.SET_SOCKETIMPL_PERMISSION);
 116         }
 117         return null;
 118     }
 119 
 120     /**
 121      * Creates an unbound server socket.
 122      *
 123      * @throws    IOException IO error when opening the socket.
 124      * @revised 1.4
 125      */
 126     public ServerSocket() throws IOException {
 127         setImpl();
 128     }
 129 
 130     /**
 131      * Creates a server socket, bound to the specified port. A port number
 132      * of {@code 0} means that the port number is automatically
 133      * allocated, typically from an ephemeral port range. This port
 134      * number can then be retrieved by calling {@link #getLocalPort getLocalPort}.
 135      * <p>
 136      * The maximum queue length for incoming connection indications (a
 137      * request to connect) is set to {@code 50}. If a connection
 138      * indication arrives when the queue is full, the connection is refused.
 139      * <p>
 140      * If the application has specified a server socket implementation
 141      * factory, that factory's {@code createSocketImpl} method is called to
 142      * create the actual socket implementation. Otherwise a system-default
 143      * socket implementation is created.
 144      * <p>
 145      * If there is a security manager,
 146      * its {@code checkListen} method is called
 147      * with the {@code port} argument
 148      * as its argument to ensure the operation is allowed.
 149      * This could result in a SecurityException.
 150      *
 151      *
 152      * @param      port  the port number, or {@code 0} to use a port
 153      *                   number that is automatically allocated.
 154      *
 155      * @throws     IOException  if an I/O error occurs when opening the socket.
 156      * @throws     SecurityException
 157      * if a security manager exists and its {@code checkListen}
 158      * method doesn't allow the operation.
 159      * @throws     IllegalArgumentException if the port parameter is outside
 160      *             the specified range of valid port values, which is between
 161      *             0 and 65535, inclusive.
 162      *
 163      * @see        java.net.SocketImpl
 164      * @see        SecurityManager#checkListen
 165      */
 166     public ServerSocket(int port) throws IOException {
 167         this(port, 50, null);
 168     }
 169 
 170     /**
 171      * Creates a server socket and binds it to the specified local port
 172      * number, with the specified backlog.
 173      * A port number of {@code 0} means that the port number is
 174      * automatically allocated, typically from an ephemeral port range.
 175      * This port number can then be retrieved by calling
 176      * {@link #getLocalPort getLocalPort}.
 177      * <p>
 178      * The maximum queue length for incoming connection indications (a
 179      * request to connect) is set to the {@code backlog} parameter. If
 180      * a connection indication arrives when the queue is full, the
 181      * connection is refused.
 182      * <p>
 183      * If the application has specified a server socket implementation
 184      * factory, that factory's {@code createSocketImpl} method is called to
 185      * create the actual socket implementation. Otherwise a system-default
 186      * socket implementation is created.
 187      * <p>
 188      * If there is a security manager,
 189      * its {@code checkListen} method is called
 190      * with the {@code port} argument
 191      * as its argument to ensure the operation is allowed.
 192      * This could result in a SecurityException.
 193      *
 194      * The {@code backlog} argument is the requested maximum number of
 195      * pending connections on the socket. Its exact semantics are implementation
 196      * specific. In particular, an implementation may impose a maximum length
 197      * or may choose to ignore the parameter altogether. The value provided
 198      * should be greater than {@code 0}. If it is less than or equal to
 199      * {@code 0}, then an implementation specific default will be used.
 200      *
 201      * @param      port     the port number, or {@code 0} to use a port
 202      *                      number that is automatically allocated.
 203      * @param      backlog  requested maximum length of the queue of incoming
 204      *                      connections.
 205      *
 206      * @throws     IOException  if an I/O error occurs when opening the socket.
 207      * @throws     SecurityException
 208      * if a security manager exists and its {@code checkListen}
 209      * method doesn't allow the operation.
 210      * @throws     IllegalArgumentException if the port parameter is outside
 211      *             the specified range of valid port values, which is between
 212      *             0 and 65535, inclusive.
 213      *
 214      * @see        java.net.SocketImpl
 215      * @see        SecurityManager#checkListen
 216      */
 217     public ServerSocket(int port, int backlog) throws IOException {
 218         this(port, backlog, null);
 219     }
 220 
 221     /**
 222      * Create a server with the specified port, listen backlog, and
 223      * local IP address to bind to.  The <i>bindAddr</i> argument
 224      * can be used on a multi-homed host for a ServerSocket that
 225      * will only accept connect requests to one of its addresses.
 226      * If <i>bindAddr</i> is null, it will default accepting
 227      * connections on any/all local addresses.
 228      * The port must be between 0 and 65535, inclusive.
 229      * A port number of {@code 0} means that the port number is
 230      * automatically allocated, typically from an ephemeral port range.
 231      * This port number can then be retrieved by calling
 232      * {@link #getLocalPort getLocalPort}.
 233      *
 234      * <P>If there is a security manager, this method
 235      * calls its {@code checkListen} method
 236      * with the {@code port} argument
 237      * as its argument to ensure the operation is allowed.
 238      * This could result in a SecurityException.
 239      *
 240      * The {@code backlog} argument is the requested maximum number of
 241      * pending connections on the socket. Its exact semantics are implementation
 242      * specific. In particular, an implementation may impose a maximum length
 243      * or may choose to ignore the parameter altogether. The value provided
 244      * should be greater than {@code 0}. If it is less than or equal to
 245      * {@code 0}, then an implementation specific default will be used.
 246      *
 247      * @param port  the port number, or {@code 0} to use a port
 248      *              number that is automatically allocated.
 249      * @param backlog requested maximum length of the queue of incoming
 250      *                connections.
 251      * @param bindAddr the local InetAddress the server will bind to
 252      *
 253      * @throws  SecurityException if a security manager exists and
 254      * its {@code checkListen} method doesn't allow the operation.
 255      *
 256      * @throws  IOException if an I/O error occurs when opening the socket.
 257      * @throws     IllegalArgumentException if the port parameter is outside
 258      *             the specified range of valid port values, which is between
 259      *             0 and 65535, inclusive.
 260      *
 261      * @see SocketOptions
 262      * @see SocketImpl
 263      * @see SecurityManager#checkListen
 264      * @since   1.1
 265      */
 266     public ServerSocket(int port, int backlog, InetAddress bindAddr) throws IOException {
 267         setImpl();
 268         if (port < 0 || port > 0xFFFF)
 269             throw new IllegalArgumentException(
 270                        "Port value out of range: " + port);
 271         if (backlog < 1)
 272           backlog = 50;
 273         try {
 274             bind(new InetSocketAddress(bindAddr, port), backlog);
 275         } catch(SecurityException e) {
 276             close();
 277             throw e;
 278         } catch(IOException e) {
 279             close();
 280             throw e;
 281         }
 282     }
 283 
 284     /**
 285      * Get the {@code SocketImpl} attached to this socket, creating
 286      * it if necessary.
 287      *
 288      * @return  the {@code SocketImpl} attached to that ServerSocket.
 289      * @throws SocketException if creation fails.
 290      * @since 1.4
 291      */
 292     SocketImpl getImpl() throws SocketException {
 293         if (!created)
 294             createImpl();
 295         return impl;
 296     }
 297 
 298     private void setImpl() {
 299         SocketImplFactory factory = ServerSocket.factory;
 300         if (factory != null) {
 301             impl = factory.createSocketImpl();
 302         } else {
 303             impl = SocketImpl.createPlatformSocketImpl(true);
 304         }
 305     }
 306 
 307     /**
 308      * Creates the socket implementation.
 309      *
 310      * @throws SocketException if creation fails
 311      * @since 1.4
 312      */
 313     void createImpl() throws SocketException {
 314         if (impl == null)
 315             setImpl();
 316         try {
 317             impl.create(true);
 318             created = true;
 319         } catch (IOException e) {
 320             throw new SocketException(e.getMessage());
 321         }
 322     }
 323 
 324     /**
 325      *
 326      * Binds the {@code ServerSocket} to a specific address
 327      * (IP address and port number).
 328      * <p>
 329      * If the address is {@code null}, then the system will pick up
 330      * an ephemeral port and a valid local address to bind the socket.
 331      *
 332      * @param   endpoint        The IP address and port number to bind to.
 333      * @throws  IOException if the bind operation fails, or if the socket
 334      *                     is already bound.
 335      * @throws  SecurityException       if a {@code SecurityManager} is present and
 336      * its {@code checkListen} method doesn't allow the operation.
 337      * @throws  IllegalArgumentException if endpoint is a
 338      *          SocketAddress subclass not supported by this socket
 339      * @since 1.4
 340      */
 341     public void bind(SocketAddress endpoint) throws IOException {
 342         bind(endpoint, 50);
 343     }
 344 
 345     /**
 346      *
 347      * Binds the {@code ServerSocket} to a specific address
 348      * (IP address and port number).
 349      * <p>
 350      * If the address is {@code null}, then the system will pick up
 351      * an ephemeral port and a valid local address to bind the socket.
 352      * <P>
 353      * The {@code backlog} argument is the requested maximum number of
 354      * pending connections on the socket. Its exact semantics are implementation
 355      * specific. In particular, an implementation may impose a maximum length
 356      * or may choose to ignore the parameter altogether. The value provided
 357      * should be greater than {@code 0}. If it is less than or equal to
 358      * {@code 0}, then an implementation specific default will be used.
 359      * @param   endpoint        The IP address and port number to bind to.
 360      * @param   backlog         requested maximum length of the queue of
 361      *                          incoming connections.
 362      * @throws  IOException if the bind operation fails, or if the socket
 363      *                     is already bound.
 364      * @throws  SecurityException       if a {@code SecurityManager} is present and
 365      * its {@code checkListen} method doesn't allow the operation.
 366      * @throws  IllegalArgumentException if endpoint is a
 367      *          SocketAddress subclass not supported by this socket
 368      * @since 1.4
 369      */
 370     public void bind(SocketAddress endpoint, int backlog) throws IOException {
 371         if (isClosed())
 372             throw new SocketException("Socket is closed");
 373         if (isBound())
 374             throw new SocketException("Already bound");
 375         if (endpoint == null)
 376             endpoint = new InetSocketAddress(0);
 377         if (!(endpoint instanceof InetSocketAddress epoint))
 378             throw new IllegalArgumentException("Unsupported address type");
 379         if (epoint.isUnresolved())
 380             throw new SocketException("Unresolved address");
 381         if (backlog < 1)
 382           backlog = 50;
 383         try {
 384             @SuppressWarnings("removal")
 385             SecurityManager security = System.getSecurityManager();
 386             if (security != null)
 387                 security.checkListen(epoint.getPort());
 388             getImpl().bind(epoint.getAddress(), epoint.getPort());
 389             getImpl().listen(backlog);
 390             bound = true;
 391         } catch(SecurityException e) {
 392             bound = false;
 393             throw e;
 394         } catch(IOException e) {
 395             bound = false;
 396             throw e;
 397         }
 398     }
 399 
 400     /**
 401      * Returns the local address of this server socket.
 402      * <p>
 403      * If the socket was bound prior to being {@link #close closed},
 404      * then this method will continue to return the local address
 405      * after the socket is closed.
 406      * <p>
 407      * If there is a security manager set, its {@code checkConnect} method is
 408      * called with the local address and {@code -1} as its arguments to see
 409      * if the operation is allowed. If the operation is not allowed,
 410      * the {@link InetAddress#getLoopbackAddress loopback} address is returned.
 411      *
 412      * @return  the address to which this socket is bound,
 413      *          or the loopback address if denied by the security manager,
 414      *          or {@code null} if the socket is unbound.
 415      *
 416      * @see SecurityManager#checkConnect
 417      */
 418     public InetAddress getInetAddress() {
 419         if (!isBound())
 420             return null;
 421         try {
 422             InetAddress in = getImpl().getInetAddress();
 423             @SuppressWarnings("removal")
 424             SecurityManager sm = System.getSecurityManager();
 425             if (sm != null)
 426                 sm.checkConnect(in.getHostAddress(), -1);
 427             return in;
 428         } catch (SecurityException e) {
 429             return InetAddress.getLoopbackAddress();
 430         } catch (SocketException e) {
 431             // nothing
 432             // If we're bound, the impl has been created
 433             // so we shouldn't get here
 434         }
 435         return null;
 436     }
 437 
 438     /**
 439      * Returns the port number on which this socket is listening.
 440      * <p>
 441      * If the socket was bound prior to being {@link #close closed},
 442      * then this method will continue to return the port number
 443      * after the socket is closed.
 444      *
 445      * @return  the port number to which this socket is listening or
 446      *          -1 if the socket is not bound yet.
 447      */
 448     public int getLocalPort() {
 449         if (!isBound())
 450             return -1;
 451         try {
 452             return getImpl().getLocalPort();
 453         } catch (SocketException e) {
 454             // nothing
 455             // If we're bound, the impl has been created
 456             // so we shouldn't get here
 457         }
 458         return -1;
 459     }
 460 
 461     /**
 462      * Returns the address of the endpoint this socket is bound to.
 463      * <p>
 464      * If the socket was bound prior to being {@link #close closed},
 465      * then this method will continue to return the address of the endpoint
 466      * after the socket is closed.
 467      * <p>
 468      * If there is a security manager set, its {@code checkConnect} method is
 469      * called with the local address and {@code -1} as its arguments to see
 470      * if the operation is allowed. If the operation is not allowed,
 471      * a {@code SocketAddress} representing the
 472      * {@link InetAddress#getLoopbackAddress loopback} address and the local
 473      * port to which the socket is bound is returned.
 474      *
 475      * @return a {@code SocketAddress} representing the local endpoint of
 476      *         this socket, or a {@code SocketAddress} representing the
 477      *         loopback address if denied by the security manager,
 478      *         or {@code null} if the socket is not bound yet.
 479      *
 480      * @see #getInetAddress()
 481      * @see #getLocalPort()
 482      * @see #bind(SocketAddress)
 483      * @see SecurityManager#checkConnect
 484      * @since 1.4
 485      */
 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>A new Socket {@code s} is created and, if there
 498      * is a security manager,
 499      * the security manager's {@code checkAccept} method is called
 500      * with {@code s.getInetAddress().getHostAddress()} and
 501      * {@code s.getPort()}
 502      * as its arguments to ensure the operation is allowed.
 503      * This could result in a SecurityException.
 504      *
 505      * @implNote
 506      * An instance of this class using a system-default {@code SocketImpl}
 507      * accepts sockets with a {@code SocketImpl} of the same type, regardless
 508      * of the {@linkplain Socket#setSocketImplFactory(SocketImplFactory)
 509      * client socket implementation factory}, if one has been set.
 510      *
 511      * @throws     IOException  if an I/O error occurs when waiting for a
 512      *               connection.
 513      * @throws     SecurityException  if a security manager exists and its
 514      *             {@code checkAccept} method doesn't allow the operation.
 515      * @throws     SocketTimeoutException if a timeout was previously set with setSoTimeout and
 516      *             the timeout has been reached.
 517      * @throws     java.nio.channels.IllegalBlockingModeException
 518      *             if this socket has an associated channel, the channel is in
 519      *             non-blocking mode, and there is no connection ready to be
 520      *             accepted
 521      *
 522      * @return the new Socket
 523      * @see SecurityManager#checkAccept
 524      * @revised 1.4
 525      */
 526     public Socket accept() throws IOException {
 527         if (isClosed())
 528             throw new SocketException("Socket is closed");
 529         if (!isBound())
 530             throw new SocketException("Socket is not bound yet");
 531         Socket s = new Socket((SocketImpl) null);
 532         implAccept(s);
 533         return s;
 534     }
 535 
 536     /**
 537      * Subclasses of ServerSocket use this method to override accept()
 538      * to return their own subclass of socket.  So a FooServerSocket
 539      * will typically hand this method a newly created, unbound, FooSocket.
 540      * On return from implAccept the FooSocket will be connected to a client.
 541      *
 542      * <p> The behavior of this method is unspecified when invoked with a
 543      * socket that is not newly created and unbound. Any socket options set
 544      * on the given socket prior to invoking this method may or may not be
 545      * preserved when the connection is accepted. It may not be possible to
 546      * accept a connection when this socket has a {@code SocketImpl} of one
 547      * type and the given socket has a {@code SocketImpl} of a completely
 548      * different type.
 549      *
 550      * @implNote
 551      * An instance of this class using a system-default {@code SocketImpl}
 552      * can accept a connection with a Socket using a {@code SocketImpl} of
 553      * the same type: {@code IOException} is thrown if the Socket is using
 554      * a custom {@code SocketImpl}. An instance of this class using a
 555      * custom {@code SocketImpl} cannot accept a connection with a Socket
 556      * using a system-default {@code SocketImpl}.
 557      *
 558      * @param s the Socket
 559      * @throws java.nio.channels.IllegalBlockingModeException
 560      *         if this socket has an associated channel,
 561      *         and the channel is in non-blocking mode
 562      * @throws IOException if an I/O error occurs when waiting
 563      *         for a connection, or if it is not possible for this socket
 564      *         to accept a connection with the given socket
 565      *
 566      * @since   1.1
 567      * @revised 1.4
 568      */
 569     protected final void implAccept(Socket s) throws IOException {
 570         SocketImpl si = s.impl;
 571 
 572         // Socket has no SocketImpl
 573         if (si == null) {
 574             si = implAccept();
 575             s.setImpl(si);
 576             s.postAccept();
 577             return;
 578         }
 579 
 580         // Socket has a SOCKS or HTTP SocketImpl, need delegate
 581         if (si instanceof DelegatingSocketImpl) {
 582             si = ((DelegatingSocketImpl) si).delegate();
 583             assert si instanceof PlatformSocketImpl;
 584         }
 585 
 586         // Accept connection with a platform or custom SocketImpl.
 587         // For the platform SocketImpl case:
 588         // - the connection is accepted with a new SocketImpl
 589         // - the SO_TIMEOUT socket option is copied to the new SocketImpl
 590         // - the Socket is connected to the new SocketImpl
 591         // - the existing/old SocketImpl is closed
 592         // For the custom SocketImpl case, the connection is accepted with the
 593         // existing custom SocketImpl.
 594         ensureCompatible(si);
 595         if (impl instanceof PlatformSocketImpl) {
 596             SocketImpl psi = platformImplAccept();
 597             si.copyOptionsTo(psi);
 598             s.setImpl(psi);
 599             si.closeQuietly();
 600         } else {
 601             s.impl = null; // temporarily break connection to impl
 602             try {
 603                 customImplAccept(si);
 604             } finally {
 605                 s.impl = si;  // restore connection to impl
 606             }
 607         }
 608         s.postAccept();
 609     }
 610 
 611     /**
 612      * Accepts a connection with a new SocketImpl.
 613      * @return the new SocketImpl
 614      */
 615     private SocketImpl implAccept() throws IOException {
 616         if (impl instanceof PlatformSocketImpl) {
 617             return platformImplAccept();
 618         } else {
 619             // custom server SocketImpl, client SocketImplFactory must be set
 620             SocketImplFactory factory = Socket.socketImplFactory();
 621             if (factory == null) {
 622                 throw new IOException("An instance of " + impl.getClass() +
 623                     " cannot accept connection with 'null' SocketImpl:" +
 624                     " client socket implementation factory not set");
 625             }
 626             SocketImpl si = factory.createSocketImpl();
 627             customImplAccept(si);
 628             return si;
 629         }
 630     }
 631 
 632     /**
 633      * Accepts a connection with a new platform SocketImpl.
 634      * @return the new platform SocketImpl
 635      */
 636     private SocketImpl platformImplAccept() throws IOException {
 637         assert impl instanceof PlatformSocketImpl;
 638 
 639         // create a new platform SocketImpl and accept the connection
 640         SocketImpl psi = SocketImpl.createPlatformSocketImpl(false);
 641         implAccept(psi);
 642         return psi;
 643     }
 644 
 645     /**
 646      * Accepts a new connection with the given custom SocketImpl.
 647      */
 648     private void customImplAccept(SocketImpl si) throws IOException {
 649         assert !(impl instanceof PlatformSocketImpl)
 650                 && !(si instanceof PlatformSocketImpl);
 651 
 652         si.reset();
 653         try {
 654             // custom SocketImpl may expect fd/address objects to be created
 655             si.fd = new FileDescriptor();
 656             si.address = new InetAddress();
 657             implAccept(si);
 658         } catch (Exception e) {
 659             si.reset();
 660             throw e;
 661         }
 662     }
 663 
 664     /**
 665      * Accepts a new connection so that the given SocketImpl is connected to
 666      * the peer. The SocketImpl and connection are closed if the connection is
 667      * denied by the security manager.
 668      * @throws IOException if an I/O error occurs
 669      * @throws SecurityException if the security manager's checkAccept method fails
 670      */
 671     private void implAccept(SocketImpl si) throws IOException {
 672         assert !(si instanceof DelegatingSocketImpl);
 673 
 674         // accept a connection
 675         impl.accept(si);
 676 
 677         // check permission, close SocketImpl/connection if denied
 678         @SuppressWarnings("removal")
 679         SecurityManager sm = System.getSecurityManager();
 680         if (sm != null) {
 681             try {
 682                 sm.checkAccept(si.getInetAddress().getHostAddress(), si.getPort());
 683             } catch (SecurityException se) {
 684                 si.close();
 685                 throw se;
 686             }
 687         }
 688     }
 689 
 690     /**
 691      * Throws IOException if the server SocketImpl and the given client
 692      * SocketImpl are not both platform or custom SocketImpls.
 693      */
 694     private void ensureCompatible(SocketImpl si) throws IOException {
 695         if ((impl instanceof PlatformSocketImpl) != (si instanceof PlatformSocketImpl)) {
 696             throw new IOException("An instance of " + impl.getClass() +
 697                 " cannot accept a connection with an instance of " + si.getClass());
 698         }
 699     }
 700 
 701     /**
 702      * Closes this socket.
 703      *
 704      * Any thread currently blocked in {@link #accept()} will throw
 705      * a {@link SocketException}.
 706      *
 707      * <p> If this socket has an associated channel then the channel is closed
 708      * as well.
 709      *
 710      * @throws     IOException  if an I/O error occurs when closing the socket.
 711      * @revised 1.4
 712      */
 713     public void close() throws IOException {
 714         synchronized(closeLock) {
 715             if (isClosed())
 716                 return;
 717             if (created)
 718                 impl.close();
 719             closed = true;
 720         }
 721     }
 722 
 723     /**
 724      * Returns the unique {@link java.nio.channels.ServerSocketChannel} object
 725      * associated with this socket, if any.
 726      *
 727      * <p> A server socket will have a channel if, and only if, the channel
 728      * itself was created via the {@link
 729      * java.nio.channels.ServerSocketChannel#open ServerSocketChannel.open}
 730      * method.
 731      *
 732      * @return  the server-socket channel associated with this socket,
 733      *          or {@code null} if this socket was not created
 734      *          for a channel
 735      *
 736      * @since 1.4
 737      */
 738     public ServerSocketChannel getChannel() {
 739         return null;
 740     }
 741 
 742     /**
 743      * Returns the binding state of the ServerSocket.
 744      * <p>
 745      * If the socket was bound prior to being {@linkplain #close closed},
 746      * then this method will continue to return {@code true}
 747      * after the socket is closed.
 748      *
 749      * @return true if the ServerSocket successfully bound to an address
 750      * @since 1.4
 751      */
 752     public boolean isBound() {
 753         return bound;
 754     }
 755 
 756     /**
 757      * Returns the closed state of the ServerSocket.
 758      *
 759      * @return true if the socket has been closed
 760      * @since 1.4
 761      */
 762     public boolean isClosed() {
 763         synchronized(closeLock) {
 764             return closed;
 765         }
 766     }
 767 
 768     /**
 769      * Enable/disable {@link SocketOptions#SO_TIMEOUT SO_TIMEOUT} with the
 770      * specified timeout, in milliseconds.  With this option set to a positive
 771      * timeout value, a call to accept() for this ServerSocket
 772      * will block for only this amount of time.  If the timeout expires,
 773      * a <B>java.net.SocketTimeoutException</B> is raised, though the
 774      * ServerSocket is still valid. A timeout of zero is interpreted as an
 775      * infinite timeout.
 776      * The option <B>must</B> be enabled prior to entering the blocking
 777      * operation to have effect.
 778      *
 779      * @param timeout the specified timeout, in milliseconds
 780      * @throws  SocketException if there is an error in the underlying protocol,
 781      *          such as a TCP error
 782      * @throws  IllegalArgumentException  if {@code timeout} is negative
 783      * @since   1.1
 784      * @see #getSoTimeout()
 785      */
 786     public synchronized void setSoTimeout(int timeout) throws SocketException {
 787         if (isClosed())
 788             throw new SocketException("Socket is closed");
 789         if (timeout < 0)
 790             throw new IllegalArgumentException("timeout < 0");
 791         getImpl().setOption(SocketOptions.SO_TIMEOUT, timeout);
 792     }
 793 
 794     /**
 795      * Retrieve setting for {@link SocketOptions#SO_TIMEOUT SO_TIMEOUT}.
 796      * 0 returns implies that the option is disabled (i.e., timeout of infinity).
 797      * @return the {@link SocketOptions#SO_TIMEOUT SO_TIMEOUT} value
 798      * @throws    IOException if an I/O error occurs
 799      * @since   1.1
 800      * @see #setSoTimeout(int)
 801      */
 802     public synchronized int getSoTimeout() throws IOException {
 803         if (isClosed())
 804             throw new SocketException("Socket is closed");
 805         Object o = getImpl().getOption(SocketOptions.SO_TIMEOUT);
 806         /* extra type safety */
 807         if (o instanceof Integer) {
 808             return ((Integer) o).intValue();
 809         } else {
 810             return 0;
 811         }
 812     }
 813 
 814     /**
 815      * Enable/disable the {@link SocketOptions#SO_REUSEADDR SO_REUSEADDR}
 816      * socket option.
 817      * <p>
 818      * When a TCP connection is closed the connection may remain
 819      * in a timeout state for a period of time after the connection
 820      * is closed (typically known as the {@code TIME_WAIT} state
 821      * or {@code 2MSL} wait state).
 822      * For applications using a well known socket address or port
 823      * it may not be possible to bind a socket to the required
 824      * {@code SocketAddress} if there is a connection in the
 825      * timeout state involving the socket address or port.
 826      * <p>
 827      * Enabling {@link SocketOptions#SO_REUSEADDR SO_REUSEADDR} prior to
 828      * binding the socket using {@link #bind(SocketAddress)} allows the socket
 829      * to be bound even though a previous connection is in a timeout state.
 830      * <p>
 831      * When a {@code ServerSocket} is created the initial setting
 832      * of {@link SocketOptions#SO_REUSEADDR SO_REUSEADDR} is not defined.
 833      * Applications can use {@link #getReuseAddress()} to determine the initial
 834      * setting of {@link SocketOptions#SO_REUSEADDR SO_REUSEADDR}.
 835      * <p>
 836      * The behaviour when {@link SocketOptions#SO_REUSEADDR SO_REUSEADDR} is
 837      * enabled or disabled after a socket is bound (See {@link #isBound()})
 838      * is not defined.
 839      *
 840      * @param on  whether to enable or disable the socket option
 841      * @throws    SocketException if an error occurs enabling or
 842      *            disabling the {@link SocketOptions#SO_REUSEADDR SO_REUSEADDR}
 843      *            socket option, or the socket is closed.
 844      * @since 1.4
 845      * @see #getReuseAddress()
 846      * @see #bind(SocketAddress)
 847      * @see #isBound()
 848      * @see #isClosed()
 849      */
 850     public void setReuseAddress(boolean on) throws SocketException {
 851         if (isClosed())
 852             throw new SocketException("Socket is closed");
 853         getImpl().setOption(SocketOptions.SO_REUSEADDR, Boolean.valueOf(on));
 854     }
 855 
 856     /**
 857      * Tests if {@link SocketOptions#SO_REUSEADDR SO_REUSEADDR} is enabled.
 858      *
 859      * @return a {@code boolean} indicating whether or not
 860      *         {@link SocketOptions#SO_REUSEADDR SO_REUSEADDR} is enabled.
 861      * @throws    SocketException if there is an error
 862      * in the underlying protocol, such as a TCP error.
 863      * @since   1.4
 864      * @see #setReuseAddress(boolean)
 865      */
 866     public boolean getReuseAddress() throws SocketException {
 867         if (isClosed())
 868             throw new SocketException("Socket is closed");
 869         return ((Boolean) (getImpl().getOption(SocketOptions.SO_REUSEADDR))).booleanValue();
 870     }
 871 
 872     /**
 873      * Returns the implementation address and implementation port of
 874      * this socket as a {@code String}.
 875      * <p>
 876      * If there is a security manager set, and this socket is
 877      * {@linkplain #isBound bound}, its {@code checkConnect} method is
 878      * called with the local address and {@code -1} as its arguments to see
 879      * if the operation is allowed. If the operation is not allowed,
 880      * an {@code InetAddress} representing the
 881      * {@link InetAddress#getLoopbackAddress loopback} address is returned as
 882      * the implementation address.
 883      *
 884      * @return  a string representation of this socket.
 885      */
 886     @SuppressWarnings("removal")
 887     public String toString() {
 888         if (!isBound())
 889             return "ServerSocket[unbound]";
 890         InetAddress in;
 891         if (System.getSecurityManager() != null)
 892             in = getInetAddress();
 893         else
 894             in = impl.getInetAddress();
 895         return "ServerSocket[addr=" + in +
 896                 ",localport=" + impl.getLocalPort()  + "]";
 897     }
 898 
 899     /**
 900      * The factory for all server sockets.
 901      */
 902     private static volatile SocketImplFactory factory;
 903 
 904     /**
 905      * Sets the server socket implementation factory for the
 906      * application. The factory can be specified only once.
 907      * <p>
 908      * When an application creates a new server socket, the socket
 909      * implementation factory's {@code createSocketImpl} method is
 910      * called to create the actual socket implementation.
 911      * <p>
 912      * Passing {@code null} to the method is a no-op unless the factory
 913      * was already set.
 914      * <p>
 915      * If there is a security manager, this method first calls
 916      * the security manager's {@code checkSetFactory} method
 917      * to ensure the operation is allowed.
 918      * This could result in a SecurityException.
 919      *
 920      * @param      fac   the desired factory.
 921      * @throws     IOException  if an I/O error occurs when setting the
 922      *               socket factory.
 923      * @throws     SocketException  if the factory has already been defined.
 924      * @throws     SecurityException  if a security manager exists and its
 925      *             {@code checkSetFactory} method doesn't allow the operation.
 926      * @see        java.net.SocketImplFactory#createSocketImpl()
 927      * @see        SecurityManager#checkSetFactory
 928      * @deprecated Use a {@link javax.net.ServerSocketFactory} and subclass {@code ServerSocket}
 929      *    directly.
 930      *    <br> This method provided a way in early JDK releases to replace the
 931      *    system wide implementation of {@code ServerSocket}. It has been mostly
 932      *    obsolete since Java 1.4. If required, a {@code ServerSocket} can be
 933      *    created to use a custom implementation by extending {@code ServerSocket}
 934      *    and using the {@linkplain #ServerSocket(SocketImpl) protected
 935      *    constructor} that takes an {@linkplain SocketImpl implementation}
 936      *    as a parameter.
 937      */
 938     @Deprecated(since = "17")
 939     public static synchronized void setSocketFactory(SocketImplFactory fac) throws IOException {
 940         if (factory != null) {
 941             throw new SocketException("factory already defined");
 942         }
 943         @SuppressWarnings("removal")
 944         SecurityManager security = System.getSecurityManager();
 945         if (security != null) {
 946             security.checkSetFactory();
 947         }
 948         factory = fac;
 949     }
 950 
 951     /**
 952      * Sets a default proposed value for the
 953      * {@link SocketOptions#SO_RCVBUF SO_RCVBUF} option for sockets
 954      * accepted from this {@code ServerSocket}. The value actually set
 955      * in the accepted socket must be determined by calling
 956      * {@link Socket#getReceiveBufferSize()} after the socket
 957      * is returned by {@link #accept()}.
 958      * <p>
 959      * The value of {@link SocketOptions#SO_RCVBUF SO_RCVBUF} is used both to
 960      * set the size of the internal socket receive buffer, and to set the size
 961      * of the TCP receive window that is advertised to the remote peer.
 962      * <p>
 963      * It is possible to change the value subsequently, by calling
 964      * {@link Socket#setReceiveBufferSize(int)}. However, if the application
 965      * wishes to allow a receive window larger than 64K bytes, as defined by RFC1323
 966      * then the proposed value must be set in the ServerSocket <B>before</B>
 967      * it is bound to a local address. This implies, that the ServerSocket must be
 968      * created with the no-argument constructor, then setReceiveBufferSize() must
 969      * be called and lastly the ServerSocket is bound to an address by calling bind().
 970      * <p>
 971      * Failure to do this will not cause an error, and the buffer size may be set to the
 972      * requested value but the TCP receive window in sockets accepted from
 973      * this ServerSocket will be no larger than 64K bytes.
 974      *
 975      * @throws    SocketException if there is an error
 976      * in the underlying protocol, such as a TCP error.
 977      *
 978      * @param size the size to which to set the receive buffer
 979      * size. This value must be greater than 0.
 980      *
 981      * @throws    IllegalArgumentException if the
 982      * value is 0 or is negative.
 983      *
 984      * @since 1.4
 985      * @see #getReceiveBufferSize
 986      */
 987      public synchronized void setReceiveBufferSize (int size) throws SocketException {
 988         if (!(size > 0)) {
 989             throw new IllegalArgumentException("negative receive size");
 990         }
 991         if (isClosed())
 992             throw new SocketException("Socket is closed");
 993         getImpl().setOption(SocketOptions.SO_RCVBUF, size);
 994     }
 995 
 996     /**
 997      * Gets the value of the {@link SocketOptions#SO_RCVBUF SO_RCVBUF} option
 998      * for this {@code ServerSocket}, that is the proposed buffer size that
 999      * will be used for Sockets accepted from this {@code ServerSocket}.
1000      *
1001      * <p>Note, the value actually set in the accepted socket is determined by
1002      * calling {@link Socket#getReceiveBufferSize()}.
1003      * @return the value of the {@link SocketOptions#SO_RCVBUF SO_RCVBUF}
1004      *         option for this {@code Socket}.
1005      * @throws    SocketException if there is an error
1006      *            in the underlying protocol, such as a TCP error.
1007      * @see #setReceiveBufferSize(int)
1008      * @since 1.4
1009      */
1010     public synchronized int getReceiveBufferSize()
1011     throws SocketException{
1012         if (isClosed())
1013             throw new SocketException("Socket is closed");
1014         int result = 0;
1015         Object o = getImpl().getOption(SocketOptions.SO_RCVBUF);
1016         if (o instanceof Integer) {
1017             result = ((Integer)o).intValue();
1018         }
1019         return result;
1020     }
1021 
1022     /**
1023      * Sets performance preferences for this ServerSocket.
1024      *
1025      * <p> Sockets use the TCP/IP protocol by default.  Some implementations
1026      * may offer alternative protocols which have different performance
1027      * characteristics than TCP/IP.  This method allows the application to
1028      * express its own preferences as to how these tradeoffs should be made
1029      * when the implementation chooses from the available protocols.
1030      *
1031      * <p> Performance preferences are described by three integers
1032      * whose values indicate the relative importance of short connection time,
1033      * low latency, and high bandwidth.  The absolute values of the integers
1034      * are irrelevant; in order to choose a protocol the values are simply
1035      * compared, with larger values indicating stronger preferences.  If the
1036      * application prefers short connection time over both low latency and high
1037      * bandwidth, for example, then it could invoke this method with the values
1038      * {@code (1, 0, 0)}.  If the application prefers high bandwidth above low
1039      * latency, and low latency above short connection time, then it could
1040      * invoke this method with the values {@code (0, 1, 2)}.
1041      *
1042      * <p> Invoking this method after this socket has been bound
1043      * will have no effect. This implies that in order to use this capability
1044      * requires the socket to be created with the no-argument constructor.
1045      *
1046      * @param  connectionTime
1047      *         An {@code int} expressing the relative importance of a short
1048      *         connection time
1049      *
1050      * @param  latency
1051      *         An {@code int} expressing the relative importance of low
1052      *         latency
1053      *
1054      * @param  bandwidth
1055      *         An {@code int} expressing the relative importance of high
1056      *         bandwidth
1057      *
1058      * @since 1.5
1059      */
1060     public void setPerformancePreferences(int connectionTime,
1061                                           int latency,
1062                                           int bandwidth)
1063     {
1064         /* Not implemented yet */
1065     }
1066 
1067     /**
1068      * Sets the value of a socket option.
1069      *
1070      * @param <T> The type of the socket option value
1071      * @param name The socket option
1072      * @param value The value of the socket option. A value of {@code null}
1073      *              may be valid for some options.
1074      * @return this ServerSocket
1075      *
1076      * @throws UnsupportedOperationException if the server socket does not
1077      *         support the option.
1078      *
1079      * @throws IllegalArgumentException if the value is not valid for
1080      *         the option.
1081      *
1082      * @throws IOException if an I/O error occurs, or if the socket is closed.
1083      *
1084      * @throws NullPointerException if name is {@code null}
1085      *
1086      * @throws SecurityException if a security manager is set and if the socket
1087      *         option requires a security permission and if the caller does
1088      *         not have the required permission.
1089      *         {@link java.net.StandardSocketOptions StandardSocketOptions}
1090      *         do not require any security permission.
1091      *
1092      * @since 9
1093      */
1094     public <T> ServerSocket setOption(SocketOption<T> name, T value)
1095         throws IOException
1096     {
1097         Objects.requireNonNull(name);
1098         if (isClosed())
1099             throw new SocketException("Socket is closed");
1100         getImpl().setOption(name, value);
1101         return this;
1102     }
1103 
1104     /**
1105      * Returns the value of a socket option.
1106      *
1107      * @param <T> The type of the socket option value
1108      * @param name The socket option
1109      *
1110      * @return The value of the socket option.
1111      *
1112      * @throws UnsupportedOperationException if the server socket does not
1113      *         support the option.
1114      *
1115      * @throws IOException if an I/O error occurs, or if the socket is closed.
1116      *
1117      * @throws NullPointerException if name is {@code null}
1118      *
1119      * @throws SecurityException if a security manager is set and if the socket
1120      *         option requires a security permission and if the caller does
1121      *         not have the required permission.
1122      *         {@link java.net.StandardSocketOptions StandardSocketOptions}
1123      *         do not require any security permission.
1124      *
1125      * @since 9
1126      */
1127     public <T> T getOption(SocketOption<T> name) throws IOException {
1128         Objects.requireNonNull(name);
1129         if (isClosed())
1130             throw new SocketException("Socket is closed");
1131         return getImpl().getOption(name);
1132     }
1133 
1134     // cache of unmodifiable impl options. Possibly set racy, in impl we trust
1135     private volatile Set<SocketOption<?>> options;
1136 
1137     /**
1138      * Returns a set of the socket options supported by this server socket.
1139      *
1140      * This method will continue to return the set of options even after
1141      * the socket has been closed.
1142      *
1143      * @return A set of the socket options supported by this socket. This set
1144      *         may be empty if the socket's SocketImpl cannot be created.
1145      *
1146      * @since 9
1147      */
1148     public Set<SocketOption<?>> supportedOptions() {
1149         Set<SocketOption<?>> so = options;
1150         if (so != null)
1151             return so;
1152 
1153         try {
1154             SocketImpl impl = getImpl();
1155             options = Collections.unmodifiableSet(impl.supportedOptions());
1156         } catch (IOException e) {
1157             options = Collections.emptySet();
1158         }
1159         return options;
1160     }
1161 }