Path: blob/main/contrib/expat/lib/random_dev_urandom.c
213651 views
/*1__ __ _2___\ \/ /_ __ __ _| |_3/ _ \\ /| '_ \ / _` | __|4| __// \| |_) | (_| | |_5\___/_/\_\ .__/ \__,_|\__|6|_| XML parser78Copyright (c) 2017-2026 Sebastian Pipping <[email protected]>9Copyright (c) 2026 Matthew Fernandez <[email protected]>10Licensed under the MIT license:1112Permission is hereby granted, free of charge, to any person obtaining13a copy of this software and associated documentation files (the14"Software"), to deal in the Software without restriction, including15without limitation the rights to use, copy, modify, merge, publish,16distribute, sublicense, and/or sell copies of the Software, and to permit17persons to whom the Software is furnished to do so, subject to the18following conditions:1920The above copyright notice and this permission notice shall be included21in all copies or substantial portions of the Software.2223THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,24EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF25MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN26NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,27DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR28OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE29USE OR OTHER DEALINGS IN THE SOFTWARE.30*/3132#include "random_dev_urandom.h"3334#if ! defined(_POSIX_C_SOURCE) \35|| (defined(_POSIX_C_SOURCE) && (_POSIX_C_SOURCE < 200809L))36# define _POSIX_C_SOURCE 200809L // for O_CLOEXEC37#endif3839#include <errno.h>40#include <fcntl.h> // open41#include <unistd.h> // close4243/* Extract entropy from /dev/urandom */44bool45writeRandomBytes_dev_urandom(void *target, size_t count) {46int success = false; /* full count bytes written? */47size_t bytesWrittenTotal = 0;4849const int fd = open("/dev/urandom", O_RDONLY | O_CLOEXEC);50if (fd < 0) {51return 0;52}5354do {55void *const currentTarget = (void *)((char *)target + bytesWrittenTotal);56const size_t bytesToWrite = count - bytesWrittenTotal;5758errno = 0;5960const ssize_t bytesWrittenMore = read(fd, currentTarget, bytesToWrite);6162if (bytesWrittenMore > 0) {63bytesWrittenTotal += bytesWrittenMore;64if (bytesWrittenTotal >= count)65success = true;66}67} while (! success && (errno == EINTR));6869close(fd);70return success;71}727374