handler.go 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  1. package outbound
  2. import (
  3. "context"
  4. "github.com/xtls/xray-core/transport/internet/stat"
  5. "github.com/xtls/xray-core/app/proxyman"
  6. "github.com/xtls/xray-core/common"
  7. "github.com/xtls/xray-core/common/mux"
  8. "github.com/xtls/xray-core/common/net"
  9. "github.com/xtls/xray-core/common/net/cnc"
  10. "github.com/xtls/xray-core/common/session"
  11. "github.com/xtls/xray-core/core"
  12. "github.com/xtls/xray-core/features/outbound"
  13. "github.com/xtls/xray-core/features/policy"
  14. "github.com/xtls/xray-core/features/stats"
  15. "github.com/xtls/xray-core/proxy"
  16. "github.com/xtls/xray-core/transport"
  17. "github.com/xtls/xray-core/transport/internet"
  18. "github.com/xtls/xray-core/transport/internet/tls"
  19. "github.com/xtls/xray-core/transport/pipe"
  20. )
  21. func getStatCounter(v *core.Instance, tag string) (stats.Counter, stats.Counter) {
  22. var uplinkCounter stats.Counter
  23. var downlinkCounter stats.Counter
  24. policy := v.GetFeature(policy.ManagerType()).(policy.Manager)
  25. if len(tag) > 0 && policy.ForSystem().Stats.OutboundUplink {
  26. statsManager := v.GetFeature(stats.ManagerType()).(stats.Manager)
  27. name := "outbound>>>" + tag + ">>>traffic>>>uplink"
  28. c, _ := stats.GetOrRegisterCounter(statsManager, name)
  29. if c != nil {
  30. uplinkCounter = c
  31. }
  32. }
  33. if len(tag) > 0 && policy.ForSystem().Stats.OutboundDownlink {
  34. statsManager := v.GetFeature(stats.ManagerType()).(stats.Manager)
  35. name := "outbound>>>" + tag + ">>>traffic>>>downlink"
  36. c, _ := stats.GetOrRegisterCounter(statsManager, name)
  37. if c != nil {
  38. downlinkCounter = c
  39. }
  40. }
  41. return uplinkCounter, downlinkCounter
  42. }
  43. // Handler is an implements of outbound.Handler.
  44. type Handler struct {
  45. tag string
  46. senderSettings *proxyman.SenderConfig
  47. streamSettings *internet.MemoryStreamConfig
  48. proxy proxy.Outbound
  49. outboundManager outbound.Manager
  50. mux *mux.ClientManager
  51. uplinkCounter stats.Counter
  52. downlinkCounter stats.Counter
  53. }
  54. // NewHandler create a new Handler based on the given configuration.
  55. func NewHandler(ctx context.Context, config *core.OutboundHandlerConfig) (outbound.Handler, error) {
  56. v := core.MustFromContext(ctx)
  57. uplinkCounter, downlinkCounter := getStatCounter(v, config.Tag)
  58. h := &Handler{
  59. tag: config.Tag,
  60. outboundManager: v.GetFeature(outbound.ManagerType()).(outbound.Manager),
  61. uplinkCounter: uplinkCounter,
  62. downlinkCounter: downlinkCounter,
  63. }
  64. if config.SenderSettings != nil {
  65. senderSettings, err := config.SenderSettings.GetInstance()
  66. if err != nil {
  67. return nil, err
  68. }
  69. switch s := senderSettings.(type) {
  70. case *proxyman.SenderConfig:
  71. h.senderSettings = s
  72. mss, err := internet.ToMemoryStreamConfig(s.StreamSettings)
  73. if err != nil {
  74. return nil, newError("failed to parse stream settings").Base(err).AtWarning()
  75. }
  76. h.streamSettings = mss
  77. default:
  78. return nil, newError("settings is not SenderConfig")
  79. }
  80. }
  81. proxyConfig, err := config.ProxySettings.GetInstance()
  82. if err != nil {
  83. return nil, err
  84. }
  85. rawProxyHandler, err := common.CreateObject(ctx, proxyConfig)
  86. if err != nil {
  87. return nil, err
  88. }
  89. proxyHandler, ok := rawProxyHandler.(proxy.Outbound)
  90. if !ok {
  91. return nil, newError("not an outbound handler")
  92. }
  93. if h.senderSettings != nil && h.senderSettings.MultiplexSettings != nil {
  94. config := h.senderSettings.MultiplexSettings
  95. if config.Concurrency < 1 || config.Concurrency > 1024 {
  96. return nil, newError("invalid mux concurrency: ", config.Concurrency).AtWarning()
  97. }
  98. h.mux = &mux.ClientManager{
  99. Enabled: h.senderSettings.MultiplexSettings.Enabled,
  100. Picker: &mux.IncrementalWorkerPicker{
  101. Factory: &mux.DialingWorkerFactory{
  102. Proxy: proxyHandler,
  103. Dialer: h,
  104. Strategy: mux.ClientStrategy{
  105. MaxConcurrency: config.Concurrency,
  106. MaxConnection: 128,
  107. },
  108. },
  109. },
  110. }
  111. }
  112. h.proxy = proxyHandler
  113. return h, nil
  114. }
  115. // Tag implements outbound.Handler.
  116. func (h *Handler) Tag() string {
  117. return h.tag
  118. }
  119. // Dispatch implements proxy.Outbound.Dispatch.
  120. func (h *Handler) Dispatch(ctx context.Context, link *transport.Link) {
  121. if h.mux != nil && (h.mux.Enabled || session.MuxPreferedFromContext(ctx)) {
  122. if err := h.mux.Dispatch(ctx, link); err != nil {
  123. newError("failed to process mux outbound traffic").Base(err).WriteToLog(session.ExportIDToError(ctx))
  124. common.Interrupt(link.Writer)
  125. }
  126. } else {
  127. if err := h.proxy.Process(ctx, link, h); err != nil {
  128. // Ensure outbound ray is properly closed.
  129. newError("failed to process outbound traffic").Base(err).WriteToLog(session.ExportIDToError(ctx))
  130. common.Interrupt(link.Writer)
  131. } else {
  132. common.Must(common.Close(link.Writer))
  133. }
  134. common.Interrupt(link.Reader)
  135. }
  136. }
  137. // Address implements internet.Dialer.
  138. func (h *Handler) Address() net.Address {
  139. if h.senderSettings == nil || h.senderSettings.Via == nil {
  140. return nil
  141. }
  142. return h.senderSettings.Via.AsAddress()
  143. }
  144. // Dial implements internet.Dialer.
  145. func (h *Handler) Dial(ctx context.Context, dest net.Destination) (stat.Connection, error) {
  146. if h.senderSettings != nil {
  147. if h.senderSettings.ProxySettings.HasTag() {
  148. tag := h.senderSettings.ProxySettings.Tag
  149. handler := h.outboundManager.GetHandler(tag)
  150. if handler != nil {
  151. newError("proxying to ", tag, " for dest ", dest).AtDebug().WriteToLog(session.ExportIDToError(ctx))
  152. ctx = session.ContextWithOutbound(ctx, &session.Outbound{
  153. Target: dest,
  154. })
  155. opts := pipe.OptionsFromContext(ctx)
  156. uplinkReader, uplinkWriter := pipe.New(opts...)
  157. downlinkReader, downlinkWriter := pipe.New(opts...)
  158. go handler.Dispatch(ctx, &transport.Link{Reader: uplinkReader, Writer: downlinkWriter})
  159. conn := cnc.NewConnection(cnc.ConnectionInputMulti(uplinkWriter), cnc.ConnectionOutputMulti(downlinkReader))
  160. if config := tls.ConfigFromStreamSettings(h.streamSettings); config != nil {
  161. tlsConfig := config.GetTLSConfig(tls.WithDestination(dest))
  162. conn = tls.Client(conn, tlsConfig)
  163. }
  164. return h.getStatCouterConnection(conn), nil
  165. }
  166. newError("failed to get outbound handler with tag: ", tag).AtWarning().WriteToLog(session.ExportIDToError(ctx))
  167. }
  168. if h.senderSettings.Via != nil {
  169. outbound := session.OutboundFromContext(ctx)
  170. if outbound == nil {
  171. outbound = new(session.Outbound)
  172. ctx = session.ContextWithOutbound(ctx, outbound)
  173. }
  174. outbound.Gateway = h.senderSettings.Via.AsAddress()
  175. }
  176. }
  177. conn, err := internet.Dial(ctx, dest, h.streamSettings)
  178. return h.getStatCouterConnection(conn), err
  179. }
  180. func (h *Handler) getStatCouterConnection(conn stat.Connection) stat.Connection {
  181. if h.uplinkCounter != nil || h.downlinkCounter != nil {
  182. return &stat.CounterConnection{
  183. Connection: conn,
  184. ReadCounter: h.downlinkCounter,
  185. WriteCounter: h.uplinkCounter,
  186. }
  187. }
  188. return conn
  189. }
  190. // GetOutbound implements proxy.GetOutbound.
  191. func (h *Handler) GetOutbound() proxy.Outbound {
  192. return h.proxy
  193. }
  194. // Start implements common.Runnable.
  195. func (h *Handler) Start() error {
  196. return nil
  197. }
  198. // Close implements common.Closable.
  199. func (h *Handler) Close() error {
  200. common.Close(h.mux)
  201. return nil
  202. }