default.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  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 *pipe.Reader
  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. r.reader.Interrupt()
  78. }
  79. // DefaultDispatcher is a default implementation of Dispatcher.
  80. type DefaultDispatcher struct {
  81. ohm outbound.Manager
  82. router routing.Router
  83. policy policy.Manager
  84. stats stats.Manager
  85. fdns dns.FakeDNSEngine
  86. }
  87. func init() {
  88. common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
  89. d := new(DefaultDispatcher)
  90. if err := core.RequireFeatures(ctx, func(om outbound.Manager, router routing.Router, pm policy.Manager, sm stats.Manager, dc dns.Client) error {
  91. core.OptionalFeatures(ctx, func(fdns dns.FakeDNSEngine) {
  92. d.fdns = fdns
  93. })
  94. return d.Init(config.(*Config), om, router, pm, sm)
  95. }); err != nil {
  96. return nil, err
  97. }
  98. return d, nil
  99. }))
  100. }
  101. // Init initializes DefaultDispatcher.
  102. func (d *DefaultDispatcher) Init(config *Config, om outbound.Manager, router routing.Router, pm policy.Manager, sm stats.Manager) error {
  103. d.ohm = om
  104. d.router = router
  105. d.policy = pm
  106. d.stats = sm
  107. return nil
  108. }
  109. // Type implements common.HasType.
  110. func (*DefaultDispatcher) Type() interface{} {
  111. return routing.DispatcherType()
  112. }
  113. // Start implements common.Runnable.
  114. func (*DefaultDispatcher) Start() error {
  115. return nil
  116. }
  117. // Close implements common.Closable.
  118. func (*DefaultDispatcher) Close() error { return nil }
  119. func (d *DefaultDispatcher) getLink(ctx context.Context) (*transport.Link, *transport.Link) {
  120. opt := pipe.OptionsFromContext(ctx)
  121. uplinkReader, uplinkWriter := pipe.New(opt...)
  122. downlinkReader, downlinkWriter := pipe.New(opt...)
  123. inboundLink := &transport.Link{
  124. Reader: downlinkReader,
  125. Writer: uplinkWriter,
  126. }
  127. outboundLink := &transport.Link{
  128. Reader: uplinkReader,
  129. Writer: downlinkWriter,
  130. }
  131. sessionInbound := session.InboundFromContext(ctx)
  132. var user *protocol.MemoryUser
  133. if sessionInbound != nil {
  134. user = sessionInbound.User
  135. }
  136. if user != nil && len(user.Email) > 0 {
  137. p := d.policy.ForLevel(user.Level)
  138. if p.Stats.UserUplink {
  139. name := "user>>>" + user.Email + ">>>traffic>>>uplink"
  140. if c, _ := stats.GetOrRegisterCounter(d.stats, name); c != nil {
  141. inboundLink.Writer = &SizeStatWriter{
  142. Counter: c,
  143. Writer: inboundLink.Writer,
  144. }
  145. }
  146. }
  147. if p.Stats.UserDownlink {
  148. name := "user>>>" + user.Email + ">>>traffic>>>downlink"
  149. if c, _ := stats.GetOrRegisterCounter(d.stats, name); c != nil {
  150. outboundLink.Writer = &SizeStatWriter{
  151. Counter: c,
  152. Writer: outboundLink.Writer,
  153. }
  154. }
  155. }
  156. if p.Stats.UserOnline {
  157. name := "user>>>" + user.Email + ">>>online"
  158. if om, _ := stats.GetOrRegisterOnlineMap(d.stats, name); om != nil {
  159. sessionInbounds := session.InboundFromContext(ctx)
  160. userIP := sessionInbounds.Source.Address.String()
  161. om.AddIP(userIP)
  162. // log Online user with ips
  163. // errors.LogDebug(ctx, "user>>>" + user.Email + ">>>online", om.Count(), om.List())
  164. }
  165. }
  166. }
  167. return inboundLink, outboundLink
  168. }
  169. func (d *DefaultDispatcher) shouldOverride(ctx context.Context, result SniffResult, request session.SniffingRequest, destination net.Destination) bool {
  170. domain := result.Domain()
  171. if domain == "" {
  172. return false
  173. }
  174. for _, d := range request.ExcludeForDomain {
  175. if strings.HasPrefix(d, "regexp:") {
  176. pattern := d[7:]
  177. re, err := regexp.Compile(pattern)
  178. if err != nil {
  179. errors.LogInfo(ctx, "Unable to compile regex")
  180. continue
  181. }
  182. if re.MatchString(domain) {
  183. return false
  184. }
  185. } else {
  186. if strings.ToLower(domain) == d {
  187. return false
  188. }
  189. }
  190. }
  191. protocolString := result.Protocol()
  192. if resComp, ok := result.(SnifferResultComposite); ok {
  193. protocolString = resComp.ProtocolForDomainResult()
  194. }
  195. for _, p := range request.OverrideDestinationForProtocol {
  196. if strings.HasPrefix(protocolString, p) || strings.HasPrefix(p, protocolString) {
  197. return true
  198. }
  199. if fkr0, ok := d.fdns.(dns.FakeDNSEngineRev0); ok && protocolString != "bittorrent" && p == "fakedns" &&
  200. fkr0.IsIPInIPPool(destination.Address) {
  201. errors.LogInfo(ctx, "Using sniffer ", protocolString, " since the fake DNS missed")
  202. return true
  203. }
  204. if resultSubset, ok := result.(SnifferIsProtoSubsetOf); ok {
  205. if resultSubset.IsProtoSubsetOf(p) {
  206. return true
  207. }
  208. }
  209. }
  210. return false
  211. }
  212. // Dispatch implements routing.Dispatcher.
  213. func (d *DefaultDispatcher) Dispatch(ctx context.Context, destination net.Destination) (*transport.Link, error) {
  214. if !destination.IsValid() {
  215. panic("Dispatcher: Invalid destination.")
  216. }
  217. outbounds := session.OutboundsFromContext(ctx)
  218. if len(outbounds) == 0 {
  219. outbounds = []*session.Outbound{{}}
  220. ctx = session.ContextWithOutbounds(ctx, outbounds)
  221. }
  222. ob := outbounds[len(outbounds)-1]
  223. ob.OriginalTarget = destination
  224. ob.Target = destination
  225. content := session.ContentFromContext(ctx)
  226. if content == nil {
  227. content = new(session.Content)
  228. ctx = session.ContextWithContent(ctx, content)
  229. }
  230. sniffingRequest := content.SniffingRequest
  231. inbound, outbound := d.getLink(ctx)
  232. if !sniffingRequest.Enabled {
  233. go d.routedDispatch(ctx, outbound, destination)
  234. } else {
  235. go func() {
  236. cReader := &cachedReader{
  237. reader: outbound.Reader.(*pipe.Reader),
  238. }
  239. outbound.Reader = cReader
  240. result, err := sniffer(ctx, cReader, sniffingRequest.MetadataOnly, destination.Network)
  241. if err == nil {
  242. content.Protocol = result.Protocol()
  243. }
  244. if err == nil && d.shouldOverride(ctx, result, sniffingRequest, destination) {
  245. domain := result.Domain()
  246. errors.LogInfo(ctx, "sniffed domain: ", domain)
  247. destination.Address = net.ParseAddress(domain)
  248. protocol := result.Protocol()
  249. if resComp, ok := result.(SnifferResultComposite); ok {
  250. protocol = resComp.ProtocolForDomainResult()
  251. }
  252. isFakeIP := false
  253. if fkr0, ok := d.fdns.(dns.FakeDNSEngineRev0); ok && fkr0.IsIPInIPPool(ob.Target.Address) {
  254. isFakeIP = true
  255. }
  256. if sniffingRequest.RouteOnly && protocol != "fakedns" && protocol != "fakedns+others" && !isFakeIP {
  257. ob.RouteTarget = destination
  258. } else {
  259. ob.Target = destination
  260. }
  261. }
  262. d.routedDispatch(ctx, outbound, destination)
  263. }()
  264. }
  265. return inbound, nil
  266. }
  267. // DispatchLink implements routing.Dispatcher.
  268. func (d *DefaultDispatcher) DispatchLink(ctx context.Context, destination net.Destination, outbound *transport.Link) error {
  269. if !destination.IsValid() {
  270. return errors.New("Dispatcher: Invalid destination.")
  271. }
  272. outbounds := session.OutboundsFromContext(ctx)
  273. if len(outbounds) == 0 {
  274. outbounds = []*session.Outbound{{}}
  275. ctx = session.ContextWithOutbounds(ctx, outbounds)
  276. }
  277. ob := outbounds[len(outbounds)-1]
  278. ob.OriginalTarget = destination
  279. ob.Target = destination
  280. content := session.ContentFromContext(ctx)
  281. if content == nil {
  282. content = new(session.Content)
  283. ctx = session.ContextWithContent(ctx, content)
  284. }
  285. sniffingRequest := content.SniffingRequest
  286. if !sniffingRequest.Enabled {
  287. d.routedDispatch(ctx, outbound, destination)
  288. } else {
  289. cReader := &cachedReader{
  290. reader: outbound.Reader.(*pipe.Reader),
  291. }
  292. outbound.Reader = cReader
  293. result, err := sniffer(ctx, cReader, sniffingRequest.MetadataOnly, destination.Network)
  294. if err == nil {
  295. content.Protocol = result.Protocol()
  296. }
  297. if err == nil && d.shouldOverride(ctx, result, sniffingRequest, destination) {
  298. domain := result.Domain()
  299. errors.LogInfo(ctx, "sniffed domain: ", domain)
  300. destination.Address = net.ParseAddress(domain)
  301. protocol := result.Protocol()
  302. if resComp, ok := result.(SnifferResultComposite); ok {
  303. protocol = resComp.ProtocolForDomainResult()
  304. }
  305. isFakeIP := false
  306. if fkr0, ok := d.fdns.(dns.FakeDNSEngineRev0); ok && fkr0.IsIPInIPPool(ob.Target.Address) {
  307. isFakeIP = true
  308. }
  309. if sniffingRequest.RouteOnly && protocol != "fakedns" && protocol != "fakedns+others" && !isFakeIP {
  310. ob.RouteTarget = destination
  311. } else {
  312. ob.Target = destination
  313. }
  314. }
  315. d.routedDispatch(ctx, outbound, destination)
  316. }
  317. return nil
  318. }
  319. func sniffer(ctx context.Context, cReader *cachedReader, metadataOnly bool, network net.Network) (SniffResult, error) {
  320. payload := buf.NewWithSize(32767)
  321. defer payload.Release()
  322. sniffer := NewSniffer(ctx)
  323. metaresult, metadataErr := sniffer.SniffMetadata(ctx)
  324. if metadataOnly {
  325. return metaresult, metadataErr
  326. }
  327. contentResult, contentErr := func() (SniffResult, error) {
  328. cacheDeadline := 200 * time.Millisecond
  329. totalAttempt := 0
  330. for {
  331. select {
  332. case <-ctx.Done():
  333. return nil, ctx.Err()
  334. default:
  335. cachingStartingTimeStamp := time.Now()
  336. err := cReader.Cache(payload, cacheDeadline)
  337. if err != nil {
  338. return nil, err
  339. }
  340. cachingTimeElapsed := time.Since(cachingStartingTimeStamp)
  341. cacheDeadline -= cachingTimeElapsed
  342. if !payload.IsEmpty() {
  343. result, err := sniffer.Sniff(ctx, payload.Bytes(), network)
  344. switch err {
  345. case common.ErrNoClue: // No Clue: protocol not matches, and sniffer cannot determine whether there will be a match or not
  346. totalAttempt++
  347. case protocol.ErrProtoNeedMoreData: // Protocol Need More Data: protocol matches, but need more data to complete sniffing
  348. // in this case, do not add totalAttempt(allow to read until timeout)
  349. default:
  350. return result, err
  351. }
  352. } else {
  353. totalAttempt++
  354. }
  355. if totalAttempt >= 2 || cacheDeadline <= 0 {
  356. return nil, errSniffingTimeout
  357. }
  358. }
  359. }
  360. }()
  361. if contentErr != nil && metadataErr == nil {
  362. return metaresult, nil
  363. }
  364. if contentErr == nil && metadataErr == nil {
  365. return CompositeResult(metaresult, contentResult), nil
  366. }
  367. return contentResult, contentErr
  368. }
  369. func (d *DefaultDispatcher) routedDispatch(ctx context.Context, link *transport.Link, destination net.Destination) {
  370. outbounds := session.OutboundsFromContext(ctx)
  371. ob := outbounds[len(outbounds)-1]
  372. var handler outbound.Handler
  373. routingLink := routing_session.AsRoutingContext(ctx)
  374. inTag := routingLink.GetInboundTag()
  375. isPickRoute := 0
  376. if forcedOutboundTag := session.GetForcedOutboundTagFromContext(ctx); forcedOutboundTag != "" {
  377. ctx = session.SetForcedOutboundTagToContext(ctx, "")
  378. if h := d.ohm.GetHandler(forcedOutboundTag); h != nil {
  379. isPickRoute = 1
  380. errors.LogInfo(ctx, "taking platform initialized detour [", forcedOutboundTag, "] for [", destination, "]")
  381. handler = h
  382. } else {
  383. errors.LogError(ctx, "non existing tag for platform initialized detour: ", forcedOutboundTag)
  384. common.Close(link.Writer)
  385. common.Interrupt(link.Reader)
  386. return
  387. }
  388. } else if d.router != nil {
  389. if route, err := d.router.PickRoute(routingLink); err == nil {
  390. outTag := route.GetOutboundTag()
  391. if h := d.ohm.GetHandler(outTag); h != nil {
  392. isPickRoute = 2
  393. if route.GetRuleTag() == "" {
  394. errors.LogInfo(ctx, "taking detour [", outTag, "] for [", destination, "]")
  395. } else {
  396. errors.LogInfo(ctx, "Hit route rule: [", route.GetRuleTag(), "] so taking detour [", outTag, "] for [", destination, "]")
  397. }
  398. handler = h
  399. } else {
  400. errors.LogWarning(ctx, "non existing outTag: ", outTag)
  401. }
  402. } else {
  403. errors.LogInfo(ctx, "default route for ", destination)
  404. }
  405. }
  406. if handler == nil {
  407. handler = d.ohm.GetDefaultHandler()
  408. }
  409. if handler == nil {
  410. errors.LogInfo(ctx, "default outbound handler not exist")
  411. common.Close(link.Writer)
  412. common.Interrupt(link.Reader)
  413. return
  414. }
  415. ob.Tag = handler.Tag()
  416. if accessMessage := log.AccessMessageFromContext(ctx); accessMessage != nil {
  417. if tag := handler.Tag(); tag != "" {
  418. if inTag == "" {
  419. accessMessage.Detour = tag
  420. } else if isPickRoute == 1 {
  421. accessMessage.Detour = inTag + " ==> " + tag
  422. } else if isPickRoute == 2 {
  423. accessMessage.Detour = inTag + " -> " + tag
  424. } else {
  425. accessMessage.Detour = inTag + " >> " + tag
  426. }
  427. }
  428. log.Record(accessMessage)
  429. }
  430. handler.Dispatch(ctx, link)
  431. }