1 /*
2  * Copyright (C) 2014 The Android Open Source Project
3  * Copyright (c) 1995, 2016, Oracle and/or its affiliates. All rights reserved.
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * This code is free software; you can redistribute it and/or modify it
7  * under the terms of the GNU General Public License version 2 only, as
8  * published by the Free Software Foundation.  Oracle designates this
9  * particular file as subject to the "Classpath" exception as provided
10  * by Oracle in the LICENSE file that accompanied this code.
11  *
12  * This code is distributed in the hope that it will be useful, but WITHOUT
13  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
14  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
15  * version 2 for more details (a copy is included in the LICENSE file that
16  * accompanied this code).
17  *
18  * You should have received a copy of the GNU General Public License version
19  * 2 along with this work; if not, write to the Free Software Foundation,
20  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
21  *
22  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
23  * or visit www.oracle.com if you need additional information or have any
24  * questions.
25  */
26 
27 package java.net;
28 
29 import sun.security.util.SecurityConstants;
30 
31 
32 import java.io.FileDescriptor;
33 import java.io.InputStream;
34 import java.io.OutputStream;
35 import java.io.IOException;
36 import java.nio.channels.SocketChannel;
37 import java.security.AccessController;
38 import java.security.PrivilegedExceptionAction;
39 import java.security.PrivilegedAction;
40 import java.util.Set;
41 import java.util.Collections;
42 
43 /**
44  * This class implements client sockets (also called just
45  * "sockets"). A socket is an endpoint for communication
46  * between two machines.
47  * <p>
48  * The actual work of the socket is performed by an instance of the
49  * {@code SocketImpl} class. An application, by changing
50  * the socket factory that creates the socket implementation,
51  * can configure itself to create sockets appropriate to the local
52  * firewall.
53  *
54  * @author  unascribed
55  * @see     java.net.Socket#setSocketImplFactory(java.net.SocketImplFactory)
56  * @see     java.net.SocketImpl
57  * @see     java.nio.channels.SocketChannel
58  * @since   1.0
59  */
60 public
61 class Socket implements java.io.Closeable {
62     /**
63      * Various states of this socket.
64      */
65     private boolean created = false;
66     private boolean bound = false;
67     private boolean connected = false;
68     private boolean closed = false;
69     private Object closeLock = new Object();
70     private boolean shutIn = false;
71     private boolean shutOut = false;
72 
73     /**
74      * The implementation of this Socket.
75      */
76     SocketImpl impl;
77 
78     /**
79      * Are we using an older SocketImpl?
80      */
81     private boolean oldImpl = false;
82 
83     /**
84      * Creates an unconnected socket, with the
85      * system-default type of SocketImpl.
86      *
87      * @since   1.1
88      * @revised 1.4
89      */
Socket()90     public Socket() {
91         setImpl();
92     }
93 
94     /**
95      * Creates an unconnected socket, specifying the type of proxy, if any,
96      * that should be used regardless of any other settings.
97      * <P>
98      * If there is a security manager, its {@code checkConnect} method
99      * is called with the proxy host address and port number
100      * as its arguments. This could result in a SecurityException.
101      * <P>
102      * Examples:
103      * <UL> <LI>{@code Socket s = new Socket(Proxy.NO_PROXY);} will create
104      * a plain socket ignoring any other proxy configuration.</LI>
105      * <LI>{@code Socket s = new Socket(new Proxy(Proxy.Type.SOCKS, new InetSocketAddress("socks.mydom.com", 1080)));}
106      * will create a socket connecting through the specified SOCKS proxy
107      * server.</LI>
108      * </UL>
109      *
110      * @param proxy a {@link java.net.Proxy Proxy} object specifying what kind
111      *              of proxying should be used.
112      * @throws IllegalArgumentException if the proxy is of an invalid type
113      *          or {@code null}.
114      * @throws SecurityException if a security manager is present and
115      *                           permission to connect to the proxy is
116      *                           denied.
117      * @see java.net.ProxySelector
118      * @see java.net.Proxy
119      *
120      * @since   1.5
121      */
Socket(Proxy proxy)122     public Socket(Proxy proxy) {
123         // Create a copy of Proxy as a security measure
124         if (proxy == null) {
125             throw new IllegalArgumentException("Invalid Proxy");
126         }
127         Proxy p = proxy == Proxy.NO_PROXY ? Proxy.NO_PROXY
128                                           : sun.net.ApplicationProxy.create(proxy);
129         Proxy.Type type = p.type();
130         // Android-changed: Removed HTTP proxy support.
131         // if (type == Proxy.Type.SOCKS || type == Proxy.Type.HTTP) {
132         if (type == Proxy.Type.SOCKS) {
133             SecurityManager security = System.getSecurityManager();
134             InetSocketAddress epoint = (InetSocketAddress) p.address();
135             if (epoint.getAddress() != null) {
136                 checkAddress (epoint.getAddress(), "Socket");
137             }
138             if (security != null) {
139                 if (epoint.isUnresolved())
140                     epoint = new InetSocketAddress(epoint.getHostName(), epoint.getPort());
141                 if (epoint.isUnresolved())
142                     security.checkConnect(epoint.getHostName(), epoint.getPort());
143                 else
144                     security.checkConnect(epoint.getAddress().getHostAddress(),
145                                   epoint.getPort());
146             }
147             // Android-changed: Removed HTTP proxy support.
148             // impl = type == Proxy.Type.SOCKS ? new SocksSocketImpl(p)
149             //                                : new HttpConnectSocketImpl(p);
150             impl = new SocksSocketImpl(p);
151             impl.setSocket(this);
152         } else {
153             if (p == Proxy.NO_PROXY) {
154                 if (factory == null) {
155                     impl = new PlainSocketImpl();
156                     impl.setSocket(this);
157                 } else
158                     setImpl();
159             } else
160                 throw new IllegalArgumentException("Invalid Proxy");
161         }
162     }
163 
164     /**
165      * Creates an unconnected Socket with a user-specified
166      * SocketImpl.
167      *
168      * @param impl an instance of a <B>SocketImpl</B>
169      * the subclass wishes to use on the Socket.
170      *
171      * @exception SocketException if there is an error in the underlying protocol,
172      * such as a TCP error.
173      *
174      * @throws SecurityException if {@code impl} is non-null and a security manager is set
175      * and its {@code checkPermission} method doesn't allow {@code NetPermission("setSocketImpl")}.
176      *
177      * @since   1.1
178      */
Socket(SocketImpl impl)179     protected Socket(SocketImpl impl) throws SocketException {
180         checkPermission(impl);
181         this.impl = impl;
182         if (impl != null) {
183             checkOldImpl();
184             this.impl.setSocket(this);
185         }
186     }
187 
checkPermission(SocketImpl impl)188     private static Void checkPermission(SocketImpl impl) {
189         // BEGIN Android-removed: SM is no-op.
190         /*
191         if (impl == null) {
192             return null;
193         }
194         SecurityManager sm = System.getSecurityManager();
195         if (sm != null) {
196             sm.checkPermission(SecurityConstants.SET_SOCKETIMPL_PERMISSION);
197         }
198         */
199         // END Android-removed: SM is no-op.
200         return null;
201     }
202 
203     /**
204      * Creates a stream socket and connects it to the specified port
205      * number on the named host.
206      * <p>
207      * If the specified host is {@code null} it is the equivalent of
208      * specifying the address as
209      * {@link java.net.InetAddress#getByName InetAddress.getByName}{@code (null)}.
210      * In other words, it is equivalent to specifying an address of the
211      * loopback interface. </p>
212      * <p>
213      * If the application has specified a server socket factory, that
214      * factory's {@code createSocketImpl} method is called to create
215      * the actual socket implementation. Otherwise a "plain" socket is created.
216      * <p>
217      * If there is a security manager, its
218      * {@code checkConnect} method is called
219      * with the host address and {@code port}
220      * as its arguments. This could result in a SecurityException.
221      *
222      * @param      host   the host name, or {@code null} for the loopback address.
223      * @param      port   the port number.
224      *
225      * @exception  UnknownHostException if the IP address of
226      * the host could not be determined.
227      *
228      * @exception  IOException  if an I/O error occurs when creating the socket.
229      * @exception  SecurityException  if a security manager exists and its
230      *             {@code checkConnect} method doesn't allow the operation.
231      * @exception  IllegalArgumentException if the port parameter is outside
232      *             the specified range of valid port values, which is between
233      *             0 and 65535, inclusive.
234      * @see        java.net.Socket#setSocketImplFactory(java.net.SocketImplFactory)
235      * @see        java.net.SocketImpl
236      * @see        java.net.SocketImplFactory#createSocketImpl()
237      * @see        SecurityManager#checkConnect
238      */
Socket(String host, int port)239     public Socket(String host, int port)
240         throws UnknownHostException, IOException
241     {
242         // Android-changed: App compat. Socket ctor should try all addresses. http://b/30007735
243         this(InetAddress.getAllByName(host), port, (SocketAddress) null, true);
244     }
245 
246     /**
247      * Creates a stream socket and connects it to the specified port
248      * number at the specified IP address.
249      * <p>
250      * If the application has specified a socket factory, that factory's
251      * {@code createSocketImpl} method is called to create the
252      * actual socket implementation. Otherwise a "plain" socket is created.
253      * <p>
254      * If there is a security manager, its
255      * {@code checkConnect} method is called
256      * with the host address and {@code port}
257      * as its arguments. This could result in a SecurityException.
258      *
259      * @param      address   the IP address.
260      * @param      port      the port number.
261      * @exception  IOException  if an I/O error occurs when creating the socket.
262      * @exception  SecurityException  if a security manager exists and its
263      *             {@code checkConnect} method doesn't allow the operation.
264      * @exception  IllegalArgumentException if the port parameter is outside
265      *             the specified range of valid port values, which is between
266      *             0 and 65535, inclusive.
267      * @exception  NullPointerException if {@code address} is null.
268      * @see        java.net.Socket#setSocketImplFactory(java.net.SocketImplFactory)
269      * @see        java.net.SocketImpl
270      * @see        java.net.SocketImplFactory#createSocketImpl()
271      * @see        SecurityManager#checkConnect
272      */
Socket(InetAddress address, int port)273     public Socket(InetAddress address, int port) throws IOException {
274         // Android-changed: App compat. Socket ctor should try all addresses. http://b/30007735
275         this(nonNullAddress(address), port, (SocketAddress) null, true);
276     }
277 
278     /**
279      * Creates a socket and connects it to the specified remote host on
280      * the specified remote port. The Socket will also bind() to the local
281      * address and port supplied.
282      * <p>
283      * If the specified host is {@code null} it is the equivalent of
284      * specifying the address as
285      * {@link java.net.InetAddress#getByName InetAddress.getByName}{@code (null)}.
286      * In other words, it is equivalent to specifying an address of the
287      * loopback interface. </p>
288      * <p>
289      * A local port number of {@code zero} will let the system pick up a
290      * free port in the {@code bind} operation.</p>
291      * <p>
292      * If there is a security manager, its
293      * {@code checkConnect} method is called
294      * with the host address and {@code port}
295      * as its arguments. This could result in a SecurityException.
296      *
297      * @param host the name of the remote host, or {@code null} for the loopback address.
298      * @param port the remote port
299      * @param localAddr the local address the socket is bound to, or
300      *        {@code null} for the {@code anyLocal} address.
301      * @param localPort the local port the socket is bound to, or
302      *        {@code zero} for a system selected free port.
303      * @exception  IOException  if an I/O error occurs when creating the socket.
304      * @exception  SecurityException  if a security manager exists and its
305      *             {@code checkConnect} method doesn't allow the connection
306      *             to the destination, or if its {@code checkListen} method
307      *             doesn't allow the bind to the local port.
308      * @exception  IllegalArgumentException if the port parameter or localPort
309      *             parameter is outside the specified range of valid port values,
310      *             which is between 0 and 65535, inclusive.
311      * @see        SecurityManager#checkConnect
312      * @since   1.1
313      */
Socket(String host, int port, InetAddress localAddr, int localPort)314     public Socket(String host, int port, InetAddress localAddr,
315                   int localPort) throws IOException {
316         // Android-changed: App compat. Socket ctor should try all addresses. http://b/30007735
317         this(InetAddress.getAllByName(host), port,
318              new InetSocketAddress(localAddr, localPort), true);
319     }
320 
321     /**
322      * Creates a socket and connects it to the specified remote address on
323      * the specified remote port. The Socket will also bind() to the local
324      * address and port supplied.
325      * <p>
326      * If the specified local address is {@code null} it is the equivalent of
327      * specifying the address as the AnyLocal address
328      * (see {@link java.net.InetAddress#isAnyLocalAddress InetAddress.isAnyLocalAddress}{@code ()}).
329      * <p>
330      * A local port number of {@code zero} will let the system pick up a
331      * free port in the {@code bind} operation.</p>
332      * <p>
333      * If there is a security manager, its
334      * {@code checkConnect} method is called
335      * with the host address and {@code port}
336      * as its arguments. This could result in a SecurityException.
337      *
338      * @param address the remote address
339      * @param port the remote port
340      * @param localAddr the local address the socket is bound to, or
341      *        {@code null} for the {@code anyLocal} address.
342      * @param localPort the local port the socket is bound to or
343      *        {@code zero} for a system selected free port.
344      * @exception  IOException  if an I/O error occurs when creating the socket.
345      * @exception  SecurityException  if a security manager exists and its
346      *             {@code checkConnect} method doesn't allow the connection
347      *             to the destination, or if its {@code checkListen} method
348      *             doesn't allow the bind to the local port.
349      * @exception  IllegalArgumentException if the port parameter or localPort
350      *             parameter is outside the specified range of valid port values,
351      *             which is between 0 and 65535, inclusive.
352      * @exception  NullPointerException if {@code address} is null.
353      * @see        SecurityManager#checkConnect
354      * @since   1.1
355      */
Socket(InetAddress address, int port, InetAddress localAddr, int localPort)356     public Socket(InetAddress address, int port, InetAddress localAddr,
357                   int localPort) throws IOException {
358         // Android-changed: App compat. Socket ctor should try all addresses. http://b/30007735
359         this(nonNullAddress(address), port,
360              new InetSocketAddress(localAddr, localPort), true);
361     }
362 
363     /**
364      * Creates a stream socket and connects it to the specified port
365      * number on the named host.
366      * <p>
367      * If the specified host is {@code null} it is the equivalent of
368      * specifying the address as
369      * {@link java.net.InetAddress#getByName InetAddress.getByName}{@code (null)}.
370      * In other words, it is equivalent to specifying an address of the
371      * loopback interface. </p>
372      * <p>
373      * If the stream argument is {@code true}, this creates a
374      * stream socket. If the stream argument is {@code false}, it
375      * creates a datagram socket.
376      * <p>
377      * If the application has specified a server socket factory, that
378      * factory's {@code createSocketImpl} method is called to create
379      * the actual socket implementation. Otherwise a "plain" socket is created.
380      * <p>
381      * If there is a security manager, its
382      * {@code checkConnect} method is called
383      * with the host address and {@code port}
384      * as its arguments. This could result in a SecurityException.
385      * <p>
386      * If a UDP socket is used, TCP/IP related socket options will not apply.
387      *
388      * @param      host     the host name, or {@code null} for the loopback address.
389      * @param      port     the port number.
390      * @param      stream   a {@code boolean} indicating whether this is
391      *                      a stream socket or a datagram socket.
392      * @exception  IOException  if an I/O error occurs when creating the socket.
393      * @exception  SecurityException  if a security manager exists and its
394      *             {@code checkConnect} method doesn't allow the operation.
395      * @exception  IllegalArgumentException if the port parameter is outside
396      *             the specified range of valid port values, which is between
397      *             0 and 65535, inclusive.
398      * @see        java.net.Socket#setSocketImplFactory(java.net.SocketImplFactory)
399      * @see        java.net.SocketImpl
400      * @see        java.net.SocketImplFactory#createSocketImpl()
401      * @see        SecurityManager#checkConnect
402      * @deprecated Use DatagramSocket instead for UDP transport.
403      */
404     @Deprecated
Socket(String host, int port, boolean stream)405     public Socket(String host, int port, boolean stream) throws IOException {
406         // Android-changed: App compat. Socket ctor should try all addresses. http://b/30007735
407         this(InetAddress.getAllByName(host), port, (SocketAddress) null, stream);
408     }
409 
410     /**
411      * Creates a socket and connects it to the specified port number at
412      * the specified IP address.
413      * <p>
414      * If the stream argument is {@code true}, this creates a
415      * stream socket. If the stream argument is {@code false}, it
416      * creates a datagram socket.
417      * <p>
418      * If the application has specified a server socket factory, that
419      * factory's {@code createSocketImpl} method is called to create
420      * the actual socket implementation. Otherwise a "plain" socket is created.
421      *
422      * <p>If there is a security manager, its
423      * {@code checkConnect} method is called
424      * with {@code host.getHostAddress()} and {@code port}
425      * as its arguments. This could result in a SecurityException.
426      * <p>
427      * If UDP socket is used, TCP/IP related socket options will not apply.
428      *
429      * @param      host     the IP address.
430      * @param      port      the port number.
431      * @param      stream    if {@code true}, create a stream socket;
432      *                       otherwise, create a datagram socket.
433      * @exception  IOException  if an I/O error occurs when creating the socket.
434      * @exception  SecurityException  if a security manager exists and its
435      *             {@code checkConnect} method doesn't allow the operation.
436      * @exception  IllegalArgumentException if the port parameter is outside
437      *             the specified range of valid port values, which is between
438      *             0 and 65535, inclusive.
439      * @exception  NullPointerException if {@code host} is null.
440      * @see        java.net.Socket#setSocketImplFactory(java.net.SocketImplFactory)
441      * @see        java.net.SocketImpl
442      * @see        java.net.SocketImplFactory#createSocketImpl()
443      * @see        SecurityManager#checkConnect
444      * @deprecated Use DatagramSocket instead for UDP transport.
445      */
446     @Deprecated
Socket(InetAddress host, int port, boolean stream)447     public Socket(InetAddress host, int port, boolean stream) throws IOException {
448         // Android-changed: App compat. Socket ctor should try all addresses. http://b/30007735
449         this(nonNullAddress(host), port, new InetSocketAddress(0), stream);
450     }
451 
452     // BEGIN Android-changed: App compat. Socket ctor should try all addresses. http://b/30007735
nonNullAddress(InetAddress address)453     private static InetAddress[] nonNullAddress(InetAddress address) {
454         // backward compatibility
455         if (address == null)
456             throw new NullPointerException();
457 
458         return new InetAddress[] { address };
459     }
460 
Socket(InetAddress[] addresses, int port, SocketAddress localAddr, boolean stream)461     private Socket(InetAddress[] addresses, int port, SocketAddress localAddr,
462             boolean stream) throws IOException {
463         if (addresses == null || addresses.length == 0) {
464             throw new SocketException("Impossible: empty address list");
465         }
466 
467         for (int i = 0; i < addresses.length; i++) {
468             setImpl();
469             try {
470                 InetSocketAddress address = new InetSocketAddress(addresses[i], port);
471                 createImpl(stream);
472                 if (localAddr != null) {
473                     bind(localAddr);
474                 }
475                 connect(address);
476                 break;
477             } catch (IOException | IllegalArgumentException | SecurityException e) {
478                 try {
479                     // Android-changed: Let ctor call impl.close() instead of overridable close().
480                     // Subclasses may not expect a call to close() coming from this constructor.
481                     impl.close();
482                     closed = true;
483                 } catch (IOException ce) {
484                     e.addSuppressed(ce);
485                 }
486 
487                 // Only stop on the last address.
488                 if (i == addresses.length - 1) {
489                     throw e;
490                 }
491             }
492 
493             // Discard the connection state and try again.
494             impl = null;
495             created = false;
496             bound = false;
497             closed = false;
498         }
499     }
500     // END Android-changed: App compat. Socket ctor should try all addresses. http://b/30007735
501 
502     /**
503      * Creates the socket implementation.
504      *
505      * @param stream a {@code boolean} value : {@code true} for a TCP socket,
506      *               {@code false} for UDP.
507      * @throws IOException if creation fails
508      * @since 1.4
509      */
createImpl(boolean stream)510      void createImpl(boolean stream) throws SocketException {
511         if (impl == null)
512             setImpl();
513         try {
514             impl.create(stream);
515             created = true;
516         } catch (IOException e) {
517             throw new SocketException(e.getMessage());
518         }
519     }
520 
checkOldImpl()521     private void checkOldImpl() {
522         if (impl == null)
523             return;
524         // SocketImpl.connect() is a protected method, therefore we need to use
525         // getDeclaredMethod, therefore we need permission to access the member
526 
527         oldImpl = AccessController.doPrivileged
528                                 (new PrivilegedAction<>() {
529             public Boolean run() {
530                 Class<?> clazz = impl.getClass();
531                 while (true) {
532                     try {
533                         clazz.getDeclaredMethod("connect", SocketAddress.class, int.class);
534                         return Boolean.FALSE;
535                     } catch (NoSuchMethodException e) {
536                         clazz = clazz.getSuperclass();
537                         // java.net.SocketImpl class will always have this abstract method.
538                         // If we have not found it by now in the hierarchy then it does not
539                         // exist, we are an old style impl.
540                         if (clazz.equals(java.net.SocketImpl.class)) {
541                             return Boolean.TRUE;
542                         }
543                     }
544                 }
545             }
546         });
547     }
548 
549     /**
550      * Sets impl to the system-default type of SocketImpl.
551      * @since 1.4
552      */
setImpl()553     void setImpl() {
554         if (factory != null) {
555             impl = factory.createSocketImpl();
556             checkOldImpl();
557         } else {
558             // No need to do a checkOldImpl() here, we know it's an up to date
559             // SocketImpl!
560             impl = new SocksSocketImpl();
561         }
562         if (impl != null)
563             impl.setSocket(this);
564     }
565 
566 
567     /**
568      * Get the {@code SocketImpl} attached to this socket, creating
569      * it if necessary.
570      *
571      * @return  the {@code SocketImpl} attached to that ServerSocket.
572      * @throws SocketException if creation fails
573      * @since 1.4
574      */
getImpl()575     SocketImpl getImpl() throws SocketException {
576         if (!created)
577             createImpl(true);
578         return impl;
579     }
580 
581     /**
582      * Connects this socket to the server.
583      *
584      * @param   endpoint the {@code SocketAddress}
585      * @throws  IOException if an error occurs during the connection
586      * @throws  java.nio.channels.IllegalBlockingModeException
587      *          if this socket has an associated channel,
588      *          and the channel is in non-blocking mode
589      * @throws  IllegalArgumentException if endpoint is null or is a
590      *          SocketAddress subclass not supported by this socket
591      * @since 1.4
592      * @spec JSR-51
593      */
connect(SocketAddress endpoint)594     public void connect(SocketAddress endpoint) throws IOException {
595         connect(endpoint, 0);
596     }
597 
598     /**
599      * Connects this socket to the server with a specified timeout value.
600      * A timeout of zero is interpreted as an infinite timeout. The connection
601      * will then block until established or an error occurs.
602      *
603      * @param   endpoint the {@code SocketAddress}
604      * @param   timeout  the timeout value to be used in milliseconds.
605      * @throws  IOException if an error occurs during the connection
606      * @throws  SocketTimeoutException if timeout expires before connecting
607      * @throws  java.nio.channels.IllegalBlockingModeException
608      *          if this socket has an associated channel,
609      *          and the channel is in non-blocking mode
610      * @throws  IllegalArgumentException if endpoint is null or is a
611      *          SocketAddress subclass not supported by this socket
612      * @since 1.4
613      * @spec JSR-51
614      */
connect(SocketAddress endpoint, int timeout)615     public void connect(SocketAddress endpoint, int timeout) throws IOException {
616         if (endpoint == null)
617             throw new IllegalArgumentException("connect: The address can't be null");
618 
619         if (timeout < 0)
620           throw new IllegalArgumentException("connect: timeout can't be negative");
621 
622         if (isClosed())
623             throw new SocketException("Socket is closed");
624 
625         if (!oldImpl && isConnected())
626             throw new SocketException("already connected");
627 
628         if (!(endpoint instanceof InetSocketAddress))
629             throw new IllegalArgumentException("Unsupported address type");
630 
631         InetSocketAddress epoint = (InetSocketAddress) endpoint;
632         InetAddress addr = epoint.getAddress ();
633         int port = epoint.getPort();
634         checkAddress(addr, "connect");
635 
636         SecurityManager security = System.getSecurityManager();
637         if (security != null) {
638             if (epoint.isUnresolved())
639                 security.checkConnect(epoint.getHostName(), port);
640             else
641                 security.checkConnect(addr.getHostAddress(), port);
642         }
643         if (!created)
644             createImpl(true);
645         if (!oldImpl)
646             impl.connect(epoint, timeout);
647         else if (timeout == 0) {
648             if (epoint.isUnresolved())
649                 impl.connect(addr.getHostName(), port);
650             else
651                 impl.connect(addr, port);
652         } else
653             throw new UnsupportedOperationException("SocketImpl.connect(addr, timeout)");
654         connected = true;
655         /*
656          * If the socket was not bound before the connect, it is now because
657          * the kernel will have picked an ephemeral port & a local address
658          */
659         bound = true;
660     }
661 
662     /**
663      * Binds the socket to a local address.
664      * <P>
665      * If the address is {@code null}, then the system will pick up
666      * an ephemeral port and a valid local address to bind the socket.
667      *
668      * @param   bindpoint the {@code SocketAddress} to bind to
669      * @throws  IOException if the bind operation fails, or if the socket
670      *                     is already bound.
671      * @throws  IllegalArgumentException if bindpoint is a
672      *          SocketAddress subclass not supported by this socket
673      * @throws  SecurityException  if a security manager exists and its
674      *          {@code checkListen} method doesn't allow the bind
675      *          to the local port.
676      *
677      * @since   1.4
678      * @see #isBound
679      */
bind(SocketAddress bindpoint)680     public void bind(SocketAddress bindpoint) throws IOException {
681         if (isClosed())
682             throw new SocketException("Socket is closed");
683         if (!oldImpl && isBound())
684             throw new SocketException("Already bound");
685 
686         if (bindpoint != null && (!(bindpoint instanceof InetSocketAddress)))
687             throw new IllegalArgumentException("Unsupported address type");
688         InetSocketAddress epoint = (InetSocketAddress) bindpoint;
689         if (epoint != null && epoint.isUnresolved())
690             throw new SocketException("Unresolved address");
691         if (epoint == null) {
692             epoint = new InetSocketAddress(0);
693         }
694         InetAddress addr = epoint.getAddress();
695         int port = epoint.getPort();
696         checkAddress (addr, "bind");
697         SecurityManager security = System.getSecurityManager();
698         if (security != null) {
699             security.checkListen(port);
700         }
701         getImpl().bind (addr, port);
702         bound = true;
703     }
704 
checkAddress(InetAddress addr, String op)705     private void checkAddress (InetAddress addr, String op) {
706         if (addr == null) {
707             return;
708         }
709         if (!(addr instanceof Inet4Address || addr instanceof Inet6Address)) {
710             throw new IllegalArgumentException(op + ": invalid address type");
711         }
712     }
713 
714     /**
715      * set the flags after an accept() call.
716      */
postAccept()717     final void postAccept() {
718         connected = true;
719         created = true;
720         bound = true;
721     }
722 
setCreated()723     void setCreated() {
724         created = true;
725     }
726 
setBound()727     void setBound() {
728         bound = true;
729     }
730 
setConnected()731     void setConnected() {
732         connected = true;
733     }
734 
735     /**
736      * Returns the address to which the socket is connected.
737      * <p>
738      * If the socket was connected prior to being {@link #close closed},
739      * then this method will continue to return the connected address
740      * after the socket is closed.
741      *
742      * @return  the remote IP address to which this socket is connected,
743      *          or {@code null} if the socket is not connected.
744      */
getInetAddress()745     public InetAddress getInetAddress() {
746         if (!isConnected())
747             return null;
748         try {
749             return getImpl().getInetAddress();
750         } catch (SocketException e) {
751         }
752         return null;
753     }
754 
755     /**
756      * Gets the local address to which the socket is bound.
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      * the {@link InetAddress#getLoopbackAddress loopback} address is returned.
762      *
763      * @return the local address to which the socket is bound,
764      *         the loopback address if denied by the security manager, or
765      *         the wildcard address if the socket is closed or not bound yet.
766      * @since   1.1
767      *
768      * @see SecurityManager#checkConnect
769      */
getLocalAddress()770     public InetAddress getLocalAddress() {
771         // This is for backward compatibility
772         if (!isBound())
773             return InetAddress.anyLocalAddress();
774         InetAddress in = null;
775         try {
776             in = (InetAddress) getImpl().getOption(SocketOptions.SO_BINDADDR);
777             SecurityManager sm = System.getSecurityManager();
778             if (sm != null)
779                 sm.checkConnect(in.getHostAddress(), -1);
780             if (in.isAnyLocalAddress()) {
781                 in = InetAddress.anyLocalAddress();
782             }
783         } catch (SecurityException e) {
784             in = InetAddress.getLoopbackAddress();
785         } catch (Exception e) {
786             in = InetAddress.anyLocalAddress(); // "0.0.0.0"
787         }
788         return in;
789     }
790 
791     /**
792      * Returns the remote port number to which this socket is connected.
793      * <p>
794      * If the socket was connected prior to being {@link #close closed},
795      * then this method will continue to return the connected port number
796      * after the socket is closed.
797      *
798      * @return  the remote port number to which this socket is connected, or
799      *          0 if the socket is not connected yet.
800      */
getPort()801     public int getPort() {
802         if (!isConnected())
803             return 0;
804         try {
805             return getImpl().getPort();
806         } catch (SocketException e) {
807             // Shouldn't happen as we're connected
808         }
809         return -1;
810     }
811 
812     /**
813      * Returns the local port number to which this socket is bound.
814      * <p>
815      * If the socket was bound prior to being {@link #close closed},
816      * then this method will continue to return the local port number
817      * after the socket is closed.
818      *
819      * @return  the local port number to which this socket is bound or -1
820      *          if the socket is not bound yet.
821      */
getLocalPort()822     public int getLocalPort() {
823         if (!isBound())
824             return -1;
825         try {
826             return getImpl().getLocalPort();
827         } catch(SocketException e) {
828             // shouldn't happen as we're bound
829         }
830         return -1;
831     }
832 
833     /**
834      * Returns the address of the endpoint this socket is connected to, or
835      * {@code null} if it is unconnected.
836      * <p>
837      * If the socket was connected prior to being {@link #close closed},
838      * then this method will continue to return the connected address
839      * after the socket is closed.
840      *
841 
842      * @return a {@code SocketAddress} representing the remote endpoint of this
843      *         socket, or {@code null} if it is not connected yet.
844      * @see #getInetAddress()
845      * @see #getPort()
846      * @see #connect(SocketAddress, int)
847      * @see #connect(SocketAddress)
848      * @since 1.4
849      */
getRemoteSocketAddress()850     public SocketAddress getRemoteSocketAddress() {
851         if (!isConnected())
852             return null;
853         return new InetSocketAddress(getInetAddress(), getPort());
854     }
855 
856     /**
857      * Returns the address of the endpoint this socket is bound to.
858      * <p>
859      * If a socket bound to an endpoint represented by an
860      * {@code InetSocketAddress } is {@link #close closed},
861      * then this method will continue to return an {@code InetSocketAddress}
862      * after the socket is closed. In that case the returned
863      * {@code InetSocketAddress}'s address is the
864      * {@link InetAddress#isAnyLocalAddress wildcard} address
865      * and its port is the local port that it was bound to.
866      * <p>
867      * If there is a security manager set, its {@code checkConnect} method is
868      * called with the local address and {@code -1} as its arguments to see
869      * if the operation is allowed. If the operation is not allowed,
870      * a {@code SocketAddress} representing the
871      * {@link InetAddress#getLoopbackAddress loopback} address and the local
872      * port to which this socket is bound is returned.
873      *
874      * @return a {@code SocketAddress} representing the local endpoint of
875      *         this socket, or a {@code SocketAddress} representing the
876      *         loopback address if denied by the security manager, or
877      *         {@code null} if the socket is not bound yet.
878      *
879      * @see #getLocalAddress()
880      * @see #getLocalPort()
881      * @see #bind(SocketAddress)
882      * @see SecurityManager#checkConnect
883      * @since 1.4
884      */
885 
getLocalSocketAddress()886     public SocketAddress getLocalSocketAddress() {
887         if (!isBound())
888             return null;
889         return new InetSocketAddress(getLocalAddress(), getLocalPort());
890     }
891 
892     /**
893      * Returns the unique {@link java.nio.channels.SocketChannel SocketChannel}
894      * object associated with this socket, if any.
895      *
896      * <p> A socket will have a channel if, and only if, the channel itself was
897      * created via the {@link java.nio.channels.SocketChannel#open
898      * SocketChannel.open} or {@link
899      * java.nio.channels.ServerSocketChannel#accept ServerSocketChannel.accept}
900      * methods.
901      *
902      * @return  the socket channel associated with this socket,
903      *          or {@code null} if this socket was not created
904      *          for a channel
905      *
906      * @since 1.4
907      * @spec JSR-51
908      */
getChannel()909     public SocketChannel getChannel() {
910         return null;
911     }
912 
913     /**
914      * Returns an input stream for this socket.
915      *
916      * <p> If this socket has an associated channel then the resulting input
917      * stream delegates all of its operations to the channel.  If the channel
918      * is in non-blocking mode then the input stream's {@code read} operations
919      * will throw an {@link java.nio.channels.IllegalBlockingModeException}.
920      *
921      * <p>Under abnormal conditions the underlying connection may be
922      * broken by the remote host or the network software (for example
923      * a connection reset in the case of TCP connections). When a
924      * broken connection is detected by the network software the
925      * following applies to the returned input stream :-
926      *
927      * <ul>
928      *
929      *   <li><p>The network software may discard bytes that are buffered
930      *   by the socket. Bytes that aren't discarded by the network
931      *   software can be read using {@link java.io.InputStream#read read}.
932      *
933      *   <li><p>If there are no bytes buffered on the socket, or all
934      *   buffered bytes have been consumed by
935      *   {@link java.io.InputStream#read read}, then all subsequent
936      *   calls to {@link java.io.InputStream#read read} will throw an
937      *   {@link java.io.IOException IOException}.
938      *
939      *   <li><p>If there are no bytes buffered on the socket, and the
940      *   socket has not been closed using {@link #close close}, then
941      *   {@link java.io.InputStream#available available} will
942      *   return {@code 0}.
943      *
944      * </ul>
945      *
946      * <p> Closing the returned {@link java.io.InputStream InputStream}
947      * will close the associated socket.
948      *
949      * @return     an input stream for reading bytes from this socket.
950      * @exception  IOException  if an I/O error occurs when creating the
951      *             input stream, the socket is closed, the socket is
952      *             not connected, or the socket input has been shutdown
953      *             using {@link #shutdownInput()}
954      *
955      * @revised 1.4
956      * @spec JSR-51
957      */
getInputStream()958     public InputStream getInputStream() throws IOException {
959         if (isClosed())
960             throw new SocketException("Socket is closed");
961         if (!isConnected())
962             throw new SocketException("Socket is not connected");
963         if (isInputShutdown())
964             throw new SocketException("Socket input is shutdown");
965         InputStream is = null;
966         try {
967             is = AccessController.doPrivileged(
968                 new PrivilegedExceptionAction<>() {
969                     public InputStream run() throws IOException {
970                         return impl.getInputStream();
971                     }
972                 });
973         } catch (java.security.PrivilegedActionException e) {
974             throw (IOException) e.getException();
975         }
976         return is;
977     }
978 
979     /**
980      * Returns an output stream for this socket.
981      *
982      * <p> If this socket has an associated channel then the resulting output
983      * stream delegates all of its operations to the channel.  If the channel
984      * is in non-blocking mode then the output stream's {@code write}
985      * operations will throw an {@link
986      * java.nio.channels.IllegalBlockingModeException}.
987      *
988      * <p> Closing the returned {@link java.io.OutputStream OutputStream}
989      * will close the associated socket.
990      *
991      * @return     an output stream for writing bytes to this socket.
992      * @exception  IOException  if an I/O error occurs when creating the
993      *               output stream or if the socket is not connected.
994      * @revised 1.4
995      * @spec JSR-51
996      */
getOutputStream()997     public OutputStream getOutputStream() throws IOException {
998         if (isClosed())
999             throw new SocketException("Socket is closed");
1000         if (!isConnected())
1001             throw new SocketException("Socket is not connected");
1002         if (isOutputShutdown())
1003             throw new SocketException("Socket output is shutdown");
1004         OutputStream os = null;
1005         try {
1006             os = AccessController.doPrivileged(
1007                 new PrivilegedExceptionAction<>() {
1008                     public OutputStream run() throws IOException {
1009                         return impl.getOutputStream();
1010                     }
1011                 });
1012         } catch (java.security.PrivilegedActionException e) {
1013             throw (IOException) e.getException();
1014         }
1015         return os;
1016     }
1017 
1018     /**
1019      * Enable/disable {@link SocketOptions#TCP_NODELAY TCP_NODELAY}
1020      * (disable/enable Nagle's algorithm).
1021      *
1022      * @param on {@code true} to enable TCP_NODELAY,
1023      * {@code false} to disable.
1024      *
1025      * @exception SocketException if there is an error
1026      * in the underlying protocol, such as a TCP error.
1027      *
1028      * @since   1.1
1029      *
1030      * @see #getTcpNoDelay()
1031      */
setTcpNoDelay(boolean on)1032     public void setTcpNoDelay(boolean on) throws SocketException {
1033         if (isClosed())
1034             throw new SocketException("Socket is closed");
1035         getImpl().setOption(SocketOptions.TCP_NODELAY, Boolean.valueOf(on));
1036     }
1037 
1038     /**
1039      * Tests if {@link SocketOptions#TCP_NODELAY TCP_NODELAY} is enabled.
1040      *
1041      * @return a {@code boolean} indicating whether or not
1042      *         {@link SocketOptions#TCP_NODELAY TCP_NODELAY} is enabled.
1043      * @exception SocketException if there is an error
1044      * in the underlying protocol, such as a TCP error.
1045      * @since   1.1
1046      * @see #setTcpNoDelay(boolean)
1047      */
getTcpNoDelay()1048     public boolean getTcpNoDelay() throws SocketException {
1049         if (isClosed())
1050             throw new SocketException("Socket is closed");
1051         return ((Boolean) getImpl().getOption(SocketOptions.TCP_NODELAY)).booleanValue();
1052     }
1053 
1054     /**
1055      * Enable/disable {@link SocketOptions#SO_LINGER SO_LINGER} with the
1056      * specified linger time in seconds. The maximum timeout value is platform
1057      * specific.
1058      *
1059      * The setting only affects socket close.
1060      *
1061      * @param on     whether or not to linger on.
1062      * @param linger how long to linger for, if on is true.
1063      * @exception SocketException if there is an error
1064      * in the underlying protocol, such as a TCP error.
1065      * @exception IllegalArgumentException if the linger value is negative.
1066      * @since 1.1
1067      * @see #getSoLinger()
1068      */
setSoLinger(boolean on, int linger)1069     public void setSoLinger(boolean on, int linger) throws SocketException {
1070         if (isClosed())
1071             throw new SocketException("Socket is closed");
1072         if (!on) {
1073             getImpl().setOption(SocketOptions.SO_LINGER, on);
1074         } else {
1075             if (linger < 0) {
1076                 throw new IllegalArgumentException("invalid value for SO_LINGER");
1077             }
1078             if (linger > 65535)
1079                 linger = 65535;
1080             getImpl().setOption(SocketOptions.SO_LINGER, linger);
1081         }
1082     }
1083 
1084     /**
1085      * Returns setting for {@link SocketOptions#SO_LINGER SO_LINGER}.
1086      * -1 returns implies that the
1087      * option is disabled.
1088      *
1089      * The setting only affects socket close.
1090      *
1091      * @return the setting for {@link SocketOptions#SO_LINGER SO_LINGER}.
1092      * @exception SocketException if there is an error
1093      * in the underlying protocol, such as a TCP error.
1094      * @since   1.1
1095      * @see #setSoLinger(boolean, int)
1096      */
getSoLinger()1097     public int getSoLinger() throws SocketException {
1098         if (isClosed())
1099             throw new SocketException("Socket is closed");
1100         Object o = getImpl().getOption(SocketOptions.SO_LINGER);
1101         if (o instanceof Integer) {
1102             return ((Integer) o).intValue();
1103         } else {
1104             return -1;
1105         }
1106     }
1107 
1108     /**
1109      * Send one byte of urgent data on the socket. The byte to be sent is the lowest eight
1110      * bits of the data parameter. The urgent byte is
1111      * sent after any preceding writes to the socket OutputStream
1112      * and before any future writes to the OutputStream.
1113      * @param data The byte of data to send
1114      * @exception IOException if there is an error
1115      *  sending the data.
1116      * @since 1.4
1117      */
sendUrgentData(int data)1118     public void sendUrgentData (int data) throws IOException  {
1119         // Android-changed: If the socket is closed, sendUrgentData should not create a new impl.
1120         // Fail early to avoid leaking resources.
1121         // http://b/31818400
1122         if (isClosed()) {
1123             throw new SocketException("Socket is closed");
1124         }
1125 
1126         if (!getImpl().supportsUrgentData ()) {
1127             throw new SocketException ("Urgent data not supported");
1128         }
1129         getImpl().sendUrgentData (data);
1130     }
1131 
1132     /**
1133      * Enable/disable {@link SocketOptions#SO_OOBINLINE SO_OOBINLINE}
1134      * (receipt of TCP urgent data)
1135      *
1136      * By default, this option is disabled and TCP urgent data received on a
1137      * socket is silently discarded. If the user wishes to receive urgent data, then
1138      * this option must be enabled. When enabled, urgent data is received
1139      * inline with normal data.
1140      * <p>
1141      * Note, only limited support is provided for handling incoming urgent
1142      * data. In particular, no notification of incoming urgent data is provided
1143      * and there is no capability to distinguish between normal data and urgent
1144      * data unless provided by a higher level protocol.
1145      *
1146      * @param on {@code true} to enable
1147      *           {@link SocketOptions#SO_OOBINLINE SO_OOBINLINE},
1148      *           {@code false} to disable.
1149      *
1150      * @exception SocketException if there is an error
1151      * in the underlying protocol, such as a TCP error.
1152      *
1153      * @since   1.4
1154      *
1155      * @see #getOOBInline()
1156      */
setOOBInline(boolean on)1157     public void setOOBInline(boolean on) throws SocketException {
1158         if (isClosed())
1159             throw new SocketException("Socket is closed");
1160         getImpl().setOption(SocketOptions.SO_OOBINLINE, Boolean.valueOf(on));
1161     }
1162 
1163     /**
1164      * Tests if {@link SocketOptions#SO_OOBINLINE SO_OOBINLINE} is enabled.
1165      *
1166      * @return a {@code boolean} indicating whether or not
1167      *         {@link SocketOptions#SO_OOBINLINE SO_OOBINLINE}is enabled.
1168      *
1169      * @exception SocketException if there is an error
1170      * in the underlying protocol, such as a TCP error.
1171      * @since   1.4
1172      * @see #setOOBInline(boolean)
1173      */
getOOBInline()1174     public boolean getOOBInline() throws SocketException {
1175         if (isClosed())
1176             throw new SocketException("Socket is closed");
1177         return ((Boolean) getImpl().getOption(SocketOptions.SO_OOBINLINE)).booleanValue();
1178     }
1179 
1180     /**
1181      *  Enable/disable {@link SocketOptions#SO_TIMEOUT SO_TIMEOUT}
1182      *  with the specified timeout, in milliseconds. With this option set
1183      *  to a non-zero timeout, a read() call on the InputStream associated with
1184      *  this Socket will block for only this amount of time.  If the timeout
1185      *  expires, a <B>java.net.SocketTimeoutException</B> is raised, though the
1186      *  Socket is still valid. The option <B>must</B> be enabled
1187      *  prior to entering the blocking operation to have effect. The
1188      *  timeout must be {@code > 0}.
1189      *  A timeout of zero is interpreted as an infinite timeout.
1190      *
1191      * @param timeout the specified timeout, in milliseconds.
1192      * @exception SocketException if there is an error
1193      * in the underlying protocol, such as a TCP error.
1194      * @since   1.1
1195      * @see #getSoTimeout()
1196      */
setSoTimeout(int timeout)1197     public synchronized void setSoTimeout(int timeout) throws SocketException {
1198         if (isClosed())
1199             throw new SocketException("Socket is closed");
1200         if (timeout < 0)
1201           throw new IllegalArgumentException("timeout can't be negative");
1202 
1203         getImpl().setOption(SocketOptions.SO_TIMEOUT, timeout);
1204     }
1205 
1206     /**
1207      * Returns setting for {@link SocketOptions#SO_TIMEOUT SO_TIMEOUT}.
1208      * 0 returns implies that the option is disabled (i.e., timeout of infinity).
1209      *
1210      * @return the setting for {@link SocketOptions#SO_TIMEOUT SO_TIMEOUT}
1211      * @exception SocketException if there is an error
1212      * in the underlying protocol, such as a TCP error.
1213      *
1214      * @since   1.1
1215      * @see #setSoTimeout(int)
1216      */
getSoTimeout()1217     public synchronized int getSoTimeout() throws SocketException {
1218         if (isClosed())
1219             throw new SocketException("Socket is closed");
1220         Object o = getImpl().getOption(SocketOptions.SO_TIMEOUT);
1221         /* extra type safety */
1222         if (o instanceof Integer) {
1223             return ((Integer) o).intValue();
1224         } else {
1225             return 0;
1226         }
1227     }
1228 
1229     /**
1230      * Sets the {@link SocketOptions#SO_SNDBUF SO_SNDBUF} option to the
1231      * specified value for this {@code Socket}.
1232      * The {@link SocketOptions#SO_SNDBUF SO_SNDBUF} option is used by the
1233      * platform's networking code as a hint for the size to set the underlying
1234      * network I/O buffers.
1235      *
1236      * <p>Because {@link SocketOptions#SO_SNDBUF SO_SNDBUF} is a hint,
1237      * applications that want to verify what size the buffers were set to
1238      * should call {@link #getSendBufferSize()}.
1239      *
1240      * @exception SocketException if there is an error
1241      * in the underlying protocol, such as a TCP error.
1242      *
1243      * @param size the size to which to set the send buffer
1244      * size. This value must be greater than 0.
1245      *
1246      * @exception IllegalArgumentException if the
1247      * value is 0 or is negative.
1248      *
1249      * @see #getSendBufferSize()
1250      * @since 1.2
1251      */
setSendBufferSize(int size)1252     public synchronized void setSendBufferSize(int size)
1253     throws SocketException{
1254         if (!(size > 0)) {
1255             throw new IllegalArgumentException("negative send size");
1256         }
1257         if (isClosed())
1258             throw new SocketException("Socket is closed");
1259         getImpl().setOption(SocketOptions.SO_SNDBUF, size);
1260     }
1261 
1262     /**
1263      * Get value of the {@link SocketOptions#SO_SNDBUF SO_SNDBUF} option
1264      * for this {@code Socket}, that is the buffer size used by the platform
1265      * for output on this {@code Socket}.
1266      * @return the value of the {@link SocketOptions#SO_SNDBUF SO_SNDBUF}
1267      *         option for this {@code Socket}.
1268      *
1269      * @exception SocketException if there is an error
1270      * in the underlying protocol, such as a TCP error.
1271      *
1272      * @see #setSendBufferSize(int)
1273      * @since 1.2
1274      */
getSendBufferSize()1275     public synchronized int getSendBufferSize() throws SocketException {
1276         if (isClosed())
1277             throw new SocketException("Socket is closed");
1278         int result = 0;
1279         Object o = getImpl().getOption(SocketOptions.SO_SNDBUF);
1280         if (o instanceof Integer) {
1281             result = ((Integer)o).intValue();
1282         }
1283         return result;
1284     }
1285 
1286     /**
1287      * Sets the {@link SocketOptions#SO_RCVBUF SO_RCVBUF} option to the
1288      * specified value for this {@code Socket}. The
1289      * {@link SocketOptions#SO_RCVBUF SO_RCVBUF} option is
1290      * used by the platform's networking code as a hint for the size to set
1291      * the underlying network I/O buffers.
1292      *
1293      * <p>Increasing the receive buffer size can increase the performance of
1294      * network I/O for high-volume connection, while decreasing it can
1295      * help reduce the backlog of incoming data.
1296      *
1297      * <p>Because {@link SocketOptions#SO_RCVBUF SO_RCVBUF} is a hint,
1298      * applications that want to verify what size the buffers were set to
1299      * should call {@link #getReceiveBufferSize()}.
1300      *
1301      * <p>The value of {@link SocketOptions#SO_RCVBUF SO_RCVBUF} is also used
1302      * to set the TCP receive window that is advertized to the remote peer.
1303      * Generally, the window size can be modified at any time when a socket is
1304      * connected. However, if a receive window larger than 64K is required then
1305      * this must be requested <B>before</B> the socket is connected to the
1306      * remote peer. There are two cases to be aware of:
1307      * <ol>
1308      * <li>For sockets accepted from a ServerSocket, this must be done by calling
1309      * {@link ServerSocket#setReceiveBufferSize(int)} before the ServerSocket
1310      * is bound to a local address.</li>
1311      * <li>For client sockets, setReceiveBufferSize() must be called before
1312      * connecting the socket to its remote peer.</li></ol>
1313      * @param size the size to which to set the receive buffer
1314      * size. This value must be greater than 0.
1315      *
1316      * @exception IllegalArgumentException if the value is 0 or is
1317      * negative.
1318      *
1319      * @exception SocketException if there is an error
1320      * in the underlying protocol, such as a TCP error.
1321      *
1322      * @see #getReceiveBufferSize()
1323      * @see ServerSocket#setReceiveBufferSize(int)
1324      * @since 1.2
1325      */
setReceiveBufferSize(int size)1326     public synchronized void setReceiveBufferSize(int size)
1327     throws SocketException{
1328         if (size <= 0) {
1329             throw new IllegalArgumentException("invalid receive size");
1330         }
1331         if (isClosed())
1332             throw new SocketException("Socket is closed");
1333         getImpl().setOption(SocketOptions.SO_RCVBUF, size);
1334     }
1335 
1336     /**
1337      * Gets the value of the {@link SocketOptions#SO_RCVBUF SO_RCVBUF} option
1338      * for this {@code Socket}, that is the buffer size used by the platform
1339      * for input on this {@code Socket}.
1340      *
1341      * @return the value of the {@link SocketOptions#SO_RCVBUF SO_RCVBUF}
1342      *         option for this {@code Socket}.
1343      * @exception SocketException if there is an error
1344      * in the underlying protocol, such as a TCP error.
1345      * @see #setReceiveBufferSize(int)
1346      * @since 1.2
1347      */
getReceiveBufferSize()1348     public synchronized int getReceiveBufferSize()
1349     throws SocketException{
1350         if (isClosed())
1351             throw new SocketException("Socket is closed");
1352         int result = 0;
1353         Object o = getImpl().getOption(SocketOptions.SO_RCVBUF);
1354         if (o instanceof Integer) {
1355             result = ((Integer)o).intValue();
1356         }
1357         return result;
1358     }
1359 
1360     /**
1361      * Enable/disable {@link SocketOptions#SO_KEEPALIVE SO_KEEPALIVE}.
1362      *
1363      * @param on  whether or not to have socket keep alive turned on.
1364      * @exception SocketException if there is an error
1365      * in the underlying protocol, such as a TCP error.
1366      * @since 1.3
1367      * @see #getKeepAlive()
1368      */
setKeepAlive(boolean on)1369     public void setKeepAlive(boolean on) throws SocketException {
1370         if (isClosed())
1371             throw new SocketException("Socket is closed");
1372         getImpl().setOption(SocketOptions.SO_KEEPALIVE, Boolean.valueOf(on));
1373     }
1374 
1375     /**
1376      * Tests if {@link SocketOptions#SO_KEEPALIVE SO_KEEPALIVE} is enabled.
1377      *
1378      * @return a {@code boolean} indicating whether or not
1379      *         {@link SocketOptions#SO_KEEPALIVE SO_KEEPALIVE} is enabled.
1380      * @exception SocketException if there is an error
1381      * in the underlying protocol, such as a TCP error.
1382      * @since   1.3
1383      * @see #setKeepAlive(boolean)
1384      */
getKeepAlive()1385     public boolean getKeepAlive() throws SocketException {
1386         if (isClosed())
1387             throw new SocketException("Socket is closed");
1388         return ((Boolean) getImpl().getOption(SocketOptions.SO_KEEPALIVE)).booleanValue();
1389     }
1390 
1391     /**
1392      * Sets traffic class or type-of-service octet in the IP
1393      * header for packets sent from this Socket.
1394      * As the underlying network implementation may ignore this
1395      * value applications should consider it a hint.
1396      *
1397      * <P> The tc <B>must</B> be in the range {@code 0 <= tc <=
1398      * 255} or an IllegalArgumentException will be thrown.
1399      * <p>Notes:
1400      * <p>For Internet Protocol v4 the value consists of an
1401      * {@code integer}, the least significant 8 bits of which
1402      * represent the value of the TOS octet in IP packets sent by
1403      * the socket.
1404      * RFC 1349 defines the TOS values as follows:
1405      *
1406      * <UL>
1407      * <LI><CODE>IPTOS_LOWCOST (0x02)</CODE></LI>
1408      * <LI><CODE>IPTOS_RELIABILITY (0x04)</CODE></LI>
1409      * <LI><CODE>IPTOS_THROUGHPUT (0x08)</CODE></LI>
1410      * <LI><CODE>IPTOS_LOWDELAY (0x10)</CODE></LI>
1411      * </UL>
1412      * The last low order bit is always ignored as this
1413      * corresponds to the MBZ (must be zero) bit.
1414      * <p>
1415      * Setting bits in the precedence field may result in a
1416      * SocketException indicating that the operation is not
1417      * permitted.
1418      * <p>
1419      * As RFC 1122 section 4.2.4.2 indicates, a compliant TCP
1420      * implementation should, but is not required to, let application
1421      * change the TOS field during the lifetime of a connection.
1422      * So whether the type-of-service field can be changed after the
1423      * TCP connection has been established depends on the implementation
1424      * in the underlying platform. Applications should not assume that
1425      * they can change the TOS field after the connection.
1426      * <p>
1427      * For Internet Protocol v6 {@code tc} is the value that
1428      * would be placed into the sin6_flowinfo field of the IP header.
1429      *
1430      * @param tc        an {@code int} value for the bitset.
1431      * @throws SocketException if there is an error setting the
1432      * traffic class or type-of-service
1433      * @since 1.4
1434      * @see #getTrafficClass
1435      * @see SocketOptions#IP_TOS
1436      */
setTrafficClass(int tc)1437     public void setTrafficClass(int tc) throws SocketException {
1438         if (tc < 0 || tc > 255)
1439             throw new IllegalArgumentException("tc is not in range 0 -- 255");
1440 
1441         if (isClosed())
1442             throw new SocketException("Socket is closed");
1443         try {
1444             getImpl().setOption(SocketOptions.IP_TOS, tc);
1445         } catch (SocketException se) {
1446             // not supported if socket already connected
1447             // Solaris returns error in such cases
1448             if(!isConnected())
1449                 throw se;
1450         }
1451     }
1452 
1453     /**
1454      * Gets traffic class or type-of-service in the IP header
1455      * for packets sent from this Socket
1456      * <p>
1457      * As the underlying network implementation may ignore the
1458      * traffic class or type-of-service set using {@link #setTrafficClass(int)}
1459      * this method may return a different value than was previously
1460      * set using the {@link #setTrafficClass(int)} method on this Socket.
1461      *
1462      * @return the traffic class or type-of-service already set
1463      * @throws SocketException if there is an error obtaining the
1464      * traffic class or type-of-service value.
1465      * @since 1.4
1466      * @see #setTrafficClass(int)
1467      * @see SocketOptions#IP_TOS
1468      */
getTrafficClass()1469     public int getTrafficClass() throws SocketException {
1470         // Android-changed: throw SocketException if the socket is already closed. http://b/31818400
1471         if (isClosed()) {
1472             throw new SocketException("Socket is closed");
1473         }
1474 
1475         return ((Integer) (getImpl().getOption(SocketOptions.IP_TOS))).intValue();
1476     }
1477 
1478     /**
1479      * Enable/disable the {@link SocketOptions#SO_REUSEADDR SO_REUSEADDR}
1480      * socket option.
1481      * <p>
1482      * When a TCP connection is closed the connection may remain
1483      * in a timeout state for a period of time after the connection
1484      * is closed (typically known as the {@code TIME_WAIT} state
1485      * or {@code 2MSL} wait state).
1486      * For applications using a well known socket address or port
1487      * it may not be possible to bind a socket to the required
1488      * {@code SocketAddress} if there is a connection in the
1489      * timeout state involving the socket address or port.
1490      * <p>
1491      * Enabling {@link SocketOptions#SO_REUSEADDR SO_REUSEADDR}
1492      * prior to binding the socket using {@link #bind(SocketAddress)} allows
1493      * the socket to be bound even though a previous connection is in a timeout
1494      * state.
1495      * <p>
1496      * When a {@code Socket} is created the initial setting
1497      * of {@link SocketOptions#SO_REUSEADDR SO_REUSEADDR} is disabled.
1498      * <p>
1499      * The behaviour when {@link SocketOptions#SO_REUSEADDR SO_REUSEADDR} is
1500      * enabled or disabled after a socket is bound (See {@link #isBound()})
1501      * is not defined.
1502      *
1503      * @param on  whether to enable or disable the socket option
1504      * @exception SocketException if an error occurs enabling or
1505      *            disabling the {@link SocketOptions#SO_REUSEADDR SO_REUSEADDR}
1506      *            socket option, or the socket is closed.
1507      * @since 1.4
1508      * @see #getReuseAddress()
1509      * @see #bind(SocketAddress)
1510      * @see #isClosed()
1511      * @see #isBound()
1512      */
setReuseAddress(boolean on)1513     public void setReuseAddress(boolean on) throws SocketException {
1514         if (isClosed())
1515             throw new SocketException("Socket is closed");
1516         getImpl().setOption(SocketOptions.SO_REUSEADDR, Boolean.valueOf(on));
1517     }
1518 
1519     /**
1520      * Tests if {@link SocketOptions#SO_REUSEADDR SO_REUSEADDR} is enabled.
1521      *
1522      * @return a {@code boolean} indicating whether or not
1523      *         {@link SocketOptions#SO_REUSEADDR SO_REUSEADDR} is enabled.
1524      * @exception SocketException if there is an error
1525      * in the underlying protocol, such as a TCP error.
1526      * @since   1.4
1527      * @see #setReuseAddress(boolean)
1528      */
getReuseAddress()1529     public boolean getReuseAddress() throws SocketException {
1530         if (isClosed())
1531             throw new SocketException("Socket is closed");
1532         return ((Boolean) (getImpl().getOption(SocketOptions.SO_REUSEADDR))).booleanValue();
1533     }
1534 
1535     /**
1536      * Closes this socket.
1537      * <p>
1538      * Any thread currently blocked in an I/O operation upon this socket
1539      * will throw a {@link SocketException}.
1540      * <p>
1541      * Once a socket has been closed, it is not available for further networking
1542      * use (i.e. can't be reconnected or rebound). A new socket needs to be
1543      * created.
1544      *
1545      * <p> Closing this socket will also close the socket's
1546      * {@link java.io.InputStream InputStream} and
1547      * {@link java.io.OutputStream OutputStream}.
1548      *
1549      * <p> If this socket has an associated channel then the channel is closed
1550      * as well.
1551      *
1552      * @exception  IOException  if an I/O error occurs when closing this socket.
1553      * @revised 1.4
1554      * @spec JSR-51
1555      * @see #isClosed
1556      */
close()1557     public synchronized void close() throws IOException {
1558         synchronized(closeLock) {
1559             if (isClosed())
1560                 return;
1561             if (created)
1562                 impl.close();
1563             closed = true;
1564         }
1565     }
1566 
1567     /**
1568      * Places the input stream for this socket at "end of stream".
1569      * Any data sent to the input stream side of the socket is acknowledged
1570      * and then silently discarded.
1571      * <p>
1572      * If you read from a socket input stream after invoking this method on the
1573      * socket, the stream's {@code available} method will return 0, and its
1574      * {@code read} methods will return {@code -1} (end of stream).
1575      *
1576      * @exception IOException if an I/O error occurs when shutting down this
1577      * socket.
1578      *
1579      * @since 1.3
1580      * @see java.net.Socket#shutdownOutput()
1581      * @see java.net.Socket#close()
1582      * @see java.net.Socket#setSoLinger(boolean, int)
1583      * @see #isInputShutdown
1584      */
shutdownInput()1585     public void shutdownInput() throws IOException
1586     {
1587         if (isClosed())
1588             throw new SocketException("Socket is closed");
1589         if (!isConnected())
1590             throw new SocketException("Socket is not connected");
1591         if (isInputShutdown())
1592             throw new SocketException("Socket input is already shutdown");
1593         getImpl().shutdownInput();
1594         shutIn = true;
1595     }
1596 
1597     /**
1598      * Disables the output stream for this socket.
1599      * For a TCP socket, any previously written data will be sent
1600      * followed by TCP's normal connection termination sequence.
1601      *
1602      * If you write to a socket output stream after invoking
1603      * shutdownOutput() on the socket, the stream will throw
1604      * an IOException.
1605      *
1606      * @exception IOException if an I/O error occurs when shutting down this
1607      * socket.
1608      *
1609      * @since 1.3
1610      * @see java.net.Socket#shutdownInput()
1611      * @see java.net.Socket#close()
1612      * @see java.net.Socket#setSoLinger(boolean, int)
1613      * @see #isOutputShutdown
1614      */
shutdownOutput()1615     public void shutdownOutput() throws IOException
1616     {
1617         if (isClosed())
1618             throw new SocketException("Socket is closed");
1619         if (!isConnected())
1620             throw new SocketException("Socket is not connected");
1621         if (isOutputShutdown())
1622             throw new SocketException("Socket output is already shutdown");
1623         getImpl().shutdownOutput();
1624         shutOut = true;
1625     }
1626 
1627     /**
1628      * Converts this socket to a {@code String}.
1629      *
1630      * @return  a string representation of this socket.
1631      */
toString()1632     public String toString() {
1633         try {
1634             // Android-changed: change localport to localPort, and addr to address.
1635             if (isConnected())
1636                 return "Socket[address=" + getImpl().getInetAddress() +
1637                     ",port=" + getImpl().getPort() +
1638                     ",localPort=" + getImpl().getLocalPort() + "]";
1639         } catch (SocketException e) {
1640         }
1641         return "Socket[unconnected]";
1642     }
1643 
1644     /**
1645      * Returns the connection state of the socket.
1646      * <p>
1647      * Note: Closing a socket doesn't clear its connection state, which means
1648      * this method will return {@code true} for a closed socket
1649      * (see {@link #isClosed()}) if it was successfuly connected prior
1650      * to being closed.
1651      *
1652      * @return true if the socket was successfuly connected to a server
1653      * @since 1.4
1654      */
isConnected()1655     public boolean isConnected() {
1656         // Before 1.3 Sockets were always connected during creation
1657         return connected || oldImpl;
1658     }
1659 
1660     /**
1661      * Returns the binding state of the socket.
1662      * <p>
1663      * Note: Closing a socket doesn't clear its binding state, which means
1664      * this method will return {@code true} for a closed socket
1665      * (see {@link #isClosed()}) if it was successfuly bound prior
1666      * to being closed.
1667      *
1668      * @return true if the socket was successfuly bound to an address
1669      * @since 1.4
1670      * @see #bind
1671      */
isBound()1672     public boolean isBound() {
1673         // Before 1.3 Sockets were always bound during creation
1674         return bound || oldImpl;
1675     }
1676 
1677     /**
1678      * Returns the closed state of the socket.
1679      *
1680      * @return true if the socket has been closed
1681      * @since 1.4
1682      * @see #close
1683      */
isClosed()1684     public boolean isClosed() {
1685         synchronized(closeLock) {
1686             return closed;
1687         }
1688     }
1689 
1690     /**
1691      * Returns whether the read-half of the socket connection is closed.
1692      *
1693      * @return true if the input of the socket has been shutdown
1694      * @since 1.4
1695      * @see #shutdownInput
1696      */
isInputShutdown()1697     public boolean isInputShutdown() {
1698         return shutIn;
1699     }
1700 
1701     /**
1702      * Returns whether the write-half of the socket connection is closed.
1703      *
1704      * @return true if the output of the socket has been shutdown
1705      * @since 1.4
1706      * @see #shutdownOutput
1707      */
isOutputShutdown()1708     public boolean isOutputShutdown() {
1709         return shutOut;
1710     }
1711 
1712     /**
1713      * The factory for all client sockets.
1714      */
1715     private static SocketImplFactory factory = null;
1716 
1717     /**
1718      * Sets the client socket implementation factory for the
1719      * application. The factory can be specified only once.
1720      * <p>
1721      * When an application creates a new client socket, the socket
1722      * implementation factory's {@code createSocketImpl} method is
1723      * called to create the actual socket implementation.
1724      * <p>
1725      * Passing {@code null} to the method is a no-op unless the factory
1726      * was already set.
1727      * <p>If there is a security manager, this method first calls
1728      * the security manager's {@code checkSetFactory} method
1729      * to ensure the operation is allowed.
1730      * This could result in a SecurityException.
1731      *
1732      * @param      fac   the desired factory.
1733      * @exception  IOException  if an I/O error occurs when setting the
1734      *               socket factory.
1735      * @exception  SocketException  if the factory is already defined.
1736      * @exception  SecurityException  if a security manager exists and its
1737      *             {@code checkSetFactory} method doesn't allow the operation.
1738      * @see        java.net.SocketImplFactory#createSocketImpl()
1739      * @see        SecurityManager#checkSetFactory
1740      */
setSocketImplFactory(SocketImplFactory fac)1741     public static synchronized void setSocketImplFactory(SocketImplFactory fac)
1742         throws IOException
1743     {
1744         if (factory != null) {
1745             throw new SocketException("factory already defined");
1746         }
1747         SecurityManager security = System.getSecurityManager();
1748         if (security != null) {
1749             security.checkSetFactory();
1750         }
1751         factory = fac;
1752     }
1753 
1754     /**
1755      * Sets performance preferences for this socket.
1756      *
1757      * <p> Sockets use the TCP/IP protocol by default.  Some implementations
1758      * may offer alternative protocols which have different performance
1759      * characteristics than TCP/IP.  This method allows the application to
1760      * express its own preferences as to how these tradeoffs should be made
1761      * when the implementation chooses from the available protocols.
1762      *
1763      * <p> Performance preferences are described by three integers
1764      * whose values indicate the relative importance of short connection time,
1765      * low latency, and high bandwidth.  The absolute values of the integers
1766      * are irrelevant; in order to choose a protocol the values are simply
1767      * compared, with larger values indicating stronger preferences. Negative
1768      * values represent a lower priority than positive values. If the
1769      * application prefers short connection time over both low latency and high
1770      * bandwidth, for example, then it could invoke this method with the values
1771      * {@code (1, 0, 0)}.  If the application prefers high bandwidth above low
1772      * latency, and low latency above short connection time, then it could
1773      * invoke this method with the values {@code (0, 1, 2)}.
1774      *
1775      * <p> Invoking this method after this socket has been connected
1776      * will have no effect.
1777      *
1778      * @param  connectionTime
1779      *         An {@code int} expressing the relative importance of a short
1780      *         connection time
1781      *
1782      * @param  latency
1783      *         An {@code int} expressing the relative importance of low
1784      *         latency
1785      *
1786      * @param  bandwidth
1787      *         An {@code int} expressing the relative importance of high
1788      *         bandwidth
1789      *
1790      * @since 1.5
1791      */
setPerformancePreferences(int connectionTime, int latency, int bandwidth)1792     public void setPerformancePreferences(int connectionTime,
1793                                           int latency,
1794                                           int bandwidth)
1795     {
1796         /* Not implemented yet */
1797     }
1798 
1799 
1800     /**
1801      * Sets the value of a socket option.
1802      *
1803      * @param <T> The type of the socket option value
1804      * @param name The socket option
1805      * @param value The value of the socket option. A value of {@code null}
1806      *              may be valid for some options.
1807      * @return this Socket
1808      *
1809      * @throws UnsupportedOperationException if the socket does not support
1810      *         the option.
1811      *
1812      * @throws IllegalArgumentException if the value is not valid for
1813      *         the option.
1814      *
1815      * @throws IOException if an I/O error occurs, or if the socket is closed.
1816      *
1817      * @throws NullPointerException if name is {@code null}
1818      *
1819      * @throws SecurityException if a security manager is set and if the socket
1820      *         option requires a security permission and if the caller does
1821      *         not have the required permission.
1822      *         {@link java.net.StandardSocketOptions StandardSocketOptions}
1823      *         do not require any security permission.
1824      *
1825      * @since 9
1826      */
setOption(SocketOption<T> name, T value)1827     public <T> Socket setOption(SocketOption<T> name, T value) throws IOException {
1828         getImpl().setOption(name, value);
1829         return this;
1830     }
1831 
1832     /**
1833      * Returns the value of a socket option.
1834      *
1835      * @param <T> The type of the socket option value
1836      * @param name The socket option
1837      *
1838      * @return The value of the socket option.
1839      *
1840      * @throws UnsupportedOperationException if the socket does not support
1841      *         the option.
1842      *
1843      * @throws IOException if an I/O error occurs, or if the socket is closed.
1844      *
1845      * @throws NullPointerException if name is {@code null}
1846      *
1847      * @throws SecurityException if a security manager is set and if the socket
1848      *         option requires a security permission and if the caller does
1849      *         not have the required permission.
1850      *         {@link java.net.StandardSocketOptions StandardSocketOptions}
1851      *         do not require any security permission.
1852      *
1853      * @since 9
1854      */
1855     @SuppressWarnings("unchecked")
getOption(SocketOption<T> name)1856     public <T> T getOption(SocketOption<T> name) throws IOException {
1857         return getImpl().getOption(name);
1858     }
1859 
1860     private static Set<SocketOption<?>> options;
1861     private static boolean optionsSet = false;
1862 
1863     /**
1864      * Returns a set of the socket options supported by this socket.
1865      *
1866      * This method will continue to return the set of options even after
1867      * the socket has been closed.
1868      *
1869      * @return A set of the socket options supported by this socket. This set
1870      *         may be empty if the socket's SocketImpl cannot be created.
1871      *
1872      * @since 9
1873      */
supportedOptions()1874     public Set<SocketOption<?>> supportedOptions() {
1875         synchronized (Socket.class) {
1876             if (optionsSet) {
1877                 return options;
1878             }
1879             try {
1880                 SocketImpl impl = getImpl();
1881                 options = Collections.unmodifiableSet(impl.supportedOptions());
1882             } catch (IOException e) {
1883                 options = Collections.emptySet();
1884             }
1885             optionsSet = true;
1886             return options;
1887         }
1888     }
1889 
1890     // Android-added: getFileDescriptor$() method for testing and internal use.
1891     /**
1892      * Gets socket's underlying {@link FileDescriptor}.
1893      *
1894      * @hide internal use only
1895      *
1896      * @return socket's underlying {@link FileDescriptor}.
1897      */
getFileDescriptor$()1898     public FileDescriptor getFileDescriptor$() {
1899         return impl.getFileDescriptor();
1900     }
1901 }
1902