RFC 4122 - A Universally Unique IDentifier (UUID) URN Namesp(2)

时间:2006-11-01 来源: 作者: 点击:
oFormataUUIDfromthecurrenttimestamp,clocksequence,andnode IDvaluesaccordingtothestepsinSection4.2.2. IfUUIDsdonotneedtobefrequentlygenerated,theabovealgorithm maybeperfectlyadequate.Forhigherperforma
  

   o  Format a UUID from the current timestamp, clock sequence, and node
      ID values according to the steps in Section 4.2.2.

   If UUIDs do not need to be frequently generated, the above algorithm
   may be perfectly adequate.  For higher performance requirements,
   however, issues with the basic algorithm include:

   o  Reading the state from stable storage each time is inefficient.

   o  The resolution of the system clock may not be 100-nanoseconds.

   o  Writing the state to stable storage each time is inefficient.

   o  Sharing the state across process boundaries may be inefficient.

   Each of these issues can be addressed in a modular fashion by local
   improvements in the functions that read and write the state and read
   the clock.  We address each of them in turn in the following
   sections.

4.2.1.1.  Reading Stable Storage

   The state only needs to be read from stable storage once at boot
   time, if it is read into a system-wide shared volatile store (and
   updated whenever the stable store is updated).

   If an implementation does not have any stable store available, then
   it can always say that the values were unavailable.  This is the
   least desirable implementation because it will increase the frequency
   of creation of new clock sequence numbers, which increases the
   probability of duplicates.

   If the node ID can never change (e.g., the net card is inseparable
   from the system), or if any change also reinitializes the clock
   sequence to a random value, then instead of keeping it in stable
   store, the current node ID may be returned.

4.2.1.2.  System Clock Resolution

   The timestamp is generated from the system time, whose resolution may
   be less than the resolution of the UUID timestamp.

   If UUIDs do not need to be frequently generated, the timestamp can
   simply be the system time multiplied by the number of 100-nanosecond
   intervals per system time interval.

   If a system overruns the generator by requesting too many UUIDs
   within a single system time interval, the UUID service MUST either
   return an error, or stall the UUID generator until the system clock
   catches up.

   A high resolution timestamp can be simulated by keeping a count of
   the number of UUIDs that have been generated with the same value of
   the system time, and using it to construct the low order bits of the
   timestamp.  The count will range between zero and the number of
   100-nanosecond intervals per system time interval.

   Note: If the processors overrun the UUID generation frequently,
   additional node identifiers can be allocated to the system, which
   will permit higher speed allocation by making multiple UUIDs
   potentially available for each time stamp value.

4.2.1.3.  Writing Stable Storage

   The state does not always need to be written to stable store every
   time a UUID is generated.  The timestamp in the stable store can be
   periodically set to a value larger than any yet used in a UUID.  As
   long as the generated UUIDs have timestamps less than that value, and

   the clock sequence and node ID remain unchanged, only the shared
   volatile copy of the state needs to be updated.  Furthermore, if the
   timestamp value in stable store is in the future by less than the
   typical time it takes the system to reboot, a crash will not cause a
   reinitialization of the clock sequence.

4.2.1.4.  Sharing State Across Processes

   If it is too expensive to access shared state each time a UUID is
   generated, then the system-wide generator can be implemented to
   allocate a block of time stamps each time it is called; a per-
   process generator can allocate from that block until it is exhausted.

