default.go 9.1 KB

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