Botan 3.14.1
Crypto and TLS for C&
Botan::OS Namespace Reference

Classes

class  Echo_Suppression
class  Fork_Detector
class  Socket
class  SocketUDP

Functions

std::vector< void * > allocate_locked_pages (size_t count)
std::string BOTAN_TEST_API format_time (time_t time, const std::string &format)
void free_locked_pages (const std::vector< void * > &pages)
std::optional< std::pair< unsigned long, unsigned long > > get_auxval_hwcap ()
size_t BOTAN_TEST_API get_cpu_available ()
uint64_t BOTAN_TEST_API get_cpu_cycle_counter ()
uint64_t BOTAN_TEST_API get_fork_generation ()
uint64_t BOTAN_TEST_API get_high_resolution_clock ()
size_t get_memory_locking_limit ()
uint32_t BOTAN_TEST_API get_process_id ()
uint64_t BOTAN_TEST_API get_system_timestamp_ns ()
std::optional< uint64_t > BOTAN_TEST_API get_thread_cpu_time_ns ()
std::unique_ptr< Socket > BOTAN_TEST_API open_socket (std::string_view hostname, std::string_view service, std::chrono::milliseconds timeout)
std::unique_ptr< SocketUDP > BOTAN_TEST_API open_socket_udp (std::string_view hostname, std::string_view service, std::chrono::microseconds timeout)
std::unique_ptr< SocketUDP > BOTAN_TEST_API open_socket_udp (std::string_view uri, std::chrono::microseconds timeout)
void page_allow_access (void *page)
void page_prohibit_access (void *page)
bool read_env_variable (std::string &value_out, std::string_view var_name)
size_t read_env_variable_sz (std::string_view var_name, size_t def_value=0)
int BOTAN_TEST_API run_cpu_instruction_probe (const std::function< int()> &probe_fn)
std::unique_ptr< Echo_Suppression > BOTAN_UNSTABLE_API suppress_echo_on_terminal ()
size_t system_page_size ()

Function Documentation

◆ allocate_locked_pages()

std::vector< void * > Botan::OS::allocate_locked_pages ( size_t count)

Request count pages of RAM which are locked into memory using mlock, VirtualLock, or some similar OS specific API. Free it with free_locked_pages.

Returns an empty list on failure. This function is allowed to return fewer than count pages.

The contents of the allocated pages are undefined.

Each page is preceded by and followed by a page which is marked as noaccess, such that accessing it will cause a crash. This turns out of bound reads/writes into crash events.

Parameters
countrequested number of locked pages

Definition at line 573 of file os_utils.cpp.

