default.go 6.6 KB

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