zmq_utils.cpp 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  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 "macros.hpp"
  26. #include "clock.hpp"
  27. #include "err.hpp"
  28. #include "thread.hpp"
  29. #include "atomic_counter.hpp"
  30. #include "atomic_ptr.hpp"
  31. #include "random.hpp"
  32. #include <assert.h>
  33. #include <new>
  34. #if !defined ZMQ_HAVE_WINDOWS
  35. #include <unistd.h>
  36. #endif
  37. #if defined(ZMQ_USE_TWEETNACL)
  38. #include "tweetnacl.h"
  39. #elif defined(ZMQ_USE_LIBSODIUM)
  40. #include "sodium.h"
  41. #endif
  42. void zmq_sleep (int seconds_)
  43. {
  44. #if defined ZMQ_HAVE_WINDOWS
  45. Sleep (seconds_ * 1000);
  46. #else
  47. sleep (seconds_);
  48. #endif
  49. }
  50. void *zmq_stopwatch_start ()
  51. {
  52. uint64_t *watch = static_cast<uint64_t *> (malloc (sizeof (uint64_t)));
  53. alloc_assert (watch);
  54. *watch = zmq::clock_t::now_us ();
  55. return static_cast<void *> (watch);
  56. }
  57. unsigned long zmq_stopwatch_intermediate (void *watch_)
  58. {
  59. const uint64_t end = zmq::clock_t::now_us ();
  60. const uint64_t start = *static_cast<uint64_t *> (watch_);
  61. return static_cast<unsigned long> (end - start);
  62. }
  63. unsigned long zmq_stopwatch_stop (void *watch_)
  64. {
  65. const unsigned long res = zmq_stopwatch_intermediate (watch_);
  66. free (watch_);
  67. return res;
  68. }
  69. void *zmq_threadstart (zmq_thread_fn *func_, void *arg_)
  70. {
  71. zmq::thread_t *thread = new (std::nothrow) zmq::thread_t;
  72. alloc_assert (thread);
  73. thread->start (func_, arg_, "ZMQapp");
  74. return thread;
  75. }
  76. void zmq_threadclose (void *thread_)
  77. {
  78. zmq::thread_t *p_thread = static_cast<zmq::thread_t *> (thread_);
  79. p_thread->stop ();
  80. LIBZMQ_DELETE (p_thread);
  81. }
  82. // Z85 codec, taken from 0MQ RFC project, implements RFC32 Z85 encoding
  83. // Maps base 256 to base 85
  84. static char encoder[85 + 1] = {"0123456789"
  85. "abcdefghij"
  86. "klmnopqrst"
  87. "uvwxyzABCD"
  88. "EFGHIJKLMN"
  89. "OPQRSTUVWX"
  90. "YZ.-:+=^!/"
  91. "*?&<>()[]{"
  92. "}@%$#"};
  93. // Maps base 85 to base 256
  94. // We chop off lower 32 and higher 128 ranges
  95. // 0xFF denotes invalid characters within this range
  96. static uint8_t decoder[96] = {
  97. 0xFF, 0x44, 0xFF, 0x54, 0x53, 0x52, 0x48, 0xFF, 0x4B, 0x4C, 0x46, 0x41,
  98. 0xFF, 0x3F, 0x3E, 0x45, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  99. 0x08, 0x09, 0x40, 0xFF, 0x49, 0x42, 0x4A, 0x47, 0x51, 0x24, 0x25, 0x26,
  100. 0x27, 0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F, 0x30, 0x31, 0x32,
  101. 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0x4D,
  102. 0xFF, 0x4E, 0x43, 0xFF, 0xFF, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10,
  103. 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C,
  104. 0x1D, 0x1E, 0x1F, 0x20, 0x21, 0x22, 0x23, 0x4F, 0xFF, 0x50, 0xFF, 0xFF};
  105. // --------------------------------------------------------------------------
  106. // Encode a binary frame as a string; destination string MUST be at least
  107. // size * 5 / 4 bytes long plus 1 byte for the null terminator. Returns
  108. // dest. Size must be a multiple of 4.
  109. // Returns NULL and sets errno = EINVAL for invalid input.
  110. char *zmq_z85_encode (char *dest_, const uint8_t *data_, size_t size_)
  111. {
  112. if (size_ % 4 != 0) {
  113. errno = EINVAL;
  114. return NULL;
  115. }
  116. unsigned int char_nbr = 0;
  117. unsigned int byte_nbr = 0;
  118. uint32_t value = 0;
  119. while (byte_nbr < size_) {
  120. // Accumulate value in base 256 (binary)
  121. value = value * 256 + data_[byte_nbr++];
  122. if (byte_nbr % 4 == 0) {
  123. // Output value in base 85
  124. unsigned int divisor = 85 * 85 * 85 * 85;
  125. while (divisor) {
  126. dest_[char_nbr++] = encoder[value / divisor % 85];
  127. divisor /= 85;
  128. }
  129. value = 0;
  130. }
  131. }
  132. assert (char_nbr == size_ * 5 / 4);
  133. dest_[char_nbr] = 0;
  134. return dest_;
  135. }
  136. // --------------------------------------------------------------------------
  137. // Decode an encoded string into a binary frame; dest must be at least
  138. // strlen (string) * 4 / 5 bytes long. Returns dest. strlen (string)
  139. // must be a multiple of 5.
  140. // Returns NULL and sets errno = EINVAL for invalid input.
  141. uint8_t *zmq_z85_decode (uint8_t *dest_, const char *string_)
  142. {
  143. unsigned int byte_nbr = 0;
  144. unsigned int char_nbr = 0;
  145. uint32_t value = 0;
  146. while (string_[char_nbr]) {
  147. // Accumulate value in base 85
  148. if (UINT32_MAX / 85 < value) {
  149. // Invalid z85 encoding, represented value exceeds 0xffffffff
  150. goto error_inval;
  151. }
  152. value *= 85;
  153. const uint8_t index = string_[char_nbr++] - 32;
  154. if (index >= sizeof (decoder)) {
  155. // Invalid z85 encoding, character outside range
  156. goto error_inval;
  157. }
  158. const uint32_t summand = decoder[index];
  159. if (summand == 0xFF || summand > (UINT32_MAX - value)) {
  160. // Invalid z85 encoding, invalid character or represented value exceeds 0xffffffff
  161. goto error_inval;
  162. }
  163. value += summand;
  164. if (char_nbr % 5 == 0) {
  165. // Output value in base 256
  166. unsigned int divisor = 256 * 256 * 256;
  167. while (divisor) {
  168. dest_[byte_nbr++] = value / divisor % 256;
  169. divisor /= 256;
  170. }
  171. value = 0;
  172. }
  173. }
  174. if (char_nbr % 5 != 0) {
  175. goto error_inval;
  176. }
  177. assert (byte_nbr == strlen (string_) * 4 / 5);
  178. return dest_;
  179. error_inval:
  180. errno = EINVAL;
  181. return NULL;
  182. }
  183. // --------------------------------------------------------------------------
  184. // Generate a public/private keypair with tweetnacl or libsodium.
  185. // Generated keys will be 40 byte z85-encoded strings.
  186. // Returns 0 on success, -1 on failure, setting errno.
  187. // Sets errno = ENOTSUP in the absence of a CURVE library.
  188. int zmq_curve_keypair (char *z85_public_key_, char *z85_secret_key_)
  189. {
  190. #if defined(ZMQ_HAVE_CURVE)
  191. #if crypto_box_PUBLICKEYBYTES != 32 || crypto_box_SECRETKEYBYTES != 32
  192. #error "CURVE encryption library not built correctly"
  193. #endif
  194. uint8_t public_key[32];
  195. uint8_t secret_key[32];
  196. zmq::random_open ();
  197. const int res = crypto_box_keypair (public_key, secret_key);
  198. zmq_z85_encode (z85_public_key_, public_key, 32);
  199. zmq_z85_encode (z85_secret_key_, secret_key, 32);
  200. zmq::random_close ();
  201. return res;
  202. #else
  203. (void) z85_public_key_, (void) z85_secret_key_;
  204. errno = ENOTSUP;
  205. return -1;
  206. #endif
  207. }
  208. // --------------------------------------------------------------------------
  209. // Derive the public key from a private key using tweetnacl or libsodium.
  210. // Derived key will be 40 byte z85-encoded string.
  211. // Returns 0 on success, -1 on failure, setting errno.
  212. // Sets errno = ENOTSUP in the absence of a CURVE library.
  213. int zmq_curve_public (char *z85_public_key_, const char *z85_secret_key_)
  214. {
  215. #if defined(ZMQ_HAVE_CURVE)
  216. #if crypto_box_PUBLICKEYBYTES != 32 || crypto_box_SECRETKEYBYTES != 32
  217. #error "CURVE encryption library not built correctly"
  218. #endif
  219. uint8_t public_key[32];
  220. uint8_t secret_key[32];
  221. zmq::random_open ();
  222. if (zmq_z85_decode (secret_key, z85_secret_key_) == NULL)
  223. return -1;
  224. // Return codes are suppressed as none of these can actually fail.
  225. crypto_scalarmult_base (public_key, secret_key);
  226. zmq_z85_encode (z85_public_key_, public_key, 32);
  227. zmq::random_close ();
  228. return 0;
  229. #else
  230. (void) z85_public_key_, (void) z85_secret_key_;
  231. errno = ENOTSUP;
  232. return -1;
  233. #endif
  234. }
  235. // --------------------------------------------------------------------------
  236. // Initialize a new atomic counter, which is set to zero
  237. void *zmq_atomic_counter_new (void)
  238. {
  239. zmq::atomic_counter_t *counter = new (std::nothrow) zmq::atomic_counter_t;
  240. alloc_assert (counter);
  241. return counter;
  242. }
  243. // Se the value of the atomic counter
  244. void zmq_atomic_counter_set (void *counter_, int value_)
  245. {
  246. (static_cast<zmq::atomic_counter_t *> (counter_))->set (value_);
  247. }
  248. // Increment the atomic counter, and return the old value
  249. int zmq_atomic_counter_inc (void *counter_)
  250. {
  251. return (static_cast<zmq::atomic_counter_t *> (counter_))->add (1);
  252. }
  253. // Decrement the atomic counter and return 1 (if counter >= 1), or
  254. // 0 if counter hit zero.
  255. int zmq_atomic_counter_dec (void *counter_)
  256. {
  257. return (static_cast<zmq::atomic_counter_t *> (counter_))->sub (1) ? 1 : 0;
  258. }
  259. // Return actual value of atomic counter
  260. int zmq_atomic_counter_value (void *counter_)
  261. {
  262. return (static_cast<zmq::atomic_counter_t *> (counter_))->get ();
  263. }
  264. // Destroy atomic counter, and set reference to NULL
  265. void zmq_atomic_counter_destroy (void **counter_p_)
  266. {
  267. delete (static_cast<zmq::atomic_counter_t *> (*counter_p_));
  268. *counter_p_ = NULL;
  269. }