1 /* Pseudo Random Number Generator
2 Copyright (C) 2022-2023 Free Software Foundation, Inc.
3 This file is part of the GNU C Library.
5 The GNU C Library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
10 The GNU C Library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public
16 License along with the GNU C Library; if not, see
17 <https://www.gnu.org/licenses/>. */
20 #include <not-cancel.h>
24 #include <sys/param.h>
25 #include <sys/random.h>
28 arc4random_getrandom_failure (void)
30 __libc_fatal ("Fatal glibc error: cannot get entropy for arc4random\n");
34 __arc4random_buf (void *p
, size_t n
)
36 static int seen_initialized
;
45 l
= TEMP_FAILURE_RETRY (__getrandom_nocancel (p
, n
, 0));
49 return; /* Done reading, success. */
50 p
= (uint8_t *) p
+ l
;
52 continue; /* Interrupted by a signal; keep going. */
54 else if (l
== -ENOSYS
)
55 break; /* No syscall, so fallback to /dev/urandom. */
56 arc4random_getrandom_failure ();
59 if (atomic_load_relaxed (&seen_initialized
) == 0)
61 /* Poll /dev/random as an approximation of RNG initialization. */
62 struct pollfd pfd
= { .events
= POLLIN
};
63 pfd
.fd
= TEMP_FAILURE_RETRY (
64 __open64_nocancel ("/dev/random", O_RDONLY
| O_CLOEXEC
| O_NOCTTY
));
66 arc4random_getrandom_failure ();
67 if (TEMP_FAILURE_RETRY (__poll_infinity_nocancel (&pfd
, 1)) < 0)
68 arc4random_getrandom_failure ();
69 if (__close_nocancel (pfd
.fd
) < 0)
70 arc4random_getrandom_failure ();
71 atomic_store_relaxed (&seen_initialized
, 1);
74 fd
= TEMP_FAILURE_RETRY (
75 __open64_nocancel ("/dev/urandom", O_RDONLY
| O_CLOEXEC
| O_NOCTTY
));
77 arc4random_getrandom_failure ();
80 l
= TEMP_FAILURE_RETRY (__read_nocancel (fd
, p
, n
));
82 arc4random_getrandom_failure ();
84 break; /* Done reading, success. */
85 p
= (uint8_t *) p
+ l
;
88 if (__close_nocancel (fd
) < 0)
89 arc4random_getrandom_failure ();
91 libc_hidden_def (__arc4random_buf
)
92 weak_alias (__arc4random_buf
, arc4random_buf
)
98 __arc4random_buf (&r
, sizeof (r
));
101 libc_hidden_def (__arc4random
)
102 weak_alias (__arc4random
, arc4random
)