Subversion Repositories uuid_mac_utils

Compare Revisions

Regard whitespace Rev 3 → Rev 4

/trunk/includes/OidDerConverter.class.phps
File deleted
/trunk/includes/uuid_utils.inc.phps
File deleted
/trunk/includes/mac_utils.inc.phps
File deleted
/trunk/includes/OidDerConverter.class.php
0,0 → 1,380
<?php
 
/*
* OidDerConverter.class.php, Version 1.1; Based on version 1.11 of oid.c
* Copyright 2014-2015 Daniel Marschall, ViaThinkSoft
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
 
 
// Note: Leading zeros are permitted in dotted notation.
 
// TODO: define output format as parameter; don't force the user to use hexStrToArray
 
class OidDerConverter {
 
/**
* @arg $str "\x12\x23" or "12 34"
* @return array(0x12, 0x23)
*/
// Doesn't need to be public, but it is a nice handy function, especially in the testcases
public static function hexStrToArray($str) {
$out = array();
 
$str = str_replace('\x', ' ', $str);
$str = trim($str);
$ary = explode(' ', $str);
 
foreach ($ary as &$a) {
$out[] = hexdec($a);
}
 
return $out;
}
 
/**
* @return Outputs .<oid> for an absolute OID and <oid> for a relative OID.
*/
public static function derToOID($abBinary, $verbose=false) {
$output_oid = array();
$output_absolute = true;
 
if (count($abBinary) < 3) {
if ($verbose) fprintf(STDERR, "Encoded OID must have at least three bytes!\n");
return false;
}
 
$nBinary = count($abBinary);
$ll = gmp_init(0);
$fOK = false;
$fSub = 0; // Subtract value from next number output. Used when encoding {2 48} and up
 
// 0 = Universal Class Identifier Tag (can be more than 1 byte, but not in our case)
// 1 = Length part (may have more than 1 byte!)
// 2 = First two arc encoding
// 3 = Encoding of arc three and higher
$part = 0;
 
$lengthbyte_count = 0;
$lengthbyte_pos = 0;
$lengthfinished = false;
 
$arcBeginning = true;
 
foreach ($abBinary as $nn => &$pb) {
if ($part == 0) { // Class Tag
// Leading octet
// Bit 7 / Bit 6 = Universal (00), Application (01), Context (10), Private(11)
// Bit 5 = Primitive (0), Constructed (1)
// Bit 4..0 = 00000 .. 11110 => Tag 0..30, 11111 for Tag > 30 (following bytes with the highest bit as "more" bit)
// --> We don't need to respect 11111 (class-tag encodes in more than 1 octet)
// as we terminate when the tag is not of type OID or RELATEIVE-OID
// See page 396 of "ASN.1 - Communication between Heterogeneous Systems" by Olivier Dubuisson.
 
// Class: 8. - 7. bit
// 0 (00) = Universal
// 1 (01) = Application
// 2 (10) = Context
// 3 (11) = Private
$cl = (($pb & 0xC0) >> 6) & 0x03;
if ($cl != 0) {
if ($verbose) fprintf(STDERR, "Error at type: The OID tags are only defined as UNIVERSAL class tags.\n");
return false;
}
 
// Primitive/Constructed: 6. bit
// 0 = Primitive
// 1 = Constructed
$pc = $pb & 0x20;
if ($pc != 0) {
if ($verbose) fprintf(STDERR, "Error at type: OIDs must be primitive, not constructed.\n");
return false;
}
 
// Tag number: 5. - 1. bit
$tag = $pb & 0x1F;
if ($tag == 0x0D) {
$isRelative = true;
} else if ($tag == 0x06) {
$isRelative = false;
} else {
if ($verbose) fprintf(STDERR, "Error at type: The tag number is neither an absolute OID (0x06) nor a relative OID (0x0D).\n");
return false;
}
 
// Output
$output_absolute = !$isRelative;
 
$part++;
} else if ($part == 1) { // Length
// Find out the length and save it into $ll
 
// [length] is encoded as follows:
// 0x00 .. 0x7F = The actual length is in this byte, followed by [data].
// 0x80 + n = The length of [data] is spread over the following 'n' bytes. (0 < n < 0x7F)
// 0x80 = "indefinite length" (only constructed form) -- Invalid
// 0xFF = Reserved for further implementations -- Invalid
// See page 396 of "ASN.1 - Communication between Heterogeneous Systems" by Olivier Dubuisson.
 
if ($nn == 1) { // The first length byte
$lengthbyte_pos = 0;
if (($pb & 0x80) != 0) {
// 0x80 + n => The length is spread over the following 'n' bytes
$lengthfinished = false;
$lengthbyte_count = $pb & 0x7F;
if ($lengthbyte_count == 0x00) {
if ($verbose) fprintf(STDERR, "Length value 0x80 is invalid (\"indefinite length\") for primitive types.\n");
return false;
} else if ($lengthbyte_count == 0x7F) {
if ($verbose) fprintf(STDERR, "Length value 0xFF is reserved for further extensions.\n");
return false;
}
$fOK = false;
} else {
// 0x01 .. 0x7F => The actual length
 
if ($pb == 0x00) {
if ($verbose) fprintf(STDERR, "Length value 0x00 is invalid for an OID.\n");
return false;
}
 
$ll = gmp_init($pb);
$lengthfinished = true;
$lengthbyte_count = 0;
$fOK = true;
}
} else {
if ($lengthbyte_count > $lengthbyte_pos) {
$ll = gmp_mul($ll, 0x100);
$ll = gmp_add($ll, $pb);
$lengthbyte_pos++;
}
 
if ($lengthbyte_count == $lengthbyte_pos) {
$lengthfinished = true;
$fOK = true;
}
}
 
if ($lengthfinished) { // The length is now in $ll
if (gmp_cmp($ll, $nBinary - 2 - $lengthbyte_count) != 0) {
if ($verbose) fprintf(STDERR, "Invalid length (%d entered, but %s expected)\n", $nBinary - 2, gmp_strval($ll, 10));
return false;
}
$ll = gmp_init(0); // reset for later usage
$fOK = true;
$part++;
if ($isRelative) $part++; // Goto step 3!
}
} else if ($part == 2) { // First two arcs
$first = $pb / 40;
$second = $pb % 40;
if ($first > 2) {
$first = 2;
$output_oid[] = $first;
$arcBeginning = true;
 
if (($pb & 0x80) != 0) {
// 2.48 and up => 2+ octets
// Output in "part 3"
 
if ($arcBeginning && ($pb == 0x80)) {
if ($verbose) fprintf(STDERR, "Encoding error. Illegal 0x80 paddings. (See Rec. ITU-T X.690, clause 8.19.2)\n");
return false;
} else {
$arcBeginning = false;
}
 
$ll = gmp_add($ll, ($pb & 0x7F));
$fSub = 80;
$fOK = false;
} else {
// 2.0 till 2.47 => 1 octet
$second = $pb - 80;
$output_oid[] = $second;
$arcBeginning = true;
$fOK = true;
$ll = gmp_init(0);
}
} else {
// 0.0 till 0.37 => 1 octet
// 1.0 till 1.37 => 1 octet
$output_oid[] = $first;
$output_oid[] = $second;
$arcBeginning = true;
$fOK = true;
$ll = gmp_init(0);
}
$part++;
} else if ($part == 3) { // Arc three and higher
if (($pb & 0x80) != 0) {
if ($arcBeginning && ($pb == 0x80)) {
if ($verbose) fprintf(STDERR, "Encoding error. Illegal 0x80 paddings. (See Rec. ITU-T X.690, clause 8.19.2)\n");
return false;
} else {
$arcBeginning = false;
}
 
$ll = gmp_mul($ll, 0x80);
$ll = gmp_add($ll, ($pb & 0x7F));
$fOK = false;
} else {
$fOK = true;
$ll = gmp_mul($ll, 0x80);
$ll = gmp_add($ll, $pb);
$ll = gmp_sub($ll, $fSub);
$output_oid[] = gmp_strval($ll, 10);
 
// Happens only if 0x80 paddings are allowed
// $fOK = gmp_cmp($ll, 0) >= 0;
$ll = gmp_init(0);
$fSub = 0;
$arcBeginning = true;
}
}
}
 
if (!$fOK) {
if ($verbose) fprintf(STDERR, "Encoding error. The OID is not constructed properly.\n");
return false;
}
 
return ($output_absolute ? '.' : '').implode('.', $output_oid);
}
 
