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