random.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. /*
  2. *
  3. * Embedded Linux library
  4. *
  5. * Copyright (C) 2015 Intel Corporation. All rights reserved.
  6. *
  7. * This library is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU Lesser General Public
  9. * License as published by the Free Software Foundation; either
  10. * version 2.1 of the License, or (at your option) any later version.
  11. *
  12. * This library is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public
  18. * License along with this library; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
  20. *
  21. */
  22. #ifdef HAVE_CONFIG_H
  23. #include <config.h>
  24. #endif
  25. #define _GNU_SOURCE
  26. #include <errno.h>
  27. #include <unistd.h>
  28. #include <stdlib.h>
  29. #include <sys/syscall.h>
  30. #include "random.h"
  31. #include "private.h"
  32. #include "missing.h"
  33. #ifndef GRND_NONBLOCK
  34. #define GRND_NONBLOCK 0x0001
  35. #endif
  36. #ifndef GRND_RANDOM
  37. #define GRND_RANDOM 0x0002
  38. #endif
  39. static inline int getrandom(void *buffer, size_t count, unsigned flags) {
  40. return syscall(__NR_getrandom, buffer, count, flags);
  41. }
  42. /**
  43. * l_getrandom:
  44. * @buf: buffer to fill with random data
  45. * @len: length of random data requested
  46. *
  47. * Request a number of randomly generated bytes given by @len and put them
  48. * into buffer @buf.
  49. *
  50. * Returns: true if the random data could be generated, false otherwise.
  51. **/
  52. LIB_EXPORT bool l_getrandom(void *buf, size_t len)
  53. {
  54. while (len) {
  55. int ret;
  56. ret = L_TFR(getrandom(buf, len, 0));
  57. if (ret < 0)
  58. return false;
  59. buf += ret;
  60. len -= ret;
  61. }
  62. return true;
  63. }
  64. LIB_EXPORT bool l_getrandom_is_supported()
  65. {
  66. static bool initialized = false;
  67. static bool supported = true;
  68. uint8_t buf[4];
  69. int ret;
  70. if (initialized)
  71. return supported;
  72. ret = getrandom(buf, sizeof(buf), GRND_NONBLOCK);
  73. if (ret < 0 && errno == ENOSYS)
  74. supported = false;
  75. initialized = true;
  76. return supported;
  77. }
  78. LIB_EXPORT uint32_t l_getrandom_uint32(void)
  79. {
  80. int ret;
  81. uint32_t u;
  82. ret = getrandom(&u, sizeof(u), GRND_NONBLOCK);
  83. if (ret == sizeof(u))
  84. return u;
  85. return random() * RAND_MAX + random();
  86. }