| 1 |
package server |
| 2 |
|
| 3 |
import ( |
| 4 |
"fmt" |
| 5 |
"math" |
| 6 |
"net/netip" |
| 7 |
"sync" |
| 8 |
"time" |
| 9 |
|
| 10 |
"golang.org/x/time/rate" |
| 11 |
"heckel.io/ntfy/v2/log" |
| 12 |
"heckel.io/ntfy/v2/message" |
| 13 |
"heckel.io/ntfy/v2/user" |
| 14 |
"heckel.io/ntfy/v2/util" |
| 15 |
) |
| 16 |
|
| 17 |
const ( |
| 18 |
// oneDay is an approximation of a day as a time.Duration |
| 19 |
oneDay = 24 * time.Hour |
| 20 |
|
| 21 |
// visitorExpungeAfter defines how long a visitor is active before it is removed from memory. This number |
| 22 |
// has to be very high to prevent e-mail abuse, but it doesn't really affect the other limits anyway, since |
| 23 |
// they are replenished faster (typically). |
| 24 |
visitorExpungeAfter = oneDay |
| 25 |
|
| 26 |
// visitorDefaultReservationsLimit is the amount of topic names a user without a tier is allowed to reserve. |
| 27 |
// This number is zero, and changing it may have unintended consequences in the web app, or otherwise |
| 28 |
visitorDefaultReservationsLimit = int64(0) |
| 29 |
|
| 30 |
// visitorDefaultCallsLimit is the amount of calls a user without a tier is allowed to make. |
| 31 |
// This number is zero, because phone numbers have to be verified first. |
| 32 |
visitorDefaultCallsLimit = int64(0) |
| 33 |
) |
| 34 |
|
| 35 |
// Constants used to convert a tier-user's MessageSizeLimit (see user.Tier) into adequate request limiter |
| 36 |
// values (token bucket). This is only used to increase the values in server.yml, never decrease them. |
| 37 |
// |
| 38 |
// Example: Assuming a user.Tier's MessageSizeLimit is 10,000: |
| 39 |
// - the allowed burst is 500 (= 10,000 * 5%), which is < 1000 (the max) |
| 40 |
// - the replenish rate is 2 * 10,000 / 24 hours |
| 41 |
const ( |
| 42 |
visitorMessageToRequestLimitBurstRate = 0.05 |
| 43 |
visitorMessageToRequestLimitBurstMax = 1000 |
| 44 |
visitorMessageToRequestLimitReplenishFactor = 2 |
| 45 |
) |
| 46 |
|
| 47 |
// Constants used to convert a tier-user's EmailLimit (see user.Tier) into adequate email limiter |
| 48 |
// values (token bucket). Example: Assuming a user.Tier's EmailLimit is 200, the allowed burst is |
| 49 |
// 40 (= 200 * 20%), which is <150 (the max). |
| 50 |
const ( |
| 51 |
visitorEmailLimitBurstRate = 0.2 |
| 52 |
visitorEmailLimitBurstMax = 150 |
| 53 |
) |
| 54 |
|
| 55 |
// visitor represents an API user, and its associated rate.Limiter used for rate limiting |
| 56 |
type visitor struct { |
| 57 |
config *Config |
| 58 |
messageCache *message.Cache |
| 59 |
userManager *user.Manager // May be nil |
| 60 |
ip netip.Addr // Visitor IP address |
| 61 |
user *user.User // Only set if authenticated user, otherwise nil |
| 62 |
requestLimiter *rate.Limiter // Rate limiter for (almost) all requests (including messages) |
| 63 |
messagesLimiter *util.FixedLimiter // Rate limiter for messages |
| 64 |
emailsLimiter *util.RateLimiter // Rate limiter for emails |
| 65 |
callsLimiter *util.FixedLimiter // Rate limiter for calls |
| 66 |
subscriptionLimiter *util.FixedLimiter // Fixed limiter for active subscriptions (ongoing connections) |
| 67 |
topicCreationLimiter *rate.Limiter // Rate limiter for inserting new topics into the in-memory topic map |
| 68 |
bandwidthLimiter *util.RateLimiter // Limiter for attachment bandwidth downloads |
| 69 |
accountLimiter *rate.Limiter // Rate limiter for account actions (signup, password-reset requests), may be nil |
| 70 |
authLimiter *rate.Limiter // Limiter for incorrect login attempts, may be nil |
| 71 |
firebase time.Time // Next allowed Firebase message |
| 72 |
seen time.Time // Last seen time of this visitor (needed for removal of stale visitors) |
| 73 |
mu sync.RWMutex |
| 74 |
} |
| 75 |
|
| 76 |
type visitorInfo struct { |
| 77 |
Limits *visitorLimits |
| 78 |
Stats *visitorStats |
| 79 |
} |
| 80 |
|
| 81 |
type visitorLimits struct { |
| 82 |
Basis visitorLimitBasis |
| 83 |
RequestLimitBurst int |
| 84 |
RequestLimitReplenish rate.Limit |
| 85 |
MessageLimit int64 |
| 86 |
MessageExpiryDuration time.Duration |
| 87 |
EmailLimit int64 |
| 88 |
EmailLimitBurst int |
| 89 |
EmailLimitReplenish rate.Limit |
| 90 |
CallLimit int64 |
| 91 |
ReservationsLimit int64 |
| 92 |
AttachmentTotalSizeLimit int64 |
| 93 |
AttachmentFileSizeLimit int64 |
| 94 |
AttachmentExpiryDuration time.Duration |
| 95 |
AttachmentBandwidthLimit int64 |
| 96 |
} |
| 97 |
|
| 98 |
type visitorStats struct { |
| 99 |
Messages int64 |
| 100 |
MessagesRemaining int64 |
| 101 |
Emails int64 |
| 102 |
EmailsRemaining int64 |
| 103 |
Calls int64 |
| 104 |
CallsRemaining int64 |
| 105 |
Reservations int64 |
| 106 |
ReservationsRemaining int64 |
| 107 |
AttachmentTotalSize int64 |
| 108 |
AttachmentTotalSizeRemaining int64 |
| 109 |
} |
| 110 |
|
| 111 |
// visitorLimitBasis describes how the visitor limits were derived, either from a user's |
| 112 |
// IP address (default config), or from its tier |
| 113 |
type visitorLimitBasis string |
| 114 |
|
| 115 |
const ( |
| 116 |
visitorLimitBasisIP = visitorLimitBasis("ip") |
| 117 |
visitorLimitBasisTier = visitorLimitBasis("tier") |
| 118 |
) |
| 119 |
|
| 120 |
func newVisitor(conf *Config, messageCache *message.Cache, userManager *user.Manager, ip netip.Addr, user *user.User) *visitor { |
| 121 |
var messages, emails, calls int64 |
| 122 |
if user != nil { |
| 123 |
messages = user.Stats.Messages |
| 124 |
emails = user.Stats.Emails |
| 125 |
calls = user.Stats.Calls |
| 126 |
} |
| 127 |
v := &visitor{ |
| 128 |
config: conf, |
| 129 |
messageCache: messageCache, |
| 130 |
userManager: userManager, // May be nil |
| 131 |
ip: ip, |
| 132 |
user: user, |
| 133 |
firebase: time.Unix(0, 0), |
| 134 |
seen: time.Now(), |
| 135 |
subscriptionLimiter: util.NewFixedLimiter(int64(conf.VisitorSubscriptionLimit)), |
| 136 |
requestLimiter: nil, // Set in resetLimiters |
| 137 |
messagesLimiter: nil, // Set in resetLimiters, may be nil |
| 138 |
emailsLimiter: nil, // Set in resetLimiters |
| 139 |
callsLimiter: nil, // Set in resetLimiters, may be nil |
| 140 |
topicCreationLimiter: nil, // Set in resetLimiters |
| 141 |
bandwidthLimiter: nil, // Set in resetLimiters |
| 142 |
accountLimiter: nil, // Set in resetLimiters, may be nil |
| 143 |
authLimiter: nil, // Set in resetLimiters, may be nil |
| 144 |
} |
| 145 |
v.resetLimitersNoLock(messages, emails, calls, false) |
| 146 |
return v |
| 147 |
} |
| 148 |
|
| 149 |
func (v *visitor) Context() log.Context { |
| 150 |
v.mu.RLock() |
| 151 |
defer v.mu.RUnlock() |
| 152 |
return v.contextNoLock() |
| 153 |
} |
| 154 |
|
| 155 |
func (v *visitor) contextNoLock() log.Context { |
| 156 |
info := v.infoLightNoLock() |
| 157 |
fields := log.Context{ |
| 158 |
"visitor_id": visitorID(v.ip, v.user, v.config), |
| 159 |
"visitor_ip": v.ip.String(), |
| 160 |
"visitor_seen": util.FormatTime(v.seen), |
| 161 |
"visitor_messages": info.Stats.Messages, |
| 162 |
"visitor_messages_limit": info.Limits.MessageLimit, |
| 163 |
"visitor_messages_remaining": info.Stats.MessagesRemaining, |
| 164 |
"visitor_requests_remaining": int64(math.Floor(v.requestLimiter.Tokens())), |
| 165 |
} |
| 166 |
if v.config.SMTPSenderFrom != "" { |
| 167 |
fields["visitor_emails"] = info.Stats.Emails |
| 168 |
fields["visitor_emails_limit"] = info.Limits.EmailLimit |
| 169 |
fields["visitor_emails_remaining"] = info.Stats.EmailsRemaining |
| 170 |
} |
| 171 |
if v.config.TwilioAccount != "" { |
| 172 |
fields["visitor_calls"] = info.Stats.Calls |
| 173 |
fields["visitor_calls_limit"] = info.Limits.CallLimit |
| 174 |
fields["visitor_calls_remaining"] = info.Stats.CallsRemaining |
| 175 |
} |
| 176 |
if v.authLimiter != nil { |
| 177 |
fields["visitor_auth_attempts_remaining"] = int64(math.Floor(v.authLimiter.Tokens())) |
| 178 |
} |
| 179 |
if v.topicCreationLimiter != nil { |
| 180 |
fields["visitor_topic_creations_remaining"] = int64(math.Floor(v.topicCreationLimiter.Tokens())) |
| 181 |
} |
| 182 |
if v.user != nil { |
| 183 |
fields["user_id"] = v.user.ID |
| 184 |
fields["user_name"] = v.user.Name |
| 185 |
if v.user.Tier != nil { |
| 186 |
for field, value := range v.user.Tier.Context() { |
| 187 |
fields[field] = value |
| 188 |
} |
| 189 |
} |
| 190 |
if v.user.Billing.StripeCustomerID != "" { |
| 191 |
fields["stripe_customer_id"] = v.user.Billing.StripeCustomerID |
| 192 |
} |
| 193 |
if v.user.Billing.StripeSubscriptionID != "" { |
| 194 |
fields["stripe_subscription_id"] = v.user.Billing.StripeSubscriptionID |
| 195 |
} |
| 196 |
} |
| 197 |
return fields |
| 198 |
} |
| 199 |
|
| 200 |
func visitorExtendedInfoContext(info *visitorInfo) log.Context { |
| 201 |
return log.Context{ |
| 202 |
"visitor_reservations": info.Stats.Reservations, |
| 203 |
"visitor_reservations_limit": info.Limits.ReservationsLimit, |
| 204 |
"visitor_reservations_remaining": info.Stats.ReservationsRemaining, |
| 205 |
"visitor_attachment_total_size": info.Stats.AttachmentTotalSize, |
| 206 |
"visitor_attachment_total_size_limit": info.Limits.AttachmentTotalSizeLimit, |
| 207 |
"visitor_attachment_total_size_remaining": info.Stats.AttachmentTotalSizeRemaining, |
| 208 |
} |
| 209 |
|
| 210 |
} |
| 211 |
func (v *visitor) RequestAllowed() bool { |
| 212 |
v.mu.RLock() // limiters could be replaced! |
| 213 |
defer v.mu.RUnlock() |
| 214 |
return v.requestLimiter.Allow() |
| 215 |
} |
| 216 |
|
| 217 |
func (v *visitor) FirebaseAllowed() bool { |
| 218 |
v.mu.RLock() |
| 219 |
defer v.mu.RUnlock() |
| 220 |
return !time.Now().Before(v.firebase) |
| 221 |
} |
| 222 |
|
| 223 |
func (v *visitor) FirebaseTemporarilyDeny() { |
| 224 |
v.mu.Lock() |
| 225 |
defer v.mu.Unlock() |
| 226 |
v.firebase = time.Now().Add(v.config.FirebaseQuotaExceededPenaltyDuration) |
| 227 |
} |
| 228 |
|
| 229 |
func (v *visitor) MessageAllowed() bool { |
| 230 |
v.mu.RLock() // limiters could be replaced! |
| 231 |
defer v.mu.RUnlock() |
| 232 |
return v.messagesLimiter.Allow() |
| 233 |
} |
| 234 |
|
| 235 |
func (v *visitor) EmailAllowed() bool { |
| 236 |
v.mu.RLock() // limiters could be replaced! |
| 237 |
defer v.mu.RUnlock() |
| 238 |
return v.emailsLimiter.Allow() |
| 239 |
} |
| 240 |
|
| 241 |
func (v *visitor) CallAllowed() bool { |
| 242 |
v.mu.RLock() // limiters could be replaced! |
| 243 |
defer v.mu.RUnlock() |
| 244 |
return v.callsLimiter.Allow() |
| 245 |
} |
| 246 |
|
| 247 |
func (v *visitor) SubscriptionAllowed() bool { |
| 248 |
v.mu.RLock() // limiters could be replaced! |
| 249 |
defer v.mu.RUnlock() |
| 250 |
return v.subscriptionLimiter.Allow() |
| 251 |
} |
| 252 |
|
| 253 |
// TopicCreationAllowed returns true if the visitor is allowed to cause a new topic to be |
| 254 |
// inserted into the server's in-memory topic map. Returns true if no limiter is configured. |
| 255 |
func (v *visitor) TopicCreationAllowed() bool { |
| 256 |
v.mu.RLock() // limiters could be replaced! |
| 257 |
defer v.mu.RUnlock() |
| 258 |
if v.topicCreationLimiter == nil { |
| 259 |
return true |
| 260 |
} |
| 261 |
return v.topicCreationLimiter.Allow() |
| 262 |
} |
| 263 |
|
| 264 |
// AuthAllowed returns true if an auth request can be attempted (> 1 token available) |
| 265 |
func (v *visitor) AuthAllowed() bool { |
| 266 |
v.mu.RLock() // limiters could be replaced! |
| 267 |
defer v.mu.RUnlock() |
| 268 |
if v.authLimiter == nil { |
| 269 |
return true |
| 270 |
} |
| 271 |
return v.authLimiter.Tokens() > 1 |
| 272 |
} |
| 273 |
|
| 274 |
// AuthFailed records an auth failure |
| 275 |
func (v *visitor) AuthFailed() { |
| 276 |
v.mu.RLock() // limiters could be replaced! |
| 277 |
defer v.mu.RUnlock() |
| 278 |
if v.authLimiter != nil { |
| 279 |
v.authLimiter.Allow() |
| 280 |
} |
| 281 |
} |
| 282 |
|
| 283 |
// AccountActionAllowed returns true if a rate-limited account action (signup or password-reset |
| 284 |
// request) is currently allowed for this visitor |
| 285 |
func (v *visitor) AccountActionAllowed() bool { |
| 286 |
v.mu.RLock() // limiters could be replaced! |
| 287 |
defer v.mu.RUnlock() |
| 288 |
if v.accountLimiter == nil || (v.accountLimiter != nil && v.accountLimiter.Tokens() < 1) { |
| 289 |
return false |
| 290 |
} |
| 291 |
return true |
| 292 |
} |
| 293 |
|
| 294 |
// AccountActionPerformed decreases the account limiter. This is to be called after a rate-limited |
| 295 |
// account action (signup or password-reset request). |
| 296 |
func (v *visitor) AccountActionPerformed() { |
| 297 |
v.mu.RLock() // limiters could be replaced! |
| 298 |
defer v.mu.RUnlock() |
| 299 |
if v.accountLimiter != nil { |
| 300 |
v.accountLimiter.Allow() |
| 301 |
} |
| 302 |
} |
| 303 |
|
| 304 |
func (v *visitor) BandwidthAllowed(bytes int64) bool { |
| 305 |
v.mu.RLock() // limiters could be replaced! |
| 306 |
defer v.mu.RUnlock() |
| 307 |
return v.bandwidthLimiter.AllowN(bytes) |
| 308 |
} |
| 309 |
|
| 310 |
func (v *visitor) RemoveSubscription() { |
| 311 |
v.mu.RLock() |
| 312 |
defer v.mu.RUnlock() |
| 313 |
v.subscriptionLimiter.AllowN(-1) |
| 314 |
} |
| 315 |
|
| 316 |
func (v *visitor) Keepalive() { |
| 317 |
v.mu.Lock() |
| 318 |
defer v.mu.Unlock() |
| 319 |
v.seen = time.Now() |
| 320 |
} |
| 321 |
|
| 322 |
func (v *visitor) BandwidthLimiter() util.Limiter { |
| 323 |
v.mu.RLock() // limiters could be replaced! |
| 324 |
defer v.mu.RUnlock() |
| 325 |
return v.bandwidthLimiter |
| 326 |
} |
| 327 |
|
| 328 |
func (v *visitor) Stale() bool { |
| 329 |
v.mu.RLock() |
| 330 |
defer v.mu.RUnlock() |
| 331 |
return time.Since(v.seen) > visitorExpungeAfter |
| 332 |
} |
| 333 |
|
| 334 |
func (v *visitor) Stats() *user.Stats { |
| 335 |
v.mu.RLock() // limiters could be replaced! |
| 336 |
defer v.mu.RUnlock() |
| 337 |
return &user.Stats{ |
| 338 |
Messages: v.messagesLimiter.Value(), |
| 339 |
Emails: v.emailsLimiter.Value(), |
| 340 |
Calls: v.callsLimiter.Value(), |
| 341 |
} |
| 342 |
} |
| 343 |
|
| 344 |
func (v *visitor) ResetStats() { |
| 345 |
v.mu.RLock() // limiters could be replaced! |
| 346 |
defer v.mu.RUnlock() |
| 347 |
v.emailsLimiter.Reset() |
| 348 |
v.messagesLimiter.Reset() |
| 349 |
v.callsLimiter.Reset() |
| 350 |
} |
| 351 |
|
| 352 |
// User returns the visitor user, or nil if there is none |
| 353 |
func (v *visitor) User() *user.User { |
| 354 |
v.mu.RLock() |
| 355 |
defer v.mu.RUnlock() |
| 356 |
return v.user // May be nil |
| 357 |
} |
| 358 |
|
| 359 |
// IP returns the visitor IP address |
| 360 |
func (v *visitor) IP() netip.Addr { |
| 361 |
v.mu.RLock() |
| 362 |
defer v.mu.RUnlock() |
| 363 |
return v.ip |
| 364 |
} |
| 365 |
|
| 366 |
// Authenticated returns true if a user successfully authenticated |
| 367 |
func (v *visitor) Authenticated() bool { |
| 368 |
v.mu.RLock() |
| 369 |
defer v.mu.RUnlock() |
| 370 |
return v.user != nil |
| 371 |
} |
| 372 |
|
| 373 |
// SetUser sets the visitors user to the given value |
| 374 |
func (v *visitor) SetUser(u *user.User) { |
| 375 |
v.mu.Lock() |
| 376 |
defer v.mu.Unlock() |
| 377 |
shouldResetLimiters := v.user.TierID() != u.TierID() // TierID works with nil receiver |
| 378 |
v.user = u // u may be nil! |
| 379 |
if shouldResetLimiters { |
| 380 |
var messages, emails, calls int64 |
| 381 |
if u != nil { |
| 382 |
messages, emails, calls = u.Stats.Messages, u.Stats.Emails, u.Stats.Calls |
| 383 |
} |
| 384 |
v.resetLimitersNoLock(messages, emails, calls, true) |
| 385 |
} |
| 386 |
} |
| 387 |
|
| 388 |
// MaybeUserID returns the user ID of the visitor (if any). If this is an anonymous visitor, |
| 389 |
// an empty string is returned. |
| 390 |
func (v *visitor) MaybeUserID() string { |
| 391 |
v.mu.RLock() |
| 392 |
defer v.mu.RUnlock() |
| 393 |
if v.user != nil { |
| 394 |
return v.user.ID |
| 395 |
} |
| 396 |
return "" |
| 397 |
} |
| 398 |
|
| 399 |
func (v *visitor) resetLimitersNoLock(messages, emails, calls int64, enqueueUpdate bool) { |
| 400 |
limits := v.limitsNoLock() |
| 401 |
v.requestLimiter = rate.NewLimiter(limits.RequestLimitReplenish, limits.RequestLimitBurst) |
| 402 |
v.messagesLimiter = util.NewFixedLimiterWithValue(limits.MessageLimit, messages) |
| 403 |
v.emailsLimiter = util.NewRateLimiterWithValue(limits.EmailLimitReplenish, limits.EmailLimitBurst, emails) |
| 404 |
v.callsLimiter = util.NewFixedLimiterWithValue(limits.CallLimit, calls) |
| 405 |
if v.config.VisitorTopicCreationLimitBurst > 0 && v.config.VisitorTopicCreationLimitReplenish > 0 { |
| 406 |
v.topicCreationLimiter = rate.NewLimiter(rate.Every(v.config.VisitorTopicCreationLimitReplenish), v.config.VisitorTopicCreationLimitBurst) |
| 407 |
} else { |
| 408 |
v.topicCreationLimiter = nil // Disabled |
| 409 |
} |
| 410 |
v.bandwidthLimiter = util.NewBytesLimiter(int(limits.AttachmentBandwidthLimit), oneDay) |
| 411 |
if v.user == nil { |
| 412 |
v.accountLimiter = rate.NewLimiter(rate.Every(v.config.VisitorAccountCreationLimitReplenish), v.config.VisitorAccountCreationLimitBurst) |
| 413 |
v.authLimiter = rate.NewLimiter(rate.Every(v.config.VisitorAuthFailureLimitReplenish), v.config.VisitorAuthFailureLimitBurst) |
| 414 |
} else { |
| 415 |
v.accountLimiter = nil // Users cannot create accounts when logged in |
| 416 |
v.authLimiter = nil // Users are already logged in, no need to limit requests |
| 417 |
} |
| 418 |
if enqueueUpdate && v.user != nil { |
| 419 |
go v.userManager.EnqueueUserStats(v.user.ID, &user.Stats{ |
| 420 |
Messages: messages, |
| 421 |
Emails: emails, |
| 422 |
Calls: calls, |
| 423 |
}) |
| 424 |
} |
| 425 |
log.Fields(v.contextNoLock()).Debug("Rate limiters reset for visitor") // Must be after function, because contextNoLock() describes rate limiters |
| 426 |
} |
| 427 |
|
| 428 |
func (v *visitor) Limits() *visitorLimits { |
| 429 |
v.mu.RLock() |
| 430 |
defer v.mu.RUnlock() |
| 431 |
return v.limitsNoLock() |
| 432 |
} |
| 433 |
|
| 434 |
func (v *visitor) limitsNoLock() *visitorLimits { |
| 435 |
if v.user != nil && v.user.Tier != nil { |
| 436 |
return tierBasedVisitorLimits(v.config, v.user.Tier) |
| 437 |
} |
| 438 |
return configBasedVisitorLimits(v.config) |
| 439 |
} |
| 440 |
|
| 441 |
func tierBasedVisitorLimits(conf *Config, tier *user.Tier) *visitorLimits { |
| 442 |
return &visitorLimits{ |
| 443 |
Basis: visitorLimitBasisTier, |
| 444 |
RequestLimitBurst: util.MinMax(int(float64(tier.MessageLimit)*visitorMessageToRequestLimitBurstRate), conf.VisitorRequestLimitBurst, visitorMessageToRequestLimitBurstMax), |
| 445 |
RequestLimitReplenish: util.Max(rate.Every(conf.VisitorRequestLimitReplenish), dailyLimitToRate(tier.MessageLimit*visitorMessageToRequestLimitReplenishFactor)), |
| 446 |
MessageLimit: tier.MessageLimit, |
| 447 |
MessageExpiryDuration: tier.MessageExpiryDuration, |
| 448 |
EmailLimit: tier.EmailLimit, |
| 449 |
EmailLimitBurst: util.MinMax(int(float64(tier.EmailLimit)*visitorEmailLimitBurstRate), conf.VisitorEmailLimitBurst, visitorEmailLimitBurstMax), |
| 450 |
EmailLimitReplenish: dailyLimitToRate(tier.EmailLimit), |
| 451 |
CallLimit: tier.CallLimit, |
| 452 |
ReservationsLimit: tier.ReservationLimit, |
| 453 |
AttachmentTotalSizeLimit: tier.AttachmentTotalSizeLimit, |
| 454 |
AttachmentFileSizeLimit: tier.AttachmentFileSizeLimit, |
| 455 |
AttachmentExpiryDuration: tier.AttachmentExpiryDuration, |
| 456 |
AttachmentBandwidthLimit: tier.AttachmentBandwidthLimit, |
| 457 |
} |
| 458 |
} |
| 459 |
|
| 460 |
func configBasedVisitorLimits(conf *Config) *visitorLimits { |
| 461 |
messagesLimit := replenishDurationToDailyLimit(conf.VisitorRequestLimitReplenish) // Approximation! |
| 462 |
if conf.VisitorMessageDailyLimit > 0 { |
| 463 |
messagesLimit = int64(conf.VisitorMessageDailyLimit) |
| 464 |
} |
| 465 |
var emailLimit int64 |
| 466 |
if conf.VisitorEmailLimitBurst > 0 { |
| 467 |
emailLimit = replenishDurationToDailyLimit(conf.VisitorEmailLimitReplenish) // Approximation! |
| 468 |
} |
| 469 |
return &visitorLimits{ |
| 470 |
Basis: visitorLimitBasisIP, |
| 471 |
RequestLimitBurst: conf.VisitorRequestLimitBurst, |
| 472 |
RequestLimitReplenish: rate.Every(conf.VisitorRequestLimitReplenish), |
| 473 |
MessageLimit: messagesLimit, |
| 474 |
MessageExpiryDuration: conf.CacheDuration, |
| 475 |
EmailLimit: emailLimit, |
| 476 |
EmailLimitBurst: conf.VisitorEmailLimitBurst, |
| 477 |
EmailLimitReplenish: rate.Every(conf.VisitorEmailLimitReplenish), |
| 478 |
CallLimit: visitorDefaultCallsLimit, |
| 479 |
ReservationsLimit: visitorDefaultReservationsLimit, |
| 480 |
AttachmentTotalSizeLimit: conf.VisitorAttachmentTotalSizeLimit, |
| 481 |
AttachmentFileSizeLimit: conf.AttachmentFileSizeLimit, |
| 482 |
AttachmentExpiryDuration: conf.AttachmentExpiryDuration, |
| 483 |
AttachmentBandwidthLimit: conf.VisitorAttachmentDailyBandwidthLimit, |
| 484 |
} |
| 485 |
} |
| 486 |
|
| 487 |
func (v *visitor) Info() (*visitorInfo, error) { |
| 488 |
v.mu.RLock() |
| 489 |
info := v.infoLightNoLock() |
| 490 |
v.mu.RUnlock() |
| 491 |
|
| 492 |
// Attachment stats from database |
| 493 |
var attachmentsBytesUsed int64 |
| 494 |
var err error |
| 495 |
u := v.User() |
| 496 |
if u != nil { |
| 497 |
attachmentsBytesUsed, err = v.messageCache.AttachmentBytesUsedByUser(u.ID) |
| 498 |
} else { |
| 499 |
attachmentsBytesUsed, err = v.messageCache.AttachmentBytesUsedBySender(v.IP().String()) |
| 500 |
} |
| 501 |
if err != nil { |
| 502 |
return nil, err |
| 503 |
} |
| 504 |
info.Stats.AttachmentTotalSize = attachmentsBytesUsed |
| 505 |
info.Stats.AttachmentTotalSizeRemaining = zeroIfNegative(info.Limits.AttachmentTotalSizeLimit - attachmentsBytesUsed) |
| 506 |
|
| 507 |
// Reservation stats from database |
| 508 |
var reservations int64 |
| 509 |
if v.userManager != nil && u != nil { |
| 510 |
reservations, err = v.userManager.ReservationsCount(u.Name) |
| 511 |
if err != nil { |
| 512 |
return nil, err |
| 513 |
} |
| 514 |
} |
| 515 |
info.Stats.Reservations = reservations |
| 516 |
info.Stats.ReservationsRemaining = zeroIfNegative(info.Limits.ReservationsLimit - reservations) |
| 517 |
|
| 518 |
return info, nil |
| 519 |
} |
| 520 |
|
| 521 |
func (v *visitor) infoLightNoLock() *visitorInfo { |
| 522 |
messages := v.messagesLimiter.Value() |
| 523 |
emails := v.emailsLimiter.Value() |
| 524 |
calls := v.callsLimiter.Value() |
| 525 |
limits := v.limitsNoLock() |
| 526 |
stats := &visitorStats{ |
| 527 |
Messages: messages, |
| 528 |
MessagesRemaining: zeroIfNegative(limits.MessageLimit - messages), |
| 529 |
Emails: emails, |
| 530 |
EmailsRemaining: zeroIfNegative(limits.EmailLimit - emails), |
| 531 |
Calls: calls, |
| 532 |
CallsRemaining: zeroIfNegative(limits.CallLimit - calls), |
| 533 |
} |
| 534 |
return &visitorInfo{ |
| 535 |
Limits: limits, |
| 536 |
Stats: stats, |
| 537 |
} |
| 538 |
} |
| 539 |
func zeroIfNegative(value int64) int64 { |
| 540 |
if value < 0 { |
| 541 |
return 0 |
| 542 |
} |
| 543 |
return value |
| 544 |
} |
| 545 |
|
| 546 |
func replenishDurationToDailyLimit(duration time.Duration) int64 { |
| 547 |
return int64(oneDay / duration) |
| 548 |
} |
| 549 |
|
| 550 |
func dailyLimitToRate(limit int64) rate.Limit { |
| 551 |
return rate.Limit(limit) * rate.Every(oneDay) |
| 552 |
} |
| 553 |
|
| 554 |
// visitorID returns a unique identifier for a visitor based on user or IP, using configurable prefix bits for IPv4/IPv6 |
| 555 |
func visitorID(ip netip.Addr, u *user.User, conf *Config) string { |
| 556 |
if u != nil && u.Tier != nil { |
| 557 |
return fmt.Sprintf("user:%s", u.ID) |
| 558 |
} |
| 559 |
if ip.Is4() { |
| 560 |
ip = netip.PrefixFrom(ip, conf.VisitorPrefixBitsIPv4).Masked().Addr() |
| 561 |
} else if ip.Is6() { |
| 562 |
ip = netip.PrefixFrom(ip, conf.VisitorPrefixBitsIPv6).Masked().Addr() |
| 563 |
} |
| 564 |
return fmt.Sprintf("ip:%s", ip.String()) |
| 565 |
} |