1
0

default.go 13 KB

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