port: add missing attributes in getrandom_nonblock() on macOS
[lttng-tools.git] / src / common / random.cpp
CommitLineData
57b90af7
JG
1/*
2 * Copyright (C) 2023 Jérémie Galarneau <jeremie.galarneau@efficios.com>
3 *
4 * SPDX-License-Identifier: LGPL-2.1-only
5 *
6 */
7
57b90af7
JG
8#include <common/file-descriptor.hpp>
9#include <common/format.hpp>
10#include <common/hashtable/utils.hpp>
11#include <common/random.hpp>
12#include <common/readwrite.hpp>
13#include <common/time.hpp>
14
28ab034a
JG
15#include <lttng/constant.h>
16
57b90af7
JG
17#include <fcntl.h>
18
19#ifdef HAVE_SYS_SYSCALL_H
20#include <sys/syscall.h>
21#endif
22
23#define LTTNG_THROW_RANDOM_PRODUCTION_ERROR(msg) \
24 throw lttng::random::production_error(msg, __FILE__, __func__, __LINE__)
25
26namespace {
27/* getrandom is available in Linux >= 3.17. */
28#if defined(__linux__) && defined(SYS_getrandom) && defined(HAVE_SYS_RANDOM_H)
29
30#include <sys/random.h>
31
32/* A glibc wrapper is provided only for glibc >= 2.25. */
33#if defined(HAVE_GETRANDOM)
34/* Simply use the existing wrapper, passing the non-block flag. */
35ssize_t _call_getrandom_nonblock(char *out_data, std::size_t size)
36{
37 return getrandom(out_data, size, GRND_NONBLOCK);
38}
39#else
40ssize_t _call_getrandom_nonblock(char *out_data, std::size_t size)
41{
42 const int grnd_nonblock_flag = 0x1;
43
44 auto ret = syscall(SYS_getrandom, out_data, size, grnd_nonblock_flag);
45 if (ret < 0) {
46 errno = -ret;
47 ret = -1;
48 }
49
50 return ret;
51}
52#endif /* defined(HAVE_GETRANDOM) */
53
54/* Returns either with a full read or throws. */
55void getrandom_nonblock(char *out_data, std::size_t size)
56{
57 /*
58 * Since GRND_RANDOM is _not_ used, a partial read can only be caused
59 * by a signal interruption. In this case, retry.
60 */
61 ssize_t ret;
62
63 do {
64 ret = _call_getrandom_nonblock(out_data, size);
65 } while ((ret > 0 && ret != size) || (ret == -1 && errno == EINTR));
66
67 if (ret < 0) {
68 LTTNG_THROW_POSIX(
28ab034a
JG
69 fmt::format("Failed to get true random data using getrandom(): size={}",
70 size),
71 errno);
57b90af7
JG
72 }
73}
74#else /* defined(__linux__) && defined(SYS_getrandom) && defined(HAVE_SYS_RANDOM_H) */
45cc2527
MJ
75__attribute__((noreturn))
76void getrandom_nonblock(char *out_data __attribute__((unused)),
77 std::size_t size __attribute__((unused)))
57b90af7 78{
28ab034a 79 LTTNG_THROW_RANDOM_PRODUCTION_ERROR("getrandom() is not supported by this platform");
57b90af7
JG
80}
81#endif /* defined(__linux__) && defined(SYS_getrandom) && defined(HAVE_SYS_RANDOM_H) */
82
83lttng::random::seed_t produce_pseudo_random_seed()
84{
85 int ret;
86 struct timespec real_time = {};
87 struct timespec monotonic_time = {};
88 unsigned long hash_seed;
89 char hostname[LTTNG_HOST_NAME_MAX] = {};
90 unsigned long seed;
91
92 ret = clock_gettime(CLOCK_REALTIME, &real_time);
93 if (ret) {
94 LTTNG_THROW_POSIX("Failed to read real time while generating pseudo-random seed",
28ab034a 95 errno);
57b90af7
JG
96 }
97
98 ret = clock_gettime(CLOCK_MONOTONIC, &monotonic_time);
99 if (ret) {
100 LTTNG_THROW_POSIX(
28ab034a 101 "Failed to read monotonic time while generating pseudo-random seed", errno);
57b90af7
JG
102 }
103
104 ret = gethostname(hostname, sizeof(hostname));
105 if (ret) {
106 LTTNG_THROW_POSIX("Failed to get host name while generating pseudo-random seed",
28ab034a 107 errno);
57b90af7
JG
108 }
109
110 hash_seed = (unsigned long) real_time.tv_nsec ^ (unsigned long) real_time.tv_sec ^
28ab034a 111 (unsigned long) monotonic_time.tv_nsec ^ (unsigned long) monotonic_time.tv_sec;
57b90af7
JG
112 seed = hash_key_ulong((void *) real_time.tv_sec, hash_seed);
113 seed ^= hash_key_ulong((void *) real_time.tv_nsec, hash_seed);
114 seed ^= hash_key_ulong((void *) monotonic_time.tv_sec, hash_seed);
115 seed ^= hash_key_ulong((void *) monotonic_time.tv_nsec, hash_seed);
116
117 const unsigned long pid = getpid();
118 seed ^= hash_key_ulong((void *) pid, hash_seed);
119 seed ^= hash_key_str(hostname, hash_seed);
120
121 return static_cast<lttng::random::seed_t>(seed);
122}
123
124lttng::random::seed_t produce_random_seed_from_urandom()
125{
126 /*
127 * Open /dev/urandom as a file_descriptor, or throw on error. The
128 * lambda is used to reduce the scope of the raw fd as much as possible.
129 */
28ab034a 130 lttng::file_descriptor urandom{ []() {
57b90af7
JG
131 const auto urandom_raw_fd = open("/dev/urandom", O_RDONLY | O_CLOEXEC);
132
133 if (urandom_raw_fd < 0) {
134 LTTNG_THROW_POSIX("Failed to open `/dev/urandom`", errno);
135 }
136
137 return urandom_raw_fd;
28ab034a 138 }() };
57b90af7
JG
139
140 lttng::random::seed_t seed;
141 const auto read_ret = lttng_read(urandom.fd(), &seed, sizeof(seed));
142 if (read_ret != sizeof(seed)) {
143 LTTNG_THROW_POSIX(fmt::format("Failed to read from `/dev/urandom`: size={}",
28ab034a
JG
144 sizeof(seed)),
145 errno);
57b90af7
JG
146 }
147
148 return seed;
149}
150
151} /* namespace */
152
153lttng::random::production_error::production_error(const std::string& msg,
28ab034a
JG
154 const char *file_name,
155 const char *function_name,
156 unsigned int line_number) :
57b90af7
JG
157 lttng::runtime_error(msg, file_name, function_name, line_number)
158{
159}
160
161lttng::random::seed_t lttng::random::produce_true_random_seed()
162{
163 lttng::random::seed_t seed;
164
165 getrandom_nonblock(reinterpret_cast<char *>(&seed), sizeof(seed));
166 return seed;
167}
168
169lttng::random::seed_t lttng::random::produce_best_effort_random_seed()
170{
171 try {
172 return lttng::random::produce_true_random_seed();
173 } catch (std::exception& e) {
174 WARN("%s",
28ab034a
JG
175 fmt::format(
176 "Failed to produce a random seed using getrandom(), falling back to pseudo-random device seed generation which will block until its pool is initialized: {}",
177 e.what())
178 .c_str());
57b90af7
JG
179 }
180
181 try {
182 /*
183 * Can fail for various reasons, including not being accessible
184 * under some containerized environments.
185 */
186 produce_random_seed_from_urandom();
187 } catch (std::exception& e) {
188 WARN("%s",
28ab034a
JG
189 fmt::format("Failed to produce a random seed from the urandom device: {}",
190 e.what())
191 .c_str());
57b90af7
JG
192 }
193
194 /* Fallback to time-based seed generation. */
195 return produce_pseudo_random_seed();
196}
This page took 0.033267 seconds and 4 git commands to generate.