src/jdk.dns.client/share/classes/jdk/dns/client/internal/DnsDatagramChannelFactory.java
branchaefimov-dns-client-branch
changeset 58870 35c438a6d45c
equal deleted inserted replaced
58869:cc66ac8c7646 58870:35c438a6d45c
       
     1 /*
       
     2  * Copyright (c) 2019, 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.dns.client.internal;
       
    27 
       
    28 import java.io.IOException;
       
    29 import java.net.InetSocketAddress;
       
    30 import java.net.ProtocolFamily;
       
    31 import java.net.SocketException;
       
    32 import java.nio.channels.DatagramChannel;
       
    33 import java.util.Objects;
       
    34 import java.util.Random;
       
    35 import java.util.concurrent.locks.ReentrantLock;
       
    36 
       
    37 class DnsDatagramChannelFactory {
       
    38     static final int DEVIATION = 3;
       
    39     static final int THRESHOLD = 6;
       
    40     static final int BIT_DEVIATION = 2;
       
    41     static final int HISTORY = 32;
       
    42     static final int MAX_RANDOM_TRIES = 5;
       
    43 
       
    44     /**
       
    45      * The dynamic allocation port range (aka ephemeral ports), as configured
       
    46      * on the system. Use nested class for lazy evaluation.
       
    47      */
       
    48     static final class EphemeralPortRange {
       
    49         private EphemeralPortRange() {
       
    50         }
       
    51 
       
    52         static final int LOWER = PortConfig.getLower();
       
    53         static final int UPPER = PortConfig.getUpper();
       
    54         static final int RANGE = UPPER - LOWER + 1;
       
    55     }
       
    56 
       
    57     // Records a subset of max {@code capacity} previously used ports
       
    58     static final class PortHistory {
       
    59         final int capacity;
       
    60         final int[] ports;
       
    61         final Random random;
       
    62         int index;
       
    63 
       
    64         PortHistory(int capacity, Random random) {
       
    65             this.random = random;
       
    66             this.capacity = capacity;
       
    67             this.ports = new int[capacity];
       
    68         }
       
    69 
       
    70         // returns true if the history contains the specified port.
       
    71         public boolean contains(int port) {
       
    72             int p = 0;
       
    73             for (int i = 0; i < capacity; i++) {
       
    74                 if ((p = ports[i]) == 0 || p == port) break;
       
    75             }
       
    76             return p == port;
       
    77         }
       
    78 
       
    79         // Adds the port to the history - doesn't check whether the port
       
    80         // is already present. Always adds the port and always return true.
       
    81         public boolean add(int port) {
       
    82             if (ports[index] != 0) { // at max capacity
       
    83                 // remove one port at random and store the new port there
       
    84                 ports[random.nextInt(capacity)] = port;
       
    85             } else { // there's a free slot
       
    86                 ports[index] = port;
       
    87             }
       
    88             if (++index == capacity) index = 0;
       
    89             return true;
       
    90         }
       
    91 
       
    92         // Adds the port to the history if not already present.
       
    93         // Return true if the port was added, false if the port was already
       
    94         // present.
       
    95         public boolean offer(int port) {
       
    96             if (contains(port)) return false;
       
    97             else return add(port);
       
    98         }
       
    99     }
       
   100 
       
   101     int lastport = 0;
       
   102     int suitablePortCount;
       
   103     int unsuitablePortCount;
       
   104     final ProtocolFamily family; // null (default) means dual stack
       
   105     final int thresholdCount; // decision point
       
   106     final int deviation;
       
   107     final Random random;
       
   108     final PortHistory history;
       
   109     final ReentrantLock factoryLock = new ReentrantLock();
       
   110 
       
   111     DnsDatagramChannelFactory() {
       
   112         this(new Random());
       
   113     }
       
   114 
       
   115     DnsDatagramChannelFactory(Random random) {
       
   116         this(Objects.requireNonNull(random), null, DEVIATION, THRESHOLD);
       
   117     }
       
   118 
       
   119     DnsDatagramChannelFactory(Random random,
       
   120                               ProtocolFamily family,
       
   121                               int deviation,
       
   122                               int threshold) {
       
   123         this.random = Objects.requireNonNull(random);
       
   124         this.history = new PortHistory(HISTORY, random);
       
   125         this.family = family;
       
   126         this.deviation = Math.max(1, deviation);
       
   127         this.thresholdCount = Math.max(2, threshold);
       
   128     }
       
   129 
       
   130     /**
       
   131      * Opens a datagram socket listening to the wildcard address on a
       
   132      * random port. If the underlying OS supports UDP port randomization
       
   133      * out of the box (if binding a socket to port 0 binds it to a random
       
   134      * port) then the underlying OS implementation is used. Otherwise, this
       
   135      * method will allocate and bind a socket on a randomly selected ephemeral
       
   136      * port in the dynamic range.
       
   137      *
       
   138      * @return A new DatagramChannel bound to a random port.
       
   139      * @throws SocketException if the socket cannot be created.
       
   140      */
       
   141     public DatagramChannel open() throws SocketException {
       
   142         factoryLock.lock();
       
   143         try {
       
   144             int lastseen = lastport;
       
   145             DatagramChannel dc;
       
   146 
       
   147             boolean thresholdCrossed = unsuitablePortCount > thresholdCount;
       
   148             if (thresholdCrossed) {
       
   149                 // Underlying stack does not support random UDP port out of the box.
       
   150                 // Use our own algorithm to allocate a random UDP port
       
   151                 dc = openRandom();
       
   152                 if (dc != null) return dc;
       
   153 
       
   154                 // couldn't allocate a random port: reset all counters and fall
       
   155                 // through.
       
   156                 unsuitablePortCount = 0;
       
   157                 suitablePortCount = 0;
       
   158                 lastseen = 0;
       
   159             }
       
   160 
       
   161             // Allocate an ephemeral port (port 0)
       
   162             dc = openDefault();
       
   163             lastport = dc.socket().getLocalPort();
       
   164             if (lastseen == 0) {
       
   165                 history.offer(lastport);
       
   166                 return dc;
       
   167             }
       
   168 
       
   169             thresholdCrossed = suitablePortCount > thresholdCount;
       
   170             boolean farEnough = Integer.bitCount(lastseen ^ lastport) > BIT_DEVIATION
       
   171                     && Math.abs(lastport - lastseen) > deviation;
       
   172             boolean recycled = history.contains(lastport);
       
   173             boolean suitable = (thresholdCrossed || farEnough && !recycled);
       
   174             if (suitable && !recycled) history.add(lastport);
       
   175 
       
   176             if (suitable) {
       
   177                 if (!thresholdCrossed) {
       
   178                     suitablePortCount++;
       
   179                 } else if (!farEnough || recycled) {
       
   180                     unsuitablePortCount = 1;
       
   181                     suitablePortCount = thresholdCount / 2;
       
   182                 }
       
   183                 // Either the underlying stack supports random UDP port allocation,
       
   184                 // or the new port is sufficiently distant from last port to make
       
   185                 // it look like it is. Let's use it.
       
   186                 return dc;
       
   187             }
       
   188 
       
   189             // Undecided... the new port was too close. Let's allocate a random
       
   190             // port using our own algorithm
       
   191             assert !thresholdCrossed;
       
   192             try {
       
   193                 dc.close();
       
   194             } catch (IOException ioe) {
       
   195                 throw new SocketException(ioe.getMessage());
       
   196             }
       
   197             dc = openRandom();
       
   198             unsuitablePortCount++;
       
   199             return dc;
       
   200         } finally {
       
   201             factoryLock.unlock();
       
   202         }
       
   203     }
       
   204 
       
   205     private DatagramChannel openDefault() throws SocketException {
       
   206         if (family != null) {
       
   207             try {
       
   208                 DatagramChannel dc = DatagramChannel.open(family);
       
   209                 try {
       
   210                     dc.bind(null);
       
   211                     return dc;
       
   212                 } catch (Throwable x) {
       
   213                     dc.close();
       
   214                     throw x;
       
   215                 }
       
   216             } catch (SocketException x) {
       
   217                 throw x;
       
   218             } catch (IOException x) {
       
   219                 SocketException e = new SocketException(x.getMessage());
       
   220                 e.initCause(x);
       
   221                 throw e;
       
   222             }
       
   223         }
       
   224         try {
       
   225             return DatagramChannel.open();
       
   226         } catch (IOException ioe) {
       
   227             throw new SocketException(ioe.getMessage());
       
   228         }
       
   229     }
       
   230 
       
   231     boolean isUsingNativePortRandomization() {
       
   232         factoryLock.lock();
       
   233         try {
       
   234             return unsuitablePortCount <= thresholdCount
       
   235                     && suitablePortCount > thresholdCount;
       
   236         } finally {
       
   237             factoryLock.unlock();
       
   238         }
       
   239     }
       
   240 
       
   241     boolean isUsingJavaPortRandomization() {
       
   242         factoryLock.lock();
       
   243         try {
       
   244             return unsuitablePortCount > thresholdCount;
       
   245         } finally {
       
   246             factoryLock.unlock();
       
   247         }
       
   248     }
       
   249 
       
   250     boolean isUndecided() {
       
   251         factoryLock.lock();
       
   252         try {
       
   253             return !isUsingJavaPortRandomization()
       
   254                     && !isUsingNativePortRandomization();
       
   255         } finally {
       
   256             factoryLock.unlock();
       
   257         }
       
   258     }
       
   259 
       
   260     private DatagramChannel openRandom() {
       
   261         int maxtries = MAX_RANDOM_TRIES;
       
   262         while (maxtries-- > 0) {
       
   263             int port = EphemeralPortRange.LOWER
       
   264                     + random.nextInt(EphemeralPortRange.RANGE);
       
   265             try {
       
   266                 if (family != null) {
       
   267                     DatagramChannel dc = DatagramChannel.open(family);
       
   268                     try {
       
   269                         dc.bind(new InetSocketAddress(port));
       
   270                         return dc;
       
   271                     } catch (Throwable x) {
       
   272                         dc.close();
       
   273                         throw x;
       
   274                     }
       
   275                 } else {
       
   276 
       
   277                 }
       
   278                 DatagramChannel dc = DatagramChannel.open(family);
       
   279                 return dc.bind(new InetSocketAddress(port));
       
   280             } catch (IOException x) {
       
   281                 // try again until maxtries == 0;
       
   282             }
       
   283         }
       
   284         return null;
       
   285     }
       
   286 
       
   287 }