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