You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

103 lines
2.2 KiB

  1. /*
  2. * ppbloom.c - Ping-Pong Bloom Filter for nonce reuse detection
  3. *
  4. * Copyright (C) 2013 - 2019, Max Lv <max.c.lv@gmail.com>
  5. *
  6. * This file is part of the shadowsocks-libev.
  7. *
  8. * shadowsocks-libev is free software; you can redistribute it and/or modify
  9. * it under the terms of the GNU General Public License as published by
  10. * the Free Software Foundation; either version 3 of the License, or
  11. * (at your option) any later version.
  12. *
  13. * shadowsocks-libev is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License
  19. * along with shadowsocks-libev; see the file COPYING. If not, see
  20. * <http://www.gnu.org/licenses/>.
  21. */
  22. #include <errno.h>
  23. #include <stdlib.h>
  24. #include "bloom.h"
  25. #include "ppbloom.h"
  26. #include "utils.h"
  27. #define PING 0
  28. #define PONG 1
  29. static struct bloom ppbloom[2];
  30. static int bloom_count[2];
  31. static int current;
  32. static int entries;
  33. static double error;
  34. int
  35. ppbloom_init(int n, double e)
  36. {
  37. int err;
  38. entries = n / 2;
  39. error = e;
  40. err = bloom_init(ppbloom + PING, entries, error);
  41. if (err)
  42. return err;
  43. err = bloom_init(ppbloom + PONG, entries, error);
  44. if (err)
  45. return err;
  46. bloom_count[PING] = 0;
  47. bloom_count[PONG] = 0;
  48. current = PING;
  49. return 0;
  50. }
  51. int
  52. ppbloom_check(const void *buffer, int len)
  53. {
  54. int ret;
  55. ret = bloom_check(ppbloom + PING, buffer, len);
  56. if (ret)
  57. return ret;
  58. ret = bloom_check(ppbloom + PONG, buffer, len);
  59. if (ret)
  60. return ret;
  61. return 0;
  62. }
  63. int
  64. ppbloom_add(const void *buffer, int len)
  65. {
  66. int err;
  67. err = bloom_add(ppbloom + current, buffer, len);
  68. if (err == -1)
  69. return err;
  70. bloom_count[current]++;
  71. if (bloom_count[current] >= entries) {
  72. bloom_count[current] = 0;
  73. current = current == PING ? PONG : PING;
  74. bloom_free(ppbloom + current);
  75. bloom_init(ppbloom + current, entries, error);
  76. }
  77. return 0;
  78. }
  79. void
  80. ppbloom_free()
  81. {
  82. bloom_free(ppbloom + PING);
  83. bloom_free(ppbloom + PONG);
  84. }