Welcome to mirror list, hosted at ThFree Co, Russian Federation.

v_randgen.c « dist « verse « extern - git.blender.org/blender.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: c65b48be60bbd58f4f32c657ca276f860c937405 (plain)
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
91
92
93
94
95
96
97
98
99
100
101
/*
 * Random number generator module. Defines a simple API to allocate, use and
 * destroy a generator of randomness. Relies on platform-specific APIs.
*/

#include <stdio.h>
#include <stdlib.h>

#include "v_randgen.h"

#if defined _WIN32

/* This is a fall-back to the old style of simply using rand(). It should
 * be replaced by something using the proper Win32 cryptography APIs.
 * The CryptAcquireContext() and CryptGenRandom() calls sound interesting.
 * 
 * FIXME: Replace ASAP.
*/

VRandGen * v_randgen_new(void)
{
	return (VRandGen *) 1;	/* Anything that isn't NULL. */
}

void v_randgen_get(VRandGen *gen, void *bytes, size_t num)
{
	if(gen != NULL && bytes != NULL)
	{
		unsigned char	*put = bytes, *get;
		size_t	i;
		int	x;

		while(num > 0)
		{
			x = rand();
			get = (unsigned char *) &x;
			for(i = 0; i < sizeof x && num > 0; i++, num--)
				*put++ = *get++;
		}
	}
}

void v_randgen_destroy(VRandGen *gen)
{
	/* Nothing to do here. */
}

#else

/* On non-Win32 platforms (which is Linux and Darwin, at the moment), we
 * read random data from a file, which is assumed to be one of the kernel's
 * virtual files.
*/

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

struct VRandGen {
	int	fd;
};

#define	SOURCE	"/dev/urandom"	/* Name of file to read random bits from. */

VRandGen * v_randgen_new(void)
{
	VRandGen	*gen;

	if((gen = malloc(sizeof *gen)) != NULL)
	{
		gen->fd = open(SOURCE, O_RDONLY);
		if(gen->fd < 0)
		{
			fprintf(stderr, __FILE__ ": Couldn't open " SOURCE " for reading\n");
			free(gen);
			gen = NULL;
		}
	}
	return gen;
}

void v_randgen_get(VRandGen *gen, void *bytes, size_t num)
{
	if(gen != NULL && bytes != NULL)
	{
		if(read(gen->fd, bytes, num) != (int) num)
			fprintf(stderr, __FILE__ ": Failed to read %u bytes of random data from " SOURCE "\n", (unsigned int) num);
	}
}

void v_randgen_destroy(VRandGen *gen)
{
	if(gen != NULL)
	{
		close(gen->fd);
		free(gen);
	}
}

#endif