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