handler.go 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  1. package outbound
  2. import (
  3. "context"
  4. "errors"
  5. "io"
  6. "os"
  7. sing_mux "github.com/sagernet/sing-mux"
  8. sing_net "github.com/sagernet/sing/common/network"
  9. "github.com/xtls/xray-core/app/proxyman"
  10. "github.com/xtls/xray-core/common"
  11. "github.com/xtls/xray-core/common/mux"
  12. "github.com/xtls/xray-core/common/net"
  13. "github.com/xtls/xray-core/common/net/cnc"
  14. "github.com/xtls/xray-core/common/session"
  15. "github.com/xtls/xray-core/common/singbridge"
  16. "github.com/xtls/xray-core/core"
  17. "github.com/xtls/xray-core/features/outbound"
  18. "github.com/xtls/xray-core/features/policy"
  19. "github.com/xtls/xray-core/features/stats"
  20. "github.com/xtls/xray-core/proxy"
  21. "github.com/xtls/xray-core/transport"
  22. "github.com/xtls/xray-core/transport/internet"
  23. "github.com/xtls/xray-core/transport/internet/stat"
  24. "github.com/xtls/xray-core/transport/internet/tls"
  25. "github.com/xtls/xray-core/transport/pipe"
  26. )
  27. func getStatCounter(v *core.Instance, tag string) (stats.Counter, stats.Counter) {
  28. var uplinkCounter stats.Counter
  29. var downlinkCounter stats.Counter
  30. policy := v.GetFeature(policy.ManagerType()).(policy.Manager)
  31. if len(tag) > 0 && policy.ForSystem().Stats.OutboundUplink {
  32. statsManager := v.GetFeature(stats.ManagerType()).(stats.Manager)
  33. name := "outbound>>>" + tag + ">>>traffic>>>uplink"
  34. c, _ := stats.GetOrRegisterCounter(statsManager, name)
  35. if c != nil {
  36. uplinkCounter = c
  37. }
  38. }
  39. if len(tag) > 0 && policy.ForSystem().Stats.OutboundDownlink {
  40. statsManager := v.GetFeature(stats.ManagerType()).(stats.Manager)
  41. name := "outbound>>>" + tag + ">>>traffic>>>downlink"
  42. c, _ := stats.GetOrRegisterCounter(statsManager, name)
  43. if c != nil {
  44. downlinkCounter = c
  45. }
  46. }
  47. return uplinkCounter, downlinkCounter
  48. }
  49. // Handler is an implements of outbound.Handler.
  50. type Handler struct {
  51. tag string
  52. senderSettings *proxyman.SenderConfig
  53. streamSettings *internet.MemoryStreamConfig
  54. proxy proxy.Outbound
  55. outboundManager outbound.Manager
  56. mux *mux.ClientManager
  57. xudp *mux.ClientManager
  58. smux *sing_mux.Client
  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. if h.senderSettings != nil && h.senderSettings.SmuxSettings != nil {
  150. if config := h.senderSettings.SmuxSettings; config.Enabled {
  151. h.smux, err = sing_mux.NewClient(sing_mux.Options{
  152. Dialer: singbridge.NewOutboundDialer(proxyHandler, h),
  153. Protocol: config.Protocol,
  154. MaxConnections: int(config.MaxConnections),
  155. MinStreams: int(config.MinStreams),
  156. MaxStreams: int(config.MaxStreams),
  157. Padding: config.Padding,
  158. })
  159. if err != nil {
  160. return nil, newError("failed to create sing mux client").Base(err)
  161. }
  162. }
  163. }
  164. h.proxy = proxyHandler
  165. return h, nil
  166. }
  167. // Tag implements outbound.Handler.
  168. func (h *Handler) Tag() string {
  169. return h.tag
  170. }
  171. // Dispatch implements proxy.Outbound.Dispatch.
  172. func (h *Handler) Dispatch(ctx context.Context, link *transport.Link) {
  173. if h.mux != nil {
  174. test := func(err error) {
  175. if err != nil {
  176. err := newError("failed to process mux outbound traffic").Base(err)
  177. session.SubmitOutboundErrorToOriginator(ctx, err)
  178. err.WriteToLog(session.ExportIDToError(ctx))
  179. common.Interrupt(link.Writer)
  180. }
  181. }
  182. outbound := session.OutboundFromContext(ctx)
  183. if outbound.Target.Network == net.Network_UDP && outbound.Target.Port == 443 {
  184. switch h.udp443 {
  185. case "reject":
  186. test(newError("XUDP rejected UDP/443 traffic").AtInfo())
  187. return
  188. case "skip":
  189. goto out
  190. }
  191. }
  192. if h.xudp != nil && outbound.Target.Network == net.Network_UDP {
  193. if !h.xudp.Enabled {
  194. goto out
  195. }
  196. test(h.xudp.Dispatch(ctx, link))
  197. return
  198. }
  199. if h.mux.Enabled {
  200. test(h.mux.Dispatch(ctx, link))
  201. return
  202. }
  203. }
  204. if h.smux != nil {
  205. test := func(err error) {
  206. if err != nil {
  207. err := newError("failed to process mux outbound traffic").Base(err)
  208. session.SubmitOutboundErrorToOriginator(ctx, err)
  209. err.WriteToLog(session.ExportIDToError(ctx))
  210. common.Interrupt(link.Writer)
  211. }
  212. }
  213. inbound := session.InboundFromContext(ctx)
  214. outbound := session.OutboundFromContext(ctx)
  215. if outbound.Target.Network == net.Network_TCP {
  216. conn, err := h.smux.DialContext(ctx, sing_net.NetworkTCP, singbridge.ToSocksaddr(outbound.Target))
  217. if err != nil {
  218. test(err)
  219. return
  220. }
  221. test(singbridge.CopyConn(ctx, inbound.Conn, link, conn))
  222. } else {
  223. packetConn, err := h.smux.ListenPacket(ctx, singbridge.ToSocksaddr(outbound.Target))
  224. if err != nil {
  225. test(err)
  226. return
  227. }
  228. test(singbridge.CopyPacketConn(ctx, inbound.Conn, link, outbound.Target, packetConn))
  229. }
  230. return
  231. }
  232. out:
  233. err := h.proxy.Process(ctx, link, h)
  234. if err != nil {
  235. if errors.Is(err, io.EOF) || errors.Is(err, io.ErrClosedPipe) || errors.Is(err, context.Canceled) {
  236. err = nil
  237. }
  238. }
  239. if err != nil {
  240. // Ensure outbound ray is properly closed.
  241. err := newError("failed to process outbound traffic").Base(err)
  242. session.SubmitOutboundErrorToOriginator(ctx, err)
  243. err.WriteToLog(session.ExportIDToError(ctx))
  244. common.Interrupt(link.Writer)
  245. } else {
  246. common.Close(link.Writer)
  247. }
  248. common.Interrupt(link.Reader)
  249. }
  250. // Address implements internet.Dialer.
  251. func (h *Handler) Address() net.Address {
  252. if h.senderSettings == nil || h.senderSettings.Via == nil {
  253. return nil
  254. }
  255. return h.senderSettings.Via.AsAddress()
  256. }
  257. // Dial implements internet.Dialer.
  258. func (h *Handler) Dial(ctx context.Context, dest net.Destination) (stat.Connection, error) {
  259. if h.senderSettings != nil {
  260. if h.senderSettings.ProxySettings.HasTag() {
  261. tag := h.senderSettings.ProxySettings.Tag
  262. handler := h.outboundManager.GetHandler(tag)
  263. if handler != nil {
  264. newError("proxying to ", tag, " for dest ", dest).AtDebug().WriteToLog(session.ExportIDToError(ctx))
  265. ctx = session.ContextWithOutbound(ctx, &session.Outbound{
  266. Target: dest,
  267. })
  268. opts := pipe.OptionsFromContext(ctx)
  269. uplinkReader, uplinkWriter := pipe.New(opts...)
  270. downlinkReader, downlinkWriter := pipe.New(opts...)
  271. go handler.Dispatch(ctx, &transport.Link{Reader: uplinkReader, Writer: downlinkWriter})
  272. conn := cnc.NewConnection(cnc.ConnectionInputMulti(uplinkWriter), cnc.ConnectionOutputMulti(downlinkReader))
  273. if config := tls.ConfigFromStreamSettings(h.streamSettings); config != nil {
  274. tlsConfig := config.GetTLSConfig(tls.WithDestination(dest))
  275. conn = tls.Client(conn, tlsConfig)
  276. }
  277. return h.getStatCouterConnection(conn), nil
  278. }
  279. newError("failed to get outbound handler with tag: ", tag).AtWarning().WriteToLog(session.ExportIDToError(ctx))
  280. }
  281. if h.senderSettings.Via != nil {
  282. outbound := session.OutboundFromContext(ctx)
  283. if outbound == nil {
  284. outbound = new(session.Outbound)
  285. ctx = session.ContextWithOutbound(ctx, outbound)
  286. }
  287. outbound.Gateway = h.senderSettings.Via.AsAddress()
  288. }
  289. }
  290. if conn, err := h.getUoTConnection(ctx, dest); err != os.ErrInvalid {
  291. return conn, err
  292. }
  293. conn, err := internet.Dial(ctx, dest, h.streamSettings)
  294. return h.getStatCouterConnection(conn), err
  295. }
  296. func (h *Handler) getStatCouterConnection(conn stat.Connection) stat.Connection {
  297. if h.uplinkCounter != nil || h.downlinkCounter != nil {
  298. return &stat.CounterConnection{
  299. Connection: conn,
  300. ReadCounter: h.downlinkCounter,
  301. WriteCounter: h.uplinkCounter,
  302. }
  303. }
  304. return conn
  305. }
  306. // GetOutbound implements proxy.GetOutbound.
  307. func (h *Handler) GetOutbound() proxy.Outbound {
  308. return h.proxy
  309. }
  310. // Start implements common.Runnable.
  311. func (h *Handler) Start() error {
  312. return nil
  313. }
  314. // Close implements common.Closable.
  315. func (h *Handler) Close() error {
  316. common.Close(h.mux)
  317. return nil
  318. }