default.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519
  1. package dispatcher
  2. import (
  3. "context"
  4. "regexp"
  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/errors"
  11. "github.com/xtls/xray-core/common/log"
  12. "github.com/xtls/xray-core/common/net"
  13. "github.com/xtls/xray-core/common/protocol"
  14. "github.com/xtls/xray-core/common/session"
  15. "github.com/xtls/xray-core/core"
  16. "github.com/xtls/xray-core/features/dns"
  17. "github.com/xtls/xray-core/features/outbound"
  18. "github.com/xtls/xray-core/features/policy"
  19. "github.com/xtls/xray-core/features/routing"
  20. routing_session "github.com/xtls/xray-core/features/routing/session"
  21. "github.com/xtls/xray-core/features/stats"
  22. "github.com/xtls/xray-core/transport"
  23. "github.com/xtls/xray-core/transport/pipe"
  24. )
  25. var errSniffingTimeout = errors.New("timeout on sniffing")
  26. type cachedReader struct {
  27. sync.Mutex
  28. reader buf.TimeoutReader // *pipe.Reader or *buf.TimeoutWrapperReader
  29. cache buf.MultiBuffer
  30. }
  31. func (r *cachedReader) Cache(b *buf.Buffer, deadline time.Duration) error {
  32. mb, err := r.reader.ReadMultiBufferTimeout(deadline)
  33. if err != nil {
  34. return err
  35. }
  36. r.Lock()
  37. if !mb.IsEmpty() {
  38. r.cache, _ = buf.MergeMulti(r.cache, mb)
  39. }
  40. b.Clear()
  41. rawBytes := b.Extend(min(r.cache.Len(), b.Cap()))
  42. n := r.cache.Copy(rawBytes)
  43. b.Resize(0, int32(n))
  44. r.Unlock()
  45. return nil
  46. }
  47. func (r *cachedReader) readInternal() buf.MultiBuffer {
  48. r.Lock()
  49. defer r.Unlock()
  50. if r.cache != nil && !r.cache.IsEmpty() {
  51. mb := r.cache
  52. r.cache = nil
  53. return mb
  54. }
  55. return nil
  56. }
  57. func (r *cachedReader) ReadMultiBuffer() (buf.MultiBuffer, error) {
  58. mb := r.readInternal()
  59. if mb != nil {
  60. return mb, nil
  61. }
  62. return r.reader.ReadMultiBuffer()
  63. }
  64. func (r *cachedReader) ReadMultiBufferTimeout(timeout time.Duration) (buf.MultiBuffer, error) {
  65. mb := r.readInternal()
  66. if mb != nil {
  67. return mb, nil
  68. }
  69. return r.reader.ReadMultiBufferTimeout(timeout)
  70. }
  71. func (r *cachedReader) Interrupt() {
  72. r.Lock()
  73. if r.cache != nil {
  74. r.cache = buf.ReleaseMulti(r.cache)
  75. }
  76. r.Unlock()
  77. if p, ok := r.reader.(*pipe.Reader); ok {
  78. p.Interrupt()
  79. }
  80. }
  81. // DefaultDispatcher is a default implementation of Dispatcher.
  82. type DefaultDispatcher struct {
  83. ohm outbound.Manager
  84. router routing.Router
  85. policy policy.Manager
  86. stats stats.Manager
  87. fdns dns.FakeDNSEngine
  88. }
  89. func init() {
  90. common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
  91. d := new(DefaultDispatcher)
  92. if err := core.RequireFeatures(ctx, func(om outbound.Manager, router routing.Router, pm policy.Manager, sm stats.Manager, dc dns.Client) error {
  93. core.OptionalFeatures(ctx, func(fdns dns.FakeDNSEngine) {
  94. d.fdns = fdns
  95. })
  96. return d.Init(config.(*Config), om, router, pm, sm)
  97. }); err != nil {
  98. return nil, err
  99. }
  100. return d, nil
  101. }))
  102. }
  103. // Init initializes DefaultDispatcher.
  104. func (d *DefaultDispatcher) Init(config *Config, om outbound.Manager, router routing.Router, pm policy.Manager, sm stats.Manager) error {
  105. d.ohm = om
  106. d.router = router
  107. d.policy = pm
  108. d.stats = sm
  109. return nil
  110. }
  111. // Type implements common.HasType.
  112. func (*DefaultDispatcher) Type() interface{} {
  113. return routing.DispatcherType()
  114. }
  115. // Start implements common.Runnable.
  116. func (*DefaultDispatcher) Start() error {
  117. return nil
  118. }
  119. // Close implements common.Closable.
  120. func (*DefaultDispatcher) Close() error { return nil }
  121. func (d *DefaultDispatcher) getLink(ctx context.Context) (*transport.Link, *transport.Link) {
  122. opt := pipe.OptionsFromContext(ctx)
  123. uplinkReader, uplinkWriter := pipe.New(opt...)
  124. downlinkReader, downlinkWriter := pipe.New(opt...)
  125. inboundLink := &transport.Link{
  126. Reader: downlinkReader,
  127. Writer: uplinkWriter,
  128. }
  129. outboundLink := &transport.Link{
  130. Reader: uplinkReader,
  131. Writer: downlinkWriter,
  132. }
  133. sessionInbound := session.InboundFromContext(ctx)
  134. var user *protocol.MemoryUser
  135. if sessionInbound != nil {
  136. user = sessionInbound.User
  137. }
  138. if user != nil && len(user.Email) > 0 {
  139. p := d.policy.ForLevel(user.Level)
  140. if p.Stats.UserUplink {
  141. name := "user>>>" + user.Email + ">>>traffic>>>uplink"
  142. if c, _ := stats.GetOrRegisterCounter(d.stats, name); c != nil {
  143. inboundLink.Writer = &SizeStatWriter{
  144. Counter: c,
  145. Writer: inboundLink.Writer,
  146. }
  147. }
  148. }
  149. if p.Stats.UserDownlink {
  150. name := "user>>>" + user.Email + ">>>traffic>>>downlink"
  151. if c, _ := stats.GetOrRegisterCounter(d.stats, name); c != nil {
  152. outboundLink.Writer = &SizeStatWriter{
  153. Counter: c,
  154. Writer: outboundLink.Writer,
  155. }
  156. }
  157. }
  158. if p.Stats.UserOnline {
  159. name := "user>>>" + user.Email + ">>>online"
  160. if om, _ := stats.GetOrRegisterOnlineMap(d.stats, name); om != nil {
  161. userIP := sessionInbound.Source.Address.String()
  162. om.AddIP(userIP)
  163. context.AfterFunc(ctx, func() { om.RemoveIP(userIP) })
  164. }
  165. }
  166. }
  167. return inboundLink, outboundLink
  168. }
  169. func WrapLink(ctx context.Context, policyManager policy.Manager, statsManager stats.Manager, link *transport.Link) *transport.Link {
  170. sessionInbound := session.InboundFromContext(ctx)
  171. var user *protocol.MemoryUser
  172. if sessionInbound != nil {
  173. user = sessionInbound.User
  174. }
  175. link.Reader = &buf.TimeoutWrapperReader{Reader: link.Reader}
  176. if user != nil && len(user.Email) > 0 {
  177. p := policyManager.ForLevel(user.Level)
  178. if p.Stats.UserUplink {
  179. name := "user>>>" + user.Email + ">>>traffic>>>uplink"
  180. if c, _ := stats.GetOrRegisterCounter(statsManager, name); c != nil {
  181. link.Reader.(*buf.TimeoutWrapperReader).Counter = c
  182. }
  183. }
  184. if p.Stats.UserDownlink {
  185. name := "user>>>" + user.Email + ">>>traffic>>>downlink"
  186. if c, _ := stats.GetOrRegisterCounter(statsManager, name); c != nil {
  187. link.Writer = &SizeStatWriter{
  188. Counter: c,
  189. Writer: link.Writer,
  190. }
  191. }
  192. }
  193. if p.Stats.UserOnline {
  194. name := "user>>>" + user.Email + ">>>online"
  195. if om, _ := stats.GetOrRegisterOnlineMap(statsManager, name); om != nil {
  196. userIP := sessionInbound.Source.Address.String()
  197. om.AddIP(userIP)
  198. context.AfterFunc(ctx, func() { om.RemoveIP(userIP) })
  199. }
  200. }
  201. }
  202. return link
  203. }
  204. func (d *DefaultDispatcher) shouldOverride(ctx context.Context, result SniffResult, request session.SniffingRequest, destination net.Destination) bool {
  205. domain := result.Domain()
  206. if domain == "" {
  207. return false
  208. }
  209. for _, d := range request.ExcludeForDomain {
  210. if strings.HasPrefix(d, "regexp:") {
  211. pattern := d[7:]
  212. re, err := regexp.Compile(pattern)
  213. if err != nil {
  214. errors.LogInfo(ctx, "Unable to compile regex")
  215. continue
  216. }
  217. if re.MatchString(domain) {
  218. return false
  219. }
  220. } else {
  221. if strings.ToLower(domain) == d {
  222. return false
  223. }
  224. }
  225. }
  226. protocolString := result.Protocol()
  227. if resComp, ok := result.(SnifferResultComposite); ok {
  228. protocolString = resComp.ProtocolForDomainResult()
  229. }
  230. for _, p := range request.OverrideDestinationForProtocol {
  231. if strings.HasPrefix(protocolString, p) || strings.HasPrefix(p, protocolString) {
  232. return true
  233. }
  234. if fkr0, ok := d.fdns.(dns.FakeDNSEngineRev0); ok && protocolString != "bittorrent" && p == "fakedns" &&
  235. fkr0.IsIPInIPPool(destination.Address) {
  236. errors.LogInfo(ctx, "Using sniffer ", protocolString, " since the fake DNS missed")
  237. return true
  238. }
  239. if resultSubset, ok := result.(SnifferIsProtoSubsetOf); ok {
  240. if resultSubset.IsProtoSubsetOf(p) {
  241. return true
  242. }
  243. }
  244. }
  245. return false
  246. }
  247. // Dispatch implements routing.Dispatcher.
  248. func (d *DefaultDispatcher) Dispatch(ctx context.Context, destination net.Destination) (*transport.Link, error) {
  249. if !destination.IsValid() {
  250. panic("Dispatcher: Invalid destination.")
  251. }
  252. outbounds := session.OutboundsFromContext(ctx)
  253. if len(outbounds) == 0 {
  254. outbounds = []*session.Outbound{{}}
  255. ctx = session.ContextWithOutbounds(ctx, outbounds)
  256. }
  257. ob := outbounds[len(outbounds)-1]
  258. ob.OriginalTarget = destination
  259. ob.Target = destination
  260. content := session.ContentFromContext(ctx)
  261. if content == nil {
  262. content = new(session.Content)
  263. ctx = session.ContextWithContent(ctx, content)
  264. }
  265. sniffingRequest := content.SniffingRequest
  266. inbound, outbound := d.getLink(ctx)
  267. if !sniffingRequest.Enabled {
  268. go d.routedDispatch(ctx, outbound, destination)
  269. } else {
  270. go func() {
  271. cReader := &cachedReader{
  272. reader: outbound.Reader.(*pipe.Reader),
  273. }
  274. outbound.Reader = cReader
  275. result, err := sniffer(ctx, cReader, sniffingRequest.MetadataOnly, destination.Network)
  276. if err == nil {
  277. content.Protocol = result.Protocol()
  278. }
  279. if err == nil && d.shouldOverride(ctx, result, sniffingRequest, destination) {
  280. domain := result.Domain()
  281. errors.LogInfo(ctx, "sniffed domain: ", domain)
  282. destination.Address = net.ParseAddress(domain)
  283. protocol := result.Protocol()
  284. if resComp, ok := result.(SnifferResultComposite); ok {
  285. protocol = resComp.ProtocolForDomainResult()
  286. }
  287. isFakeIP := false
  288. if fkr0, ok := d.fdns.(dns.FakeDNSEngineRev0); ok && fkr0.IsIPInIPPool(ob.Target.Address) {
  289. isFakeIP = true
  290. }
  291. if sniffingRequest.RouteOnly && protocol != "fakedns" && protocol != "fakedns+others" && !isFakeIP {
  292. ob.RouteTarget = destination
  293. } else {
  294. ob.Target = destination
  295. }
  296. }
  297. d.routedDispatch(ctx, outbound, destination)
  298. }()
  299. }
  300. return inbound, nil
  301. }
  302. // DispatchLink implements routing.Dispatcher.
  303. func (d *DefaultDispatcher) DispatchLink(ctx context.Context, destination net.Destination, outbound *transport.Link) error {
  304. if !destination.IsValid() {
  305. return errors.New("Dispatcher: Invalid destination.")
  306. }
  307. outbounds := session.OutboundsFromContext(ctx)
  308. if len(outbounds) == 0 {
  309. outbounds = []*session.Outbound{{}}
  310. ctx = session.ContextWithOutbounds(ctx, outbounds)
  311. }
  312. ob := outbounds[len(outbounds)-1]
  313. ob.OriginalTarget = destination
  314. ob.Target = destination
  315. content := session.ContentFromContext(ctx)
  316. if content == nil {
  317. content = new(session.Content)
  318. ctx = session.ContextWithContent(ctx, content)
  319. }
  320. outbound = WrapLink(ctx, d.policy, d.stats, outbound)
  321. sniffingRequest := content.SniffingRequest
  322. if !sniffingRequest.Enabled {
  323. d.routedDispatch(ctx, outbound, destination)
  324. } else {
  325. cReader := &cachedReader{
  326. reader: outbound.Reader.(buf.TimeoutReader),
  327. }
  328. outbound.Reader = cReader
  329. result, err := sniffer(ctx, cReader, sniffingRequest.MetadataOnly, destination.Network)
  330. if err == nil {
  331. content.Protocol = result.Protocol()
  332. }
  333. if err == nil && d.shouldOverride(ctx, result, sniffingRequest, destination) {
  334. domain := result.Domain()
  335. errors.LogInfo(ctx, "sniffed domain: ", domain)
  336. destination.Address = net.ParseAddress(domain)
  337. protocol := result.Protocol()
  338. if resComp, ok := result.(SnifferResultComposite); ok {
  339. protocol = resComp.ProtocolForDomainResult()
  340. }
  341. isFakeIP := false
  342. if fkr0, ok := d.fdns.(dns.FakeDNSEngineRev0); ok && fkr0.IsIPInIPPool(ob.Target.Address) {
  343. isFakeIP = true
  344. }
  345. if sniffingRequest.RouteOnly && protocol != "fakedns" && protocol != "fakedns+others" && !isFakeIP {
  346. ob.RouteTarget = destination
  347. } else {
  348. ob.Target = destination
  349. }
  350. }
  351. d.routedDispatch(ctx, outbound, destination)
  352. }
  353. return nil
  354. }
  355. func sniffer(ctx context.Context, cReader *cachedReader, metadataOnly bool, network net.Network) (SniffResult, error) {
  356. payload := buf.NewWithSize(32767)
  357. defer payload.Release()
  358. sniffer := NewSniffer(ctx)
  359. metaresult, metadataErr := sniffer.SniffMetadata(ctx)
  360. if metadataOnly {
  361. return metaresult, metadataErr
  362. }
  363. contentResult, contentErr := func() (SniffResult, error) {
  364. cacheDeadline := 200 * time.Millisecond
  365. totalAttempt := 0
  366. for {
  367. select {
  368. case <-ctx.Done():
  369. return nil, ctx.Err()
  370. default:
  371. cachingStartingTimeStamp := time.Now()
  372. err := cReader.Cache(payload, cacheDeadline)
  373. if err != nil {
  374. return nil, err
  375. }
  376. cachingTimeElapsed := time.Since(cachingStartingTimeStamp)
  377. cacheDeadline -= cachingTimeElapsed
  378. if !payload.IsEmpty() {
  379. result, err := sniffer.Sniff(ctx, payload.Bytes(), network)
  380. switch err {
  381. case common.ErrNoClue: // No Clue: protocol not matches, and sniffer cannot determine whether there will be a match or not
  382. totalAttempt++
  383. case protocol.ErrProtoNeedMoreData: // Protocol Need More Data: protocol matches, but need more data to complete sniffing
  384. // in this case, do not add totalAttempt(allow to read until timeout)
  385. default:
  386. return result, err
  387. }
  388. } else {
  389. totalAttempt++
  390. }
  391. if totalAttempt >= 2 || cacheDeadline <= 0 {
  392. return nil, errSniffingTimeout
  393. }
  394. }
  395. }
  396. }()
  397. if contentErr != nil && metadataErr == nil {
  398. return metaresult, nil
  399. }
  400. if contentErr == nil && metadataErr == nil {
  401. return CompositeResult(metaresult, contentResult), nil
  402. }
  403. return contentResult, contentErr
  404. }
  405. func (d *DefaultDispatcher) routedDispatch(ctx context.Context, link *transport.Link, destination net.Destination) {
  406. outbounds := session.OutboundsFromContext(ctx)
  407. ob := outbounds[len(outbounds)-1]
  408. var handler outbound.Handler
  409. routingLink := routing_session.AsRoutingContext(ctx)
  410. inTag := routingLink.GetInboundTag()
  411. isPickRoute := 0
  412. if forcedOutboundTag := session.GetForcedOutboundTagFromContext(ctx); forcedOutboundTag != "" {
  413. ctx = session.SetForcedOutboundTagToContext(ctx, "")
  414. if h := d.ohm.GetHandler(forcedOutboundTag); h != nil {
  415. isPickRoute = 1
  416. errors.LogInfo(ctx, "taking platform initialized detour [", forcedOutboundTag, "] for [", destination, "]")
  417. handler = h
  418. } else {
  419. errors.LogError(ctx, "non existing tag for platform initialized detour: ", forcedOutboundTag)
  420. common.Close(link.Writer)
  421. common.Interrupt(link.Reader)
  422. return
  423. }
  424. } else if d.router != nil {
  425. if route, err := d.router.PickRoute(routingLink); err == nil {
  426. outTag := route.GetOutboundTag()
  427. if h := d.ohm.GetHandler(outTag); h != nil {
  428. isPickRoute = 2
  429. if route.GetRuleTag() == "" {
  430. errors.LogInfo(ctx, "taking detour [", outTag, "] for [", destination, "]")
  431. } else {
  432. errors.LogInfo(ctx, "Hit route rule: [", route.GetRuleTag(), "] so taking detour [", outTag, "] for [", destination, "]")
  433. }
  434. handler = h
  435. } else {
  436. errors.LogWarning(ctx, "non existing outTag: ", outTag)
  437. common.Close(link.Writer)
  438. common.Interrupt(link.Reader)
  439. return // DO NOT CHANGE: the traffic shouldn't be processed by default outbound if the specified outbound tag doesn't exist (yet), e.g., VLESS Reverse Proxy
  440. }
  441. } else {
  442. errors.LogInfo(ctx, "default route for ", destination)
  443. }
  444. }
  445. if handler == nil {
  446. handler = d.ohm.GetDefaultHandler()
  447. }
  448. if handler == nil {
  449. errors.LogInfo(ctx, "default outbound handler not exist")
  450. common.Close(link.Writer)
  451. common.Interrupt(link.Reader)
  452. return
  453. }
  454. ob.Tag = handler.Tag()
  455. if accessMessage := log.AccessMessageFromContext(ctx); accessMessage != nil {
  456. if tag := handler.Tag(); tag != "" {
  457. if inTag == "" {
  458. accessMessage.Detour = tag
  459. } else if isPickRoute == 1 {
  460. accessMessage.Detour = inTag + " ==> " + tag
  461. } else if isPickRoute == 2 {
  462. accessMessage.Detour = inTag + " -> " + tag
  463. } else {
  464. accessMessage.Detour = inTag + " >> " + tag
  465. }
  466. }
  467. log.Record(accessMessage)
  468. }
  469. handler.Dispatch(ctx, link)
  470. }