Annotation of parser3/src/main/pa_random.C, revision 1.12

1.1       misha       1: /** @file
                      2:        Parser: random related functions.
                      3: 
1.10      moko        4:        Copyright (c) 2001-2020 Art. Lebedev Studio (http://www.artlebedev.com)
1.1       misha       5:        Author: Alexandr Petrosian <paf@design.ru> (http://paf.design.ru)
                      6: */
                      7: 
                      8: // includes
                      9: 
1.8       moko       10: #include "pa_common.h"
1.1       misha      11: #include "pa_random.h"
                     12: #include "pa_exception.h"
                     13: #include "pa_threads.h"
                     14: 
1.12    ! moko       15: volatile const char * IDENT_PA_RANDOM_C="$Id: pa_random.C,v 1.11 2021/01/13 21:28:15 moko Exp $" IDENT_PA_RANDOM_H;
1.3       moko       16: 
1.5       moko       17: #ifdef _MSC_VER
1.4       moko       18: #include <windows.h>
1.1       misha      19: 
                     20: class Random_provider {
                     21:        HCRYPTPROV fhProv;
                     22:        
                     23:        void acquire() {
                     24:                SYNCHRONIZED;
                     25: 
                     26:                if(fhProv)
                     27:                        return;
                     28: 
                     29:                if(!CryptAcquireContext(&fhProv, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT))
1.7       moko       30:                        throw Exception(0, 0, "CryptAcquireContext failed");
1.1       misha      31:        }
                     32:        void release() {
                     33:                if(fhProv)
                     34:                        CryptReleaseContext(fhProv, 0);
                     35:        }
                     36:        
                     37: public:
                     38:        Random_provider(): fhProv(0) {}
                     39:        ~Random_provider() { release(); }
                     40:        void generate(void *buffer, size_t size) {
                     41:                acquire();
                     42: 
                     43:                if(!CryptGenRandom(fhProv, size, (BYTE*)buffer))
1.7       moko       44:                        throw Exception(0, 0, "CryptGenRandom failed");
1.1       misha      45:        }
1.12    ! moko       46: } random_provider;
        !            47: 
        !            48: typedef struct timeval {
        !            49:     long tv_sec;
        !            50:     long tv_usec;
        !            51: } timeval;
        !            52: 
        !            53: int gettimeofday(struct timeval * tp, void *);
1.1       misha      54: 
                     55: #else
                     56: 
                     57: /// from gen_uuid.c
                     58: static int get_random_fd(void)
                     59: {
                     60:         struct timeval  tv;
                     61:         static int      fd = -2;
                     62:         int             i;
                     63: 
                     64:         if (fd == -2) {
                     65:                 gettimeofday(&tv, 0);
                     66:                 fd = open("/dev/urandom", O_RDONLY);
                     67:                 if (fd == -1)
                     68:                         fd = open("/dev/random", O_RDONLY | O_NONBLOCK);
                     69:                 srand((getpid() << 16) ^ getuid() ^ tv.tv_sec ^ tv.tv_usec);
                     70:         }
                     71:         /* Crank the random number generator a few times */
                     72:         gettimeofday(&tv, 0);
                     73:         for (i = (tv.tv_sec ^ tv.tv_usec) & 0x1F; i > 0; i--)
                     74:                 rand();
                     75:         return fd;
                     76: }
                     77: 
                     78: 
                     79: /*
                     80:  * Generate a series of random bytes.  Use /dev/urandom if possible,
                     81:  * and if not, use srandom/random.
                     82:  */
                     83: static void get_random_bytes(void *buf, int nbytes)
                     84: {
                     85:         int i, fd = get_random_fd();
                     86:         int lose_counter = 0;
                     87:         char *cp = (char *) buf;
                     88: 
                     89:         if (fd >= 0) {
                     90:                 while (nbytes > 0) {
                     91:                         i = read(fd, cp, nbytes);
                     92:                         if (i <= 0) {
                     93:                                 if (lose_counter++ > 16)
                     94:                                         break;
                     95:                                 continue;
                     96:                         }
                     97:                         nbytes -= i;
                     98:                         cp += i;
                     99:                         lose_counter = 0;
                    100:                 }
                    101:         }
                    102: 
                    103:         /* XXX put something better here if no /dev/random! */
                    104:         for (i = 0; i < nbytes; i++)
                    105:                 *cp++ = rand() & 0xFF;
                    106:         return;
                    107: }
                    108: 
                    109: 
                    110: #endif
                    111: 
                    112: void random(void *buffer, size_t size) {
1.5       moko      113: #ifdef _MSC_VER
1.1       misha     114:        random_provider.generate(buffer, size);
                    115: #else
                    116:        get_random_bytes(buffer, size);
                    117: #endif
                    118: }
                    119: 
