/*
 * Embedded Linux library
 * Copyright (C) 2015  Intel Corporation
 *
 * SPDX-License-Identifier: LGPL-2.1-or-later
 */

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#define _GNU_SOURCE
#include <errno.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/syscall.h>

#include "random.h"
#include "private.h"
#include "missing.h"

#ifndef GRND_NONBLOCK
#define GRND_NONBLOCK	0x0001
#endif

#ifndef GRND_RANDOM
#define GRND_RANDOM	0x0002
#endif

static inline int getrandom(void *buffer, size_t count, unsigned flags) {
        return syscall(__NR_getrandom, buffer, count, flags);
}

/**
 * l_getrandom:
 * @buf: buffer to fill with random data
 * @len: length of random data requested
 *
 * Request a number of randomly generated bytes given by @len and put them
 * into buffer @buf.
 *
 * Returns: true if the random data could be generated, false otherwise.
 **/
LIB_EXPORT bool l_getrandom(void *buf, size_t len)
{
	while (len) {
		int ret;

		ret = L_TFR(getrandom(buf, len, 0));
		if (ret < 0)
			return false;

		buf += ret;
		len -= ret;
	}

	return true;
}

LIB_EXPORT bool l_getrandom_is_supported()
{
	static bool initialized = false;
	static bool supported = true;
	uint8_t buf[4];
	int ret;

	if (initialized)
		return supported;

	ret = getrandom(buf, sizeof(buf), GRND_NONBLOCK);

	if (ret < 0 && errno == ENOSYS)
		supported = false;

	initialized = true;
	return supported;
}

LIB_EXPORT uint32_t l_getrandom_uint32(void)
{
	int ret;
	uint32_t u;

	ret = getrandom(&u, sizeof(u), GRND_NONBLOCK);

	if (ret == sizeof(u))
		return u;

        return random() * RAND_MAX + random();
}
