]>
git.ipfire.org Git - thirdparty/systemd.git/blob - src/basic/random-util.c
2 This file is part of systemd.
4 Copyright 2010 Lennart Poettering
6 systemd is free software; you can redistribute it and/or modify it
7 under the terms of the GNU Lesser General Public License as published by
8 the Free Software Foundation; either version 2.1 of the License, or
9 (at your option) any later version.
11 systemd is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 Lesser General Public License for more details.
16 You should have received a copy of the GNU Lesser General Public License
17 along with systemd; If not, see <http://www.gnu.org/licenses/>.
22 #include <linux/random.h>
24 #ifdef HAVE_SYS_AUXV_H
28 #include <sys/types.h>
33 #include "random-util.h"
34 #include "time-util.h"
37 int dev_urandom(void *p
, size_t n
) {
38 static int have_syscall
= -1;
40 _cleanup_close_
int fd
= -1;
43 /* Gathers some randomness from the kernel. This call will
44 * never block, and will always return some data from the
45 * kernel, regardless if the random pool is fully initialized
46 * or not. It thus makes no guarantee for the quality of the
47 * returned entropy, but is good enough for or usual usecases
48 * of seeding the hash functions for hashtable */
50 /* Use the getrandom() syscall unless we know we don't have
51 * it, or when the requested size is too large for it. */
52 if (have_syscall
!= 0 || (size_t) (int) n
!= n
) {
53 r
= getrandom(p
, n
, GRND_NONBLOCK
);
61 /* we lack the syscall, continue with
62 * reading from /dev/urandom */
64 else if (errno
== EAGAIN
)
65 /* not enough entropy for now. Let's
66 * remember to use the syscall the
67 * next time, again, but also read
68 * from /dev/urandom for now, which
69 * doesn't care about the current
70 * amount of entropy. */
79 fd
= open("/dev/urandom", O_RDONLY
|O_CLOEXEC
|O_NOCTTY
);
81 return errno
== ENOENT
? -ENOSYS
: -errno
;
83 return loop_read_exact(fd
, p
, n
, true);
86 void initialize_srand(void) {
87 static bool srand_called
= false;
89 #ifdef HAVE_SYS_AUXV_H
98 #ifdef HAVE_SYS_AUXV_H
99 /* The kernel provides us with a bit of entropy in auxv, so
100 * let's try to make use of that to seed the pseudo-random
101 * generator. It's better than nothing... */
103 auxv
= (void*) getauxval(AT_RANDOM
);
105 x
^= *(unsigned*) auxv
;
108 x
^= (unsigned) now(CLOCK_REALTIME
);
109 x
^= (unsigned) gettid();
115 void random_bytes(void *p
, size_t n
) {
119 r
= dev_urandom(p
, n
);
123 /* If some idiot made /dev/urandom unavailable to us, he'll
124 * get a PRNG instead. */
128 for (q
= p
; q
< (uint8_t*) p
+ n
; q
++)