resolve.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. package dialer
  2. import (
  3. "context"
  4. "net"
  5. "net/netip"
  6. M "github.com/sagernet/sing/common/metadata"
  7. N "github.com/sagernet/sing/common/network"
  8. "github.com/sagernet/sing-box/adapter"
  9. C "github.com/sagernet/sing-box/constant"
  10. )
  11. type ResolveDialer struct {
  12. dialer N.Dialer
  13. router adapter.Router
  14. strategy C.DomainStrategy
  15. }
  16. func NewResolveDialer(router adapter.Router, dialer N.Dialer, strategy C.DomainStrategy) *ResolveDialer {
  17. return &ResolveDialer{
  18. dialer,
  19. router,
  20. strategy,
  21. }
  22. }
  23. func (d *ResolveDialer) DialContext(ctx context.Context, network string, destination M.Socksaddr) (net.Conn, error) {
  24. if !destination.IsFqdn() {
  25. return d.dialer.DialContext(ctx, network, destination)
  26. }
  27. var addresses []netip.Addr
  28. var err error
  29. if d.strategy == C.DomainStrategyAsIS {
  30. addresses, err = d.router.LookupDefault(ctx, destination.Fqdn)
  31. } else {
  32. addresses, err = d.router.Lookup(ctx, destination.Fqdn, d.strategy)
  33. }
  34. if err != nil {
  35. return nil, err
  36. }
  37. return DialSerial(ctx, d.dialer, network, destination, addresses)
  38. }
  39. func (d *ResolveDialer) ListenPacket(ctx context.Context, destination M.Socksaddr) (net.PacketConn, error) {
  40. if !destination.IsFqdn() {
  41. return d.dialer.ListenPacket(ctx, destination)
  42. }
  43. var addresses []netip.Addr
  44. var err error
  45. if d.strategy == C.DomainStrategyAsIS {
  46. addresses, err = d.router.LookupDefault(ctx, destination.Fqdn)
  47. } else {
  48. addresses, err = d.router.Lookup(ctx, destination.Fqdn, d.strategy)
  49. }
  50. if err != nil {
  51. return nil, err
  52. }
  53. return ListenSerial(ctx, d.dialer, destination, addresses)
  54. }
  55. func (d *ResolveDialer) Upstream() any {
  56. return d.dialer
  57. }