default.go 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  1. package dispatcher
  2. //go:generate go run github.com/v2fly/v2ray-core/v5/common/errors/errorgen
  3. import (
  4. "context"
  5. "strings"
  6. "sync"
  7. "time"
  8. core "github.com/v2fly/v2ray-core/v5"
  9. "github.com/v2fly/v2ray-core/v5/common"
  10. "github.com/v2fly/v2ray-core/v5/common/buf"
  11. "github.com/v2fly/v2ray-core/v5/common/log"
  12. "github.com/v2fly/v2ray-core/v5/common/net"
  13. "github.com/v2fly/v2ray-core/v5/common/protocol"
  14. "github.com/v2fly/v2ray-core/v5/common/session"
  15. "github.com/v2fly/v2ray-core/v5/common/strmatcher"
  16. "github.com/v2fly/v2ray-core/v5/features/outbound"
  17. "github.com/v2fly/v2ray-core/v5/features/policy"
  18. "github.com/v2fly/v2ray-core/v5/features/routing"
  19. routing_session "github.com/v2fly/v2ray-core/v5/features/routing/session"
  20. "github.com/v2fly/v2ray-core/v5/features/stats"
  21. "github.com/v2fly/v2ray-core/v5/transport"
  22. "github.com/v2fly/v2ray-core/v5/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, deadline time.Duration) error {
  31. mb, err := r.reader.ReadMultiBufferTimeout(deadline)
  32. if err != nil {
  33. return err
  34. }
  35. r.Lock()
  36. if !mb.IsEmpty() {
  37. r.cache, _ = buf.MergeMulti(r.cache, mb)
  38. }
  39. b.Clear()
  40. rawBytes := b.Extend(b.Cap())
  41. n := r.cache.Copy(rawBytes)
  42. b.Resize(0, int32(n))
  43. r.Unlock()
  44. return nil
  45. }
  46. func (r *cachedReader) readInternal() buf.MultiBuffer {
  47. r.Lock()
  48. defer r.Unlock()
  49. if r.cache != nil && !r.cache.IsEmpty() {
  50. mb := r.cache
  51. r.cache = nil
  52. return mb
  53. }
  54. return nil
  55. }
  56. func (r *cachedReader) ReadMultiBuffer() (buf.MultiBuffer, error) {
  57. mb := r.readInternal()
  58. if mb != nil {
  59. return mb, nil
  60. }
  61. return r.reader.ReadMultiBuffer()
  62. }
  63. func (r *cachedReader) ReadMultiBufferTimeout(timeout time.Duration) (buf.MultiBuffer, error) {
  64. mb := r.readInternal()
  65. if mb != nil {
  66. return mb, nil
  67. }
  68. return r.reader.ReadMultiBufferTimeout(timeout)
  69. }
  70. func (r *cachedReader) Interrupt() {
  71. r.Lock()
  72. if r.cache != nil {
  73. r.cache = buf.ReleaseMulti(r.cache)
  74. }
  75. r.Unlock()
  76. r.reader.Interrupt()
  77. }
  78. // DefaultDispatcher is a default implementation of Dispatcher.
  79. type DefaultDispatcher struct {
  80. ohm outbound.Manager
  81. router routing.Router
  82. policy policy.Manager
  83. stats stats.Manager
  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) error {
  89. return d.Init(config.(*Config), om, router, pm, sm)
  90. }); err != nil {
  91. return nil, err
  92. }
  93. return d, nil
  94. }))
  95. }
  96. // Init initializes DefaultDispatcher.
  97. func (d *DefaultDispatcher) Init(config *Config, om outbound.Manager, router routing.Router, pm policy.Manager, sm stats.Manager) error {
  98. d.ohm = om
  99. d.router = router
  100. d.policy = pm
  101. d.stats = sm
  102. return nil
  103. }
  104. // Type implements common.HasType.
  105. func (*DefaultDispatcher) Type() interface{} {
  106. return routing.DispatcherType()
  107. }
  108. // Start implements common.Runnable.
  109. func (*DefaultDispatcher) Start() error {
  110. return nil
  111. }
  112. // Close implements common.Closable.
  113. func (*DefaultDispatcher) Close() error { return nil }
  114. func (d *DefaultDispatcher) getLink(ctx context.Context) (*transport.Link, *transport.Link) {
  115. opt := pipe.OptionsFromContext(ctx)
  116. uplinkReader, uplinkWriter := pipe.New(opt...)
  117. downlinkReader, downlinkWriter := pipe.New(opt...)
  118. inboundLink := &transport.Link{
  119. Reader: downlinkReader,
  120. Writer: uplinkWriter,
  121. }
  122. outboundLink := &transport.Link{
  123. Reader: uplinkReader,
  124. Writer: downlinkWriter,
  125. }
  126. sessionInbound := session.InboundFromContext(ctx)
  127. var user *protocol.MemoryUser
  128. if sessionInbound != nil {
  129. user = sessionInbound.User
  130. }
  131. if user != nil && len(user.Email) > 0 {
  132. p := d.policy.ForLevel(user.Level)
  133. if p.Stats.UserUplink {
  134. name := "user>>>" + user.Email + ">>>traffic>>>uplink"
  135. if c, _ := stats.GetOrRegisterCounter(d.stats, name); c != nil {
  136. inboundLink.Writer = &SizeStatWriter{
  137. Counter: c,
  138. Writer: inboundLink.Writer,
  139. }
  140. }
  141. }
  142. if p.Stats.UserDownlink {
  143. name := "user>>>" + user.Email + ">>>traffic>>>downlink"
  144. if c, _ := stats.GetOrRegisterCounter(d.stats, name); c != nil {
  145. outboundLink.Writer = &SizeStatWriter{
  146. Counter: c,
  147. Writer: outboundLink.Writer,
  148. }
  149. }
  150. }
  151. }
  152. return inboundLink, outboundLink
  153. }
  154. func shouldOverride(result SniffResult, domainOverride []string) bool {
  155. if result.Domain() == "" {
  156. return false
  157. }
  158. protocolString := result.Protocol()
  159. if resComp, ok := result.(SnifferResultComposite); ok {
  160. protocolString = resComp.ProtocolForDomainResult()
  161. }
  162. for _, p := range domainOverride {
  163. if strings.HasPrefix(protocolString, p) || strings.HasSuffix(protocolString, p) {
  164. return true
  165. }
  166. if resultSubset, ok := result.(SnifferIsProtoSubsetOf); ok {
  167. if resultSubset.IsProtoSubsetOf(p) {
  168. return true
  169. }
  170. }
  171. }
  172. return false
  173. }
  174. // Dispatch implements routing.Dispatcher.
  175. func (d *DefaultDispatcher) Dispatch(ctx context.Context, destination net.Destination) (*transport.Link, error) {
  176. if !destination.IsValid() {
  177. panic("Dispatcher: Invalid destination.")
  178. }
  179. ob := &session.Outbound{
  180. Target: destination,
  181. }
  182. ctx = session.ContextWithOutbound(ctx, ob)
  183. inbound, outbound := d.getLink(ctx)
  184. content := session.ContentFromContext(ctx)
  185. if content == nil {
  186. content = new(session.Content)
  187. ctx = session.ContextWithContent(ctx, content)
  188. }
  189. sniffingRequest := content.SniffingRequest
  190. if !sniffingRequest.Enabled {
  191. go d.routedDispatch(ctx, outbound, destination)
  192. } else {
  193. go func() {
  194. cReader := &cachedReader{
  195. reader: outbound.Reader.(*pipe.Reader),
  196. }
  197. outbound.Reader = cReader
  198. result, err := sniffer(ctx, cReader, sniffingRequest.MetadataOnly, destination.Network)
  199. if err == nil {
  200. content.Protocol = result.Protocol()
  201. }
  202. if err == nil && shouldOverride(result, sniffingRequest.OverrideDestinationForProtocol) {
  203. if domain, err := strmatcher.ToDomain(result.Domain()); err == nil {
  204. newError("sniffed domain: ", domain, " for ", destination).WriteToLog(session.ExportIDToError(ctx))
  205. destination.Address = net.ParseAddress(domain)
  206. ob.Target = destination
  207. }
  208. }
  209. d.routedDispatch(ctx, outbound, destination)
  210. }()
  211. }
  212. return inbound, nil
  213. }
  214. func sniffer(ctx context.Context, cReader *cachedReader, metadataOnly bool, network net.Network) (SniffResult, error) {
  215. payload := buf.NewWithSize(32767)
  216. defer payload.Release()
  217. sniffer := NewSniffer(ctx)
  218. metaresult, metadataErr := sniffer.SniffMetadata(ctx)
  219. if metadataOnly {
  220. return metaresult, metadataErr
  221. }
  222. contentResult, contentErr := func() (SniffResult, error) {
  223. cacheDeadline := 200 * time.Millisecond
  224. totalAttempt := 0
  225. for {
  226. select {
  227. case <-ctx.Done():
  228. return nil, ctx.Err()
  229. default:
  230. cachingStartingTimeStamp := time.Now()
  231. cacheErr := cReader.Cache(payload, cacheDeadline)
  232. cachingTimeElapsed := time.Since(cachingStartingTimeStamp)
  233. cacheDeadline -= cachingTimeElapsed
  234. if !payload.IsEmpty() {
  235. result, err := sniffer.Sniff(ctx, payload.Bytes(), network)
  236. switch err {
  237. case common.ErrNoClue: // No Clue: protocol not matches, and sniffer cannot determine whether there will be a match or not
  238. totalAttempt++
  239. case protocol.ErrProtoNeedMoreData: // Protocol Need More Data: protocol matches, but need more data to complete sniffing
  240. if cacheErr != nil { // Cache error (e.g. timeout) counts for failed attempt
  241. totalAttempt++
  242. }
  243. default:
  244. return result, err
  245. }
  246. }
  247. if totalAttempt >= 2 || cacheDeadline <= 0 {
  248. return nil, errSniffingTimeout
  249. }
  250. }
  251. }
  252. }()
  253. if contentErr != nil && metadataErr == nil {
  254. return metaresult, nil
  255. }
  256. if contentErr == nil && metadataErr == nil {
  257. return CompositeResult(metaresult, contentResult), nil
  258. }
  259. return contentResult, contentErr
  260. }
  261. func (d *DefaultDispatcher) routedDispatch(ctx context.Context, link *transport.Link, destination net.Destination) {
  262. var handler outbound.Handler
  263. if forcedOutboundTag := session.GetForcedOutboundTagFromContext(ctx); forcedOutboundTag != "" {
  264. ctx = session.SetForcedOutboundTagToContext(ctx, "")
  265. if h := d.ohm.GetHandler(forcedOutboundTag); h != nil {
  266. newError("taking platform initialized detour [", forcedOutboundTag, "] for [", destination, "]").WriteToLog(session.ExportIDToError(ctx))
  267. handler = h
  268. } else {
  269. newError("non existing tag for platform initialized detour: ", forcedOutboundTag).AtError().WriteToLog(session.ExportIDToError(ctx))
  270. common.Close(link.Writer)
  271. common.Interrupt(link.Reader)
  272. return
  273. }
  274. } else if d.router != nil {
  275. if route, err := d.router.PickRoute(routing_session.AsRoutingContext(ctx)); err == nil {
  276. tag := route.GetOutboundTag()
  277. if h := d.ohm.GetHandler(tag); h != nil {
  278. newError("taking detour [", tag, "] for [", destination, "]").WriteToLog(session.ExportIDToError(ctx))
  279. handler = h
  280. } else {
  281. newError("non existing tag: ", tag).AtWarning().WriteToLog(session.ExportIDToError(ctx))
  282. }
  283. } else {
  284. newError("default route for ", destination).AtWarning().WriteToLog(session.ExportIDToError(ctx))
  285. }
  286. }
  287. if handler == nil {
  288. handler = d.ohm.GetDefaultHandler()
  289. }
  290. if handler == nil {
  291. newError("default outbound handler not exist").WriteToLog(session.ExportIDToError(ctx))
  292. common.Close(link.Writer)
  293. common.Interrupt(link.Reader)
  294. return
  295. }
  296. if accessMessage := log.AccessMessageFromContext(ctx); accessMessage != nil {
  297. if tag := handler.Tag(); tag != "" {
  298. accessMessage.Detour = tag
  299. if d.policy.ForSystem().OverrideAccessLogDest {
  300. accessMessage.To = destination
  301. }
  302. }
  303. log.Record(accessMessage)
  304. }
  305. handler.Dispatch(ctx, link)
  306. }