UUID source Code

 

   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);

    uuid->time_low = ntohl(uuid->time_low);

    uuid->time_mid = ntohs(uuid->time_mid);

    uuid->time_hi_and_version = ntohs(uuid->time_hi_and_version);

 

    /* put in the variant and version bits */

    uuid->time_hi_and_version &= 0x0FFF;

    uuid->time_hi_and_version |= (v << 12);

    uuid->clock_seq_hi_and_reserved &= 0x3F;

    uuid->clock_seq_hi_and_reserved |= 0x80;

}

 

/* uuid_compare --  Compare two UUID's "lexically" and return */

#define CHECK(f1, f2) if (f1 != f2) return f1 < f2 ? -1 : 1;

int uuid_compare(uuid_t *u1, uuid_t *u2)

{

    int i;

    CHECK(u1->time_low, u2->time_low);

    CHECK(u1->time_mid, u2->time_mid);

    CHECK(u1->time_hi_and_version, u2->time_hi_and_version);

    CHECK(u1->clock_seq_hi_and_reserved, u2->clock_seq_hi_and_reserved);

    CHECK(u1->clock_seq_low, u2->clock_seq_low)

    for (i = 0; i < 6; i++) {

        if (u1->node[i] < u2->node[i])

            return -1;

        if (u1->node[i] > u2->node[i])

            return 1;

    }

    return 0;

}

#undef CHECK

sysdep.h

#include "copyrt.h"

/* remove the following define if you aren't running WIN32 */

#define WININC 0

 

#ifdef WININC

#include <windows.h>

#else

#include <sys/types.h>

#include <sys/time.h>

#include <sys/sysinfo.h>

#endif

 

#include "global.h"

/* change to point to where MD5 .h's live; RFC 1321 has sample implementation */

#include "md5.h"

 

/* set the following to the number of 100ns ticks of the actual resolution of your system's clock */

#define UUIDS_PER_TICK 1024

 

/* Set the following to a calls to get and release a global lock */

#define LOCK

#define UNLOCK

 

typedef unsigned long   unsigned32;

typedef unsigned short  unsigned16;

typedef unsigned char   unsigned8;

typedef unsigned char   byte;

 

/* Set this to what your compiler uses for 64-bit data type */

#ifdef WININC

#define unsigned64_t unsigned __int64

#define I64(C) C

#else

#define unsigned64_t unsigned long long

#define I64(C) C##LL

#endif

 

typedef unsigned64_t uuid_time_t;

typedef struct {

    char nodeID[6];

} uuid_node_t;

 

void get_ieee_node_identifier(uuid_node_t *node);

void get_system_time(uuid_time_t *uuid_time);

void get_random_info(char seed[16]);

sysdep.c

#include "copyrt.h"

#include <stdio.h>

#include "sysdep.h"

 

/* system dependent call to get IEEE node ID. This sample implementation generates a random node ID. */

void get_ieee_node_identifier(uuid_node_t *node)

{

    static inited = 0;

    static uuid_node_t saved_node;

    char seed[16];

    FILE *fp;

    if (!inited) {

        fp = fopen("nodeid", "rb");

        if (fp) {

            fread(&saved_node, sizeof saved_node, 1, fp);

            fclose(fp);

        }

        else {

            get_random_info(seed);

            seed[0] |= 0x01;

            memcpy(&saved_node, seed, sizeof saved_node);

            fp = fopen("nodeid", "wb");

            if (fp) {

                fwrite(&saved_node, sizeof saved_node, 1, fp);

                fclose(fp);

            }

        }

        inited = 1;

    }

    *node = saved_node;

}

 

/* system dependent call to get the current system time. Returned as 100ns ticks since UUID epoch, but resolution may be less than 100ns. */

#ifdef _WINDOWS_

 

void get_system_time(uuid_time_t *uuid_time)

{

    ULARGE_INTEGER time;

 

/* NT keeps time in FILETIME format which is 100ns ticks since Jan 1, 1601. UUIDs use time in 100ns ticks since Oct 15, 1582. The difference is 17 Days in Oct + 30 (Nov) + 31 (Dec) + 18 years and 5 leap days. */

GetSystemTimeAsFileTime((FILETIME *)&time);

    time.QuadPart += (unsigned __int64) (1000*1000*10)       // seconds

        * (unsigned __int64) (60 * 60 * 24)       // days

        * (unsigned __int64) (17+30+31+365*18+5); // # of days

        *uuid_time = time.QuadPart;

}

 

/* Sample code, not for use in production; see RFC 1750 */

void get_random_info(char seed[16])

{

    MD5_CTX c;

    struct {

        MEMORYSTATUS m;

        SYSTEM_INFO s;

        FILETIME t;

        LARGE_INTEGER pc;

        DWORD tc;

        DWORD l;

        char hostname[MAX_COMPUTERNAME_LENGTH + 1];

    } r;

    MD5Init(&c);

    GlobalMemoryStatus(&r.m);

    GetSystemInfo(&r.s);

    GetSystemTimeAsFileTime(&r.t);

    QueryPerformanceCounter(&r.pc);

    r.tc = GetTickCount();

    r.l = MAX_COMPUTERNAME_LENGTH + 1;

    GetComputerName(r.hostname, &r.l);

    MD5Update(&c, &r, sizeof r);

    MD5Final(seed, &c);

}