4.2.2.  Generation Details

   Version 1 UUIDs are generated according to the following algorithm:

   o  Determine the values for the UTC-based timestamp and clock
      sequence to be used in the UUID, as described in Section 4.2.1.

   o  For the purposes of this algorithm, consider the timestamp to be a
      60-bit unsigned integer and the clock sequence to be a 14-bit
      unsigned integer.  Sequentially number the bits in a field,
      starting with zero for the least significant bit.

   o  Set the time_low field equal to the least significant 32 bits
      (bits zero through 31) of the timestamp in the same order of
      significance.

   o  Set the time_mid field equal to bits 32 through 47 from the
      timestamp in the same order of significance.

   o  Set the 12 least significant bits (bits zero through 11) of the
      time_hi_and_version field equal to bits 48 through 59 from the
      timestamp in the same order of significance.

   o  Set the four most significant bits (bits 12 through 15) of the
      time_hi_and_version field to the 4-bit version number
      corresponding to the UUID version being created, as shown in the
      table above.

   o  Set the clock_seq_low field to the eight least significant bits
      (bits zero through 7) of the clock sequence in the same order of
      significance.

   o  Set the 6 least significant bits (bits zero through 5) of the
      clock_seq_hi_and_reserved field to the 6 most significant bits
      (bits 8 through 13) of the clock sequence in the same order of
      significance.

   o  Set the two most significant bits (bits 6 and 7) of the
      clock_seq_hi_and_reserved to zero and one, respectively.

   o  Set the node field to the 48-bit IEEE address in the same order of
      significance as the address.

4.3.  Algorithm for Creating a Name-Based UUID

   The version 3 or 5 UUID is meant for generating UUIDs from "names"
   that are drawn from, and unique within, some "name space".  The
   concept of name and name space should be broadly construed, and not
   limited to textual names.  For example, some name spaces are the
   domain name system, URLs, ISO Object IDs (OIDs), X.500 Distinguished
   Names (DNs), and reserved words in a programming language.  The
   mechanisms or conventions used for allocating names and ensuring
   their uniqueness within their name spaces are beyond the scope of
   this specification.

   The requirements for these types of UUIDs are as follows:

   o  The UUIDs generated at different times from the same name in the
      same namespace MUST be equal.

   o  The UUIDs generated from two different names in the same namespace
      should be different (with very high probability).

   o  The UUIDs generated from the same name in two different namespaces
      should be different with (very high probability).

   o  If two UUIDs that were generated from names are equal, then they
      were generated from the same name in the same namespace (with very
      high probability).

   The algorithm for generating a UUID from a name and a name space are
   as follows:

   o  Allocate a UUID to use as a "name space ID" for all UUIDs
      generated from names in that name space; see Appendix C for some
      pre-defined values.

   o  Choose either MD5 [4] or SHA-1 [8] as the hash algorithm; If
      backward compatibility is not an issue, SHA-1 is preferred.

   o  Convert the name to a canonical sequence of octets (as defined by
      the standards or conventions of its name space); put the name
      space ID in network byte order.

   o  Compute the hash of the name space ID concatenated with the name.

   o  Set octets zero through 3 of the time_low field to octets zero
      through 3 of the hash.

   o  Set octets zero and one of the time_mid field to octets 4 and 5 of
      the hash.

   o  Set octets zero and one of the time_hi_and_version field to octets
      6 and 7 of the hash.

   o  Set the four most significant bits (bits 12 through 15) of the
      time_hi_and_version field to the appropriate 4-bit version number
      from Section 4.1.3.

   o  Set the clock_seq_hi_and_reserved field to octet 8 of the hash.

   o  Set the two most significant bits (bits 6 and 7) of the
      clock_seq_hi_and_reserved to zero and one, respectively.

   o  Set the clock_seq_low field to octet 9 of the hash.

   o  Set octets zero through five of the node field to octets 10
      through 15 of the hash.

   o  Convert the resulting UUID to local byte order.

4.4.  Algorithms for Creating a UUID from Truly Random or
      Pseudo-Random Numbers

   The version 4 UUID is meant for generating UUIDs from truly-random or
   pseudo-random numbers.

   The algorithm is as follows:

   o  Set the two most significant bits (bits 6 and 7) of the
      clock_seq_hi_and_reserved to zero and one, respectively.

   o  Set the four most significant bits (bits 12 through 15) of the
      time_hi_and_version field to the 4-bit version number from
      Section 4.1.3.

   o  Set all the other bits to randomly (or pseudo-randomly) chosen
      values.

   See Section 4.5 for a discussion on random numbers.

