handler.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  1. package outbound
  2. import (
  3. "context"
  4. "crypto/rand"
  5. goerrors "errors"
  6. "io"
  7. "math/big"
  8. gonet "net"
  9. "os"
  10. "github.com/xtls/xray-core/common/dice"
  11. "github.com/xtls/xray-core/app/proxyman"
  12. "github.com/xtls/xray-core/common"
  13. "github.com/xtls/xray-core/common/buf"
  14. "github.com/xtls/xray-core/common/errors"
  15. "github.com/xtls/xray-core/common/mux"
  16. "github.com/xtls/xray-core/common/net"
  17. "github.com/xtls/xray-core/common/net/cnc"
  18. "github.com/xtls/xray-core/common/serial"
  19. "github.com/xtls/xray-core/common/session"
  20. "github.com/xtls/xray-core/core"
  21. "github.com/xtls/xray-core/features/outbound"
  22. "github.com/xtls/xray-core/features/policy"
  23. "github.com/xtls/xray-core/features/stats"
  24. "github.com/xtls/xray-core/proxy"
  25. "github.com/xtls/xray-core/transport"
  26. "github.com/xtls/xray-core/transport/internet"
  27. "github.com/xtls/xray-core/transport/internet/stat"
  28. "github.com/xtls/xray-core/transport/internet/tls"
  29. "github.com/xtls/xray-core/transport/pipe"
  30. "google.golang.org/protobuf/proto"
  31. )
  32. func getStatCounter(v *core.Instance, tag string) (stats.Counter, stats.Counter) {
  33. var uplinkCounter stats.Counter
  34. var downlinkCounter stats.Counter
  35. policy := v.GetFeature(policy.ManagerType()).(policy.Manager)
  36. if len(tag) > 0 && policy.ForSystem().Stats.OutboundUplink {
  37. statsManager := v.GetFeature(stats.ManagerType()).(stats.Manager)
  38. name := "outbound>>>" + tag + ">>>traffic>>>uplink"
  39. c, _ := stats.GetOrRegisterCounter(statsManager, name)
  40. if c != nil {
  41. uplinkCounter = c
  42. }
  43. }
  44. if len(tag) > 0 && policy.ForSystem().Stats.OutboundDownlink {
  45. statsManager := v.GetFeature(stats.ManagerType()).(stats.Manager)
  46. name := "outbound>>>" + tag + ">>>traffic>>>downlink"
  47. c, _ := stats.GetOrRegisterCounter(statsManager, name)
  48. if c != nil {
  49. downlinkCounter = c
  50. }
  51. }
  52. return uplinkCounter, downlinkCounter
  53. }
  54. // Handler implements outbound.Handler.
  55. type Handler struct {
  56. tag string
  57. senderSettings *proxyman.SenderConfig
  58. streamSettings *internet.MemoryStreamConfig
  59. proxyConfig proto.Message
  60. proxy proxy.Outbound
  61. outboundManager outbound.Manager
  62. mux *mux.ClientManager
  63. xudp *mux.ClientManager
  64. udp443 string
  65. uplinkCounter stats.Counter
  66. downlinkCounter stats.Counter
  67. }
  68. // NewHandler creates a new Handler based on the given configuration.
  69. func NewHandler(ctx context.Context, config *core.OutboundHandlerConfig) (outbound.Handler, error) {
  70. v := core.MustFromContext(ctx)
  71. uplinkCounter, downlinkCounter := getStatCounter(v, config.Tag)
  72. h := &Handler{
  73. tag: config.Tag,
  74. outboundManager: v.GetFeature(outbound.ManagerType()).(outbound.Manager),
  75. uplinkCounter: uplinkCounter,
  76. downlinkCounter: downlinkCounter,
  77. }
  78. if config.SenderSettings != nil {
  79. senderSettings, err := config.SenderSettings.GetInstance()
  80. if err != nil {
  81. return nil, err
  82. }
  83. switch s := senderSettings.(type) {
  84. case *proxyman.SenderConfig:
  85. h.senderSettings = s
  86. mss, err := internet.ToMemoryStreamConfig(s.StreamSettings)
  87. if err != nil {
  88. return nil, errors.New("failed to parse stream settings").Base(err).AtWarning()
  89. }
  90. h.streamSettings = mss
  91. default:
  92. return nil, errors.New("settings is not SenderConfig")
  93. }
  94. }
  95. proxyConfig, err := config.ProxySettings.GetInstance()
  96. if err != nil {
  97. return nil, err
  98. }
  99. h.proxyConfig = proxyConfig
  100. ctx = session.ContextWithFullHandler(ctx, h)
  101. rawProxyHandler, err := common.CreateObject(ctx, proxyConfig)
  102. if err != nil {
  103. return nil, err
  104. }
  105. proxyHandler, ok := rawProxyHandler.(proxy.Outbound)
  106. if !ok {
  107. return nil, errors.New("not an outbound handler")
  108. }
  109. if h.senderSettings != nil && h.senderSettings.MultiplexSettings != nil {
  110. if config := h.senderSettings.MultiplexSettings; config.Enabled {
  111. if config.Concurrency < 0 {
  112. h.mux = &mux.ClientManager{Enabled: false}
  113. }
  114. if config.Concurrency == 0 {
  115. config.Concurrency = 8 // same as before
  116. }
  117. if config.Concurrency > 0 {
  118. h.mux = &mux.ClientManager{
  119. Enabled: true,
  120. Picker: &mux.IncrementalWorkerPicker{
  121. Factory: &mux.DialingWorkerFactory{
  122. Proxy: proxyHandler,
  123. Dialer: h,
  124. Strategy: mux.ClientStrategy{
  125. MaxConcurrency: uint32(config.Concurrency),
  126. MaxConnection: 128,
  127. },
  128. },
  129. },
  130. }
  131. }
  132. if config.XudpConcurrency < 0 {
  133. h.xudp = &mux.ClientManager{Enabled: false}
  134. }
  135. if config.XudpConcurrency == 0 {
  136. h.xudp = nil // same as before
  137. }
  138. if config.XudpConcurrency > 0 {
  139. h.xudp = &mux.ClientManager{
  140. Enabled: true,
  141. Picker: &mux.IncrementalWorkerPicker{
  142. Factory: &mux.DialingWorkerFactory{
  143. Proxy: proxyHandler,
  144. Dialer: h,
  145. Strategy: mux.ClientStrategy{
  146. MaxConcurrency: uint32(config.XudpConcurrency),
  147. MaxConnection: 128,
  148. },
  149. },
  150. },
  151. }
  152. }
  153. h.udp443 = config.XudpProxyUDP443
  154. }
  155. }
  156. h.proxy = proxyHandler
  157. return h, nil
  158. }
  159. // Tag implements outbound.Handler.
  160. func (h *Handler) Tag() string {
  161. return h.tag
  162. }
  163. // Dispatch implements proxy.Outbound.Dispatch.
  164. func (h *Handler) Dispatch(ctx context.Context, link *transport.Link) {
  165. outbounds := session.OutboundsFromContext(ctx)
  166. ob := outbounds[len(outbounds)-1]
  167. content := session.ContentFromContext(ctx)
  168. if h.senderSettings != nil && h.senderSettings.TargetStrategy.HasStrategy() && ob.Target.Address.Family().IsDomain() && (content == nil || !content.SkipDNSResolve) {
  169. strategy := h.senderSettings.TargetStrategy
  170. if ob.Target.Network == net.Network_UDP && ob.OriginalTarget.Address != nil {
  171. strategy = strategy.GetDynamicStrategy(ob.OriginalTarget.Address.Family())
  172. }
  173. ips, err := internet.LookupForIP(ob.Target.Address.Domain(), strategy, nil)
  174. if err != nil {
  175. errors.LogInfoInner(ctx, err, "failed to resolve ip for target ", ob.Target.Address.Domain())
  176. if h.senderSettings.TargetStrategy.ForceIP() {
  177. err := errors.New("failed to resolve ip for target ", ob.Target.Address.Domain()).Base(err)
  178. session.SubmitOutboundErrorToOriginator(ctx, err)
  179. common.Interrupt(link.Writer)
  180. common.Interrupt(link.Reader)
  181. return
  182. }
  183. } else {
  184. unchangedDomain := ob.Target.Address.Domain()
  185. ob.Target.Address = net.IPAddress(ips[dice.Roll(len(ips))])
  186. errors.LogInfo(ctx, "target: ", unchangedDomain, " resolved to: ", ob.Target.Address.String())
  187. }
  188. }
  189. if ob.Target.Network == net.Network_UDP && ob.OriginalTarget.Address != nil && ob.OriginalTarget.Address != ob.Target.Address {
  190. link.Reader = &buf.EndpointOverrideReader{Reader: link.Reader, Dest: ob.Target.Address, OriginalDest: ob.OriginalTarget.Address}
  191. link.Writer = &buf.EndpointOverrideWriter{Writer: link.Writer, Dest: ob.Target.Address, OriginalDest: ob.OriginalTarget.Address}
  192. }
  193. if h.mux != nil {
  194. test := func(err error) {
  195. if err != nil {
  196. err := errors.New("failed to process mux outbound traffic").Base(err)
  197. session.SubmitOutboundErrorToOriginator(ctx, err)
  198. errors.LogInfo(ctx, err.Error())
  199. common.Interrupt(link.Writer)
  200. common.Interrupt(link.Reader)
  201. }
  202. }
  203. if ob.Target.Network == net.Network_UDP && ob.Target.Port == 443 {
  204. switch h.udp443 {
  205. case "reject":
  206. test(errors.New("XUDP rejected UDP/443 traffic").AtInfo())
  207. return
  208. case "skip":
  209. goto out
  210. }
  211. }
  212. if h.xudp != nil && ob.Target.Network == net.Network_UDP {
  213. if !h.xudp.Enabled {
  214. goto out
  215. }
  216. test(h.xudp.Dispatch(ctx, link))
  217. return
  218. }
  219. if h.mux.Enabled {
  220. test(h.mux.Dispatch(ctx, link))
  221. return
  222. }
  223. }
  224. out:
  225. err := h.proxy.Process(ctx, link, h)
  226. var errC error
  227. if err != nil {
  228. errC = errors.Cause(err)
  229. if goerrors.Is(errC, io.EOF) || goerrors.Is(errC, io.ErrClosedPipe) || goerrors.Is(errC, context.Canceled) {
  230. err = nil
  231. }
  232. }
  233. if err != nil {
  234. // Ensure outbound ray is properly closed.
  235. err := errors.New("failed to process outbound traffic").Base(err)
  236. session.SubmitOutboundErrorToOriginator(ctx, err)
  237. errors.LogInfo(ctx, err.Error())
  238. common.Interrupt(link.Writer)
  239. } else {
  240. if errC != nil && goerrors.Is(errC, io.ErrClosedPipe) {
  241. common.Interrupt(link.Writer)
  242. } else {
  243. common.Close(link.Writer)
  244. }
  245. }
  246. common.Interrupt(link.Reader)
  247. }
  248. func (h *Handler) DestIpAddress() net.IP {
  249. return internet.DestIpAddress()
  250. }
  251. // Dial implements internet.Dialer.
  252. func (h *Handler) Dial(ctx context.Context, dest net.Destination) (stat.Connection, error) {
  253. if h.senderSettings != nil {
  254. if h.senderSettings.ProxySettings.HasTag() {
  255. tag := h.senderSettings.ProxySettings.Tag
  256. handler := h.outboundManager.GetHandler(tag)
  257. if handler != nil {
  258. errors.LogDebug(ctx, "proxying to ", tag, " for dest ", dest)
  259. outbounds := session.OutboundsFromContext(ctx)
  260. ctx = session.ContextWithOutbounds(ctx, append(outbounds, &session.Outbound{
  261. Target: dest,
  262. Tag: tag,
  263. })) // add another outbound in session ctx
  264. opts := pipe.OptionsFromContext(ctx)
  265. uplinkReader, uplinkWriter := pipe.New(opts...)
  266. downlinkReader, downlinkWriter := pipe.New(opts...)
  267. go handler.Dispatch(ctx, &transport.Link{Reader: uplinkReader, Writer: downlinkWriter})
  268. conn := cnc.NewConnection(cnc.ConnectionInputMulti(uplinkWriter), cnc.ConnectionOutputMulti(downlinkReader))
  269. if config := tls.ConfigFromStreamSettings(h.streamSettings); config != nil {
  270. tlsConfig := config.GetTLSConfig(tls.WithDestination(dest))
  271. conn = tls.Client(conn, tlsConfig)
  272. }
  273. return h.getStatCouterConnection(conn), nil
  274. }
  275. errors.LogError(ctx, "failed to get outbound handler with tag: ", tag)
  276. return nil, errors.New("failed to get outbound handler with tag: " + tag)
  277. }
  278. if h.senderSettings.Via != nil {
  279. outbounds := session.OutboundsFromContext(ctx)
  280. ob := outbounds[len(outbounds)-1]
  281. h.SetOutboundGateway(ctx, ob)
  282. }
  283. }
  284. if conn, err := h.getUoTConnection(ctx, dest); err != os.ErrInvalid {
  285. return conn, err
  286. }
  287. conn, err := internet.Dial(ctx, dest, h.streamSettings)
  288. conn = h.getStatCouterConnection(conn)
  289. outbounds := session.OutboundsFromContext(ctx)
  290. ob := outbounds[len(outbounds)-1]
  291. ob.Conn = conn
  292. return conn, err
  293. }
  294. func (h *Handler) SetOutboundGateway(ctx context.Context, ob *session.Outbound) {
  295. if ob.Gateway == nil && h.senderSettings != nil && h.senderSettings.Via != nil && !h.senderSettings.ProxySettings.HasTag() && (h.streamSettings.SocketSettings == nil || len(h.streamSettings.SocketSettings.DialerProxy) == 0) {
  296. var domain string
  297. addr := h.senderSettings.Via.AsAddress()
  298. domain = h.senderSettings.Via.GetDomain()
  299. switch {
  300. case h.senderSettings.ViaCidr != "":
  301. ob.Gateway = ParseRandomIP(addr, h.senderSettings.ViaCidr)
  302. case domain == "origin":
  303. if inbound := session.InboundFromContext(ctx); inbound != nil {
  304. if inbound.Local.IsValid() && inbound.Local.Address.Family().IsIP() {
  305. ob.Gateway = inbound.Local.Address
  306. errors.LogDebug(ctx, "use inbound local ip as sendthrough: ", inbound.Local.Address.String())
  307. }
  308. }
  309. case domain == "srcip":
  310. if inbound := session.InboundFromContext(ctx); inbound != nil {
  311. if inbound.Source.IsValid() && inbound.Source.Address.Family().IsIP() {
  312. ob.Gateway = inbound.Source.Address
  313. errors.LogDebug(ctx, "use inbound source ip as sendthrough: ", inbound.Source.Address.String())
  314. }
  315. }
  316. //case addr.Family().IsDomain():
  317. default:
  318. ob.Gateway = addr
  319. }
  320. }
  321. }
  322. func (h *Handler) getStatCouterConnection(conn stat.Connection) stat.Connection {
  323. if h.uplinkCounter != nil || h.downlinkCounter != nil {
  324. return &stat.CounterConnection{
  325. Connection: conn,
  326. ReadCounter: h.downlinkCounter,
  327. WriteCounter: h.uplinkCounter,
  328. }
  329. }
  330. return conn
  331. }
  332. // GetOutbound implements proxy.GetOutbound.
  333. func (h *Handler) GetOutbound() proxy.Outbound {
  334. return h.proxy
  335. }
  336. // Start implements common.Runnable.
  337. func (h *Handler) Start() error {
  338. return nil
  339. }
  340. // Close implements common.Closable.
  341. func (h *Handler) Close() error {
  342. common.Close(h.mux)
  343. common.Close(h.proxy)
  344. return nil
  345. }
  346. // SenderSettings implements outbound.Handler.
  347. func (h *Handler) SenderSettings() *serial.TypedMessage {
  348. return serial.ToTypedMessage(h.senderSettings)
  349. }
  350. // ProxySettings implements outbound.Handler.
  351. func (h *Handler) ProxySettings() *serial.TypedMessage {
  352. return serial.ToTypedMessage(h.proxyConfig)
  353. }
  354. func ParseRandomIP(addr net.Address, prefix string) net.Address {
  355. _, ipnet, _ := gonet.ParseCIDR(addr.IP().String() + "/" + prefix)
  356. ones, bits := ipnet.Mask.Size()
  357. subnetSize := new(big.Int).Lsh(big.NewInt(1), uint(bits-ones))
  358. rnd, _ := rand.Int(rand.Reader, subnetSize)
  359. startInt := new(big.Int).SetBytes(ipnet.IP)
  360. rndInt := new(big.Int).Add(startInt, rnd)
  361. rndBytes := rndInt.Bytes()
  362. padded := make([]byte, len(ipnet.IP))
  363. copy(padded[len(padded)-len(rndBytes):], rndBytes)
  364. return net.ParseAddress(gonet.IP(padded).String())
  365. }