default.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  1. package dialer
  2. import (
  3. "context"
  4. "errors"
  5. "net"
  6. "net/netip"
  7. "syscall"
  8. "time"
  9. "github.com/sagernet/sing-box/adapter"
  10. "github.com/sagernet/sing-box/common/conntrack"
  11. "github.com/sagernet/sing-box/common/listener"
  12. C "github.com/sagernet/sing-box/constant"
  13. "github.com/sagernet/sing-box/experimental/libbox/platform"
  14. "github.com/sagernet/sing-box/option"
  15. "github.com/sagernet/sing/common"
  16. "github.com/sagernet/sing/common/atomic"
  17. "github.com/sagernet/sing/common/control"
  18. E "github.com/sagernet/sing/common/exceptions"
  19. M "github.com/sagernet/sing/common/metadata"
  20. N "github.com/sagernet/sing/common/network"
  21. "github.com/sagernet/sing/service"
  22. )
  23. var (
  24. _ ParallelInterfaceDialer = (*DefaultDialer)(nil)
  25. _ WireGuardListener = (*DefaultDialer)(nil)
  26. )
  27. type DefaultDialer struct {
  28. dialer4 tcpDialer
  29. dialer6 tcpDialer
  30. udpDialer4 net.Dialer
  31. udpDialer6 net.Dialer
  32. udpListener net.ListenConfig
  33. udpAddr4 string
  34. udpAddr6 string
  35. netns string
  36. networkManager adapter.NetworkManager
  37. networkStrategy *C.NetworkStrategy
  38. defaultNetworkStrategy bool
  39. networkType []C.InterfaceType
  40. fallbackNetworkType []C.InterfaceType
  41. networkFallbackDelay time.Duration
  42. networkLastFallback atomic.TypedValue[time.Time]
  43. }
  44. func NewDefault(ctx context.Context, options option.DialerOptions) (*DefaultDialer, error) {
  45. networkManager := service.FromContext[adapter.NetworkManager](ctx)
  46. platformInterface := service.FromContext[platform.Interface](ctx)
  47. var (
  48. dialer net.Dialer
  49. listener net.ListenConfig
  50. interfaceFinder control.InterfaceFinder
  51. networkStrategy *C.NetworkStrategy
  52. defaultNetworkStrategy bool
  53. networkType []C.InterfaceType
  54. fallbackNetworkType []C.InterfaceType
  55. networkFallbackDelay time.Duration
  56. )
  57. if networkManager != nil {
  58. interfaceFinder = networkManager.InterfaceFinder()
  59. } else {
  60. interfaceFinder = control.NewDefaultInterfaceFinder()
  61. }
  62. if options.BindInterface != "" {
  63. if !(C.IsLinux || C.IsDarwin || C.IsWindows) {
  64. return nil, E.New("`bind_interface` is only supported on Linux, macOS and Windows")
  65. }
  66. bindFunc := control.BindToInterface(interfaceFinder, options.BindInterface, -1)
  67. dialer.Control = control.Append(dialer.Control, bindFunc)
  68. listener.Control = control.Append(listener.Control, bindFunc)
  69. }
  70. if options.RoutingMark > 0 {
  71. if !C.IsLinux {
  72. return nil, E.New("`routing_mark` is only supported on Linux")
  73. }
  74. dialer.Control = control.Append(dialer.Control, setMarkWrapper(networkManager, uint32(options.RoutingMark), false))
  75. listener.Control = control.Append(listener.Control, setMarkWrapper(networkManager, uint32(options.RoutingMark), false))
  76. }
  77. disableDefaultBind := options.BindInterface != "" || options.Inet4BindAddress != nil || options.Inet6BindAddress != nil
  78. if disableDefaultBind || options.TCPFastOpen {
  79. if options.NetworkStrategy != nil || len(options.NetworkType) > 0 && options.FallbackNetworkType == nil && options.FallbackDelay == 0 {
  80. return nil, E.New("`network_strategy` is conflict with `bind_interface`, `inet4_bind_address`, `inet6_bind_address` and `tcp_fast_open`")
  81. }
  82. }
  83. if networkManager != nil {
  84. defaultOptions := networkManager.DefaultOptions()
  85. if !disableDefaultBind {
  86. if defaultOptions.BindInterface != "" {
  87. bindFunc := control.BindToInterface(networkManager.InterfaceFinder(), defaultOptions.BindInterface, -1)
  88. dialer.Control = control.Append(dialer.Control, bindFunc)
  89. listener.Control = control.Append(listener.Control, bindFunc)
  90. } else if networkManager.AutoDetectInterface() {
  91. if platformInterface != nil {
  92. networkStrategy = (*C.NetworkStrategy)(options.NetworkStrategy)
  93. networkType = common.Map(options.NetworkType, option.InterfaceType.Build)
  94. fallbackNetworkType = common.Map(options.FallbackNetworkType, option.InterfaceType.Build)
  95. if networkStrategy == nil && len(networkType) == 0 && len(fallbackNetworkType) == 0 {
  96. networkStrategy = defaultOptions.NetworkStrategy
  97. networkType = defaultOptions.NetworkType
  98. fallbackNetworkType = defaultOptions.FallbackNetworkType
  99. }
  100. networkFallbackDelay = time.Duration(options.FallbackDelay)
  101. if networkFallbackDelay == 0 && defaultOptions.FallbackDelay != 0 {
  102. networkFallbackDelay = defaultOptions.FallbackDelay
  103. }
  104. if networkStrategy == nil {
  105. networkStrategy = common.Ptr(C.NetworkStrategyDefault)
  106. defaultNetworkStrategy = true
  107. }
  108. bindFunc := networkManager.ProtectFunc()
  109. dialer.Control = control.Append(dialer.Control, bindFunc)
  110. listener.Control = control.Append(listener.Control, bindFunc)
  111. } else {
  112. bindFunc := networkManager.AutoDetectInterfaceFunc()
  113. dialer.Control = control.Append(dialer.Control, bindFunc)
  114. listener.Control = control.Append(listener.Control, bindFunc)
  115. }
  116. }
  117. }
  118. if options.RoutingMark == 0 && defaultOptions.RoutingMark != 0 {
  119. dialer.Control = control.Append(dialer.Control, setMarkWrapper(networkManager, defaultOptions.RoutingMark, true))
  120. listener.Control = control.Append(listener.Control, setMarkWrapper(networkManager, defaultOptions.RoutingMark, true))
  121. }
  122. }
  123. if options.ReuseAddr {
  124. listener.Control = control.Append(listener.Control, control.ReuseAddr())
  125. }
  126. if options.ProtectPath != "" {
  127. dialer.Control = control.Append(dialer.Control, control.ProtectPath(options.ProtectPath))
  128. listener.Control = control.Append(listener.Control, control.ProtectPath(options.ProtectPath))
  129. }
  130. if options.ConnectTimeout != 0 {
  131. dialer.Timeout = time.Duration(options.ConnectTimeout)
  132. } else {
  133. dialer.Timeout = C.TCPConnectTimeout
  134. }
  135. // TODO: Add an option to customize the keep alive period
  136. dialer.KeepAlive = C.TCPKeepAliveInitial
  137. dialer.Control = control.Append(dialer.Control, control.SetKeepAlivePeriod(C.TCPKeepAliveInitial, C.TCPKeepAliveInterval))
  138. var udpFragment bool
  139. if options.UDPFragment != nil {
  140. udpFragment = *options.UDPFragment
  141. } else {
  142. udpFragment = options.UDPFragmentDefault
  143. }
  144. if !udpFragment {
  145. dialer.Control = control.Append(dialer.Control, control.DisableUDPFragment())
  146. listener.Control = control.Append(listener.Control, control.DisableUDPFragment())
  147. }
  148. var (
  149. dialer4 = dialer
  150. udpDialer4 = dialer
  151. udpAddr4 string
  152. )
  153. if options.Inet4BindAddress != nil {
  154. bindAddr := options.Inet4BindAddress.Build(netip.IPv4Unspecified())
  155. dialer4.LocalAddr = &net.TCPAddr{IP: bindAddr.AsSlice()}
  156. udpDialer4.LocalAddr = &net.UDPAddr{IP: bindAddr.AsSlice()}
  157. udpAddr4 = M.SocksaddrFrom(bindAddr, 0).String()
  158. }
  159. var (
  160. dialer6 = dialer
  161. udpDialer6 = dialer
  162. udpAddr6 string
  163. )
  164. if options.Inet6BindAddress != nil {
  165. bindAddr := options.Inet6BindAddress.Build(netip.IPv6Unspecified())
  166. dialer6.LocalAddr = &net.TCPAddr{IP: bindAddr.AsSlice()}
  167. udpDialer6.LocalAddr = &net.UDPAddr{IP: bindAddr.AsSlice()}
  168. udpAddr6 = M.SocksaddrFrom(bindAddr, 0).String()
  169. }
  170. if options.TCPMultiPath {
  171. if !go121Available {
  172. return nil, E.New("MultiPath TCP requires go1.21, please recompile your binary.")
  173. }
  174. setMultiPathTCP(&dialer4)
  175. }
  176. tcpDialer4, err := newTCPDialer(dialer4, options.TCPFastOpen)
  177. if err != nil {
  178. return nil, err
  179. }
  180. tcpDialer6, err := newTCPDialer(dialer6, options.TCPFastOpen)
  181. if err != nil {
  182. return nil, err
  183. }
  184. return &DefaultDialer{
  185. dialer4: tcpDialer4,
  186. dialer6: tcpDialer6,
  187. udpDialer4: udpDialer4,
  188. udpDialer6: udpDialer6,
  189. udpListener: listener,
  190. udpAddr4: udpAddr4,
  191. udpAddr6: udpAddr6,
  192. netns: options.NetNs,
  193. networkManager: networkManager,
  194. networkStrategy: networkStrategy,
  195. defaultNetworkStrategy: defaultNetworkStrategy,
  196. networkType: networkType,
  197. fallbackNetworkType: fallbackNetworkType,
  198. networkFallbackDelay: networkFallbackDelay,
  199. }, nil
  200. }
  201. func setMarkWrapper(networkManager adapter.NetworkManager, mark uint32, isDefault bool) control.Func {
  202. if networkManager == nil {
  203. return control.RoutingMark(mark)
  204. }
  205. return func(network, address string, conn syscall.RawConn) error {
  206. if networkManager.AutoRedirectOutputMark() != 0 {
  207. if isDefault {
  208. return E.New("`route.default_mark` is conflict with `tun.auto_redirect`")
  209. } else {
  210. return E.New("`routing_mark` is conflict with `tun.auto_redirect`")
  211. }
  212. }
  213. return control.RoutingMark(mark)(network, address, conn)
  214. }
  215. }
  216. func (d *DefaultDialer) DialContext(ctx context.Context, network string, address M.Socksaddr) (net.Conn, error) {
  217. if !address.IsValid() {
  218. return nil, E.New("invalid address")
  219. } else if address.IsFqdn() {
  220. return nil, E.New("domain not resolved")
  221. }
  222. if d.networkStrategy == nil {
  223. return trackConn(listener.ListenNetworkNamespace[net.Conn](d.netns, func() (net.Conn, error) {
  224. switch N.NetworkName(network) {
  225. case N.NetworkUDP:
  226. if !address.IsIPv6() {
  227. return d.udpDialer4.DialContext(ctx, network, address.String())
  228. } else {
  229. return d.udpDialer6.DialContext(ctx, network, address.String())
  230. }
  231. }
  232. if !address.IsIPv6() {
  233. return DialSlowContext(&d.dialer4, ctx, network, address)
  234. } else {
  235. return DialSlowContext(&d.dialer6, ctx, network, address)
  236. }
  237. }))
  238. } else {
  239. return d.DialParallelInterface(ctx, network, address, d.networkStrategy, d.networkType, d.fallbackNetworkType, d.networkFallbackDelay)
  240. }
  241. }
  242. 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) {
  243. if strategy == nil {
  244. strategy = d.networkStrategy
  245. }
  246. if strategy == nil {
  247. return d.DialContext(ctx, network, address)
  248. }
  249. if len(interfaceType) == 0 {
  250. interfaceType = d.networkType
  251. }
  252. if len(fallbackInterfaceType) == 0 {
  253. fallbackInterfaceType = d.fallbackNetworkType
  254. }
  255. if fallbackDelay == 0 {
  256. fallbackDelay = d.networkFallbackDelay
  257. }
  258. var dialer net.Dialer
  259. if N.NetworkName(network) == N.NetworkTCP {
  260. dialer = dialerFromTCPDialer(d.dialer4)
  261. } else {
  262. dialer = d.udpDialer4
  263. }
  264. fastFallback := time.Since(d.networkLastFallback.Load()) < C.TCPTimeout
  265. var (
  266. conn net.Conn
  267. isPrimary bool
  268. err error
  269. )
  270. if !fastFallback {
  271. conn, isPrimary, err = d.dialParallelInterface(ctx, dialer, network, address.String(), *strategy, interfaceType, fallbackInterfaceType, fallbackDelay)
  272. } else {
  273. conn, isPrimary, err = d.dialParallelInterfaceFastFallback(ctx, dialer, network, address.String(), *strategy, interfaceType, fallbackInterfaceType, fallbackDelay, d.networkLastFallback.Store)
  274. }
  275. if err != nil {
  276. // bind interface failed on legacy xiaomi systems
  277. if d.defaultNetworkStrategy && errors.Is(err, syscall.EPERM) {
  278. d.networkStrategy = nil
  279. return d.DialContext(ctx, network, address)
  280. } else {
  281. return nil, err
  282. }
  283. }
  284. if !fastFallback && !isPrimary {
  285. d.networkLastFallback.Store(time.Now())
  286. }
  287. return trackConn(conn, nil)
  288. }
  289. func (d *DefaultDialer) ListenPacket(ctx context.Context, destination M.Socksaddr) (net.PacketConn, error) {
  290. if d.networkStrategy == nil {
  291. return trackPacketConn(listener.ListenNetworkNamespace[net.PacketConn](d.netns, func() (net.PacketConn, error) {
  292. if destination.IsIPv6() {
  293. return d.udpListener.ListenPacket(ctx, N.NetworkUDP, d.udpAddr6)
  294. } else if destination.IsIPv4() && !destination.Addr.IsUnspecified() {
  295. return d.udpListener.ListenPacket(ctx, N.NetworkUDP+"4", d.udpAddr4)
  296. } else {
  297. return d.udpListener.ListenPacket(ctx, N.NetworkUDP, d.udpAddr4)
  298. }
  299. }))
  300. } else {
  301. return d.ListenSerialInterfacePacket(ctx, destination, d.networkStrategy, d.networkType, d.fallbackNetworkType, d.networkFallbackDelay)
  302. }
  303. }
  304. 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) {
  305. if strategy == nil {
  306. strategy = d.networkStrategy
  307. }
  308. if strategy == nil {
  309. return d.ListenPacket(ctx, destination)
  310. }
  311. if len(interfaceType) == 0 {
  312. interfaceType = d.networkType
  313. }
  314. if len(fallbackInterfaceType) == 0 {
  315. fallbackInterfaceType = d.fallbackNetworkType
  316. }
  317. if fallbackDelay == 0 {
  318. fallbackDelay = d.networkFallbackDelay
  319. }
  320. network := N.NetworkUDP
  321. if destination.IsIPv4() && !destination.Addr.IsUnspecified() {
  322. network += "4"
  323. }
  324. packetConn, err := d.listenSerialInterfacePacket(ctx, d.udpListener, network, "", *strategy, interfaceType, fallbackInterfaceType, fallbackDelay)
  325. if err != nil {
  326. // bind interface failed on legacy xiaomi systems
  327. if d.defaultNetworkStrategy && errors.Is(err, syscall.EPERM) {
  328. d.networkStrategy = nil
  329. return d.ListenPacket(ctx, destination)
  330. } else {
  331. return nil, err
  332. }
  333. }
  334. return trackPacketConn(packetConn, nil)
  335. }
  336. func (d *DefaultDialer) ListenPacketCompat(network, address string) (net.PacketConn, error) {
  337. udpListener := d.udpListener
  338. udpListener.Control = control.Append(udpListener.Control, func(network, address string, conn syscall.RawConn) error {
  339. for _, wgControlFn := range WgControlFns {
  340. err := wgControlFn(network, address, conn)
  341. if err != nil {
  342. return err
  343. }
  344. }
  345. return nil
  346. })
  347. return udpListener.ListenPacket(context.Background(), network, address)
  348. }
  349. func trackConn(conn net.Conn, err error) (net.Conn, error) {
  350. if !conntrack.Enabled || err != nil {
  351. return conn, err
  352. }
  353. return conntrack.NewConn(conn)
  354. }
  355. func trackPacketConn(conn net.PacketConn, err error) (net.PacketConn, error) {
  356. if !conntrack.Enabled || err != nil {
  357. return conn, err
  358. }
  359. return conntrack.NewPacketConn(conn)
  360. }