default.go 13 KB

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