1 /* Hurdish implementation of getrandom
2 Copyright (C) 2016-2022 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 extern char *__trivfs_server_name __attribute__((weak));
25
26 /* Write up to LENGTH bytes of randomness starting at BUFFER.
27 Return the number of bytes written, or -1 on error. */
28 ssize_t
__getrandom(void * buffer,size_t length,unsigned int flags)29 __getrandom (void *buffer, size_t length, unsigned int flags)
30 {
31 const char *random_source = "/dev/urandom";
32 int open_flags = O_RDONLY | O_CLOEXEC;
33 size_t amount_read;
34 int fd;
35
36 if (&__trivfs_server_name && __trivfs_server_name
37 && __trivfs_server_name[0] == 'r'
38 && __trivfs_server_name[1] == 'a'
39 && __trivfs_server_name[2] == 'n'
40 && __trivfs_server_name[3] == 'd'
41 && __trivfs_server_name[4] == 'o'
42 && __trivfs_server_name[5] == 'm'
43 && __trivfs_server_name[6] == '\0')
44 /* We are random, don't try to read ourselves! */
45 return length;
46
47 if (flags & GRND_RANDOM)
48 random_source = "/dev/random";
49
50 if (flags & GRND_NONBLOCK)
51 open_flags |= O_NONBLOCK;
52
53 fd = __open_nocancel(random_source, open_flags);
54 if (fd == -1)
55 return -1;
56
57 amount_read = __read_nocancel(fd, buffer, length);
58 __close_nocancel_nostatus(fd);
59 return amount_read;
60 }
61
62 libc_hidden_def (__getrandom)
63 weak_alias (__getrandom, getrandom)
64