address_set.c 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /* Copyright (c) 2018-2018, The Tor Project, Inc. */
  2. /* See LICENSE for licensing information */
  3. /**
  4. * \file address_set.c
  5. * \brief Implementation for a set of addresses.
  6. *
  7. * This module was first written on a semi-emergency basis to improve the
  8. * robustness of the anti-DoS module. As such, it's written in a pretty
  9. * conservative way, and should be susceptible to improvement later on.
  10. **/
  11. #include "orconfig.h"
  12. #include "common/address_set.h"
  13. #include "lib/net/address.h"
  14. #include "common/compat.h"
  15. #include "lib/container/bloomfilt.h"
  16. #include "lib/crypt_ops/crypto_rand.h"
  17. #include "common/util.h"
  18. #include "siphash.h"
  19. /* Wrap our hash function to have the signature that the bloom filter
  20. * needs. */
  21. static uint64_t
  22. bloomfilt_addr_hash(const struct sipkey *key,
  23. const void *item)
  24. {
  25. return tor_addr_keyed_hash(key, item);
  26. }
  27. /**
  28. * Allocate and return an address_set, suitable for holding up to
  29. * <b>max_address_guess</b> distinct values.
  30. */
  31. address_set_t *
  32. address_set_new(int max_addresses_guess)
  33. {
  34. uint8_t k[BLOOMFILT_KEY_LEN];
  35. crypto_rand((void*)k, sizeof(k));
  36. return bloomfilt_new(max_addresses_guess, bloomfilt_addr_hash, k);
  37. }
  38. /**
  39. * Add <b>addr</b> to <b>set</b>.
  40. *
  41. * All future queries for <b>addr</b> in set will return true. Removing
  42. * items is not possible.
  43. */
  44. void
  45. address_set_add(address_set_t *set, const struct tor_addr_t *addr)
  46. {
  47. bloomfilt_add(set, addr);
  48. }
  49. /** As address_set_add(), but take an ipv4 address in host order. */
  50. void
  51. address_set_add_ipv4h(address_set_t *set, uint32_t addr)
  52. {
  53. tor_addr_t a;
  54. tor_addr_from_ipv4h(&a, addr);
  55. address_set_add(set, &a);
  56. }
  57. /**
  58. * Return true if <b>addr</b> is a member of <b>set</b>. (And probably,
  59. * return false if <b>addr</b> is not a member of set.)
  60. */
  61. int
  62. address_set_probably_contains(const address_set_t *set,
  63. const struct tor_addr_t *addr)
  64. {
  65. return bloomfilt_probably_contains(set, addr);
  66. }