default.go 9.0 KB

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