default.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478
  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. sessionInbounds := session.InboundFromContext(ctx)
  162. userIP := sessionInbounds.Source.Address.String()
  163. om.AddIP(userIP)
  164. // log Online user with ips
  165. // errors.LogDebug(ctx, "user>>>" + user.Email + ">>>online", om.Count(), om.List())
  166. }
  167. }
  168. }
  169. return inboundLink, outboundLink
  170. }
  171. func (d *DefaultDispatcher) shouldOverride(ctx context.Context, result SniffResult, request session.SniffingRequest, destination net.Destination) bool {
  172. domain := result.Domain()
  173. if domain == "" {
  174. return false
  175. }
  176. for _, d := range request.ExcludeForDomain {
  177. if strings.HasPrefix(d, "regexp:") {
  178. pattern := d[7:]
  179. re, err := regexp.Compile(pattern)
  180. if err != nil {
  181. errors.LogInfo(ctx, "Unable to compile regex")
  182. continue
  183. }
  184. if re.MatchString(domain) {
  185. return false
  186. }
  187. } else {
  188. if strings.ToLower(domain) == d {
  189. return false
  190. }
  191. }
  192. }
  193. protocolString := result.Protocol()
  194. if resComp, ok := result.(SnifferResultComposite); ok {
  195. protocolString = resComp.ProtocolForDomainResult()
  196. }
  197. for _, p := range request.OverrideDestinationForProtocol {
  198. if strings.HasPrefix(protocolString, p) || strings.HasPrefix(p, protocolString) {
  199. return true
  200. }
  201. if fkr0, ok := d.fdns.(dns.FakeDNSEngineRev0); ok && protocolString != "bittorrent" && p == "fakedns" &&
  202. fkr0.IsIPInIPPool(destination.Address) {
  203. errors.LogInfo(ctx, "Using sniffer ", protocolString, " since the fake DNS missed")
  204. return true
  205. }
  206. if resultSubset, ok := result.(SnifferIsProtoSubsetOf); ok {
  207. if resultSubset.IsProtoSubsetOf(p) {
  208. return true
  209. }
  210. }
  211. }
  212. return false
  213. }
  214. // Dispatch implements routing.Dispatcher.
  215. func (d *DefaultDispatcher) Dispatch(ctx context.Context, destination net.Destination) (*transport.Link, error) {
  216. if !destination.IsValid() {
  217. panic("Dispatcher: Invalid destination.")
  218. }
  219. outbounds := session.OutboundsFromContext(ctx)
  220. if len(outbounds) == 0 {
  221. outbounds = []*session.Outbound{{}}
  222. ctx = session.ContextWithOutbounds(ctx, outbounds)
  223. }
  224. ob := outbounds[len(outbounds)-1]
  225. ob.OriginalTarget = destination
  226. ob.Target = destination
  227. content := session.ContentFromContext(ctx)
  228. if content == nil {
  229. content = new(session.Content)
  230. ctx = session.ContextWithContent(ctx, content)
  231. }
  232. sniffingRequest := content.SniffingRequest
  233. inbound, outbound := d.getLink(ctx)
  234. if !sniffingRequest.Enabled {
  235. go d.routedDispatch(ctx, outbound, destination)
  236. } else {
  237. go func() {
  238. cReader := &cachedReader{
  239. reader: outbound.Reader.(*pipe.Reader),
  240. }
  241. outbound.Reader = cReader
  242. result, err := sniffer(ctx, cReader, sniffingRequest.MetadataOnly, destination.Network)
  243. if err == nil {
  244. content.Protocol = result.Protocol()
  245. }
  246. if err == nil && d.shouldOverride(ctx, result, sniffingRequest, destination) {
  247. domain := result.Domain()
  248. errors.LogInfo(ctx, "sniffed domain: ", domain)
  249. destination.Address = net.ParseAddress(domain)
  250. protocol := result.Protocol()
  251. if resComp, ok := result.(SnifferResultComposite); ok {
  252. protocol = resComp.ProtocolForDomainResult()
  253. }
  254. isFakeIP := false
  255. if fkr0, ok := d.fdns.(dns.FakeDNSEngineRev0); ok && fkr0.IsIPInIPPool(ob.Target.Address) {
  256. isFakeIP = true
  257. }
  258. if sniffingRequest.RouteOnly && protocol != "fakedns" && protocol != "fakedns+others" && !isFakeIP {
  259. ob.RouteTarget = destination
  260. } else {
  261. ob.Target = destination
  262. }
  263. }
  264. d.routedDispatch(ctx, outbound, destination)
  265. }()
  266. }
  267. return inbound, nil
  268. }
  269. // DispatchLink implements routing.Dispatcher.
  270. func (d *DefaultDispatcher) DispatchLink(ctx context.Context, destination net.Destination, outbound *transport.Link) error {
  271. if !destination.IsValid() {
  272. return errors.New("Dispatcher: Invalid destination.")
  273. }
  274. outbounds := session.OutboundsFromContext(ctx)
  275. if len(outbounds) == 0 {
  276. outbounds = []*session.Outbound{{}}
  277. ctx = session.ContextWithOutbounds(ctx, outbounds)
  278. }
  279. ob := outbounds[len(outbounds)-1]
  280. ob.OriginalTarget = destination
  281. ob.Target = destination
  282. content := session.ContentFromContext(ctx)
  283. if content == nil {
  284. content = new(session.Content)
  285. ctx = session.ContextWithContent(ctx, content)
  286. }
  287. sniffingRequest := content.SniffingRequest
  288. if !sniffingRequest.Enabled {
  289. d.routedDispatch(ctx, outbound, destination)
  290. } else {
  291. cReader := &cachedReader{
  292. reader: outbound.Reader.(buf.TimeoutReader),
  293. }
  294. outbound.Reader = cReader
  295. result, err := sniffer(ctx, cReader, sniffingRequest.MetadataOnly, destination.Network)
  296. if err == nil {
  297. content.Protocol = result.Protocol()
  298. }
  299. if err == nil && d.shouldOverride(ctx, result, sniffingRequest, destination) {
  300. domain := result.Domain()
  301. errors.LogInfo(ctx, "sniffed domain: ", domain)
  302. destination.Address = net.ParseAddress(domain)
  303. protocol := result.Protocol()
  304. if resComp, ok := result.(SnifferResultComposite); ok {
  305. protocol = resComp.ProtocolForDomainResult()
  306. }
  307. isFakeIP := false
  308. if fkr0, ok := d.fdns.(dns.FakeDNSEngineRev0); ok && fkr0.IsIPInIPPool(ob.Target.Address) {
  309. isFakeIP = true
  310. }
  311. if sniffingRequest.RouteOnly && protocol != "fakedns" && protocol != "fakedns+others" && !isFakeIP {
  312. ob.RouteTarget = destination
  313. } else {
  314. ob.Target = destination
  315. }
  316. }
  317. d.routedDispatch(ctx, outbound, destination)
  318. }
  319. return nil
  320. }
  321. func sniffer(ctx context.Context, cReader *cachedReader, metadataOnly bool, network net.Network) (SniffResult, error) {
  322. payload := buf.NewWithSize(32767)
  323. defer payload.Release()
  324. sniffer := NewSniffer(ctx)
  325. metaresult, metadataErr := sniffer.SniffMetadata(ctx)
  326. if metadataOnly {
  327. return metaresult, metadataErr
  328. }
  329. contentResult, contentErr := func() (SniffResult, error) {
  330. cacheDeadline := 200 * time.Millisecond
  331. totalAttempt := 0
  332. for {
  333. select {
  334. case <-ctx.Done():
  335. return nil, ctx.Err()
  336. default:
  337. cachingStartingTimeStamp := time.Now()
  338. err := cReader.Cache(payload, cacheDeadline)
  339. if err != nil {
  340. return nil, err
  341. }
  342. cachingTimeElapsed := time.Since(cachingStartingTimeStamp)
  343. cacheDeadline -= cachingTimeElapsed
  344. if !payload.IsEmpty() {
  345. result, err := sniffer.Sniff(ctx, payload.Bytes(), network)
  346. switch err {
  347. case common.ErrNoClue: // No Clue: protocol not matches, and sniffer cannot determine whether there will be a match or not
  348. totalAttempt++
  349. case protocol.ErrProtoNeedMoreData: // Protocol Need More Data: protocol matches, but need more data to complete sniffing
  350. // in this case, do not add totalAttempt(allow to read until timeout)
  351. default:
  352. return result, err
  353. }
  354. } else {
  355. totalAttempt++
  356. }
  357. if totalAttempt >= 2 || cacheDeadline <= 0 {
  358. return nil, errSniffingTimeout
  359. }
  360. }
  361. }
  362. }()
  363. if contentErr != nil && metadataErr == nil {
  364. return metaresult, nil
  365. }
  366. if contentErr == nil && metadataErr == nil {
  367. return CompositeResult(metaresult, contentResult), nil
  368. }
  369. return contentResult, contentErr
  370. }
  371. func (d *DefaultDispatcher) routedDispatch(ctx context.Context, link *transport.Link, destination net.Destination) {
  372. outbounds := session.OutboundsFromContext(ctx)
  373. ob := outbounds[len(outbounds)-1]
  374. var handler outbound.Handler
  375. routingLink := routing_session.AsRoutingContext(ctx)
  376. inTag := routingLink.GetInboundTag()
  377. isPickRoute := 0
  378. if forcedOutboundTag := session.GetForcedOutboundTagFromContext(ctx); forcedOutboundTag != "" {
  379. ctx = session.SetForcedOutboundTagToContext(ctx, "")
  380. if h := d.ohm.GetHandler(forcedOutboundTag); h != nil {
  381. isPickRoute = 1
  382. errors.LogInfo(ctx, "taking platform initialized detour [", forcedOutboundTag, "] for [", destination, "]")
  383. handler = h
  384. } else {
  385. errors.LogError(ctx, "non existing tag for platform initialized detour: ", forcedOutboundTag)
  386. common.Close(link.Writer)
  387. common.Interrupt(link.Reader)
  388. return
  389. }
  390. } else if d.router != nil {
  391. if route, err := d.router.PickRoute(routingLink); err == nil {
  392. outTag := route.GetOutboundTag()
  393. if h := d.ohm.GetHandler(outTag); h != nil {
  394. isPickRoute = 2
  395. if route.GetRuleTag() == "" {
  396. errors.LogInfo(ctx, "taking detour [", outTag, "] for [", destination, "]")
  397. } else {
  398. errors.LogInfo(ctx, "Hit route rule: [", route.GetRuleTag(), "] so taking detour [", outTag, "] for [", destination, "]")
  399. }
  400. handler = h
  401. } else {
  402. errors.LogWarning(ctx, "non existing outTag: ", outTag)
  403. }
  404. } else {
  405. errors.LogInfo(ctx, "default route for ", destination)
  406. }
  407. }
  408. if handler == nil {
  409. handler = d.ohm.GetDefaultHandler()
  410. }
  411. if handler == nil {
  412. errors.LogInfo(ctx, "default outbound handler not exist")
  413. common.Close(link.Writer)
  414. common.Interrupt(link.Reader)
  415. return
  416. }
  417. ob.Tag = handler.Tag()
  418. if accessMessage := log.AccessMessageFromContext(ctx); accessMessage != nil {
  419. if tag := handler.Tag(); tag != "" {
  420. if inTag == "" {
  421. accessMessage.Detour = tag
  422. } else if isPickRoute == 1 {
  423. accessMessage.Detour = inTag + " ==> " + tag
  424. } else if isPickRoute == 2 {
  425. accessMessage.Detour = inTag + " -> " + tag
  426. } else {
  427. accessMessage.Detour = inTag + " >> " + tag
  428. }
  429. }
  430. log.Record(accessMessage)
  431. }
  432. handler.Dispatch(ctx, link)
  433. }