Subversion Repositories uuid_mac_utils

Rev

Rev 26 | Rev 28 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
2 daniel-mar 1
<?php
2
 
3
/*
4
 * UUID utils for PHP
15 daniel-mar 5
 * Copyright 2011 - 2023 Daniel Marschall, ViaThinkSoft
26 daniel-mar 6
 * Version 2023-07-11
2 daniel-mar 7
 *
8
 * Licensed under the Apache License, Version 2.0 (the "License");
9
 * you may not use this file except in compliance with the License.
10
 * You may obtain a copy of the License at
11
 *
12
 *     http://www.apache.org/licenses/LICENSE-2.0
13
 *
14
 * Unless required by applicable law or agreed to in writing, software
15
 * distributed under the License is distributed on an "AS IS" BASIS,
16
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17
 * See the License for the specific language governing permissions and
18
 * limitations under the License.
19
 */
20
 
21
# This library requires either the GMP extension (or BCMath if gmp_supplement.inc.php is present)
22
 
23
if (file_exists(__DIR__ . '/mac_utils.inc.phps')) include_once __DIR__ . '/mac_utils.inc.phps'; // optionally used for uuid_info()
24
if (file_exists(__DIR__ . '/gmp_supplement.inc.php')) include_once __DIR__ . '/gmp_supplement.inc.php';
25
 
26
define('UUID_NAMEBASED_NS_DNS',     '6ba7b810-9dad-11d1-80b4-00c04fd430c8');
27
define('UUID_NAMEBASED_NS_URL',     '6ba7b811-9dad-11d1-80b4-00c04fd430c8');
28
define('UUID_NAMEBASED_NS_OID',     '6ba7b812-9dad-11d1-80b4-00c04fd430c8');
29
define('UUID_NAMEBASED_NS_X500_DN', '6ba7b814-9dad-11d1-80b4-00c04fd430c8');
30
 
24 daniel-mar 31
function _random_int($min, $max) {
32
        // This function tries a CSRNG and falls back to a RNG if no CSRNG is available
33
        try {
34
                return random_int($min, $max);
35
        } catch (Exception $e) {
36
                return mt_rand($min, $max);
37
        }
38
}
39
 
2 daniel-mar 40
function uuid_valid($uuid) {
41
        $uuid = str_replace(array('-', '{', '}'), '', $uuid);
42
        $uuid = strtoupper($uuid);
43
        #$uuid = trim($uuid);
44
 
45
        if (strlen($uuid) != 32) return false;
46
 
47
        $uuid = preg_replace('@[0-9A-F]@', '', $uuid);
48
 
49
        return ($uuid == '');
50
}
51
 
