-
Notifications
You must be signed in to change notification settings - Fork 182
Expand file tree
/
Copy pathroute_direct.go
More file actions
61 lines (54 loc) · 1.58 KB
/
route_direct.go
File metadata and controls
61 lines (54 loc) · 1.58 KB
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
package tun
import (
"net/netip"
"time"
"github.com/sagernet/sing/common"
"github.com/sagernet/sing/common/buf"
"github.com/sagernet/sing/contrab/freelru"
"github.com/sagernet/sing/contrab/maphash"
)
type DirectRouteDestination interface {
WritePacket(packet *buf.Buffer) error
Close() error
IsClosed() bool
}
type DirectRouteSession struct {
// IPVersion uint8
// Network uint8
Source netip.Addr
Destination netip.Addr
}
type DirectRouteMapping struct {
mapping freelru.Cache[DirectRouteSession, DirectRouteDestination]
timeout time.Duration
}
func NewDirectRouteMapping(timeout time.Duration) *DirectRouteMapping {
mapping := common.Must1(freelru.NewSharded[DirectRouteSession, DirectRouteDestination](1024, maphash.NewHasher[DirectRouteSession]().Hash32))
mapping.SetHealthCheck(func(session DirectRouteSession, action DirectRouteDestination) bool {
if action != nil {
return !action.IsClosed()
}
return true
})
mapping.SetOnEvict(func(session DirectRouteSession, action DirectRouteDestination) {
if action != nil {
action.Close()
}
})
mapping.SetLifetime(timeout)
return &DirectRouteMapping{mapping, timeout}
}
func (m *DirectRouteMapping) Lookup(session DirectRouteSession, constructor func(timeout time.Duration) (DirectRouteDestination, error)) (DirectRouteDestination, error) {
var (
created DirectRouteDestination
err error
)
action, _, ok := m.mapping.GetAndRefreshOrAdd(session, func() (DirectRouteDestination, bool) {
created, err = constructor(m.timeout)
return created, err == nil
})
if !ok {
return nil, err
}
return action, nil
}