Subversion Repositories uuid_mac_utils

Rev

Rev 15 | Rev 25 | 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
24 daniel-mar 6
 * Version 2023-05-06
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:
70
                        echo sprintf("%-24s %s\n", "Variant:", "[0xx] NCS (reserved for backward compatibility)");
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
                         * +--------------------------------------------------------------+
86
                         * |                    high 32 bits of time                      |  0-3  .time_high
87
                         * +-------------------------------+-------------------------------
88
                         * |     low 16 bits of time       |  4-5               .time_low
89
                         * +-------+-----------------------+
90
                         * |         reserved              |  6-7               .reserved
91
                         * +---------------+---------------+
92
                         * |    family     |   8                                .family
93
                         * +---------------+----------...-----+
94
                         * |            node ID               |  9-16           .node
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
 
103
                        # Timestamp: Count of 4us intervals since 01 Jan 1980 00:00:00 GMT
104
                        # 1/0,000004 = 250000
105
                        # Seconds between 1970 and 1980 : 315532800
106
                        # 250000*315532800=78883200000000
107
                        $timestamp = substr($uuid, 0, 12);
108
                        $ts = gmp_init($timestamp, 16);
109
                        $ts = gmp_add($ts, gmp_init("78883200000000"));
110
                        $ms = gmp_mod($ts, gmp_init("250000"));
111
                        $ts = gmp_div($ts, gmp_init("250000"));
112
                        $ts = gmp_strval($ts);
113
                        $ms = gmp_strval($ms);
114
                        $ts = gmdate('Y-m-d H:i:s', intval($ts))."'".str_pad($ms, 7, '0', STR_PAD_LEFT).' GMT';
115
                        echo sprintf("%-24s %s\n", "Timestamp:", "[0x$timestamp] $ts");
116
 
117
                        $reserved = substr($uuid, 12, 4);
118
                        echo sprintf("%-24s %s\n", "Reserved:", "0x$reserved");
119
 
120
                        # Family 13 (dds) looks like node is 00 | nnnnnn 000000.
121
                        # Family 2 is presumably (ip).
122
                        # Not sure if anything else was used.
123
                        $family_hex = substr($uuid, 16, 2);
124
                        $family_dec = hexdec($family_hex);
125
                        if ($family_dec == 2) {
126
                                $family_ = 'IP';
127
                        } else if ($family_dec == 13) {
128
                                $family_ = 'DDS (Data Link)';
129
                        } else {
130
                                $family_ = "Unknown ($family_dec)"; # There are probably no more families
131
                        }
132
                        echo sprintf("%-24s %s\n", "Family:", "[0x$family_hex = $family_dec] $family_");
133
 
134
                        $nodeid = substr($uuid, 18, 14);
135
                        echo sprintf("%-24s %s\n", "Node ID:", "0x$nodeid");
136
                        # TODO: interprete node id (the family specifies it)
137
 
138
                        break;
139
                case 1:
140
                        echo sprintf("%-24s %s\n", "Variant:", "[10x] RFC 4122 (Leach-Mealling-Salz)");
141
 
142
                        $version = hexdec(substr($uuid, 12, 1));