52
# TODO: Don't echo
53
function uuid_info($uuid) {
54
        if (!uuid_valid($uuid)) return false;
55
 
56
        #$uuid = trim($uuid);
57
        # $uuid = str_replace(array('-', '{', '}'), '', $uuid);
58
        $uuid = strtoupper($uuid);
59
        $uuid = preg_replace('@[^0-9A-F]@', '', $uuid);
60
 
61
        $x = hexdec(substr($uuid, 16, 1));
62
             if ($x >= 14 /* 1110 */) $variant = 3;
63
        else if ($x >= 12 /* 1100 */) $variant = 2;
64
        else if ($x >=  8 /* 1000 */) $variant = 1;
65
        else if ($x >=  0 /* 0000 */) $variant = 0;
66
        else $variant = -1; // should not happen
67
 
68
        switch ($variant) {
69
                case 0:
27 daniel-mar 70
                        echo sprintf("%-32s %s\n", "Variant:", "[0b0__] NCS (reserved for backward compatibility)");
2 daniel-mar 71
 
72
                        /*
73
                         * Internal structure of variant #0 UUIDs
74
                         *
75
                         * The first 6 octets are the number of 4 usec units of time that have
76
                         * passed since 1/1/80 0000 GMT.  The next 2 octets are reserved for
77
                         * future use.  The next octet is an address family.  The next 7 octets
78
                         * are a host ID in the form allowed by the specified address family.
79
                         *
80
                         * Note that while the family field (octet 8) was originally conceived
81
                         * of as being able to hold values in the range [0..255], only [0..13]
82
                         * were ever used.  Thus, the 2 MSB of this field are always 0 and are
83
                         * used to distinguish old and current UUID forms.
84
                         *
85
                         * +--------------------------------------------------------------+
27 daniel-mar 86
                         * |                    high 32 bits of time                      |  byte 0-3  .time_high
2 daniel-mar 87
                         * +-------------------------------+-------------------------------
27 daniel-mar 88
                         * |     low 16 bits of time       |  byte 4-5               .time_low
2 daniel-mar 89
                         * +-------+-----------------------+
27 daniel-mar 90
                         * |         reserved              |  byte 6-7               .reserved
2 daniel-mar 91
                         * +---------------+---------------+
27 daniel-mar 92
                         * |    family     |   byte 8                                .family
2 daniel-mar 93
                         * +---------------+----------...-----+
27 daniel-mar 94
                         * |            node ID               |  byte 9-16           .node
2 daniel-mar 95
                         * +--------------------------...-----+
96
                         *
97
                         */
98
 
99
                        // Example of an UUID: 333a2276-0000-0000-0d00-00809c000000
100
 
101
                        # TODO: See https://github.com/cjsv/uuid/blob/master/Doc
102
 
27 daniel-mar 103
                        // TODO: Make a generator !
104
 
2 daniel-mar 105
                        # Timestamp: Count of 4us intervals since 01 Jan 1980 00:00:00 GMT
106
                        # 1/0,000004 = 250000
107
                        # Seconds between 1970 and 1980 : 315532800
108
                        # 250000*315532800=78883200000000
109
                        $timestamp = substr($uuid, 0, 12);
110
                        $ts = gmp_init($timestamp, 16);
111
                        $ts = gmp_add($ts, gmp_init("78883200000000"));
112
                        $ms = gmp_mod($ts, gmp_init("250000"));
113
                        $ts = gmp_div($ts, gmp_init("250000"));
114
                        $ts = gmp_strval($ts);
115
                        $ms = gmp_strval($ms);
116
                        $ts = gmdate('Y-m-d H:i:s', intval($ts))."'".str_pad($ms, 7, '0', STR_PAD_LEFT).' GMT';
25 daniel-mar 117
                        echo sprintf("%-32s %s\n", "Timestamp:", "[0x$timestamp] $ts");
2 daniel-mar 118
 
119
                        $reserved = substr($uuid, 12, 4);
27 daniel-mar 120
                        echo sprintf("%-32s %s\n", "Reserved:", "[0x$reserved]");
2 daniel-mar 121
 
27 daniel-mar 122
                        # TODO: interprete node id (the family specifies it)
2 daniel-mar 123
                        # Family 13 (dds) looks like node is 00 | nnnnnn 000000.
124
                        # Family 2 is presumably (ip).
125
                        # Not sure if anything else was used.
126
                        $family_hex = substr($uuid, 16, 2);
127
                        $family_dec = hexdec($family_hex);
128
                        if ($family_dec == 2) {
129
                                $family_ = 'IP';
130
                        } else if ($family_dec == 13) {
131
                                $family_ = 'DDS (Data Link)';
132
                        } else {
133
                                $family_ = "Unknown ($family_dec)"; # There are probably no more families
134
                        }
25 daniel-mar 135
                        echo sprintf("%-32s %s\n", "Family:", "[0x$family_hex = $family_dec] $family_");
2 daniel-mar 136
 
137
                        $nodeid = substr($uuid, 18, 14);
27 daniel-mar 138
                        echo sprintf("%-32s %s\n", "Node ID:", "[0x$nodeid]");
2 daniel-mar 139
 
140
                        break;
141
                case 1:
27 daniel-mar 142
                        echo sprintf("%-32s %s\n", "Variant:", "[0b10_] RFC 4122 (Leach-Mealling-Salz) / DCE 1.1");
2 daniel-mar 143
 
144
                        $version = hexdec(substr($uuid, 12, 1));
145
                        switch ($version) {
146
                                case 1:
27 daniel-mar 147
                                        /*
148
                                        Variant 1, Version 1 UUID
149
                                        - 32 bit Low Time
150
                                        - 16 bit Mid Time
151
                                        -  4 bit Version (fix 0x1)
152
                                        - 12 bit High Time
153
                                        -  2 bit Variant (fix 0b10__)
154
                                        -  2 bit Clock Seq High
155
                                        -  4 bit Clock Seq Low
156
                                        - 48 bit MAC Address
157
                                        */
158
 
25 daniel-mar 159
                                        echo sprintf("%-32s %s\n", "Version:", "[1] Time-based with unique random host identifier");
2 daniel-mar 160
 
161
                                        # Timestamp: Count of 100ns intervals since 15 Oct 1582 00:00:00
162
                                        # 1/0,0000001 = 10000000
163
                                        $timestamp = substr($uuid, 13, 3).substr($uuid, 8, 4).substr($uuid, 0, 8);
164
                                        $ts = gmp_init($timestamp, 16);
165
                                        $ts = gmp_sub($ts, gmp_init("122192928000000000"));
166
                                        $ms = gmp_mod($ts, gmp_init("10000000"));
167
                                        $ts = gmp_div($ts, gmp_init("10000000"));
168
                                        $ts = gmp_strval($ts);
169
                                        $ms = gmp_strval($ms);
170
                                        $ts = gmdate('Y-m-d H:i:s', intval($ts))."'".str_pad($ms, 7, '0', STR_PAD_LEFT).' GMT';
25 daniel-mar 171
                                        echo sprintf("%-32s %s\n", "Timestamp:", "[0x$timestamp] $ts");
2 daniel-mar 172
 
173
                                        $x = hexdec(substr($uuid, 16, 4));
174
                                        $dec = $x & 0x3FFF; // The highest 2 bits are used by "variant" (10x)
175
                                        $hex = substr($uuid, 16, 4);
25 daniel-mar 176
                                        echo sprintf("%-32s %s\n", "Clock ID:", "[0x$hex] $dec");
2 daniel-mar 177
 
178
                                        $x = substr($uuid, 20, 12);
179
                                        $nodeid = '';
180
                                        for ($i=0; $i<6; $i++) {
181
                                                $nodeid .= substr($x, $i*2, 2);
25 daniel-mar 182
                                                if ($i != 5) $nodeid .= '-';
2 daniel-mar 183
                                        }
27 daniel-mar 184
                                        echo sprintf("%-32s %s\n", "Node ID:", "[0x$x] $nodeid");
2 daniel-mar 185
 
186
                                        if (function_exists('decode_mac')) {
25 daniel-mar 187
                                                echo "\nIn case that this Node ID is a MAC address, here is the interpretation of that MAC address:\n\n";
15 daniel-mar 188
                                                decode_mac($nodeid);
2 daniel-mar 189
                                        }
190
 
191
                                        break;
192
                                case 2:
27 daniel-mar 193
                                        /*
194
                                        Variant 1, Version 2 UUID
195
                                        - 32 bit Local Domain Number
196
                                        - 16 bit Mid Time
197
                                        -  4 bit Version (fix 0x2)
198
                                        - 12 bit High Time
199
                                        -  4 bit Variant (fix 0b10__; lower 2 bits not used)
200
                                        -  4 bit Clock Seq
201
                                        - 16 bit Local Domain
202
                                        - 48 bit MAC Address
203
                                        */
204
 
25 daniel-mar 205
                                        echo sprintf("%-32s %s\n", "Version:", "[2] DCE Security version");
2 daniel-mar 206
 
27 daniel-mar 207
                                        # The clock_seq_low field (which represents an integer in the range [0, 28-1]) is interpreted as a local domain (as represented by sec_rgy_domain_t; see sec_rgy_domain_t ); that is, an identifier domain meaningful to the local host. (Note that the data type sec_rgy_domain_t can potentially hold values outside the range [0, 28-1]; however, the only values currently registered are in the range [0, 2], so this type mismatch is not significant.) In the particular case of a POSIX host, the value sec_rgy_domain_person is to be interpreted as the "POSIX UID domain", and the value sec_rgy_domain_group is to be interpreted as the "POSIX GID domain".
208
                                        $x = substr($uuid, 18, 2);
209
                                        if ($x == '00') $domain_info = 'Person (POSIX: User-ID)';
210
                                        else if ($x == '01') $domain_info = 'Group (POSIX: Group-ID)';
211
                                        else if ($x == '02') $domain_info = 'Organization';
212
                                        else $domain_info = 'site-defined (Domain '.hexdec($x).')';
213
                                        echo sprintf("%-32s %s\n", "Local Domain:", "[0x$x] $domain_info");
214
 
2 daniel-mar 215
                                        # The time_low field (which represents an integer in the range [0, 232-1]) is interpreted as a local-ID; that is, an identifier (within the domain specified by clock_seq_low) meaningful to the local host. In the particular case of a POSIX host, when combined with a POSIX UID or POSIX GID domain in the clock_seq_low field (above), the time_low field represents a POSIX UID or POSIX GID, respectively.
216
                                        $x = substr($uuid, 0, 8);
27 daniel-mar 217
                                        echo sprintf("%-32s %s\n", "Local Domain Number:", "[0x$x]");
2 daniel-mar 218
 
219
                                        # Timestamp: Count of 100ns intervals since 15 Oct 1582 00:00:00
220
                                        # 1/0,0000001 = 10000000
221
                                        $timestamp = substr($uuid, 13, 3).substr($uuid, 8, 4).'00000000';
222
                                        $ts = gmp_init($timestamp, 16);
223
                                        $ts = gmp_sub($ts, gmp_init("122192928000000000"));
224
                                        $ms = gmp_mod($ts, gmp_init("10000000"));
225
                                        $ts = gmp_div($ts, gmp_init("10000000"));
226
                                        $ts = gmp_strval($ts);
227
                                        $ms = gmp_strval($ms);
228
                                        $ts_min = gmdate('Y-m-d H:i:s', intval($ts))."'".str_pad($ms, 7, '0', STR_PAD_LEFT).' GMT';
229
 
230
                                        $timestamp = substr($uuid, 13, 3).substr($uuid, 8, 4).'FFFFFFFF';
231
                                        $ts = gmp_init($timestamp, 16);
232
                                        $ts = gmp_sub($ts, gmp_init("122192928000000000"));
233
                                        $ms = gmp_mod($ts, gmp_init("10000000"));
234
                                        $ts = gmp_div($ts, gmp_init("10000000"));
235
                                        $ts = gmp_strval($ts);
236
                                        $ms = gmp_strval($ms);
237
                                        $ts_max = gmdate('Y-m-d H:i:s', intval($ts))."'".str_pad($ms, 7, '0', STR_PAD_LEFT).' GMT';
238
 
239
                                        $timestamp = substr($uuid, 13, 3).substr($uuid, 8, 4).'xxxxxxxx';
25 daniel-mar 240
                                        echo sprintf("%-32s %s\n", "Timestamp:", "[0x$timestamp] $ts_min - $ts_max");
2 daniel-mar 241
 
27 daniel-mar 242
                                        $x = hexdec(substr($uuid, 16, 1));
243
                                        $dec = $x & 0x3FFF; // The highest 2 bits are used by "variant" (10xx)
244
                                        $hex = substr($uuid, 16, 1);
245
                                        echo sprintf("%-32s %s\n", "Clock ID:", "[0x$hex] $dec");
2 daniel-mar 246
 
247
                                        $x = substr($uuid, 20, 12);
248
                                        $nodeid = '';
249
                                        for ($i=0; $i<6; $i++) {
250
                                                $nodeid .= substr($x, $i*2, 2);
25 daniel-mar 251
                                                if ($i != 5) $nodeid .= '-';
2 daniel-mar 252
                                        }
27 daniel-mar 253
                                        echo sprintf("%-32s %s\n", "Node ID:", "[0x$x] $nodeid");
2 daniel-mar 254
 
255
                                        if (function_exists('decode_mac')) {
25 daniel-mar 256
                                                echo "\nIn case that this Node ID is a MAC address, here is the interpretation of that MAC address:\n\n";
15 daniel-mar 257
                                                decode_mac($nodeid);
2 daniel-mar 258
                                        }
259
 
260
                                        break;
261
                                case 3:
25 daniel-mar 262
                                        echo sprintf("%-32s %s\n", "Version:", "[3] Name-based (MD5 hash)");
2 daniel-mar 263
 
264
                                        $hash = str_replace('-', '', strtolower($uuid));
27 daniel-mar 265
 
2 daniel-mar 266
                                        $hash[12] = '?'; // was overwritten by version
27 daniel-mar 267
 
268
                                        $var16a = dechex((hexdec($hash[16])&3) + 0x0/*00__*/);
269
                                        $var16b = dechex((hexdec($hash[16])&3) + 0x4/*01__*/);
270
                                        $var16c = dechex((hexdec($hash[16])&3) + 0x8/*10__*/);
271
                                        $var16d = dechex((hexdec($hash[16])&3) + 0xC/*11__*/);
2 daniel-mar 272
                                        $hash[16] = '?'; // was partially overwritten by variant
273
 
27 daniel-mar 274
                                        echo sprintf("%-32s %s\n", "MD5(Namespace+Subject):", "[0x$hash]");
275
                                        echo sprintf("%-32s %s\n", "", "                   ^");
276
                                        echo sprintf("%-32s %s\n", "", "                   $var16a, $var16b, $var16c, or $var16d");
2 daniel-mar 277
 
278
                                        break;
279
                                case 4:
25 daniel-mar 280
                                        echo sprintf("%-32s %s\n", "Version:", "[4] Random");
2 daniel-mar 281
 
25 daniel-mar 282
                                        $rand_line1 = '';
283
                                        $rand_line2 = '';
2 daniel-mar 284
                                        for ($i=0; $i<16; $i++) {
285
                                                $bin = base_convert(substr($uuid, $i*2, 2), 16, 2);
286
                                                $bin = str_pad($bin, 8, "0", STR_PAD_LEFT);
287
 
288
                                                if ($i == 6) {
25 daniel-mar 289
                                                        // was overwritten by version
290
                                                        $bin[0] = '?';
291
                                                        $bin[1] = '?';
292
                                                        $bin[2] = '?';
293
                                                        $bin[3] = '?';
2 daniel-mar 294
                                                } else if ($i == 8) {
25 daniel-mar 295
                                                        // was partially overwritten by variant
296
                                                        $bin[0] = '?';
297
                                                        $bin[1] = '?';
2 daniel-mar 298
                                                }
299
 
25 daniel-mar 300
                                                if ($i<8) $rand_line1 .= "$bin ";
301
                                                if ($i>=8) $rand_line2 .= "$bin ";
2 daniel-mar 302
                                        }
25 daniel-mar 303
                                        echo sprintf("%-32s %s\n", "Random bits:", trim($rand_line1));
304
                                        echo sprintf("%-32s %s\n", "",             trim($rand_line2));
2 daniel-mar 305
 
27 daniel-mar 306
                                        $rand_bytes = str_replace('-', '', strtolower($uuid));
307
                                        $rand_bytes[12] = '?'; // was overwritten by version
308
                                        $var16a = dechex((hexdec($rand_bytes[16])&3) + 0x0/*00__*/);
309
                                        $var16b = dechex((hexdec($rand_bytes[16])&3) + 0x4/*01__*/);
310
                                        $var16c = dechex((hexdec($rand_bytes[16])&3) + 0x8/*10__*/);
311
                                        $var16d = dechex((hexdec($rand_bytes[16])&3) + 0xC/*11__*/);
312
                                        $rand_bytes[16] = '?'; // was partially overwritten by variant
313
                                        echo sprintf("%-32s %s\n", "Random bytes:", "[0x$rand_bytes]");
314
                                        echo sprintf("%-32s %s\n", "", "                   ^");
315
                                        echo sprintf("%-32s %s\n", "", "                   $var16a, $var16b, $var16c, or $var16d");
316
 
2 daniel-mar 317
                                        break;
318
                                case 5:
25 daniel-mar 319
                                        echo sprintf("%-32s %s\n", "Version:", "[5] Name-based (SHA-1 hash)");
2 daniel-mar 320
 
321
                                        $hash = str_replace('-', '', strtolower($uuid));
27 daniel-mar 322
 
2 daniel-mar 323
                                        $hash[12] = '?'; // was overwritten by version
27 daniel-mar 324
 
325
                                        $var16a = dechex((hexdec($hash[16])&3) + 0x0/*00__*/);
326
                                        $var16b = dechex((hexdec($hash[16])&3) + 0x4/*01__*/);
327
                                        $var16c = dechex((hexdec($hash[16])&3) + 0x8/*10__*/);
328
                                        $var16d = dechex((hexdec($hash[16])&3) + 0xC/*11__*/);
2 daniel-mar 329
                                        $hash[16] = '?'; // was partially overwritten by variant
27 daniel-mar 330
 
2 daniel-mar 331
                                        $hash .= '????????'; // was cut off
332
 
27 daniel-mar 333
                                        echo sprintf("%-32s %s\n", "SHA1(Namespace+Subject):", "[0x$hash]");
334
                                        echo sprintf("%-32s %s\n", "", "                   ^");
335
                                        echo sprintf("%-32s %s\n", "", "                   $var16a, $var16b, $var16c, or $var16d");
2 daniel-mar 336
 
337
                                        break;
27 daniel-mar 338
                                case 6:
339
                                        echo sprintf("%-32s %s\n", "Version:", "[$version] Reordered Time (NOT IMPLEMENTED YET)"); // TODO
340
                                        break;
341
                                case 7:
342
                                        echo sprintf("%-32s %s\n", "Version:", "[$version] Unix Epoch Time (NOT IMPLEMENTED YET)"); // TODO
343
                                        break;
344
                                case 8:
345
                                        echo sprintf("%-32s %s\n", "Version:", "[$version] Custom (NOT IMPLEMENTED YET)"); // TODO
346
                                        break;
2 daniel-mar 347
                                default:
25 daniel-mar 348
                                        echo sprintf("%-32s %s\n", "Version:", "[$version] Unknown");
2 daniel-mar 349
                                        break;
350
                        }
351
 
352
                        break;
353
                case 2:
27 daniel-mar 354
                        echo sprintf("%-32s %s\n", "Variant:", "[0b110] Reserved for Microsoft Corporation");
2 daniel-mar 355
                        break;
356
                case 3:
27 daniel-mar 357
                        echo sprintf("%-32s %s\n", "Variant:", "[0b111] Reserved for future use");
2 daniel-mar 358
                        break;
359
        }
360
}
361
 
