default.go 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  1. package dispatcher
  2. //go:generate errorgen
  3. import (
  4. "context"
  5. "strings"
  6. "sync"
  7. "time"
  8. "v2ray.com/core"
  9. "v2ray.com/core/app/proxyman"
  10. "v2ray.com/core/common"
  11. "v2ray.com/core/common/buf"
  12. "v2ray.com/core/common/net"
  13. "v2ray.com/core/common/protocol"
  14. "v2ray.com/core/common/session"
  15. "v2ray.com/core/common/vio"
  16. "v2ray.com/core/features/outbound"
  17. "v2ray.com/core/features/policy"
  18. "v2ray.com/core/features/routing"
  19. "v2ray.com/core/features/stats"
  20. "v2ray.com/core/transport"
  21. "v2ray.com/core/transport/pipe"
  22. )
  23. var (
  24. errSniffingTimeout = newError("timeout on sniffing")
  25. )
  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. common.Must(r.cache.WriteMultiBuffer(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) ReadMultiBuffer() (buf.MultiBuffer, error) {
  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, nil
  50. }
  51. return r.reader.ReadMultiBuffer()
  52. }
  53. func (r *cachedReader) ReadMultiBufferTimeout(timeout time.Duration) (buf.MultiBuffer, error) {
  54. r.Lock()
  55. defer r.Unlock()
  56. if r.cache != nil && !r.cache.IsEmpty() {
  57. mb := r.cache
  58. r.cache = nil
  59. return mb, nil
  60. }
  61. return r.reader.ReadMultiBufferTimeout(timeout)
  62. }
  63. func (r *cachedReader) CloseError() {
  64. r.Lock()
  65. if r.cache != nil {
  66. r.cache.Release()
  67. r.cache = nil
  68. }
  69. r.Unlock()
  70. r.reader.CloseError()
  71. }
  72. // DefaultDispatcher is a default implementation of Dispatcher.
  73. type DefaultDispatcher struct {
  74. ohm outbound.Manager
  75. router routing.Router
  76. policy policy.Manager
  77. stats stats.Manager
  78. }
  79. func init() {
  80. common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
  81. d := new(DefaultDispatcher)
  82. if err := core.RequireFeatures(ctx, func(om outbound.Manager, router routing.Router, pm policy.Manager, sm stats.Manager) error {
  83. return d.Init(config.(*Config), om, router, pm, sm)
  84. }); err != nil {
  85. return nil, err
  86. }
  87. return d, nil
  88. }))
  89. }
  90. // Init initializes DefaultDispatcher.
  91. func (d *DefaultDispatcher) Init(config *Config, om outbound.Manager, router routing.Router, pm policy.Manager, sm stats.Manager) error {
  92. d.ohm = om
  93. d.router = router
  94. d.policy = pm
  95. d.stats = sm
  96. return nil
  97. }
  98. // Type implements common.HasType.
  99. func (*DefaultDispatcher) Type() interface{} {
  100. return routing.DispatcherType()
  101. }
  102. // Start implements common.Runnable.
  103. func (*DefaultDispatcher) Start() error {
  104. return nil
  105. }
  106. // Close implements common.Closable.
  107. func (*DefaultDispatcher) Close() error { return nil }
  108. func (d *DefaultDispatcher) getLink(ctx context.Context) (*transport.Link, *transport.Link) {
  109. opt := pipe.OptionsFromContext(ctx)
  110. uplinkReader, uplinkWriter := pipe.New(opt...)
  111. downlinkReader, downlinkWriter := pipe.New(opt...)
  112. inboundLink := &transport.Link{
  113. Reader: downlinkReader,
  114. Writer: uplinkWriter,
  115. }
  116. outboundLink := &transport.Link{
  117. Reader: uplinkReader,
  118. Writer: downlinkWriter,
  119. }
  120. sessionInbound := session.InboundFromContext(ctx)
  121. var user *protocol.MemoryUser
  122. if sessionInbound != nil {
  123. user = sessionInbound.User
  124. }
  125. if user != nil && len(user.Email) > 0 {
  126. p := d.policy.ForLevel(user.Level)
  127. if p.Stats.UserUplink {
  128. name := "user>>>" + user.Email + ">>>traffic>>>uplink"
  129. if c, _ := stats.GetOrRegisterCounter(d.stats, name); c != nil {
  130. inboundLink.Writer = &vio.SizeStatWriter{
  131. Counter: c,
  132. Writer: inboundLink.Writer,
  133. }
  134. }
  135. }
  136. if p.Stats.UserDownlink {
  137. name := "user>>>" + user.Email + ">>>traffic>>>downlink"
  138. if c, _ := stats.GetOrRegisterCounter(d.stats, name); c != nil {
  139. outboundLink.Writer = &vio.SizeStatWriter{
  140. Counter: c,
  141. Writer: outboundLink.Writer,
  142. }
  143. }
  144. }
  145. }
  146. return inboundLink, outboundLink
  147. }
  148. func shouldOverride(result SniffResult, domainOverride []string) bool {
  149. for _, p := range domainOverride {
  150. if strings.HasPrefix(result.Protocol(), p) {
  151. return true
  152. }
  153. }
  154. return false
  155. }
  156. // Dispatch implements routing.Dispatcher.
  157. func (d *DefaultDispatcher) Dispatch(ctx context.Context, destination net.Destination) (*transport.Link, error) {
  158. if !destination.IsValid() {
  159. panic("Dispatcher: Invalid destination.")
  160. }
  161. ob := &session.Outbound{
  162. Target: destination,
  163. }
  164. ctx = session.ContextWithOutbound(ctx, ob)
  165. inbound, outbound := d.getLink(ctx)
  166. sniffingConfig := proxyman.SniffingConfigFromContext(ctx)
  167. if destination.Network != net.Network_TCP || sniffingConfig == nil || !sniffingConfig.Enabled {
  168. go d.routedDispatch(ctx, outbound, destination)
  169. } else {
  170. go func() {
  171. cReader := &cachedReader{
  172. reader: outbound.Reader.(*pipe.Reader),
  173. }
  174. outbound.Reader = cReader
  175. result, err := sniffer(ctx, cReader)
  176. if err == nil {
  177. ctx = ContextWithSniffingResult(ctx, result)
  178. }
  179. if err == nil && shouldOverride(result, sniffingConfig.DestinationOverride) {
  180. domain := result.Domain()
  181. newError("sniffed domain: ", domain).WriteToLog(session.ExportIDToError(ctx))
  182. destination.Address = net.ParseAddress(domain)
  183. ob.Target = destination
  184. }
  185. d.routedDispatch(ctx, outbound, destination)
  186. }()
  187. }
  188. return inbound, nil
  189. }
  190. func sniffer(ctx context.Context, cReader *cachedReader) (SniffResult, error) {
  191. payload := buf.New()
  192. defer payload.Release()
  193. sniffer := NewSniffer()
  194. totalAttempt := 0
  195. for {
  196. select {
  197. case <-ctx.Done():
  198. return nil, ctx.Err()
  199. default:
  200. totalAttempt++
  201. if totalAttempt > 2 {
  202. return nil, errSniffingTimeout
  203. }
  204. cReader.Cache(payload)
  205. if !payload.IsEmpty() {
  206. result, err := sniffer.Sniff(payload.Bytes())
  207. if err != common.ErrNoClue {
  208. return result, err
  209. }
  210. }
  211. if payload.IsFull() {
  212. return nil, errUnknownContent
  213. }
  214. }
  215. }
  216. }
  217. func (d *DefaultDispatcher) routedDispatch(ctx context.Context, link *transport.Link, destination net.Destination) {
  218. dispatcher := d.ohm.GetDefaultHandler()
  219. if d.router != nil {
  220. if tag, err := d.router.PickRoute(ctx); err == nil {
  221. if handler := d.ohm.GetHandler(tag); handler != nil {
  222. newError("taking detour [", tag, "] for [", destination, "]").WriteToLog(session.ExportIDToError(ctx))
  223. dispatcher = handler
  224. } else {
  225. newError("non existing tag: ", tag).AtWarning().WriteToLog(session.ExportIDToError(ctx))
  226. }
  227. } else {
  228. newError("default route for ", destination).WriteToLog(session.ExportIDToError(ctx))
  229. }
  230. }
  231. dispatcher.Dispatch(ctx, link)
  232. }