dialer.go 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  1. package internet
  2. import (
  3. "context"
  4. "fmt"
  5. "strings"
  6. "github.com/xtls/xray-core/common"
  7. "github.com/xtls/xray-core/common/dice"
  8. "github.com/xtls/xray-core/common/errors"
  9. "github.com/xtls/xray-core/common/net"
  10. "github.com/xtls/xray-core/common/net/cnc"
  11. "github.com/xtls/xray-core/common/session"
  12. "github.com/xtls/xray-core/features/dns"
  13. "github.com/xtls/xray-core/features/outbound"
  14. "github.com/xtls/xray-core/transport"
  15. "github.com/xtls/xray-core/transport/internet/stat"
  16. "github.com/xtls/xray-core/transport/pipe"
  17. )
  18. // Dialer is the interface for dialing outbound connections.
  19. type Dialer interface {
  20. // Dial dials a system connection to the given destination.
  21. Dial(ctx context.Context, destination net.Destination) (stat.Connection, error)
  22. // DestIpAddress returns the ip of proxy server. It is useful in case of Android client, which prepare an IP before proxy connection is established
  23. DestIpAddress() net.IP
  24. // SetOutboundGateway set outbound gateway
  25. SetOutboundGateway(ctx context.Context, ob *session.Outbound)
  26. }
  27. // dialFunc is an interface to dial network connection to a specific destination.
  28. type dialFunc func(ctx context.Context, dest net.Destination, streamSettings *MemoryStreamConfig) (stat.Connection, error)
  29. var transportDialerCache = make(map[string]dialFunc)
  30. // RegisterTransportDialer registers a Dialer with given name.
  31. func RegisterTransportDialer(protocol string, dialer dialFunc) error {
  32. if _, found := transportDialerCache[protocol]; found {
  33. return errors.New(protocol, " dialer already registered").AtError()
  34. }
  35. transportDialerCache[protocol] = dialer
  36. return nil
  37. }
  38. // Dial dials a internet connection towards the given destination.
  39. func Dial(ctx context.Context, dest net.Destination, streamSettings *MemoryStreamConfig) (stat.Connection, error) {
  40. if dest.Network == net.Network_TCP {
  41. if streamSettings == nil {
  42. s, err := ToMemoryStreamConfig(nil)
  43. if err != nil {
  44. return nil, errors.New("failed to create default stream settings").Base(err)
  45. }
  46. streamSettings = s
  47. }
  48. protocol := streamSettings.ProtocolName
  49. dialer := transportDialerCache[protocol]
  50. if dialer == nil {
  51. return nil, errors.New(protocol, " dialer not registered").AtError()
  52. }
  53. return dialer(ctx, dest, streamSettings)
  54. }
  55. if dest.Network == net.Network_UDP {
  56. udpDialer := transportDialerCache["udp"]
  57. if udpDialer == nil {
  58. return nil, errors.New("UDP dialer not registered").AtError()
  59. }
  60. return udpDialer(ctx, dest, streamSettings)
  61. }
  62. return nil, errors.New("unknown network ", dest.Network)
  63. }
  64. // DestIpAddress returns the ip of proxy server. It is useful in case of Android client, which prepare an IP before proxy connection is established
  65. func DestIpAddress() net.IP {
  66. return effectiveSystemDialer.DestIpAddress()
  67. }
  68. var (
  69. dnsClient dns.Client
  70. obm outbound.Manager
  71. )
  72. func LookupForIP(domain string, strategy DomainStrategy, localAddr net.Address) ([]net.IP, error) {
  73. if dnsClient == nil {
  74. return nil, errors.New("DNS client not initialized").AtError()
  75. }
  76. ips, _, err := dnsClient.LookupIP(domain, dns.IPOption{
  77. IPv4Enable: (localAddr == nil && strategy.PreferIP4()) || (localAddr != nil && localAddr.Family().IsIPv4() && (strategy.PreferIP4() || strategy.FallbackIP4())),
  78. IPv6Enable: (localAddr == nil && strategy.PreferIP6()) || (localAddr != nil && localAddr.Family().IsIPv6() && (strategy.PreferIP6() || strategy.FallbackIP6())),
  79. })
  80. { // Resolve fallback
  81. if (len(ips) == 0 || err != nil) && strategy.HasFallback() && localAddr == nil {
  82. ips, _, err = dnsClient.LookupIP(domain, dns.IPOption{
  83. IPv4Enable: strategy.FallbackIP4(),
  84. IPv6Enable: strategy.FallbackIP6(),
  85. })
  86. }
  87. }
  88. if err == nil && len(ips) == 0 {
  89. return nil, dns.ErrEmptyResponse
  90. }
  91. return ips, err
  92. }
  93. func redirect(ctx context.Context, dst net.Destination, obt string, h outbound.Handler) net.Conn {
  94. errors.LogInfo(ctx, "redirecting request "+dst.String()+" to "+obt)
  95. outbounds := session.OutboundsFromContext(ctx)
  96. ctx = session.ContextWithOutbounds(ctx, append(outbounds, &session.Outbound{
  97. Target: dst,
  98. Gateway: nil,
  99. Tag: obt,
  100. })) // add another outbound in session ctx
  101. ur, uw := pipe.New(pipe.OptionsFromContext(ctx)...)
  102. dr, dw := pipe.New(pipe.OptionsFromContext(ctx)...)
  103. go h.Dispatch(context.WithoutCancel(ctx), &transport.Link{Reader: ur, Writer: dw})
  104. var readerOpt cnc.ConnectionOption
  105. if dst.Network == net.Network_TCP {
  106. readerOpt = cnc.ConnectionOutputMulti(dr)
  107. } else {
  108. readerOpt = cnc.ConnectionOutputMultiUDP(dr)
  109. }
  110. nc := cnc.NewConnection(
  111. cnc.ConnectionInputMulti(uw),
  112. readerOpt,
  113. cnc.ConnectionOnClose(common.ChainedClosable{uw, dw}),
  114. )
  115. return nc
  116. }
  117. func checkAddressPortStrategy(ctx context.Context, dest net.Destination, sockopt *SocketConfig) (*net.Destination, error) {
  118. if sockopt.AddressPortStrategy == AddressPortStrategy_None {
  119. return nil, nil
  120. }
  121. newDest := dest
  122. var OverridePort, OverrideAddress bool
  123. var OverrideBy string
  124. switch sockopt.AddressPortStrategy {
  125. case AddressPortStrategy_SrvPortOnly:
  126. OverridePort = true
  127. OverrideAddress = false
  128. OverrideBy = "srv"
  129. case AddressPortStrategy_SrvAddressOnly:
  130. OverridePort = false
  131. OverrideAddress = true
  132. OverrideBy = "srv"
  133. case AddressPortStrategy_SrvPortAndAddress:
  134. OverridePort = true
  135. OverrideAddress = true
  136. OverrideBy = "srv"
  137. case AddressPortStrategy_TxtPortOnly:
  138. OverridePort = true
  139. OverrideAddress = false
  140. OverrideBy = "txt"
  141. case AddressPortStrategy_TxtAddressOnly:
  142. OverridePort = false
  143. OverrideAddress = true
  144. OverrideBy = "txt"
  145. case AddressPortStrategy_TxtPortAndAddress:
  146. OverridePort = true
  147. OverrideAddress = true
  148. OverrideBy = "txt"
  149. default:
  150. return nil, errors.New("unknown AddressPortStrategy")
  151. }
  152. if !dest.Address.Family().IsDomain() {
  153. return nil, nil
  154. }
  155. if OverrideBy == "srv" {
  156. errors.LogDebug(ctx, "query SRV record for "+dest.Address.String())
  157. parts := strings.SplitN(dest.Address.String(), ".", 3)
  158. if len(parts) != 3 {
  159. return nil, errors.New("invalid address format", dest.Address.String())
  160. }
  161. _, srvRecords, err := net.DefaultResolver.LookupSRV(context.Background(), parts[0][1:], parts[1][1:], parts[2])
  162. if err != nil {
  163. return nil, errors.New("failed to lookup SRV record").Base(err)
  164. }
  165. errors.LogDebug(ctx, "SRV record: "+fmt.Sprintf("addr=%s, port=%d, priority=%d, weight=%d", srvRecords[0].Target, srvRecords[0].Port, srvRecords[0].Priority, srvRecords[0].Weight))
  166. if OverridePort {
  167. newDest.Port = net.Port(srvRecords[0].Port)
  168. }
  169. if OverrideAddress {
  170. newDest.Address = net.ParseAddress(srvRecords[0].Target)
  171. }
  172. return &newDest, nil
  173. }
  174. if OverrideBy == "txt" {
  175. errors.LogDebug(ctx, "query TXT record for "+dest.Address.String())
  176. txtRecords, err := net.DefaultResolver.LookupTXT(ctx, dest.Address.String())
  177. if err != nil {
  178. errors.LogError(ctx, "failed to lookup SRV record: "+err.Error())
  179. return nil, errors.New("failed to lookup SRV record").Base(err)
  180. }
  181. for _, txtRecord := range txtRecords {
  182. errors.LogDebug(ctx, "TXT record: "+txtRecord)
  183. addr_s, port_s, _ := net.SplitHostPort(string(txtRecord))
  184. addr := net.ParseAddress(addr_s)
  185. port, err := net.PortFromString(port_s)
  186. if err != nil {
  187. continue
  188. }
  189. if OverridePort {
  190. newDest.Port = port
  191. }
  192. if OverrideAddress {
  193. newDest.Address = addr
  194. }
  195. return &newDest, nil
  196. }
  197. }
  198. return nil, nil
  199. }
  200. // DialSystem calls system dialer to create a network connection.
  201. func DialSystem(ctx context.Context, dest net.Destination, sockopt *SocketConfig) (net.Conn, error) {
  202. var src net.Address
  203. outbounds := session.OutboundsFromContext(ctx)
  204. var outboundName string
  205. var origTargetAddr net.Address
  206. if len(outbounds) > 0 {
  207. ob := outbounds[len(outbounds)-1]
  208. if sockopt == nil || len(sockopt.DialerProxy) == 0 {
  209. src = ob.Gateway
  210. }
  211. outboundName = ob.Name
  212. origTargetAddr = ob.OriginalTarget.Address
  213. if origTargetAddr == nil {
  214. origTargetAddr = ob.Target.Address
  215. }
  216. }
  217. if sockopt == nil {
  218. return effectiveSystemDialer.Dial(ctx, src, dest, sockopt)
  219. }
  220. if newDest, err := checkAddressPortStrategy(ctx, dest, sockopt); err == nil && newDest != nil {
  221. errors.LogInfo(ctx, "replace destination with "+newDest.String())
  222. dest = *newDest
  223. }
  224. if sockopt.DomainStrategy.HasStrategy() && dest.Address.Family().IsDomain() {
  225. finalStrategy := sockopt.DomainStrategy
  226. if outboundName == "freedom" && dest.Network == net.Network_UDP && origTargetAddr != nil && src == nil {
  227. finalStrategy = finalStrategy.GetDynamicStrategy(origTargetAddr.Family())
  228. }
  229. ips, err := LookupForIP(dest.Address.Domain(), finalStrategy, src)
  230. if err != nil {
  231. errors.LogErrorInner(ctx, err, "failed to resolve ip")
  232. if sockopt.DomainStrategy.ForceIP() {
  233. return nil, err
  234. }
  235. } else if sockopt.HappyEyeballs == nil || sockopt.HappyEyeballs.TryDelayMs == 0 || sockopt.HappyEyeballs.MaxConcurrentTry == 0 || len(ips) < 2 || len(sockopt.DialerProxy) > 0 || dest.Network != net.Network_TCP {
  236. dest.Address = net.IPAddress(ips[dice.Roll(len(ips))])
  237. errors.LogInfo(ctx, "replace destination with "+dest.String())
  238. } else {
  239. return TcpRaceDial(ctx, src, ips, dest.Port, sockopt, dest.Address.String())
  240. }
  241. }
  242. if len(sockopt.DialerProxy) > 0 {
  243. if obm == nil {
  244. return nil, errors.New("there is no outbound manager for dialerProxy").AtError()
  245. }
  246. h := obm.GetHandler(sockopt.DialerProxy)
  247. if h == nil {
  248. return nil, errors.New("there is no outbound handler for dialerProxy").AtError()
  249. }
  250. return redirect(ctx, dest, sockopt.DialerProxy, h), nil
  251. }
  252. return effectiveSystemDialer.Dial(ctx, src, dest, sockopt)
  253. }
  254. func InitSystemDialer(dc dns.Client, om outbound.Manager) {
  255. dnsClient = dc
  256. obm = om
  257. }