362
function uuid_canonize($uuid) {
363
        if (!uuid_valid($uuid)) return false;
364
        return oid_to_uuid(uuid_to_oid($uuid));
365
}
366
 
367
function oid_to_uuid($oid) {
368
        if (!is_uuid_oid($oid)) return false;
369
 
8 daniel-mar 370
        if (substr($oid,0,1) == '.') {
2 daniel-mar 371
                $oid = substr($oid, 1);
372
        }
373
        $ary = explode('.', $oid);
374
 
375
        if (!isset($ary[2])) return false;
376
 
377
        $val = $ary[2];
378
 
379
        $x = gmp_init($val, 10);
380
        $y = gmp_strval($x, 16);
381
        $y = str_pad($y, 32, "0", STR_PAD_LEFT);
382
        return substr($y,  0, 8).'-'.
383
               substr($y,  8, 4).'-'.
384
               substr($y, 12, 4).'-'.
385
               substr($y, 16, 4).'-'.
386
               substr($y, 20, 12);
387
}
388
 
389
function is_uuid_oid($oid, $only_allow_root=false) {
9 daniel-mar 390
        if (substr($oid,0,1) == '.') $oid = substr($oid, 1); // remove leading dot
2 daniel-mar 391
 
392
        $ary = explode('.', $oid);
393
 
394
        if ($only_allow_root) {
395
                if (count($ary) != 3) return false;
396
        } else {
397
                if (count($ary) < 3) return false;
398
        }
399
 
400
        if ($ary[0] != '2') return false;
401
        if ($ary[1] != '25') return false;
402
        for ($i=2; $i<count($ary); $i++) {
403
                $v = $ary[$i];
404
                if (!is_numeric($v)) return false;
405
                if ($i == 2) {
406
                        // Must be in the range of 128 bit UUID
407
                        $test = gmp_init($v, 10);
408
                        if (strlen(gmp_strval($test, 16)) > 32) return false;
409
                }
410
                if ($v < 0) return false;
411
        }
412
 
413
        return true;
414
}
415
 
