default.go 13 KB

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