143
                        switch ($version) {
144
                                case 1:
145
                                        echo sprintf("%-24s %s\n", "Version:", "[1] Time-based with unique random host identifier");
146
 
147
                                        # Timestamp: Count of 100ns intervals since 15 Oct 1582 00:00:00
148
                                        # 1/0,0000001 = 10000000
149
                                        $timestamp = substr($uuid, 13, 3).substr($uuid, 8, 4).substr($uuid, 0, 8);
150
                                        $ts = gmp_init($timestamp, 16);
151
                                        $ts = gmp_sub($ts, gmp_init("122192928000000000"));
152
                                        $ms = gmp_mod($ts, gmp_init("10000000"));
153
                                        $ts = gmp_div($ts, gmp_init("10000000"));
154
                                        $ts = gmp_strval($ts);
155
                                        $ms = gmp_strval($ms);
156
                                        $ts = gmdate('Y-m-d H:i:s', intval($ts))."'".str_pad($ms, 7, '0', STR_PAD_LEFT).' GMT';
157
                                        echo sprintf("%-24s %s\n", "Timestamp:", "[0x$timestamp] $ts");
158
 
159
                                        $x = hexdec(substr($uuid, 16, 4));
160
                                        $dec = $x & 0x3FFF; // The highest 2 bits are used by "variant" (10x)
161
                                        $hex = substr($uuid, 16, 4);
162
                                        echo sprintf("%-24s %s\n", "Clock ID:", "[0x$hex] $dec");
163
 
164
                                        $x = substr($uuid, 20, 12);
165
                                        $nodeid = '';
166
                                        for ($i=0; $i<6; $i++) {
167
                                                $nodeid .= substr($x, $i*2, 2);
168
                                                if ($i != 5) $nodeid .= ':';
169
                                        }
170
                                        echo sprintf("%-24s %s\n", "Node ID:", "$nodeid");
171
 
172
                                        if (function_exists('decode_mac')) {
173
                                                echo "\nIn case that this Node ID is a MAC address, here is the interpretation of that MAC address:\n";
15 daniel-mar 174
                                                decode_mac($nodeid);
2 daniel-mar 175
                                        }
176
 
177
                                        break;
178
                                case 2:
179
                                        echo sprintf("%-24s %s\n", "Version:", "[2] DCE Security version");
180
 
181
                                        # 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.
182
                                        $x = substr($uuid, 0, 8);
183
                                        echo sprintf("%-24s %s\n", "Local ID:", "0x$x");
184
 
185
                                        # 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".
186
                                        $x = substr($uuid, 18, 2);
187
                                        if ($x == '00') $domain_info = 'POSIX: User-ID / Non-POSIX: site-defined';
188
                                        else if ($x == '01') $domain_info = 'POSIX: Group-ID / Non-POSIX: site-defined';
189
                                        else $domain_info = 'site-defined';
190
                                        echo sprintf("%-24s %s\n", "Local Domain:", "0x$x ($domain_info)");
191
 
192
                                        # Timestamp: Count of 100ns intervals since 15 Oct 1582 00:00:00
193
                                        # 1/0,0000001 = 10000000
194
                                        $timestamp = substr($uuid, 13, 3).substr($uuid, 8, 4).'00000000';
195
                                        $ts = gmp_init($timestamp, 16);
196
                                        $ts = gmp_sub($ts, gmp_init("122192928000000000"));
197
                                        $ms = gmp_mod($ts, gmp_init("10000000"));
198
                                        $ts = gmp_div($ts, gmp_init("10000000"));
199
                                        $ts = gmp_strval($ts);
200
                                        $ms = gmp_strval($ms);
201
                                        $ts_min = gmdate('Y-m-d H:i:s', intval($ts))."'".str_pad($ms, 7, '0', STR_PAD_LEFT).' GMT';
202
 
203
                                        $timestamp = substr($uuid, 13, 3).substr($uuid, 8, 4).'FFFFFFFF';
204
                                        $ts = gmp_init($timestamp, 16);
205
                                        $ts = gmp_sub($ts, gmp_init("122192928000000000"));
206
                                        $ms = gmp_mod($ts, gmp_init("10000000"));
207
                                        $ts = gmp_div($ts, gmp_init("10000000"));
208
                                        $ts = gmp_strval($ts);
209
                                        $ms = gmp_strval($ms);
210
                                        $ts_max = gmdate('Y-m-d H:i:s', intval($ts))."'".str_pad($ms, 7, '0', STR_PAD_LEFT).' GMT';
211
 
212
                                        $timestamp = substr($uuid, 13, 3).substr($uuid, 8, 4).'xxxxxxxx';
213
                                        echo sprintf("%-24s %s\n", "Timestamp:", "[0x$timestamp] $ts_min - $ts_max");
214
 
215
                                        $x = hexdec(substr($uuid, 16, 2).'00');
216
                                        $dec_min = $x & 0x3FFF; // The highest 2 bits are used by "variant" (10x)
217
                                        $x = hexdec(substr($uuid, 16, 2).'FF');
218
                                        $dec_max = $x & 0x3FFF; // The highest 2 bits are used by "variant" (10x)
219
                                        $hex = substr($uuid, 16, 2).'xx';
220
                                        echo sprintf("%-24s %s\n", "Clock ID:", "[0x$hex] $dec_min - $dec_max");
221
 
222
                                        $x = substr($uuid, 20, 12);
223
                                        $nodeid = '';
224
                                        for ($i=0; $i<6; $i++) {
225
                                                $nodeid .= substr($x, $i*2, 2);
226
                                                if ($i != 5) $nodeid .= ':';
227
                                        }
228
                                        echo sprintf("%-24s %s\n", "Node ID:", "$nodeid");
229
 
230
                                        if (function_exists('decode_mac')) {
231
                                                echo "\nIn case that this Node ID is a MAC address, here is the interpretation of that MAC address:\n";
15 daniel-mar 232
                                                decode_mac($nodeid);
2 daniel-mar 233
                                        }
234
 
235
                                        break;
236
                                case 3:
237
                                        echo sprintf("%-24s %s\n", "Version:", "[3] Name-based (MD5 hash)");
238
 
239
                                        $hash = str_replace('-', '', strtolower($uuid));
240
                                        $hash[12] = '?'; // was overwritten by version
241
                                        $hash[16] = '?'; // was partially overwritten by variant
242
 
243
                                        echo sprintf("%-24s %s\n", "MD5(Namespace+Subject):", "$hash");
244
 
245
                                        break;
246
                                case 4:
247
                                        echo sprintf("%-24s %s\n", "Version:", "[4] Random");
248
 
249
                                        $rand = '';
250
                                        for ($i=0; $i<16; $i++) {
251
                                                $bin = base_convert(substr($uuid, $i*2, 2), 16, 2);
252
                                                $bin = str_pad($bin, 8, "0", STR_PAD_LEFT);
253
 
254
                                                if ($i == 6) {
255
                                                        $bin[0] = 'x';
256
                                                        $bin[1] = 'x';
257
                                                } else if ($i == 8) {
258
                                                        $bin[0] = 'x';
259
                                                        $bin[1] = 'x';
260
                                                        $bin[2] = 'x';
261
                                                        $bin[3] = 'x';
262
                                                }
263
 
264
                                                $rand .= "$bin ";
265
                                        }
266
 
267
                                        echo sprintf("%-24s %s\n", "Random bits:", trim($rand));
268
 
269
                                        break;
270
                                case 5:
271
                                        echo sprintf("%-24s %s\n", "Version:", "[5] Name-based (SHA-1 hash)");
272
 
273
                                        $hash = str_replace('-', '', strtolower($uuid));
274
                                        $hash[12] = '?'; // was overwritten by version
275
                                        $hash[16] = '?'; // was partially overwritten by variant
276
                                        $hash .= '????????'; // was cut off
277
 
278
                                        echo sprintf("%-24s %s\n", "SHA1(Namespace+Subject):", "$hash");
279
 
280
 
281
                                        break;
282
                                default:
283
                                        echo sprintf("%-24s %s\n", "Version:", "[$version] Unknown");
284
                                        break;
285
                        }