1.7       moko      120: /// to hell with extra bytes on 64bit platforms
                    121: struct uuid {
                    122:        unsigned int    time_low;
                    123:        unsigned short  time_mid;
                    124:        unsigned short  time_hi_and_version;
                    125:        unsigned short  clock_seq;
                    126:        unsigned char   node[6];
                    127: };
                    128: 
                    129: static uuid get_uuid() {
1.1       misha     130:        // random
                    131:        uuid uuid;
                    132:        random(&uuid, sizeof(uuid));
                    133: 
                    134:        // http://www.opengroup.org/onlinepubs/9629399/apdxa.htm#tagtcjh_35
                    135:        // ~
                    136:        // version = DCE Security version, with embedded POSIX UIDs.  
                    137:        // variant = DCE
                    138:        //
                    139:        // DCE=Distributed Computing Environment
                    140:        // http://www.opengroup.org/dce/
                    141:        //
                    142:        // they say this influences comparison&such,
                    143:        // but could not figure out how, hence structure layout specified strictly
                    144:        // anyhow, uuidgen on Win32 yield those values
                    145:        // 
                    146:        // xxxxxxxx-xxxx-4xxx-{8,9,A,B}xxx-xxxxxxxxxxxx
                    147:        uuid.clock_seq = (uuid.clock_seq & 0x3FFF) | 0x8000;
                    148:         uuid.time_hi_and_version = (uuid.time_hi_and_version & 0x0FFF) | 0x4000;
                    149: 
                    150:        return uuid;
                    151: }
                    152: 
1.11      moko      153: char *get_uuid_cstr(bool lower, bool solid) {
1.7       moko      154:        uuid uuid=get_uuid();
                    155: 
                    156:        const size_t bufsize=36+1/*zero-teminator*/+1/*for faulty snprintfs*/;
                    157:        char* cstr=new(PointerFreeGC) char[bufsize];
                    158: 
1.11      moko      159:        const char *format[] = {
                    160:                "%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X",
                    161:                "%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x",
                    162:                "%08X%04X%04X%02X%02X%02X%02X%02X%02X%02X%02X",
                    163:                "%08x%04x%04x%02x%02x%02x%02x%02x%02x%02x%02x"
                    164:        };
                    165: 
1.7       moko      166:        snprintf(cstr, bufsize,
1.11      moko      167:                format[(lower ? 1:0) + (solid ? 2:0)],
1.7       moko      168:                uuid.time_low, uuid.time_mid, uuid.time_hi_and_version,
                    169:                uuid.clock_seq >> 8, uuid.clock_seq & 0xFF,
                    170:                uuid.node[0], uuid.node[1], uuid.node[2],
                    171:                uuid.node[3], uuid.node[4], uuid.node[5]);
                    172:        return cstr;
                    173: }
                    174: 
                    175: char *get_uuid_boundary() {
                    176:        uuid uuid=get_uuid();
                    177: 
                    178:        const int boundary_bufsize=10+32+1/*for zero-teminator*/+1/*for faulty snprintfs*/;
                    179:        char* boundary=new(PointerFreeGC) char[boundary_bufsize];
                    180: 
                    181:        snprintf(boundary, boundary_bufsize,
                    182:                "----------%08X%04X%04X%02X%02X%02X%02X%02X%02X%02X%02X",
                    183:                uuid.time_low, uuid.time_mid, uuid.time_hi_and_version,
                    184:                uuid.clock_seq >> 8, uuid.clock_seq & 0xFF,
                    185:                uuid.node[0], uuid.node[1], uuid.node[2],
                    186:                uuid.node[3], uuid.node[4], uuid.node[5]);
                    187:        return boundary;
                    188: }
