handler.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  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/app/proxyman"
  11. "github.com/xtls/xray-core/common"
  12. "github.com/xtls/xray-core/common/buf"
  13. "github.com/xtls/xray-core/common/errors"
  14. "github.com/xtls/xray-core/common/mux"
  15. "github.com/xtls/xray-core/common/net"
  16. "github.com/xtls/xray-core/common/net/cnc"
  17. "github.com/xtls/xray-core/common/session"
  18. "github.com/xtls/xray-core/core"
  19. "github.com/xtls/xray-core/features/outbound"
  20. "github.com/xtls/xray-core/features/policy"
  21. "github.com/xtls/xray-core/features/stats"
  22. "github.com/xtls/xray-core/proxy"
  23. "github.com/xtls/xray-core/transport"
  24. "github.com/xtls/xray-core/transport/internet"
  25. "github.com/xtls/xray-core/transport/internet/stat"
  26. "github.com/xtls/xray-core/transport/internet/tls"
  27. "github.com/xtls/xray-core/transport/pipe"
  28. )
  29. func getStatCounter(v *core.Instance, tag string) (stats.Counter, stats.Counter) {
  30. var uplinkCounter stats.Counter
  31. var downlinkCounter stats.Counter
  32. policy := v.GetFeature(policy.ManagerType()).(policy.Manager)
  33. if len(tag) > 0 && policy.ForSystem().Stats.OutboundUplink {
  34. statsManager := v.GetFeature(stats.ManagerType()).(stats.Manager)
  35. name := "outbound>>>" + tag + ">>>traffic>>>uplink"
  36. c, _ := stats.GetOrRegisterCounter(statsManager, name)
  37. if c != nil {
  38. uplinkCounter = c
  39. }
  40. }
  41. if len(tag) > 0 && policy.ForSystem().Stats.OutboundDownlink {
  42. statsManager := v.GetFeature(stats.ManagerType()).(stats.Manager)
  43. name := "outbound>>>" + tag + ">>>traffic>>>downlink"
  44. c, _ := stats.GetOrRegisterCounter(statsManager, name)
  45. if c != nil {
  46. downlinkCounter = c
  47. }
  48. }
  49. return uplinkCounter, downlinkCounter
  50. }
  51. // Handler implements outbound.Handler.
  52. type Handler struct {
  53. tag string
  54. senderSettings *proxyman.SenderConfig
  55. streamSettings *internet.MemoryStreamConfig
  56. proxy proxy.Outbound
  57. outboundManager outbound.Manager
  58. mux *mux.ClientManager
  59. xudp *mux.ClientManager
  60. udp443 string
  61. uplinkCounter stats.Counter
  62. downlinkCounter stats.Counter
  63. }
  64. // NewHandler creates a new Handler based on the given configuration.
  65. func NewHandler(ctx context.Context, config *core.OutboundHandlerConfig) (outbound.Handler, error) {
  66. v := core.MustFromContext(ctx)
  67. uplinkCounter, downlinkCounter := getStatCounter(v, config.Tag)
  68. h := &Handler{
  69. tag: config.Tag,
  70. outboundManager: v.GetFeature(outbound.ManagerType()).(outbound.Manager),
  71. uplinkCounter: uplinkCounter,
  72. downlinkCounter: downlinkCounter,
  73. }
  74. if config.SenderSettings != nil {
  75. senderSettings, err := config.SenderSettings.GetInstance()
  76. if err != nil {
  77. return nil, err
  78. }
  79. switch s := senderSettings.(type) {
  80. case *proxyman.SenderConfig:
  81. h.senderSettings = s
  82. mss, err := internet.ToMemoryStreamConfig(s.StreamSettings)
  83. if err != nil {
  84. return nil, errors.New("failed to parse stream settings").Base(err).AtWarning()
  85. }
  86. h.streamSettings = mss
  87. default:
  88. return nil, errors.New("settings is not SenderConfig")
  89. }
  90. }
  91. proxyConfig, err := config.ProxySettings.GetInstance()
  92. if err != nil {
  93. return nil, err
  94. }
  95. rawProxyHandler, err := common.CreateObject(ctx, proxyConfig)
  96. if err != nil {
  97. return nil, err
  98. }
  99. proxyHandler, ok := rawProxyHandler.(proxy.Outbound)
  100. if !ok {
  101. return nil, errors.New("not an outbound handler")
  102. }
  103. if h.senderSettings != nil && h.senderSettings.MultiplexSettings != nil {
  104. if config := h.senderSettings.MultiplexSettings; config.Enabled {
  105. // MaxReuseTimes use 65535 as default, and it also means the upper limit of MaxReuseTimes
  106. // Because in mux cool spec, connection ID is 2 bytes
  107. MaxReuseTimes := uint32(65535)
  108. if config.MaxReuseTimes != 0 && config.MaxReuseTimes < 65535 {
  109. MaxReuseTimes = uint32(config.MaxReuseTimes)
  110. }
  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. MaxReuseTimes: MaxReuseTimes,
  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. MaxReuseTimes: 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. if ob.Target.Network == net.Network_UDP && ob.OriginalTarget.Address != nil && ob.OriginalTarget.Address != ob.Target.Address {
  168. link.Reader = &buf.EndpointOverrideReader{Reader: link.Reader, Dest: ob.Target.Address, OriginalDest: ob.OriginalTarget.Address}
  169. link.Writer = &buf.EndpointOverrideWriter{Writer: link.Writer, Dest: ob.Target.Address, OriginalDest: ob.OriginalTarget.Address}
  170. }
  171. if h.mux != nil {
  172. test := func(err error) {
  173. if err != nil {
  174. err := errors.New("failed to process mux outbound traffic").Base(err)
  175. session.SubmitOutboundErrorToOriginator(ctx, err)
  176. errors.LogInfo(ctx, err.Error())
  177. common.Interrupt(link.Writer)
  178. }
  179. }
  180. if ob.Target.Network == net.Network_UDP && ob.Target.Port == 443 {
  181. switch h.udp443 {
  182. case "reject":
  183. test(errors.New("XUDP rejected UDP/443 traffic").AtInfo())
  184. return
  185. case "skip":
  186. goto out
  187. }
  188. }
  189. if h.xudp != nil && ob.Target.Network == net.Network_UDP {
  190. if !h.xudp.Enabled {
  191. goto out
  192. }
  193. test(h.xudp.Dispatch(ctx, link))
  194. return
  195. }
  196. if h.mux.Enabled {
  197. test(h.mux.Dispatch(ctx, link))
  198. return
  199. }
  200. }
  201. out:
  202. err := h.proxy.Process(ctx, link, h)
  203. if err != nil {
  204. if goerrors.Is(err, io.EOF) || goerrors.Is(err, io.ErrClosedPipe) || goerrors.Is(err, context.Canceled) {
  205. err = nil
  206. }
  207. }
  208. if err != nil {
  209. // Ensure outbound ray is properly closed.
  210. err := errors.New("failed to process outbound traffic").Base(err)
  211. session.SubmitOutboundErrorToOriginator(ctx, err)
  212. errors.LogInfo(ctx, err.Error())
  213. common.Interrupt(link.Writer)
  214. } else {
  215. common.Close(link.Writer)
  216. }
  217. common.Interrupt(link.Reader)
  218. }
  219. // Address implements internet.Dialer.
  220. func (h *Handler) Address() net.Address {
  221. if h.senderSettings == nil || h.senderSettings.Via == nil {
  222. return nil
  223. }
  224. return h.senderSettings.Via.AsAddress()
  225. }
  226. func (h *Handler) DestIpAddress() net.IP {
  227. return internet.DestIpAddress()
  228. }
  229. // Dial implements internet.Dialer.
  230. func (h *Handler) Dial(ctx context.Context, dest net.Destination) (stat.Connection, error) {
  231. if h.senderSettings != nil {
  232. if h.senderSettings.ProxySettings.HasTag() {
  233. tag := h.senderSettings.ProxySettings.Tag
  234. handler := h.outboundManager.GetHandler(tag)
  235. if handler != nil {
  236. errors.LogDebug(ctx, "proxying to ", tag, " for dest ", dest)
  237. outbounds := session.OutboundsFromContext(ctx)
  238. ctx = session.ContextWithOutbounds(ctx, append(outbounds, &session.Outbound{
  239. Target: dest,
  240. Tag: tag,
  241. })) // add another outbound in session ctx
  242. opts := pipe.OptionsFromContext(ctx)
  243. uplinkReader, uplinkWriter := pipe.New(opts...)
  244. downlinkReader, downlinkWriter := pipe.New(opts...)
  245. go handler.Dispatch(ctx, &transport.Link{Reader: uplinkReader, Writer: downlinkWriter})
  246. conn := cnc.NewConnection(cnc.ConnectionInputMulti(uplinkWriter), cnc.ConnectionOutputMulti(downlinkReader))
  247. if config := tls.ConfigFromStreamSettings(h.streamSettings); config != nil {
  248. tlsConfig := config.GetTLSConfig(tls.WithDestination(dest))
  249. conn = tls.Client(conn, tlsConfig)
  250. }
  251. return h.getStatCouterConnection(conn), nil
  252. }
  253. errors.LogWarning(ctx, "failed to get outbound handler with tag: ", tag)
  254. }
  255. if h.senderSettings.Via != nil {
  256. outbounds := session.OutboundsFromContext(ctx)
  257. ob := outbounds[len(outbounds)-1]
  258. if h.senderSettings.ViaCidr == "" {
  259. ob.Gateway = h.senderSettings.Via.AsAddress()
  260. } else { //Get a random address.
  261. ob.Gateway = ParseRandomIPv6(h.senderSettings.Via.AsAddress(), h.senderSettings.ViaCidr)
  262. }
  263. }
  264. }
  265. if conn, err := h.getUoTConnection(ctx, dest); err != os.ErrInvalid {
  266. return conn, err
  267. }
  268. conn, err := internet.Dial(ctx, dest, h.streamSettings)
  269. conn = h.getStatCouterConnection(conn)
  270. outbounds := session.OutboundsFromContext(ctx)
  271. ob := outbounds[len(outbounds)-1]
  272. ob.Conn = conn
  273. return conn, err
  274. }
  275. func (h *Handler) getStatCouterConnection(conn stat.Connection) stat.Connection {
  276. if h.uplinkCounter != nil || h.downlinkCounter != nil {
  277. return &stat.CounterConnection{
  278. Connection: conn,
  279. ReadCounter: h.downlinkCounter,
  280. WriteCounter: h.uplinkCounter,
  281. }
  282. }
  283. return conn
  284. }
  285. // GetOutbound implements proxy.GetOutbound.
  286. func (h *Handler) GetOutbound() proxy.Outbound {
  287. return h.proxy
  288. }
  289. // Start implements common.Runnable.
  290. func (h *Handler) Start() error {
  291. return nil
  292. }
  293. // Close implements common.Closable.
  294. func (h *Handler) Close() error {
  295. common.Close(h.mux)
  296. return nil
  297. }
  298. func ParseRandomIPv6(address net.Address, prefix string) net.Address {
  299. _, network, _ := gonet.ParseCIDR(address.IP().String() + "/" + prefix)
  300. maskSize, totalBits := network.Mask.Size()
  301. subnetSize := big.NewInt(1).Lsh(big.NewInt(1), uint(totalBits-maskSize))
  302. // random
  303. randomBigInt, _ := rand.Int(rand.Reader, subnetSize)
  304. startIPBigInt := big.NewInt(0).SetBytes(network.IP.To16())
  305. randomIPBigInt := big.NewInt(0).Add(startIPBigInt, randomBigInt)
  306. randomIPBytes := randomIPBigInt.Bytes()
  307. randomIPBytes = append(make([]byte, 16-len(randomIPBytes)), randomIPBytes...)
  308. return net.ParseAddress(gonet.IP(randomIPBytes).String())
  309. }