sing-box/transport/fakeip/memory.go

90 lines
2.2 KiB
Go
Raw Normal View History

2023-03-25 12:03:23 +08:00
package fakeip
import (
"net/netip"
2023-07-11 14:05:14 +08:00
"sync"
2023-03-25 12:03:23 +08:00
"github.com/sagernet/sing-box/adapter"
2023-07-08 16:08:46 +08:00
"github.com/sagernet/sing/common/logger"
2023-03-25 12:03:23 +08:00
)
var _ adapter.FakeIPStorage = (*MemoryStorage)(nil)
type MemoryStorage struct {
2023-07-11 14:05:14 +08:00
addressAccess sync.RWMutex
domainAccess sync.RWMutex
addressCache map[netip.Addr]string
domainCache4 map[string]netip.Addr
domainCache6 map[string]netip.Addr
2023-03-25 12:03:23 +08:00
}
func NewMemoryStorage() *MemoryStorage {
return &MemoryStorage{
2023-07-11 14:05:14 +08:00
addressCache: make(map[netip.Addr]string),
domainCache4: make(map[string]netip.Addr),
domainCache6: make(map[string]netip.Addr),
2023-03-25 12:03:23 +08:00
}
}
func (s *MemoryStorage) FakeIPMetadata() *adapter.FakeIPMetadata {
2023-07-11 14:05:14 +08:00
return nil
2023-03-25 12:03:23 +08:00
}
func (s *MemoryStorage) FakeIPSaveMetadata(metadata *adapter.FakeIPMetadata) error {
return nil
}
2023-08-07 21:53:19 +08:00
func (s *MemoryStorage) FakeIPSaveMetadataAsync(metadata *adapter.FakeIPMetadata) {
}
2023-03-25 12:03:23 +08:00
func (s *MemoryStorage) FakeIPStore(address netip.Addr, domain string) error {
2023-07-11 14:05:14 +08:00
s.addressAccess.Lock()
s.domainAccess.Lock()
2024-04-27 22:31:12 +08:00
if oldDomain, loaded := s.addressCache[address]; loaded {
if address.Is4() {
delete(s.domainCache4, oldDomain)
} else {
delete(s.domainCache6, oldDomain)
}
}
2023-07-11 14:05:14 +08:00
s.addressCache[address] = domain
if address.Is4() {
s.domainCache4[domain] = address
} else {
s.domainCache6[domain] = address
}
s.domainAccess.Unlock()
s.addressAccess.Unlock()
2023-03-25 12:03:23 +08:00
return nil
}
2023-07-08 16:08:46 +08:00
func (s *MemoryStorage) FakeIPStoreAsync(address netip.Addr, domain string, logger logger.Logger) {
2023-07-11 14:05:14 +08:00
_ = s.FakeIPStore(address, domain)
2023-07-08 16:08:46 +08:00
}
2023-03-25 12:03:23 +08:00
func (s *MemoryStorage) FakeIPLoad(address netip.Addr) (string, bool) {
2023-07-11 14:05:14 +08:00
s.addressAccess.RLock()
defer s.addressAccess.RUnlock()
domain, loaded := s.addressCache[address]
return domain, loaded
}
func (s *MemoryStorage) FakeIPLoadDomain(domain string, isIPv6 bool) (netip.Addr, bool) {
s.domainAccess.RLock()
defer s.domainAccess.RUnlock()
if !isIPv6 {
address, loaded := s.domainCache4[domain]
return address, loaded
} else {
address, loaded := s.domainCache6[domain]
return address, loaded
}
2023-03-25 12:03:23 +08:00
}
func (s *MemoryStorage) FakeIPReset() error {
2023-07-11 14:05:14 +08:00
s.addressCache = make(map[netip.Addr]string)
s.domainCache4 = make(map[string]netip.Addr)
s.domainCache6 = make(map[string]netip.Addr)
2023-03-25 12:03:23 +08:00
return nil
}