default.go 13 KB

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