4.5.  Node IDs that Do Not Identify the Host

   This section describes how to generate a version 1 UUID if an IEEE
   802 address is not available, or its use is not desired.

   One approach is to contact the IEEE and get a separate block of
   addresses.  At the time of writing, the application could be found at
   <http://standards.ieee.org/regauth/oui/pilot-ind.html>, and the cost
   was US$550.

   A better solution is to obtain a 47-bit cryptographic quality random
   number and use it as the low 47 bits of the node ID, with the least
   significant bit of the first octet of the node ID set to one.  This
   bit is the unicast/multicast bit, which will never be set in IEEE 802
   addresses obtained from network cards.  Hence, there can never be a
   conflict between UUIDs generated by machines with and without network
   cards.  (Recall that the IEEE 802 spec talks about transmission
   order, which is the opposite of the in-memory representation that is
   discussed in this document.)

   For compatibility with earlier specifications, note that this
   document uses the unicast/multicast bit, instead of the arguably more
   correct local/global bit.

   Advice on generating cryptographic-quality random numbers can be
   found in RFC1750 [5].

   In addition, items such as the computer’s name and the name of the
   operating system, while not strictly speaking random, will help
   differentiate the results from those obtained by other systems.

   The exact algorithm to generate a node ID using these data is system
   specific, because both the data available and the functions to obtain
   them are often very system specific.  A generic approach, however, is
   to accumulate as many sources as possible into a buffer, use a
   message digest such as MD5 [4] or SHA-1 [8], take an arbitrary 6
   bytes from the hash value, and set the multicast bit as described
   above.

5.  Community Considerations

   The use of UUIDs is extremely pervasive in computing.  They comprise
   the core identifier infrastructure for many operating systems
   (Microsoft Windows) and applications (the Mozilla browser) and in
   many cases, become exposed to the Web in many non-standard ways.

   This specification attempts to standardize that practice as openly as
   possible and in a way that attempts to benefit the entire Internet.

6.  Security Considerations

   Do not assume that UUIDs are hard to guess; they should not be used
   as security capabilities (identifiers whose mere possession grants
   access), for example.  A predictable random number source will
   exacerbate the situation.

   Do not assume that it is easy to determine if a UUID has been
   slightly transposed in order to redirect a reference to another
   object.  Humans do not have the ability to easily check the integrity
   of a UUID by simply glancing at it.

   Distributed applications generating UUIDs at a variety of hosts must
   be willing to rely on the random number source at all hosts.  If this
   is not feasible, the namespace variant should be used.

7.  Acknowledgments

   This document draws heavily on the OSF DCE specification for UUIDs.
   Ted Ts’o provided helpful comments, especially on the byte ordering
   section which we mostly plagiarized from a proposed wording he
   supplied (all errors in that section are our responsibility,
   however).

   We are also grateful to the careful reading and bit-twiddling of Ralf
   S. Engelschall, John Larmouth, and Paul Thorpe.  Professor Larmouth
   was also invaluable in achieving coordination with ISO/IEC.

8.  Normative References

   [1]  Zahn, L., Dineen, T., and P. Leach, "Network Computing
        Architecture", ISBN 0-13-611674-4, January 1990.

   [2]  "DCE: Remote Procedure Call", Open Group CAE Specification C309,
        ISBN 1-85912-041-5, August 1994.

   [3]  ISO/IEC 9834-8:2004 Information Technology, "Procedures for the
        operation of OSI Registration Authorities: Generation and
        registration of Universally Unique Identifiers (UUIDs) and their
        use as ASN.1 Object Identifier components" ITU-T Rec. X.667,
        2004.

   [4]  Rivest, R., "The MD5 Message-Digest Algorithm ", RFC 1321, April
        1992.

   [5]  Eastlake, D., 3rd, Schiller, J., and S. Crocker, "Randomness
        Requirements for Security", BCP 106, RFC 4086, June 2005.

   [6]  Moats, R., "URN Syntax", RFC 2141, May 1997.

   [7]  Crocker, D. and P. Overell, "Augmented BNF for Syntax
        Specifications: ABNF", RFC 2234, November 1997.

   [8]  National Institute of Standards and Technology, "Secure Hash
        Standard", FIPS PUB 180-1, April 1995,
        <http://www.itl.nist.gov/fipspubs/fip180-1.htm>.