// Doesn't need to be public, but it is a nice handy function, especially in the testcases
public static function hexarrayToStr($ary, $nCHex=false) {
$str = '';
if ($ary === false) return false;
foreach ($ary as &$a) {
if ($nCHex) {
$str .= sprintf("\"\\x%02X", $a);
} else {
$str .= sprintf("%02X ", $a);
}
}
return trim($str);
}
 
public static function oidToDER($oid, $isRelative=false, $verbose=false) {
if ($oid[0] == '.') { // MIB notation
$oid = substr($oid, 1);
$isRelative = false;
}
 
$cl = 0x00; // Class. Always UNIVERSAL (00)
 
// Tag for Universal Class
if ($isRelative) {
$cl |= 0x0D;
} else {
$cl |= 0x06;
}
 
$arcs = explode('.', $oid);
 
$b = 0;
$isjoint = false;
$abBinary = array();
 
if ((!$isRelative) && (count($arcs) < 2)) {
if ($verbose) fprintf(STDERR, "Encoding error. The minimum depth of an encodeable absolute OID is 2. (e.g. 2.999)\n");
return false;
}
 
foreach ($arcs as $n => &$arc) {
if (!preg_match('@^\d+$@', $arc)) {
if ($verbose) fprintf(STDERR, "Encoding error. Arc '%s' is invalid.\n", $arc);
return false;
}
 
$l = gmp_init($arc, 10);
 
if ((!$isRelative) && ($n == 0)) {
if (gmp_cmp($l, 2) > 0) {
if ($verbose) fprintf(STDERR, "Encoding error. The top arc is limited to 0, 1 and 2.\n");
return false;
}
$b += 40 * gmp_intval($l);
$isjoint = gmp_cmp($l, 2) == 0;
} else if ((!$isRelative) && ($n == 1)) {
if ((!$isjoint) && (gmp_cmp($l, 39) > 0)) {
if ($verbose) fprintf(STDERR, "Encoding error. The second arc is limited to 0..39 for root arcs 0 and 1.\n");
return false;
}
 
if (gmp_cmp($l, 47) > 0) {
$l = gmp_add($l, 80);
self::makeBase128($l, 1, $abBinary);
} else {
$b += gmp_intval($l);
$abBinary[] = $b;
}
} else {
self::makeBase128($l, 1, $abBinary);
}
}
 
$output = array();
 
// Write class-tag
$output[] = $cl;
 
// Write length
$nBinary = count($abBinary);
if ($nBinary <= 0x7F) {
$output[] = $nBinary;
} else {
$lengthCount = 0;
$nBinaryWork = $nBinary;
do {
$lengthCount++;
$nBinaryWork /= 0x100;
} while ($nBinaryWork > 0);
 
if ($lengthCount >= 0x7F) {
if ($verbose) fprintf(STDERR, "The length cannot be encoded.\n");
return false;
}
 
$output[] = 0x80 + $lengthCount;
 
$nBinaryWork = $nBinary;
do {
$output[] = nBinaryWork & 0xFF;
$nBinaryWork /= 0x100;
} while ($nBinaryWork > 0);
}
 
foreach ($abBinary as $b) {
$output[] = $b;
}
 
return $output;
}
 
