randutil.c 1005 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. /*
  2. * randutil.c
  3. *
  4. * Copyright (c) 2001 Dug Song <dugsong@monkey.org>
  5. *
  6. * $Id: randutil.c 2191 2009-02-01 21:34:27Z aturner $
  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. #include <dnet.h>
  16. #endif
  17. #include <stdio.h>
  18. #include <stdlib.h>
  19. #include <string.h>
  20. #include <time.h>
  21. #include "randutil.h"
  22. static const char base64[] =
  23. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  24. void
  25. rand_strset(rand_t *r, void *buf, size_t len)
  26. {
  27. uint32_t u;
  28. char *p;
  29. int i;
  30. p = (char *)buf;
  31. i = (len + 3) / 4;
  32. u = rand_uint32(r);
  33. /* XXX - more Duff's device tomfoolery. */
  34. switch (len % 4) {
  35. case 0: do {
  36. u = rand_uint32(r);
  37. *p++ = base64[(u >> 18) & 0x3f];
  38. case 3:
  39. *p++ = base64[(u >> 12) & 0x3f];
  40. case 2:
  41. *p++ = base64[(u >> 6) & 0x3f];
  42. case 1:
  43. *p++ = base64[(u >> 0) & 0x3f];
  44. } while (--i > 0);
  45. }
  46. p[-1] = '\0';
  47. }