default.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  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. bindFunc := control.BindToInterface(interfaceFinder, options.BindInterface, -1)
  64. dialer.Control = control.Append(dialer.Control, bindFunc)
  65. listener.Control = control.Append(listener.Control, bindFunc)
  66. }
  67. if options.RoutingMark > 0 {
  68. dialer.Control = control.Append(dialer.Control, control.RoutingMark(uint32(options.RoutingMark)))
  69. listener.Control = control.Append(listener.Control, control.RoutingMark(uint32(options.RoutingMark)))
  70. }
  71. if networkManager != nil {
  72. autoRedirectOutputMark := networkManager.AutoRedirectOutputMark()
  73. if autoRedirectOutputMark > 0 {
  74. if options.RoutingMark > 0 {
  75. return nil, E.New("`routing_mark` is conflict with `tun.auto_redirect` with `tun.route_[_exclude]_address_set")
  76. }
  77. dialer.Control = control.Append(dialer.Control, control.RoutingMark(autoRedirectOutputMark))
  78. listener.Control = control.Append(listener.Control, control.RoutingMark(autoRedirectOutputMark))
  79. }
  80. }
  81. disableDefaultBind := options.BindInterface != "" || options.Inet4BindAddress != nil || options.Inet6BindAddress != nil
  82. if disableDefaultBind || options.TCPFastOpen {
  83. if options.NetworkStrategy != nil || len(options.NetworkType) > 0 && options.FallbackNetworkType == nil && options.FallbackDelay == 0 {
  84. return nil, E.New("`network_strategy` is conflict with `bind_interface`, `inet4_bind_address`, `inet6_bind_address` and `tcp_fast_open`")
  85. }
  86. }
  87. if networkManager != nil {
  88. defaultOptions := networkManager.DefaultOptions()
  89. if !disableDefaultBind {
  90. if defaultOptions.BindInterface != "" {
  91. bindFunc := control.BindToInterface(networkManager.InterfaceFinder(), defaultOptions.BindInterface, -1)
  92. dialer.Control = control.Append(dialer.Control, bindFunc)
  93. listener.Control = control.Append(listener.Control, bindFunc)
  94. } else if networkManager.AutoDetectInterface() {
  95. if platformInterface != nil {
  96. networkStrategy = (*C.NetworkStrategy)(options.NetworkStrategy)
  97. if networkStrategy == nil {
  98. networkStrategy = common.Ptr(C.NetworkStrategyDefault)
  99. defaultNetworkStrategy = true
  100. }
  101. networkType = common.Map(options.NetworkType, option.InterfaceType.Build)
  102. fallbackNetworkType = common.Map(options.FallbackNetworkType, option.InterfaceType.Build)
  103. if networkStrategy == nil && len(networkType) == 0 && len(fallbackNetworkType) == 0 {
  104. networkStrategy = defaultOptions.NetworkStrategy
  105. networkType = defaultOptions.NetworkType
  106. fallbackNetworkType = defaultOptions.FallbackNetworkType
  107. }
  108. networkFallbackDelay = time.Duration(options.FallbackDelay)
  109. if networkFallbackDelay == 0 && defaultOptions.FallbackDelay != 0 {
  110. networkFallbackDelay = defaultOptions.FallbackDelay
  111. }
  112. bindFunc := networkManager.ProtectFunc()
  113. dialer.Control = control.Append(dialer.Control, bindFunc)
  114. listener.Control = control.Append(listener.Control, bindFunc)
  115. } else {
  116. bindFunc := networkManager.AutoDetectInterfaceFunc()
  117. dialer.Control = control.Append(dialer.Control, bindFunc)
  118. listener.Control = control.Append(listener.Control, bindFunc)
  119. }
  120. }
  121. }
  122. if options.RoutingMark == 0 && defaultOptions.RoutingMark != 0 {
  123. dialer.Control = control.Append(dialer.Control, control.RoutingMark(defaultOptions.RoutingMark))
  124. listener.Control = control.Append(listener.Control, control.RoutingMark(defaultOptions.RoutingMark))
  125. }
  126. }
  127. if options.ReuseAddr {
  128. listener.Control = control.Append(listener.Control, control.ReuseAddr())
  129. }
  130. if options.ProtectPath != "" {
  131. dialer.Control = control.Append(dialer.Control, control.ProtectPath(options.ProtectPath))
  132. listener.Control = control.Append(listener.Control, control.ProtectPath(options.ProtectPath))
  133. }
  134. if options.ConnectTimeout != 0 {
  135. dialer.Timeout = time.Duration(options.ConnectTimeout)
  136. } else {
  137. dialer.Timeout = C.TCPConnectTimeout
  138. }
  139. // TODO: Add an option to customize the keep alive period
  140. dialer.KeepAlive = C.TCPKeepAliveInitial
  141. dialer.Control = control.Append(dialer.Control, control.SetKeepAlivePeriod(C.TCPKeepAliveInitial, C.TCPKeepAliveInterval))
  142. var udpFragment bool
  143. if options.UDPFragment != nil {
  144. udpFragment = *options.UDPFragment
  145. } else {
  146. udpFragment = options.UDPFragmentDefault
  147. }
  148. if !udpFragment {
  149. dialer.Control = control.Append(dialer.Control, control.DisableUDPFragment())
  150. listener.Control = control.Append(listener.Control, control.DisableUDPFragment())
  151. }
  152. var (
  153. dialer4 = dialer
  154. udpDialer4 = dialer
  155. udpAddr4 string
  156. )
  157. if options.Inet4BindAddress != nil {
  158. bindAddr := options.Inet4BindAddress.Build(netip.IPv4Unspecified())
  159. dialer4.LocalAddr = &net.TCPAddr{IP: bindAddr.AsSlice()}
  160. udpDialer4.LocalAddr = &net.UDPAddr{IP: bindAddr.AsSlice()}
  161. udpAddr4 = M.SocksaddrFrom(bindAddr, 0).String()
  162. }
  163. var (
  164. dialer6 = dialer
  165. udpDialer6 = dialer
  166. udpAddr6 string
  167. )
  168. if options.Inet6BindAddress != nil {
  169. bindAddr := options.Inet6BindAddress.Build(netip.IPv6Unspecified())
  170. dialer6.LocalAddr = &net.TCPAddr{IP: bindAddr.AsSlice()}
  171. udpDialer6.LocalAddr = &net.UDPAddr{IP: bindAddr.AsSlice()}
  172. udpAddr6 = M.SocksaddrFrom(bindAddr, 0).String()
  173. }
  174. if options.TCPMultiPath {
  175. if !go121Available {
  176. return nil, E.New("MultiPath TCP requires go1.21, please recompile your binary.")
  177. }
  178. setMultiPathTCP(&dialer4)
  179. }
  180. tcpDialer4, err := newTCPDialer(dialer4, options.TCPFastOpen)
  181. if err != nil {
  182. return nil, err
  183. }
  184. tcpDialer6, err := newTCPDialer(dialer6, options.TCPFastOpen)
  185. if err != nil {
  186. return nil, err
  187. }
  188. return &DefaultDialer{
  189. dialer4: tcpDialer4,
  190. dialer6: tcpDialer6,
  191. udpDialer4: udpDialer4,
  192. udpDialer6: udpDialer6,
  193. udpListener: listener,
  194. udpAddr4: udpAddr4,
  195. udpAddr6: udpAddr6,
  196. netns: options.NetNs,
  197. networkManager: networkManager,
  198. networkStrategy: networkStrategy,
  199. defaultNetworkStrategy: defaultNetworkStrategy,
  200. networkType: networkType,
  201. fallbackNetworkType: fallbackNetworkType,
  202. networkFallbackDelay: networkFallbackDelay,
  203. }, nil
  204. }
  205. func (d *DefaultDialer) DialContext(ctx context.Context, network string, address M.Socksaddr) (net.Conn, error) {
  206. if !address.IsValid() {
  207. return nil, E.New("invalid address")
  208. } else if address.IsFqdn() {
  209. return nil, E.New("domain not resolved")
  210. }
  211. if d.networkStrategy == nil {
  212. return trackConn(listener.ListenNetworkNamespace[net.Conn](d.netns, func() (net.Conn, error) {
  213. switch N.NetworkName(network) {
  214. case N.NetworkUDP:
  215. if !address.IsIPv6() {
  216. return d.udpDialer4.DialContext(ctx, network, address.String())
  217. } else {
  218. return d.udpDialer6.DialContext(ctx, network, address.String())
  219. }
  220. }
  221. if !address.IsIPv6() {
  222. return DialSlowContext(&d.dialer4, ctx, network, address)
  223. } else {
  224. return DialSlowContext(&d.dialer6, ctx, network, address)
  225. }
  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. return trackPacketConn(listener.ListenNetworkNamespace[net.PacketConn](d.netns, func() (net.PacketConn, error) {
  281. if destination.IsIPv6() {
  282. return d.udpListener.ListenPacket(ctx, N.NetworkUDP, d.udpAddr6)
  283. } else if destination.IsIPv4() && !destination.Addr.IsUnspecified() {
  284. return d.udpListener.ListenPacket(ctx, N.NetworkUDP+"4", d.udpAddr4)
  285. } else {
  286. return d.udpListener.ListenPacket(ctx, N.NetworkUDP, d.udpAddr4)
  287. }
  288. }))
  289. } else {
  290. return d.ListenSerialInterfacePacket(ctx, destination, d.networkStrategy, d.networkType, d.fallbackNetworkType, d.networkFallbackDelay)
  291. }
  292. }
  293. 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) {
  294. if strategy == nil {
  295. strategy = d.networkStrategy
  296. }
  297. if strategy == nil {
  298. return d.ListenPacket(ctx, destination)
  299. }
  300. if len(interfaceType) == 0 {
  301. interfaceType = d.networkType
  302. }
  303. if len(fallbackInterfaceType) == 0 {
  304. fallbackInterfaceType = d.fallbackNetworkType
  305. }
  306. if fallbackDelay == 0 {
  307. fallbackDelay = d.networkFallbackDelay
  308. }
  309. network := N.NetworkUDP
  310. if destination.IsIPv4() && !destination.Addr.IsUnspecified() {
  311. network += "4"
  312. }
  313. packetConn, err := d.listenSerialInterfacePacket(ctx, d.udpListener, network, "", *strategy, interfaceType, fallbackInterfaceType, fallbackDelay)
  314. if err != nil {
  315. // bind interface failed on legacy xiaomi systems
  316. if d.defaultNetworkStrategy && errors.Is(err, syscall.EPERM) {
  317. d.networkStrategy = nil
  318. return d.ListenPacket(ctx, destination)
  319. } else {
  320. return nil, err
  321. }
  322. }
  323. return trackPacketConn(packetConn, nil)
  324. }
  325. func (d *DefaultDialer) ListenPacketCompat(network, address string) (net.PacketConn, error) {
  326. return d.udpListener.ListenPacket(context.Background(), network, address)
  327. }
  328. func trackConn(conn net.Conn, err error) (net.Conn, error) {
  329. if !conntrack.Enabled || err != nil {
  330. return conn, err
  331. }
  332. return conntrack.NewConn(conn)
  333. }
  334. func trackPacketConn(conn net.PacketConn, err error) (net.PacketConn, error) {
  335. if !conntrack.Enabled || err != nil {
  336. return conn, err
  337. }
  338. return conntrack.NewPacketConn(conn)
  339. }