2 * Copyright (c) 2005 Apple Computer, Inc. All rights reserved.
4 * @APPLE_LICENSE_HEADER_START@
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. Please obtain a copy of the License at
10 * http://www.opensource.apple.com/apsl/ and read it before using this
13 * The Original Code and all software distributed under the License are
14 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
15 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
16 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
18 * Please see the License for the specific language governing rights and
19 * limitations under the License.
21 * @APPLE_LICENSE_HEADER_END@
24 Copyright 1999-2002, Apple, Inc. All rights reserved.
25 Responsibility: Doug Davidson
28 #include <CoreFoundation/CFBase.h>
29 #include <CoreFoundation/CFDate.h>
30 #include "CFInternal.h"
31 #include "CFUtilitiesPriv.h"
36 unsigned char eaddr
[6]; /* 6 bytes of ethernet hardware address */
39 #if defined(__WIN32__)
41 static OSErr
GetEthernetAddr(uuid_address_t
*addr
) {
49 #include <sys/socket.h>
50 #include <sys/ioctl.h>
51 #include <sys/sockio.h>
53 #include <sys/errno.h>
55 #include <netinet/in.h>
57 #include <net/if_dl.h>
58 #include <net/if_types.h>
61 #define MAX(a, b) ((a) < (b) ? (b) : (a))
64 #define IFR_NEXT(ifr) \
65 ((struct ifreq *) ((char *) (ifr) + sizeof(*(ifr)) + \
66 MAX(0, (int) (ifr)->ifr_addr.sa_len - (int) sizeof((ifr)->ifr_addr))))
68 static OSErr
GetEthernetAddr(uuid_address_t
*addr
) {
70 struct ifreq ifrbuf
[30], *ifr
;
72 Boolean foundIt
= false;
74 if ((s
= socket(AF_INET
, SOCK_DGRAM
, 0)) == -1) {
78 ifc
.ifc_buf
= (caddr_t
)ifrbuf
;
79 ifc
.ifc_len
= sizeof (ifrbuf
);
80 if (ioctl(s
, SIOCGIFCONF
, &ifc
) == -1) {
85 for (ifr
= (struct ifreq
*)ifc
.ifc_buf
, i
=0; (char *)ifr
< &ifc
.ifc_buf
[ifc
.ifc_len
]; ifr
= IFR_NEXT(ifr
), i
++) {
88 if (*ifr
->ifr_name
== '\0') {
92 * Adapt to buggy kernel implementation (> 9 of a type)
95 p
= &ifr
->ifr_name
[strlen(ifr
->ifr_name
)-1];
96 if ((c
= *p
) > '0'+9) {
97 snprintf(p
, 2, "%d", c
-'0'); // at least 3 bytes available here, we hope!
100 if (strcmp(ifr
->ifr_name
, "en0") == 0) {
101 if (ifr
->ifr_addr
.sa_family
== AF_LINK
) {
102 struct sockaddr_dl
*sa
= ((struct sockaddr_dl
*)&ifr
->ifr_addr
);
103 if (sa
->sdl_type
== IFT_ETHER
|| sa
->sdl_type
== IFT_FDDI
|| sa
->sdl_type
== IFT_ISO88023
|| sa
->sdl_type
== IFT_ISO88024
|| sa
->sdl_type
== IFT_ISO88025
) {
104 for (i
=0, p
=&sa
->sdl_data
[sa
->sdl_nlen
] ; i
++ < sa
->sdl_alen
; p
++) {
105 addr
->eaddr
[i
-1] = *p
;
114 return (foundIt
? 0 : -1);
121 __private_extern__ CFStringRef
__CFCopyRegularEthernetAddrString(void) {
123 static CFStringRef string
= NULL
;
124 static Boolean lookedUpAddr
= false;
127 if (GetEthernetAddr(&addr
) == 0) {
128 string
= CFStringCreateWithFormat(kCFAllocatorDefault
, NULL
, CFSTR("%02x:%02x:%02x:%02x:%02x:%02x"), addr
.eaddr
[0], addr
.eaddr
[1], addr
.eaddr
[2], addr
.eaddr
[3], addr
.eaddr
[4], addr
.eaddr
[5]);
132 return (string
? CFRetain(string
) : NULL
);
135 __private_extern__ CFStringRef
__CFCopyEthernetAddrString(void) {
137 static CFStringRef string
= NULL
;
138 static Boolean lookedUpAddr
= false;
141 if (GetEthernetAddr(&addr
) == 0) {
142 string
= CFStringCreateWithFormat(kCFAllocatorDefault
, NULL
, CFSTR("%02x%02x%02x%02x%02x%02x"), addr
.eaddr
[0], addr
.eaddr
[1], addr
.eaddr
[2], addr
.eaddr
[3], addr
.eaddr
[4], addr
.eaddr
[5]);
146 return (string
? CFRetain(string
) : NULL
);
149 #if defined(__WIN32__)
150 /* _CFGenerateUUID function just calls the COM library's UUID generator
151 * (Aleksey Dukhnyakov)
157 LONG
_CFGenerateUUID(uint8_t *uuid_bytes
) {
160 /* call GetScode() function to get RPC_STATUS, because
161 * CoCreateGuid(uuid) function return HRESULT type
163 rStatus
= GetScode(CoCreateGuid((uuid_t
*)uuid_bytes
));
165 /* We accept only following results RPC_S_OK, RPC_S_UUID_LOCAL_ONLY
167 if ( rStatus
== RPC_S_UUID_NO_ADDRESS
)
177 * Modifications made by William Woody to make this thing
178 * work on the Macintosh.
183 * (c) Copyright 1989 OPEN SOFTWARE FOUNDATION, INC.
184 * (c) Copyright 1989 HEWLETT-PACKARD COMPANY
185 * (c) Copyright 1989 DIGITAL EQUIPMENT CORPORATION
186 * To anyone who acknowledges that this file is provided "AS IS"
187 * without any express or implied warranty:
188 * permission to use, copy, modify, and distribute this
189 * file for any purpose is hereby granted without fee, provided that
190 * the above copyright notices and this notice appears in all source
191 * code copies, and that none of the names of Open Software
192 * Foundation, Inc., Hewlett-Packard Company, or Digital Equipment
193 * Corporation be used in advertising or publicity pertaining to
194 * distribution of the software without specific, written prior
195 * permission. Neither Open Software Foundation, Inc., Hewlett-
196 * Packard Company, nor Digital Equipment Corporation makes any
197 * representations about the suitability of this software for any
215 ** UUID - routines that manipulate uuid's
223 * Universal Unique ID. Note this definition will result is a 16-byte
224 * structure regardless what platform it is on.
230 uint16_t time_hi_and_version
;
231 unsigned char clock_seq_hi_and_reserved
;
232 unsigned char clock_seq_low
;
233 unsigned char node
[6];
236 typedef struct uuid_v1_t uuid_v1_t
;
239 kUUIDInternalError
= -21001,
240 kUUIDInvalidString
= -21002
248 static OSErr
GenRandomEthernet(uuid_address_t
*addr
);
249 static OSErr
ReadPrefData(void);
252 * Preferences file management
255 static uuid_address_t GSavedENetAddr
= {{0, 0, 0, 0, 0, 0}};
256 static uuid_time_t GLastTime
= {0, 0}; /* Clock state info */
257 static uint16_t GTimeAdjust
= 0;
258 static uint16_t GClockSeq
= 0;
262 * Internal structure of universal unique IDs (UUIDs).
264 * There are three "variants" of UUIDs that this code knows about. The
265 * variant #0 is what was defined in the 1989 HP/Apollo Network Computing
266 * Architecture (NCA) specification and implemented in NCS 1.x and DECrpc
267 * v1. Variant #1 is what was defined for the joint HP/DEC specification
268 * for the OSF (in DEC's "UID Architecture Functional Specification Version
269 * X1.0.4") and implemented in NCS 2.0, DECrpc v2, and OSF 1.0 DCE RPC.
270 * Variant #2 is defined by Microsoft.
272 * This code creates only variant #1 UUIDs.
274 * The three UUID variants can exist on the same wire because they have
275 * distinct values in the 3 MSB bits of octet 8 (see table below). Do
276 * NOT confuse the version number with these 3 bits. (Note the distinct
277 * use of the terms "version" and "variant".) Variant #0 had no version
278 * field in it. Changes to variant #1 (should any ever need to be made)
279 * can be accomodated using the current form's 4 bit version field.
281 * The UUID record structure MUST NOT contain padding between fields.
282 * The total size = 128 bits.
284 * To minimize confusion about bit assignment within octets, the UUID
285 * record definition is defined only in terms of fields that are integral
288 * Depending on the network data representation, the multi-octet unsigned
289 * integer fields are subject to byte swapping when communicated between
290 * dissimilar endian machines. Note that all three UUID variants have
291 * the same record structure; this allows this byte swapping to occur.
292 * (The ways in which the contents of the fields are generated can and
295 * The following information applies to variant #1 UUIDs:
297 * The lowest addressed octet contains the global/local bit and the
298 * unicast/multicast bit, and is the first octet of the address transmitted
301 * The adjusted time stamp is split into three fields, and the clockSeq
302 * is split into two fields.
304 * |<------------------------- 32 bits -------------------------->|
306 * +--------------------------------------------------------------+
307 * | low 32 bits of time | 0-3 .time_low
308 * +-------------------------------+-------------------------------
309 * | mid 16 bits of time | 4-5 .time_mid
310 * +-------+-----------------------+
311 * | vers. | hi 12 bits of time | 6-7 .time_hi_and_version
312 * +-------+-------+---------------+
313 * |Res| clkSeqHi | 8 .clock_seq_hi_and_reserved
315 * | clkSeqLow | 9 .clock_seq_low
316 * +---------------+----------...-----+
317 * | node ID | 8-16 .node
318 * +--------------------------...-----+
320 * --------------------------------------------------------------------------
322 * The structure layout of all three UUID variants is fixed for all time.
323 * I.e., the layout consists of a 32 bit int, 2 16 bit ints, and 8 8
324 * bit ints. The current form version field does NOT determine/affect
325 * the layout. This enables us to do certain operations safely on the
326 * variants of UUIDs without regard to variant; this increases the utility
327 * of this code even as the version number changes (i.e., this code does
328 * NOT need to check the version field).
330 * The "Res" field in the octet #8 is the so-called "reserved" bit-field
331 * and determines whether or not the uuid is a old, current or other
334 * MS-bit 2MS-bit 3MS-bit Variant
335 * ---------------------------------------------
337 * 1 0 x 1 (DCE 1.0 RPC)
338 * 1 1 0 2 (Microsoft)
341 * --------------------------------------------------------------------------
343 * Internal structure of variant #0 UUIDs
345 * The first 6 octets are the number of 4 usec units of time that have
346 * passed since 1/1/80 0000 GMT. The next 2 octets are reserved for
347 * future use. The next octet is an address family. The next 7 octets
348 * are a host ID in the form allowed by the specified address family.
350 * Note that while the family field (octet 8) was originally conceived
351 * of as being able to hold values in the range [0..255], only [0..13]
352 * were ever used. Thus, the 2 MSB of this field are always 0 and are
353 * used to distinguish old and current UUID forms.
355 * +--------------------------------------------------------------+
356 * | high 32 bits of time | 0-3 .time_high
357 * +-------------------------------+-------------------------------
358 * | low 16 bits of time | 4-5 .time_low
359 * +-------+-----------------------+
360 * | reserved | 6-7 .reserved
361 * +---------------+---------------+
362 * | family | 8 .family
363 * +---------------+----------...-----+
364 * | node ID | 9-16 .node
365 * +--------------------------...-----+
369 /***************************************************************************
373 **************************************************************************/
375 static const long uuid_c_version
= 1;
378 * local defines used in uuid bit-diddling
380 #define HI_WORD(w) ((w) >> 16)
381 #define RAND_MASK 0x3fff /* same as CLOCK_SEQ_LAST */
383 #define TIME_MID_MASK 0x0000ffff
384 #define TIME_HIGH_MASK 0x0fff0000
385 #define TIME_HIGH_SHIFT_COUNT 16
388 * The following was modified in order to prevent overlap because
389 * our clock is (theoretically) accurate to 1us (or 1s in CarbonLib)
393 #define MAX_TIME_ADJUST 9 /* Max adjust before tick */
395 #define CLOCK_SEQ_LOW_MASK 0xff
396 #define CLOCK_SEQ_HIGH_MASK 0x3f00
397 #define CLOCK_SEQ_HIGH_SHIFT_COUNT 8
398 #define CLOCK_SEQ_FIRST 1
399 #define CLOCK_SEQ_LAST 0x3fff /* same as RAND_MASK */
402 * Note: If CLOCK_SEQ_BIT_BANG == true, then we can avoid the modulo
403 * operation. This should save us a divide instruction and speed
407 #ifndef CLOCK_SEQ_BIT_BANG
408 #define CLOCK_SEQ_BIT_BANG 1
411 #if CLOCK_SEQ_BIT_BANG
412 #define CLOCK_SEQ_BUMP(seq) ((*seq) = ((*seq) + 1) & CLOCK_SEQ_LAST)
414 #define CLOCK_SEQ_BUMP(seq) ((*seq) = ((*seq) + 1) % (CLOCK_SEQ_LAST+1))
417 #define UUID_VERSION_BITS (uuid_c_version << 12)
418 #define UUID_RESERVED_BITS 0x80
420 #define IS_OLD_UUID(uuid) (((uuid)->clock_seq_hi_and_reserved & 0xc0) != 0x80)
422 /****************************************************************************
424 * local data declarations
426 ****************************************************************************/
434 * declarations used in UTC time calculations
437 static uuid_time_t time_now
= {0, 0}; /* utc time as of last query */
438 //static uuid_time_t time_last; /* utc time last time I looked */
439 //static uint16_t time_adjust; /* 'adjustment' to ensure uniqness */
440 //static uint16_t clock_seq; /* 'adjustment' for backwards clocks*/
443 * true_random variables
446 static uint32_t rand_m
= 0; /* multiplier */
447 static uint32_t rand_ia
= 0; /* adder #1 */
448 static uint32_t rand_ib
= 0; /* adder #2 */
449 static uint32_t rand_irand
= 0; /* random value */
453 uuid_e_less_than
, uuid_e_equal_to
, uuid_e_greater_than
459 /****************************************************************************
461 * local function declarations
463 ****************************************************************************/
468 * Startup initialization routine for UUID module.
471 static OSErr
init (void);
474 * T R U E _ R A N D O M _ I N I T
477 static void true_random_init (void);
480 * T R U E _ R A N D O M
482 static uint16_t true_random (void);
486 * N E W _ C L O C K _ S E Q
488 * Ensure clock_seq is up-to-date
490 * Note: clock_seq is architected to be 14-bits (unsigned) but
491 * I've put it in here as 16-bits since there isn't a
492 * 14-bit unsigned integer type (yet)
494 static void new_clock_seq ( uint16_t * /*clock_seq*/);
500 * Compares two UUID times (64-bit DEC UID UTC values)
502 static uuid_compval_t
time_cmp (
503 uuid_time_t
* /*time1*/,
504 uuid_time_t
* /*time2*/
508 /************************************************************************/
512 /************************************************************************/
515 * saved copy of our IEEE 802 address for quick reference
518 static uuid_address_t saved_addr
= {{0, 0, 0, 0, 0, 0}};
519 static int got_address
= false;
520 static int last_addr_result
= false;
522 static OSErr
GenRandomEthernet(uuid_address_t
*addr
) {
524 for (i
= 0; i
< 6; i
++) {
525 addr
->eaddr
[i
] = (unsigned char)(true_random() & 0xff);
533 ** ROUTINE NAME: uuid_get_address
539 ** Return our IEEE 802 address.
541 ** This function is not really "public", but more like the SPI functions
542 ** -- available but not part of the official API. We've done this so
543 ** that other subsystems (of which there are hopefully few or none)
544 ** that need the IEEE 802 address can use this function rather than
545 ** duplicating the gore it does (or more specifically, the gore that
546 ** "uuid__get_os_address" does).
550 ** INPUTS/OUTPUTS: none
554 ** addr IEEE 802 address
556 ** status return status value
558 ** IMPLICIT INPUTS: none
560 ** IMPLICIT OUTPUTS: none
562 ** FUNCTION VALUE: none
564 ** SIDE EFFECTS: none
569 static int uuid_get_address(uuid_address_t
*addr
)
573 * just return address we determined previously if we've
578 memmove (addr
, &saved_addr
, sizeof (uuid_address_t
));
579 return last_addr_result
;
583 * Otherwise, call the system specific routine.
586 last_addr_result
= GetEthernetAddr(addr
);
589 * Was this an error? If so, I need to generate a random
590 * sequence to use in place of an Ethernet address.
592 if (last_addr_result
) {
593 last_addr_result
= GenRandomEthernet(addr
);
597 if (last_addr_result
== 0) {
598 /* On no error copy */
599 memmove (&saved_addr
, addr
, sizeof (uuid_address_t
));
601 return last_addr_result
;
604 /*****************************************************************************
608 ****************************************************************************/
611 * ensure we've been initialized
613 static int uuid_init_done
= false;
616 #define UUID_VERIFY_INIT(Arg) \
617 if (! uuid_init_done) \
620 if (*status != uuid_s_ok) \
627 * Check the reserved bits to make sure the UUID is of the known structure.
630 #define CHECK_STRUCTURE(uuid) \
632 (((uuid)->clock_seq_hi_and_reserved & 0x80) == 0x00) || /* var #0 */ \
633 (((uuid)->clock_seq_hi_and_reserved & 0xc0) == 0x80) || /* var #1 */ \
634 (((uuid)->clock_seq_hi_and_reserved & 0xe0) == 0xc0) /* var #2 */ \
638 * The following macros invoke CHECK_STRUCTURE(), check that the return
639 * value is okay and if not, they set the status variable appropriately
640 * and return either a boolean false, nothing (for void procedures),
641 * or a value passed to the macro. This has been done so that checking
642 * can be done more simply and values are returned where appropriate
643 * to keep compilers happy.
645 * bCHECK_STRUCTURE - returns boolean false
646 * vCHECK_STRUCTURE - returns nothing (void)
647 * rCHECK_STRUCTURE - returns 'r' macro parameter
650 #define bCHECK_STRUCTURE(uuid, status) \
652 if (!CHECK_STRUCTURE (uuid)) \
654 *(status) = uuid_s_bad_version; \
659 #define vCHECK_STRUCTURE(uuid, status) \
661 if (!CHECK_STRUCTURE (uuid)) \
663 *(status) = uuid_s_bad_version; \
668 #define rCHECK_STRUCTURE(uuid, status, result) \
670 if (!CHECK_STRUCTURE (uuid)) \
672 *(status) = uuid_s_bad_version; \
679 * Define constant designation difference in Unix and DTSS base times:
680 * DTSS UTC base time is October 15, 1582.
681 * Unix base time is January 1, 1970.
683 #define uuid_c_os_base_time_diff_lo 0x13814000
684 #define uuid_c_os_base_time_diff_hi 0x01B21DD2
686 #ifndef UUID_C_100NS_PER_SEC
687 #define UUID_C_100NS_PER_SEC 10000000
690 #ifndef UUID_C_100NS_PER_USEC
691 #define UUID_C_100NS_PER_USEC 10
699 * UADD_UVLW_2_UVLW - macro to add two unsigned 64-bit long integers
700 * (ie. add two unsigned 'very' long words)
702 * Important note: It is important that this macro accommodate (and it does)
703 * invocations where one of the addends is also the sum.
705 * This macro was snarfed from the DTSS group and was originally:
707 * UTCadd - macro to add two UTC times
709 * add lo and high order longword separately, using sign bits of the low-order
710 * longwords to determine carry. sign bits are tested before addition in two
711 * cases - where sign bits match. when the addend sign bits differ the sign of
712 * the result is also tested:
715 * addend 1 addend 2 carry?
718 * 1 0 true if sign of sum clear
719 * 0 1 true if sign of sum clear
722 #define UADD_UVLW_2_UVLW(add1, add2, sum) \
723 if (!(((add1)->lo&0x80000000UL) ^ ((add2)->lo&0x80000000UL))) \
725 if (((add1)->lo&0x80000000UL)) \
727 (sum)->lo = (add1)->lo + (add2)->lo ; \
728 (sum)->hi = (add1)->hi + (add2)->hi+1 ; \
732 (sum)->lo = (add1)->lo + (add2)->lo ; \
733 (sum)->hi = (add1)->hi + (add2)->hi ; \
738 (sum)->lo = (add1)->lo + (add2)->lo ; \
739 (sum)->hi = (add1)->hi + (add2)->hi ; \
740 if (!((sum)->lo&0x80000000UL)) \
745 * UADD_UW_2_UVLW - macro to add a 16-bit unsigned integer to
746 * a 64-bit unsigned integer
748 * Note: see the UADD_UVLW_2_UVLW() macro
751 #define UADD_UW_2_UVLW(add1, add2, sum) \
753 (sum)->hi = (add2)->hi; \
754 if ((add2)->lo & 0x80000000UL) \
756 (sum)->lo = (*add1) + (add2)->lo; \
757 if (!((sum)->lo & 0x80000000UL)) \
764 (sum)->lo = (*add1) + (add2)->lo; \
769 * U U I D _ _ G E T _ O S _ T I M E
771 * Get OS time - contains platform-specific code.
774 static const double utc_conversion_factor
= 429.4967296; // 2^32 / 10^7
776 static void uuid__get_os_time (uuid_time_t
* uuid_time
)
780 CFAbsoluteTime at
= CFAbsoluteTimeGetCurrent() + kCFAbsoluteTimeIntervalSince1970
;
781 double utc_at
= at
/ utc_conversion_factor
;
783 /* Convert 'at' in double seconds to 100ns units in utc */
784 utc
.hi
= (uint32_t)utc_at
;
785 utc_at
-= (double)utc
.hi
;
786 utc_at
*= utc_conversion_factor
;
787 utc_at
*= 10000000.0;
788 utc
.lo
= (uint32_t)utc_at
;
791 * Offset between DTSS formatted times and Unix formatted times.
793 os_basetime_diff
.lo
= uuid_c_os_base_time_diff_lo
;
794 os_basetime_diff
.hi
= uuid_c_os_base_time_diff_hi
;
795 UADD_UVLW_2_UVLW (&utc
, &os_basetime_diff
, uuid_time
);
802 ** ROUTINE NAME: init
804 ** SCOPE: INTERNAL - declared locally
808 ** Startup initialization routine for the UUID module.
812 ** INPUTS/OUTPUTS: none
816 ** status return status value
819 ** uuid_s_coding_error
821 ** IMPLICIT INPUTS: none
823 ** IMPLICIT OUTPUTS: none
825 ** FUNCTION VALUE: void
827 ** SIDE EFFECTS: sets uuid_init_done so this won't be done again
835 * init the random number generator
841 * Read the preferences data from the Macintosh pref file
847 * Get the time. Note that I renamed 'time_last' to
848 * GLastTime to indicate that I'm using it elsewhere as
849 * a shared library global.
852 if ((GLastTime
.hi
== 0) && (GLastTime
.lo
== 0)) {
853 uuid__get_os_time (&GLastTime
);
854 GClockSeq
= true_random();
856 uuid_init_done
= true;
860 static uint32_t _CFGenerateV1UUID(uint8_t *uuid_bytes
)
862 uuid_v1_t
*uuid
= (uuid_v1_t
*)uuid_bytes
;
864 uuid_address_t eaddr
;
865 int got_no_time
= false;
867 if (!uuid_init_done
) {
872 * get our hardware network address
875 if (0 != (err
= uuid_get_address(&eaddr
))) return err
;
880 * get the current time
882 uuid__get_os_time (&time_now
);
887 * o check that our clock hasn't gone backwards and handle it
888 * accordingly with clock_seq
889 * o check that we're not generating uuid's faster than we
890 * can accommodate with our time_adjust fudge factor
892 switch (time_cmp (&time_now
, &GLastTime
))
894 case uuid_e_less_than
:
895 new_clock_seq (&GClockSeq
);
898 case uuid_e_greater_than
:
901 case uuid_e_equal_to
:
902 if (GTimeAdjust
== MAX_TIME_ADJUST
)
905 * spin your wheels while we wait for the clock to tick
915 return kUUIDInternalError
;
917 } while (got_no_time
);
919 GLastTime
.lo
= time_now
.lo
;
920 GLastTime
.hi
= time_now
.hi
;
922 if (GTimeAdjust
!= 0)
924 UADD_UW_2_UVLW (>imeAdjust
, &time_now
, &time_now
);
928 * now construct a uuid with the information we've gathered
929 * plus a few constants
931 uuid
->time_low
= time_now
.lo
;
932 uuid
->time_mid
= time_now
.hi
& TIME_MID_MASK
;
934 uuid
->time_hi_and_version
=
935 (time_now
.hi
& TIME_HIGH_MASK
) >> TIME_HIGH_SHIFT_COUNT
;
936 uuid
->time_hi_and_version
|= UUID_VERSION_BITS
;
938 uuid
->clock_seq_low
= GClockSeq
& CLOCK_SEQ_LOW_MASK
;
939 uuid
->clock_seq_hi_and_reserved
=
940 (GClockSeq
& CLOCK_SEQ_HIGH_MASK
) >> CLOCK_SEQ_HIGH_SHIFT_COUNT
;
942 uuid
->clock_seq_hi_and_reserved
|= UUID_RESERVED_BITS
;
944 memmove (uuid
->node
, &eaddr
, sizeof (uuid_address_t
));
949 #if defined(__MACH__)
951 #include <uuid/uuid.h>
953 __private_extern__
uint32_t _CFGenerateUUID(uuid_t
*uuid_bytes
) {
954 static Boolean useV1UUIDs
= false, checked
= false;
957 const char *value
= getenv("CFUUIDVersionNumber");
959 if (1 == strtoul(value
, NULL
, 0)) useV1UUIDs
= true;
961 if (!_CFExecutableLinkedOnOrAfter(CFSystemVersionTiger
)) useV1UUIDs
= true;
965 if (useV1UUIDs
) return _CFGenerateV1UUID(uuid_bytes
);
966 uuid_generate_random(uuid
);
967 memcpy(uuid_bytes
, uuid
, sizeof(uuid
));
973 __private_extern__
uint32_t _CFGenerateUUID(uuid_t
*uuid_bytes
) {
974 return _CFGenerateV1UUID(uuid_bytes
);
980 /*****************************************************************************
982 * LOCAL MATH PROCEDURES - math procedures used internally by the UUID module
984 ****************************************************************************/
989 ** Compares two UUID times (64-bit UTC values)
992 static uuid_compval_t
time_cmp(uuid_time_t
*time1
,uuid_time_t
*time2
)
995 * first check the hi parts
997 if (time1
->hi
< time2
->hi
) return (uuid_e_less_than
);
998 if (time1
->hi
> time2
->hi
) return (uuid_e_greater_than
);
1001 * hi parts are equal, check the lo parts
1003 if (time1
->lo
< time2
->lo
) return (uuid_e_less_than
);
1004 if (time1
->lo
> time2
->lo
) return (uuid_e_greater_than
);
1006 return (uuid_e_equal_to
);
1011 /****************************************************************************
1013 ** U U I D T R U E R A N D O M N U M B E R G E N E R A T O R
1015 *****************************************************************************
1017 ** This random number generator (RNG) was found in the ALGORITHMS Notesfile.
1019 ** (Note 16.7, July 7, 1989 by Robert (RDVAX::)Gries, Cambridge Research Lab,
1020 ** Computational Quality Group)
1022 ** It is really a "Multiple Prime Random Number Generator" (MPRNG) and is
1023 ** completely discussed in reference #1 (see below).
1026 ** 1) "The Multiple Prime Random Number Generator" by Alexander Hass
1027 ** pp. 368 to 381 in ACM Transactions on Mathematical Software,
1029 ** 2) "The Art of Computer Programming: Seminumerical Algorithms
1030 ** (vol 2)" by Donald E. Knuth, pp. 39 to 113.
1032 ** A summary of the notesfile entry follows:
1034 ** Gries discusses the two RNG's available for ULTRIX-C. The default RNG
1035 ** uses a Linear Congruential Method (very popular) and the second RNG uses
1036 ** a technique known as a linear feedback shift register.
1038 ** The first (default) RNG suffers from bit-cycles (patterns/repetition),
1039 ** ie. it's "not that random."
1041 ** While the second RNG passes all the emperical tests, there are "states"
1042 ** that become "stable", albeit contrived.
1044 ** Gries then presents the MPRNG and says that it passes all emperical
1045 ** tests listed in reference #2. In addition, the number of calls to the
1046 ** MPRNG before a sequence of bit position repeats appears to have a normal
1049 ** Note (mbs): I have coded the Gries's MPRNG with the same constants that
1050 ** he used in his paper. I have no way of knowing whether they are "ideal"
1051 ** for the range of numbers we are dealing with.
1053 ****************************************************************************/
1056 ** T R U E _ R A N D O M _ I N I T
1058 ** Note: we "seed" the RNG with the bits from the clock and the PID
1062 static void true_random_init (void)
1065 uint16_t *seedp
, seed
=0;
1069 * optimal/recommended starting values according to the reference
1071 static uint32_t rand_m_init
= 971;
1072 static uint32_t rand_ia_init
= 11113;
1073 static uint32_t rand_ib_init
= 104322;
1074 static uint32_t rand_irand_init
= 4181;
1076 rand_m
= rand_m_init
;
1077 rand_ia
= rand_ia_init
;
1078 rand_ib
= rand_ib_init
;
1079 rand_irand
= rand_irand_init
;
1082 * Generating our 'seed' value
1084 * We start with the current time, but, since the resolution of clocks is
1085 * system hardware dependent (eg. Ultrix is 10 msec.) and most likely
1086 * coarser than our resolution (10 usec) we 'mixup' the bits by xor'ing
1087 * all the bits together. This will have the effect of involving all of
1088 * the bits in the determination of the seed value while remaining system
1089 * independent. Then for good measure to ensure a unique seed when there
1090 * are multiple processes creating UUID's on a system, we add in the PID.
1092 uuid__get_os_time(&t
);
1093 seedp
= (uint16_t *)(&t
);
1102 ** T R U E _ R A N D O M
1104 ** Note: we return a value which is 'tuned' to our purposes. Anyone
1105 ** using this routine should modify the return value accordingly.
1108 static uint16_t true_random (void)
1114 if (rand_m
>= 9973) rand_m
-= 9871;
1115 if (rand_ia
>= 99991) rand_ia
-= 89989;
1116 if (rand_ib
>= 224729) rand_ib
-= 96233;
1118 rand_irand
= (rand_irand
* rand_m
) + rand_ia
+ rand_ib
;
1120 return (HI_WORD (rand_irand
) ^ (rand_irand
& RAND_MASK
));
1123 /*****************************************************************************
1125 * LOCAL PROCEDURES - procedures used staticly by the UUID module
1127 ****************************************************************************/
1130 ** N E W _ C L O C K _ S E Q
1132 ** Ensure *clkseq is up-to-date
1134 ** Note: clock_seq is architected to be 14-bits (unsigned) but
1135 ** I've put it in here as 16-bits since there isn't a
1136 ** 14-bit unsigned integer type (yet)
1139 static void new_clock_seq
1150 * A clkseq value of 0 indicates that it hasn't been initialized.
1154 #ifdef UUID_NONVOLATILE_CLOCK
1155 *clkseq
= uuid__read_clock(); /* read nonvolatile clock */
1156 if (*clkseq
== 0) /* still not init'd ??? */
1158 *clkseq
= true_random(); /* yes, set random */
1162 * with a volatile clock, we always init to a random number
1164 *clkseq
= true_random();
1168 CLOCK_SEQ_BUMP (clkseq
);
1171 *clkseq
= *clkseq
+ 1;
1174 #ifdef UUID_NONVOLATILE_CLOCK
1175 uuid_write_clock (clkseq
);
1183 * Read the preferences data into my global variables
1186 static OSErr
ReadPrefData(void)
1189 * Zero out the saved preferences information
1192 memset((void *)&GSavedENetAddr
, 0, sizeof(GSavedENetAddr
));
1193 memset((void *)&GLastTime
, 0, sizeof(GLastTime
));
1206 * Write the preferences data back out to my global variables.
1207 * This gets called a couple of times. First, this is called by
1208 * my GetRandomEthernet routine if I generated a psudorandom MAC
1209 * address. Second, this is called when the library is being
1210 * terminated through the __terminate() CFM call.
1212 * Note this does it's best attempt at writing the data out,
1213 * and relies on ReadPrefData to check for integrety of the actual
1217 static void WritePrefData(void)
1225 #undef TIME_MID_MASK
1226 #undef TIME_HIGH_MASK
1227 #undef TIME_HIGH_SHIFT_COUNT
1228 #undef MAX_TIME_ADJUST
1229 #undef CLOCK_SEQ_LOW_MASK
1230 #undef CLOCK_SEQ_HIGH_MASK
1231 #undef CLOCK_SEQ_HIGH_SHIFT_COUNT
1232 #undef CLOCK_SEQ_FIRST
1233 #undef CLOCK_SEQ_LAST
1234 #undef CLOCK_SEQ_BIT_BANG
1235 #undef CLOCK_SEQ_BUMP
1236 #undef UUID_VERSION_BITS
1237 #undef UUID_RESERVED_BITS
1240 #undef UUID_VERIFY_INIT
1241 #undef CHECK_STRUCTURE
1242 #undef bCHECK_STRUCTURE
1243 #undef vCHECK_STRUCTURE
1244 #undef rCHECK_STRUCTURE
1245 #undef uuid_c_os_base_time_diff_lo
1246 #undef uuid_c_os_base_time_diff_hi
1247 #undef UUID_C_100NS_PER_SEC
1248 #undef UUID_C_100NS_PER_USEC
1249 #undef UADD_UVLW_2_UVLW
1250 #undef UADD_UW_2_UVLW