default.go 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  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. 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. switch {
  186. case !sniffingRequest.Enabled:
  187. go d.routedDispatch(ctx, outbound, destination)
  188. case destination.Network != net.Network_TCP:
  189. // Only metadata sniff will be used for non tcp connection
  190. result, err := sniffer(ctx, nil, true)
  191. if err == nil {
  192. content.Protocol = result.Protocol()
  193. if shouldOverride(result, sniffingRequest.OverrideDestinationForProtocol) {
  194. domain := result.Domain()
  195. newError("sniffed domain: ", domain).WriteToLog(session.ExportIDToError(ctx))
  196. destination.Address = net.ParseAddress(domain)
  197. ob.Target = destination
  198. }
  199. }
  200. go d.routedDispatch(ctx, outbound, destination)
  201. default:
  202. go func() {
  203. cReader := &cachedReader{
  204. reader: outbound.Reader.(*pipe.Reader),
  205. }
  206. outbound.Reader = cReader
  207. result, err := sniffer(ctx, cReader, sniffingRequest.MetadataOnly)
  208. if err == nil {
  209. content.Protocol = result.Protocol()
  210. }
  211. if err == nil && shouldOverride(result, sniffingRequest.OverrideDestinationForProtocol) {
  212. domain := result.Domain()
  213. newError("sniffed domain: ", domain).WriteToLog(session.ExportIDToError(ctx))
  214. destination.Address = net.ParseAddress(domain)
  215. ob.Target = destination
  216. }
  217. d.routedDispatch(ctx, outbound, destination)
  218. }()
  219. }
  220. return inbound, nil
  221. }
  222. func sniffer(ctx context.Context, cReader *cachedReader, metadataOnly bool) (SniffResult, error) {
  223. payload := buf.New()
  224. defer payload.Release()
  225. sniffer := NewSniffer(ctx)
  226. metaresult, metadataErr := sniffer.SniffMetadata(ctx)
  227. if metadataOnly {
  228. return metaresult, metadataErr
  229. }
  230. contentResult, contentErr := func() (SniffResult, error) {
  231. totalAttempt := 0
  232. for {
  233. select {
  234. case <-ctx.Done():
  235. return nil, ctx.Err()
  236. default:
  237. totalAttempt++
  238. if totalAttempt > 2 {
  239. return nil, errSniffingTimeout
  240. }
  241. cReader.Cache(payload)
  242. if !payload.IsEmpty() {
  243. result, err := sniffer.Sniff(ctx, payload.Bytes())
  244. if err != common.ErrNoClue {
  245. return result, err
  246. }
  247. }
  248. if payload.IsFull() {
  249. return nil, errUnknownContent
  250. }
  251. }
  252. }
  253. }()
  254. if contentErr != nil && metadataErr == nil {
  255. return metaresult, nil
  256. }
  257. if contentErr == nil && metadataErr == nil {
  258. return CompositeResult(metaresult, contentResult), nil
  259. }
  260. return contentResult, contentErr
  261. }
  262. func (d *DefaultDispatcher) routedDispatch(ctx context.Context, link *transport.Link, destination net.Destination) {
  263. var handler outbound.Handler
  264. if forcedOutboundTag := session.GetForcedOutboundTagFromContext(ctx); forcedOutboundTag != "" {
  265. ctx = session.SetForcedOutboundTagToContext(ctx, "")
  266. if h := d.ohm.GetHandler(forcedOutboundTag); h != nil {
  267. newError("taking platform initialized detour [", forcedOutboundTag, "] for [", destination, "]").WriteToLog(session.ExportIDToError(ctx))
  268. handler = h
  269. } else {
  270. newError("non existing tag for platform initialized detour: ", forcedOutboundTag).AtError().WriteToLog(session.ExportIDToError(ctx))
  271. common.Close(link.Writer)
  272. common.Interrupt(link.Reader)
  273. return
  274. }
  275. } else if d.router != nil {
  276. if route, err := d.router.PickRoute(routing_session.AsRoutingContext(ctx)); err == nil {
  277. tag := route.GetOutboundTag()
  278. if h := d.ohm.GetHandler(tag); h != nil {
  279. newError("taking detour [", tag, "] for [", destination, "]").WriteToLog(session.ExportIDToError(ctx))
  280. handler = h
  281. } else {
  282. newError("non existing tag: ", tag).AtWarning().WriteToLog(session.ExportIDToError(ctx))
  283. }
  284. } else {
  285. newError("default route for ", destination).WriteToLog(session.ExportIDToError(ctx))
  286. }
  287. }
  288. if handler == nil {
  289. handler = d.ohm.GetDefaultHandler()
  290. }
  291. if handler == nil {
  292. newError("default outbound handler not exist").WriteToLog(session.ExportIDToError(ctx))
  293. common.Close(link.Writer)
  294. common.Interrupt(link.Reader)
  295. return
  296. }
  297. if accessMessage := log.AccessMessageFromContext(ctx); accessMessage != nil {
  298. if tag := handler.Tag(); tag != "" {
  299. accessMessage.Detour = tag
  300. }
  301. log.Record(accessMessage)
  302. }
  303. handler.Dispatch(ctx, link)
  304. }