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