protected static function makeBase128($l, $first, &$abBinary) {
if (gmp_cmp($l, 127) > 0) {
$l2 = gmp_div($l, 128);
self::makeBase128($l2 , 0, $abBinary);
}
$l = gmp_mod($l, 128);
 
if ($first) {
$abBinary[] = gmp_intval($l);
} else {
$abBinary[] = 0x80 | gmp_intval($l);
}
}
}
/trunk/includes/mac_utils.inc.php
0,0 → 1,130
<?php
 
/*
* MAC utils for PHP
* Copyright 2017 Daniel Marschall, ViaThinkSoft
* Version 19 August 2017
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
 
define('IEEE_MAC_REGISTRY', __DIR__ . '/../web-data');
 
function mac_valid($mac) {
$mac = str_replace(array('-', ':'), '', $mac);
$mac = strtoupper($mac);
 
if (strlen($mac) != 12) return false;
 
$mac = preg_replace('@[0-9A-F]@', '', $mac);
 
return ($mac == '');
}
 
function _lookup_ieee_registry($file, $oui_name, $mac) {
$begin = substr($mac, 0, 2).'-'.substr($mac, 2, 2).'-'.substr($mac, 4, 2);
$f = file_get_contents($file);
 
$f = str_replace("\r", '', $f);
 
# We are using a positive-lookahead because entries like the MA-M references have a blank line between organization and address
preg_match_all('@^\s*'.preg_quote($begin, '@').'\s+\(hex\)\s+(\S+)\s+(.*)\n\n\s*(?=[0-9A-F])@ismU', "$f\n\nA", $m, PREG_SET_ORDER);
foreach ($m as $n) {
preg_match('@(\S+)\s+\(base 16\)(.*)$@ism', $n[2], $m);
 
if (preg_match('@(.+)\-(.+)@ism', $m[1], $o)) {
$z = hexdec(substr($mac, 6, 6));
$beg = hexdec($o[1]);
$end = hexdec($o[2]);
if (($z < $beg) || ($z > $end)) continue;
} else {
$beg = 0x000000;
$end = 0xFFFFFF;
}
 
$x = trim(preg_replace('@^\s+@ism', '', $m[2]));
 
# "PRIVATE" entries are only marked at the "(hex)" line, but not at the "(base16)" line
if ($x == '') $x = trim($n[1]);
 
$x = explode("\n", $x);
 
$ra_len = strlen(dechex($end-$beg));
 
$out = '';
$out .= sprintf("%-24s 0x%s\n", "IEEE $oui_name part:", substr($mac, 0, 12-$ra_len));
$out .= sprintf("%-24s 0x%s\n", "NIC specific part:", substr($mac, 12-$ra_len));
$out .= sprintf("%-24s %s\n", "Registrant:", $x[0]);
foreach ($x as $n => $y) {
if ($n == 0) continue;
else if ($n == 1) $out .= sprintf("%-24s %s\n", "Address of registrant:", $y);
else if ($n >= 2) $out .= sprintf("%-24s %s\n", "", $y);
}
 
// TODO: also print the date of last update of the OUI files
 
return $out;
}
 
return false;
}
 
function decode_mac($mac) {
if (!mac_valid($mac)) return false;
 
// Format MAC
$mac = strtoupper($mac);
$mac = preg_replace('@[^0-9A-F]@', '', $mac);
if (strlen($mac) != 12) {
# echo "Invalid MAC address\n";
return false;
}
$mac_ = preg_replace('@^(..)(..)(..)(..)(..)(..)$@', '\\1-\\2-\\3-\\4-\\5-\\6', $mac);
echo sprintf("%-24s %s\n", "MAC address:", $mac_);
 
// Empfaengergruppe
$ig = hexdec($mac[1]) & 1; // Bit #LSB+0 of Byte 1
$ig_ = ($ig == 0) ? '[0] Individual' : '[1] Group';
echo sprintf("%-24s %s\n", "I/G flag:", $ig_);
 
// Vergabestelle
$ul = hexdec($mac[1]) & 2; // Bit #LSB+1 of Byte 1
$ul_ = ($ul == 0) ? '[0] Universally Administered Address (UAA)' : '[1] Locally Administered Address (LAA)';
echo sprintf("%-24s %s\n", "U/L flag:", $ul_);
 
// Query IEEE registries
// TODO: gilt OUI nur bei Individual UAA?
if (
($x = _lookup_ieee_registry(IEEE_MAC_REGISTRY.'/mam.txt', 'OUI-28 (MA-M)', $mac)) ||
($x = _lookup_ieee_registry(IEEE_MAC_REGISTRY.'/oui36.txt', 'OUI-36 (MA-S)', $mac)) ||
# The IEEE Registration Authority distinguishes between IABs and OUI-36 values. Both are 36-bit values which may be used to generate EUI-48 values, but IABs may not be used to generate EUI-64 values.[6]
# Note: The Individual Address Block (IAB) is an inactive registry activity, which has been replaced by the MA-S registry product as of January 1, 2014.
($x = _lookup_ieee_registry(IEEE_MAC_REGISTRY.'/iab.txt', 'IAB', $mac))
) {
return $x;
} else {
return _lookup_ieee_registry(IEEE_MAC_REGISTRY.'/oui.txt', 'OUI-24 (MA-L)', $mac);
}
 
// TODO
// FF-FF-FF-FF-FF-FF = Broadcast-Adresse
 
// TODO
// IP-Multicast
// 01-00-5E-00-00-00 bis 01-00-5E-7F-FF-FF (unterste 23 bit der MAC = unterste 23 Bit der IP) ...
// 224.0.0.1 -> 01-00-5e-00-00-01
// erste 4 Bits durch Class D konvention belegt. 5 bits sind unbekannt
 
// TODO: VRRP
// 00-00-5E-00-01-ID
}
/trunk/includes/uuid_utils.inc.php
0,0 → 1,650
<?php
 
/*
* UUID utils for PHP
* Copyright 2011 - 2021 Daniel Marschall, ViaThinkSoft
* Version 2021-05-21
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
 
# This library requires either the GMP extension (or BCMath if gmp_supplement.inc.php is present)
 
if (file_exists(__DIR__ . '/mac_utils.inc.phps')) include_once __DIR__ . '/mac_utils.inc.phps'; // optionally used for uuid_info()
if (file_exists(__DIR__ . '/gmp_supplement.inc.php')) include_once __DIR__ . '/gmp_supplement.inc.php';
 
define('UUID_NAMEBASED_NS_DNS', '6ba7b810-9dad-11d1-80b4-00c04fd430c8');
define('UUID_NAMEBASED_NS_URL', '6ba7b811-9dad-11d1-80b4-00c04fd430c8');
define('UUID_NAMEBASED_NS_OID', '6ba7b812-9dad-11d1-80b4-00c04fd430c8');
define('UUID_NAMEBASED_NS_X500_DN', '6ba7b814-9dad-11d1-80b4-00c04fd430c8');
 
function uuid_valid($uuid) {
$uuid = str_replace(array('-', '{', '}'), '', $uuid);
$uuid = strtoupper($uuid);
#$uuid = trim($uuid);
 
if (strlen($uuid) != 32) return false;
 
$uuid = preg_replace('@[0-9A-F]@', '', $uuid);
 
return ($uuid == '');
}
 
# TODO: Don't echo
function uuid_info($uuid) {
if (!uuid_valid($uuid)) return false;
 
#$uuid = trim($uuid);
# $uuid = str_replace(array('-', '{', '}'), '', $uuid);
$uuid = strtoupper($uuid);
$uuid = preg_replace('@[^0-9A-F]@', '', $uuid);
 
$x = hexdec(substr($uuid, 16, 1));
if ($x >= 14 /* 1110 */) $variant = 3;
else if ($x >= 12 /* 1100 */) $variant = 2;
else if ($x >= 8 /* 1000 */) $variant = 1;
else if ($x >= 0 /* 0000 */) $variant = 0;
else $variant = -1; // should not happen
 
