Repository: LadybirdBrowser/ladybird
File: AK/Random.cpp (C++)

Code before:
#endif

static inline ErrorOr<void> csprng(void* const buf, size_t size)
{
    // We shouldn't use OpenSSL's RAND_bytes function here, because we want to avoid adding dependencies to AK.
    // Therefore, we will use the best platform-specific CSPRNG.
#if defined(AK_OS_SERENITY) || defined(AK_OS_ANDROID) || defined(AK_OS_BSD_GENERIC) || defined(AK_OS_HAIKU) || AK_LIBC_GLIBC_PREREQ(2, 36)
    // MacOS and iOS both appear to support arc4random_buf, and AK/Platform.h defines AK_OS_BSD_GENERIC when building for them,
    // so they will be covered by the compile target that uses arc4random_buf.
    //
    // Note that although [SecRandomCopyBytes](https://developer.apple.com/documentation/security/secrandomcopybytes(_:_:_:)) appears to be more commonly used on those platforms,
    // it doesn't seem to be required.
    arc4random_buf(buf, size);
#elif defined(AK_OS_LINUX)
    int ret;
    while (size > 0u) {
        // The possible errors that can be returned here are:
        //
        // EINTR, interrupted by a signal handler.
        // EAGAIN, the requested entropy wasn't available. Only possible if the GRND_NONBLOCK flag is set, which it isn't.
        // EINVAL, invalid flags provided, which there aren't.
        // ENOSYS, the kernel doesn't implement the syscall. The syscall has been available since Linux 3.17, which was released in 2019.
        // EFAULT, the address is outside the accessible space; the caller is responsible for providing a valid address.
        //
        // Therefore, the only somewhat plausible errors are EFAULT and EINTR.
        // Nonetheless, we will check for the possibility of all the error codes out of an abundance of caution.
        ret = getrandom(buf, size, 0);

        if (ret == -1 && errno != EINTR) [[unlikely]]
            return Error::from_errno(errno);

        // Per the manual:
        //
        // > On success, getrandom() returns the number of bytes that were
        // > copied to the buffer buf.  This may be less than the number of
        // > bytes requested via buflen if either GRND_RANDOM was specified in
        // > flags and insufficient entropy was present in the random source or
        // > the system call was interrupted by a signal.
        //
        // > The user of getrandom() *must* always check the return value, to
        // > determine whether either an error occurred or fewer bytes than
        // > requested were returned.
        if (ret > 0) [[likely]] {
            size -= ret;
            buf += ret;
        }
    }
#elif defined(AK_OS_WINDOWS)
    // ProcessPRNG is currently the best option:
    // - It includes very few imports and doesn't create any handles, therefore being the best for sandboxing and reducing unnecessary imports.
    // - The BCryptPrimitives DLL is already being imported by libtommath and probably other dependencies so importing it here doesn't matter.

Review comment (suggestion):
That's a lot of text just to say "we're checking all error cases" - let's put this in the commit message if it's really relevant enough.

Code after:

static inline ErrorOr<void> csprng(void* const buf, size_t size)
{
    // We shouldn't use OpenSSL's RAND_bytes function here, because we want to avoid adding dependencies to AK.
    // Therefore, we will use the best platform-specific CSPRNG.
#if defined(AK_OS_SERENITY) || defined(AK_OS_ANDROID) || defined(AK_OS_BSD_GENERIC) || defined(AK_OS_HAIKU) || AK_LIBC_GLIBC_PREREQ(2, 36)
    // This target also covers MacOS and iOS and they both seem to support arc4random_buf
    arc4random_buf(buf, size);
#elif defined(AK_OS_LINUX)
    unsigned char* out = (unsigned char*)buf;
    while (size > 0u) {
        // EINTR can be handled safely by just trying again. Others are fatal
        // See manual for more details
        int ret = getrandom(out, size, 0);
        if (ret == -1 && errno != EINTR) [[unlikely]]
            return Error::from_errno(errno);

        // If ret > 0 then ret indicates how much was copied
        if (ret > 0) [[likely]] {
            size -= ret;
            out += ret;
        }
    }
#elif defined(AK_OS_WINDOWS)
    // Documented to always return TRUE
    g_system.ProcessPrng((PBYTE)buf, size);
#else
    static_assert(false, "This build target doesn't have a valid CSPRNG interface specified in AK/Random.cpp.");
#endif
    return {};
}

namespace AK {

void fill_with_random(Bytes bytes)
{
    MUST(csprng(bytes.data(), bytes.size()));
}

u32 get_random_uniform(u32 max_bounds)
{
    // If we try to divide all 2**32 numbers into groups of "max_bounds" numbers, we may end up
    // with a group around 2**32-1 that is a bit too small. For this reason, the implementation
    // `arc4random() % max_bounds` would be insufficient. Here we compute the last number of the
    // last "full group". Note that if max_bounds is a divisor of UINT32_MAX,
    // then we end up with UINT32_MAX:
    u32 const max_usable = UINT32_MAX - (static_cast<u64>(UINT32_MAX) + 1) % max_bounds;
    auto random_value = get_random<u32>();
    for (int i = 0; i < 20 && random_value > max_usable; ++i) {
        // By chance we picked a value from the incomplete group. Note that this group has size at
        // most 2**31-1, so picking this group has a chance of less than 50%.