DevUrandomRandomSeed.c 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /* vim: set expandtab ts=4 sw=4: */
  2. /*
  3. * You may redistribute this program and/or modify it under the terms of
  4. * the GNU General Public License as published by the Free Software Foundation,
  5. * either version 3 of the License, or (at your option) any later version.
  6. *
  7. * This program is distributed in the hope that it will be useful,
  8. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. * GNU General Public License for more details.
  11. *
  12. * You should have received a copy of the GNU General Public License
  13. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  14. */
  15. #include "crypto/random/seed/DevUrandomRandomSeed.h"
  16. #include "util/Identity.h"
  17. #include "util/Bits.h"
  18. #include <sys/types.h>
  19. #include <sys/stat.h>
  20. #include <fcntl.h>
  21. #include <unistd.h>
  22. #include <errno.h>
  23. /** Number of times to try each operation. */
  24. #define MAX_TRIES 10
  25. static int get(struct RandomSeed* randomSeed, uint64_t output[8])
  26. {
  27. Bits_memset(output, 0, 64);
  28. int fd = -1;
  29. int tries = 0;
  30. while ((fd = open("/dev/urandom", O_RDONLY, 0)) < 0) {
  31. if (++tries > MAX_TRIES || errno == ENOENT) {
  32. return -1;
  33. }
  34. sleep(1);
  35. }
  36. tries = 0;
  37. uint8_t* buff = (uint8_t*) output;
  38. int count = 64;
  39. while (count > 0) {
  40. int r = read(fd, buff, count);
  41. if (r < 1) {
  42. if (++tries > MAX_TRIES) {
  43. break;
  44. }
  45. sleep(1);
  46. continue;
  47. }
  48. buff += r;
  49. count -= r;
  50. }
  51. close(fd);
  52. if (count == 0 && !Bits_isZero(output, 64)) {
  53. return 0;
  54. }
  55. return -1;
  56. }
  57. struct RandomSeed* DevUrandomRandomSeed_new(struct Allocator* alloc)
  58. {
  59. return Allocator_clone(alloc, (&(struct RandomSeed) {
  60. .get = get,
  61. .name = "/dev/urandom"
  62. }));
  63. }