switch ($variant) {
case 0:
echo sprintf("%-24s %s\n", "Variant:", "[0xx] NCS (reserved for backward compatibility)");
 
/*
* Internal structure of variant #0 UUIDs
*
* The first 6 octets are the number of 4 usec units of time that have
* passed since 1/1/80 0000 GMT. The next 2 octets are reserved for
* future use. The next octet is an address family. The next 7 octets
* are a host ID in the form allowed by the specified address family.
*
* Note that while the family field (octet 8) was originally conceived
* of as being able to hold values in the range [0..255], only [0..13]
* were ever used. Thus, the 2 MSB of this field are always 0 and are
* used to distinguish old and current UUID forms.
*
* +--------------------------------------------------------------+
* | high 32 bits of time | 0-3 .time_high
* +-------------------------------+-------------------------------
* | low 16 bits of time | 4-5 .time_low
* +-------+-----------------------+
* | reserved | 6-7 .reserved
* +---------------+---------------+
* | family | 8 .family
* +---------------+----------...-----+
* | node ID | 9-16 .node
* +--------------------------...-----+
*
*/
 
// Example of an UUID: 333a2276-0000-0000-0d00-00809c000000
 
# TODO: See https://github.com/cjsv/uuid/blob/master/Doc
 
# Timestamp: Count of 4us intervals since 01 Jan 1980 00:00:00 GMT
# 1/0,000004 = 250000
# Seconds between 1970 and 1980 : 315532800
# 250000*315532800=78883200000000
$timestamp = substr($uuid, 0, 12);
$ts = gmp_init($timestamp, 16);
$ts = gmp_add($ts, gmp_init("78883200000000"));
$ms = gmp_mod($ts, gmp_init("250000"));
$ts = gmp_div($ts, gmp_init("250000"));
$ts = gmp_strval($ts);
$ms = gmp_strval($ms);
$ts = gmdate('Y-m-d H:i:s', intval($ts))."'".str_pad($ms, 7, '0', STR_PAD_LEFT).' GMT';
echo sprintf("%-24s %s\n", "Timestamp:", "[0x$timestamp] $ts");
 
$reserved = substr($uuid, 12, 4);
echo sprintf("%-24s %s\n", "Reserved:", "0x$reserved");
 
# Family 13 (dds) looks like node is 00 | nnnnnn 000000.
# Family 2 is presumably (ip).
# Not sure if anything else was used.
$family_hex = substr($uuid, 16, 2);
$family_dec = hexdec($family_hex);
if ($family_dec == 2) {
$family_ = 'IP';
} else if ($family_dec == 13) {
$family_ = 'DDS (Data Link)';
} else {
$family_ = "Unknown ($family_dec)"; # There are probably no more families
}
echo sprintf("%-24s %s\n", "Family:", "[0x$family_hex = $family_dec] $family_");
 
$nodeid = substr($uuid, 18, 14);
echo sprintf("%-24s %s\n", "Node ID:", "0x$nodeid");
# TODO: interprete node id (the family specifies it)
 
break;
case 1:
echo sprintf("%-24s %s\n", "Variant:", "[10x] RFC 4122 (Leach-Mealling-Salz)");
 
$version = hexdec(substr($uuid, 12, 1));
switch ($version) {
case 1:
echo sprintf("%-24s %s\n", "Version:", "[1] Time-based with unique random host identifier");
 
# Timestamp: Count of 100ns intervals since 15 Oct 1582 00:00:00
# 1/0,0000001 = 10000000
$timestamp = substr($uuid, 13, 3).substr($uuid, 8, 4).substr($uuid, 0, 8);
$ts = gmp_init($timestamp, 16);
$ts = gmp_sub($ts, gmp_init("122192928000000000"));
$ms = gmp_mod($ts, gmp_init("10000000"));
$ts = gmp_div($ts, gmp_init("10000000"));
$ts = gmp_strval($ts);
$ms = gmp_strval($ms);
$ts = gmdate('Y-m-d H:i:s', intval($ts))."'".str_pad($ms, 7, '0', STR_PAD_LEFT).' GMT';
echo sprintf("%-24s %s\n", "Timestamp:", "[0x$timestamp] $ts");
 
$x = hexdec(substr($uuid, 16, 4));
$dec = $x & 0x3FFF; // The highest 2 bits are used by "variant" (10x)
$hex = substr($uuid, 16, 4);
echo sprintf("%-24s %s\n", "Clock ID:", "[0x$hex] $dec");
 
$x = substr($uuid, 20, 12);
$nodeid = '';
for ($i=0; $i<6; $i++) {
$nodeid .= substr($x, $i*2, 2);
if ($i != 5) $nodeid .= ':';
}
echo sprintf("%-24s %s\n", "Node ID:", "$nodeid");
 
if (function_exists('decode_mac')) {
echo "\nIn case that this Node ID is a MAC address, here is the interpretation of that MAC address:\n";
echo decode_mac($nodeid); /** @phpstan-ignore-line */
}
 
break;
case 2:
echo sprintf("%-24s %s\n", "Version:", "[2] DCE Security version");
 
# 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.
$x = substr($uuid, 0, 8);
echo sprintf("%-24s %s\n", "Local ID:", "0x$x");
 
# 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".
$x = substr($uuid, 18, 2);
if ($x == '00') $domain_info = 'POSIX: User-ID / Non-POSIX: site-defined';
else if ($x == '01') $domain_info = 'POSIX: Group-ID / Non-POSIX: site-defined';
else $domain_info = 'site-defined';
echo sprintf("%-24s %s\n", "Local Domain:", "0x$x ($domain_info)");
 
# Timestamp: Count of 100ns intervals since 15 Oct 1582 00:00:00
# 1/0,0000001 = 10000000
$timestamp = substr($uuid, 13, 3).substr($uuid, 8, 4).'00000000';
$ts = gmp_init($timestamp, 16);
$ts = gmp_sub($ts, gmp_init("122192928000000000"));
$ms = gmp_mod($ts, gmp_init("10000000"));
$ts = gmp_div($ts, gmp_init("10000000"));
$ts = gmp_strval($ts);
$ms = gmp_strval($ms);
$ts_min = gmdate('Y-m-d H:i:s', intval($ts))."'".str_pad($ms, 7, '0', STR_PAD_LEFT).' GMT';
 
$timestamp = substr($uuid, 13, 3).substr($uuid, 8, 4).'FFFFFFFF';
$ts = gmp_init($timestamp, 16);
$ts = gmp_sub($ts, gmp_init("122192928000000000"));
$ms = gmp_mod($ts, gmp_init("10000000"));
$ts = gmp_div($ts, gmp_init("10000000"));
$ts = gmp_strval($ts);
$ms = gmp_strval($ms);
$ts_max = gmdate('Y-m-d H:i:s', intval($ts))."'".str_pad($ms, 7, '0', STR_PAD_LEFT).' GMT';
 
$timestamp = substr($uuid, 13, 3).substr($uuid, 8, 4).'xxxxxxxx';
echo sprintf("%-24s %s\n", "Timestamp:", "[0x$timestamp] $ts_min - $ts_max");
 
$x = hexdec(substr($uuid, 16, 2).'00');
$dec_min = $x & 0x3FFF; // The highest 2 bits are used by "variant" (10x)
$x = hexdec(substr($uuid, 16, 2).'FF');
$dec_max = $x & 0x3FFF; // The highest 2 bits are used by "variant" (10x)
$hex = substr($uuid, 16, 2).'xx';
echo sprintf("%-24s %s\n", "Clock ID:", "[0x$hex] $dec_min - $dec_max");
 
$x = substr($uuid, 20, 12);
$nodeid = '';
for ($i=0; $i<6; $i++) {
$nodeid .= substr($x, $i*2, 2);
if ($i != 5) $nodeid .= ':';
}
echo sprintf("%-24s %s\n", "Node ID:", "$nodeid");
 
if (function_exists('decode_mac')) {
echo "\nIn case that this Node ID is a MAC address, here is the interpretation of that MAC address:\n";
echo decode_mac($nodeid); /** @phpstan-ignore-line */
}
 
break;
case 3:
echo sprintf("%-24s %s\n", "Version:", "[3] Name-based (MD5 hash)");
 
$hash = str_replace('-', '', strtolower($uuid));
$hash[12] = '?'; // was overwritten by version
$hash[16] = '?'; // was partially overwritten by variant
 
echo sprintf("%-24s %s\n", "MD5(Namespace+Subject):", "$hash");
 
break;
case 4:
echo sprintf("%-24s %s\n", "Version:", "[4] Random");
 
$rand = '';
for ($i=0; $i<16; $i++) {
$bin = base_convert(substr($uuid, $i*2, 2), 16, 2);
$bin = str_pad($bin, 8, "0", STR_PAD_LEFT);
 
if ($i == 6) {
$bin[0] = 'x';
$bin[1] = 'x';
} else if ($i == 8) {
$bin[0] = 'x';
$bin[1] = 'x';
$bin[2] = 'x';
$bin[3] = 'x';
}
 
$rand .= "$bin ";
}
 
echo sprintf("%-24s %s\n", "Random bits:", trim($rand));
 
break;
case 5:
echo sprintf("%-24s %s\n", "Version:", "[5] Name-based (SHA-1 hash)");
 
$hash = str_replace('-', '', strtolower($uuid));
$hash[12] = '?'; // was overwritten by version
$hash[16] = '?'; // was partially overwritten by variant
$hash .= '????????'; // was cut off
 
echo sprintf("%-24s %s\n", "SHA1(Namespace+Subject):", "$hash");
 
 
break;
default:
echo sprintf("%-24s %s\n", "Version:", "[$version] Unknown");
break;
}
 
break;
case 2:
echo sprintf("%-24s %s\n", "Variant:", "[110] Reserved for Microsoft Corporation");
break;
case 3:
echo sprintf("%-24s %s\n", "Variant:", "[111] Reserved for future use");
break;
}
}
 
