File: random.c

package info (click to toggle)
cryptsetup 2%3A1.0.6-7
  • links: PTS, VCS
  • area: main
  • in suites: lenny
  • size: 2,644 kB
  • ctags: 500
  • sloc: sh: 10,578; ansic: 4,114; xml: 471; makefile: 356; python: 90; perl: 44; sed: 16
file content (48 lines) | stat: -rw-r--r-- 840 bytes parent folder | download
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
/*
 *	Random supply helper
 * Copyright 2004, Clemens Fruhwirth <clemens@endorphin.org>
 *
 */

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

static int randomfd = -1; 

int openRandom() {
    if(randomfd == -1) 
	randomfd = open("/dev/urandom", O_RDONLY);
    return randomfd;
}

/* This method leaks a file descriptor that can be obtained by calling
   closeRandom */
int getRandom(char *buf, size_t len)
{
    int r = 0;

    if(openRandom() == -1) {
	perror("getRandom:");
	return -EINVAL;
    }
    while(len) {
	int r;
	r = read(randomfd,buf,len);
	if (-1 == r && errno != -EINTR) {	
	    perror("read: "); return -EINVAL;
	}
	len-= r; buf += r;
    }
    return r;
}

void closeRandom() {
    if(randomfd != -1) {
	close(randomfd);
	randomfd = -1;
    }
}