286
 
287
                        break;
288
                case 2:
289
                        echo sprintf("%-24s %s\n", "Variant:", "[110] Reserved for Microsoft Corporation");
290
                        break;
291
                case 3:
292
                        echo sprintf("%-24s %s\n", "Variant:", "[111] Reserved for future use");
293
                        break;
294
        }
295
}
296
 
297
function uuid_canonize($uuid) {
298
        if (!uuid_valid($uuid)) return false;
299
        return oid_to_uuid(uuid_to_oid($uuid));
300
}
301
 
302
function oid_to_uuid($oid) {
303
        if (!is_uuid_oid($oid)) return false;
304
 
8 daniel-mar 305
        if (substr($oid,0,1) == '.') {
2 daniel-mar 306
                $oid = substr($oid, 1);
307
        }
308
        $ary = explode('.', $oid);
309
 
310
        if (!isset($ary[2])) return false;
311
 
312
        $val = $ary[2];
313
 
314
        $x = gmp_init($val, 10);
315
        $y = gmp_strval($x, 16);
316
        $y = str_pad($y, 32, "0", STR_PAD_LEFT);
317
        return substr($y,  0, 8).'-'.
318
               substr($y,  8, 4).'-'.
319
               substr($y, 12, 4).'-'.
320
               substr($y, 16, 4).'-'.
321
               substr($y, 20, 12);
322
}
323
 
324
function is_uuid_oid($oid, $only_allow_root=false) {
9 daniel-mar 325
        if (substr($oid,0,1) == '.') $oid = substr($oid, 1); // remove leading dot
2 daniel-mar 326
 
327
        $ary = explode('.', $oid);
328
 
329
        if ($only_allow_root) {
330
                if (count($ary) != 3) return false;
331
        } else {
332
                if (count($ary) < 3) return false;
333
        }
334
 
335
        if ($ary[0] != '2') return false;
336
        if ($ary[1] != '25') return false;
337
        for ($i=2; $i<count($ary); $i++) {
338
                $v = $ary[$i];
339
                if (!is_numeric($v)) return false;
340
                if ($i == 2) {
341
                        // Must be in the range of 128 bit UUID
342
                        $test = gmp_init($v, 10);
343
                        if (strlen(gmp_strval($test, 16)) > 32) return false;
344
                }
345
                if ($v < 0) return false;
346
        }
347
 
348
        return true;
349
}
350
 