function uuid_canonize($uuid) {
if (!uuid_valid($uuid)) return false;
return oid_to_uuid(uuid_to_oid($uuid));
}
 
function oid_to_uuid($oid) {
if (!is_uuid_oid($oid)) return false;
 
if ($oid[0] == '.') {
$oid = substr($oid, 1);
}
$ary = explode('.', $oid);
 
if (!isset($ary[2])) return false;
 
$val = $ary[2];
 
$x = gmp_init($val, 10);
$y = gmp_strval($x, 16);
$y = str_pad($y, 32, "0", STR_PAD_LEFT);
return substr($y, 0, 8).'-'.
substr($y, 8, 4).'-'.
substr($y, 12, 4).'-'.
substr($y, 16, 4).'-'.
substr($y, 20, 12);
}
 
function is_uuid_oid($oid, $only_allow_root=false) {
if ($oid[0] == '.') $oid = substr($oid, 1); // remove leading dot
 
$ary = explode('.', $oid);
 
if ($only_allow_root) {
if (count($ary) != 3) return false;
} else {
if (count($ary) < 3) return false;
}
 
if ($ary[0] != '2') return false;
if ($ary[1] != '25') return false;
for ($i=2; $i<count($ary); $i++) {
$v = $ary[$i];
if (!is_numeric($v)) return false;
if ($i == 2) {
// Must be in the range of 128 bit UUID
$test = gmp_init($v, 10);
if (strlen(gmp_strval($test, 16)) > 32) return false;
}
if ($v < 0) return false;
}
 
return true;
}
 
