sing-box/common/dialer/resolve.go

78 lines
2.0 KiB
Go
Raw Normal View History

2022-07-07 21:47:21 +08:00
package dialer
import (
"context"
"net"
"net/netip"
2022-07-08 12:58:43 +08:00
"time"
2022-07-07 21:47:21 +08:00
"github.com/sagernet/sing-box/adapter"
C "github.com/sagernet/sing-box/constant"
2022-07-08 23:03:57 +08:00
M "github.com/sagernet/sing/common/metadata"
N "github.com/sagernet/sing/common/network"
2022-07-07 21:47:21 +08:00
)
type ResolveDialer struct {
2022-07-08 12:58:43 +08:00
dialer N.Dialer
router adapter.Router
strategy C.DomainStrategy
fallbackDelay time.Duration
2022-07-07 21:47:21 +08:00
}
2022-07-08 12:58:43 +08:00
func NewResolveDialer(router adapter.Router, dialer N.Dialer, strategy C.DomainStrategy, fallbackDelay time.Duration) *ResolveDialer {
2022-07-07 21:47:21 +08:00
return &ResolveDialer{
dialer,
router,
strategy,
2022-07-08 12:58:43 +08:00
fallbackDelay,
2022-07-07 21:47:21 +08:00
}
}
func (d *ResolveDialer) DialContext(ctx context.Context, network string, destination M.Socksaddr) (net.Conn, error) {
if !destination.IsFqdn() {
return d.dialer.DialContext(ctx, network, destination)
}
2022-07-10 09:15:01 +08:00
ctx, metadata := adapter.AppendContext(ctx)
metadata.Destination = destination
metadata.Domain = ""
2022-07-07 21:47:21 +08:00
var addresses []netip.Addr
var err error
if d.strategy == C.DomainStrategyAsIS {
addresses, err = d.router.LookupDefault(ctx, destination.Fqdn)
} else {
addresses, err = d.router.Lookup(ctx, destination.Fqdn, d.strategy)
}
if err != nil {
return nil, err
}
2022-07-08 12:58:43 +08:00
return DialParallel(ctx, d.dialer, network, destination, addresses, d.strategy, d.fallbackDelay)
2022-07-07 21:47:21 +08:00
}
func (d *ResolveDialer) ListenPacket(ctx context.Context, destination M.Socksaddr) (net.PacketConn, error) {
if !destination.IsFqdn() {
return d.dialer.ListenPacket(ctx, destination)
}
2022-07-10 09:15:01 +08:00
ctx, metadata := adapter.AppendContext(ctx)
metadata.Destination = destination
metadata.Domain = ""
2022-07-07 21:47:21 +08:00
var addresses []netip.Addr
var err error
if d.strategy == C.DomainStrategyAsIS {
addresses, err = d.router.LookupDefault(ctx, destination.Fqdn)
} else {
addresses, err = d.router.Lookup(ctx, destination.Fqdn, d.strategy)
}
if err != nil {
return nil, err
}
2022-07-08 12:58:43 +08:00
conn, err := ListenSerial(ctx, d.dialer, destination, addresses)
if err != nil {
return nil, err
}
return NewResolvePacketConn(d.router, d.strategy, conn), nil
2022-07-07 21:47:21 +08:00
}
func (d *ResolveDialer) Upstream() any {
return d.dialer
}