randutil.c 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. /*
  2. * randutil.c
  3. *
  4. * Copyright (c) 2001 Dug Song <dugsong@monkey.org>
  5. *
  6. * $Id$
  7. */
  8. #include "config.h"
  9. #ifdef HAVE_LIBDNET
  10. /* need to undef these which are pulled in via defines.h, prior to importing dnet.h */
  11. #undef icmp_id
  12. #undef icmp_seq
  13. #undef icmp_data
  14. #undef icmp_mask
  15. #ifdef HAVE_DNET_H
  16. #include <dnet.h>
  17. #endif
  18. #ifdef HAVE_DUMBNET_H
  19. #include <dumbnet.h>
  20. #endif
  21. #endif
  22. #include "randutil.h"
  23. #include <stdio.h>
  24. #include <stdlib.h>
  25. #include <string.h>
  26. #include <time.h>
  27. static const char base64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  28. void
  29. rand_strset(rand_t *r, void *buf, size_t len)
  30. {
  31. uint32_t u;
  32. char *p;
  33. int i;
  34. p = (char *)buf;
  35. i = (len + 3) / 4;
  36. u = rand_uint32(r);
  37. /* XXX - more Duff's device tomfoolery. */
  38. switch (len % 4) {
  39. case 0:
  40. do {
  41. u = rand_uint32(r);
  42. *p++ = base64[(u >> 18) & 0x3f];
  43. /* fall through */
  44. case 3:
  45. *p++ = base64[(u >> 12) & 0x3f];
  46. /* fall through */
  47. case 2:
  48. *p++ = base64[(u >> 6) & 0x3f];
  49. /* fall through */
  50. case 1:
  51. *p++ = base64[(u >> 0) & 0x3f];
  52. } while (--i > 0);
  53. }
  54. p[-1] = '\0';
  55. }