default.go 9.2 KB

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