default.go 13 KB

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