416
function uuid_to_oid($uuid) {
417
        if (!uuid_valid($uuid)) return false;
418
 
419
        $uuid = str_replace(array('-', '{', '}'), '', $uuid);
420
        $x = gmp_init($uuid, 16);
421
        return '2.25.'.gmp_strval($x, 10); # TODO: parameter with or without leading dot
422
}
423
 
424
function gen_uuid($prefer_timebased = true) {
425
        $uuid = $prefer_timebased ? gen_uuid_timebased() : false;
426
        if ($uuid === false) $uuid = gen_uuid_random();
427
        return $uuid;
428
}
429
 
430
// Version 1 (Time based) UUID
431
function gen_uuid_timebased() {
432
        # On Debian: apt-get install php-uuid
433
        # extension_loaded('uuid')
434
        if (function_exists('uuid_create')) {
435
                # OSSP uuid extension like seen in php5-uuid at Debian 8
436
                /*
437
                $x = uuid_create($context);
438
                uuid_make($context, UUID_MAKE_V1);
439
                uuid_export($context, UUID_FMT_STR, $uuid);
440
                return trim($uuid);
441
                */
442
 
443
                # PECL uuid extension like seen in php-uuid at Debian 9
444
                return trim(uuid_create(UUID_TYPE_TIME));
445
        }
446
 
447
        # On Debian: apt-get install uuid-runtime
448
        if (strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN') {
449
                $out = array();
450
                $ec = -1;
451
                exec('uuidgen -t 2>/dev/null', $out, $ec);
452
                if ($ec == 0) return trim($out[0]);
453
        }
454
 
455
        # If we hadn't any success yet, then implement the time based generation routine ourselves!
456
        # Based on https://github.com/fredriklindberg/class.uuid.php/blob/master/class.uuid.php
457
 
458
        $uuid = array(
459
                'time_low' => 0,                /* 32-bit */
460
                'time_mid' => 0,                /* 16-bit */
461
                'time_hi' => 0,                 /* 16-bit */
462
                'clock_seq_hi' => 0,            /*  8-bit */
463
                'clock_seq_low' => 0,           /*  8-bit */
464
                'node' => array()               /* 48-bit */
465
        );
466
 
467
        /*
468
         * Get current time in 100 ns intervals. The magic value
469
         * is the offset between UNIX epoch and the UUID UTC
470
         * time base October 15, 1582.
471
         */
472
        $tp = gettimeofday();
473
        $time = ($tp['sec'] * 10000000) + ($tp['usec'] * 10) + 0x01B21DD213814000;
474
 
475
        $uuid['time_low'] = $time & 0xffffffff;
476
        /* Work around PHP 32-bit bit-operation limits */
477
        $high = intval($time / 0xffffffff);
478
        $uuid['time_mid'] = $high & 0xffff;
479
        $uuid['time_hi'] = (($high >> 16) & 0xfff) | (1/*TimeBased*/ << 12);
480
 
481
        /*
482
         * We don't support saved state information and generate
483
         * a random clock sequence each time.
484
         */
24 daniel-mar 485
        $uuid['clock_seq_hi'] = 0x80 | _random_int(0, 64);
486
        $uuid['clock_seq_low'] = _random_int(0, 255);
2 daniel-mar 487
 
488
        /*
489
         * Node should be set to the 48-bit IEEE node identifier
490
         */
491
        $mac = get_mac_address();
492
        if ($mac) {
25 daniel-mar 493
                $node = str_replace('-','',str_replace(':','',$mac));
2 daniel-mar 494
                for ($i = 0; $i < 6; $i++) {
495
                        $uuid['node'][$i] = hexdec(substr($node, $i*2, 2));
496
                }
497
 
498
                /*
499
                 * Now output the UUID
500
                 */
501
                return sprintf(
502
                        '%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x',
503
                        ($uuid['time_low']), ($uuid['time_mid']), ($uuid['time_hi']),
504
                        $uuid['clock_seq_hi'], $uuid['clock_seq_low'],
505
                        $uuid['node'][0], $uuid['node'][1], $uuid['node'][2],
506
                        $uuid['node'][3], $uuid['node'][4], $uuid['node'][5]);
507
        }
508
 
509
        # We cannot generate the timebased UUID!
510
        return false;
511
}
512
 