351
function uuid_to_oid($uuid) {
352
        if (!uuid_valid($uuid)) return false;
353
 
354
        $uuid = str_replace(array('-', '{', '}'), '', $uuid);
355
        $x = gmp_init($uuid, 16);
356
        return '2.25.'.gmp_strval($x, 10); # TODO: parameter with or without leading dot
357
}
358
 
359
function gen_uuid($prefer_timebased = true) {
360
        $uuid = $prefer_timebased ? gen_uuid_timebased() : false;
361
        if ($uuid === false) $uuid = gen_uuid_random();
362
        return $uuid;
363
}
364
 
365
// Version 1 (Time based) UUID
366
function gen_uuid_timebased() {
367
        # On Debian: apt-get install php-uuid
368
        # extension_loaded('uuid')
369
        if (function_exists('uuid_create')) {
370
                # OSSP uuid extension like seen in php5-uuid at Debian 8
371
                /*
372
                $x = uuid_create($context);
373
                uuid_make($context, UUID_MAKE_V1);
374
                uuid_export($context, UUID_FMT_STR, $uuid);
375
                return trim($uuid);
376
                */
377
 
378
                # PECL uuid extension like seen in php-uuid at Debian 9
379
                return trim(uuid_create(UUID_TYPE_TIME));
380
        }
381
 
382
        # On Debian: apt-get install uuid-runtime
383
        if (strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN') {
384
                $out = array();
385
                $ec = -1;
386
                exec('uuidgen -t 2>/dev/null', $out, $ec);
387
                if ($ec == 0) return trim($out[0]);
388
        }
389
 
390
        # If we hadn't any success yet, then implement the time based generation routine ourselves!
391
        # Based on https://github.com/fredriklindberg/class.uuid.php/blob/master/class.uuid.php
392
 
393
        $uuid = array(
394
                'time_low' => 0,                /* 32-bit */
395
                'time_mid' => 0,                /* 16-bit */
396
                'time_hi' => 0,                 /* 16-bit */
397
                'clock_seq_hi' => 0,            /*  8-bit */
398
                'clock_seq_low' => 0,           /*  8-bit */
399
                'node' => array()               /* 48-bit */
400
        );
401
 
402
        /*
403
         * Get current time in 100 ns intervals. The magic value
404
         * is the offset between UNIX epoch and the UUID UTC
405
         * time base October 15, 1582.
406
         */
407
        $tp = gettimeofday();
408
        $time = ($tp['sec'] * 10000000) + ($tp['usec'] * 10) + 0x01B21DD213814000;
409
 
410
        $uuid['time_low'] = $time & 0xffffffff;
411
        /* Work around PHP 32-bit bit-operation limits */
412
        $high = intval($time / 0xffffffff);
413
        $uuid['time_mid'] = $high & 0xffff;
414
        $uuid['time_hi'] = (($high >> 16) & 0xfff) | (1/*TimeBased*/ << 12);
415
 
416
        /*
417
         * We don't support saved state information and generate
418
         * a random clock sequence each time.
419
         */
24 daniel-mar 420
        $uuid['clock_seq_hi'] = 0x80 | _random_int(0, 64);
421
        $uuid['clock_seq_low'] = _random_int(0, 255);
2 daniel-mar 422
 
423
        /*
424
         * Node should be set to the 48-bit IEEE node identifier
425
         */
426
        $mac = get_mac_address();
427
        if ($mac) {
428
                $node = str_replace(':','',$mac);
429
                for ($i = 0; $i < 6; $i++) {
430
                        $uuid['node'][$i] = hexdec(substr($node, $i*2, 2));
431
                }
432
 
433
                /*
434
                 * Now output the UUID
435
                 */
436
                return sprintf(
437
                        '%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x',
438
                        ($uuid['time_low']), ($uuid['time_mid']), ($uuid['time_hi']),
439
                        $uuid['clock_seq_hi'], $uuid['clock_seq_low'],
440
                        $uuid['node'][0], $uuid['node'][1], $uuid['node'][2],
441
                        $uuid['node'][3], $uuid['node'][4], $uuid['node'][5]);
442
        }
443
 
444
        # We cannot generate the timebased UUID!
445
        return false;
446
}
447
 