function uuid_to_oid($uuid) {
if (!uuid_valid($uuid)) return false;
 
$uuid = str_replace(array('-', '{', '}'), '', $uuid);
$x = gmp_init($uuid, 16);
return '2.25.'.gmp_strval($x, 10); # TODO: parameter with or without leading dot
}
 
function gen_uuid($prefer_timebased = true) {
$uuid = $prefer_timebased ? gen_uuid_timebased() : false;
if ($uuid === false) $uuid = gen_uuid_random();
return $uuid;
}
 
// Version 1 (Time based) UUID
function gen_uuid_timebased() {
# On Debian: apt-get install php-uuid
# extension_loaded('uuid')
if (function_exists('uuid_create')) {
# OSSP uuid extension like seen in php5-uuid at Debian 8
/*
$x = uuid_create($context);
uuid_make($context, UUID_MAKE_V1);
uuid_export($context, UUID_FMT_STR, $uuid);
return trim($uuid);
*/
 
# PECL uuid extension like seen in php-uuid at Debian 9
return trim(uuid_create(UUID_TYPE_TIME));
}
 
# On Debian: apt-get install uuid-runtime
if (strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN') {
$out = array();
$ec = -1;
exec('uuidgen -t 2>/dev/null', $out, $ec);
if ($ec == 0) return trim($out[0]);
}
 
# If we hadn't any success yet, then implement the time based generation routine ourselves!
# Based on https://github.com/fredriklindberg/class.uuid.php/blob/master/class.uuid.php
 
$uuid = array(
'time_low' => 0, /* 32-bit */
'time_mid' => 0, /* 16-bit */
'time_hi' => 0, /* 16-bit */
'clock_seq_hi' => 0, /* 8-bit */
'clock_seq_low' => 0, /* 8-bit */
'node' => array() /* 48-bit */
);
 
/*
* Get current time in 100 ns intervals. The magic value
* is the offset between UNIX epoch and the UUID UTC
* time base October 15, 1582.
*/
$tp = gettimeofday();
$time = ($tp['sec'] * 10000000) + ($tp['usec'] * 10) + 0x01B21DD213814000;
 
$uuid['time_low'] = $time & 0xffffffff;
/* Work around PHP 32-bit bit-operation limits */
$high = intval($time / 0xffffffff);
$uuid['time_mid'] = $high & 0xffff;
$uuid['time_hi'] = (($high >> 16) & 0xfff) | (1/*TimeBased*/ << 12);
 
/*
* We don't support saved state information and generate
* a random clock sequence each time.
*/
$uuid['clock_seq_hi'] = 0x80 | mt_rand(0, 64);
$uuid['clock_seq_low'] = mt_rand(0, 255);
 
/*
* Node should be set to the 48-bit IEEE node identifier
*/
$mac = get_mac_address();
if ($mac) {
$node = str_replace(':','',$mac);
for ($i = 0; $i < 6; $i++) {
$uuid['node'][$i] = hexdec(substr($node, $i*2, 2));
}
 
/*
* Now output the UUID
*/
return sprintf(
'%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x',
($uuid['time_low']), ($uuid['time_mid']), ($uuid['time_hi']),
$uuid['clock_seq_hi'], $uuid['clock_seq_low'],
$uuid['node'][0], $uuid['node'][1], $uuid['node'][2],
$uuid['node'][3], $uuid['node'][4], $uuid['node'][5]);
}
 
# We cannot generate the timebased UUID!
return false;
}
 