1.12    ! moko      189: 
        !           190: // UUID version 7
        !           191: // https://datatracker.ietf.org/doc/draft-ietf-uuidrev-rfc4122bis/
        !           192: //
        !           193: // UUID version 7 features a time-ordered value field derived from the
        !           194: // widely implemented and well known Unix Epoch timestamp source, the
        !           195: // number of milliseconds since midnight 1 Jan 1970 UTC, leap seconds
        !           196: // excluded.  UUIDv7 generally has improved entropy characteristics over
        !           197: // UUIDv1 or UUIDv6.
        !           198: //
        !           199: //  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
        !           200: // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
        !           201: // |                           unix_ts_ms                          |
        !           202: // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
        !           203: // |          unix_ts_ms           |  ver  |       rand_a          |
        !           204: // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
        !           205: // |var|                        rand_b                             |
        !           206: // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
        !           207: // |                            rand_b                             |
        !           208: // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
        !           209: //
        !           210: // unix_ts_ms:
        !           211: //    48 bit big-endian unsigned number of Unix epoch timestamp in
        !           212: //    milliseconds.  Occupies bits 0 through 47 (octets 0-5).
        !           213: // ver:
        !           214: //    The 4 bit version field, set to 0b0111 (7).
        !           215: //    Occupies bits 48 through 51 of octet 6.
        !           216: // rand_a:
        !           217: //    12 bits pseudo-random data to provide uniqueness as per
        !           218: //    Section 6.8 and/or optional constructs to guarantee additional
        !           219: //    monotonicity. Occupies bits 52 through 63 (octets 6-7).
        !           220: // var:
        !           221: //    The 2 bit variant field as defined by Section 4.1, set to 0b10.
        !           222: //    Occupies bits 64 and 65 of octet 8.
        !           223: // rand_b:
        !           224: //    The final 62 bits of pseudo-random data to provide uniqueness as
        !           225: //    per Section 6.8 and/or an optional counter to guarantee additional
        !           226: //    monotonicity. Occupies bits 66 through 127 (octets 8-15).
        !           227: 
        !           228: char *get_uuid7_cstr(bool lower, bool solid) {
        !           229:        unsigned char uuid[16];
        !           230:        random(&uuid[8], 8);
        !           231: 
        !           232:        struct timeval tv;
        !           233:        gettimeofday(&tv, 0);
        !           234: 
        !           235:        // 48 bit big-endian unsigned number of Unix epoch timestamp in milliseconds
        !           236:        uint64_t unix_ts_ms = (uint64_t)tv.tv_sec * 1000 + (uint64_t)tv.tv_usec / 1000;
        !           237:        uuid[5] = (unsigned char) (unix_ts_ms); unix_ts_ms >>= 8;
        !           238:        uuid[4] = (unsigned char) (unix_ts_ms); unix_ts_ms >>= 8;
        !           239:        uuid[3] = (unsigned char) (unix_ts_ms); unix_ts_ms >>= 8;
        !           240:        uuid[2] = (unsigned char) (unix_ts_ms); unix_ts_ms >>= 8;
        !           241:        uuid[1] = (unsigned char) (unix_ts_ms); unix_ts_ms >>= 8;
        !           242:        uuid[0] = (unsigned char) (unix_ts_ms);
        !           243: 
        !           244:        // Use increased clock precision as left-most random bits
        !           245:        uint64_t usec = tv.tv_usec;
        !           246:        uuid[7] = (unsigned char) (usec); usec >>= 8;
        !           247:        uuid[6] = (unsigned char) (usec);
        !           248: 
        !           249:        // Set magic numbers for a "version 7" UUID, see
        !           250:        // https://www.ietf.org/archive/id/draft-ietf-uuidrev-rfc4122bis-00.html#name-uuid-version-7
        !           251:        uuid[6] = (uuid[6] & 0x0f) | 0x70; /* 4 bit version [0111] */
        !           252:        uuid[8] = (uuid[8] & 0x3f) | 0x80; /* 2 bit variant [10]   */
        !           253: 
        !           254:        const size_t bufsize=36+1/*zero-teminator*/+1/*for faulty snprintfs*/;
        !           255:        char* cstr=new(PointerFreeGC) char[bufsize];
        !           256: 
        !           257:        const char *format[] = {
        !           258:                "%02X%02X%02X%02X-%02X%02X-%02X%02X-%02X%02X-%02X%02X%02X%02X%02X%02X",
        !           259:                "%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x",
        !           260:                "%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
        !           261:                "%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
        !           262:        };
        !           263: 
        !           264:        snprintf(cstr, bufsize, format[(lower ? 1:0) + (solid ? 2:0)],
        !           265:                uuid[0], uuid[1], uuid[2], uuid[3], uuid[4], uuid[5], uuid[6], uuid[7],
        !           266:                uuid[8], uuid[9], uuid[10], uuid[11], uuid[12], uuid[13], uuid[14], uuid[15]
        !           267:        );
        !           268: 
        !           269:        return cstr;
        !           270: }

E-mail: