random.cpp 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  1. /*
  2. Copyright (c) 2007-2017 Contributors as noted in the AUTHORS file
  3. This file is part of libzmq, the ZeroMQ core engine in C++.
  4. libzmq is free software; you can redistribute it and/or modify it under
  5. the terms of the GNU Lesser General Public License (LGPL) as published
  6. by the Free Software Foundation; either version 3 of the License, or
  7. (at your option) any later version.
  8. As a special exception, the Contributors give you permission to link
  9. this library with independent modules to produce an executable,
  10. regardless of the license terms of these independent modules, and to
  11. copy and distribute the resulting executable under terms of your choice,
  12. provided that you also meet, for each linked independent module, the
  13. terms and conditions of the license of that module. An independent
  14. module is a module which is not derived from or based on this library.
  15. If you modify this library, you must extend this exception to your
  16. version of the library.
  17. libzmq is distributed in the hope that it will be useful, but WITHOUT
  18. ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  19. FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
  20. License for more details.
  21. You should have received a copy of the GNU Lesser General Public License
  22. along with this program. If not, see <http://www.gnu.org/licenses/>.
  23. */
  24. #include "precompiled.hpp"
  25. #include <stdlib.h>
  26. #if !defined ZMQ_HAVE_WINDOWS
  27. #include <unistd.h>
  28. #endif
  29. #include "random.hpp"
  30. #include "stdint.hpp"
  31. #include "clock.hpp"
  32. #include "mutex.hpp"
  33. #include "macros.hpp"
  34. #if defined(ZMQ_USE_TWEETNACL)
  35. #include "tweetnacl.h"
  36. #elif defined(ZMQ_USE_LIBSODIUM)
  37. #include "sodium.h"
  38. #endif
  39. void zmq::seed_random ()
  40. {
  41. #if defined ZMQ_HAVE_WINDOWS
  42. const int pid = static_cast<int> (GetCurrentProcessId ());
  43. #else
  44. int pid = static_cast<int> (getpid ());
  45. #endif
  46. srand (static_cast<unsigned int> (clock_t::now_us () + pid));
  47. }
  48. uint32_t zmq::generate_random ()
  49. {
  50. // Compensate for the fact that rand() returns signed integer.
  51. const uint32_t low = static_cast<uint32_t> (rand ());
  52. uint32_t high = static_cast<uint32_t> (rand ());
  53. high <<= (sizeof (int) * 8 - 1);
  54. return high | low;
  55. }
  56. // When different threads have their own context the file descriptor
  57. // variable is shared and is subject to race conditions in tweetnacl,
  58. // that lead to file descriptors leaks. In long-running programs with
  59. // ephemeral threads this is a problem as it accumulates.
  60. // thread-local storage cannot be used to initialise the file descriptor
  61. // as it is perfectly legal to share a context among many threads, each
  62. // of which might call curve APIs.
  63. // Also libsodium documentation specifically states that sodium_init
  64. // must not be called concurrently from multiple threads, for the
  65. // same reason. Inspecting the code also reveals that the close API is
  66. // not thread safe.
  67. // The context class cannot be used with static variables as the curve
  68. // utility APIs like zmq_curve_keypair also call into the crypto
  69. // library.
  70. // The safest solution for all use cases therefore is to have a
  71. // static lock to serialize calls into an initialiser and a finaliser,
  72. // using refcounts to make sure that a thread does not close the library
  73. // while another is still using it. To avoid the static initialization
  74. // order fiasco, this is done using function-local statics, if the
  75. // compiler implementation supports thread-safe initialization of those.
  76. // Otherwise, we fall back to global statics.
  77. // HOWEVER, this initialisation code imposes ordering constraints, which
  78. // are not obvious to users of libzmq, and may lead to problems if atexit
  79. // or similar methods are used for cleanup.
  80. // In that case, a strict ordering is imposed whereas the contexts MUST
  81. // be initialised BEFORE registering the cleanup with atexit. CZMQ is an
  82. // example. Hence we make the choice to restrict this global transition
  83. // mechanism ONLY to Tweenacl + *NIX (when using /dev/urandom) as it is
  84. // the less risky option.
  85. // TODO if there is some other user of libsodium besides libzmq, this must
  86. // be synchronized by the application. This should probably also be
  87. // configurable via config.h
  88. // TODO this should probably be done via config.h
  89. #if __cplusplus >= 201103L \
  90. || (defined(__cpp_threadsafe_static_init) \
  91. && __cpp_threadsafe_static_init >= 200806) \
  92. || (defined(_MSC_VER) && _MSC_VER >= 1900)
  93. #define ZMQ_HAVE_THREADSAFE_STATIC_LOCAL_INIT 1
  94. // TODO this might probably also be set if a sufficiently recent gcc is used
  95. // without -fno-threadsafe-statics, but this cannot be determined at
  96. // compile-time, so it must be set via config.h
  97. #else
  98. #define ZMQ_HAVE_THREADSAFE_STATIC_LOCAL_INIT 0
  99. #endif
  100. #if !ZMQ_HAVE_THREADSAFE_STATIC_LOCAL_INIT \
  101. && (defined(ZMQ_USE_TWEETNACL) && !defined(ZMQ_HAVE_WINDOWS) \
  102. && !defined(ZMQ_HAVE_GETRANDOM))
  103. static unsigned int random_refcount = 0;
  104. static zmq::mutex_t random_sync;
  105. #endif
  106. static void manage_random (bool init_)
  107. {
  108. #if defined(ZMQ_USE_TWEETNACL) && !defined(ZMQ_HAVE_WINDOWS) \
  109. && !defined(ZMQ_HAVE_GETRANDOM)
  110. #if ZMQ_HAVE_THREADSAFE_STATIC_LOCAL_INIT
  111. static int random_refcount = 0;
  112. static zmq::mutex_t random_sync;
  113. #endif
  114. if (init_) {
  115. zmq::scoped_lock_t locker (random_sync);
  116. if (random_refcount == 0) {
  117. int rc = sodium_init ();
  118. zmq_assert (rc != -1);
  119. }
  120. ++random_refcount;
  121. } else {
  122. zmq::scoped_lock_t locker (random_sync);
  123. --random_refcount;
  124. if (random_refcount == 0) {
  125. randombytes_close ();
  126. }
  127. }
  128. #elif defined(ZMQ_USE_LIBSODIUM)
  129. if (init_) {
  130. int rc = sodium_init ();
  131. zmq_assert (rc != -1);
  132. } else {
  133. randombytes_close ();
  134. }
  135. #else
  136. LIBZMQ_UNUSED (init_);
  137. #endif
  138. }
  139. void zmq::random_open ()
  140. {
  141. manage_random (true);
  142. }
  143. void zmq::random_close ()
  144. {
  145. manage_random (false);
  146. }