ratelim.h 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  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. /* Rate-limiter */
  8. /** A ratelim_t remembers how often an event is occurring, and how often
  9. * it's allowed to occur. Typical usage is something like:
  10. *
  11. <pre>
  12. if (possibly_very_frequent_event()) {
  13. const int INTERVAL = 300;
  14. static ratelim_t warning_limit = RATELIM_INIT(INTERVAL);
  15. char *m;
  16. if ((m = rate_limit_log(&warning_limit, approx_time()))) {
  17. log_warn(LD_GENERAL, "The event occurred!%s", m);
  18. tor_free(m);
  19. }
  20. }
  21. </pre>
  22. As a convenience wrapper for logging, you can replace the above with:
  23. <pre>
  24. if (possibly_very_frequent_event()) {
  25. static ratelim_t warning_limit = RATELIM_INIT(300);
  26. log_fn_ratelim(&warning_limit, LOG_WARN, LD_GENERAL,
  27. "The event occurred!");
  28. }
  29. </pre>
  30. */
  31. typedef struct ratelim_t {
  32. int rate;
  33. time_t last_allowed;
  34. int n_calls_since_last_time;
  35. } ratelim_t;
  36. #define RATELIM_INIT(r) { (r), 0, 0 }
  37. #define RATELIM_TOOMANY (16*1000*1000)
  38. char *rate_limit_log(ratelim_t *lim, time_t now);
  39. #endif