sing-box/transport/fakeip/memory.go

90 lines
2.2 KiB
Go
Raw Permalink Normal View History

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