github.com/sagernet/sing-box@v1.9.0-rc.20/transport/fakeip/server.go (about) 1 package fakeip 2 3 import ( 4 "context" 5 "net/netip" 6 "os" 7 8 "github.com/sagernet/sing-box/adapter" 9 "github.com/sagernet/sing-dns" 10 E "github.com/sagernet/sing/common/exceptions" 11 "github.com/sagernet/sing/common/logger" 12 13 mDNS "github.com/miekg/dns" 14 ) 15 16 var ( 17 _ dns.Transport = (*Transport)(nil) 18 _ adapter.FakeIPTransport = (*Transport)(nil) 19 ) 20 21 func init() { 22 dns.RegisterTransport([]string{"fakeip"}, func(options dns.TransportOptions) (dns.Transport, error) { 23 return NewTransport(options) 24 }) 25 } 26 27 type Transport struct { 28 name string 29 router adapter.Router 30 store adapter.FakeIPStore 31 logger logger.ContextLogger 32 } 33 34 func NewTransport(options dns.TransportOptions) (*Transport, error) { 35 router := adapter.RouterFromContext(options.Context) 36 if router == nil { 37 return nil, E.New("missing router in context") 38 } 39 return &Transport{ 40 name: options.Name, 41 router: router, 42 logger: options.Logger, 43 }, nil 44 } 45 46 func (s *Transport) Name() string { 47 return s.name 48 } 49 50 func (s *Transport) Start() error { 51 s.store = s.router.FakeIPStore() 52 if s.store == nil { 53 return E.New("fakeip not enabled") 54 } 55 return nil 56 } 57 58 func (s *Transport) Reset() { 59 } 60 61 func (s *Transport) Close() error { 62 return nil 63 } 64 65 func (s *Transport) Raw() bool { 66 return false 67 } 68 69 func (s *Transport) Exchange(ctx context.Context, message *mDNS.Msg) (*mDNS.Msg, error) { 70 return nil, os.ErrInvalid 71 } 72 73 func (s *Transport) Lookup(ctx context.Context, domain string, strategy dns.DomainStrategy) ([]netip.Addr, error) { 74 var addresses []netip.Addr 75 if strategy != dns.DomainStrategyUseIPv6 { 76 inet4Address, err := s.store.Create(domain, false) 77 if err != nil { 78 return nil, err 79 } 80 addresses = append(addresses, inet4Address) 81 } 82 if strategy != dns.DomainStrategyUseIPv4 { 83 inet6Address, err := s.store.Create(domain, true) 84 if err != nil { 85 return nil, err 86 } 87 addresses = append(addresses, inet6Address) 88 } 89 return addresses, nil 90 } 91 92 func (s *Transport) Store() adapter.FakeIPStore { 93 return s.store 94 }