protocol uint/magnolia / source / mg_random.c
 1#include "mg_random.h"
 2
 3#include <errno.h>
 4#include <stddef.h>
 5
 6#if defined(__linux__)
 7#include <sys/random.h>
 8#elif defined(__APPLE__) || defined(__OpenBSD__) || defined(__FreeBSD__) || defined(__NetBSD__) || \
 9    defined(__DragonFly__)
10#include <stdlib.h>
11#elif defined(_WIN32)
12/* TODO: Windows shi*/
13#else
14#error "mg_random_bytes needs a platform CSPRNG implementation"
15#endif
16
17int mg_random_bytes(u8* data, size_t size)
18{
19#if defined(__linux__)
20	while (size > 0) {
21		ssize_t count = getrandom(data, size, 0);
22		if (count > 0) {
23			data += (size_t)count;
24			size -= (size_t)count;
25			continue;
26		}
27		if (count < 0 && errno == EINTR)
28			continue;
29		return 0;
30	}
31	return 1;
32#else
33	arc4random_buf(data, size);
34	return 1;
35#endif
36}