448
function get_mac_address() {
449
        static $detected_mac = false;
450
 
451
        if ($detected_mac !== false) { // false NOT null!
452
                return $detected_mac;
453
        }
454
 
455
        // TODO: This should actually be part of mac_utils.inc.php, but we need it
456
        //       here, and mac_utils.inc.php shall only be optional. What to do?
457
        if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
458
                // Windows
459
                $cmds = array(
460
                        "ipconfig /all", // faster
461
                        "getmac"
462
                );
463
                foreach ($cmds as $cmd) {
464
                        $out = array();
465
                        $ec = -1;
466
                        exec($cmd, $out, $ec);
467
                        if ($ec == 0) {
468
                                $out = implode("\n",$out);
469
                                $m = array();
470
                                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)) {
471
                                        $detected_mac = str_replace('-', ':', strtolower($m[1]));
472
                                        return $detected_mac;
473
                                }
474
                        }
475
                }
476
        } else if (strtoupper(PHP_OS) == 'DARWIN') {
477
                // Mac OS X
478
                $cmds = array(
479
                        "networksetup -listallhardwareports 2>/dev/null",
480
                        "netstat -i 2>/dev/null"
481
                );
482
                foreach ($cmds as $cmd) {
483
                        $out = array();
484
                        $ec = -1;
485
                        exec($cmd, $out, $ec);
486
                        if ($ec == 0) {
487
                                $out = implode("\n",$out);
488
                                $m = array();
489
                                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)) {
490
                                        $detected_mac = $m[1];
491
                                        return $detected_mac;
492
                                }
493
                        }
494
                }
495
        } else {
496
                // Linux
8 daniel-mar 497
                $addresses = @glob('/sys/class/net/'.'*'.'/address');
498
                foreach ($addresses as $x) {
2 daniel-mar 499
                        if (!strstr($x,'/lo/')) {
500
                                $detected_mac = trim(file_get_contents($x));
501
                                return $detected_mac;
502
                        }
503
                }
504
                $cmds = array(
505
                        "netstat -ie 2>/dev/null",
506
                        "ifconfig 2>/dev/null" // only available for root (because it is in sbin)
507
                );
508
                foreach ($cmds as $cmd) {
509
                        $out = array();
510
                        $ec = -1;
511
                        exec($cmd, $out, $ec);
512
                        if ($ec == 0) {
513
                                $out = implode("\n",$out);
514
                                $m = array();
515
                                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)) {
516
                                        $detected_mac = $m[1];
517
                                        return $detected_mac;
518
                                }
519
                        }
520
                }
521
        }
522
 
523
        $detected_mac = null;
524
        return $detected_mac;
525
}
526
 
527
// Version 2 (DCE Security) UUID
528
function gen_uuid_dce($domain, $id) {
529
        # Start with a version 1 UUID
530
        $uuid = gen_uuid_timebased();
531
 
532
        # Add ID
533
        $uuid = str_pad(dechex($id), 8, '0', STR_PAD_LEFT) . substr($uuid, 8);
534
 
535
        # Add domain
536
        $uuid = substr($uuid,0,21) . str_pad(dechex($domain), 2, '0', STR_PAD_LEFT) . substr($uuid, 23);
537
 
538
        # Change version to 2
539
        $uuid[14] = '2';
540
 
541
        return $uuid;
542
}
543
 
544
// Version 3 (MD5 name based) UUID
545
function gen_uuid_md5_namebased($namespace_uuid, $name) {
546
        if (!uuid_valid($namespace_uuid)) return false;
547
        $namespace_uuid = uuid_canonize($namespace_uuid);
548
        $namespace_uuid = str_replace('-', '', $namespace_uuid);
549
        $namespace_uuid = hex2bin($namespace_uuid);
550
 
551
        $hash = md5($namespace_uuid.$name);
552
        $hash[12] = '3'; // Set version: 3 = MD5
553
        $hash[16] = dechex(hexdec($hash[16]) & 0x3 | 0x8); // Set variant to "10xx" (RFC4122)
554
 
555
        return substr($hash,  0, 8).'-'.
556
               substr($hash,  8, 4).'-'.
557
               substr($hash, 12, 4).'-'.
558
               substr($hash, 16, 4).'-'.
559
               substr($hash, 20, 12);
560
}
561
 
