You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

106 lines
2.6KB

  1. /*
  2. * Copyright (c) 2009 Baptiste Coudurier <baptiste.coudurier@gmail.com>
  3. *
  4. * This file is part of Libav.
  5. *
  6. * Libav is free software; you can redistribute it and/or
  7. * modify it under the terms of the GNU Lesser General Public
  8. * License as published by the Free Software Foundation; either
  9. * version 2.1 of the License, or (at your option) any later version.
  10. *
  11. * Libav is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  14. * Lesser General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU Lesser General Public
  17. * License along with Libav; if not, write to the Free Software
  18. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  19. */
  20. #include "config.h"
  21. #if HAVE_UNISTD_H
  22. #include <unistd.h>
  23. #endif
  24. #if HAVE_CRYPTGENRANDOM
  25. #include <windows.h>
  26. #include <wincrypt.h>
  27. #endif
  28. #include <fcntl.h>
  29. #include <math.h>
  30. #include <time.h>
  31. #include "timer.h"
  32. #include "random_seed.h"
  33. static int read_random(uint32_t *dst, const char *file)
  34. {
  35. #if HAVE_UNISTD_H
  36. int fd = open(file, O_RDONLY);
  37. int err = -1;
  38. if (fd == -1)
  39. return -1;
  40. err = read(fd, dst, sizeof(*dst));
  41. close(fd);
  42. return err;
  43. #else
  44. return -1;
  45. #endif
  46. }
  47. static uint32_t get_generic_seed(void)
  48. {
  49. clock_t last_t = 0;
  50. int bits = 0;
  51. uint64_t random = 0;
  52. unsigned i;
  53. float s = 0.000000000001;
  54. for (i = 0; bits < 64; i++) {
  55. clock_t t = clock();
  56. if (last_t && fabs(t - last_t) > s || t == (clock_t) -1) {
  57. if (i < 10000 && s < (1 << 24)) {
  58. s += s;
  59. i = t = 0;
  60. } else {
  61. random = 2 * random + (i & 1);
  62. bits++;
  63. }
  64. }
  65. last_t = t;
  66. }
  67. #ifdef AV_READ_TIME
  68. random ^= AV_READ_TIME();
  69. #else
  70. random ^= clock();
  71. #endif
  72. random += random >> 32;
  73. return random;
  74. }
  75. uint32_t av_get_random_seed(void)
  76. {
  77. uint32_t seed;
  78. #if HAVE_CRYPTGENRANDOM
  79. HCRYPTPROV provider;
  80. if (CryptAcquireContext(&provider, NULL, NULL, PROV_RSA_FULL,
  81. CRYPT_VERIFYCONTEXT | CRYPT_SILENT)) {
  82. BOOL ret = CryptGenRandom(provider, sizeof(seed), (PBYTE) &seed);
  83. CryptReleaseContext(provider, 0);
  84. if (ret)
  85. return seed;
  86. }
  87. #endif
  88. if (read_random(&seed, "/dev/urandom") == sizeof(seed))
  89. return seed;
  90. if (read_random(&seed, "/dev/random") == sizeof(seed))
  91. return seed;
  92. return get_generic_seed();
  93. }