visitor.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. package server
  2. import (
  3. "errors"
  4. "golang.org/x/time/rate"
  5. "heckel.io/ntfy/util"
  6. "sync"
  7. "time"
  8. )
  9. const (
  10. // visitorExpungeAfter defines how long a visitor is active before it is removed from memory. This number
  11. // has to be very high to prevent e-mail abuse, but it doesn't really affect the other limits anyway, since
  12. // they are replenished faster (typically).
  13. visitorExpungeAfter = 24 * time.Hour
  14. )
  15. var (
  16. errVisitorLimitReached = errors.New("limit reached")
  17. )
  18. // visitor represents an API user, and its associated rate.Limiter used for rate limiting
  19. type visitor struct {
  20. config *Config
  21. ip string
  22. requests *rate.Limiter
  23. emails *rate.Limiter
  24. subscriptions util.Limiter
  25. bandwidth util.Limiter
  26. seen time.Time
  27. mu sync.Mutex
  28. }
  29. func newVisitor(conf *Config, ip string) *visitor {
  30. return &visitor{
  31. config: conf,
  32. ip: ip,
  33. requests: rate.NewLimiter(rate.Every(conf.VisitorRequestLimitReplenish), conf.VisitorRequestLimitBurst),
  34. emails: rate.NewLimiter(rate.Every(conf.VisitorEmailLimitReplenish), conf.VisitorEmailLimitBurst),
  35. subscriptions: util.NewFixedLimiter(int64(conf.VisitorSubscriptionLimit)),
  36. bandwidth: util.NewBytesLimiter(conf.VisitorAttachmentDailyBandwidthLimit, 24*time.Hour),
  37. seen: time.Now(),
  38. }
  39. }
  40. func (v *visitor) IP() string {
  41. return v.ip
  42. }
  43. func (v *visitor) RequestAllowed() error {
  44. if !v.requests.Allow() {
  45. return errVisitorLimitReached
  46. }
  47. return nil
  48. }
  49. func (v *visitor) EmailAllowed() error {
  50. if !v.emails.Allow() {
  51. return errVisitorLimitReached
  52. }
  53. return nil
  54. }
  55. func (v *visitor) SubscriptionAllowed() error {
  56. v.mu.Lock()
  57. defer v.mu.Unlock()
  58. if err := v.subscriptions.Allow(1); err != nil {
  59. return errVisitorLimitReached
  60. }
  61. return nil
  62. }
  63. func (v *visitor) RemoveSubscription() {
  64. v.mu.Lock()
  65. defer v.mu.Unlock()
  66. v.subscriptions.Allow(-1)
  67. }
  68. func (v *visitor) Keepalive() {
  69. v.mu.Lock()
  70. defer v.mu.Unlock()
  71. v.seen = time.Now()
  72. }
  73. func (v *visitor) BandwidthLimiter() util.Limiter {
  74. return v.bandwidth
  75. }
  76. func (v *visitor) Stale() bool {
  77. v.mu.Lock()
  78. defer v.mu.Unlock()
  79. return time.Since(v.seen) > visitorExpungeAfter
  80. }