CheckConnection checks if a connection from the given address should be allowed. Returns an error message if the connection should be rejected, or empty string if allowed.
(addr net.Addr)
| 74 | // CheckConnection checks if a connection from the given address should be allowed. |
| 75 | // Returns an error message if the connection should be rejected, or empty string if allowed. |
| 76 | func (rl *RateLimiter) CheckConnection(addr net.Addr) string { |
| 77 | ip := extractIP(addr) |
| 78 | if ip == "" { |
| 79 | return "" |
| 80 | } |
| 81 | |
| 82 | rl.mu.Lock() |
| 83 | defer rl.mu.Unlock() |
| 84 | |
| 85 | if rl.config.MaxConnections > 0 && rl.totalActiveConns >= rl.config.MaxConnections { |
| 86 | return "too many concurrent connections" |
| 87 | } |
| 88 | |
| 89 | record := rl.getOrCreateRecord(ip) |
| 90 | |
| 91 | if !record.bannedUntil.IsZero() && time.Now().Before(record.bannedUntil) { |
| 92 | remaining := time.Until(record.bannedUntil).Round(time.Second) |
| 93 | return "too many failed authentication attempts, try again in " + remaining.String() |
| 94 | } |
| 95 | |
| 96 | if rl.config.MaxConnectionsPerIP > 0 && record.activeConns >= rl.config.MaxConnectionsPerIP { |
| 97 | return "too many connections from your IP address" |
| 98 | } |
| 99 | |
| 100 | return "" |
| 101 | } |
| 102 | |
| 103 | // RegisterConnection records a new connection from the given address. |
| 104 | // Returns true if the connection is allowed, false otherwise. |