handler.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  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. if config.Concurrency < 0 {
  106. h.mux = &mux.ClientManager{Enabled: false}
  107. }
  108. if config.Concurrency == 0 {
  109. config.Concurrency = 8 // same as before
  110. }
  111. if config.Concurrency > 0 {
  112. h.mux = &mux.ClientManager{
  113. Enabled: true,
  114. Picker: &mux.IncrementalWorkerPicker{
  115. Factory: &mux.DialingWorkerFactory{
  116. Proxy: proxyHandler,
  117. Dialer: h,
  118. Strategy: mux.ClientStrategy{
  119. MaxConcurrency: uint32(config.Concurrency),
  120. MaxConnection: 128,
  121. },
  122. },
  123. },
  124. }
  125. }
  126. if config.XudpConcurrency < 0 {
  127. h.xudp = &mux.ClientManager{Enabled: false}
  128. }
  129. if config.XudpConcurrency == 0 {
  130. h.xudp = nil // same as before
  131. }
  132. if config.XudpConcurrency > 0 {
  133. h.xudp = &mux.ClientManager{
  134. Enabled: true,
  135. Picker: &mux.IncrementalWorkerPicker{
  136. Factory: &mux.DialingWorkerFactory{
  137. Proxy: proxyHandler,
  138. Dialer: h,
  139. Strategy: mux.ClientStrategy{
  140. MaxConcurrency: uint32(config.XudpConcurrency),
  141. MaxConnection: 128,
  142. },
  143. },
  144. },
  145. }
  146. }
  147. h.udp443 = config.XudpProxyUDP443
  148. }
  149. }
  150. h.proxy = proxyHandler
  151. return h, nil
  152. }
  153. // Tag implements outbound.Handler.
  154. func (h *Handler) Tag() string {
  155. return h.tag
  156. }
  157. // Dispatch implements proxy.Outbound.Dispatch.
  158. func (h *Handler) Dispatch(ctx context.Context, link *transport.Link) {
  159. outbounds := session.OutboundsFromContext(ctx)
  160. ob := outbounds[len(outbounds)-1]
  161. if ob.Target.Network == net.Network_UDP && ob.OriginalTarget.Address != nil && ob.OriginalTarget.Address != ob.Target.Address {
  162. link.Reader = &buf.EndpointOverrideReader{Reader: link.Reader, Dest: ob.Target.Address, OriginalDest: ob.OriginalTarget.Address}
  163. link.Writer = &buf.EndpointOverrideWriter{Writer: link.Writer, Dest: ob.Target.Address, OriginalDest: ob.OriginalTarget.Address}
  164. }
  165. if h.mux != nil {
  166. test := func(err error) {
  167. if err != nil {
  168. err := errors.New("failed to process mux outbound traffic").Base(err)
  169. session.SubmitOutboundErrorToOriginator(ctx, err)
  170. errors.LogInfo(ctx, err.Error())
  171. common.Interrupt(link.Writer)
  172. }
  173. }
  174. if ob.Target.Network == net.Network_UDP && ob.Target.Port == 443 {
  175. switch h.udp443 {
  176. case "reject":
  177. test(errors.New("XUDP rejected UDP/443 traffic").AtInfo())
  178. return
  179. case "skip":
  180. goto out
  181. }
  182. }
  183. if h.xudp != nil && ob.Target.Network == net.Network_UDP {
  184. if !h.xudp.Enabled {
  185. goto out
  186. }
  187. test(h.xudp.Dispatch(ctx, link))
  188. return
  189. }
  190. if h.mux.Enabled {
  191. test(h.mux.Dispatch(ctx, link))
  192. return
  193. }
  194. }
  195. out:
  196. err := h.proxy.Process(ctx, link, h)
  197. if err != nil {
  198. if goerrors.Is(err, io.EOF) || goerrors.Is(err, io.ErrClosedPipe) || goerrors.Is(err, context.Canceled) {
  199. err = nil
  200. }
  201. }
  202. if err != nil {
  203. // Ensure outbound ray is properly closed.
  204. err := errors.New("failed to process outbound traffic").Base(err)
  205. session.SubmitOutboundErrorToOriginator(ctx, err)
  206. errors.LogInfo(ctx, err.Error())
  207. common.Interrupt(link.Writer)
  208. } else {
  209. common.Close(link.Writer)
  210. }
  211. common.Interrupt(link.Reader)
  212. }
  213. // Address implements internet.Dialer.
  214. func (h *Handler) Address() net.Address {
  215. if h.senderSettings == nil || h.senderSettings.Via == nil {
  216. return nil
  217. }
  218. return h.senderSettings.Via.AsAddress()
  219. }
  220. func (h *Handler) DestIpAddress() net.IP {
  221. return internet.DestIpAddress()
  222. }
  223. // Dial implements internet.Dialer.
  224. func (h *Handler) Dial(ctx context.Context, dest net.Destination) (stat.Connection, error) {
  225. if h.senderSettings != nil {
  226. if h.senderSettings.ProxySettings.HasTag() {
  227. tag := h.senderSettings.ProxySettings.Tag
  228. handler := h.outboundManager.GetHandler(tag)
  229. if handler != nil {
  230. errors.LogDebug(ctx, "proxying to ", tag, " for dest ", dest)
  231. outbounds := session.OutboundsFromContext(ctx)
  232. ctx = session.ContextWithOutbounds(ctx, append(outbounds, &session.Outbound{
  233. Target: dest,
  234. Tag: tag,
  235. })) // add another outbound in session ctx
  236. opts := pipe.OptionsFromContext(ctx)
  237. uplinkReader, uplinkWriter := pipe.New(opts...)
  238. downlinkReader, downlinkWriter := pipe.New(opts...)
  239. go handler.Dispatch(ctx, &transport.Link{Reader: uplinkReader, Writer: downlinkWriter})
  240. conn := cnc.NewConnection(cnc.ConnectionInputMulti(uplinkWriter), cnc.ConnectionOutputMulti(downlinkReader))
  241. if config := tls.ConfigFromStreamSettings(h.streamSettings); config != nil {
  242. tlsConfig := config.GetTLSConfig(tls.WithDestination(dest))
  243. conn = tls.Client(conn, tlsConfig)
  244. }
  245. return h.getStatCouterConnection(conn), nil
  246. }
  247. errors.LogWarning(ctx, "failed to get outbound handler with tag: ", tag)
  248. }
  249. if h.senderSettings.Via != nil {
  250. outbounds := session.OutboundsFromContext(ctx)
  251. ob := outbounds[len(outbounds)-1]
  252. if h.senderSettings.ViaCidr == "" {
  253. if h.senderSettings.Via.AsAddress().Family().IsDomain() && h.senderSettings.Via.AsAddress().Domain() == "origin" {
  254. if inbound := session.InboundFromContext(ctx); inbound != nil {
  255. origin, _, err := net.SplitHostPort(inbound.Conn.LocalAddr().String())
  256. if err == nil {
  257. ob.Gateway = net.ParseAddress(origin)
  258. }
  259. }
  260. } else {
  261. ob.Gateway = h.senderSettings.Via.AsAddress()
  262. }
  263. } else { //Get a random address.
  264. ob.Gateway = ParseRandomIPv6(h.senderSettings.Via.AsAddress(), h.senderSettings.ViaCidr)
  265. }
  266. }
  267. }
  268. if conn, err := h.getUoTConnection(ctx, dest); err != os.ErrInvalid {
  269. return conn, err
  270. }
  271. conn, err := internet.Dial(ctx, dest, h.streamSettings)
  272. conn = h.getStatCouterConnection(conn)
  273. outbounds := session.OutboundsFromContext(ctx)
  274. ob := outbounds[len(outbounds)-1]
  275. ob.Conn = conn
  276. return conn, err
  277. }
  278. func (h *Handler) getStatCouterConnection(conn stat.Connection) stat.Connection {
  279. if h.uplinkCounter != nil || h.downlinkCounter != nil {
  280. return &stat.CounterConnection{
  281. Connection: conn,
  282. ReadCounter: h.downlinkCounter,
  283. WriteCounter: h.uplinkCounter,
  284. }
  285. }
  286. return conn
  287. }
  288. // GetOutbound implements proxy.GetOutbound.
  289. func (h *Handler) GetOutbound() proxy.Outbound {
  290. return h.proxy
  291. }
  292. // Start implements common.Runnable.
  293. func (h *Handler) Start() error {
  294. return nil
  295. }
  296. // Close implements common.Closable.
  297. func (h *Handler) Close() error {
  298. common.Close(h.mux)
  299. return nil
  300. }
  301. func ParseRandomIPv6(address net.Address, prefix string) net.Address {
  302. _, network, _ := gonet.ParseCIDR(address.IP().String() + "/" + prefix)
  303. maskSize, totalBits := network.Mask.Size()
  304. subnetSize := big.NewInt(1).Lsh(big.NewInt(1), uint(totalBits-maskSize))
  305. // random
  306. randomBigInt, _ := rand.Int(rand.Reader, subnetSize)
  307. startIPBigInt := big.NewInt(0).SetBytes(network.IP.To16())
  308. randomIPBigInt := big.NewInt(0).Add(startIPBigInt, randomBigInt)
  309. randomIPBytes := randomIPBigInt.Bytes()
  310. randomIPBytes = append(make([]byte, 16-len(randomIPBytes)), randomIPBytes...)
  311. return net.ParseAddress(gonet.IP(randomIPBytes).String())
  312. }