1 /*
   2  * Copyright (c) 1995, 2015, 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      * 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 
 553             SecurityManager security = System.getSecurityManager();
 554             if (security != null) {
 555                 security.checkAccept(si.getInetAddress().getHostAddress(),
 556                                      si.getPort());
 557             }
 558         } catch (IOException e) {
 559             if (si != null)
 560                 si.reset();
 561             s.impl = si;
 562             throw e;
 563         } catch (SecurityException e) {
 564             if (si != null)
 565                 si.reset();
 566             s.impl = si;
 567             throw e;
 568         }
 569         s.impl = si;
 570         s.postAccept();
 571     }
 572 
 573     /**
 574      * Closes this socket.
 575      *
 576      * Any thread currently blocked in {@link #accept()} will throw
 577      * a {@link SocketException}.
 578      *
 579      * <p> If this socket has an associated channel then the channel is closed
 580      * as well.
 581      *
 582      * @exception  IOException  if an I/O error occurs when closing the socket.
 583      * @revised 1.4
 584      * @spec JSR-51
 585      */
 586     public void close() throws IOException {
 587         synchronized(closeLock) {
 588             if (isClosed())
 589                 return;
 590             if (created)
 591                 impl.close();
 592             closed = true;
 593         }
 594     }
 595 
 596     /**
 597      * Returns the unique {@link java.nio.channels.ServerSocketChannel} object
 598      * associated with this socket, if any.
 599      *
 600      * <p> A server socket will have a channel if, and only if, the channel
 601      * itself was created via the {@link
 602      * java.nio.channels.ServerSocketChannel#open ServerSocketChannel.open}
 603      * method.
 604      *
 605      * @return  the server-socket channel associated with this socket,
 606      *          or {@code null} if this socket was not created
 607      *          for a channel
 608      *
 609      * @since 1.4
 610      * @spec JSR-51
 611      */
 612     public ServerSocketChannel getChannel() {
 613         return null;
 614     }
 615 
 616     /**
 617      * Returns the binding state of the ServerSocket.
 618      *
 619      * @return true if the ServerSocket successfully bound to an address
 620      * @since 1.4
 621      */
 622     public boolean isBound() {
 623         // Before 1.3 ServerSockets were always bound during creation
 624         return bound || oldImpl;
 625     }
 626 
 627     /**
 628      * Returns the closed state of the ServerSocket.
 629      *
 630      * @return true if the socket has been closed
 631      * @since 1.4
 632      */
 633     public boolean isClosed() {
 634         synchronized(closeLock) {
 635             return closed;
 636         }
 637     }
 638 
 639     /**
 640      * Enable/disable {@link SocketOptions#SO_TIMEOUT SO_TIMEOUT} with the
 641      * specified timeout, in milliseconds.  With this option set to a non-zero
 642      * timeout, a call to accept() for this ServerSocket
 643      * will block for only this amount of time.  If the timeout expires,
 644      * a <B>java.net.SocketTimeoutException</B> is raised, though the
 645      * ServerSocket is still valid.  The option <B>must</B> be enabled
 646      * prior to entering the blocking operation to have effect.  The
 647      * timeout must be {@code > 0}.
 648      * A timeout of zero is interpreted as an infinite timeout.
 649      * @param timeout the specified timeout, in milliseconds
 650      * @exception SocketException if there is an error in
 651      * the underlying protocol, such as a TCP error.
 652      * @since   1.1
 653      * @see #getSoTimeout()
 654      */
 655     public synchronized void setSoTimeout(int timeout) throws SocketException {
 656         if (isClosed())
 657             throw new SocketException("Socket is closed");
 658         getImpl().setOption(SocketOptions.SO_TIMEOUT, timeout);
 659     }
 660 
 661     /**
 662      * Retrieve setting for {@link SocketOptions#SO_TIMEOUT SO_TIMEOUT}.
 663      * 0 returns implies that the option is disabled (i.e., timeout of infinity).
 664      * @return the {@link SocketOptions#SO_TIMEOUT SO_TIMEOUT} value
 665      * @exception IOException if an I/O error occurs
 666      * @since   1.1
 667      * @see #setSoTimeout(int)
 668      */
 669     public synchronized int getSoTimeout() throws IOException {
 670         if (isClosed())
 671             throw new SocketException("Socket is closed");
 672         Object o = getImpl().getOption(SocketOptions.SO_TIMEOUT);
 673         /* extra type safety */
 674         if (o instanceof Integer) {
 675             return ((Integer) o).intValue();
 676         } else {
 677             return 0;
 678         }
 679     }
 680 
 681     /**
 682      * Enable/disable the {@link SocketOptions#SO_REUSEADDR SO_REUSEADDR}
 683      * socket option.
 684      * <p>
 685      * When a TCP connection is closed the connection may remain
 686      * in a timeout state for a period of time after the connection
 687      * is closed (typically known as the {@code TIME_WAIT} state
 688      * or {@code 2MSL} wait state).
 689      * For applications using a well known socket address or port
 690      * it may not be possible to bind a socket to the required
 691      * {@code SocketAddress} if there is a connection in the
 692      * timeout state involving the socket address or port.
 693      * <p>
 694      * Enabling {@link SocketOptions#SO_REUSEADDR SO_REUSEADDR} prior to
 695      * binding the socket using {@link #bind(SocketAddress)} allows the socket
 696      * to be bound even though a previous connection is in a timeout state.
 697      * <p>
 698      * When a {@code ServerSocket} is created the initial setting
 699      * of {@link SocketOptions#SO_REUSEADDR SO_REUSEADDR} is not defined.
 700      * Applications can use {@link #getReuseAddress()} to determine the initial
 701      * setting of {@link SocketOptions#SO_REUSEADDR SO_REUSEADDR}.
 702      * <p>
 703      * The behaviour when {@link SocketOptions#SO_REUSEADDR SO_REUSEADDR} is
 704      * enabled or disabled after a socket is bound (See {@link #isBound()})
 705      * is not defined.
 706      *
 707      * @param on  whether to enable or disable the socket option
 708      * @exception SocketException if an error occurs enabling or
 709      *            disabling the {@link SocketOptions#SO_REUSEADDR SO_REUSEADDR}
 710      *            socket option, or the socket is closed.
 711      * @since 1.4
 712      * @see #getReuseAddress()
 713      * @see #bind(SocketAddress)
 714      * @see #isBound()
 715      * @see #isClosed()
 716      */
 717     public void setReuseAddress(boolean on) throws SocketException {
 718         if (isClosed())
 719             throw new SocketException("Socket is closed");
 720         getImpl().setOption(SocketOptions.SO_REUSEADDR, Boolean.valueOf(on));
 721     }
 722 
 723     /**
 724      * Tests if {@link SocketOptions#SO_REUSEADDR SO_REUSEADDR} is enabled.
 725      *
 726      * @return a {@code boolean} indicating whether or not
 727      *         {@link SocketOptions#SO_REUSEADDR SO_REUSEADDR} is enabled.
 728      * @exception SocketException if there is an error
 729      * in the underlying protocol, such as a TCP error.
 730      * @since   1.4
 731      * @see #setReuseAddress(boolean)
 732      */
 733     public boolean getReuseAddress() throws SocketException {
 734         if (isClosed())
 735             throw new SocketException("Socket is closed");
 736         return ((Boolean) (getImpl().getOption(SocketOptions.SO_REUSEADDR))).booleanValue();
 737     }
 738 
 739     /**
 740      * Returns the implementation address and implementation port of
 741      * this socket as a {@code String}.
 742      * <p>
 743      * If there is a security manager set, its {@code checkConnect} method is
 744      * called with the local address and {@code -1} as its arguments to see
 745      * if the operation is allowed. If the operation is not allowed,
 746      * an {@code InetAddress} representing the
 747      * {@link InetAddress#getLoopbackAddress loopback} address is returned as
 748      * the implementation address.
 749      *
 750      * @return  a string representation of this socket.
 751      */
 752     public String toString() {
 753         if (!isBound())
 754             return "ServerSocket[unbound]";
 755         InetAddress in;
 756         if (System.getSecurityManager() != null)
 757             in = InetAddress.getLoopbackAddress();
 758         else
 759             in = impl.getInetAddress();
 760         return "ServerSocket[addr=" + in +
 761                 ",localport=" + impl.getLocalPort()  + "]";
 762     }
 763 
 764     void setBound() {
 765         bound = true;
 766     }
 767 
 768     void setCreated() {
 769         created = true;
 770     }
 771 
 772     /**
 773      * The factory for all server sockets.
 774      */
 775     private static SocketImplFactory factory = null;
 776 
 777     /**
 778      * Sets the server socket implementation factory for the
 779      * application. The factory can be specified only once.
 780      * <p>
 781      * When an application creates a new server socket, the socket
 782      * implementation factory's {@code createSocketImpl} method is
 783      * called to create the actual socket implementation.
 784      * <p>
 785      * Passing {@code null} to the method is a no-op unless the factory
 786      * was already set.
 787      * <p>
 788      * If there is a security manager, this method first calls
 789      * the security manager's {@code checkSetFactory} method
 790      * to ensure the operation is allowed.
 791      * This could result in a SecurityException.
 792      *
 793      * @param      fac   the desired factory.
 794      * @exception  IOException  if an I/O error occurs when setting the
 795      *               socket factory.
 796      * @exception  SocketException  if the factory has already been defined.
 797      * @exception  SecurityException  if a security manager exists and its
 798      *             {@code checkSetFactory} method doesn't allow the operation.
 799      * @see        java.net.SocketImplFactory#createSocketImpl()
 800      * @see        SecurityManager#checkSetFactory
 801      */
 802     public static synchronized void setSocketFactory(SocketImplFactory fac) throws IOException {
 803         if (factory != null) {
 804             throw new SocketException("factory already defined");
 805         }
 806         SecurityManager security = System.getSecurityManager();
 807         if (security != null) {
 808             security.checkSetFactory();
 809         }
 810         factory = fac;
 811     }
 812 
 813     /**
 814      * Sets a default proposed value for the
 815      * {@link SocketOptions#SO_RCVBUF SO_RCVBUF} option for sockets
 816      * accepted from this {@code ServerSocket}. The value actually set
 817      * in the accepted socket must be determined by calling
 818      * {@link Socket#getReceiveBufferSize()} after the socket
 819      * is returned by {@link #accept()}.
 820      * <p>
 821      * The value of {@link SocketOptions#SO_RCVBUF SO_RCVBUF} is used both to
 822      * set the size of the internal socket receive buffer, and to set the size
 823      * of the TCP receive window that is advertized to the remote peer.
 824      * <p>
 825      * It is possible to change the value subsequently, by calling
 826      * {@link Socket#setReceiveBufferSize(int)}. However, if the application
 827      * wishes to allow a receive window larger than 64K bytes, as defined by RFC1323
 828      * then the proposed value must be set in the ServerSocket <B>before</B>
 829      * it is bound to a local address. This implies, that the ServerSocket must be
 830      * created with the no-argument constructor, then setReceiveBufferSize() must
 831      * be called and lastly the ServerSocket is bound to an address by calling bind().
 832      * <p>
 833      * Failure to do this will not cause an error, and the buffer size may be set to the
 834      * requested value but the TCP receive window in sockets accepted from
 835      * this ServerSocket will be no larger than 64K bytes.
 836      *
 837      * @exception SocketException if there is an error
 838      * in the underlying protocol, such as a TCP error.
 839      *
 840      * @param size the size to which to set the receive buffer
 841      * size. This value must be greater than 0.
 842      *
 843      * @exception IllegalArgumentException if the
 844      * value is 0 or is negative.
 845      *
 846      * @since 1.4
 847      * @see #getReceiveBufferSize
 848      */
 849      public synchronized void setReceiveBufferSize (int size) throws SocketException {
 850         if (!(size > 0)) {
 851             throw new IllegalArgumentException("negative receive size");
 852         }
 853         if (isClosed())
 854             throw new SocketException("Socket is closed");
 855         getImpl().setOption(SocketOptions.SO_RCVBUF, size);
 856     }
 857 
 858     /**
 859      * Gets the value of the {@link SocketOptions#SO_RCVBUF SO_RCVBUF} option
 860      * for this {@code ServerSocket}, that is the proposed buffer size that
 861      * will be used for Sockets accepted from this {@code ServerSocket}.
 862      *
 863      * <p>Note, the value actually set in the accepted socket is determined by
 864      * calling {@link Socket#getReceiveBufferSize()}.
 865      * @return the value of the {@link SocketOptions#SO_RCVBUF SO_RCVBUF}
 866      *         option for this {@code Socket}.
 867      * @exception SocketException if there is an error
 868      *            in the underlying protocol, such as a TCP error.
 869      * @see #setReceiveBufferSize(int)
 870      * @since 1.4
 871      */
 872     public synchronized int getReceiveBufferSize()
 873     throws SocketException{
 874         if (isClosed())
 875             throw new SocketException("Socket is closed");
 876         int result = 0;
 877         Object o = getImpl().getOption(SocketOptions.SO_RCVBUF);
 878         if (o instanceof Integer) {
 879             result = ((Integer)o).intValue();
 880         }
 881         return result;
 882     }
 883 
 884     /**
 885      * Sets performance preferences for this ServerSocket.
 886      *
 887      * <p> Sockets use the TCP/IP protocol by default.  Some implementations
 888      * may offer alternative protocols which have different performance
 889      * characteristics than TCP/IP.  This method allows the application to
 890      * express its own preferences as to how these tradeoffs should be made
 891      * when the implementation chooses from the available protocols.
 892      *
 893      * <p> Performance preferences are described by three integers
 894      * whose values indicate the relative importance of short connection time,
 895      * low latency, and high bandwidth.  The absolute values of the integers
 896      * are irrelevant; in order to choose a protocol the values are simply
 897      * compared, with larger values indicating stronger preferences.  If the
 898      * application prefers short connection time over both low latency and high
 899      * bandwidth, for example, then it could invoke this method with the values
 900      * {@code (1, 0, 0)}.  If the application prefers high bandwidth above low
 901      * latency, and low latency above short connection time, then it could
 902      * invoke this method with the values {@code (0, 1, 2)}.
 903      *
 904      * <p> Invoking this method after this socket has been bound
 905      * will have no effect. This implies that in order to use this capability
 906      * requires the socket to be created with the no-argument constructor.
 907      *
 908      * @param  connectionTime
 909      *         An {@code int} expressing the relative importance of a short
 910      *         connection time
 911      *
 912      * @param  latency
 913      *         An {@code int} expressing the relative importance of low
 914      *         latency
 915      *
 916      * @param  bandwidth
 917      *         An {@code int} expressing the relative importance of high
 918      *         bandwidth
 919      *
 920      * @since 1.5
 921      */
 922     public void setPerformancePreferences(int connectionTime,
 923                                           int latency,
 924                                           int bandwidth)
 925     {
 926         /* Not implemented yet */
 927     }
 928 
 929     /**
 930      * Sets the value of a socket option.
 931      *
 932      * @param <T> The type of the socket option value
 933      * @param name The socket option
 934      * @param value The value of the socket option. A value of {@code null}
 935      *              may be valid for some options.
 936      * @return this ServerSocket
 937      *
 938      * @throws UnsupportedOperationException if the server socket does not
 939      *         support the option.
 940      *
 941      * @throws IllegalArgumentException if the value is not valid for
 942      *         the option.
 943      *
 944      * @throws IOException if an I/O error occurs, or if the socket is closed.
 945      *
 946      * @throws NullPointerException if name is {@code null}
 947      *
 948      * @throws SecurityException if a security manager is set and if the socket
 949      *         option requires a security permission and if the caller does
 950      *         not have the required permission.
 951      *         {@link java.net.StandardSocketOptions StandardSocketOptions}
 952      *         do not require any security permission.
 953      *
 954      * @since 9
 955      */
 956     public <T> ServerSocket setOption(SocketOption<T> name, T value)
 957         throws IOException
 958     {
 959         getImpl().setOption(name, value);
 960         return this;
 961     }
 962 
 963     /**
 964      * Returns the value of a socket option.
 965      *
 966      * @param <T> The type of the socket option value
 967      * @param name The socket option
 968      *
 969      * @return The value of the socket option.
 970      *
 971      * @throws UnsupportedOperationException if the server socket does not
 972      *         support the option.
 973      *
 974      * @throws IOException if an I/O error occurs, or if the socket is closed.
 975      *
 976      * @throws NullPointerException if name is {@code null}
 977      *
 978      * @throws SecurityException if a security manager is set and if the socket
 979      *         option requires a security permission and if the caller does
 980      *         not have the required permission.
 981      *         {@link java.net.StandardSocketOptions StandardSocketOptions}
 982      *         do not require any security permission.
 983      *
 984      * @since 9
 985      */
 986     public <T> T getOption(SocketOption<T> name) throws IOException {
 987         return getImpl().getOption(name);
 988     }
 989 
 990     private static Set<SocketOption<?>> options;
 991     private static boolean optionsSet = false;
 992 
 993     /**
 994      * Returns a set of the socket options supported by this server socket.
 995      *
 996      * This method will continue to return the set of options even after
 997      * the socket has been closed.
 998      *
 999      * @return A set of the socket options supported by this socket. This set
1000      *         may be empty if the socket's SocketImpl cannot be created.
1001      *
1002      * @since 9
1003      */
1004     public Set<SocketOption<?>> supportedOptions() {
1005         synchronized (ServerSocket.class) {
1006             if (optionsSet) {
1007                 return options;
1008             }
1009             try {
1010                 SocketImpl impl = getImpl();
1011                 options = Collections.unmodifiableSet(impl.supportedOptions());
1012             } catch (IOException e) {
1013                 options = Collections.emptySet();
1014             }
1015             optionsSet = true;
1016             return options;
1017         }
1018     }
1019 
1020     static {
1021         SharedSecrets.setJavaNetSocketAccess(
1022             new JavaNetSocketAccess() {
1023                 @Override
1024                 public ServerSocket newServerSocket(SocketImpl impl) {
1025                     return new ServerSocket(impl);
1026                 }
1027 
1028                 @Override
1029                 public SocketImpl newSocketImpl(Class<? extends SocketImpl> implClass) {
1030                     try {
1031                         Constructor<? extends SocketImpl> ctor =
1032                             implClass.getDeclaredConstructor();
1033                         return ctor.newInstance();
1034                     } catch (NoSuchMethodException | InstantiationException |
1035                              IllegalAccessException | InvocationTargetException e) {
1036                         throw new AssertionError(e);
1037                     }
1038                 }
1039             }
1040         );
1041     }
1042 }