sing-box/common/dialer/default.go

304 lines
12 KiB
Go
Raw Normal View History

package dialer
import (
"context"
"net"
2024-11-18 18:55:34 +08:00
"net/netip"
"time"
"github.com/sagernet/sing-box/adapter"
2023-09-20 14:12:08 +08:00
"github.com/sagernet/sing-box/common/conntrack"
2022-07-06 15:01:09 +08:00
C "github.com/sagernet/sing-box/constant"
"github.com/sagernet/sing-box/option"
2024-11-13 19:05:28 +08:00
"github.com/sagernet/sing/common"
2024-11-12 19:37:10 +08:00
"github.com/sagernet/sing/common/atomic"
2022-07-08 23:03:57 +08:00
"github.com/sagernet/sing/common/control"
2022-08-29 19:58:58 +08:00
E "github.com/sagernet/sing/common/exceptions"
2022-07-08 23:03:57 +08:00
M "github.com/sagernet/sing/common/metadata"
2022-07-30 00:29:22 +08:00
N "github.com/sagernet/sing/common/network"
)
2024-11-12 19:37:10 +08:00
var (
_ ParallelInterfaceDialer = (*DefaultDialer)(nil)
_ WireGuardListener = (*DefaultDialer)(nil)
)
2022-07-07 21:47:21 +08:00
type DefaultDialer struct {
2024-11-12 19:37:10 +08:00
dialer4 tcpDialer
dialer6 tcpDialer
udpDialer4 net.Dialer
udpDialer6 net.Dialer
udpListener net.ListenConfig
udpAddr4 string
udpAddr6 string
isWireGuardListener bool
networkManager adapter.NetworkManager
networkStrategy C.NetworkStrategy
2024-11-13 19:05:28 +08:00
networkType []C.InterfaceType
fallbackNetworkType []C.InterfaceType
2024-11-12 19:37:10 +08:00
networkFallbackDelay time.Duration
networkLastFallback atomic.TypedValue[time.Time]
}
2024-11-10 12:11:21 +08:00
func NewDefault(networkManager adapter.NetworkManager, options option.DialerOptions) (*DefaultDialer, error) {
2024-11-12 19:37:10 +08:00
var (
dialer net.Dialer
listener net.ListenConfig
interfaceFinder control.InterfaceFinder
networkStrategy C.NetworkStrategy
2024-11-13 19:05:28 +08:00
networkType []C.InterfaceType
fallbackNetworkType []C.InterfaceType
2024-11-12 19:37:10 +08:00
networkFallbackDelay time.Duration
)
if networkManager != nil {
interfaceFinder = networkManager.InterfaceFinder()
} else {
interfaceFinder = control.NewDefaultInterfaceFinder()
}
if options.BindInterface != "" {
2024-04-25 22:16:13 +08:00
bindFunc := control.BindToInterface(interfaceFinder, options.BindInterface, -1)
2022-08-04 22:01:20 +08:00
dialer.Control = control.Append(dialer.Control, bindFunc)
listener.Control = control.Append(listener.Control, bindFunc)
2024-06-07 15:55:21 +08:00
}
if options.RoutingMark > 0 {
2024-11-13 19:05:28 +08:00
dialer.Control = control.Append(dialer.Control, control.RoutingMark(uint32(options.RoutingMark)))
listener.Control = control.Append(listener.Control, control.RoutingMark(uint32(options.RoutingMark)))
2024-11-12 19:37:10 +08:00
}
if networkManager != nil {
autoRedirectOutputMark := networkManager.AutoRedirectOutputMark()
2024-06-07 15:55:21 +08:00
if autoRedirectOutputMark > 0 {
2024-11-12 19:37:10 +08:00
if options.RoutingMark > 0 {
return nil, E.New("`routing_mark` is conflict with `tun.auto_redirect` with `tun.route_[_exclude]_address_set")
}
dialer.Control = control.Append(dialer.Control, control.RoutingMark(autoRedirectOutputMark))
listener.Control = control.Append(listener.Control, control.RoutingMark(autoRedirectOutputMark))
2024-06-07 15:55:21 +08:00
}
2024-11-12 19:37:10 +08:00
}
if C.NetworkStrategy(options.NetworkStrategy) != C.NetworkStrategyDefault {
if options.BindInterface != "" || options.Inet4BindAddress != nil || options.Inet6BindAddress != nil {
return nil, E.New("`network_strategy` is conflict with `bind_interface`, `inet4_bind_address` and `inet6_bind_address`")
}
networkStrategy = C.NetworkStrategy(options.NetworkStrategy)
2024-11-13 19:05:28 +08:00
networkType = common.Map(options.NetworkType, option.InterfaceType.Build)
fallbackNetworkType = common.Map(options.FallbackNetworkType, option.InterfaceType.Build)
2024-11-12 19:37:10 +08:00
networkFallbackDelay = time.Duration(options.NetworkFallbackDelay)
if networkManager == nil || !networkManager.AutoDetectInterface() {
return nil, E.New("`route.auto_detect_interface` is require by `network_strategy`")
}
}
if networkManager != nil && options.BindInterface == "" && options.Inet4BindAddress == nil && options.Inet6BindAddress == nil {
defaultOptions := networkManager.DefaultOptions()
2024-11-13 19:05:28 +08:00
if options.BindInterface == "" {
if defaultOptions.BindInterface != "" {
bindFunc := control.BindToInterface(networkManager.InterfaceFinder(), defaultOptions.BindInterface, -1)
2024-11-12 19:37:10 +08:00
dialer.Control = control.Append(dialer.Control, bindFunc)
listener.Control = control.Append(listener.Control, bindFunc)
2024-11-13 19:05:28 +08:00
} else if networkManager.AutoDetectInterface() {
if defaultOptions.NetworkStrategy != C.NetworkStrategyDefault && C.NetworkStrategy(options.NetworkStrategy) == C.NetworkStrategyDefault {
networkStrategy = defaultOptions.NetworkStrategy
networkType = defaultOptions.NetworkType
fallbackNetworkType = defaultOptions.FallbackNetworkType
networkFallbackDelay = defaultOptions.FallbackDelay
bindFunc := networkManager.ProtectFunc()
dialer.Control = control.Append(dialer.Control, bindFunc)
listener.Control = control.Append(listener.Control, bindFunc)
} else {
bindFunc := networkManager.AutoDetectInterfaceFunc()
dialer.Control = control.Append(dialer.Control, bindFunc)
listener.Control = control.Append(listener.Control, bindFunc)
}
2024-11-12 19:37:10 +08:00
}
2024-06-07 15:55:21 +08:00
}
2024-11-13 19:05:28 +08:00
if options.RoutingMark == 0 && defaultOptions.RoutingMark != 0 {
dialer.Control = control.Append(dialer.Control, control.RoutingMark(defaultOptions.RoutingMark))
listener.Control = control.Append(listener.Control, control.RoutingMark(defaultOptions.RoutingMark))
}
}
if options.ReuseAddr {
listener.Control = control.Append(listener.Control, control.ReuseAddr())
}
2022-07-06 14:45:56 +08:00
if options.ProtectPath != "" {
2022-07-11 18:44:59 +08:00
dialer.Control = control.Append(dialer.Control, control.ProtectPath(options.ProtectPath))
listener.Control = control.Append(listener.Control, control.ProtectPath(options.ProtectPath))
2022-07-06 14:45:56 +08:00
}
if options.ConnectTimeout != 0 {
2022-07-08 12:58:43 +08:00
dialer.Timeout = time.Duration(options.ConnectTimeout)
2022-07-18 20:40:14 +08:00
} else {
2024-10-30 13:09:05 +08:00
dialer.Timeout = C.TCPConnectTimeout
}
2024-04-08 18:00:48 +08:00
// TODO: Add an option to customize the keep alive period
dialer.KeepAlive = C.TCPKeepAliveInitial
dialer.Control = control.Append(dialer.Control, control.SetKeepAlivePeriod(C.TCPKeepAliveInitial, C.TCPKeepAliveInterval))
var udpFragment bool
if options.UDPFragment != nil {
udpFragment = *options.UDPFragment
} else {
udpFragment = options.UDPFragmentDefault
}
if !udpFragment {
2022-09-06 00:54:57 +08:00
dialer.Control = control.Append(dialer.Control, control.DisableUDPFragment())
listener.Control = control.Append(listener.Control, control.DisableUDPFragment())
}
2022-11-03 11:51:09 +08:00
var (
dialer4 = dialer
udpDialer4 = dialer
udpAddr4 string
)
if options.Inet4BindAddress != nil {
2024-11-18 18:55:34 +08:00
bindAddr := options.Inet4BindAddress.Build(netip.IPv4Unspecified())
2022-11-03 11:51:09 +08:00
dialer4.LocalAddr = &net.TCPAddr{IP: bindAddr.AsSlice()}
udpDialer4.LocalAddr = &net.UDPAddr{IP: bindAddr.AsSlice()}
udpAddr4 = M.SocksaddrFrom(bindAddr, 0).String()
2022-08-25 14:49:49 +08:00
}
2022-11-03 11:51:09 +08:00
var (
dialer6 = dialer
udpDialer6 = dialer
udpAddr6 string
)
if options.Inet6BindAddress != nil {
2024-11-18 18:55:34 +08:00
bindAddr := options.Inet6BindAddress.Build(netip.IPv6Unspecified())
2022-11-03 11:51:09 +08:00
dialer6.LocalAddr = &net.TCPAddr{IP: bindAddr.AsSlice()}
udpDialer6.LocalAddr = &net.UDPAddr{IP: bindAddr.AsSlice()}
udpAddr6 = M.SocksaddrFrom(bindAddr, 0).String()
}
2023-08-08 16:14:03 +08:00
if options.TCPMultiPath {
2023-08-16 17:47:24 +08:00
if !go121Available {
2023-08-08 16:14:03 +08:00
return nil, E.New("MultiPath TCP requires go1.21, please recompile your binary.")
}
setMultiPathTCP(&dialer4)
}
if options.IsWireGuardListener {
2024-11-02 00:39:02 +08:00
for _, controlFn := range WgControlFns {
listener.Control = control.Append(listener.Control, controlFn)
}
}
2024-11-12 19:37:10 +08:00
if networkStrategy != C.NetworkStrategyDefault && options.TCPFastOpen {
return nil, E.New("`tcp_fast_open` is conflict with `network_strategy` or `route.default_network_strategy`")
}
2023-08-16 17:47:24 +08:00
tcpDialer4, err := newTCPDialer(dialer4, options.TCPFastOpen)
if err != nil {
return nil, err
}
tcpDialer6, err := newTCPDialer(dialer6, options.TCPFastOpen)
if err != nil {
return nil, err
}
2022-11-03 11:51:09 +08:00
return &DefaultDialer{
2024-11-12 19:37:10 +08:00
dialer4: tcpDialer4,
dialer6: tcpDialer6,
udpDialer4: udpDialer4,
udpDialer6: udpDialer6,
udpListener: listener,
udpAddr4: udpAddr4,
udpAddr6: udpAddr6,
isWireGuardListener: options.IsWireGuardListener,
networkManager: networkManager,
networkStrategy: networkStrategy,
2024-11-13 19:05:28 +08:00
networkType: networkType,
fallbackNetworkType: fallbackNetworkType,
2024-11-12 19:37:10 +08:00
networkFallbackDelay: networkFallbackDelay,
2023-08-08 16:14:03 +08:00
}, nil
}
2022-07-07 21:47:21 +08:00
func (d *DefaultDialer) DialContext(ctx context.Context, network string, address M.Socksaddr) (net.Conn, error) {
2022-08-29 19:58:58 +08:00
if !address.IsValid() {
return nil, E.New("invalid address")
}
2024-11-12 19:37:10 +08:00
if d.networkStrategy == C.NetworkStrategyDefault {
switch N.NetworkName(network) {
case N.NetworkUDP:
if !address.IsIPv6() {
return trackConn(d.udpDialer4.DialContext(ctx, network, address.String()))
} else {
return trackConn(d.udpDialer6.DialContext(ctx, network, address.String()))
}
}
2022-11-03 11:51:09 +08:00
if !address.IsIPv6() {
2024-11-12 19:37:10 +08:00
return trackConn(DialSlowContext(&d.dialer4, ctx, network, address))
2022-11-03 11:51:09 +08:00
} else {
2024-11-12 19:37:10 +08:00
return trackConn(DialSlowContext(&d.dialer6, ctx, network, address))
2022-11-03 11:51:09 +08:00
}
2024-11-12 19:37:10 +08:00
} else {
2024-11-13 19:05:28 +08:00
return d.DialParallelInterface(ctx, network, address, d.networkStrategy, d.networkType, d.fallbackNetworkType, d.networkFallbackDelay)
2024-11-12 19:37:10 +08:00
}
}
2024-11-13 19:05:28 +08:00
func (d *DefaultDialer) DialParallelInterface(ctx context.Context, network string, address M.Socksaddr, strategy C.NetworkStrategy, interfaceType []C.InterfaceType, fallbackInterfaceType []C.InterfaceType, fallbackDelay time.Duration) (net.Conn, error) {
2024-11-12 19:37:10 +08:00
if strategy == C.NetworkStrategyDefault {
return d.DialContext(ctx, network, address)
2022-11-03 11:51:09 +08:00
}
2024-11-12 19:37:10 +08:00
if !d.networkManager.AutoDetectInterface() {
return nil, E.New("`route.auto_detect_interface` is require by `network_strategy`")
}
var dialer net.Dialer
if N.NetworkName(network) == N.NetworkTCP {
dialer = dialerFromTCPDialer(d.dialer4)
} else {
dialer = d.udpDialer4
}
fastFallback := time.Now().Sub(d.networkLastFallback.Load()) < C.TCPTimeout
var (
conn net.Conn
isPrimary bool
err error
)
if !fastFallback {
2024-11-13 19:05:28 +08:00
conn, isPrimary, err = d.dialParallelInterface(ctx, dialer, network, address.String(), strategy, interfaceType, fallbackInterfaceType, fallbackDelay)
2022-11-03 11:51:09 +08:00
} else {
2024-11-13 19:05:28 +08:00
conn, isPrimary, err = d.dialParallelInterfaceFastFallback(ctx, dialer, network, address.String(), strategy, interfaceType, fallbackInterfaceType, fallbackDelay, d.networkLastFallback.Store)
2022-08-22 14:35:05 +08:00
}
2024-11-12 19:37:10 +08:00
if err != nil {
return nil, err
}
if !fastFallback && !isPrimary {
d.networkLastFallback.Store(time.Now())
}
return trackConn(conn, nil)
}
2022-07-07 21:47:21 +08:00
func (d *DefaultDialer) ListenPacket(ctx context.Context, destination M.Socksaddr) (net.PacketConn, error) {
2024-11-12 19:37:10 +08:00
if d.networkStrategy == C.NetworkStrategyDefault {
if destination.IsIPv6() {
return trackPacketConn(d.udpListener.ListenPacket(ctx, N.NetworkUDP, d.udpAddr6))
} else if destination.IsIPv4() && !destination.Addr.IsUnspecified() {
return trackPacketConn(d.udpListener.ListenPacket(ctx, N.NetworkUDP+"4", d.udpAddr4))
} else {
return trackPacketConn(d.udpListener.ListenPacket(ctx, N.NetworkUDP, d.udpAddr4))
}
2023-10-03 11:08:25 +08:00
} else {
2024-11-13 19:05:28 +08:00
return d.ListenSerialInterfacePacket(ctx, destination, d.networkStrategy, d.networkType, d.fallbackNetworkType, d.networkFallbackDelay)
2024-11-12 19:37:10 +08:00
}
}
2024-11-13 19:05:28 +08:00
func (d *DefaultDialer) ListenSerialInterfacePacket(ctx context.Context, destination M.Socksaddr, strategy C.NetworkStrategy, interfaceType []C.InterfaceType, fallbackInterfaceType []C.InterfaceType, fallbackDelay time.Duration) (net.PacketConn, error) {
2024-11-12 19:37:10 +08:00
if strategy == C.NetworkStrategyDefault {
return d.ListenPacket(ctx, destination)
}
if !d.networkManager.AutoDetectInterface() {
return nil, E.New("`route.auto_detect_interface` is require by `network_strategy`")
}
network := N.NetworkUDP
if destination.IsIPv4() && !destination.Addr.IsUnspecified() {
network += "4"
2022-11-03 11:51:09 +08:00
}
2024-11-13 19:05:28 +08:00
return trackPacketConn(d.listenSerialInterfacePacket(ctx, d.udpListener, network, "", strategy, interfaceType, fallbackInterfaceType, fallbackDelay))
2022-07-07 21:47:21 +08:00
}
2023-03-03 19:26:54 +08:00
func (d *DefaultDialer) ListenPacketCompat(network, address string) (net.PacketConn, error) {
2024-11-21 18:10:41 +08:00
return d.udpListener.ListenPacket(context.Background(), network, address)
}
2023-03-03 19:26:54 +08:00
func trackConn(conn net.Conn, err error) (net.Conn, error) {
if !conntrack.Enabled || err != nil {
return conn, err
}
2023-03-16 10:55:06 +08:00
return conntrack.NewConn(conn)
2023-03-03 19:26:54 +08:00
}
func trackPacketConn(conn net.PacketConn, err error) (net.PacketConn, error) {
if !conntrack.Enabled || err != nil {
return conn, err
}
2023-03-16 10:55:06 +08:00
return conntrack.NewPacketConn(conn)
2023-03-03 19:26:54 +08:00
}