handler.go 11 KB

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