-
Notifications
You must be signed in to change notification settings - Fork 20
/
reqid.c
75 lines (62 loc) · 1.13 KB
/
reqid.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
/*
* See LICENSE file for copyright and license details.
*
* Copyright (c) 2013 Joyent, Inc.
* Copyright (c) 2024 MNX Cloud, Inc.
*/
#include <sys/types.h>
#include <errno.h>
#include <fcntl.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/uio.h>
#include <time.h>
#include <unistd.h>
#include "common.h"
#include "reqid.h"
static int urandom_fd = -1;
char *
reqid(char *buf)
{
int i;
static int seed = -1;
int32_t tmp = 0;
VERIFY(buf != NULL);
/*
* If we were able to open it, try and read a random request ID
* from /dev/urandom:
*/
if (urandom_fd != -1) {
if (read(urandom_fd, &tmp, sizeof (tmp)) == sizeof (tmp))
goto out;
}
/*
* Otherwise, fall back to C rand():
*/
if (seed == -1) {
seed = (int) time(NULL);
srand((unsigned int)seed);
}
for (i = 0; i < 4; i++) {
tmp |= (0xff & (rand())) << (i * 8);
}
out:
sprintf(buf, "%08x", tmp);
return (buf);
}
int
reqid_init(void)
{
if (urandom_fd == -1)
urandom_fd = open("/dev/urandom", O_RDONLY | O_NONBLOCK);
return (0);
}
void
reqid_fini(void)
{
if (urandom_fd == -1)
return;
(void) close(urandom_fd);
urandom_fd = -1;
}