dialer.go 9.0 KB

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