getentropy.c 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /* Implementation of getentropy based on the getrandom system call.
  2. Copyright (C) 2016-2019 Free Software Foundation, Inc.
  3. This file is part of the GNU C Library.
  4. The GNU C Library is free software; you can redistribute it and/or
  5. modify it under the terms of the GNU Lesser General Public
  6. License as published by the Free Software Foundation; either
  7. version 2.1 of the License, or (at your option) any later version.
  8. The GNU C Library is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. Lesser General Public License for more details.
  12. You should have received a copy of the GNU Lesser General Public
  13. License along with the GNU C Library; if not, see
  14. <http://www.gnu.org/licenses/>. */
  15. #include <sys/random.h>
  16. #include <assert.h>
  17. #include <errno.h>
  18. #include <unistd.h>
  19. #ifdef __NR_getrandom
  20. /* Write LENGTH bytes of randomness starting at BUFFER. Return 0 on
  21. success and -1 on failure. */
  22. int
  23. getentropy (void *buffer, size_t length)
  24. {
  25. /* The interface is documented to return EIO for buffer lengths
  26. longer than 256 bytes. */
  27. if (length > 256)
  28. {
  29. __set_errno (EIO);
  30. return -1;
  31. }
  32. /* Try to fill the buffer completely. Even with the 256 byte limit
  33. above, we might still receive an EINTR error (when blocking
  34. during boot). */
  35. void *end = buffer + length;
  36. while (buffer < end)
  37. {
  38. /* NB: No cancellation point. */
  39. ssize_t bytes = INLINE_SYSCALL_CALL (getrandom, buffer, end - buffer, 0);
  40. if (bytes < 0)
  41. {
  42. if (errno == EINTR)
  43. /* Try again if interrupted by a signal. */
  44. continue;
  45. else
  46. return -1;
  47. }
  48. if (bytes == 0)
  49. {
  50. /* No more bytes available. This should not happen under
  51. normal circumstances. */
  52. __set_errno (EIO);
  53. return -1;
  54. }
  55. /* Try again in case of a short read. */
  56. buffer += bytes;
  57. }
  58. return 0;
  59. }
  60. #else
  61. int
  62. getentropy (void *buffer, size_t length)
  63. {
  64. __set_errno (ENOSYS);
  65. return -1;
  66. }
  67. #endif