default.go 9.5 KB

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