513
function get_mac_address() {
514
        static $detected_mac = false;
515
 
516
        if ($detected_mac !== false) { // false NOT null!
517
                return $detected_mac;
518
        }
519
 
520
        // TODO: This should actually be part of mac_utils.inc.php, but we need it
521
        //       here, and mac_utils.inc.php shall only be optional. What to do?
522
        if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
523
                // Windows
524
                $cmds = array(
525
                        "ipconfig /all", // faster
526
                        "getmac"
527
                );
528
                foreach ($cmds as $cmd) {
529
                        $out = array();
530
                        $ec = -1;
531
                        exec($cmd, $out, $ec);
532
                        if ($ec == 0) {
533
                                $out = implode("\n",$out);
534
                                $m = array();
535
                                if (preg_match("/([0-9a-f]{2}\\-[0-9a-f]{2}\\-[0-9a-f]{2}\\-[0-9a-f]{2}\\-[0-9a-f]{2}\\-[0-9a-f]{2})/ismU", $out, $m)) {
25 daniel-mar 536
                                        $detected_mac = strtolower($m[1]);
2 daniel-mar 537
                                        return $detected_mac;
538
                                }
539
                        }
540
                }
541
        } else if (strtoupper(PHP_OS) == 'DARWIN') {
542
                // Mac OS X
543
                $cmds = array(
544
                        "networksetup -listallhardwareports 2>/dev/null",
545
                        "netstat -i 2>/dev/null"
546
                );
547
                foreach ($cmds as $cmd) {
548
                        $out = array();
549
                        $ec = -1;
550
                        exec($cmd, $out, $ec);
551
                        if ($ec == 0) {
552
                                $out = implode("\n",$out);
553
                                $m = array();
554
                                if (preg_match("/([0-9a-f]{2}:[0-9a-f]{2}:[0-9a-f]{2}:[0-9a-f]{2}:[0-9a-f]{2}:[0-9a-f]{2})/ismU", $out, $m)) {
555
                                        $detected_mac = $m[1];
556
                                        return $detected_mac;
557
                                }
558
                        }
559
                }
560
        } else {
561
                // Linux
8 daniel-mar 562
                $addresses = @glob('/sys/class/net/'.'*'.'/address');
563
                foreach ($addresses as $x) {
2 daniel-mar 564
                        if (!strstr($x,'/lo/')) {
565
                                $detected_mac = trim(file_get_contents($x));
566
                                return $detected_mac;
567
                        }
568
                }
569
                $cmds = array(
570
                        "netstat -ie 2>/dev/null",
571
                        "ifconfig 2>/dev/null" // only available for root (because it is in sbin)
572
                );
573
                foreach ($cmds as $cmd) {
574
                        $out = array();
575
                        $ec = -1;
576
                        exec($cmd, $out, $ec);
577
                        if ($ec == 0) {
578
                                $out = implode("\n",$out);
579
                                $m = array();
580
                                if (preg_match("/([0-9a-f]{2}:[0-9a-f]{2}:[0-9a-f]{2}:[0-9a-f]{2}:[0-9a-f]{2}:[0-9a-f]{2})/ismU", $out, $m)) {
581
                                        $detected_mac = $m[1];
582
                                        return $detected_mac;
583
                                }
584
                        }
585
                }
586
        }
