1
0

handler.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  1. package outbound
  2. import (
  3. "context"
  4. "crypto/rand"
  5. goerrors "errors"
  6. "io"
  7. "math/big"
  8. "os"
  9. "github.com/xtls/xray-core/common/dice"
  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. ctx = session.ContextWithFullHandler(ctx, h)
  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. var errC error
  226. if err != nil {
  227. errC = errors.Cause(err)
  228. if goerrors.Is(errC, io.EOF) || goerrors.Is(errC, io.ErrClosedPipe) || goerrors.Is(errC, context.Canceled) {
  229. err = nil
  230. }
  231. }
  232. if err != nil {
  233. // Ensure outbound ray is properly closed.
  234. err := errors.New("failed to process outbound traffic").Base(err)
  235. session.SubmitOutboundErrorToOriginator(ctx, err)
  236. errors.LogInfo(ctx, err.Error())
  237. common.Interrupt(link.Writer)
  238. } else {
  239. if errC != nil && goerrors.Is(errC, io.ErrClosedPipe) {
  240. common.Interrupt(link.Writer)
  241. } else {
  242. common.Close(link.Writer)
  243. }
  244. }
  245. common.Interrupt(link.Reader)
  246. }
  247. func (h *Handler) DestIpAddress() net.IP {
  248. return internet.DestIpAddress()
  249. }
  250. // Dial implements internet.Dialer.
  251. func (h *Handler) Dial(ctx context.Context, dest net.Destination) (stat.Connection, error) {
  252. if h.senderSettings != nil {
  253. if h.senderSettings.ProxySettings.HasTag() {
  254. tag := h.senderSettings.ProxySettings.Tag
  255. handler := h.outboundManager.GetHandler(tag)
  256. if handler != nil {
  257. errors.LogDebug(ctx, "proxying to ", tag, " for dest ", dest)
  258. outbounds := session.OutboundsFromContext(ctx)
  259. ctx = session.ContextWithOutbounds(ctx, append(outbounds, &session.Outbound{
  260. Target: dest,
  261. Tag: tag,
  262. })) // add another outbound in session ctx
  263. opts := pipe.OptionsFromContext(ctx)
  264. uplinkReader, uplinkWriter := pipe.New(opts...)
  265. downlinkReader, downlinkWriter := pipe.New(opts...)
  266. go handler.Dispatch(ctx, &transport.Link{Reader: uplinkReader, Writer: downlinkWriter})
  267. conn := cnc.NewConnection(cnc.ConnectionInputMulti(uplinkWriter), cnc.ConnectionOutputMulti(downlinkReader))
  268. if config := tls.ConfigFromStreamSettings(h.streamSettings); config != nil {
  269. tlsConfig := config.GetTLSConfig(tls.WithDestination(dest))
  270. conn = tls.Client(conn, tlsConfig)
  271. }
  272. return h.getStatCouterConnection(conn), nil
  273. }
  274. errors.LogError(ctx, "failed to get outbound handler with tag: ", tag)
  275. return nil, errors.New("failed to get outbound handler with tag: " + tag)
  276. }
  277. if h.senderSettings.Via != nil {
  278. outbounds := session.OutboundsFromContext(ctx)
  279. ob := outbounds[len(outbounds)-1]
  280. h.SetOutboundGateway(ctx, ob)
  281. }
  282. }
  283. if conn, err := h.getUoTConnection(ctx, dest); err != os.ErrInvalid {
  284. return conn, err
  285. }
  286. conn, err := internet.Dial(ctx, dest, h.streamSettings)
  287. conn = h.getStatCouterConnection(conn)
  288. outbounds := session.OutboundsFromContext(ctx)
  289. if outbounds != nil {
  290. ob := outbounds[len(outbounds)-1]
  291. ob.Conn = conn
  292. } else {
  293. // for Vision's pre-connect
  294. }
  295. return conn, err
  296. }
  297. func (h *Handler) SetOutboundGateway(ctx context.Context, ob *session.Outbound) {
  298. 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) {
  299. var domain string
  300. addr := h.senderSettings.Via.AsAddress()
  301. domain = h.senderSettings.Via.GetDomain()
  302. switch {
  303. case h.senderSettings.ViaCidr != "":
  304. ob.Gateway = ParseRandomIP(addr, h.senderSettings.ViaCidr)
  305. case domain == "origin":
  306. if inbound := session.InboundFromContext(ctx); inbound != nil {
  307. if inbound.Local.IsValid() && inbound.Local.Address.Family().IsIP() {
  308. ob.Gateway = inbound.Local.Address
  309. errors.LogDebug(ctx, "use inbound local ip as sendthrough: ", inbound.Local.Address.String())
  310. }
  311. }
  312. case domain == "srcip":
  313. if inbound := session.InboundFromContext(ctx); inbound != nil {
  314. if inbound.Source.IsValid() && inbound.Source.Address.Family().IsIP() {
  315. ob.Gateway = inbound.Source.Address
  316. errors.LogDebug(ctx, "use inbound source ip as sendthrough: ", inbound.Source.Address.String())
  317. }
  318. }
  319. //case addr.Family().IsDomain():
  320. default:
  321. ob.Gateway = addr
  322. }
  323. }
  324. }
  325. func (h *Handler) getStatCouterConnection(conn stat.Connection) stat.Connection {
  326. if h.uplinkCounter != nil || h.downlinkCounter != nil {
  327. return &stat.CounterConnection{
  328. Connection: conn,
  329. ReadCounter: h.downlinkCounter,
  330. WriteCounter: h.uplinkCounter,
  331. }
  332. }
  333. return conn
  334. }
  335. // GetOutbound implements proxy.GetOutbound.
  336. func (h *Handler) GetOutbound() proxy.Outbound {
  337. return h.proxy
  338. }
  339. // Start implements common.Runnable.
  340. func (h *Handler) Start() error {
  341. return nil
  342. }
  343. // Close implements common.Closable.
  344. func (h *Handler) Close() error {
  345. common.Close(h.mux)
  346. common.Close(h.proxy)
  347. return nil
  348. }
  349. // SenderSettings implements outbound.Handler.
  350. func (h *Handler) SenderSettings() *serial.TypedMessage {
  351. return serial.ToTypedMessage(h.senderSettings)
  352. }
  353. // ProxySettings implements outbound.Handler.
  354. func (h *Handler) ProxySettings() *serial.TypedMessage {
  355. return serial.ToTypedMessage(h.proxyConfig)
  356. }
  357. func ParseRandomIP(addr net.Address, prefix string) net.Address {
  358. _, ipnet, _ := net.ParseCIDR(addr.IP().String() + "/" + prefix)
  359. ones, bits := ipnet.Mask.Size()
  360. subnetSize := new(big.Int).Lsh(big.NewInt(1), uint(bits-ones))
  361. rnd, _ := rand.Int(rand.Reader, subnetSize)
  362. startInt := new(big.Int).SetBytes(ipnet.IP)
  363. rndInt := new(big.Int).Add(startInt, rnd)
  364. rndBytes := rndInt.Bytes()
  365. padded := make([]byte, len(ipnet.IP))
  366. copy(padded[len(padded)-len(rndBytes):], rndBytes)
  367. return net.ParseAddress(net.IP(padded).String())
  368. }