Path: blob/main/sys/contrib/openzfs/lib/libspl/random.c
96339 views
// SPDX-License-Identifier: CDDL-1.01/*2* CDDL HEADER START3*4* The contents of this file are subject to the terms of the5* Common Development and Distribution License (the "License").6* You may not use this file except in compliance with the License.7*8* You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE9* or https://opensource.org/licenses/CDDL-1.0.10* See the License for the specific language governing permissions11* and limitations under the License.12*13* When distributing Covered Code, include this CDDL HEADER in each14* file and include the License file at usr/src/OPENSOLARIS.LICENSE.15* If applicable, add the following below this CDDL HEADER, with the16* fields enclosed by brackets "[]" replaced with your own identifying17* information: Portions Copyright [yyyy] [name of copyright owner]18*19* CDDL HEADER END20*/21/*22* Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.23* Copyright (c) 2012, 2018 by Delphix. All rights reserved.24* Copyright (c) 2016 Actifio, Inc. All rights reserved.25* Copyright (c) 2025, Klara, Inc.26*/2728#include <stdint.h>29#include <fcntl.h>30#include <assert.h>31#include <sys/random.h>32#include "libspl_impl.h"3334#define RANDOM_PATH "/dev/random"35#define URANDOM_PATH "/dev/urandom"3637static int random_fd = -1, urandom_fd = -1;3839static boolean_t force_pseudo = B_FALSE;4041void42random_init(void)43{44/* Handle multiple calls. */45if (random_fd != -1) {46ASSERT3U(urandom_fd, !=, -1);47return;48}4950VERIFY((random_fd = open(RANDOM_PATH, O_RDONLY | O_CLOEXEC)) != -1);51VERIFY((urandom_fd = open(URANDOM_PATH, O_RDONLY | O_CLOEXEC)) != -1);52}5354void55random_fini(void)56{57close(random_fd);58close(urandom_fd);5960random_fd = -1;61urandom_fd = -1;62}6364void65random_force_pseudo(boolean_t onoff)66{67force_pseudo = onoff;68}6970static int71random_get_bytes_common(uint8_t *ptr, size_t len, int fd)72{73size_t resid = len;74ssize_t bytes;7576ASSERT(fd != -1);7778while (resid != 0) {79bytes = read(fd, ptr, resid);80ASSERT3S(bytes, >=, 0);81ptr += bytes;82resid -= bytes;83}8485return (0);86}8788int89random_get_bytes(uint8_t *ptr, size_t len)90{91if (force_pseudo)92return (random_get_pseudo_bytes(ptr, len));93return (random_get_bytes_common(ptr, len, random_fd));94}9596int97random_get_pseudo_bytes(uint8_t *ptr, size_t len)98{99return (random_get_bytes_common(ptr, len, urandom_fd));100}101102103