default.go 8.7 KB

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