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