-
Notifications
You must be signed in to change notification settings - Fork 13
/
local_routes.go
76 lines (67 loc) · 1.38 KB
/
local_routes.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
75
76
package main
import (
"github.com/vishvananda/netlink"
"gopkg.in/netaddr.v1"
"net"
"sync"
"time"
)
type LocalRoutes struct {
sync.RWMutex
ipset *netaddr.IPSet
ticker *time.Ticker
done chan bool
}
func (lr *LocalRoutes) Contains(ip net.IP) bool {
lr.RLock()
r := lr.ipset.Contains(ip)
lr.RUnlock()
return r
}
func (lr *LocalRoutes) Start(interval time.Duration) {
lr.Lock()
lr.ticker = time.NewTicker(interval)
lr.done = make(chan bool)
lr.ipset = FetchLocalRoutes()
lr.Unlock()
go func() {
for {
lr.Lock()
lr.ipset = FetchLocalRoutes()
lr.Unlock()
select {
case <-lr.done:
return
case <-lr.ticker.C:
}
}
}()
}
func (lr *LocalRoutes) Stop() {
lr.Lock()
close(lr.done)
lr.Unlock()
}
// Regularly load "local" and "main" routing tables, for both IPv4 and
// IPv6. The idea is to refuse connections to IP ranges that might be
// local.
func FetchLocalRoutes() *netaddr.IPSet {
ipset := netaddr.IPSet{}
// "local" routing table
fltr := netlink.Route{Table: 255}
routes, _ := netlink.RouteListFiltered(0, &fltr, netlink.RT_FILTER_TABLE)
for _, r := range routes {
if r.Dst != nil {
ipset.InsertNet(r.Dst)
}
}
// "main" routing table
fltr = netlink.Route{Table: 254}
routes, _ = netlink.RouteListFiltered(0, &fltr, netlink.RT_FILTER_TABLE)
for _, r := range routes {
if r.Dst != nil {
ipset.InsertNet(r.Dst)
}
}
return &ipset
}