function get_mac_address() {
static $detected_mac = false;
 
if ($detected_mac !== false) { // false NOT null!
return $detected_mac;
}
 
// TODO: This should actually be part of mac_utils.inc.php, but we need it
// here, and mac_utils.inc.php shall only be optional. What to do?
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
// Windows
$cmds = array(
"ipconfig /all", // faster
"getmac"
);
foreach ($cmds as $cmd) {
$out = array();
$ec = -1;
exec($cmd, $out, $ec);
if ($ec == 0) {
$out = implode("\n",$out);
$m = array();
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)) {
$detected_mac = str_replace('-', ':', strtolower($m[1]));
return $detected_mac;
}
}
}
} else if (strtoupper(PHP_OS) == 'DARWIN') {
// Mac OS X
$cmds = array(
"networksetup -listallhardwareports 2>/dev/null",
"netstat -i 2>/dev/null"
);
foreach ($cmds as $cmd) {
$out = array();
$ec = -1;
exec($cmd, $out, $ec);
if ($ec == 0) {
$out = implode("\n",$out);
$m = array();
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)) {
$detected_mac = $m[1];
return $detected_mac;
}
}
}
} else {
// Linux
foreach (glob('/sys/class/net/'.'*'.'/address') as $x) {
if (!strstr($x,'/lo/')) {
$detected_mac = trim(file_get_contents($x));
return $detected_mac;
}
}
$cmds = array(
"netstat -ie 2>/dev/null",
"ifconfig 2>/dev/null" // only available for root (because it is in sbin)
);
foreach ($cmds as $cmd) {
$out = array();
$ec = -1;
exec($cmd, $out, $ec);
if ($ec == 0) {
$out = implode("\n",$out);
$m = array();
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)) {
$detected_mac = $m[1];
return $detected_mac;
}
}
}
}
 
