default.go 10.0 KB

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