default.go 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  1. package dispatcher
  2. //go:generate go run github.com/v2fly/v2ray-core/v4/common/errors/errorgen
  3. import (
  4. "context"
  5. "strings"
  6. "sync"
  7. "time"
  8. core "github.com/v2fly/v2ray-core/v4"
  9. "github.com/v2fly/v2ray-core/v4/common"
  10. "github.com/v2fly/v2ray-core/v4/common/buf"
  11. "github.com/v2fly/v2ray-core/v4/common/log"
  12. "github.com/v2fly/v2ray-core/v4/common/net"
  13. "github.com/v2fly/v2ray-core/v4/common/protocol"
  14. "github.com/v2fly/v2ray-core/v4/common/session"
  15. "github.com/v2fly/v2ray-core/v4/features/outbound"
  16. "github.com/v2fly/v2ray-core/v4/features/policy"
  17. "github.com/v2fly/v2ray-core/v4/features/routing"
  18. routing_session "github.com/v2fly/v2ray-core/v4/features/routing/session"
  19. "github.com/v2fly/v2ray-core/v4/features/stats"
  20. "github.com/v2fly/v2ray-core/v4/transport"
  21. "github.com/v2fly/v2ray-core/v4/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. protocolString := result.Protocol()
  151. if resComp, ok := result.(SnifferResultComposite); ok {
  152. protocolString = resComp.ProtocolForDomainResult()
  153. }
  154. for _, p := range domainOverride {
  155. if strings.HasPrefix(protocolString, p) {
  156. return true
  157. }
  158. if resultSubset, ok := result.(SnifferIsProtoSubsetOf); ok {
  159. if resultSubset.IsProtoSubsetOf(p) {
  160. return true
  161. }
  162. }
  163. }
  164. return false
  165. }
  166. // Dispatch implements routing.Dispatcher.
  167. func (d *DefaultDispatcher) Dispatch(ctx context.Context, destination net.Destination) (*transport.Link, error) {
  168. if !destination.IsValid() {
  169. panic("Dispatcher: Invalid destination.")
  170. }
  171. ob := &session.Outbound{
  172. Target: destination,
  173. }
  174. ctx = session.ContextWithOutbound(ctx, ob)
  175. inbound, outbound := d.getLink(ctx)
  176. content := session.ContentFromContext(ctx)
  177. if content == nil {
  178. content = new(session.Content)
  179. ctx = session.ContextWithContent(ctx, content)
  180. }
  181. sniffingRequest := content.SniffingRequest
  182. switch {
  183. case !sniffingRequest.Enabled:
  184. go d.routedDispatch(ctx, outbound, destination)
  185. case destination.Network != net.Network_TCP:
  186. // Only metadata sniff will be used for non tcp connection
  187. result, err := sniffer(ctx, nil, true)
  188. if err == nil {
  189. content.Protocol = result.Protocol()
  190. if shouldOverride(result, sniffingRequest.OverrideDestinationForProtocol) {
  191. domain := result.Domain()
  192. newError("sniffed domain: ", domain).WriteToLog(session.ExportIDToError(ctx))
  193. destination.Address = net.ParseAddress(domain)
  194. ob.Target = destination
  195. }
  196. }
  197. go d.routedDispatch(ctx, outbound, destination)
  198. default:
  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)
  205. if err == nil {
  206. content.Protocol = result.Protocol()
  207. }
  208. if err == nil && shouldOverride(result, sniffingRequest.OverrideDestinationForProtocol) {
  209. domain := result.Domain()
  210. newError("sniffed domain: ", domain).WriteToLog(session.ExportIDToError(ctx))
  211. destination.Address = net.ParseAddress(domain)
  212. ob.Target = destination
  213. }
  214. d.routedDispatch(ctx, outbound, destination)
  215. }()
  216. }
  217. return inbound, nil
  218. }
  219. func sniffer(ctx context.Context, cReader *cachedReader, metadataOnly bool) (SniffResult, error) {
  220. payload := buf.New()
  221. defer payload.Release()
  222. sniffer := NewSniffer(ctx)
  223. metaresult, metadataErr := sniffer.SniffMetadata(ctx)
  224. if metadataOnly {
  225. return metaresult, metadataErr
  226. }
  227. contentResult, contentErr := func() (SniffResult, error) {
  228. totalAttempt := 0
  229. for {
  230. select {
  231. case <-ctx.Done():
  232. return nil, ctx.Err()
  233. default:
  234. totalAttempt++
  235. if totalAttempt > 2 {
  236. return nil, errSniffingTimeout
  237. }
  238. cReader.Cache(payload)
  239. if !payload.IsEmpty() {
  240. result, err := sniffer.Sniff(ctx, payload.Bytes())
  241. if err != common.ErrNoClue {
  242. return result, err
  243. }
  244. }
  245. if payload.IsFull() {
  246. return nil, errUnknownContent
  247. }
  248. }
  249. }
  250. }()
  251. if contentErr != nil && metadataErr == nil {
  252. return metaresult, nil
  253. }
  254. if contentErr == nil && metadataErr == nil {
  255. return CompositeResult(metaresult, contentResult), nil
  256. }
  257. return contentResult, contentErr
  258. }
  259. func (d *DefaultDispatcher) routedDispatch(ctx context.Context, link *transport.Link, destination net.Destination) {
  260. var handler outbound.Handler
  261. if forcedOutboundTag := session.GetForcedOutboundTagFromContext(ctx); forcedOutboundTag != "" {
  262. ctx = session.SetForcedOutboundTagToContext(ctx, "")
  263. if h := d.ohm.GetHandler(forcedOutboundTag); h != nil {
  264. newError("taking platform initialized detour [", forcedOutboundTag, "] for [", destination, "]").WriteToLog(session.ExportIDToError(ctx))
  265. handler = h
  266. } else {
  267. newError("non existing tag for platform initialized detour: ", forcedOutboundTag).AtError().WriteToLog(session.ExportIDToError(ctx))
  268. common.Close(link.Writer)
  269. common.Interrupt(link.Reader)
  270. return
  271. }
  272. } else if d.router != nil {
  273. if route, err := d.router.PickRoute(routing_session.AsRoutingContext(ctx)); err == nil {
  274. tag := route.GetOutboundTag()
  275. if h := d.ohm.GetHandler(tag); h != nil {
  276. newError("taking detour [", tag, "] for [", destination, "]").WriteToLog(session.ExportIDToError(ctx))
  277. handler = h
  278. } else {
  279. newError("non existing tag: ", tag).AtWarning().WriteToLog(session.ExportIDToError(ctx))
  280. }
  281. } else {
  282. newError("default route for ", destination).WriteToLog(session.ExportIDToError(ctx))
  283. }
  284. }
  285. if handler == nil {
  286. handler = d.ohm.GetDefaultHandler()
  287. }
  288. if handler == nil {
  289. newError("default outbound handler not exist").WriteToLog(session.ExportIDToError(ctx))
  290. common.Close(link.Writer)
  291. common.Interrupt(link.Reader)
  292. return
  293. }
  294. if accessMessage := log.AccessMessageFromContext(ctx); accessMessage != nil {
  295. if tag := handler.Tag(); tag != "" {
  296. accessMessage.Detour = tag
  297. }
  298. log.Record(accessMessage)
  299. }
  300. handler.Dispatch(ctx, link)
  301. }