devurandom.c 592 B

123456789101112131415161718192021222324252627282930313233343536
  1. #include <sys/types.h>
  2. #include <sys/stat.h>
  3. #include <fcntl.h>
  4. #include <unistd.h>
  5. #include "randombytes.h"
  6. /* it's really stupid that there isn't a syscall for this */
  7. static int fd = -1;
  8. void randombytes(unsigned char *x,unsigned long long xlen)
  9. {
  10. ssize_t i;
  11. if (fd == -1) {
  12. for (;;) {
  13. fd = open("/dev/urandom",O_RDONLY);
  14. if (fd != -1) break;
  15. sleep(1);
  16. }
  17. }
  18. while (xlen > 0) {
  19. if (xlen < 1048576) i = (ssize_t)xlen; else i = 1048576;
  20. i = read(fd,x,i);
  21. if (i < 1) {
  22. sleep(1);
  23. continue;
  24. }
  25. x += i;
  26. xlen -= i;
  27. }
  28. }