Files
allmende/internal/p2p/ipgate.go
T

121 lines
3.4 KiB
Go

package p2p
import (
"net"
"sync"
"sync/atomic"
"github.com/libp2p/go-libp2p/core/control"
"github.com/libp2p/go-libp2p/core/network"
"github.com/libp2p/go-libp2p/core/peer"
ma "github.com/multiformats/go-multiaddr"
)
// DefaultConnsPerIP is how many inbound connections one public IP address may
// hold. A household or an office with a few nodes behind one router stays well
// below it; one machine that mints peer IDs to get around a ban does not.
const DefaultConnsPerIP = 16
// ipGate is the node's connection gater. It refuses an inbound connection when
// its source address already holds the limit, and any connection from a peer the
// guard has banned (so a ban cannot be undone by redialing). Local, private and
// link-local addresses are exempt: a LAN, the simulator and a cluster network
// that hides real source addresses behind one internal address would otherwise
// lock out everyone at once.
type ipGate struct {
max int // per address; 0 means no limit
mu sync.Mutex
counts map[string]int
banned atomic.Pointer[func(peer.ID) bool]
// Totals since the start, for the metrics.
refusedFull atomic.Uint64 // connections refused: the source address was full
refusedBanned atomic.Uint64 // connections refused: the peer is banned
}
func newIPGate(max int) *ipGate { return &ipGate{max: max, counts: map[string]int{}} }
// ipKey names the source of a connection: the IPv4 address, or the /64 of an
// IPv6 one (a single machine usually owns a whole /64). It is empty for
// addresses that are exempt or not IP at all.
func ipKey(a ma.Multiaddr) string {
for _, code := range []int{ma.P_IP4, ma.P_IP6} {
v, err := a.ValueForProtocol(code)
if err != nil {
continue
}
ip := net.ParseIP(v)
if ip == nil || ip.IsLoopback() || ip.IsPrivate() || ip.IsLinkLocalUnicast() || ip.IsUnspecified() {
return ""
}
if ip4 := ip.To4(); ip4 != nil {
return ip4.String()
}
return ip.Mask(net.CIDRMask(64, 128)).String() + "/64"
}
return ""
}
func (g *ipGate) full(a ma.Multiaddr) bool {
if g.max <= 0 {
return false
}
k := ipKey(a)
if k == "" {
return false
}
g.mu.Lock()
defer g.mu.Unlock()
return g.counts[k] >= g.max
}
// connection gater
func (g *ipGate) InterceptPeerDial(peer.ID) bool { return true }
func (g *ipGate) InterceptAddrDial(peer.ID, ma.Multiaddr) bool { return true }
func (g *ipGate) InterceptAccept(cm network.ConnMultiaddrs) bool {
if g.full(cm.RemoteMultiaddr()) {
g.refusedFull.Add(1)
return false
}
return true
}
func (g *ipGate) InterceptSecured(dir network.Direction, p peer.ID, _ network.ConnMultiaddrs) bool {
if dir == network.DirInbound {
if f := g.banned.Load(); f != nil && (*f)(p) {
g.refusedBanned.Add(1)
return false
}
}
return true
}
func (g *ipGate) InterceptUpgraded(network.Conn) (bool, control.DisconnectReason) { return true, 0 }
// notifee: count the inbound connections that got established
func (g *ipGate) track(c network.Conn, delta int) {
if g.max <= 0 || c.Stat().Direction != network.DirInbound {
return
}
k := ipKey(c.RemoteMultiaddr())
if k == "" {
return
}
g.mu.Lock()
defer g.mu.Unlock()
if g.counts[k]+delta <= 0 {
delete(g.counts, k)
return
}
g.counts[k] += delta
}
func (g *ipGate) notifee() network.Notifiee {
return &network.NotifyBundle{
ConnectedF: func(_ network.Network, c network.Conn) { g.track(c, 1) },
DisconnectedF: func(_ network.Network, c network.Conn) { g.track(c, -1) },
}
}