sing-box/transport/fakeip/memory.go

80 lines
1.9 KiB
Go
Raw 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
}
func (s *MemoryStorage) FakeIPStore(address netip.Addr, domain string) error {
2023-07-11 06:05:14 +00:00
s.addressAccess.Lock()
s.domainAccess.Lock()
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
}