xref: /dragonfly/contrib/cryptsetup/luks/random.c (revision a8ca8ac6)
1 /*
2  *	Random supply helper
3  * Copyright 2004, Clemens Fruhwirth <clemens@endorphin.org>
4  *
5  */
6 
7 #include <sys/types.h>
8 #include <sys/stat.h>
9 #include <fcntl.h>
10 #include <errno.h>
11 #include <stdio.h>
12 #include <unistd.h>
13 
14 static int randomfd = -1;
15 
16 int openRandom() {
17     if(randomfd == -1)
18 	randomfd = open("/dev/urandom", O_RDONLY);
19     return randomfd;
20 }
21 
22 /* This method leaks a file descriptor that can be obtained by calling
23    closeRandom */
24 int getRandom(char *buf, size_t len)
25 {
26     if(openRandom() == -1) {
27 	perror("getRandom:");
28 	return -EINVAL;
29     }
30     while(len) {
31 	int r;
32 	r = read(randomfd,buf,len);
33 	if (-1 == r && errno != -EINTR) {
34 	    perror("read: "); return -EINVAL;
35 	}
36 	len-= r; buf += r;
37     }
38     return 0;
39 }
40 
41 void closeRandom() {
42     if(randomfd != -1) {
43 	close(randomfd);
44 	randomfd = -1;
45     }
46 }
47