Appendix A.  Appendix A - Sample Implementation

   This implementation consists of 5 files: uuid.h, uuid.c, sysdep.h,
   sysdep.c and utest.c.  The uuid.* files are the system independent
   implementation of the UUID generation algorithms described above,
   with all the optimizations described above except efficient state
   sharing across processes included.  The code has been tested on Linux
   (Red Hat 4.0) with GCC (2.7.2), and Windows NT 4.0 with VC++ 5.0.
   The code assumes 64-bit integer support, which makes it much clearer.

   All the following source files should have the following copyright
   notice included:

copyrt.h

/*
** Copyright (c) 1990- 1993, 1996 Open Software Foundation, Inc.
** Copyright (c) 1989 by Hewlett-Packard Company, Palo Alto, Ca. &
** Digital Equipment Corporation, Maynard, Mass.
** Copyright (c) 1998 Microsoft.
** To anyone who acknowledges that this file is provided "AS IS"
** without any express or implied warranty: permission to use, copy,
** modify, and distribute this file for any purpose is hereby
** granted without fee, provided that the above copyright notices and
** this notice appears in all source code copies, and that none of
** the names of Open Software Foundation, Inc., Hewlett-Packard
** Company, Microsoft, or Digital Equipment Corporation be used in
** advertising or publicity pertaining to distribution of the software
** without specific, written prior permission. Neither Open Software
** Foundation, Inc., Hewlett-Packard Company, Microsoft, nor Digital
** Equipment Corporation makes any representations about the
** suitability of this software for any purpose.
*/

uuid.h

#include "copyrt.h"
#undef uuid_t
typedef struct {
    unsigned32  time_low;
    unsigned16  time_mid;
    unsigned16  time_hi_and_version;
    unsigned8   clock_seq_hi_and_reserved;
    unsigned8   clock_seq_low;
    byte        node[6];
} uuid_t;

/* uuid_create -- generate a UUID */
int uuid_create(uuid_t * uuid);

/* uuid_create_md5_from_name -- create a version 3 (MD5) UUID using a
   "name" from a "name space" */
void uuid_create_md5_from_name(
    uuid_t *uuid,         /* resulting UUID */
    uuid_t nsid,          /* UUID of the namespace */
    void *name,           /* the name from which to generate a UUID */
    int namelen           /* the length of the name */
);

/* uuid_create_sha1_from_name -- create a version 5 (SHA-1) UUID
   using a "name" from a "name space" */
void uuid_create_sha1_from_name(

    uuid_t *uuid,         /* resulting UUID */
    uuid_t nsid,          /* UUID of the namespace */
    void *name,           /* the name from which to generate a UUID */
    int namelen           /* the length of the name */
);

/* uuid_compare --  Compare two UUID’s "lexically" and return
        -1   u1 is lexically before u2
         0   u1 is equal to u2
         1   u1 is lexically after u2
   Note that lexical ordering is not temporal ordering!
*/
int uuid_compare(uuid_t *u1, uuid_t *u2);

uuid.c

#include "copyrt.h"
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "sysdep.h"
#include "uuid.h"

/* various forward declarations */
static int read_state(unsigned16 *clockseq, uuid_time_t *timestamp,
    uuid_node_t *node);
static void write_state(unsigned16 clockseq, uuid_time_t timestamp,
    uuid_node_t node);
