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