default.go 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  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 (
  25. errSniffingTimeout = newError("timeout on sniffing")
  26. )
  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. }
  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) error {
  87. return d.Init(config.(*Config), om, router, pm, sm)
  88. }); err != nil {
  89. return nil, err
  90. }
  91. return d, nil
  92. }))
  93. }
  94. // Init initializes DefaultDispatcher.
  95. func (d *DefaultDispatcher) Init(config *Config, om outbound.Manager, router routing.Router, pm policy.Manager, sm stats.Manager) error {
  96. d.ohm = om
  97. d.router = router
  98. d.policy = pm
  99. d.stats = sm
  100. return nil
  101. }
  102. // Type implements common.HasType.
  103. func (*DefaultDispatcher) Type() interface{} {
  104. return routing.DispatcherType()
  105. }
  106. // Start implements common.Runnable.
  107. func (*DefaultDispatcher) Start() error {
  108. return nil
  109. }
  110. // Close implements common.Closable.
  111. func (*DefaultDispatcher) Close() error { return nil }
  112. func (d *DefaultDispatcher) getLink(ctx context.Context) (*transport.Link, *transport.Link) {
  113. opt := pipe.OptionsFromContext(ctx)
  114. uplinkReader, uplinkWriter := pipe.New(opt...)
  115. downlinkReader, downlinkWriter := pipe.New(opt...)
  116. inboundLink := &transport.Link{
  117. Reader: downlinkReader,
  118. Writer: uplinkWriter,
  119. }
  120. outboundLink := &transport.Link{
  121. Reader: uplinkReader,
  122. Writer: downlinkWriter,
  123. }
  124. sessionInbound := session.InboundFromContext(ctx)
  125. var user *protocol.MemoryUser
  126. if sessionInbound != nil {
  127. user = sessionInbound.User
  128. }
  129. if user != nil && len(user.Email) > 0 {
  130. p := d.policy.ForLevel(user.Level)
  131. if p.Stats.UserUplink {
  132. name := "user>>>" + user.Email + ">>>traffic>>>uplink"
  133. if c, _ := stats.GetOrRegisterCounter(d.stats, name); c != nil {
  134. inboundLink.Writer = &SizeStatWriter{
  135. Counter: c,
  136. Writer: inboundLink.Writer,
  137. }
  138. }
  139. }
  140. if p.Stats.UserDownlink {
  141. name := "user>>>" + user.Email + ">>>traffic>>>downlink"
  142. if c, _ := stats.GetOrRegisterCounter(d.stats, name); c != nil {
  143. outboundLink.Writer = &SizeStatWriter{
  144. Counter: c,
  145. Writer: outboundLink.Writer,
  146. }
  147. }
  148. }
  149. }
  150. return inboundLink, outboundLink
  151. }
  152. func shouldOverride(ctx context.Context, result SniffResult, request session.SniffingRequest, destination net.Destination) bool {
  153. domain := result.Domain()
  154. for _, d := range request.ExcludeForDomain {
  155. if strings.ToLower(domain) == d {
  156. return false
  157. }
  158. }
  159. var fakeDNSEngine dns.FakeDNSEngine
  160. core.RequireFeatures(ctx, func(fdns dns.FakeDNSEngine) {
  161. fakeDNSEngine = fdns
  162. })
  163. protocolString := result.Protocol()
  164. if resComp, ok := result.(SnifferResultComposite); ok {
  165. protocolString = resComp.ProtocolForDomainResult()
  166. }
  167. for _, p := range request.OverrideDestinationForProtocol {
  168. if strings.HasPrefix(protocolString, p) {
  169. return true
  170. }
  171. if fakeDNSEngine != nil && protocolString != "bittorrent" && p == "fakedns" &&
  172. destination.Address.Family().IsIP() && fakeDNSEngine.GetFakeIPRange().Contains(destination.Address.IP()) {
  173. newError("Using sniffer ", protocolString, " since the fake DNS missed").WriteToLog(session.ExportIDToError(ctx))
  174. return true
  175. }
  176. }
  177. return false
  178. }
  179. // Dispatch implements routing.Dispatcher.
  180. func (d *DefaultDispatcher) Dispatch(ctx context.Context, destination net.Destination) (*transport.Link, error) {
  181. if !destination.IsValid() {
  182. panic("Dispatcher: Invalid destination.")
  183. }
  184. ob := &session.Outbound{
  185. Target: destination,
  186. }
  187. ctx = session.ContextWithOutbound(ctx, ob)
  188. inbound, outbound := d.getLink(ctx)
  189. content := session.ContentFromContext(ctx)
  190. if content == nil {
  191. content = new(session.Content)
  192. ctx = session.ContextWithContent(ctx, content)
  193. }
  194. sniffingRequest := content.SniffingRequest
  195. switch {
  196. case !sniffingRequest.Enabled:
  197. go d.routedDispatch(ctx, outbound, destination)
  198. case destination.Network != net.Network_TCP:
  199. // Only metadata sniff will be used for non tcp connection
  200. result, err := sniffer(ctx, nil, true)
  201. if err == nil {
  202. content.Protocol = result.Protocol()
  203. if shouldOverride(ctx, result, sniffingRequest, destination) {
  204. domain := result.Domain()
  205. newError("sniffed domain: ", domain).WriteToLog(session.ExportIDToError(ctx))
  206. destination.Address = net.ParseAddress(domain)
  207. ob.Target = destination
  208. }
  209. }
  210. go d.routedDispatch(ctx, outbound, destination)
  211. default:
  212. go func() {
  213. cReader := &cachedReader{
  214. reader: outbound.Reader.(*pipe.Reader),
  215. }
  216. outbound.Reader = cReader
  217. result, err := sniffer(ctx, cReader, sniffingRequest.MetadataOnly)
  218. if err == nil {
  219. content.Protocol = result.Protocol()
  220. }
  221. if err == nil && shouldOverride(ctx, result, sniffingRequest, destination) {
  222. domain := result.Domain()
  223. newError("sniffed domain: ", domain).WriteToLog(session.ExportIDToError(ctx))
  224. destination.Address = net.ParseAddress(domain)
  225. ob.Target = destination
  226. }
  227. d.routedDispatch(ctx, outbound, destination)
  228. }()
  229. }
  230. return inbound, nil
  231. }
  232. func sniffer(ctx context.Context, cReader *cachedReader, metadataOnly bool) (SniffResult, error) {
  233. payload := buf.New()
  234. defer payload.Release()
  235. sniffer := NewSniffer(ctx)
  236. metaresult, metadataErr := sniffer.SniffMetadata(ctx)
  237. if metadataOnly {
  238. return metaresult, metadataErr
  239. }
  240. contentResult, contentErr := func() (SniffResult, error) {
  241. totalAttempt := 0
  242. for {
  243. select {
  244. case <-ctx.Done():
  245. return nil, ctx.Err()
  246. default:
  247. totalAttempt++
  248. if totalAttempt > 2 {
  249. return nil, errSniffingTimeout
  250. }
  251. cReader.Cache(payload)
  252. if !payload.IsEmpty() {
  253. result, err := sniffer.Sniff(ctx, payload.Bytes())
  254. if err != common.ErrNoClue {
  255. return result, err
  256. }
  257. }
  258. if payload.IsFull() {
  259. return nil, errUnknownContent
  260. }
  261. }
  262. }
  263. }()
  264. if contentErr != nil && metadataErr == nil {
  265. return metaresult, nil
  266. }
  267. if contentErr == nil && metadataErr == nil {
  268. return CompositeResult(metaresult, contentResult), nil
  269. }
  270. return contentResult, contentErr
  271. }
  272. func (d *DefaultDispatcher) routedDispatch(ctx context.Context, link *transport.Link, destination net.Destination) {
  273. var handler outbound.Handler
  274. routingLink := routing_session.AsRoutingContext(ctx)
  275. inTag := routingLink.GetInboundTag()
  276. isPickRoute := false
  277. if d.router != nil {
  278. if route, err := d.router.PickRoute(routingLink); err == nil {
  279. outTag := route.GetOutboundTag()
  280. isPickRoute = true
  281. if h := d.ohm.GetHandler(outTag); h != nil {
  282. newError("taking detour [", outTag, "] for [", destination, "]").WriteToLog(session.ExportIDToError(ctx))
  283. handler = h
  284. } else {
  285. newError("non existing outTag: ", outTag).AtWarning().WriteToLog(session.ExportIDToError(ctx))
  286. }
  287. } else {
  288. newError("default route for ", destination).WriteToLog(session.ExportIDToError(ctx))
  289. }
  290. }
  291. if handler == nil {
  292. handler = d.ohm.GetDefaultHandler()
  293. }
  294. if handler == nil {
  295. newError("default outbound handler not exist").WriteToLog(session.ExportIDToError(ctx))
  296. common.Close(link.Writer)
  297. common.Interrupt(link.Reader)
  298. return
  299. }
  300. if accessMessage := log.AccessMessageFromContext(ctx); accessMessage != nil {
  301. if tag := handler.Tag(); tag != "" {
  302. if isPickRoute {
  303. if inTag != "" {
  304. accessMessage.Detour = inTag + " -> " + tag
  305. } else {
  306. accessMessage.Detour = tag
  307. }
  308. } else {
  309. if inTag != "" {
  310. accessMessage.Detour = inTag + " >> " + tag
  311. } else {
  312. accessMessage.Detour = tag
  313. }
  314. }
  315. }
  316. log.Record(accessMessage)
  317. }
  318. handler.Dispatch(ctx, link)
  319. }