Line data Source code
1 : /*
2 : MIT License
3 :
4 : Copyright (c) 2026 - A bunch of nerds
5 :
6 : Permission is hereby granted, free of charge, to any person obtaining a copy
7 : of this software and associated documentation files (the "Software"), to deal
8 : in the Software without restriction, including without limitation the rights
9 : to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 : copies of the Software, and to permit persons to whom the Software is
11 : furnished to do so, subject to the following conditions:
12 :
13 : The above copyright notice and this permission notice shall be included in all
14 : copies or substantial portions of the Software.
15 :
16 : THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 : IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 : FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 : AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 : LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 : OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22 : SOFTWARE.
23 : */
24 :
25 : // Random bytes from the kernel, without blocking.
26 :
27 : #ifndef CCOL_INTERNAL_CRANDOM_H
28 : #define CCOL_INTERNAL_CRANDOM_H
29 :
30 : #if !defined(__STDC_VERSION__) || __STDC_VERSION__ < 202311L
31 : #include <stdbool.h>
32 : #endif
33 : #include <stddef.h>
34 : #include <sys/types.h>
35 : #if defined(__APPLE__) || defined(__OpenBSD__)
36 : #include <unistd.h>
37 : #if defined(__APPLE__)
38 : #include <sys/random.h>
39 : #endif
40 : #else
41 : #include <sys/random.h>
42 : #endif
43 :
44 : // Fills buf with len random bytes from the kernel, without blocking. chashmap
45 : // seeds its process secret with it, so hash collisions can't be computed
46 : // offline. It uses getrandom(2) on Linux and FreeBSD and getentropy(2) on macOS
47 : // and OpenBSD (at most 256 bytes per call there; OpenBSD has no <sys/random.h>
48 : // for it). Gives false when the bytes aren't available, and the caller then
49 : // falls back to a mix of its own.
50 2098 : static inline bool ccol_random_bytes(void *buf, size_t len) {
51 : #if defined(__APPLE__) || defined(__OpenBSD__)
52 : return len <= 256 && getentropy(buf, len) == 0;
53 : #else
54 2098 : return getrandom(buf, len, GRND_NONBLOCK) == (ssize_t)len;
55 : #endif
56 : }
57 :
58 : #endif
|