static void format_uuid_v1(uuid_t *uuid, unsigned16 clockseq,
    uuid_time_t timestamp, uuid_node_t node);

static void format_uuid_v3or5(uuid_t *uuid, unsigned char hash[16],
    int v);
static void get_current_time(uuid_time_t *timestamp);
static unsigned16 true_random(void);

/* uuid_create -- generator a UUID */
int uuid_create(uuid_t *uuid)
{
     uuid_time_t timestamp, last_time;
     unsigned16 clockseq;
     uuid_node_t node;
     uuid_node_t last_node;
     int f;

     /* acquire system-wide lock so we’re alone */
     LOCK;
     /* get time, node ID, saved state from non-volatile storage */
     get_current_time(&timestamp);
     get_ieee_node_identifier(&node);
     f = read_state(&clockseq, &last_time, &last_node);

     /* if no NV state, or if clock went backwards, or node ID
        changed (e.g., new network card) change clockseq */
     if (!f || memcmp(&node, &last_node, sizeof node))
         clockseq = true_random();
     else if (timestamp < last_time)
         clockseq++;

     /* save the state for next time */
     write_state(clockseq, timestamp, node);

     UNLOCK;

     /* stuff fields into the UUID */
     format_uuid_v1(uuid, clockseq, timestamp, node);
     return 1;
}

/* format_uuid_v1 -- make a UUID from the timestamp, clockseq,
                     and node ID */
void format_uuid_v1(uuid_t* uuid, unsigned16 clock_seq,
                    uuid_time_t timestamp, uuid_node_t node)
{
    /* Construct a version 1 uuid with the information we’ve gathered
       plus a few constants. */
    uuid->time_low = (unsigned long)(timestamp & 0xFFFFFFFF);
    uuid->time_mid = (unsigned short)((timestamp >> 32) & 0xFFFF);
    uuid->time_hi_and_version =

        (unsigned short)((timestamp >> 48) & 0x0FFF);
    uuid->time_hi_and_version |= (1 << 12);
    uuid->clock_seq_low = clock_seq & 0xFF;
    uuid->clock_seq_hi_and_reserved = (clock_seq & 0x3F00) >> 8;
    uuid->clock_seq_hi_and_reserved |= 0x80;
    memcpy(&uuid->node, &node, sizeof uuid->node);
}

/* data type for UUID generator persistent state */
typedef struct {
    uuid_time_t  ts;       /* saved timestamp */
    uuid_node_t  node;     /* saved node ID */
    unsigned16   cs;       /* saved clock sequence */
} uuid_state;

static uuid_state st;

/* read_state -- read UUID generator state from non-volatile store */
int read_state(unsigned16 *clockseq, uuid_time_t *timestamp,
               uuid_node_t *node)
{
    static int inited = 0;
    FILE *fp;

    /* only need to read state once per boot */
    if (!inited) {
        fp = fopen("state", "rb");
        if (fp == NULL)
            return 0;
        fread(&st, sizeof st, 1, fp);
        fclose(fp);
        inited = 1;
    }
    *clockseq = st.cs;
    *timestamp = st.ts;
    *node = st.node;
    return 1;
}

/* write_state -- save UUID generator state back to non-volatile
   storage */
void write_state(unsigned16 clockseq, uuid_time_t timestamp,
                 uuid_node_t node)
{
    static int inited = 0;
    static uuid_time_t next_save;
    FILE* fp;

    if (!inited) {
        next_save = timestamp;
        inited = 1;
    }

    /* always save state to volatile shared state */
    st.cs = clockseq;
    st.ts = timestamp;
    st.node = node;
    if (timestamp >= next_save) {
        fp = fopen("state", "wb");
        fwrite(&st, sizeof st, 1, fp);
        fclose(fp);
        /* schedule next save for 10 seconds from now */
        next_save = timestamp + (10 * 10 * 1000 * 1000);
    }
}

