handler.go 9.9 KB

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