default.go 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  1. package dispatcher
  2. //go:generate go run github.com/xtls/xray-core/common/errors/errorgen
  3. import (
  4. "context"
  5. "strings"
  6. "sync"
  7. "time"
  8. "github.com/xtls/xray-core/common"
  9. "github.com/xtls/xray-core/common/buf"
  10. "github.com/xtls/xray-core/common/log"
  11. "github.com/xtls/xray-core/common/net"
  12. "github.com/xtls/xray-core/common/protocol"
  13. "github.com/xtls/xray-core/common/session"
  14. "github.com/xtls/xray-core/core"
  15. "github.com/xtls/xray-core/features/dns"
  16. "github.com/xtls/xray-core/features/outbound"
  17. "github.com/xtls/xray-core/features/policy"
  18. "github.com/xtls/xray-core/features/routing"
  19. routing_session "github.com/xtls/xray-core/features/routing/session"
  20. "github.com/xtls/xray-core/features/stats"
  21. "github.com/xtls/xray-core/transport"
  22. "github.com/xtls/xray-core/transport/pipe"
  23. )
  24. var errSniffingTimeout = newError("timeout on sniffing")
  25. type cachedReader struct {
  26. sync.Mutex
  27. reader *pipe.Reader
  28. cache buf.MultiBuffer
  29. }
  30. func (r *cachedReader) Cache(b *buf.Buffer) {
  31. mb, _ := r.reader.ReadMultiBufferTimeout(time.Millisecond * 100)
  32. r.Lock()
  33. if !mb.IsEmpty() {
  34. r.cache, _ = buf.MergeMulti(r.cache, mb)
  35. }
  36. b.Clear()
  37. rawBytes := b.Extend(buf.Size)
  38. n := r.cache.Copy(rawBytes)
  39. b.Resize(0, int32(n))
  40. r.Unlock()
  41. }
  42. func (r *cachedReader) readInternal() buf.MultiBuffer {
  43. r.Lock()
  44. defer r.Unlock()
  45. if r.cache != nil && !r.cache.IsEmpty() {
  46. mb := r.cache
  47. r.cache = nil
  48. return mb
  49. }
  50. return nil
  51. }
  52. func (r *cachedReader) ReadMultiBuffer() (buf.MultiBuffer, error) {
  53. mb := r.readInternal()
  54. if mb != nil {
  55. return mb, nil
  56. }
  57. return r.reader.ReadMultiBuffer()
  58. }
  59. func (r *cachedReader) ReadMultiBufferTimeout(timeout time.Duration) (buf.MultiBuffer, error) {
  60. mb := r.readInternal()
  61. if mb != nil {
  62. return mb, nil
  63. }
  64. return r.reader.ReadMultiBufferTimeout(timeout)
  65. }
  66. func (r *cachedReader) Interrupt() {
  67. r.Lock()
  68. if r.cache != nil {
  69. r.cache = buf.ReleaseMulti(r.cache)
  70. }
  71. r.Unlock()
  72. r.reader.Interrupt()
  73. }
  74. // DefaultDispatcher is a default implementation of Dispatcher.
  75. type DefaultDispatcher struct {
  76. ohm outbound.Manager
  77. router routing.Router
  78. policy policy.Manager
  79. stats stats.Manager
  80. }
  81. func init() {
  82. common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
  83. d := new(DefaultDispatcher)
  84. if err := core.RequireFeatures(ctx, func(om outbound.Manager, router routing.Router, pm policy.Manager, sm stats.Manager) error {
  85. return d.Init(config.(*Config), om, router, pm, sm)
  86. }); err != nil {
  87. return nil, err
  88. }
  89. return d, nil
  90. }))
  91. }
  92. // Init initializes DefaultDispatcher.
  93. func (d *DefaultDispatcher) Init(config *Config, om outbound.Manager, router routing.Router, pm policy.Manager, sm stats.Manager) error {
  94. d.ohm = om
  95. d.router = router
  96. d.policy = pm
  97. d.stats = sm
  98. return nil
  99. }
  100. // Type implements common.HasType.
  101. func (*DefaultDispatcher) Type() interface{} {
  102. return routing.DispatcherType()
  103. }
  104. // Start implements common.Runnable.
  105. func (*DefaultDispatcher) Start() error {
  106. return nil
  107. }
  108. // Close implements common.Closable.
  109. func (*DefaultDispatcher) Close() error { return nil }
  110. func (d *DefaultDispatcher) getLink(ctx context.Context) (*transport.Link, *transport.Link) {
  111. opt := pipe.OptionsFromContext(ctx)
  112. uplinkReader, uplinkWriter := pipe.New(opt...)
  113. downlinkReader, downlinkWriter := pipe.New(opt...)
  114. inboundLink := &transport.Link{
  115. Reader: downlinkReader,
  116. Writer: uplinkWriter,
  117. }
  118. outboundLink := &transport.Link{
  119. Reader: uplinkReader,
  120. Writer: downlinkWriter,
  121. }
  122. sessionInbound := session.InboundFromContext(ctx)
  123. var user *protocol.MemoryUser
  124. if sessionInbound != nil {
  125. user = sessionInbound.User
  126. }
  127. if user != nil && len(user.Email) > 0 {
  128. p := d.policy.ForLevel(user.Level)
  129. if p.Stats.UserUplink {
  130. name := "user>>>" + user.Email + ">>>traffic>>>uplink"
  131. if c, _ := stats.GetOrRegisterCounter(d.stats, name); c != nil {
  132. inboundLink.Writer = &SizeStatWriter{
  133. Counter: c,
  134. Writer: inboundLink.Writer,
  135. }
  136. }
  137. }
  138. if p.Stats.UserDownlink {
  139. name := "user>>>" + user.Email + ">>>traffic>>>downlink"
  140. if c, _ := stats.GetOrRegisterCounter(d.stats, name); c != nil {
  141. outboundLink.Writer = &SizeStatWriter{
  142. Counter: c,
  143. Writer: outboundLink.Writer,
  144. }
  145. }
  146. }
  147. }
  148. return inboundLink, outboundLink
  149. }
  150. func shouldOverride(ctx context.Context, result SniffResult, request session.SniffingRequest, destination net.Destination) bool {
  151. domain := result.Domain()
  152. for _, d := range request.ExcludeForDomain {
  153. if strings.ToLower(domain) == d {
  154. return false
  155. }
  156. }
  157. var fakeDNSEngine dns.FakeDNSEngine
  158. core.RequireFeatures(ctx, func(fdns dns.FakeDNSEngine) {
  159. fakeDNSEngine = fdns
  160. })
  161. protocolString := result.Protocol()
  162. if resComp, ok := result.(SnifferResultComposite); ok {
  163. protocolString = resComp.ProtocolForDomainResult()
  164. }
  165. for _, p := range request.OverrideDestinationForProtocol {
  166. if strings.HasPrefix(protocolString, p) {
  167. return true
  168. }
  169. if fkr0, ok := fakeDNSEngine.(dns.FakeDNSEngineRev0); ok && protocolString != "bittorrent" && p == "fakedns" &&
  170. destination.Address.Family().IsIP() && fkr0.IsIPInIPPool(destination.Address) {
  171. newError("Using sniffer ", protocolString, " since the fake DNS missed").WriteToLog(session.ExportIDToError(ctx))
  172. return true
  173. }
  174. if resultSubset, ok := result.(SnifferIsProtoSubsetOf); ok {
  175. if resultSubset.IsProtoSubsetOf(p) {
  176. return true
  177. }
  178. }
  179. }
  180. return false
  181. }
  182. // Dispatch implements routing.Dispatcher.
  183. func (d *DefaultDispatcher) Dispatch(ctx context.Context, destination net.Destination) (*transport.Link, error) {
  184. if !destination.IsValid() {
  185. panic("Dispatcher: Invalid destination.")
  186. }
  187. ob := &session.Outbound{
  188. Target: destination,
  189. }
  190. ctx = session.ContextWithOutbound(ctx, ob)
  191. inbound, outbound := d.getLink(ctx)
  192. content := session.ContentFromContext(ctx)
  193. if content == nil {
  194. content = new(session.Content)
  195. ctx = session.ContextWithContent(ctx, content)
  196. }
  197. sniffingRequest := content.SniffingRequest
  198. switch {
  199. case !sniffingRequest.Enabled:
  200. go d.routedDispatch(ctx, outbound, destination)
  201. case destination.Network != net.Network_TCP:
  202. // Only metadata sniff will be used for non tcp connection
  203. result, err := sniffer(ctx, nil, true)
  204. if err == nil {
  205. content.Protocol = result.Protocol()
  206. if shouldOverride(ctx, result, sniffingRequest, destination) {
  207. domain := result.Domain()
  208. newError("sniffed domain: ", domain).WriteToLog(session.ExportIDToError(ctx))
  209. destination.Address = net.ParseAddress(domain)
  210. ob.Target = destination
  211. }
  212. }
  213. go d.routedDispatch(ctx, outbound, destination)
  214. default:
  215. go func() {
  216. cReader := &cachedReader{
  217. reader: outbound.Reader.(*pipe.Reader),
  218. }
  219. outbound.Reader = cReader
  220. result, err := sniffer(ctx, cReader, sniffingRequest.MetadataOnly)
  221. if err == nil {
  222. content.Protocol = result.Protocol()
  223. }
  224. if err == nil && shouldOverride(ctx, result, sniffingRequest, destination) {
  225. domain := result.Domain()
  226. newError("sniffed domain: ", domain).WriteToLog(session.ExportIDToError(ctx))
  227. destination.Address = net.ParseAddress(domain)
  228. ob.Target = destination
  229. }
  230. d.routedDispatch(ctx, outbound, destination)
  231. }()
  232. }
  233. return inbound, nil
  234. }
  235. func sniffer(ctx context.Context, cReader *cachedReader, metadataOnly bool) (SniffResult, error) {
  236. payload := buf.New()
  237. defer payload.Release()
  238. sniffer := NewSniffer(ctx)
  239. metaresult, metadataErr := sniffer.SniffMetadata(ctx)
  240. if metadataOnly {
  241. return metaresult, metadataErr
  242. }
  243. contentResult, contentErr := func() (SniffResult, error) {
  244. totalAttempt := 0
  245. for {
  246. select {
  247. case <-ctx.Done():
  248. return nil, ctx.Err()
  249. default:
  250. totalAttempt++
  251. if totalAttempt > 2 {
  252. return nil, errSniffingTimeout
  253. }
  254. cReader.Cache(payload)
  255. if !payload.IsEmpty() {
  256. result, err := sniffer.Sniff(ctx, payload.Bytes())
  257. if err != common.ErrNoClue {
  258. return result, err
  259. }
  260. }
  261. if payload.IsFull() {
  262. return nil, errUnknownContent
  263. }
  264. }
  265. }
  266. }()
  267. if contentErr != nil && metadataErr == nil {
  268. return metaresult, nil
  269. }
  270. if contentErr == nil && metadataErr == nil {
  271. return CompositeResult(metaresult, contentResult), nil
  272. }
  273. return contentResult, contentErr
  274. }
  275. func (d *DefaultDispatcher) routedDispatch(ctx context.Context, link *transport.Link, destination net.Destination) {
  276. var handler outbound.Handler
  277. if d.router != nil {
  278. if route, err := d.router.PickRoute(routing_session.AsRoutingContext(ctx)); err == nil {
  279. tag := route.GetOutboundTag()
  280. if h := d.ohm.GetHandler(tag); h != nil {
  281. newError("taking detour [", tag, "] for [", destination, "]").WriteToLog(session.ExportIDToError(ctx))
  282. handler = h
  283. } else {
  284. newError("non existing outTag: ", tag).AtWarning().WriteToLog(session.ExportIDToError(ctx))
  285. }
  286. } else {
  287. newError("default route for ", destination).WriteToLog(session.ExportIDToError(ctx))
  288. }
  289. }
  290. if handler == nil {
  291. handler = d.ohm.GetDefaultHandler()
  292. }
  293. if handler == nil {
  294. newError("default outbound handler not exist").WriteToLog(session.ExportIDToError(ctx))
  295. common.Close(link.Writer)
  296. common.Interrupt(link.Reader)
  297. return
  298. }
  299. if accessMessage := log.AccessMessageFromContext(ctx); accessMessage != nil {
  300. if tag := handler.Tag(); tag != "" {
  301. accessMessage.Detour = tag
  302. }
  303. log.Record(accessMessage)
  304. }
  305. handler.Dispatch(ctx, link)
  306. }