handler.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  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. rawProxyHandler, err := common.CreateObject(ctx, proxyConfig)
  101. if err != nil {
  102. return nil, err
  103. }
  104. proxyHandler, ok := rawProxyHandler.(proxy.Outbound)
  105. if !ok {
  106. return nil, errors.New("not an outbound handler")
  107. }
  108. if h.senderSettings != nil && h.senderSettings.MultiplexSettings != nil {
  109. if config := h.senderSettings.MultiplexSettings; config.Enabled {
  110. if config.Concurrency < 0 {
  111. h.mux = &mux.ClientManager{Enabled: false}
  112. }
  113. if config.Concurrency == 0 {
  114. config.Concurrency = 8 // same as before
  115. }
  116. if config.Concurrency > 0 {
  117. h.mux = &mux.ClientManager{
  118. Enabled: true,
  119. Picker: &mux.IncrementalWorkerPicker{
  120. Factory: &mux.DialingWorkerFactory{
  121. Proxy: proxyHandler,
  122. Dialer: h,
  123. Strategy: mux.ClientStrategy{
  124. MaxConcurrency: uint32(config.Concurrency),
  125. MaxConnection: 128,
  126. },
  127. },
  128. },
  129. }
  130. }
  131. if config.XudpConcurrency < 0 {
  132. h.xudp = &mux.ClientManager{Enabled: false}
  133. }
  134. if config.XudpConcurrency == 0 {
  135. h.xudp = nil // same as before
  136. }
  137. if config.XudpConcurrency > 0 {
  138. h.xudp = &mux.ClientManager{
  139. Enabled: true,
  140. Picker: &mux.IncrementalWorkerPicker{
  141. Factory: &mux.DialingWorkerFactory{
  142. Proxy: proxyHandler,
  143. Dialer: h,
  144. Strategy: mux.ClientStrategy{
  145. MaxConcurrency: uint32(config.XudpConcurrency),
  146. MaxConnection: 128,
  147. },
  148. },
  149. },
  150. }
  151. }
  152. h.udp443 = config.XudpProxyUDP443
  153. }
  154. }
  155. h.proxy = proxyHandler
  156. return h, nil
  157. }
  158. // Tag implements outbound.Handler.
  159. func (h *Handler) Tag() string {
  160. return h.tag
  161. }
  162. // Dispatch implements proxy.Outbound.Dispatch.
  163. func (h *Handler) Dispatch(ctx context.Context, link *transport.Link) {
  164. outbounds := session.OutboundsFromContext(ctx)
  165. ob := outbounds[len(outbounds)-1]
  166. content := session.ContentFromContext(ctx)
  167. if h.senderSettings != nil && h.senderSettings.TargetStrategy.HasStrategy() && ob.Target.Address.Family().IsDomain() && (content == nil || !content.SkipDNSResolve) {
  168. strategy := h.senderSettings.TargetStrategy
  169. if ob.Target.Network == net.Network_UDP && ob.OriginalTarget.Address != nil {
  170. strategy = strategy.GetDynamicStrategy(ob.OriginalTarget.Address.Family())
  171. }
  172. ips, err := internet.LookupForIP(ob.Target.Address.Domain(), strategy, nil)
  173. if err != nil {
  174. errors.LogInfoInner(ctx, err, "failed to resolve ip for target ", ob.Target.Address.Domain())
  175. if h.senderSettings.TargetStrategy.ForceIP() {
  176. err := errors.New("failed to resolve ip for target ", ob.Target.Address.Domain()).Base(err)
  177. session.SubmitOutboundErrorToOriginator(ctx, err)
  178. common.Interrupt(link.Writer)
  179. common.Interrupt(link.Reader)
  180. return
  181. }
  182. } else {
  183. unchangedDomain := ob.Target.Address.Domain()
  184. ob.Target.Address = net.IPAddress(ips[dice.Roll(len(ips))])
  185. errors.LogInfo(ctx, "target: ", unchangedDomain, " resolved to: ", ob.Target.Address.String())
  186. }
  187. }
  188. if ob.Target.Network == net.Network_UDP && ob.OriginalTarget.Address != nil && ob.OriginalTarget.Address != ob.Target.Address {
  189. link.Reader = &buf.EndpointOverrideReader{Reader: link.Reader, Dest: ob.Target.Address, OriginalDest: ob.OriginalTarget.Address}
  190. link.Writer = &buf.EndpointOverrideWriter{Writer: link.Writer, Dest: ob.Target.Address, OriginalDest: ob.OriginalTarget.Address}
  191. }
  192. if h.mux != nil {
  193. test := func(err error) {
  194. if err != nil {
  195. err := errors.New("failed to process mux outbound traffic").Base(err)
  196. session.SubmitOutboundErrorToOriginator(ctx, err)
  197. errors.LogInfo(ctx, err.Error())
  198. common.Interrupt(link.Writer)
  199. common.Interrupt(link.Reader)
  200. }
  201. }
  202. if ob.Target.Network == net.Network_UDP && ob.Target.Port == 443 {
  203. switch h.udp443 {
  204. case "reject":
  205. test(errors.New("XUDP rejected UDP/443 traffic").AtInfo())
  206. return
  207. case "skip":
  208. goto out
  209. }
  210. }
  211. if h.xudp != nil && ob.Target.Network == net.Network_UDP {
  212. if !h.xudp.Enabled {
  213. goto out
  214. }
  215. test(h.xudp.Dispatch(ctx, link))
  216. return
  217. }
  218. if h.mux.Enabled {
  219. test(h.mux.Dispatch(ctx, link))
  220. return
  221. }
  222. }
  223. out:
  224. err := h.proxy.Process(ctx, link, h)
  225. if err != nil {
  226. if goerrors.Is(err, io.EOF) || goerrors.Is(err, io.ErrClosedPipe) || goerrors.Is(err, context.Canceled) {
  227. err = nil
  228. }
  229. }
  230. if err != nil {
  231. // Ensure outbound ray is properly closed.
  232. err := errors.New("failed to process outbound traffic").Base(err)
  233. session.SubmitOutboundErrorToOriginator(ctx, err)
  234. errors.LogInfo(ctx, err.Error())
  235. common.Interrupt(link.Writer)
  236. } else {
  237. common.Close(link.Writer)
  238. }
  239. common.Interrupt(link.Reader)
  240. }
  241. func (h *Handler) DestIpAddress() net.IP {
  242. return internet.DestIpAddress()
  243. }
  244. // Dial implements internet.Dialer.
  245. func (h *Handler) Dial(ctx context.Context, dest net.Destination) (stat.Connection, error) {
  246. if h.senderSettings != nil {
  247. if h.senderSettings.ProxySettings.HasTag() {
  248. tag := h.senderSettings.ProxySettings.Tag
  249. handler := h.outboundManager.GetHandler(tag)
  250. if handler != nil {
  251. errors.LogDebug(ctx, "proxying to ", tag, " for dest ", dest)
  252. outbounds := session.OutboundsFromContext(ctx)
  253. ctx = session.ContextWithOutbounds(ctx, append(outbounds, &session.Outbound{
  254. Target: dest,
  255. Tag: tag,
  256. })) // add another outbound in session ctx
  257. opts := pipe.OptionsFromContext(ctx)
  258. uplinkReader, uplinkWriter := pipe.New(opts...)
  259. downlinkReader, downlinkWriter := pipe.New(opts...)
  260. go handler.Dispatch(ctx, &transport.Link{Reader: uplinkReader, Writer: downlinkWriter})
  261. conn := cnc.NewConnection(cnc.ConnectionInputMulti(uplinkWriter), cnc.ConnectionOutputMulti(downlinkReader))
  262. if config := tls.ConfigFromStreamSettings(h.streamSettings); config != nil {
  263. tlsConfig := config.GetTLSConfig(tls.WithDestination(dest))
  264. conn = tls.Client(conn, tlsConfig)
  265. }
  266. return h.getStatCouterConnection(conn), nil
  267. }
  268. errors.LogError(ctx, "failed to get outbound handler with tag: ", tag)
  269. return nil, errors.New("failed to get outbound handler with tag: " + tag)
  270. }
  271. if h.senderSettings.Via != nil {
  272. outbounds := session.OutboundsFromContext(ctx)
  273. ob := outbounds[len(outbounds)-1]
  274. h.SetOutboundGateway(ctx, ob)
  275. }
  276. }
  277. if conn, err := h.getUoTConnection(ctx, dest); err != os.ErrInvalid {
  278. return conn, err
  279. }
  280. conn, err := internet.Dial(ctx, dest, h.streamSettings)
  281. conn = h.getStatCouterConnection(conn)
  282. outbounds := session.OutboundsFromContext(ctx)
  283. ob := outbounds[len(outbounds)-1]
  284. ob.Conn = conn
  285. return conn, err
  286. }
  287. func (h *Handler) SetOutboundGateway(ctx context.Context, ob *session.Outbound) {
  288. 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) {
  289. var domain string
  290. addr := h.senderSettings.Via.AsAddress()
  291. domain = h.senderSettings.Via.GetDomain()
  292. switch {
  293. case h.senderSettings.ViaCidr != "":
  294. ob.Gateway = ParseRandomIP(addr, h.senderSettings.ViaCidr)
  295. case domain == "origin":
  296. if inbound := session.InboundFromContext(ctx); inbound != nil {
  297. if inbound.Local.IsValid() && inbound.Local.Address.Family().IsIP() {
  298. ob.Gateway = inbound.Local.Address
  299. errors.LogDebug(ctx, "use inbound local ip as sendthrough: ", inbound.Local.Address.String())
  300. }
  301. }
  302. case domain == "srcip":
  303. if inbound := session.InboundFromContext(ctx); inbound != nil {
  304. if inbound.Source.IsValid() && inbound.Source.Address.Family().IsIP() {
  305. ob.Gateway = inbound.Source.Address
  306. errors.LogDebug(ctx, "use inbound source ip as sendthrough: ", inbound.Source.Address.String())
  307. }
  308. }
  309. //case addr.Family().IsDomain():
  310. default:
  311. ob.Gateway = addr
  312. }
  313. }
  314. }
  315. func (h *Handler) getStatCouterConnection(conn stat.Connection) stat.Connection {
  316. if h.uplinkCounter != nil || h.downlinkCounter != nil {
  317. return &stat.CounterConnection{
  318. Connection: conn,
  319. ReadCounter: h.downlinkCounter,
  320. WriteCounter: h.uplinkCounter,
  321. }
  322. }
  323. return conn
  324. }
  325. // GetOutbound implements proxy.GetOutbound.
  326. func (h *Handler) GetOutbound() proxy.Outbound {
  327. return h.proxy
  328. }
  329. // Start implements common.Runnable.
  330. func (h *Handler) Start() error {
  331. return nil
  332. }
  333. // Close implements common.Closable.
  334. func (h *Handler) Close() error {
  335. common.Close(h.mux)
  336. common.Close(h.proxy)
  337. return nil
  338. }
  339. // SenderSettings implements outbound.Handler.
  340. func (h *Handler) SenderSettings() *serial.TypedMessage {
  341. return serial.ToTypedMessage(h.senderSettings)
  342. }
  343. // ProxySettings implements outbound.Handler.
  344. func (h *Handler) ProxySettings() *serial.TypedMessage {
  345. return serial.ToTypedMessage(h.proxyConfig)
  346. }
  347. func ParseRandomIP(addr net.Address, prefix string) net.Address {
  348. _, ipnet, _ := gonet.ParseCIDR(addr.IP().String() + "/" + prefix)
  349. ones, bits := ipnet.Mask.Size()
  350. subnetSize := new(big.Int).Lsh(big.NewInt(1), uint(bits-ones))
  351. rnd, _ := rand.Int(rand.Reader, subnetSize)
  352. startInt := new(big.Int).SetBytes(ipnet.IP)
  353. rndInt := new(big.Int).Add(startInt, rnd)
  354. rndBytes := rndInt.Bytes()
  355. padded := make([]byte, len(ipnet.IP))
  356. copy(padded[len(padded)-len(rndBytes):], rndBytes)
  357. return net.ParseAddress(gonet.IP(padded).String())
  358. }