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.

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. // Copyright (c) 2019 Shivaram Lingamneni <slingamn@cs.stanford.edu>
  2. // released under the MIT license
  3. package connection_limits
  4. import (
  5. "sync"
  6. "time"
  7. )
  8. // TorLimiter is a combined limiter and throttler for use on connections
  9. // proxied from a Tor hidden service (so we don't have meaningful IPs,
  10. // a notion of CIDR width, etc.)
  11. type TorLimiter struct {
  12. sync.Mutex
  13. numConnections int
  14. maxConnections int
  15. throttle GenericThrottle
  16. }
  17. func (tl *TorLimiter) Configure(maxConnections int, duration time.Duration, maxConnectionsPerDuration int) {
  18. tl.Lock()
  19. defer tl.Unlock()
  20. tl.maxConnections = maxConnections
  21. tl.throttle.Duration = duration
  22. tl.throttle.Limit = maxConnectionsPerDuration
  23. }
  24. func (tl *TorLimiter) AddClient() error {
  25. tl.Lock()
  26. defer tl.Unlock()
  27. if tl.maxConnections != 0 && tl.maxConnections <= tl.numConnections {
  28. return ErrLimitExceeded
  29. }
  30. throttled, _ := tl.throttle.Touch()
  31. if throttled {
  32. return ErrThrottleExceeded
  33. }
  34. tl.numConnections += 1
  35. return nil
  36. }
  37. func (tl *TorLimiter) RemoveClient() {
  38. tl.Lock()
  39. tl.numConnections -= 1
  40. tl.Unlock()
  41. }