forked from anacrolix/torrent
-
Notifications
You must be signed in to change notification settings - Fork 0
/
connections.go
69 lines (55 loc) · 1.24 KB
/
connections.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
package connections
import (
"errors"
"net"
"github.com/james-lawrence/torrent/internal/netx"
)
// Handshaker accepts connections from a net listener and performs
// a handshake to ensure the connection is acceptable.
type Handshaker interface {
Accept(l net.Listener) (net.Conn, error)
Release(c net.Conn, cause error) error
}
// NewHandshaker default handshake method.
func NewHandshaker(firewall FirewallStateful) Handshaker {
return handshaker{
Firewall: firewall,
}
}
type handshaker struct {
Firewall FirewallStateful
}
func (t handshaker) Accept(l net.Listener) (c net.Conn, err error) {
var (
rip net.IP
port int
conn net.Conn
)
for {
if conn, err = l.Accept(); err != nil {
return nil, err
}
if rip, port, err = netx.NetIPPort(conn.RemoteAddr()); err != nil {
conn.Close()
continue
}
if err = t.Firewall.Blocked(rip, port); err != nil {
conn.Close()
continue
}
return conn, nil
}
}
func (t handshaker) Release(conn net.Conn, cause error) (err error) {
var (
rip net.IP
port int
)
if rip, port, err = netx.NetIPPort(conn.RemoteAddr()); err != nil {
return err
}
if banned := new(bannedConnection); errors.As(cause, banned) {
t.Firewall.Inhibit(rip, port, cause)
}
return conn.Close()
}