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