1/* Pseudo Random Number Generator
2 Copyright (C) 2022-2024 Free Software Foundation, Inc.
3 This file is part of the GNU C Library.
4
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.
9
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.
14
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/>. */
18
19#include <errno.h>
20#include <not-cancel.h>
21#include <stdio.h>
22#include <stdlib.h>
23#include <sys/mman.h>
24#include <sys/param.h>
25#include <sys/random.h>
26
27static void
28arc4random_getrandom_failure (void)
29{
30 __libc_fatal ("Fatal glibc error: cannot get entropy for arc4random\n");
31}
32
33void
34__arc4random_buf (void *p, size_t n)
35{
36 static int seen_initialized;
37 ssize_t l;
38 int fd;
39
40 if (n == 0)
41 return;
42
43 for (;;)
44 {
45 l = TEMP_FAILURE_RETRY (__getrandom_nocancel (p, n, 0));
46 if (l > 0)
47 {
48 if ((size_t) l == n)
49 return; /* Done reading, success. */
50 p = (uint8_t *) p + l;
51 n -= l;
52 continue; /* Interrupted by a signal; keep going. */
53 }
54 else if (l == -ENOSYS)
55 break; /* No syscall, so fallback to /dev/urandom. */
56 arc4random_getrandom_failure ();
57 }
58
59 if (atomic_load_relaxed (&seen_initialized) == 0)
60 {
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));
65 if (pfd.fd < 0)
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);
72 }
73
74 fd = TEMP_FAILURE_RETRY (
75 __open64_nocancel ("/dev/urandom", O_RDONLY | O_CLOEXEC | O_NOCTTY));
76 if (fd < 0)
77 arc4random_getrandom_failure ();
78 for (;;)
79 {
80 l = TEMP_FAILURE_RETRY (__read_nocancel (fd, p, n));
81 if (l <= 0)
82 arc4random_getrandom_failure ();
83 if ((size_t) l == n)
84 break; /* Done reading, success. */
85 p = (uint8_t *) p + l;
86 n -= l;
87 }
88 if (__close_nocancel (fd) < 0)
89 arc4random_getrandom_failure ();
90}
91libc_hidden_def (__arc4random_buf)
92weak_alias (__arc4random_buf, arc4random_buf)
93
94uint32_t
95__arc4random (void)
96{
97 uint32_t r;
98 __arc4random_buf (p: &r, n: sizeof (r));
99 return r;
100}
101libc_hidden_def (__arc4random)
102weak_alias (__arc4random, arc4random)
103

source code of glibc/stdlib/arc4random.c