$detected_mac = null;
return $detected_mac;
}
 
// Version 2 (DCE Security) UUID
function gen_uuid_dce($domain, $id) {
# Start with a version 1 UUID
$uuid = gen_uuid_timebased();
 
# Add ID
$uuid = str_pad(dechex($id), 8, '0', STR_PAD_LEFT) . substr($uuid, 8);
 
# Add domain
$uuid = substr($uuid,0,21) . str_pad(dechex($domain), 2, '0', STR_PAD_LEFT) . substr($uuid, 23);
 
# Change version to 2
$uuid[14] = '2';
 
return $uuid;
}
 
// Version 3 (MD5 name based) UUID
function gen_uuid_md5_namebased($namespace_uuid, $name) {
if (!uuid_valid($namespace_uuid)) return false;
$namespace_uuid = uuid_canonize($namespace_uuid);
$namespace_uuid = str_replace('-', '', $namespace_uuid);
$namespace_uuid = hex2bin($namespace_uuid);
 
$hash = md5($namespace_uuid.$name);
$hash[12] = '3'; // Set version: 3 = MD5
$hash[16] = dechex(hexdec($hash[16]) & 0x3 | 0x8); // Set variant to "10xx" (RFC4122)
 
return substr($hash, 0, 8).'-'.
substr($hash, 8, 4).'-'.
substr($hash, 12, 4).'-'.
substr($hash, 16, 4).'-'.
substr($hash, 20, 12);
}
 
// Version 4 (Random) UUID
function gen_uuid_random() {
# On Windows: Requires
# extension_dir = "C:\php-8.0.3-nts-Win32-vs16-x64\ext"
# extension=com_dotnet
if (function_exists('com_create_guid')) {
return strtolower(trim(com_create_guid(), '{}'));
}
 
# On Debian: apt-get install php-uuid
# extension_loaded('uuid')
if (function_exists('uuid_create')) {
# OSSP uuid extension like seen in php5-uuid at Debian 8
/*
$x = uuid_create($context);
uuid_make($context, UUID_MAKE_V4);
uuid_export($context, UUID_FMT_STR, $uuid);
return trim($uuid);
*/
 
# PECL uuid extension like seen in php-uuid at Debian 9
return trim(uuid_create(UUID_TYPE_RANDOM));
}
 
if (strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN') {
# On Debian: apt-get install uuid-runtime
$out = array();
$ec = -1;
exec('uuidgen -r 2>/dev/null', $out, $ec);
if ($ec == 0) return trim($out[0]);
 
# On Debian Jessie: UUID V4 (Random)
if (file_exists('/proc/sys/kernel/random/uuid')) {
return trim(file_get_contents('/proc/sys/kernel/random/uuid'));
}
}
 
# Make the UUID by ourselves
# Source: http://rogerstringer.com/2013/11/15/generate-uuids-php
return sprintf( '%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ),
mt_rand( 0, 0xffff ),
mt_rand( 0, 0x0fff ) | 0x4000,
mt_rand( 0, 0x3fff ) | 0x8000,
mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff )
);
}
 
// Version 5 (SHA1 name based) UUID
function gen_uuid_sha1_namebased($namespace_uuid, $name) {
$namespace_uuid = str_replace('-', '', $namespace_uuid);
$namespace_uuid = hex2bin($namespace_uuid);
 
$hash = sha1($namespace_uuid.$name);
$hash[12] = '5'; // Set version: 5 = SHA1
$hash[16] = dechex(hexdec($hash[16]) & 0x3 | 0x8); // Set variant to "10xx" (RFC4122)
 
return substr($hash, 0, 8).'-'.
substr($hash, 8, 4).'-'.
substr($hash, 12, 4).'-'.
substr($hash, 16, 4).'-'.
substr($hash, 20, 12);
}
 
function uuid_numeric_value($uuid) {
$oid = uuid_to_oid($uuid);
if (!$oid) return false;
return substr($oid, strlen('2.25.'));
}
 
function uuid_c_syntax($uuid) {
$uuid = str_replace('{', '', $uuid);
return '{ 0x' . substr($uuid, 0, 8) .
', 0x' . substr($uuid, 9, 4) .
', 0x' . substr($uuid, 14, 4) .
', { 0x' . substr($uuid, 19, 2).
', 0x' . substr($uuid, 21, 2) .
', 0x' . substr($uuid, 24, 2) .
', 0x' . substr($uuid, 26, 2) .
', 0x' . substr($uuid, 28, 2) .
', 0x' . substr($uuid, 30, 2) .
', 0x' . substr($uuid, 32, 2) .
', 0x' . substr($uuid, 34, 2) . ' } }';
}
 
# ---
 
// http://php.net/manual/de/function.hex2bin.php#113057
if ( !function_exists( 'hex2bin' ) ) {
function hex2bin( $str ) {
$sbin = "";
$len = strlen( $str );
for ( $i = 0; $i < $len; $i += 2 ) {
$sbin .= pack( "H*", substr( $str, $i, 2 ) );
}
 
return $sbin;
}
}