-
Notifications
You must be signed in to change notification settings - Fork 92
/
limiter.go
74 lines (62 loc) · 2.01 KB
/
limiter.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package p2p
import (
"fmt"
"net"
"strings"
"time"
)
// limitListenerSources will limit the number of connections allowed to 1
// connection per ip per second. Any more than that it will reject.
// The rate limiting is pretty dumb, when a connection is made, no other
// connection by that IP is allowed for 1 second
type limitListenerSources struct {
net.Listener
// This is not garbage collected, be aware it is a small memory leak
// TODO: Fix the memory leak issue.
// Technically it is bounded by the number of possible IP addresses, so it will consume
// at most ~34.4GB if every possible ipv4 address connects.
accepted map[string]time.Time
}
// Accept is overridden here to the default Accept
func (l *limitListenerSources) Accept() (net.Conn, error) {
// We need to accept the connection first to determine the IP address.
c, err := l.Listener.Accept()
if err != nil {
return nil, err
}
// Grab the address, check for last connection
addr := strings.Split(c.RemoteAddr().String(), ":")
if v, ok := l.accepted[addr[0]]; !ok || time.Since(v) > time.Second {
l.accepted[addr[0]] = time.Now()
return c, nil
}
c.Close()
return nil, fmt.Errorf("rate limited")
}
func LimitListenerSources(l net.Listener) net.Listener {
return &limitListenerSources{Listener: l, accepted: make(map[string]time.Time)}
}
// limitListenerAll will limit the number of connections allowed to 1
// connection per second. Any more than that it will reject.
// The rate limiting is pretty dumb, when a connection is made, no other
// connection is allowed for 1 second
type limitListenerAll struct {
net.Listener
last time.Time
}
// Accept is overridden here to the default Accept
func (l *limitListenerAll) Accept() (net.Conn, error) {
if time.Since(l.last) < time.Second {
return nil, fmt.Errorf("rate limited")
}
fmt.Println("Accepted")
c, err := l.Listener.Accept()
if err != nil {
return nil, err
}
l.last = time.Now()
return c, nil
}
func LimitListenerAll(l net.Listener) net.Listener {
return &limitListenerAll{Listener: l}
}