Files
sing-tun/route_direct.go

62 lines
1.6 KiB
Go
Raw Normal View History

2025-08-24 10:36:16 +08:00
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
2025-08-24 17:46:03 +08:00
IsClosed() bool
2025-08-24 10:36:16 +08:00
}
type DirectRouteSession struct {
// IPVersion uint8
// Network uint8
Source netip.Addr
Destination netip.Addr
}
type DirectRouteMapping struct {
mapping freelru.Cache[DirectRouteSession, DirectRouteDestination]
2025-08-24 18:59:55 +08:00
timeout time.Duration
2025-08-24 10:36:16 +08:00
}
func NewDirectRouteMapping(timeout time.Duration) *DirectRouteMapping {
mapping := common.Must1(freelru.NewSharded[DirectRouteSession, DirectRouteDestination](1024, maphash.NewHasher[DirectRouteSession]().Hash32))
2025-08-24 21:09:55 +08:00
mapping.SetHealthCheck(func(session DirectRouteSession, action DirectRouteDestination) bool {
if action != nil {
return !action.IsClosed()
}
return true
2025-08-24 17:46:03 +08:00
})
2025-08-24 10:36:16 +08:00
mapping.SetOnEvict(func(session DirectRouteSession, action DirectRouteDestination) {
2025-08-24 21:09:55 +08:00
if action != nil {
action.Close()
}
2025-08-24 10:36:16 +08:00
})
mapping.SetLifetime(timeout)
2025-08-24 18:59:55 +08:00
return &DirectRouteMapping{mapping, timeout}
2025-08-24 10:36:16 +08:00
}
2025-08-24 18:59:55 +08:00
func (m *DirectRouteMapping) Lookup(session DirectRouteSession, constructor func(timeout time.Duration) (DirectRouteDestination, error)) (DirectRouteDestination, error) {
2025-08-24 10:36:16 +08:00
var (
created DirectRouteDestination
err error
)
action, _, ok := m.mapping.GetAndRefreshOrAdd(session, func() (DirectRouteDestination, bool) {
2025-08-24 18:59:55 +08:00
created, err = constructor(m.timeout)
2025-08-24 10:36:16 +08:00
return created, err == nil
})
if !ok {
return nil, err
}
return action, nil
}