-
-
Notifications
You must be signed in to change notification settings - Fork 497
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
XPG8 defines getentropy() as the only good source for random numbers. However, real world use a bit more nuanced. On BSD systems, we would prefer to use arc4random as it avoids unnecessary system calls. On Linux however, getentropy is implemented in terms of getrandom, and should be used directly when available.
- Loading branch information
Showing
2 changed files
with
43 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,39 @@ | ||
// | ||
// Copyright 2024 Staysail Systems, Inc. <[email protected]> | ||
// | ||
// This software is supplied under the terms of the MIT License, a | ||
// copy of which should be located in the distribution where this | ||
// file was obtained (LICENSE.txt). A copy of the license may also be | ||
// found online at https://opensource.org/licenses/MIT. | ||
// | ||
|
||
// getrandom is not as nice as arc4random, but on platforms where it | ||
// exists and arc4random does not, we should use it. | ||
// | ||
// getrandom will block only if the urandom device is not seeded yet. | ||
// That can only happen during very early boot (earlier than we should | ||
// normally be running. This is the only time it can fail with correct | ||
// arguments, and then only if it is interrupted with a signal. | ||
|
||
#include <stddef.h> | ||
#include <stdint.h> | ||
#include <unistd.h> | ||
#ifdef NNG_HAVE_SYS_RANDOM | ||
#include <sys/random.h> | ||
#endif | ||
|
||
#include "core/panic.h" | ||
|
||
#ifdef NNG_HAVE_GETENTROPY | ||
|
||
uint32_t | ||
nni_random(void) | ||
{ | ||
uint32_t val; | ||
if (getentropy(&val, sizeof(val)) != sizeof(val)) { | ||
nni_panic("getentropy failed"); | ||
} | ||
return (val); | ||
} | ||
|
||
#endif |