github.com/sagernet/sing-box@v1.9.0-rc.20/transport/fakeip/memory.go (about) 1 package fakeip 2 3 import ( 4 "net/netip" 5 "sync" 6 7 "github.com/sagernet/sing-box/adapter" 8 "github.com/sagernet/sing/common/logger" 9 ) 10 11 var _ adapter.FakeIPStorage = (*MemoryStorage)(nil) 12 13 type MemoryStorage struct { 14 addressAccess sync.RWMutex 15 domainAccess sync.RWMutex 16 addressCache map[netip.Addr]string 17 domainCache4 map[string]netip.Addr 18 domainCache6 map[string]netip.Addr 19 } 20 21 func NewMemoryStorage() *MemoryStorage { 22 return &MemoryStorage{ 23 addressCache: make(map[netip.Addr]string), 24 domainCache4: make(map[string]netip.Addr), 25 domainCache6: make(map[string]netip.Addr), 26 } 27 } 28 29 func (s *MemoryStorage) FakeIPMetadata() *adapter.FakeIPMetadata { 30 return nil 31 } 32 33 func (s *MemoryStorage) FakeIPSaveMetadata(metadata *adapter.FakeIPMetadata) error { 34 return nil 35 } 36 37 func (s *MemoryStorage) FakeIPSaveMetadataAsync(metadata *adapter.FakeIPMetadata) { 38 } 39 40 func (s *MemoryStorage) FakeIPStore(address netip.Addr, domain string) error { 41 s.addressAccess.Lock() 42 s.domainAccess.Lock() 43 if oldDomain, loaded := s.addressCache[address]; loaded { 44 if address.Is4() { 45 delete(s.domainCache4, oldDomain) 46 } else { 47 delete(s.domainCache6, oldDomain) 48 } 49 } 50 s.addressCache[address] = domain 51 if address.Is4() { 52 s.domainCache4[domain] = address 53 } else { 54 s.domainCache6[domain] = address 55 } 56 s.domainAccess.Unlock() 57 s.addressAccess.Unlock() 58 return nil 59 } 60 61 func (s *MemoryStorage) FakeIPStoreAsync(address netip.Addr, domain string, logger logger.Logger) { 62 _ = s.FakeIPStore(address, domain) 63 } 64 65 func (s *MemoryStorage) FakeIPLoad(address netip.Addr) (string, bool) { 66 s.addressAccess.RLock() 67 defer s.addressAccess.RUnlock() 68 domain, loaded := s.addressCache[address] 69 return domain, loaded 70 } 71 72 func (s *MemoryStorage) FakeIPLoadDomain(domain string, isIPv6 bool) (netip.Addr, bool) { 73 s.domainAccess.RLock() 74 defer s.domainAccess.RUnlock() 75 if !isIPv6 { 76 address, loaded := s.domainCache4[domain] 77 return address, loaded 78 } else { 79 address, loaded := s.domainCache6[domain] 80 return address, loaded 81 } 82 } 83 84 func (s *MemoryStorage) FakeIPReset() error { 85 s.addressCache = make(map[netip.Addr]string) 86 s.domainCache4 = make(map[string]netip.Addr) 87 s.domainCache6 = make(map[string]netip.Addr) 88 return nil 89 }