Source code pulled from OpenBSD for OpenNTPD. The place to contribute to this code is via the OpenBSD CVS tree.
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.

81 lines
2.2 KiB

10 years ago
10 years ago
10 years ago
10 years ago
  1. /* $OpenBSD: arc4random_osx.h,v 1.11 2016/06/30 12:19:51 bcook Exp $ */
  2. /*
  3. * Copyright (c) 1996, David Mazieres <dm@uun.org>
  4. * Copyright (c) 2008, Damien Miller <djm@openbsd.org>
  5. * Copyright (c) 2013, Markus Friedl <markus@openbsd.org>
  6. * Copyright (c) 2014, Theo de Raadt <deraadt@openbsd.org>
  7. *
  8. * Permission to use, copy, modify, and distribute this software for any
  9. * purpose with or without fee is hereby granted, provided that the above
  10. * copyright notice and this permission notice appear in all copies.
  11. *
  12. * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  13. * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  14. * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  15. * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  16. * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  17. * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  18. * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  19. */
  20. /*
  21. * Stub functions for portability.
  22. */
  23. #include <sys/mman.h>
  24. #include <pthread.h>
  25. #include <signal.h>
  26. static pthread_mutex_t arc4random_mtx = PTHREAD_MUTEX_INITIALIZER;
  27. #define _ARC4_LOCK() pthread_mutex_lock(&arc4random_mtx)
  28. #define _ARC4_UNLOCK() pthread_mutex_unlock(&arc4random_mtx)
  29. #define _ARC4_ATFORK(f) pthread_atfork(NULL, NULL, (f))
  30. static inline void
  31. _getentropy_fail(void)
  32. {
  33. raise(SIGKILL);
  34. }
  35. static volatile sig_atomic_t _rs_forked;
  36. static inline void
  37. _rs_forkhandler(void)
  38. {
  39. _rs_forked = 1;
  40. }
  41. static inline void
  42. _rs_forkdetect(void)
  43. {
  44. static pid_t _rs_pid = 0;
  45. pid_t pid = getpid();
  46. if (_rs_pid == 0 || _rs_pid != pid || _rs_forked) {
  47. _rs_pid = pid;
  48. _rs_forked = 0;
  49. if (rs)
  50. memset(rs, 0, sizeof(*rs));
  51. }
  52. }
  53. static inline int
  54. _rs_allocate(struct _rs **rsp, struct _rsx **rsxp)
  55. {
  56. if ((*rsp = mmap(NULL, sizeof(**rsp), PROT_READ|PROT_WRITE,
  57. MAP_ANON|MAP_PRIVATE, -1, 0)) == MAP_FAILED)
  58. return (-1);
  59. if ((*rsxp = mmap(NULL, sizeof(**rsxp), PROT_READ|PROT_WRITE,
  60. MAP_ANON|MAP_PRIVATE, -1, 0)) == MAP_FAILED) {
  61. munmap(*rsp, sizeof(**rsp));
  62. *rsp = NULL;
  63. return (-1);
  64. }
  65. _ARC4_ATFORK(_rs_forkhandler);
  66. return (0);
  67. }