001    /*
002     * Licensed to the Apache Software Foundation (ASF) under one or more
003     * contributor license agreements. See the NOTICE file distributed with
004     * this work for additional information regarding copyright ownership.
005     * The ASF licenses this file to You under the Apache license, Version 2.0
006     * (the "License"); you may not use this file except in compliance with
007     * the License. You may obtain a copy of the License at
008     *
009     *      http://www.apache.org/licenses/LICENSE-2.0
010     *
011     * Unless required by applicable law or agreed to in writing, software
012     * distributed under the License is distributed on an "AS IS" BASIS,
013     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014     * See the license for the specific language governing permissions and
015     * limitations under the license.
016     */
017    package org.apache.logging.log4j.core.helpers;
018    
019    import java.lang.reflect.Method;
020    import java.net.InetAddress;
021    import java.net.NetworkInterface;
022    import java.net.UnknownHostException;
023    import java.nio.ByteBuffer;
024    import java.security.SecureRandom;
025    import java.util.Enumeration;
026    import java.util.Random;
027    import java.util.UUID;
028    import java.util.concurrent.atomic.AtomicInteger;
029    
030    /**
031     * Generates a unique id. The generated UUID will be unique for approximately 8,925 years so long as
032     * less than 4095 ids are generated per millisecond on the same device (as identified by its MAC adddress).
033     */
034    public final class UUIDUtil {
035        /**
036         * System property that may be used to seed the uuid generation with an integer value.
037         */
038        public static final String UUID_SEQUENCE = "org.apache.logging.log4j.uuidSequence";
039    
040        private static final String ASSIGNED_SEQUENCES = "org.apache.logging.log4j.assignedSequences";
041    
042        private static AtomicInteger count = new AtomicInteger(0);
043    
044        private static final long TYPE1 = 0x1000L;
045    
046        private static final byte VARIANT = (byte) 0x80;
047    
048        private static final int SEQUENCE_MASK = 0x3FFF;
049    
050        private static final long NUM_100NS_INTERVALS_SINCE_UUID_EPOCH = 0x01b21dd213814000L;
051    
052        private static long uuidSequence = Long.getLong(UUID_SEQUENCE, 0);
053    
054        private static long least;
055    
056        private static final long LOW_MASK = 0xffffffffL;
057        private static final long MID_MASK = 0xffff00000000L;
058        private static final long HIGH_MASK = 0xfff000000000000L;
059        private static final int NODE_SIZE = 8;
060        private static final int SHIFT_2 = 16;
061        private static final int SHIFT_4 = 32;
062        private static final int SHIFT_6 = 48;
063        private static final int HUNDRED_NANOS_PER_MILLI = 10000;
064    
065        static {
066            byte[] mac = null;
067            try {
068                InetAddress address = InetAddress.getLocalHost();
069                try {
070                    NetworkInterface ni = NetworkInterface.getByInetAddress(address);
071                    if (ni != null && !ni.isLoopback() && ni.isUp()) {
072                        Method method = ni.getClass().getMethod("getHardwareAddress");
073                        if (method != null) {
074                            mac = (byte[]) method.invoke(ni);
075                        }
076                    }
077    
078                    if (mac == null) {
079                        Enumeration<NetworkInterface> enumeration = NetworkInterface.getNetworkInterfaces();
080                        while (enumeration.hasMoreElements() && mac == null) {
081                            ni = enumeration.nextElement();
082                            if (ni != null && ni.isUp() && !ni.isLoopback()) {
083                                Method method = ni.getClass().getMethod("getHardwareAddress");
084                                if (method != null) {
085                                    mac = (byte[]) method.invoke(ni);
086                                }
087                            }
088                        }
089                    }
090                } catch (Exception ex) {
091                    ex.printStackTrace();
092                    // Ignore exception
093                }
094                if (mac == null || mac.length == 0) {
095                    mac = address.getAddress();
096                }
097            } catch (UnknownHostException e) {
098                // Ignore exception
099            }
100            Random randomGenerator = new SecureRandom();
101            if (mac == null || mac.length == 0) {
102                mac = new byte[6];
103                randomGenerator.nextBytes(mac);
104            }
105            int length = mac.length >= 6 ? 6 : mac.length;
106            int index = mac.length >= 6 ? mac.length - 6 : 0;
107            byte[] node = new byte[NODE_SIZE];
108            node[0] = VARIANT;
109            node[1] = 0;
110            for (int i = 2; i < NODE_SIZE; ++i) {
111                node[i] = 0;
112            }
113            System.arraycopy(mac, index, node, index + 2, length);
114            ByteBuffer buf = ByteBuffer.wrap(node);
115            long rand = uuidSequence;
116            Runtime runtime = Runtime.getRuntime();
117            synchronized (runtime) {
118                String assigned = System.getProperty(ASSIGNED_SEQUENCES);
119                long[] sequences;
120                if (assigned == null) {
121                    sequences = new long[0];
122                } else {
123                    String[] array = assigned.split(",");
124                    sequences = new long[array.length];
125                    int i = 0;
126                    for (String value : array) {
127                        sequences[i] = Long.parseLong(value);
128                        ++i;
129                    }
130                }
131                if (rand == 0) {
132                    rand = randomGenerator.nextLong();
133                }
134                rand &= SEQUENCE_MASK;
135                boolean duplicate;
136                do {
137                    duplicate = false;
138                    for (long sequence : sequences) {
139                        if (sequence == rand) {
140                            duplicate = true;
141                        }
142                    }
143                    if (duplicate) {
144                        rand = (rand + 1) & SEQUENCE_MASK;
145                    }
146                } while (duplicate);
147                assigned = assigned == null ? Long.toString(rand) : assigned + "," + Long.toString(rand);
148                System.setProperty(ASSIGNED_SEQUENCES, assigned);
149            }
150    
151            least = buf.getLong() | rand << SHIFT_6;
152        }
153    
154    
155        /* This class cannot be instantiated */
156        private UUIDUtil() {
157        }
158    
159        /**
160         * Generates Type 1 UUID. The time contains the number of 100NS intervals that have occurred
161         * since 00:00:00.00 UTC, 10 October 1582. Each UUID on a particular machine is unique to the 100NS interval
162         * until they rollover around 3400 A.D.
163         * <ol>
164         * <li>Digits 1-12 are the lower 48 bits of the number of 100 ns increments since the start of the UUID
165         * epoch.</li>
166         * <li>Digit 13 is the version (with a value of 1).</li>
167         * <li>Digits 14-16 are a sequence number that is incremented each time a UUID is generated.</li>
168         * <li>Digit 17 is the variant (with a value of binary 10) and 10 bits of the sequence number</li>
169         * <li>Digit 18 is final 16 bits of the sequence number.</li>
170         * <li>Digits 19-32 represent the system the application is running on.
171         * </ol>
172         *
173         * @return universally unique identifiers (UUID)
174         */
175        public static UUID getTimeBasedUUID() {
176    
177            long time = ((System.currentTimeMillis() * HUNDRED_NANOS_PER_MILLI) + NUM_100NS_INTERVALS_SINCE_UUID_EPOCH) +
178                (count.incrementAndGet() % HUNDRED_NANOS_PER_MILLI);
179            long timeLow = (time & LOW_MASK) << SHIFT_4;
180            long timeMid = (time & MID_MASK) >> SHIFT_2;
181            long timeHi = (time & HIGH_MASK) >> SHIFT_6;
182            long most = timeLow | timeMid | TYPE1 | timeHi;
183            return new UUID(most, least);
184        }
185    }
186