573 {
574 std::vector<void*> result;
575
576#if(defined(BOTAN_TARGET_OS_HAS_POSIX1) && defined(BOTAN_TARGET_OS_HAS_POSIX_MLOCK)) || \
577 defined(BOTAN_TARGET_OS_HAS_VIRTUAL_LOCK)
578
579 result.reserve(count);
580
581 const size_t page_size = OS::system_page_size();
582
583 #if defined(BOTAN_TARGET_OS_HAS_POSIX1) && defined(BOTAN_TARGET_OS_HAS_POSIX_MLOCK)
584 static const int locked_fd = get_locked_fd();
585 #endif
586
587 for(size_t i = 0; i != count; ++i) {
588 void* ptr = nullptr;
589
590 #if defined(BOTAN_TARGET_OS_HAS_POSIX1) && defined(BOTAN_TARGET_OS_HAS_POSIX_MLOCK)
591 ptr = ::mmap(nullptr,
592 3 * page_size,
593 mmap_prot(),
594 mmap_flags(),
595 /*fd=*/locked_fd,
596 /*offset=*/0);
597
598 if(ptr == MAP_FAILED) {
599 continue;
600 }
601
602 // lock the data page
603 if(::mlock(static_cast<uint8_t*>(ptr) + page_size, page_size) != 0) {
604 ::munmap(ptr, 3 * page_size);
605 continue;
606 }
607
608 #if defined(MADV_DONTDUMP)
609 // we ignore errors here, as DONTDUMP is just a bonus
610 ::madvise(static_cast<uint8_t*>(ptr) + page_size, page_size, MADV_DONTDUMP);
611 #endif
612
613 #elif defined(BOTAN_TARGET_OS_HAS_VIRTUAL_LOCK)
614 ptr = ::VirtualAlloc(nullptr, 3 * page_size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
615
616 if(ptr == nullptr)
617 continue;
618
619 if(::VirtualLock(static_cast<uint8_t*>(ptr) + page_size, page_size) == 0) {
620 ::VirtualFree(ptr, 0, MEM_RELEASE);
621 continue;
622 }
623 #endif
624
625 std::memset(ptr, 0, 3 * page_size); // zero data page and both guard pages
626
627 #if defined(BOTAN_TARGET_OS_HAS_PRCTL) && defined(PR_SET_VMA) && defined(PR_SET_VMA_ANON_NAME)
628 // Attempt to name the data page
629 static constexpr char page_name[] = "Botan mlock pool";
630 // NOLINTNEXTLINE(*-vararg)
631 const int rc = ::prctl(PR_SET_VMA, PR_SET_VMA_ANON_NAME, ptr, 3 * page_size, page_name);
632 BOTAN_UNUSED(rc);
633 #endif
634
635 // Make guard page preceding the data page
636 page_prohibit_access(static_cast<uint8_t*>(ptr));
637 // Make guard page following the data page
638 page_prohibit_access(static_cast<uint8_t*>(ptr) + 2 * page_size);
639
640 result.push_back(static_cast<uint8_t*>(ptr) + page_size);
641 }
642#else
643 BOTAN_UNUSED(count);
644#endif
645
646 return result;
647}
#define BOTAN_UNUSED
Definition assert.h:151
void page_prohibit_access(void *page)
Definition os_utils.cpp:663
size_t system_page_size()
Definition os_utils.cpp:390

References BOTAN_UNUSED, page_prohibit_access(), and system_page_size().

Referenced by Botan::mlock_allocator::mlock_allocator().

◆ format_time()

std::string Botan::OS::format_time ( time_t time,
const std::string & format )

Format a time

Converts the time_t to a local time representation, then invokes std::put_time with the specified format.

Definition at line 366 of file os_utils.cpp.

366 {
367 std::tm tm{};
368
369#if defined(BOTAN_TARGET_OS_HAS_WIN32)
370 if(::localtime_s(&tm, &time) != 0) {
371 throw Encoding_Error("Could not convert time_t to localtime");
372 }
373#elif defined(BOTAN_TARGET_OS_HAS_POSIX1)
374 if(::localtime_r(&time, &tm) == nullptr) {
375 throw Encoding_Error("Could not convert time_t to localtime");
376 }
377#else
378 if(auto tmp = std::localtime(&time)) {
379 tm = *tmp;
380 } else {
381 throw Encoding_Error("Could not convert time_t to localtime");
382 }
383#endif
384
385 std::ostringstream oss;
386 oss << std::put_time(&tm, format.c_str());
387 return oss.str();
388}

◆ free_locked_pages()

void Botan::OS::free_locked_pages ( const std::vector< void * > & pages)

Free memory allocated by allocate_locked_pages

Parameters
pagesa list of pages returned by allocate_locked_pages

Definition at line 725 of file os_utils.cpp.

725 {
726 const size_t page_size = OS::system_page_size();
727
728 for(void* ptr : pages) {
729 secure_scrub_memory(ptr, page_size);
730
731 // ptr points to the data page, guard pages are before and after
732 page_allow_access(static_cast<uint8_t*>(ptr) - page_size);
733 page_allow_access(static_cast<uint8_t*>(ptr) + page_size);
734
735#if defined(BOTAN_TARGET_OS_HAS_POSIX1) && defined(BOTAN_TARGET_OS_HAS_POSIX_MLOCK)
736 ::munlock(ptr, page_size);
737 ::munmap(static_cast<uint8_t*>(ptr) - page_size, 3 * page_size);
738#elif defined(BOTAN_TARGET_OS_HAS_VIRTUAL_LOCK)
739 ::VirtualUnlock(ptr, page_size);
740 ::VirtualFree(static_cast<uint8_t*>(ptr) - page_size, 0, MEM_RELEASE);
741#endif
742 }
743}
void page_allow_access(void *page)
Definition os_utils.cpp:649
void secure_scrub_memory(void *ptr, size_t n)
Definition mem_utils.cpp:24

References page_allow_access(), Botan::secure_scrub_memory(), and system_page_size().

Referenced by Botan::mlock_allocator::mlock_allocator(), and Botan::mlock_allocator::~mlock_allocator().

◆ get_auxval_hwcap()

std::optional< std::pair< unsigned long, unsigned long > > Botan::OS::get_auxval_hwcap ( )

If this system supports getauxval (or an equivalent interface, like FreeBSD's elf_aux_info) queries AT_HWCAP and AT_HWCAP2 and returns both.

Otherwise returns nullopt.

Definition at line 137 of file os_utils.cpp.

137 {
138 if(const auto hwcap = get_auxval(auxval_hwcap())) {
139 // If hwcap worked/was valid, we don't require hwcap2 to also
140 // succeed but instead will return zeros if it failed.
141 const auto hwcap2 = get_auxval(auxval_hwcap2()).value_or(0);
142 return std::make_pair(*hwcap, hwcap2);
143 } else {
144 return {};
145 }
146}

◆ get_cpu_available()

size_t Botan::OS::get_cpu_available ( )

Definition at line 241 of file os_utils.cpp.

241 {
242#if defined(BOTAN_TARGET_OS_HAS_POSIX1)
243
244 #if defined(_SC_NPROCESSORS_ONLN)
245 const long cpu_online = ::sysconf(_SC_NPROCESSORS_ONLN);
246 if(cpu_online > 0) {
247 return static_cast<size_t>(cpu_online);
248 }
249 #endif
250
251 #if defined(_SC_NPROCESSORS_CONF)
252 const long cpu_conf = ::sysconf(_SC_NPROCESSORS_CONF);
253 if(cpu_conf > 0) {
254 return static_cast<size_t>(cpu_conf);
255 }
256 #endif
257
258#endif
259
260#if defined(BOTAN_TARGET_OS_HAS_THREADS)
261 // hardware_concurrency is allowed to return 0 if the value is not
262 // well defined or not computable.
263 const size_t hw_concur = std::thread::hardware_concurrency();
264
265 if(hw_concur > 0) {
266 return hw_concur;
267 }
268#endif
269
270 return 1;
271}

◆ get_cpu_cycle_counter()

uint64_t Botan::OS::get_cpu_cycle_counter ( )
Returns
CPU processor clock, if available

On Windows, calls QueryPerformanceCounter.

Under GCC or Clang on supported platforms the hardware cycle counter is queried. Currently supported processors are x86, PPC, Alpha, SPARC, IA-64, S/390x, and HP-PA. If no CPU cycle counter is available on this system, returns zero.

Definition at line 170 of file os_utils.cpp.

170 {
171 uint64_t rtc = 0;
172
173#if defined(BOTAN_TARGET_OS_HAS_WIN32)
174 LARGE_INTEGER tv;
175 ::QueryPerformanceCounter(&tv);
176 rtc = tv.QuadPart;
177
178#elif defined(BOTAN_USE_GCC_INLINE_ASM)
179
180 // NOLINTBEGIN(*-no-assembler)
181
182 #if defined(BOTAN_TARGET_ARCH_IS_X86_64)
183
184 uint32_t rtc_low = 0; // NOLINT(*-const-correctness) clang-tidy doesn't understand inline asm
185 uint32_t rtc_high = 0; // NOLINT(*-const-correctness) clang-tidy doesn't understand inline asm
186 asm volatile("rdtsc" : "=d"(rtc_high), "=a"(rtc_low));
187 rtc = (static_cast<uint64_t>(rtc_high) << 32) | rtc_low;
188
189 #elif defined(BOTAN_TARGET_ARCH_IS_X86_FAMILY) && defined(BOTAN_HAS_CPUID)
190
192 uint32_t rtc_low = 0;
193 uint32_t rtc_high = 0;
194 asm volatile("rdtsc" : "=d"(rtc_high), "=a"(rtc_low));
195 rtc = (static_cast<uint64_t>(rtc_high) << 32) | rtc_low;
196 }
197
198 #elif defined(BOTAN_TARGET_ARCH_IS_PPC64)
199
200 for(;;) {
201 uint32_t rtc_low = 0;
202 uint32_t rtc_high = 0;
203 uint32_t rtc_high2 = 0;
204 asm volatile("mftbu %0" : "=r"(rtc_high));
205 asm volatile("mftb %0" : "=r"(rtc_low));
206 asm volatile("mftbu %0" : "=r"(rtc_high2));
207
208 if(rtc_high == rtc_high2) {
209 rtc = (static_cast<uint64_t>(rtc_high) << 32) | rtc_low;
210 break;
211 }
212 }
213
214 #elif defined(BOTAN_TARGET_ARCH_IS_ALPHA)
215 asm volatile("rpcc %0" : "=r"(rtc));
216
217 #elif defined(BOTAN_TARGET_ARCH_IS_SPARC64) && !defined(BOTAN_TARGET_OS_IS_OPENBSD)
218 // OpenBSD does not trap access to the %tick register so we avoid it there
219 asm volatile("rd %%tick, %0" : "=r"(rtc));
220
221 #elif defined(BOTAN_TARGET_ARCH_IS_IA64)
222 asm volatile("mov %0=ar.itc" : "=r"(rtc));
223
224 #elif defined(BOTAN_TARGET_ARCH_IS_S390X)
225 asm volatile("stck 0(%0)" : : "a"(&rtc) : "memory", "cc");
226
227 #elif defined(BOTAN_TARGET_ARCH_IS_HPPA)
228 asm volatile("mfctl 16,%0" : "=r"(rtc)); // 64-bit only?
229
230 #else
231 //#warning "OS::get_cpu_cycle_counter not implemented"
232 #endif
233
234 // NOLINTEND(*-no-assembler)
235
236#endif
237
238 return rtc;
239}
static bool has(CPUID::Feature feat)
Definition cpuid.h:93

References Botan::CPUID::has(), and Botan::CPUFeature::RDTSC.

Referenced by get_high_resolution_clock().

◆ get_fork_generation()

uint64_t Botan::OS::get_fork_generation ( )
Returns
an integer which increments every time the process forks.

If the system does not have any notion of fork() this returns constant 0

Definition at line 704 of file os_utils.cpp.

704 {
705#if defined(BOTAN_TARGET_OS_HAS_POSIX1)
706 static std::once_flag g_atfork_initialized;
707 std::call_once(g_atfork_initialized, setup_atfork);
708 return g_fork_generation;
709#else
710 return 0;
711#endif
712}

Referenced by Botan::OS::Fork_Detector::fork_detected(), and Botan::OS::Fork_Detector::Fork_Detector().

◆ get_high_resolution_clock()

uint64_t Botan::OS::get_high_resolution_clock ( )

Definition at line 273 of file os_utils.cpp.

273 {
274 if(const uint64_t cpu_clock = OS::get_cpu_cycle_counter()) {
275 return cpu_clock;
276 }
277
278#if defined(BOTAN_TARGET_OS_IS_EMSCRIPTEN)
279 return emscripten_get_now();
280#endif
281
282 /*
283 If we got here either we either don't have an asm instruction
284 above, or (for x86) RDTSC is not available at runtime. Try some
285 clock_gettimes and return the first one that works, or otherwise
286 fall back to std::chrono.
287 */
288
289#if defined(BOTAN_TARGET_OS_HAS_CLOCK_GETTIME)
290
291 // The ordering here is somewhat arbitrary...
292 const clockid_t clock_types[] = {
293 #if defined(CLOCK_MONOTONIC_HR)
294 CLOCK_MONOTONIC_HR,
295 #endif
296 #if defined(CLOCK_MONOTONIC_RAW)
297 CLOCK_MONOTONIC_RAW,
298 #endif
299 #if defined(CLOCK_MONOTONIC)
300 CLOCK_MONOTONIC,
301 #endif
302 #if defined(CLOCK_PROCESS_CPUTIME_ID)
303 CLOCK_PROCESS_CPUTIME_ID,
304 #endif
305 #if defined(CLOCK_THREAD_CPUTIME_ID)
306 CLOCK_THREAD_CPUTIME_ID,
307 #endif
308 };
309
310 for(const clockid_t clock : clock_types) {
311 struct timespec ts {};
312
313 if(::clock_gettime(clock, &ts) == 0) {
314 return (static_cast<uint64_t>(ts.tv_sec) * 1000000000) + static_cast<uint64_t>(ts.tv_nsec);
315 }
316 }
317#endif
318
319#if defined(BOTAN_TARGET_OS_HAS_SYSTEM_CLOCK)
320 // Plain C++11 fallback
321 const auto now = std::chrono::high_resolution_clock::now().time_since_epoch();
322 return std::chrono::duration_cast<std::chrono::nanoseconds>(now).count();
323#else
324 return 0;
325#endif
326}
uint64_t BOTAN_TEST_API get_cpu_cycle_counter()
Definition os_utils.cpp:170

References get_cpu_cycle_counter().

◆ get_memory_locking_limit()

size_t Botan::OS::get_memory_locking_limit ( )
Returns
maximum amount of memory (in bytes) Botan could/should hypothetically allocate for the memory poool. Reads environment variable "BOTAN_MLOCK_POOL_SIZE", set to "0" to disable pool.

Definition at line 410 of file os_utils.cpp.

410 {
411 /*
412 * Linux defaults to only 64 KiB of mlockable memory per process (too small)
413 * but BSDs offer a small fraction of total RAM (more than we need). Bound the
414 * total mlock size to 512 KiB which is enough to run the entire test suite
415 * without spilling to non-mlock memory (and thus presumably also enough for
416 * many useful programs), but small enough that we should not cause problems
417 * even if many processes are mlocking on the same machine.
418 */
419 const size_t max_locked_kb = 512;
420
421 /*
422 * If RLIMIT_MEMLOCK is not defined, likely the OS does not support
423 * unprivileged mlock calls.
424 */
425#if defined(RLIMIT_MEMLOCK) && defined(BOTAN_TARGET_OS_HAS_POSIX1) && defined(BOTAN_TARGET_OS_HAS_POSIX_MLOCK)
426 const size_t mlock_requested =
427 std::min<size_t>(read_env_variable_sz("BOTAN_MLOCK_POOL_SIZE", max_locked_kb), max_locked_kb);
428
429 if(mlock_requested > 0) {
430 struct ::rlimit limits {};
431
432 ::getrlimit(RLIMIT_MEMLOCK, &limits);
433
434 if(limits.rlim_cur < limits.rlim_max) {
435 limits.rlim_cur = limits.rlim_max;
436 ::setrlimit(RLIMIT_MEMLOCK, &limits);
437 ::getrlimit(RLIMIT_MEMLOCK, &limits);
438 }
439
440 return std::min<size_t>(limits.rlim_cur, mlock_requested * 1024);
441 }
442
443#elif defined(BOTAN_TARGET_OS_HAS_VIRTUAL_LOCK)
444 const size_t mlock_requested =
445 std::min<size_t>(read_env_variable_sz("BOTAN_MLOCK_POOL_SIZE", max_locked_kb), max_locked_kb);
446
447 SIZE_T working_min = 0, working_max = 0;
448 if(!::GetProcessWorkingSetSize(::GetCurrentProcess(), &working_min, &working_max)) {
449 return 0;
450 }
451
452 // According to Microsoft MSDN:
453 // The maximum number of pages that a process can lock is equal to the number of pages in its minimum working set minus a small overhead
454 // In the book "Windows Internals Part 2": the maximum lockable pages are minimum working set size - 8 pages
455 // But the information in the book seems to be inaccurate/outdated
456 // I've tested this on Windows 8.1 x64, Windows 10 x64 and Windows 7 x86
457 // On all three OS the value is 11 instead of 8
458 const size_t overhead = OS::system_page_size() * 11;
459 if(working_min > overhead) {
460 const size_t lockable_bytes = working_min - overhead;
461 return std::min<size_t>(lockable_bytes, mlock_requested * 1024);
462 }
463#else
464 // Not supported on this platform
465 BOTAN_UNUSED(max_locked_kb);
466#endif
467
468 return 0;
469}
size_t read_env_variable_sz(std::string_view var_name, size_t def_value=0)
Definition os_utils.cpp:507

References BOTAN_UNUSED, read_env_variable_sz(), and system_page_size().

Referenced by Botan::mlock_allocator::mlock_allocator().

◆ get_process_id()

uint32_t Botan::OS::get_process_id ( )
Returns
process ID assigned by the operating system.

On Unix and Windows systems, this always returns a result

On systems where there is no processes to speak of (for example on baremetal systems or within a unikernel), this function returns zero.

Definition at line 78 of file os_utils.cpp.

78 {
79#if defined(BOTAN_TARGET_OS_HAS_POSIX1)
80 return ::getpid();
81#elif defined(BOTAN_TARGET_OS_HAS_WIN32)
82 return ::GetCurrentProcessId();
83#elif defined(BOTAN_TARGET_OS_IS_LLVM) || defined(BOTAN_TARGET_OS_IS_NONE)
84 return 0; // truly no meaningful value
85#else
86 #error "Missing get_process_id"
87#endif
88}

Referenced by Botan::OS::Fork_Detector::fork_detected(), and Botan::OS::Fork_Detector::Fork_Detector().

◆ get_system_timestamp_ns()

uint64_t Botan::OS::get_system_timestamp_ns ( )
Returns
system clock (reflecting wall clock) with best resolution available, normalized to nanoseconds resolution, using Unix epoch.

If the system does not have a real time clock this function will throw Not_Implemented

Definition at line 328 of file os_utils.cpp.

328 {
329#if defined(BOTAN_TARGET_OS_HAS_CLOCK_GETTIME)
330 struct timespec ts {};
331
332 if(::clock_gettime(CLOCK_REALTIME, &ts) == 0) {
333 return (static_cast<uint64_t>(ts.tv_sec) * 1000000000) + static_cast<uint64_t>(ts.tv_nsec);
334 }
335#endif
336
337#if defined(BOTAN_TARGET_OS_HAS_SYSTEM_CLOCK)
338 const auto now = std::chrono::system_clock::now().time_since_epoch();
339 return std::chrono::duration_cast<std::chrono::nanoseconds>(now).count();
340#else
341 throw Not_Implemented("OS::get_system_timestamp_ns this system does not support a clock");
342#endif
343}

◆ get_thread_cpu_time_ns()

std::optional< uint64_t > Botan::OS::get_thread_cpu_time_ns ( )
Returns
CPU time consumed by the calling thread, normalized to nanoseconds resolution, or nullopt if the system does not support it or if the reported resolution is too coarse.

The epoch is arbitrary; only differences between calls are meaningful.

Definition at line 345 of file os_utils.cpp.

345 {
346#if defined(BOTAN_TARGET_OS_HAS_CLOCK_GETTIME) && defined(CLOCK_THREAD_CPUTIME_ID)
347 // Tick-based accounting is useless for timing a single call, so only
348 // use this clock if it claims fine resolution
349 static const bool usable = []() {
350 struct timespec res {};
351 return ::clock_getres(CLOCK_THREAD_CPUTIME_ID, &res) == 0 && res.tv_sec == 0 && res.tv_nsec <= 10000;
352 }();
353
354 if(usable) {
355 struct timespec ts {};
356
357 if(::clock_gettime(CLOCK_THREAD_CPUTIME_ID, &ts) == 0) {
358 return (static_cast<uint64_t>(ts.tv_sec) * 1000000000) + static_cast<uint64_t>(ts.tv_nsec);
359 }
360 }
361#endif
362
363 return std::nullopt;
364}

Referenced by Botan::measure_cost().

◆ open_socket()

std::unique_ptr< OS::Socket > Botan::OS::open_socket ( std::string_view hostname,
std::string_view service,
std::chrono::milliseconds timeout )

Open up a socket. Will throw on error. Returns null if sockets are not available on this platform.

The timeout is a deadline for the lifetime of the socket: it bounds connecting plus all subsequent reads and writes combined.

Definition at line 491 of file socket.cpp.

493 {
494#if defined(BOTAN_HAS_BOOST_ASIO)
495 return std::make_unique<Asio_Socket>(hostname, service, timeout);
496
497#elif defined(BOTAN_TARGET_OS_HAS_SOCKETS) || defined(BOTAN_TARGET_OS_HAS_WINSOCK2)
498 return std::make_unique<BSD_Socket>(hostname, service, timeout);
499
500#else
501 BOTAN_UNUSED(hostname, service, timeout);
502 // No sockets for you
503 return std::unique_ptr<Socket>();
504#endif
505}

References BOTAN_UNUSED.

◆ open_socket_udp() [1/2]

std::unique_ptr< OS::SocketUDP > Botan::OS::open_socket_udp ( std::string_view hostname,
std::string_view service,
std::chrono::microseconds timeout )

Open up a socket. Will throw on error. Returns null if sockets are not available on this platform.

Definition at line 404 of file socket_udp.cpp.

406 {
407#if defined(BOTAN_HAS_BOOST_ASIO)
408 return std::make_unique<Asio_SocketUDP>(hostname, service, timeout);
409#elif defined(BOTAN_TARGET_OS_HAS_SOCKETS) || defined(BOTAN_TARGET_OS_HAS_WINSOCK2)
410 return std::make_unique<BSD_SocketUDP>(hostname, service, timeout);
411#else
412 BOTAN_UNUSED(hostname);
413 BOTAN_UNUSED(service);
414 BOTAN_UNUSED(timeout);
415 return std::unique_ptr<OS::SocketUDP>();
416#endif
417}

References BOTAN_UNUSED.

Referenced by Botan::Roughtime::online_request(), and open_socket_udp().

◆ open_socket_udp() [2/2]

std::unique_ptr< OS::SocketUDP > Botan::OS::open_socket_udp ( std::string_view uri,
std::chrono::microseconds timeout )

Open up a socket. Will throw on error. Returns null if sockets are not available on this platform.

Definition at line 419 of file socket_udp.cpp.

419 {
420 const auto authority = URI::Authority::from_string(uri_string);
421 if(!authority.has_value() || !authority->port().has_value()) {
422 throw Invalid_Argument("UDP port not specified");
423 }
424 return open_socket_udp(authority->host_to_string(), std::to_string(*authority->port()), timeout);
425}
static std::optional< Authority > from_string(std::string_view raw)
Definition uri.cpp:247
std::unique_ptr< SocketUDP > BOTAN_TEST_API open_socket_udp(std::string_view hostname, std::string_view service, std::chrono::microseconds timeout)

References Botan::URI::Authority::from_string(), and open_socket_udp().

◆ page_allow_access()

void Botan::OS::page_allow_access ( void * page)

Set the MMU to allow R/W access to this page

Definition at line 649 of file os_utils.cpp.

649 {
650#if defined(BOTAN_TARGET_OS_HAS_POSIX1)
651 const size_t page_size = OS::system_page_size();
652 ::mprotect(page, page_size, PROT_READ | PROT_WRITE);
653#elif defined(BOTAN_TARGET_OS_HAS_VIRTUAL_LOCK)
654 const size_t page_size = OS::system_page_size();
655 DWORD old_perms = 0;
656 ::VirtualProtect(page, page_size, PAGE_READWRITE, &old_perms);
657 BOTAN_UNUSED(old_perms);
658#else
659 BOTAN_UNUSED(page);
660#endif
661}

References BOTAN_UNUSED, and system_page_size().

Referenced by Botan::Memory_Pool::allocate(), free_locked_pages(), and Botan::Memory_Pool::~Memory_Pool().

◆ page_prohibit_access()

void Botan::OS::page_prohibit_access ( void * page)

Set the MMU to prohibit access to this page

Definition at line 663 of file os_utils.cpp.

663 {
664#if defined(BOTAN_TARGET_OS_HAS_POSIX1)
665 const size_t page_size = OS::system_page_size();
666 ::mprotect(page, page_size, PROT_NONE);
667#elif defined(BOTAN_TARGET_OS_HAS_VIRTUAL_LOCK)
668 const size_t page_size = OS::system_page_size();
669 DWORD old_perms = 0;
670 ::VirtualProtect(page, page_size, PAGE_NOACCESS, &old_perms);
671 BOTAN_UNUSED(old_perms);
672#else
673 BOTAN_UNUSED(page);
674#endif
675}

References BOTAN_UNUSED, and system_page_size().

Referenced by allocate_locked_pages(), Botan::Memory_Pool::deallocate(), and Botan::Memory_Pool::Memory_Pool().

◆ read_env_variable()

bool Botan::OS::read_env_variable ( std::string & value_out,
std::string_view var_name )

Read the value of an environment variable, setting it to value_out if it exists. Returns false and sets value_out to empty string if no such variable is set. If the process seems to be running in a privileged state (such as setuid) then always returns false and does not examine the environment.

Definition at line 471 of file os_utils.cpp.

471 {
472 value_out = "";
473
474 if(running_in_privileged_state()) {
475 return false;
476 }
477
478#if defined(BOTAN_TARGET_OS_HAS_WIN32) && \
479 (defined(BOTAN_BUILD_COMPILER_IS_MSVC) || defined(BOTAN_BUILD_COMPILER_IS_CLANGCL))
480 const std::string name(name_view);
481
482 // First query the required buffer size; req_size is 0 if the variable is not set
483 size_t req_size = 0;
484 if(getenv_s(&req_size, nullptr, 0, name.c_str()) != 0 || req_size == 0) {
485 return false;
486 }
487
488 // The reported size includes the terminating \0
489 std::string val(req_size, '\0');
490 if(getenv_s(&req_size, val.data(), val.size(), name.c_str()) != 0) {
491 return false;
492 }
493
494 value_out = std::string(val.c_str());
495 return true;
496#else
497 const std::string name(name_view);
498 if(const char* val = std::getenv(name.c_str())) {
499 value_out = val;
500 return true;
501 }
502#endif
503
504 return false;
505}
const char * name
Definition ffi_tls.h:59

References name.

Referenced by Botan_FFI::ffi_error_exception_thrown(), and read_env_variable_sz().

◆ read_env_variable_sz()

size_t Botan::OS::read_env_variable_sz ( std::string_view var_name,
size_t def_value = 0 )

Read the value of an environment variable and convert it to an integer. If not set or conversion fails, returns the default value.

If the process seems to be running in a privileged state (such as setuid) then always returns nullptr, similar to glibc's secure_getenv.

Definition at line 507 of file os_utils.cpp.

507 {
508 std::string value;
509 if(read_env_variable(value, name) && !value.empty()) {
510 if(const auto sz = parse_sz(value)) {
511 return *sz;
512 }
513 }
514
515 return def;
516}
bool read_env_variable(std::string &value_out, std::string_view var_name)
Definition os_utils.cpp:471
std::optional< size_t > parse_sz(std::string_view input, bool require_canonical)
Definition parsing.cpp:71

References name, Botan::parse_sz(), and read_env_variable().

Referenced by get_memory_locking_limit().

◆ run_cpu_instruction_probe()

int Botan::OS::run_cpu_instruction_probe ( const std::function< int()> & probe_fn)

Run a probe instruction to test for support for a CPU instruction. Runs in system-specific env that catches illegal instructions; this function always fails if the OS doesn't provide this. Returns value of probe_fn, if it could run. If error occurs, returns negative number. This allows probe_fn to indicate errors of its own, if it wants. For example the instruction might not only be only available on some CPUs, but also buggy on some subset of these - the probe function can test to make sure the instruction works properly before indicating that the instruction is available.

Warning
on Unix systems this temporarily replaces the process-wide SIGILL handler. Probes are serialized, and a SIGILL raised by another thread while a probe is running is forwarded to the previous handler, but any such fault on the probing thread (other than the probe itself) will be misreported.

If probe_fn throws an exception the result is undefined.

Return codes: -1 illegal instruction detected

Definition at line 814 of file os_utils.cpp.

814 {
815 volatile int probe_result = -3;
816
817#if defined(BOTAN_TARGET_OS_HAS_POSIX1) && !defined(BOTAN_TARGET_OS_IS_EMSCRIPTEN)
818
819 #if defined(BOTAN_TARGET_OS_HAS_THREADS)
820 // Signal dispositions are process wide, so only run one probe at a time
821 static std::mutex g_sigill_probe_mutex;
822 const std::lock_guard<std::mutex> lock(g_sigill_probe_mutex);
823 #endif
824
825 struct sigaction sigaction {};
826
827 sigaction.sa_handler = botan_sigill_handler;
828 sigemptyset(&sigaction.sa_mask);
829 sigaction.sa_flags = 0;
830
831 g_sigill_probe_thread = ::pthread_self();
832
833 int rc = ::sigaction(SIGILL, &sigaction, &g_sigill_prev_action);
834
835 if(rc != 0) {
836 throw System_Error("run_cpu_instruction_probe sigaction failed", errno);
837 }
838
839 rc = sigsetjmp(g_sigill_jmp_buf, /*save sigs*/ 1);
840
841 if(rc == 0) {
842 // first call to sigsetjmp
843 probe_result = probe_fn();
844 } else if(rc == 1) {
845 // non-local return from siglongjmp in signal handler: return error
846 probe_result = -1;
847 }
848
849 // Restore old SIGILL handler, if any
850 rc = ::sigaction(SIGILL, &g_sigill_prev_action, nullptr);
851 if(rc != 0) {
852 throw System_Error("run_cpu_instruction_probe sigaction restore failed", errno);
853 }
854
855#else
856 BOTAN_UNUSED(probe_fn);
857#endif
858
859 return probe_result;
860}
secure_vector< T > lock(const std::vector< T > &in)
Definition secmem.h:145

References BOTAN_UNUSED, and Botan::lock().

◆ suppress_echo_on_terminal()

std::unique_ptr< OS::Echo_Suppression > Botan::OS::suppress_echo_on_terminal ( )

Suppress echo on the terminal Returns null if this operation is not supported on the current system.

Definition at line 862 of file os_utils.cpp.

862 {
863#if defined(BOTAN_TARGET_OS_HAS_POSIX1)
864 class POSIX_Echo_Suppression final : public Echo_Suppression {
865 public:
866 POSIX_Echo_Suppression() : m_stdin_fd(fileno(stdin)), m_old_termios{} {
867 if(::tcgetattr(m_stdin_fd, &m_old_termios) != 0) {
868 throw System_Error("Getting terminal status failed", errno);
869 }
870
871 struct termios noecho_flags = m_old_termios;
872 noecho_flags.c_lflag &= ~ECHO;
873 noecho_flags.c_lflag |= ECHONL;
874
875 if(::tcsetattr(m_stdin_fd, TCSANOW, &noecho_flags) != 0) {
876 throw System_Error("Clearing terminal echo bit failed", errno);
877 }
878 }
879
880 void reenable_echo() override {
881 if(m_stdin_fd > 0) {
882 if(::tcsetattr(m_stdin_fd, TCSANOW, &m_old_termios) != 0) {
883 throw System_Error("Restoring terminal echo bit failed", errno);
884 }
885 m_stdin_fd = -1;
886 }
887 }
888
889 ~POSIX_Echo_Suppression() override {
890 try {
892 } catch(...) {}
893 }
894
895 POSIX_Echo_Suppression(const POSIX_Echo_Suppression& other) = delete;
896 POSIX_Echo_Suppression(POSIX_Echo_Suppression&& other) = delete;
897 POSIX_Echo_Suppression& operator=(const POSIX_Echo_Suppression& other) = delete;
898 POSIX_Echo_Suppression& operator=(POSIX_Echo_Suppression&& other) = delete;
899
900 private:
901 int m_stdin_fd;
902 struct termios m_old_termios;
903 };
904
905 return std::make_unique<POSIX_Echo_Suppression>();
906
907#elif defined(BOTAN_TARGET_OS_HAS_WIN32)
908
909 class Win32_Echo_Suppression final : public Echo_Suppression {
910 public:
911 Win32_Echo_Suppression() : m_input_handle(::GetStdHandle(STD_INPUT_HANDLE)) {
912 if(::GetConsoleMode(m_input_handle, &m_console_state) == 0)
913 throw System_Error("Getting console mode failed", ::GetLastError());
914
915 DWORD new_mode = ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT;
916 if(::SetConsoleMode(m_input_handle, new_mode) == 0)
917 throw System_Error("Setting console mode failed", ::GetLastError());
918 }
919
920 void reenable_echo() override {
921 if(m_input_handle != INVALID_HANDLE_VALUE) {
922 if(::SetConsoleMode(m_input_handle, m_console_state) == 0)
923 throw System_Error("Setting console mode failed", ::GetLastError());
924 m_input_handle = INVALID_HANDLE_VALUE;
925 }
926 }
927
928 ~Win32_Echo_Suppression() override {
929 try {
930 reenable_echo();
931 } catch(...) {}
932 }
933
934 Win32_Echo_Suppression(const Win32_Echo_Suppression& other) = delete;
935 Win32_Echo_Suppression(Win32_Echo_Suppression&& other) = delete;
936 Win32_Echo_Suppression& operator=(const Win32_Echo_Suppression& other) = delete;
937 Win32_Echo_Suppression& operator=(Win32_Echo_Suppression&& other) = delete;
938
939 private:
940 HANDLE m_input_handle;
941 DWORD m_console_state;
942 };
943
944 return std::make_unique<Win32_Echo_Suppression>();
945
946#else
947
948 // Not supported on this platform, return null
949 return nullptr;
950#endif
951}
virtual void reenable_echo()=0

◆ system_page_size()

size_t Botan::OS::system_page_size ( )

Return the size of a memory page, if that can be derived on the current system. Otherwise returns some default value (eg 4096)

Definition at line 390 of file os_utils.cpp.

390 {
391 const size_t default_page_size = 4096;
392
393#if defined(BOTAN_TARGET_OS_HAS_POSIX1)
394 const long p = ::sysconf(_SC_PAGESIZE);
395 if(p > 1) {
396 return static_cast<size_t>(p);
397 } else {
398 return default_page_size;
399 }
400#elif defined(BOTAN_TARGET_OS_HAS_VIRTUAL_LOCK)
401 BOTAN_UNUSED(default_page_size);
402 SYSTEM_INFO sys_info;
403 ::GetSystemInfo(&sys_info);
404 return sys_info.dwPageSize;
405#else
406 return default_page_size;
407#endif
408}

References BOTAN_UNUSED.

Referenced by allocate_locked_pages(), free_locked_pages(), get_memory_locking_limit(), Botan::mlock_allocator::mlock_allocator(), page_allow_access(), and page_prohibit_access().