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