default.go 14 KB

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