handler.go 8.9 KB

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