#include "openthread-posix-config.h"
#include "platform-posix.h"
#include <assert.h>
#include <stdio.h>
#include <openthread/error.h>
#include <openthread/platform/entropy.h>
#include "common/code_utils.hpp"
#ifndef __SANITIZE_ADDRESS__
#define __SANITIZE_ADDRESS__ 0
#endif
#if __SANITIZE_ADDRESS__ != 0
static uint32_t sState = 1;
#endif
void platformRandomInit(void)
{
#if __SANITIZE_ADDRESS__ != 0
sState = (uint32_t)time(NULL) + (3600 * gNodeId);
#endif }
#if __SANITIZE_ADDRESS__ != 0
uint32_t randomUint32Get(void)
{
uint32_t mlcg, p, q;
uint64_t tmpstate;
tmpstate = (uint64_t)33614 * (uint64_t)sState;
q = tmpstate & 0xffffffff;
q = q >> 1;
p = tmpstate >> 32;
mlcg = p + q;
if (mlcg & 0x80000000)
{
mlcg &= 0x7fffffff;
mlcg++;
}
sState = mlcg;
return mlcg;
}
#endif
otError otPlatEntropyGet(uint8_t *aOutput, uint16_t aOutputLength)
{
otError error = OT_ERROR_NONE;
#if __SANITIZE_ADDRESS__ == 0
FILE * file = NULL;
size_t readLength;
VerifyOrExit(aOutput && aOutputLength, error = OT_ERROR_INVALID_ARGS);
file = fopen("/dev/urandom", "rb");
VerifyOrExit(file != NULL, error = OT_ERROR_FAILED);
readLength = fread(aOutput, 1, aOutputLength, file);
VerifyOrExit(readLength == aOutputLength, error = OT_ERROR_FAILED);
exit:
if (file != NULL)
{
fclose(file);
}
#else
VerifyOrExit(aOutput && aOutputLength, error = OT_ERROR_INVALID_ARGS);
for (uint16_t length = 0; length < aOutputLength; length++)
{
aOutput[length] = (uint8_t)randomUint32Get();
}
exit:
#endif
return error;
}