/* get-current_time -- get time as 60-bit 100ns ticks since UUID epoch.
   Compensate for the fact that real clock resolution is
   less than 100ns. */
void get_current_time(uuid_time_t *timestamp)
{
    static int inited = 0;
    static uuid_time_t time_last;
    static unsigned16 uuids_this_tick;
    uuid_time_t time_now;

    if (!inited) {
        get_system_time(&time_now);
        uuids_this_tick = UUIDS_PER_TICK;
        inited = 1;
    }

    for ( ; ; ) {
        get_system_time(&time_now);

        /* if clock reading changed since last UUID generated, */
        if (time_last != time_now) {
            /* reset count of uuids gen’d with this clock reading */
            uuids_this_tick = 0;
            time_last = time_now;
            break;
        }
        if (uuids_this_tick < UUIDS_PER_TICK) {
            uuids_this_tick++;
            break;
        }

        /* going too fast for our clock; spin */
    }
    /* add the count of uuids to low order bits of the clock reading */
    *timestamp = time_now + uuids_this_tick;
}

/* true_random -- generate a crypto-quality random number.
   **This sample doesn’t do that.** */
static unsigned16 true_random(void)
{
    static int inited = 0;
    uuid_time_t time_now;

    if (!inited) {
        get_system_time(&time_now);
        time_now = time_now / UUIDS_PER_TICK;
        srand((unsigned int)
               (((time_now >> 32) ^ time_now) & 0xffffffff));
        inited = 1;
    }

    return rand();
}

/* uuid_create_md5_from_name -- create a version 3 (MD5) UUID using a
   "name" from a "name space" */
void uuid_create_md5_from_name(uuid_t *uuid, uuid_t nsid, void *name,
                               int namelen)
{
    MD5_CTX c;
    unsigned char hash[16];
    uuid_t net_nsid;

    /* put name space ID in network byte order so it hashes the same
       no matter what endian machine we’re on */
    net_nsid = nsid;
    net_nsid.time_low = htonl(net_nsid.time_low);
    net_nsid.time_mid = htons(net_nsid.time_mid);
    net_nsid.time_hi_and_version = htons(net_nsid.time_hi_and_version);

    MD5Init(&c);
    MD5Update(&c, &net_nsid, sizeof net_nsid);
    MD5Update(&c, name, namelen);
    MD5Final(hash, &c);

    /* the hash is in network byte order at this point */
    format_uuid_v3or5(uuid, hash, 3);
}

void uuid_create_sha1_from_name(uuid_t *uuid, uuid_t nsid, void *name,
                                int namelen)
{
    SHA_CTX c;
    unsigned char hash[20];
    uuid_t net_nsid;

    /* put name space ID in network byte order so it hashes the same
       no matter what endian machine we’re on */
    net_nsid = nsid;
    net_nsid.time_low = htonl(net_nsid.time_low);
    net_nsid.time_mid = htons(net_nsid.time_mid);
    net_nsid.time_hi_and_version = htons(net_nsid.time_hi_and_version);

    SHA1_Init(&c);
    SHA1_Update(&c, &net_nsid, sizeof net_nsid);
    SHA1_Update(&c, name, namelen);
    SHA1_Final(hash, &c);

    /* the hash is in network byte order at this point */
    format_uuid_v3or5(uuid, hash, 5);
}

/* format_uuid_v3or5 -- make a UUID from a (pseudo)random 128-bit
   number */
void format_uuid_v3or5(uuid_t *uuid, unsigned char hash[16], int v)
{
    /* convert UUID to local byte order */
    memcpy(uuid, hash, sizeof *uuid);
------分隔线----------------------------
顶一下
(0)
0%
踩一下
(0)
0%
------分隔线----------------------------
最新评论 查看所有评论
发表评论 查看所有评论
请自觉遵守互联网相关的政策法规,严禁发布色情、暴力、反动的言论。
评价:
表情:
用户名: 密码: 验证码:
推荐内容