ratelim.h 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. /* Copyright (c) 2003-2004, Roger Dingledine
  2. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  3. * Copyright (c) 2007-2018, The Tor Project, Inc. */
  4. /* See LICENSE for licensing information */
  5. #ifndef TOR_RATELIM_H
  6. #define TOR_RATELIM_H
  7. #include <time.h>
  8. /* Rate-limiter */
  9. /** A ratelim_t remembers how often an event is occurring, and how often
  10. * it's allowed to occur. Typical usage is something like:
  11. *
  12. <pre>
  13. if (possibly_very_frequent_event()) {
  14. const int INTERVAL = 300;
  15. static ratelim_t warning_limit = RATELIM_INIT(INTERVAL);
  16. char *m;
  17. if ((m = rate_limit_log(&warning_limit, approx_time()))) {
  18. log_warn(LD_GENERAL, "The event occurred!%s", m);
  19. tor_free(m);
  20. }
  21. }
  22. </pre>
  23. As a convenience wrapper for logging, you can replace the above with:
  24. <pre>
  25. if (possibly_very_frequent_event()) {
  26. static ratelim_t warning_limit = RATELIM_INIT(300);
  27. log_fn_ratelim(&warning_limit, LOG_WARN, LD_GENERAL,
  28. "The event occurred!");
  29. }
  30. </pre>
  31. */
  32. typedef struct ratelim_t {
  33. int rate;
  34. time_t last_allowed;
  35. int n_calls_since_last_time;
  36. } ratelim_t;
  37. #define RATELIM_INIT(r) { (r), 0, 0 }
  38. #define RATELIM_TOOMANY (16*1000*1000)
  39. char *rate_limit_log(ratelim_t *lim, time_t now);
  40. #endif