Initial checking of what was revision 56 on http://luks.endorphin.org/svn/cryptsetup
[platform/upstream/cryptsetup.git] / luks / random.c
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     int r = 0;
27
28     if(openRandom() == -1) {
29         perror("getRandom:");
30         return -EINVAL;
31     }
32     while(len) {
33         int r;
34         r = read(randomfd,buf,len);
35         if (-1 == r && errno != -EINTR) {       
36             perror("read: "); return -EINVAL;
37         }
38         len-= r; buf += r;
39     }
40     return r;
41 }
42
43 void closeRandom() {
44     if(randomfd != -1) {
45         close(randomfd);
46         randomfd = -1;
47     }
48 }