#else

void get_system_time(uuid_time_t *uuid_time)

{

    struct timeval tp;

 

    gettimeofday(&tp, (struct timezone *)0);

    /* Offset between UUID formatted times and Unix formatted times. UUID UTC base time is October 15, 1582. Unix base time is January 1, 1970.*/

    *uuid_time = ((unsigned64)tp.tv_sec * 10000000)+((unsigned64)tp.tv_usec * 10) + I64(0x01B21DD213814000);

}

 

/* Sample code, not for use in production; see RFC 1750 */

void get_random_info(char seed[16])

{

    MD5_CTX c;

    struct {

        struct sysinfo s;

        struct timeval t;

        char hostname[257];

    } r;

 

    MD5Init(&c);

    sysinfo(&r.s);

    gettimeofday(&r.t, (struct timezone *)0);

    gethostname(r.hostname, 256);

    MD5Update(&c, &r, sizeof r);

    MD5Final(seed, &c);

}

#endif

utest.c

#include "copyrt.h"

#include "sysdep.h"

#include <stdio.h>

#include "uuid.h"

uuid_t NameSpace_DNS = {                       /* 6ba7b810-9dad-11d1-80b4-00c04fd430c8 */

    0x6ba7b810,

    0x9dad,

    0x11d1,

    0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8

};

 

/* puid -- print a UUID */

void puid(uuid_t u)

{

    int i;

 

    printf("%8.8x-%4.4x-%4.4x-%2.2x%2.2x-", u.time_low, u.time_mid, u.time_hi_and_version, u.clock_seq_hi_and_reserved, u.clock_seq_low);

    for (i = 0; i < 6; i++)

        printf("%2.2x", u.node[i]);

    printf("\n");

}

 

/* Simple driver for UUID generator */

void main(int argc, char **argv)

{

    uuid_t u;

    int f;

 

    uuid_create(&u);

    printf("uuid_create(): "); puid(u);

 

    f = uuid_compare(&u, &u);

    printf("uuid_compare(u,u): %d\n", f);     /* should be 0 */

    f = uuid_compare(&u, &NameSpace_DNS);

    printf("uuid_compare(u, NameSpace_DNS): %d\n", f); /* s.b. 1 */

    f = uuid_compare(&NameSpace_DNS, &u);

    printf("uuid_compare(NameSpace_DNS, u): %d\n", f); /* s.b. -1 */

    uuid_create_md5_from_name(&u, NameSpace_DNS, "www.widgets.com", 15);

    printf("uuid_create_md5_from_name(): "); puid(u);

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
npm WARN deprecated stable@0.1.8: Modern JS already guarantees Array#sort() is a stable sort, so this library is deprecated. See the compatibility table on MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort#browser_compatibility npm WARN deprecated source-map-url@0.4.1: See https://github.com/lydell/source-map-url#deprecated npm WARN deprecated @hapi/bourne@1.3.2: This version has been deprecated and is no longer supported or maintained npm WARN deprecated @hapi/topo@3.1.6: This version has been deprecated and is no longer supported or maintained npm WARN deprecated eslint-loader@2.2.1: This loader has been deprecated. Please use eslint-webpack-plugin npm WARN deprecated urix@0.1.0: Please see https://github.com/lydell/urix#deprecated npm WARN deprecated har-validator@5.1.5: this library is no longer supported npm WARN deprecated source-map-resolve@0.5.3: See https://github.com/lydell/source-map-resolve#deprecated npm WARN deprecated chokidar@2.1.8: Chokidar 2 does not receive security updates since 2019. Upgrade to chokidar 3 with 15x fewer dependencies npm WARN deprecated chokidar@2.1.8: Chokidar 2 does not receive security updates since 2019. Upgrade to chokidar 3 with 15x fewer dependencies npm WARN deprecated resolve-url@0.2.1: https://github.com/lydell/resolve-url#deprecated npm WARN deprecated html-webpack-plugin@3.2.0: 3.x is no longer supported npm WARN deprecated @hapi/address@2.1.4: Moved to 'npm install @sideway/address' npm WARN deprecated querystring@0.2.0: The querystring API is considered Legacy. new code should use the URLSearchParams API instead. npm WARN deprecated babel-eslint@10.1.0: babel-eslint is now @babel/eslint-parser. This package will no longer receive updates. npm WARN deprecated uuid@3.4.0: Please upgrade to version 7 or higher. Older versions may use Math.random() in certain circumstances, which is known to be problematic. See https://v8.dev/blog/math-random for details. npm WARN deprecated request@2.88.2: request has been deprecated, see https://github.com/request/request/issues/3142 npm WARN deprecated @hapi/hoek@8.5.1: This version has been deprecated and is no longer supported or maintained npm WARN deprecated @hapi/joi@15.1.1: Switch to 'npm install joi' npm WARN deprecated svgo@1.3.2: This SVGO version is no longer supported. Upgrade to v2.x.x. npm WARN deprecated core-js@2.6.12: core-js@<3.23.3 is no longer maintained and not recommended for usage due to the number of issues. Because of the V8 engine whims, feature detection in old core-js versions could cause a slowdown up to 100x even if nothing is polyfilled. Some versions have web compatibility issues. Please, upgrade your dependencies to the actual version of core-js. added 1400 packages in 1m
06-08
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值