587
 
588
        $detected_mac = null;
589
        return $detected_mac;
590
}
591
 
592
// Version 2 (DCE Security) UUID
27 daniel-mar 593
define('DCE_DOMAIN_PERSON', 0);
594
define('DCE_DOMAIN_GROUP', 1);
595
define('DCE_DOMAIN_ORG', 2);
2 daniel-mar 596
function gen_uuid_dce($domain, $id) {
597
        # Start with a version 1 UUID
598
        $uuid = gen_uuid_timebased();
599
 
27 daniel-mar 600
        # Add Domain Number
2 daniel-mar 601
        $uuid = str_pad(dechex($id), 8, '0', STR_PAD_LEFT) . substr($uuid, 8);
602
 
27 daniel-mar 603
        # Add Domain (this overwrites part of the clock sequence)
2 daniel-mar 604
        $uuid = substr($uuid,0,21) . str_pad(dechex($domain), 2, '0', STR_PAD_LEFT) . substr($uuid, 23);
605
 
606
        # Change version to 2
607
        $uuid[14] = '2';
608
 
609
        return $uuid;
610
}
611
 
612
// Version 3 (MD5 name based) UUID
613
function gen_uuid_md5_namebased($namespace_uuid, $name) {
614
        if (!uuid_valid($namespace_uuid)) return false;
615
        $namespace_uuid = uuid_canonize($namespace_uuid);
616
        $namespace_uuid = str_replace('-', '', $namespace_uuid);
617
        $namespace_uuid = hex2bin($namespace_uuid);
618
 
619
        $hash = md5($namespace_uuid.$name);
620
        $hash[12] = '3'; // Set version: 3 = MD5
621
        $hash[16] = dechex(hexdec($hash[16]) & 0x3 | 0x8); // Set variant to "10xx" (RFC4122)
622
 
623
        return substr($hash,  0, 8).'-'.
624
               substr($hash,  8, 4).'-'.
625
               substr($hash, 12, 4).'-'.
626
               substr($hash, 16, 4).'-'.
627
               substr($hash, 20, 12);
628
}
629
 
