1 /*
   2  * Copyright (c) 2003, 2020, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package java.util;
  27 
  28 import java.security.*;
  29 
  30 import jdk.internal.access.JavaLangAccess;
  31 import jdk.internal.access.SharedSecrets;
  32 
  33 /**
  34  * A class that represents an immutable universally unique identifier (UUID).
  35  * A UUID represents a 128-bit value.
  36  *
  37  * <p> There exist different variants of these global identifiers.  The methods
  38  * of this class are for manipulating the Leach-Salz variant, although the
  39  * constructors allow the creation of any variant of UUID (described below).
  40  *
  41  * <p> The layout of a variant 2 (Leach-Salz) UUID is as follows:
  42  *
  43  * The most significant long consists of the following unsigned fields:
  44  * <pre>
  45  * 0xFFFFFFFF00000000 time_low
  46  * 0x00000000FFFF0000 time_mid
  47  * 0x000000000000F000 version
  48  * 0x0000000000000FFF time_hi
  49  * </pre>
  50  * The least significant long consists of the following unsigned fields:
  51  * <pre>
  52  * 0xC000000000000000 variant
  53  * 0x3FFF000000000000 clock_seq
  54  * 0x0000FFFFFFFFFFFF node
  55  * </pre>
  56  *
  57  * <p> The variant field contains a value which identifies the layout of the
  58  * {@code UUID}.  The bit layout described above is valid only for a {@code
  59  * UUID} with a variant value of 2, which indicates the Leach-Salz variant.
  60  *
  61  * <p> The version field holds a value that describes the type of this {@code
  62  * UUID}.  There are four different basic types of UUIDs: time-based, DCE
  63  * security, name-based, and randomly generated UUIDs.  These types have a
  64  * version value of 1, 2, 3 and 4, respectively.
  65  *
  66  * <p> For more information including algorithms used to create {@code UUID}s,
  67  * see <a href="http://www.ietf.org/rfc/rfc4122.txt"> <i>RFC&nbsp;4122: A
  68  * Universally Unique IDentifier (UUID) URN Namespace</i></a>, section 4.2
  69  * &quot;Algorithms for Creating a Time-Based UUID&quot;.
  70  *
  71  * @since   1.5
  72  */
  73 public final class UUID implements java.io.Serializable, Comparable<UUID> {
  74 
  75     /**
  76      * Explicit serialVersionUID for interoperability.
  77      */
  78     @java.io.Serial
  79     private static final long serialVersionUID = -4856846361193249489L;
  80 
  81     /*
  82      * The most significant 64 bits of this UUID.
  83      *
  84      * @serial
  85      */
  86     private final long mostSigBits;
  87 
  88     /*
  89      * The least significant 64 bits of this UUID.
  90      *
  91      * @serial
  92      */
  93     private final long leastSigBits;
  94 
  95     private static final JavaLangAccess jla = SharedSecrets.getJavaLangAccess();
  96 
  97     /*
  98      * The random number generator used by this class to create random
  99      * based UUIDs. In a holder class to defer initialization until needed.
 100      */
 101     private static class Holder {
 102         static final SecureRandom numberGenerator = new SecureRandom();
 103     }
 104 
 105     // Constructors and Factories
 106 
 107     /*
 108      * Private constructor which uses a byte array to construct the new UUID.
 109      */
 110     private UUID(byte[] data) {
 111         long msb = 0;
 112         long lsb = 0;
 113         assert data.length == 16 : "data must be 16 bytes in length";
 114         for (int i=0; i<8; i++)
 115             msb = (msb << 8) | (data[i] & 0xff);
 116         for (int i=8; i<16; i++)
 117             lsb = (lsb << 8) | (data[i] & 0xff);
 118         this.mostSigBits = msb;
 119         this.leastSigBits = lsb;
 120     }
 121 
 122     /**
 123      * Constructs a new {@code UUID} using the specified data.  {@code
 124      * mostSigBits} is used for the most significant 64 bits of the {@code
 125      * UUID} and {@code leastSigBits} becomes the least significant 64 bits of
 126      * the {@code UUID}.
 127      *
 128      * @param  mostSigBits
 129      *         The most significant bits of the {@code UUID}
 130      *
 131      * @param  leastSigBits
 132      *         The least significant bits of the {@code UUID}
 133      */
 134     public UUID(long mostSigBits, long leastSigBits) {
 135         this.mostSigBits = mostSigBits;
 136         this.leastSigBits = leastSigBits;
 137     }
 138 
 139     /**
 140      * Static factory to retrieve a type 4 (pseudo randomly generated) UUID.
 141      *
 142      * The {@code UUID} is generated using a cryptographically strong pseudo
 143      * random number generator.
 144      *
 145      * @return  A randomly generated {@code UUID}
 146      */
 147     public static UUID randomUUID() {
 148         SecureRandom ng = Holder.numberGenerator;
 149 
 150         byte[] randomBytes = new byte[16];
 151         ng.nextBytes(randomBytes);
 152         randomBytes[6]  &= 0x0f;  /* clear version        */
 153         randomBytes[6]  |= 0x40;  /* set to version 4     */
 154         randomBytes[8]  &= 0x3f;  /* clear variant        */
 155         randomBytes[8]  |= 0x80;  /* set to IETF variant  */
 156         return new UUID(randomBytes);
 157     }
 158 
 159     /**
 160      * Static factory to retrieve a type 3 (name based) {@code UUID} based on
 161      * the specified byte array.
 162      *
 163      * @param  name
 164      *         A byte array to be used to construct a {@code UUID}
 165      *
 166      * @return  A {@code UUID} generated from the specified array
 167      */
 168     public static UUID nameUUIDFromBytes(byte[] name) {
 169         MessageDigest md;
 170         try {
 171             md = MessageDigest.getInstance("MD5");
 172         } catch (NoSuchAlgorithmException nsae) {
 173             throw new InternalError("MD5 not supported", nsae);
 174         }
 175         byte[] md5Bytes = md.digest(name);
 176         md5Bytes[6]  &= 0x0f;  /* clear version        */
 177         md5Bytes[6]  |= 0x30;  /* set to version 3     */
 178         md5Bytes[8]  &= 0x3f;  /* clear variant        */
 179         md5Bytes[8]  |= 0x80;  /* set to IETF variant  */
 180         return new UUID(md5Bytes);
 181     }
 182 
 183     private static final byte[] NIBBLES;
 184     static {
 185         byte[] ns = new byte[256];
 186         Arrays.fill(ns, (byte) -1);
 187         ns['0'] = 0;
 188         ns['1'] = 1;
 189         ns['2'] = 2;
 190         ns['3'] = 3;
 191         ns['4'] = 4;
 192         ns['5'] = 5;
 193         ns['6'] = 6;
 194         ns['7'] = 7;
 195         ns['8'] = 8;
 196         ns['9'] = 9;
 197         ns['A'] = 10;
 198         ns['B'] = 11;
 199         ns['C'] = 12;
 200         ns['D'] = 13;
 201         ns['E'] = 14;
 202         ns['F'] = 15;
 203         ns['a'] = 10;
 204         ns['b'] = 11;
 205         ns['c'] = 12;
 206         ns['d'] = 13;
 207         ns['e'] = 14;
 208         ns['f'] = 15;
 209         NIBBLES = ns;
 210     }
 211 
 212     private static long parse4Nibbles(String name, int pos) {
 213         byte[] ns = NIBBLES;
 214         char ch1 = name.charAt(pos);
 215         char ch2 = name.charAt(pos + 1);
 216         char ch3 = name.charAt(pos + 2);
 217         char ch4 = name.charAt(pos + 3);
 218         return (ch1 | ch2 | ch3 | ch4) > 0xff ?
 219                 -1 : ns[ch1] << 12 | ns[ch2] << 8 | ns[ch3] << 4 | ns[ch4];
 220     }
 221 
 222     /**
 223      * Creates a {@code UUID} from the string standard representation as
 224      * described in the {@link #toString} method.
 225      *
 226      * @param  uuidString
 227      *         A string that specifies a {@code UUID}
 228      *
 229      * @return  A {@code UUID} with the specified value
 230      *
 231      * @throws  IllegalArgumentException
 232      *          If {@code uuidString} does not conform to the string representation as
 233      *          described in {@link #toString}
 234      *
 235      * @since 15
 236      */
 237     public static UUID valueOf(String uuidString) {
 238         UUID uuid = valueOf1(uuidString);
 239         if (uuid == null) {
 240             throw new IllegalArgumentException("Invalid UUID string: " + uuidString);
 241         }
 242         return uuid;
 243     }
 244 
 245     /**
 246      * Creates a {@code UUID} from the string standard representation as
 247      * described in the {@link #toString} method.
 248      *
 249      * @param  name
 250      *         A string that specifies a {@code UUID}
 251      *
 252      * @return  A {@code UUID} with the specified value
 253      *
 254      * @throws  IllegalArgumentException
 255      *          If name does not conform loosely to the string representation as
 256      *          described in {@link #toString}
 257      *
 258      * @deprecated Since it allows invalid input strings to be converted to
 259      *             UUID instances. For example:
 260      *             <ul>
 261      *                 <li>{@code UUID.fromString("1-1-1-1-1")} becomes
 262      *                 {@code 00000001-0001-0001-0001-000000000001}</li>
 263      *                 <li>{@code UUID.fromString("5-4-3-DEADBEEF0002-9000000001")} becomes
 264      *                 {@code 00000005-0004-0003-0002-009000000001 }</li>
 265      *                 <li>etc...</li>
 266      *             </ul>
 267      *             Use {@link #valueOf(String)} instead.
 268      */
 269     @Deprecated
 270     public static UUID fromString(String name) {
 271         UUID uuid = valueOf1(name);
 272         return uuid != null ? uuid : fromString1(name);
 273     }
 274 
 275     private static UUID valueOf1(String name) {
 276         if (name.length() == 36) {
 277             char ch1 = name.charAt(8);
 278             char ch2 = name.charAt(13);
 279             char ch3 = name.charAt(18);
 280             char ch4 = name.charAt(23);
 281             if (ch1 == '-' && ch2 == '-' && ch3 == '-' && ch4 == '-') {
 282                 long msb1 = parse4Nibbles(name, 0);
 283                 long msb2 = parse4Nibbles(name, 4);
 284                 long msb3 = parse4Nibbles(name, 9);
 285                 long msb4 = parse4Nibbles(name, 14);
 286                 long lsb1 = parse4Nibbles(name, 19);
 287                 long lsb2 = parse4Nibbles(name, 24);
 288                 long lsb3 = parse4Nibbles(name, 28);
 289                 long lsb4 = parse4Nibbles(name, 32);
 290                 if ((msb1 | msb2 | msb3 | msb4 | lsb1 | lsb2 | lsb3 | lsb4) >= 0) {
 291                     return new UUID(
 292                             msb1 << 48 | msb2 << 32 | msb3 << 16 | msb4,
 293                             lsb1 << 48 | lsb2 << 32 | lsb3 << 16 | lsb4);
 294                 }
 295             }
 296         }
 297         return null;
 298     }
 299 
 300     private static UUID fromString1(String name) {
 301         int len = name.length();
 302         if (len > 36) {
 303             throw new IllegalArgumentException("UUID string too large");
 304         }
 305 
 306         int dash1 = name.indexOf('-', 0);
 307         int dash2 = name.indexOf('-', dash1 + 1);
 308         int dash3 = name.indexOf('-', dash2 + 1);
 309         int dash4 = name.indexOf('-', dash3 + 1);
 310         int dash5 = name.indexOf('-', dash4 + 1);
 311 
 312         // For any valid input, dash1 through dash4 will be positive and dash5
 313         // negative, but it's enough to check dash4 and dash5:
 314         // - if dash1 is -1, dash4 will be -1
 315         // - if dash1 is positive but dash2 is -1, dash4 will be -1
 316         // - if dash1 and dash2 is positive, dash3 will be -1, dash4 will be
 317         //   positive, but so will dash5
 318         if (dash4 < 0 || dash5 >= 0) {
 319             throw new IllegalArgumentException("Invalid UUID string: " + name);
 320         }
 321 
 322         long mostSigBits = Long.parseLong(name, 0, dash1, 16) & 0xffffffffL;
 323         mostSigBits <<= 16;
 324         mostSigBits |= Long.parseLong(name, dash1 + 1, dash2, 16) & 0xffffL;
 325         mostSigBits <<= 16;
 326         mostSigBits |= Long.parseLong(name, dash2 + 1, dash3, 16) & 0xffffL;
 327         long leastSigBits = Long.parseLong(name, dash3 + 1, dash4, 16) & 0xffffL;
 328         leastSigBits <<= 48;
 329         leastSigBits |= Long.parseLong(name, dash4 + 1, len, 16) & 0xffffffffffffL;
 330 
 331         return new UUID(mostSigBits, leastSigBits);
 332     }
 333 
 334     // Field Accessor Methods
 335 
 336     /**
 337      * Returns the least significant 64 bits of this UUID's 128 bit value.
 338      *
 339      * @return  The least significant 64 bits of this UUID's 128 bit value
 340      */
 341     public long getLeastSignificantBits() {
 342         return leastSigBits;
 343     }
 344 
 345     /**
 346      * Returns the most significant 64 bits of this UUID's 128 bit value.
 347      *
 348      * @return  The most significant 64 bits of this UUID's 128 bit value
 349      */
 350     public long getMostSignificantBits() {
 351         return mostSigBits;
 352     }
 353 
 354     /**
 355      * The version number associated with this {@code UUID}.  The version
 356      * number describes how this {@code UUID} was generated.
 357      *
 358      * The version number has the following meaning:
 359      * <ul>
 360      * <li>1    Time-based UUID
 361      * <li>2    DCE security UUID
 362      * <li>3    Name-based UUID
 363      * <li>4    Randomly generated UUID
 364      * </ul>
 365      *
 366      * @return  The version number of this {@code UUID}
 367      */
 368     public int version() {
 369         // Version is bits masked by 0x000000000000F000 in MS long
 370         return (int)((mostSigBits >> 12) & 0x0f);
 371     }
 372 
 373     /**
 374      * The variant number associated with this {@code UUID}.  The variant
 375      * number describes the layout of the {@code UUID}.
 376      *
 377      * The variant number has the following meaning:
 378      * <ul>
 379      * <li>0    Reserved for NCS backward compatibility
 380      * <li>2    <a href="http://www.ietf.org/rfc/rfc4122.txt">IETF&nbsp;RFC&nbsp;4122</a>
 381      * (Leach-Salz), used by this class
 382      * <li>6    Reserved, Microsoft Corporation backward compatibility
 383      * <li>7    Reserved for future definition
 384      * </ul>
 385      *
 386      * @return  The variant number of this {@code UUID}
 387      */
 388     public int variant() {
 389         // This field is composed of a varying number of bits.
 390         // 0    -    -    Reserved for NCS backward compatibility
 391         // 1    0    -    The IETF aka Leach-Salz variant (used by this class)
 392         // 1    1    0    Reserved, Microsoft backward compatibility
 393         // 1    1    1    Reserved for future definition.
 394         return (int) ((leastSigBits >>> (64 - (leastSigBits >>> 62)))
 395                       & (leastSigBits >> 63));
 396     }
 397 
 398     /**
 399      * The timestamp value associated with this UUID.
 400      *
 401      * <p> The 60 bit timestamp value is constructed from the time_low,
 402      * time_mid, and time_hi fields of this {@code UUID}.  The resulting
 403      * timestamp is measured in 100-nanosecond units since midnight,
 404      * October 15, 1582 UTC.
 405      *
 406      * <p> The timestamp value is only meaningful in a time-based UUID, which
 407      * has version type 1.  If this {@code UUID} is not a time-based UUID then
 408      * this method throws UnsupportedOperationException.
 409      *
 410      * @throws UnsupportedOperationException
 411      *         If this UUID is not a version 1 UUID
 412      * @return The timestamp of this {@code UUID}.
 413      */
 414     public long timestamp() {
 415         if (version() != 1) {
 416             throw new UnsupportedOperationException("Not a time-based UUID");
 417         }
 418 
 419         return (mostSigBits & 0x0FFFL) << 48
 420              | ((mostSigBits >> 16) & 0x0FFFFL) << 32
 421              | mostSigBits >>> 32;
 422     }
 423 
 424     /**
 425      * The clock sequence value associated with this UUID.
 426      *
 427      * <p> The 14 bit clock sequence value is constructed from the clock
 428      * sequence field of this UUID.  The clock sequence field is used to
 429      * guarantee temporal uniqueness in a time-based UUID.
 430      *
 431      * <p> The {@code clockSequence} value is only meaningful in a time-based
 432      * UUID, which has version type 1.  If this UUID is not a time-based UUID
 433      * then this method throws UnsupportedOperationException.
 434      *
 435      * @return  The clock sequence of this {@code UUID}
 436      *
 437      * @throws  UnsupportedOperationException
 438      *          If this UUID is not a version 1 UUID
 439      */
 440     public int clockSequence() {
 441         if (version() != 1) {
 442             throw new UnsupportedOperationException("Not a time-based UUID");
 443         }
 444 
 445         return (int)((leastSigBits & 0x3FFF000000000000L) >>> 48);
 446     }
 447 
 448     /**
 449      * The node value associated with this UUID.
 450      *
 451      * <p> The 48 bit node value is constructed from the node field of this
 452      * UUID.  This field is intended to hold the IEEE 802 address of the machine
 453      * that generated this UUID to guarantee spatial uniqueness.
 454      *
 455      * <p> The node value is only meaningful in a time-based UUID, which has
 456      * version type 1.  If this UUID is not a time-based UUID then this method
 457      * throws UnsupportedOperationException.
 458      *
 459      * @return  The node value of this {@code UUID}
 460      *
 461      * @throws  UnsupportedOperationException
 462      *          If this UUID is not a version 1 UUID
 463      */
 464     public long node() {
 465         if (version() != 1) {
 466             throw new UnsupportedOperationException("Not a time-based UUID");
 467         }
 468 
 469         return leastSigBits & 0x0000FFFFFFFFFFFFL;
 470     }
 471 
 472     // Object Inherited Methods
 473 
 474     /**
 475      * Returns a {@code String} object representing this {@code UUID}.
 476      *
 477      * <p> The UUID string representation is as described by this BNF:
 478      * <blockquote><pre>
 479      * {@code
 480      * UUID                   = <time_low> "-" <time_mid> "-"
 481      *                          <time_high_and_version> "-"
 482      *                          <variant_and_sequence> "-"
 483      *                          <node>
 484      * time_low               = 4*<hexOctet>
 485      * time_mid               = 2*<hexOctet>
 486      * time_high_and_version  = 2*<hexOctet>
 487      * variant_and_sequence   = 2*<hexOctet>
 488      * node                   = 6*<hexOctet>
 489      * hexOctet               = <hexDigit><hexDigit>
 490      * hexDigit               =
 491      *       "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9"
 492      *       | "a" | "b" | "c" | "d" | "e" | "f"
 493      *       | "A" | "B" | "C" | "D" | "E" | "F"
 494      * }</pre></blockquote>
 495      *
 496      * @return  A string representation of this {@code UUID}
 497      */
 498     public String toString() {
 499         return jla.fastUUID(leastSigBits, mostSigBits);
 500     }
 501 
 502     /**
 503      * Returns a hash code for this {@code UUID}.
 504      *
 505      * @return  A hash code value for this {@code UUID}
 506      */
 507     public int hashCode() {
 508         long hilo = mostSigBits ^ leastSigBits;
 509         return ((int)(hilo >> 32)) ^ (int) hilo;
 510     }
 511 
 512     /**
 513      * Compares this object to the specified object.  The result is {@code
 514      * true} if and only if the argument is not {@code null}, is a {@code UUID}
 515      * object, has the same variant, and contains the same value, bit for bit,
 516      * as this {@code UUID}.
 517      *
 518      * @param  obj
 519      *         The object to be compared
 520      *
 521      * @return  {@code true} if the objects are the same; {@code false}
 522      *          otherwise
 523      */
 524     public boolean equals(Object obj) {
 525         if ((null == obj) || (obj.getClass() != UUID.class))
 526             return false;
 527         UUID id = (UUID)obj;
 528         return (mostSigBits == id.mostSigBits &&
 529                 leastSigBits == id.leastSigBits);
 530     }
 531 
 532     // Comparison Operations
 533 
 534     /**
 535      * Compares this UUID with the specified UUID.
 536      *
 537      * <p> The first of two UUIDs is greater than the second if the most
 538      * significant field in which the UUIDs differ is greater for the first
 539      * UUID.
 540      *
 541      * @param  val
 542      *         {@code UUID} to which this {@code UUID} is to be compared
 543      *
 544      * @return  -1, 0 or 1 as this {@code UUID} is less than, equal to, or
 545      *          greater than {@code val}
 546      *
 547      */
 548     public int compareTo(UUID val) {
 549         // The ordering is intentionally set up so that the UUIDs
 550         // can simply be numerically compared as two numbers
 551         return (this.mostSigBits < val.mostSigBits ? -1 :
 552                 (this.mostSigBits > val.mostSigBits ? 1 :
 553                  (this.leastSigBits < val.leastSigBits ? -1 :
 554                   (this.leastSigBits > val.leastSigBits ? 1 :
 555                    0))));
 556     }
 557 }