1 /*
2  * Copyright (c) 2014, 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 jdk.net;
27 
28 import java.io.FileDescriptor;
29 import java.net.SocketException;
30 import java.net.SocketOption;
31 import java.security.AccessController;
32 import java.security.PrivilegedAction;
33 import java.util.Collections;
34 import java.util.HashSet;
35 import java.util.Set;
36 import jdk.internal.access.JavaIOFileDescriptorAccess;
37 import jdk.internal.access.SharedSecrets;
38 
39 /**
40  * Defines extended socket options, beyond those defined in
41  * {@link java.net.StandardSocketOptions}. These options may be platform
42  * specific.
43  *
44  * @since 1.8
45  */
46 // Android-removed: @jdk.Exported, not present on Android.
47 // @jdk.Exported
48 public final class ExtendedSocketOptions {
49 
50     private static class ExtSocketOption<T> implements SocketOption<T> {
51         private final String name;
52         private final Class<T> type;
ExtSocketOption(String name, Class<T> type)53         ExtSocketOption(String name, Class<T> type) {
54             this.name = name;
55             this.type = type;
56         }
name()57         @Override public String name() { return name; }
type()58         @Override public Class<T> type() { return type; }
toString()59         @Override public String toString() { return name; }
60     }
61 
ExtendedSocketOptions()62     private ExtendedSocketOptions() { }
63 
64     /**
65      * Service level properties. When a security manager is installed,
66      * setting or getting this option requires a {@link NetworkPermission}
67      * {@code ("setOption.SO_FLOW_SLA")} or {@code "getOption.SO_FLOW_SLA"}
68      * respectively.
69      */
70     public static final SocketOption<SocketFlow> SO_FLOW_SLA = new
71         ExtSocketOption<SocketFlow>("SO_FLOW_SLA", SocketFlow.class);
72 
73     /**
74      * Disable Delayed Acknowledgements.
75      *
76      * <p>
77      * This socket option can be used to reduce or disable delayed
78      * acknowledgments (ACKs). When {@code TCP_QUICKACK} is enabled, ACKs are
79      * sent immediately, rather than delayed if needed in accordance to normal
80      * TCP operation. This option is not permanent, it only enables a switch to
81      * or from {@code TCP_QUICKACK} mode. Subsequent operations of the TCP
82      * protocol will once again disable/enable {@code TCP_QUICKACK} mode
83      * depending on internal protocol processing and factors such as delayed ACK
84      * timeouts occurring and data transfer, therefore this option needs to be
85      * set with {@code setOption} after each operation of TCP on a given socket.
86      *
87      * <p>
88      * The value of this socket option is a {@code Boolean} that represents
89      * whether the option is enabled or disabled. The socket option is specific
90      * to stream-oriented sockets using the TCP/IP protocol. The exact semantics
91      * of this socket option are socket type and system dependent.
92      *
93      * @since 10
94      */
95     public static final SocketOption<Boolean> TCP_QUICKACK =
96             new ExtSocketOption<Boolean>("TCP_QUICKACK", Boolean.class);
97 
98     /**
99      * Keep-Alive idle time.
100      *
101      * <p>
102      * The value of this socket option is an {@code Integer} that is the number
103      * of seconds of idle time before keep-alive initiates a probe. The socket
104      * option is specific to stream-oriented sockets using the TCP/IP protocol.
105      * The exact semantics of this socket option are system dependent.
106      *
107      * <p>
108      * When the {@link java.net.StandardSocketOptions#SO_KEEPALIVE
109      * SO_KEEPALIVE} option is enabled, TCP probes a connection that has been
110      * idle for some amount of time. The default value for this idle period is
111      * system dependent, but is typically 2 hours. The {@code TCP_KEEPIDLE}
112      * option can be used to affect this value for a given socket.
113      *
114      * @since 11
115      */
116     public static final SocketOption<Integer> TCP_KEEPIDLE
117             = new ExtSocketOption<Integer>("TCP_KEEPIDLE", Integer.class);
118 
119     /**
120      * Keep-Alive retransmission interval time.
121      *
122      * <p>
123      * The value of this socket option is an {@code Integer} that is the number
124      * of seconds to wait before retransmitting a keep-alive probe. The socket
125      * option is specific to stream-oriented sockets using the TCP/IP protocol.
126      * The exact semantics of this socket option are system dependent.
127      *
128      * <p>
129      * When the {@link java.net.StandardSocketOptions#SO_KEEPALIVE
130      * SO_KEEPALIVE} option is enabled, TCP probes a connection that has been
131      * idle for some amount of time. If the remote system does not respond to a
132      * keep-alive probe, TCP retransmits the probe after some amount of time.
133      * The default value for this retransmission interval is system dependent,
134      * but is typically 75 seconds. The {@code TCP_KEEPINTERVAL} option can be
135      * used to affect this value for a given socket.
136      *
137      * @since 11
138      */
139     public static final SocketOption<Integer> TCP_KEEPINTERVAL
140             = new ExtSocketOption<Integer>("TCP_KEEPINTERVAL", Integer.class);
141 
142     /**
143      * Keep-Alive retransmission maximum limit.
144      *
145      * <p>
146      * The value of this socket option is an {@code Integer} that is the maximum
147      * number of keep-alive probes to be sent. The socket option is specific to
148      * stream-oriented sockets using the TCP/IP protocol. The exact semantics of
149      * this socket option are system dependent.
150      *
151      * <p>
152      * When the {@link java.net.StandardSocketOptions#SO_KEEPALIVE
153      * SO_KEEPALIVE} option is enabled, TCP probes a connection that has been
154      * idle for some amount of time. If the remote system does not respond to a
155      * keep-alive probe, TCP retransmits the probe a certain number of times
156      * before a connection is considered to be broken. The default value for
157      * this keep-alive probe retransmit limit is system dependent, but is
158      * typically 8. The {@code TCP_KEEPCOUNT} option can be used to affect this
159      * value for a given socket.
160      *
161      * @since 11
162      */
163     public static final SocketOption<Integer> TCP_KEEPCOUNT
164             = new ExtSocketOption<Integer>("TCP_KEEPCOUNT", Integer.class);
165 
166     private static final PlatformSocketOptions platformSocketOptions =
167             PlatformSocketOptions.get();
168 
169     private static final boolean flowSupported =
170             platformSocketOptions.flowSupported();
171     private static final boolean quickAckSupported =
172             platformSocketOptions.quickAckSupported();
173     private static final boolean keepAliveOptSupported =
174             platformSocketOptions.keepAliveOptionsSupported();
175     private static final Set<SocketOption<?>> extendedOptions = options();
176 
options()177     static Set<SocketOption<?>> options() {
178         Set<SocketOption<?>> options = new HashSet<>();
179         if (flowSupported) {
180             options.add(SO_FLOW_SLA);
181         }
182         if (quickAckSupported) {
183             options.add(TCP_QUICKACK);
184         }
185         if (keepAliveOptSupported) {
186             options.addAll(Set.of(TCP_KEEPCOUNT, TCP_KEEPIDLE, TCP_KEEPINTERVAL));
187         }
188         return Collections.unmodifiableSet(options);
189     }
190 
191     static {
192         // Registers the extended socket options with the base module.
sun.net.ext.ExtendedSocketOptions.register( new sun.net.ext.ExtendedSocketOptions(extendedOptions) { @Override public void setOption(FileDescriptor fd, SocketOption<?> option, Object value) throws SocketException { SecurityManager sm = System.getSecurityManager(); if (sm != null) sm.checkPermission(new NetworkPermission("setOption." + option.name())); if (fd == null || !fd.valid()) throw new SocketException("socket closed"); if (option == SO_FLOW_SLA) { assert flowSupported; SocketFlow flow = checkValueType(value, option.type()); setFlowOption(fd, flow); } else if (option == TCP_QUICKACK) { setQuickAckOption(fd, (boolean) value); } else if (option == TCP_KEEPCOUNT) { setTcpkeepAliveProbes(fd, (Integer) value); } else if (option == TCP_KEEPIDLE) { setTcpKeepAliveTime(fd, (Integer) value); } else if (option == TCP_KEEPINTERVAL) { setTcpKeepAliveIntvl(fd, (Integer) value); } else { throw new InternalError("Unexpected option " + option); } } @Override public Object getOption(FileDescriptor fd, SocketOption<?> option) throws SocketException { SecurityManager sm = System.getSecurityManager(); if (sm != null) sm.checkPermission(new NetworkPermission("getOption." + option.name())); if (fd == null || !fd.valid()) throw new SocketException("socket closed"); if (option == SO_FLOW_SLA) { assert flowSupported; SocketFlow flow = SocketFlow.create(); getFlowOption(fd, flow); return flow; } else if (option == TCP_QUICKACK) { return getQuickAckOption(fd); } else if (option == TCP_KEEPCOUNT) { return getTcpkeepAliveProbes(fd); } else if (option == TCP_KEEPIDLE) { return getTcpKeepAliveTime(fd); } else if (option == TCP_KEEPINTERVAL) { return getTcpKeepAliveIntvl(fd); } else { throw new InternalError("Unexpected option " + option); } } })193         sun.net.ext.ExtendedSocketOptions.register(
194                 new sun.net.ext.ExtendedSocketOptions(extendedOptions) {
195 
196             @Override
197             public void setOption(FileDescriptor fd,
198                                   SocketOption<?> option,
199                                   Object value)
200                 throws SocketException
201             {
202                 SecurityManager sm = System.getSecurityManager();
203                 if (sm != null)
204                     sm.checkPermission(new NetworkPermission("setOption." + option.name()));
205 
206                 if (fd == null || !fd.valid())
207                     throw new SocketException("socket closed");
208 
209                 if (option == SO_FLOW_SLA) {
210                     assert flowSupported;
211                     SocketFlow flow = checkValueType(value, option.type());
212                     setFlowOption(fd, flow);
213                 } else if (option == TCP_QUICKACK) {
214                     setQuickAckOption(fd, (boolean) value);
215                 } else if (option == TCP_KEEPCOUNT) {
216                     setTcpkeepAliveProbes(fd, (Integer) value);
217                 } else if (option == TCP_KEEPIDLE) {
218                     setTcpKeepAliveTime(fd, (Integer) value);
219                 } else if (option == TCP_KEEPINTERVAL) {
220                     setTcpKeepAliveIntvl(fd, (Integer) value);
221                 } else {
222                     throw new InternalError("Unexpected option " + option);
223                 }
224             }
225 
226             @Override
227             public Object getOption(FileDescriptor fd,
228                                     SocketOption<?> option)
229                 throws SocketException
230             {
231                 SecurityManager sm = System.getSecurityManager();
232                 if (sm != null)
233                     sm.checkPermission(new NetworkPermission("getOption." + option.name()));
234 
235                 if (fd == null || !fd.valid())
236                     throw new SocketException("socket closed");
237 
238                 if (option == SO_FLOW_SLA) {
239                     assert flowSupported;
240                     SocketFlow flow = SocketFlow.create();
241                     getFlowOption(fd, flow);
242                     return flow;
243                 } else if (option == TCP_QUICKACK) {
244                     return getQuickAckOption(fd);
245                 } else if (option == TCP_KEEPCOUNT) {
246                     return getTcpkeepAliveProbes(fd);
247                 } else if (option == TCP_KEEPIDLE) {
248                     return getTcpKeepAliveTime(fd);
249                 } else if (option == TCP_KEEPINTERVAL) {
250                     return getTcpKeepAliveIntvl(fd);
251                 } else {
252                     throw new InternalError("Unexpected option " + option);
253                 }
254             }
255         });
256     }
257 
258     @SuppressWarnings("unchecked")
checkValueType(Object value, Class<?> type)259     private static <T> T checkValueType(Object value, Class<?> type) {
260         if (!type.isAssignableFrom(value.getClass())) {
261             String s = "Found: " + value.getClass() + ", Expected: " + type;
262             throw new IllegalArgumentException(s);
263         }
264         return (T) value;
265     }
266 
267     private static final JavaIOFileDescriptorAccess fdAccess =
268             SharedSecrets.getJavaIOFileDescriptorAccess();
269 
setFlowOption(FileDescriptor fd, SocketFlow f)270     private static void setFlowOption(FileDescriptor fd, SocketFlow f)
271         throws SocketException
272     {
273         int status = platformSocketOptions.setFlowOption(fdAccess.get(fd),
274                                                          f.priority(),
275                                                          f.bandwidth());
276         f.status(status);  // augment the given flow with the status
277     }
278 
getFlowOption(FileDescriptor fd, SocketFlow f)279     private static void getFlowOption(FileDescriptor fd, SocketFlow f)
280             throws SocketException {
281         int status = platformSocketOptions.getFlowOption(fdAccess.get(fd), f);
282         f.status(status);  // augment the given flow with the status
283     }
284 
setQuickAckOption(FileDescriptor fd, boolean enable)285     private static void setQuickAckOption(FileDescriptor fd, boolean enable)
286             throws SocketException {
287         platformSocketOptions.setQuickAck(fdAccess.get(fd), enable);
288     }
289 
getQuickAckOption(FileDescriptor fd)290     private static Object getQuickAckOption(FileDescriptor fd)
291             throws SocketException {
292         return platformSocketOptions.getQuickAck(fdAccess.get(fd));
293     }
294 
setTcpkeepAliveProbes(FileDescriptor fd, int value)295     private static void setTcpkeepAliveProbes(FileDescriptor fd, int value)
296             throws SocketException {
297         platformSocketOptions.setTcpkeepAliveProbes(fdAccess.get(fd), value);
298     }
299 
setTcpKeepAliveTime(FileDescriptor fd, int value)300     private static void setTcpKeepAliveTime(FileDescriptor fd, int value)
301             throws SocketException {
302         platformSocketOptions.setTcpKeepAliveTime(fdAccess.get(fd), value);
303     }
304 
setTcpKeepAliveIntvl(FileDescriptor fd, int value)305     private static void setTcpKeepAliveIntvl(FileDescriptor fd, int value)
306             throws SocketException {
307         platformSocketOptions.setTcpKeepAliveIntvl(fdAccess.get(fd), value);
308     }
309 
getTcpkeepAliveProbes(FileDescriptor fd)310     private static int getTcpkeepAliveProbes(FileDescriptor fd) throws SocketException {
311         return platformSocketOptions.getTcpkeepAliveProbes(fdAccess.get(fd));
312     }
313 
getTcpKeepAliveTime(FileDescriptor fd)314     private static int getTcpKeepAliveTime(FileDescriptor fd) throws SocketException {
315         return platformSocketOptions.getTcpKeepAliveTime(fdAccess.get(fd));
316     }
317 
getTcpKeepAliveIntvl(FileDescriptor fd)318     private static int getTcpKeepAliveIntvl(FileDescriptor fd) throws SocketException {
319         return platformSocketOptions.getTcpKeepAliveIntvl(fdAccess.get(fd));
320     }
321 
322     static class PlatformSocketOptions {
323 
PlatformSocketOptions()324         protected PlatformSocketOptions() {}
325 
326         @SuppressWarnings("unchecked")
newInstance(String cn)327         private static PlatformSocketOptions newInstance(String cn) {
328             Class<PlatformSocketOptions> c;
329             try {
330                 c = (Class<PlatformSocketOptions>)Class.forName(cn);
331                 return c.getConstructor(new Class<?>[] { }).newInstance();
332             } catch (ReflectiveOperationException x) {
333                 throw new AssertionError(x);
334             }
335         }
336 
create()337         private static PlatformSocketOptions create() {
338             // Android-removed: other platforms are unsupported.
339 //            String osname = AccessController.doPrivileged(
340 //                    new PrivilegedAction<String>() {
341 //                        public String run() {
342 //                            return System.getProperty("os.name");
343 //                        }
344 //                    });
345 //            if ("SunOS".equals(osname)) {
346 //                return newInstance("jdk.net.SolarisSocketOptions");
347 //            } else if ("Linux".equals(osname)) {
348 //                return newInstance("jdk.net.LinuxSocketOptions");
349 //            } else if (osname.startsWith("Mac")) {
350 //                return newInstance("jdk.net.MacOSXSocketOptions");
351 //            }
352             return new PlatformSocketOptions();
353         }
354 
355         private static final PlatformSocketOptions instance = create();
356 
get()357         static PlatformSocketOptions get() {
358             return instance;
359         }
360 
setFlowOption(int fd, int priority, long bandwidth)361         int setFlowOption(int fd, int priority, long bandwidth)
362             throws SocketException
363         {
364             throw new UnsupportedOperationException("unsupported socket option");
365         }
366 
getFlowOption(int fd, SocketFlow f)367         int getFlowOption(int fd, SocketFlow f) throws SocketException {
368             throw new UnsupportedOperationException("unsupported socket option");
369         }
370 
flowSupported()371         boolean flowSupported() {
372             return false;
373         }
374 
setQuickAck(int fd, boolean on)375         void setQuickAck(int fd, boolean on) throws SocketException {
376             throw new UnsupportedOperationException("unsupported TCP_QUICKACK option");
377         }
378 
getQuickAck(int fd)379         boolean getQuickAck(int fd) throws SocketException {
380             throw new UnsupportedOperationException("unsupported TCP_QUICKACK option");
381         }
382 
quickAckSupported()383         boolean quickAckSupported() {
384             return false;
385         }
386 
keepAliveOptionsSupported()387         boolean keepAliveOptionsSupported() {
388             return false;
389         }
390 
setTcpkeepAliveProbes(int fd, final int value)391         void setTcpkeepAliveProbes(int fd, final int value) throws SocketException {
392             throw new UnsupportedOperationException("unsupported TCP_KEEPCNT option");
393         }
394 
setTcpKeepAliveTime(int fd, final int value)395         void setTcpKeepAliveTime(int fd, final int value) throws SocketException {
396             throw new UnsupportedOperationException("unsupported TCP_KEEPIDLE option");
397         }
398 
setTcpKeepAliveIntvl(int fd, final int value)399         void setTcpKeepAliveIntvl(int fd, final int value) throws SocketException {
400             throw new UnsupportedOperationException("unsupported TCP_KEEPINTVL option");
401         }
402 
getTcpkeepAliveProbes(int fd)403         int getTcpkeepAliveProbes(int fd) throws SocketException {
404             throw new UnsupportedOperationException("unsupported TCP_KEEPCNT option");
405         }
406 
getTcpKeepAliveTime(int fd)407         int getTcpKeepAliveTime(int fd) throws SocketException {
408             throw new UnsupportedOperationException("unsupported TCP_KEEPIDLE option");
409         }
410 
getTcpKeepAliveIntvl(int fd)411         int getTcpKeepAliveIntvl(int fd) throws SocketException {
412             throw new UnsupportedOperationException("unsupported TCP_KEEPINTVL option");
413         }
414     }
415 }
416