630
// Version 4 (Random) UUID
631
function gen_uuid_random() {
632
        # On Windows: Requires
633
        #    extension_dir = "C:\php-8.0.3-nts-Win32-vs16-x64\ext"
634
        #    extension=com_dotnet
635
        if (function_exists('com_create_guid')) {
636
                return strtolower(trim(com_create_guid(), '{}'));
637
        }
638
 
639
        # On Debian: apt-get install php-uuid
640
        # extension_loaded('uuid')
641
        if (function_exists('uuid_create')) {
642
                # OSSP uuid extension like seen in php5-uuid at Debian 8
643
                /*
644
                $x = uuid_create($context);
645
                uuid_make($context, UUID_MAKE_V4);
646
                uuid_export($context, UUID_FMT_STR, $uuid);
647
                return trim($uuid);
648
                */
649
 
650
                # PECL uuid extension like seen in php-uuid at Debian 9
651
                return trim(uuid_create(UUID_TYPE_RANDOM));
652
        }
653
 
654
        if (strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN') {
655
                # On Debian: apt-get install uuid-runtime
656
                $out = array();
657
                $ec = -1;
658
                exec('uuidgen -r 2>/dev/null', $out, $ec);
659
                if ($ec == 0) return trim($out[0]);
660
 
661
                # On Debian Jessie: UUID V4 (Random)
662
                if (file_exists('/proc/sys/kernel/random/uuid')) {
663
                        return trim(file_get_contents('/proc/sys/kernel/random/uuid'));
664
                }
665
        }
666
 
667
        # Make the UUID by ourselves
668
        # Source: http://rogerstringer.com/2013/11/15/generate-uuids-php
669
        return sprintf( '%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
24 daniel-mar 670
                _random_int( 0, 0xffff ), _random_int( 0, 0xffff ),
671
                _random_int( 0, 0xffff ),
672
                _random_int( 0, 0x0fff ) | 0x4000,
673
                _random_int( 0, 0x3fff ) | 0x8000,
674
                _random_int( 0, 0xffff ), _random_int( 0, 0xffff ), _random_int( 0, 0xffff )
2 daniel-mar 675
        );
676
}
677
 