562
// Version 4 (Random) UUID
563
function gen_uuid_random() {
564
        # On Windows: Requires
565
        #    extension_dir = "C:\php-8.0.3-nts-Win32-vs16-x64\ext"
566
        #    extension=com_dotnet
567
        if (function_exists('com_create_guid')) {
568
                return strtolower(trim(com_create_guid(), '{}'));
569
        }
570
 
571
        # On Debian: apt-get install php-uuid
572
        # extension_loaded('uuid')
573
        if (function_exists('uuid_create')) {
574
                # OSSP uuid extension like seen in php5-uuid at Debian 8
575
                /*
576
                $x = uuid_create($context);
577
                uuid_make($context, UUID_MAKE_V4);
578
                uuid_export($context, UUID_FMT_STR, $uuid);
579
                return trim($uuid);
580
                */
581
 
582
                # PECL uuid extension like seen in php-uuid at Debian 9
583
                return trim(uuid_create(UUID_TYPE_RANDOM));
584
        }
585
 
586
        if (strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN') {
587
                # On Debian: apt-get install uuid-runtime
588
                $out = array();
589
                $ec = -1;
590
                exec('uuidgen -r 2>/dev/null', $out, $ec);
591
                if ($ec == 0) return trim($out[0]);
592
 
593
                # On Debian Jessie: UUID V4 (Random)
594
                if (file_exists('/proc/sys/kernel/random/uuid')) {
595
                        return trim(file_get_contents('/proc/sys/kernel/random/uuid'));
596
                }
597
        }
598
 
599
        # Make the UUID by ourselves
600
        # Source: http://rogerstringer.com/2013/11/15/generate-uuids-php
601
        return sprintf( '%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
24 daniel-mar 602
                _random_int( 0, 0xffff ), _random_int( 0, 0xffff ),
603
                _random_int( 0, 0xffff ),
604
                _random_int( 0, 0x0fff ) | 0x4000,
605
                _random_int( 0, 0x3fff ) | 0x8000,
606
                _random_int( 0, 0xffff ), _random_int( 0, 0xffff ), _random_int( 0, 0xffff )
2 daniel-mar 607
        );
608
}
609
 
610
// Version 5 (SHA1 name based) UUID
611
function gen_uuid_sha1_namebased($namespace_uuid, $name) {
612
        $namespace_uuid = str_replace('-', '', $namespace_uuid);
613
        $namespace_uuid = hex2bin($namespace_uuid);
614
 
615
        $hash = sha1($namespace_uuid.$name);
616
        $hash[12] = '5'; // Set version: 5 = SHA1
617
        $hash[16] = dechex(hexdec($hash[16]) & 0x3 | 0x8); // Set variant to "10xx" (RFC4122)
618
 
619
        return substr($hash,  0, 8).'-'.
620
               substr($hash,  8, 4).'-'.
621
               substr($hash, 12, 4).'-'.
622
               substr($hash, 16, 4).'-'.
623
               substr($hash, 20, 12);
624
}
625
 
626
function uuid_numeric_value($uuid) {
627
        $oid = uuid_to_oid($uuid);
628
        if (!$oid) return false;
629
        return substr($oid, strlen('2.25.'));
630
}
631
 
632
function uuid_c_syntax($uuid) {
633
        $uuid = str_replace('{', '', $uuid);
634
        return '{ 0x' . substr($uuid, 0, 8) .
635
                ', 0x' . substr($uuid, 9, 4) .
636
                ', 0x' . substr($uuid, 14, 4) .
637
                ', { 0x' . substr($uuid, 19, 2).
638
                ', 0x' . substr($uuid, 21, 2) .
639
                ', 0x' . substr($uuid, 24, 2) .
640
                ', 0x' . substr($uuid, 26, 2) .
641
                ', 0x' . substr($uuid, 28, 2) .
642
                ', 0x' . substr($uuid, 30, 2) .
643
                ', 0x' . substr($uuid, 32, 2) .
644
                ', 0x' . substr($uuid, 34, 2) . ' } }';
645
}
646
 
647
# ---
648
 
649
// http://php.net/manual/de/function.hex2bin.php#113057
650
if ( !function_exists( 'hex2bin' ) ) {
651
    function hex2bin( $str ) {
652
        $sbin = "";
653
        $len = strlen( $str );
654
        for ( $i = 0; $i < $len; $i += 2 ) {
655
            $sbin .= pack( "H*", substr( $str, $i, 2 ) );
656
        }
657
 
658
        return $sbin;
659
    }
660
}