handler.go 8.4 KB

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