678
// Version 5 (SHA1 name based) UUID
679
function gen_uuid_sha1_namebased($namespace_uuid, $name) {
680
        $namespace_uuid = str_replace('-', '', $namespace_uuid);
681
        $namespace_uuid = hex2bin($namespace_uuid);
682
 
683
        $hash = sha1($namespace_uuid.$name);
684
        $hash[12] = '5'; // Set version: 5 = SHA1
27 daniel-mar 685
        $hash[16] = dechex(hexdec($hash[16]) & 0x3 | 0x8); // Set variant to "0b10__" (RFC4122/DCE1.1)
2 daniel-mar 686
 
687
        return substr($hash,  0, 8).'-'.
688
               substr($hash,  8, 4).'-'.
689
               substr($hash, 12, 4).'-'.
690
               substr($hash, 16, 4).'-'.
691
               substr($hash, 20, 12);
692
}
693
 
694
function uuid_numeric_value($uuid) {
695
        $oid = uuid_to_oid($uuid);
696
        if (!$oid) return false;
697
        return substr($oid, strlen('2.25.'));
698
}
699
 
700
function uuid_c_syntax($uuid) {
701
        $uuid = str_replace('{', '', $uuid);
702
        return '{ 0x' . substr($uuid, 0, 8) .
703
                ', 0x' . substr($uuid, 9, 4) .
704
                ', 0x' . substr($uuid, 14, 4) .
705
                ', { 0x' . substr($uuid, 19, 2).
706
                ', 0x' . substr($uuid, 21, 2) .
707
                ', 0x' . substr($uuid, 24, 2) .
708
                ', 0x' . substr($uuid, 26, 2) .
709
                ', 0x' . substr($uuid, 28, 2) .
710
                ', 0x' . substr($uuid, 30, 2) .
711
                ', 0x' . substr($uuid, 32, 2) .
712
                ', 0x' . substr($uuid, 34, 2) . ' } }';
713
}
714
 
715
# ---
716
 
717
// http://php.net/manual/de/function.hex2bin.php#113057
718
if ( !function_exists( 'hex2bin' ) ) {
719
    function hex2bin( $str ) {
720
        $sbin = "";
721
        $len = strlen( $str );
722
        for ( $i = 0; $i < $len; $i += 2 ) {
723
            $sbin .= pack( "H*", substr( $str, $i, 2 ) );
724
        }
725
 
726
        return $sbin;
727
    }
728
}