File: random.c

package info (click to toggle)
ofono 2.18-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 12,064 kB
  • sloc: ansic: 224,979; sh: 5,012; python: 4,040; makefile: 956
file content (90 lines) | stat: -rw-r--r-- 1,609 bytes parent folder | download | duplicates (8)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
/*
 * 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();
}