default.go 13 KB

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