default.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  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. destination.Address.Family().IsIP() && 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. ob := session.OutboundFromContext(ctx)
  193. if ob == nil {
  194. ob = &session.Outbound{}
  195. ctx = session.ContextWithOutbound(ctx, ob)
  196. }
  197. ob.OriginalTarget = destination
  198. ob.Target = destination
  199. content := session.ContentFromContext(ctx)
  200. if content == nil {
  201. content = new(session.Content)
  202. ctx = session.ContextWithContent(ctx, content)
  203. }
  204. sniffingRequest := content.SniffingRequest
  205. inbound, outbound := d.getLink(ctx)
  206. if !sniffingRequest.Enabled {
  207. go d.routedDispatch(ctx, outbound, destination)
  208. } else {
  209. go func() {
  210. cReader := &cachedReader{
  211. reader: outbound.Reader.(*pipe.Reader),
  212. }
  213. outbound.Reader = cReader
  214. result, err := sniffer(ctx, cReader, sniffingRequest.MetadataOnly, destination.Network)
  215. if err == nil {
  216. content.Protocol = result.Protocol()
  217. }
  218. if err == nil && d.shouldOverride(ctx, result, sniffingRequest, destination) {
  219. domain := result.Domain()
  220. newError("sniffed domain: ", domain).WriteToLog(session.ExportIDToError(ctx))
  221. destination.Address = net.ParseAddress(domain)
  222. protocol := result.Protocol()
  223. if resComp, ok := result.(SnifferResultComposite); ok {
  224. protocol = resComp.ProtocolForDomainResult()
  225. }
  226. isFakeIP := false
  227. if fkr0, ok := d.fdns.(dns.FakeDNSEngineRev0); ok && ob.Target.Address.Family().IsIP() && fkr0.IsIPInIPPool(ob.Target.Address) {
  228. isFakeIP = true
  229. }
  230. if sniffingRequest.RouteOnly && protocol != "fakedns" && protocol != "fakedns+others" && !isFakeIP {
  231. ob.RouteTarget = destination
  232. } else {
  233. ob.Target = destination
  234. }
  235. }
  236. d.routedDispatch(ctx, outbound, destination)
  237. }()
  238. }
  239. return inbound, nil
  240. }
  241. // DispatchLink implements routing.Dispatcher.
  242. func (d *DefaultDispatcher) DispatchLink(ctx context.Context, destination net.Destination, outbound *transport.Link) error {
  243. if !destination.IsValid() {
  244. return newError("Dispatcher: Invalid destination.")
  245. }
  246. ob := session.OutboundFromContext(ctx)
  247. if ob == nil {
  248. ob = &session.Outbound{}
  249. ctx = session.ContextWithOutbound(ctx, ob)
  250. }
  251. ob.OriginalTarget = destination
  252. ob.Target = destination
  253. content := session.ContentFromContext(ctx)
  254. if content == nil {
  255. content = new(session.Content)
  256. ctx = session.ContextWithContent(ctx, content)
  257. }
  258. sniffingRequest := content.SniffingRequest
  259. if !sniffingRequest.Enabled {
  260. d.routedDispatch(ctx, outbound, destination)
  261. } else {
  262. cReader := &cachedReader{
  263. reader: outbound.Reader.(*pipe.Reader),
  264. }
  265. outbound.Reader = cReader
  266. result, err := sniffer(ctx, cReader, sniffingRequest.MetadataOnly, destination.Network)
  267. if err == nil {
  268. content.Protocol = result.Protocol()
  269. }
  270. if err == nil && d.shouldOverride(ctx, result, sniffingRequest, destination) {
  271. domain := result.Domain()
  272. newError("sniffed domain: ", domain).WriteToLog(session.ExportIDToError(ctx))
  273. destination.Address = net.ParseAddress(domain)
  274. protocol := result.Protocol()
  275. if resComp, ok := result.(SnifferResultComposite); ok {
  276. protocol = resComp.ProtocolForDomainResult()
  277. }
  278. isFakeIP := false
  279. if fkr0, ok := d.fdns.(dns.FakeDNSEngineRev0); ok && ob.Target.Address.Family().IsIP() && fkr0.IsIPInIPPool(ob.Target.Address) {
  280. isFakeIP = true
  281. }
  282. if sniffingRequest.RouteOnly && protocol != "fakedns" && protocol != "fakedns+others" && !isFakeIP {
  283. ob.RouteTarget = destination
  284. } else {
  285. ob.Target = destination
  286. }
  287. }
  288. d.routedDispatch(ctx, outbound, destination)
  289. }
  290. return nil
  291. }
  292. func sniffer(ctx context.Context, cReader *cachedReader, metadataOnly bool, network net.Network) (SniffResult, error) {
  293. payload := buf.New()
  294. defer payload.Release()
  295. sniffer := NewSniffer(ctx)
  296. metaresult, metadataErr := sniffer.SniffMetadata(ctx)
  297. if metadataOnly {
  298. return metaresult, metadataErr
  299. }
  300. contentResult, contentErr := func() (SniffResult, error) {
  301. totalAttempt := 0
  302. for {
  303. select {
  304. case <-ctx.Done():
  305. return nil, ctx.Err()
  306. default:
  307. totalAttempt++
  308. if totalAttempt > 2 {
  309. return nil, errSniffingTimeout
  310. }
  311. cReader.Cache(payload)
  312. if !payload.IsEmpty() {
  313. result, err := sniffer.Sniff(ctx, payload.Bytes(), network)
  314. if err != common.ErrNoClue {
  315. return result, err
  316. }
  317. }
  318. if payload.IsFull() {
  319. return nil, errUnknownContent
  320. }
  321. }
  322. }
  323. }()
  324. if contentErr != nil && metadataErr == nil {
  325. return metaresult, nil
  326. }
  327. if contentErr == nil && metadataErr == nil {
  328. return CompositeResult(metaresult, contentResult), nil
  329. }
  330. return contentResult, contentErr
  331. }
  332. func (d *DefaultDispatcher) routedDispatch(ctx context.Context, link *transport.Link, destination net.Destination) {
  333. ob := session.OutboundFromContext(ctx)
  334. if hosts, ok := d.dns.(dns.HostsLookup); ok && destination.Address.Family().IsDomain() {
  335. proxied := hosts.LookupHosts(ob.Target.String())
  336. if proxied != nil {
  337. ro := ob.RouteTarget == destination
  338. destination.Address = *proxied
  339. if ro {
  340. ob.RouteTarget = destination
  341. } else {
  342. ob.Target = destination
  343. }
  344. }
  345. }
  346. var handler outbound.Handler
  347. routingLink := routing_session.AsRoutingContext(ctx)
  348. inTag := routingLink.GetInboundTag()
  349. isPickRoute := 0
  350. if forcedOutboundTag := session.GetForcedOutboundTagFromContext(ctx); forcedOutboundTag != "" {
  351. ctx = session.SetForcedOutboundTagToContext(ctx, "")
  352. if h := d.ohm.GetHandler(forcedOutboundTag); h != nil {
  353. isPickRoute = 1
  354. newError("taking platform initialized detour [", forcedOutboundTag, "] for [", destination, "]").WriteToLog(session.ExportIDToError(ctx))
  355. handler = h
  356. } else {
  357. newError("non existing tag for platform initialized detour: ", forcedOutboundTag).AtError().WriteToLog(session.ExportIDToError(ctx))
  358. common.Close(link.Writer)
  359. common.Interrupt(link.Reader)
  360. return
  361. }
  362. } else if d.router != nil {
  363. if route, err := d.router.PickRoute(routingLink); err == nil {
  364. outTag := route.GetOutboundTag()
  365. if h := d.ohm.GetHandler(outTag); h != nil {
  366. isPickRoute = 2
  367. newError("taking detour [", outTag, "] for [", destination, "]").WriteToLog(session.ExportIDToError(ctx))
  368. handler = h
  369. } else {
  370. newError("non existing outTag: ", outTag).AtWarning().WriteToLog(session.ExportIDToError(ctx))
  371. }
  372. } else {
  373. newError("default route for ", destination).WriteToLog(session.ExportIDToError(ctx))
  374. }
  375. }
  376. if handler == nil {
  377. handler = d.ohm.GetDefaultHandler()
  378. }
  379. if handler == nil {
  380. newError("default outbound handler not exist").WriteToLog(session.ExportIDToError(ctx))
  381. common.Close(link.Writer)
  382. common.Interrupt(link.Reader)
  383. return
  384. }
  385. if accessMessage := log.AccessMessageFromContext(ctx); accessMessage != nil {
  386. if tag := handler.Tag(); tag != "" {
  387. if inTag == "" {
  388. accessMessage.Detour = tag
  389. } else if isPickRoute == 1 {
  390. accessMessage.Detour = inTag + " ==> " + tag
  391. } else if isPickRoute == 2 {
  392. accessMessage.Detour = inTag + " -> " + tag
  393. } else {
  394. accessMessage.Detour = inTag + " >> " + tag
  395. }
  396. }
  397. log.Record(accessMessage)
  398. }
  399. handler.Dispatch(ctx, link)
  400. }