1 /* Hurdish implementation of getrandom
2 Copyright (C) 2016-2021 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 <sys/random.h>
20 #include <fcntl.h>
21 #include <unistd.h>
22 #include <not-cancel.h>
23
24 /* Write up to LENGTH bytes of randomness starting at BUFFER.
25 Return the number of bytes written, or -1 on error. */
26 ssize_t
__getrandom(void * buffer,size_t length,unsigned int flags)27 __getrandom (void *buffer, size_t length, unsigned int flags)
28 {
29 const char *random_source = "/dev/urandom";
30 int open_flags = O_RDONLY | O_CLOEXEC;
31 size_t amount_read;
32 int fd;
33
34 if (flags & GRND_RANDOM)
35 random_source = "/dev/random";
36
37 if (flags & GRND_NONBLOCK)
38 open_flags |= O_NONBLOCK;
39
40 fd = __open_nocancel(random_source, open_flags);
41 if (fd == -1)
42 return -1;
43
44 amount_read = __read_nocancel(fd, buffer, length);
45 __close_nocancel_nostatus(fd);
46 return amount_read;
47 }
48
49 libc_hidden_def (__getrandom)
50 weak_alias (__getrandom, getrandom)
51