address_set.c 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. /* Copyright (c) 2018-2019, 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 "core/or/address_set.h"
  13. #include "lib/net/address.h"
  14. #include "lib/container/bloomfilt.h"
  15. #include "lib/crypt_ops/crypto_rand.h"
  16. #include "siphash.h"
  17. /* Wrap our hash function to have the signature that the bloom filter
  18. * needs. */
  19. static uint64_t
  20. bloomfilt_addr_hash(const struct sipkey *key,
  21. const void *item)
  22. {
  23. return tor_addr_keyed_hash(key, item);
  24. }
  25. /**
  26. * Allocate and return an address_set, suitable for holding up to
  27. * <b>max_address_guess</b> distinct values.
  28. */
  29. address_set_t *
  30. address_set_new(int max_addresses_guess)
  31. {
  32. uint8_t k[BLOOMFILT_KEY_LEN];
  33. crypto_rand((void*)k, sizeof(k));
  34. return bloomfilt_new(max_addresses_guess, bloomfilt_addr_hash, k);
  35. }
  36. /**
  37. * Add <b>addr</b> to <b>set</b>.
  38. *
  39. * All future queries for <b>addr</b> in set will return true. Removing
  40. * items is not possible.
  41. */
  42. void
  43. address_set_add(address_set_t *set, const struct tor_addr_t *addr)
  44. {
  45. bloomfilt_add(set, addr);
  46. }
  47. /** As address_set_add(), but take an ipv4 address in host order. */
  48. void
  49. address_set_add_ipv4h(address_set_t *set, uint32_t addr)
  50. {
  51. tor_addr_t a;
  52. tor_addr_from_ipv4h(&a, addr);
  53. address_set_add(set, &a);
  54. }
  55. /**
  56. * Return true if <b>addr</b> is a member of <b>set</b>. (And probably,
  57. * return false if <b>addr</b> is not a member of set.)
  58. */
  59. int
  60. address_set_probably_contains(const address_set_t *set,
  61. const struct tor_addr_t *addr)
  62. {
  63. return bloomfilt_probably_contains(set, addr);
  64. }