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