sys_bsd.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. /* $MirOS: contrib/hosted/fwcf/sys_bsd.c,v 1.4 2007/03/13 18:14:30 tg Exp $ */
  2. /*-
  3. * Copyright (c) 2006, 2007
  4. * Thorsten Glaser <tg@mirbsd.de>
  5. *
  6. * Provided that these terms and disclaimer and all copyright notices
  7. * are retained or reproduced in an accompanying document, permission
  8. * is granted to deal in this work without restriction, including un-
  9. * limited rights to use, publicly perform, distribute, sell, modify,
  10. * merge, give away, or sublicence.
  11. *
  12. * This work is provided "AS IS" and WITHOUT WARRANTY of any kind, to
  13. * the utmost extent permitted by applicable law, neither express nor
  14. * implied; without malicious intent or gross negligence. In no event
  15. * may a licensor, author or contributor be held liable for indirect,
  16. * direct, other damage, loss, or other issues arising in any way out
  17. * of dealing in the work, even if advised of the possibility of such
  18. * damage or existence of a defect, except proven that it results out
  19. * of said person's immediate fault when using the work as intended.
  20. */
  21. #include <fcntl.h>
  22. #include <stdio.h>
  23. #include <stdlib.h>
  24. #include "defs.h"
  25. #include "sysdeps.h"
  26. __RCSID("$MirOS: contrib/hosted/fwcf/sys_bsd.c,v 1.4 2007/03/13 18:14:30 tg Exp $");
  27. void
  28. pull_rndata(uint8_t *buf, size_t n)
  29. {
  30. #ifdef RND_DISABLE
  31. while (n--)
  32. *buf++ = 0xF6;
  33. *--buf = 0xFF;
  34. #else
  35. #ifdef RND_DEBUG
  36. fprintf(stderr, "writing %ld bytes of entropy\n", n);
  37. while (n > 4) {
  38. #else
  39. while (n >= 4) {
  40. #endif
  41. *(uint32_t *)buf = arc4random();
  42. #ifdef RND_DEBUG
  43. *buf = 0xF6;
  44. #endif
  45. buf += 4;
  46. n -= 4;
  47. }
  48. while (n) {
  49. #ifdef RND_DEBUG
  50. *buf++ = 0xF6;
  51. #else
  52. *buf++ = arc4random() & 0xFF;
  53. #endif
  54. n--;
  55. }
  56. #ifdef RND_DEBUG
  57. *--buf = 0xFF;
  58. #endif
  59. #endif
  60. }
  61. void
  62. push_rndata(uint8_t *buf, size_t n)
  63. {
  64. #ifdef RND_DEBUG
  65. size_t i;
  66. #endif
  67. #ifdef __MirBSD__
  68. arc4random_pushb(buf, n);
  69. #else
  70. int fd;
  71. uint32_t x;
  72. arc4random_addrandom(buf, n);
  73. x = arc4random();
  74. if ((fd = open("/dev/arandom", O_WRONLY)) >= 0) {
  75. write(fd, &x, 4);
  76. close(fd);
  77. } else
  78. warn("cannot write to /dev/arandom");
  79. #endif
  80. #ifdef RND_DEBUG
  81. printf("reading %ld bytes of entropy\n", n);
  82. for (i = 0; i < n; ++i) {
  83. printf(" %02X", buf[i]);
  84. if ((i & 0xF) == 0xF)
  85. putchar('\n');
  86. }
  87. putchar('\n');
  88. #endif
  89. }