Path: blob/master/Utilities/cmlibuv/src/unix/random-devurandom.c
3156 views
/* Copyright libuv contributors. All rights reserved.1*2* Permission is hereby granted, free of charge, to any person obtaining a copy3* of this software and associated documentation files (the "Software"), to4* deal in the Software without restriction, including without limitation the5* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or6* sell copies of the Software, and to permit persons to whom the Software is7* furnished to do so, subject to the following conditions:8*9* The above copyright notice and this permission notice shall be included in10* all copies or substantial portions of the Software.11*12* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR13* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,14* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE15* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER16* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING17* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS18* IN THE SOFTWARE.19*/2021#include "uv.h"22#include "internal.h"2324#include <sys/stat.h>25#include <unistd.h>2627static uv_once_t once = UV_ONCE_INIT;28static int status;293031int uv__random_readpath(const char* path, void* buf, size_t buflen) {32struct stat s;33size_t pos;34ssize_t n;35int fd;3637fd = uv__open_cloexec(path, O_RDONLY);3839if (fd < 0)40return fd;4142if (fstat(fd, &s)) {43uv__close(fd);44return UV__ERR(errno);45}4647if (!S_ISCHR(s.st_mode)) {48uv__close(fd);49return UV_EIO;50}5152for (pos = 0; pos != buflen; pos += n) {53do54n = read(fd, (char*) buf + pos, buflen - pos);55while (n == -1 && errno == EINTR);5657if (n == -1) {58uv__close(fd);59return UV__ERR(errno);60}6162if (n == 0) {63uv__close(fd);64return UV_EIO;65}66}6768uv__close(fd);69return 0;70}717273static void uv__random_devurandom_init(void) {74char c;7576/* Linux's random(4) man page suggests applications should read at least77* once from /dev/random before switching to /dev/urandom in order to seed78* the system RNG. Reads from /dev/random can of course block indefinitely79* until entropy is available but that's the point.80*/81status = uv__random_readpath("/dev/random", &c, 1);82}838485int uv__random_devurandom(void* buf, size_t buflen) {86uv_once(&once, uv__random_devurandom_init);8788if (status != 0)89return status;9091return uv__random_readpath("/dev/urandom", buf, buflen);92}939495