default.go 13 KB

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