Blame


1 60d3db8e 2004-04-21 devnull #include <u.h>
2 60d3db8e 2004-04-21 devnull #include <libc.h>
3 60d3db8e 2004-04-21 devnull
4 60d3db8e 2004-04-21 devnull ulong
5 60d3db8e 2004-04-21 devnull truerand(void)
6 60d3db8e 2004-04-21 devnull {
7 60d3db8e 2004-04-21 devnull int i, n;
8 60d3db8e 2004-04-21 devnull uchar buf[sizeof(ulong)];
9 0c9c620f 2010-03-10 rsc ulong x;
10 60d3db8e 2004-04-21 devnull static int randfd = -1;
11 3a6c348f 2005-09-19 devnull static char *randfile;
12 60d3db8e 2004-04-21 devnull
13 60d3db8e 2004-04-21 devnull if(randfd < 0){
14 3a6c348f 2005-09-19 devnull randfd = open(randfile="/dev/random", OREAD);
15 3a6c348f 2005-09-19 devnull /* OpenBSD lets you open /dev/random but not read it! */
16 3a6c348f 2005-09-19 devnull if(randfd < 0 || read(randfd, buf, 1) != 1)
17 3a6c348f 2005-09-19 devnull randfd = open(randfile="/dev/srandom", OREAD); /* OpenBSD */
18 fea3228f 2005-08-11 devnull if(randfd < 0)
19 c4791fa5 2005-10-29 devnull sysfatal("can't open %s: %r", randfile);
20 60d3db8e 2004-04-21 devnull fcntl(randfd, F_SETFD, FD_CLOEXEC);
21 60d3db8e 2004-04-21 devnull }
22 60d3db8e 2004-04-21 devnull for(i=0; i<sizeof(buf); i += n)
23 60d3db8e 2004-04-21 devnull if((n = readn(randfd, buf+i, sizeof(buf)-i)) < 0)
24 3a6c348f 2005-09-19 devnull sysfatal("can't read %s: %r", randfile);
25 0c9c620f 2010-03-10 rsc memmove(&x, buf, sizeof x);
26 0c9c620f 2010-03-10 rsc return x;
27 60d3db8e 2004-04-21 devnull }