default.go 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. package dispatcher
  2. //go:generate go run $GOPATH/src/v2ray.com/core/common/errors/errorgen/main.go -pkg impl -path App,Dispatcher,Default
  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/stats"
  16. "v2ray.com/core/proxy"
  17. "v2ray.com/core/transport/pipe"
  18. )
  19. var (
  20. errSniffingTimeout = newError("timeout on sniffing")
  21. )
  22. type cachedReader struct {
  23. sync.Mutex
  24. reader *pipe.Reader
  25. cache buf.MultiBuffer
  26. }
  27. func (r *cachedReader) Cache(b *buf.Buffer) {
  28. mb, _ := r.reader.ReadMultiBufferTimeout(time.Millisecond * 100)
  29. r.Lock()
  30. if !mb.IsEmpty() {
  31. common.Must(r.cache.WriteMultiBuffer(mb))
  32. }
  33. common.Must(b.Reset(func(x []byte) (int, error) {
  34. return r.cache.Copy(x), nil
  35. }))
  36. r.Unlock()
  37. }
  38. func (r *cachedReader) ReadMultiBuffer() (buf.MultiBuffer, error) {
  39. r.Lock()
  40. defer r.Unlock()
  41. if r.cache != nil && !r.cache.IsEmpty() {
  42. mb := r.cache
  43. r.cache = nil
  44. return mb, nil
  45. }
  46. return r.reader.ReadMultiBuffer()
  47. }
  48. func (r *cachedReader) ReadMultiBufferTimeout(timeout time.Duration) (buf.MultiBuffer, error) {
  49. r.Lock()
  50. defer r.Unlock()
  51. if r.cache != nil && !r.cache.IsEmpty() {
  52. mb := r.cache
  53. r.cache = nil
  54. return mb, nil
  55. }
  56. return r.reader.ReadMultiBufferTimeout(timeout)
  57. }
  58. func (r *cachedReader) CloseError() {
  59. r.Lock()
  60. if r.cache != nil {
  61. r.cache.Release()
  62. r.cache = nil
  63. }
  64. r.Unlock()
  65. r.reader.CloseError()
  66. }
  67. // DefaultDispatcher is a default implementation of Dispatcher.
  68. type DefaultDispatcher struct {
  69. ohm core.OutboundHandlerManager
  70. router core.Router
  71. policy core.PolicyManager
  72. stats core.StatManager
  73. }
  74. // NewDefaultDispatcher create a new DefaultDispatcher.
  75. func NewDefaultDispatcher(ctx context.Context, config *Config) (*DefaultDispatcher, error) {
  76. v := core.MustFromContext(ctx)
  77. d := &DefaultDispatcher{
  78. ohm: v.OutboundHandlerManager(),
  79. router: v.Router(),
  80. policy: v.PolicyManager(),
  81. stats: v.Stats(),
  82. }
  83. if err := v.RegisterFeature((*core.Dispatcher)(nil), d); err != nil {
  84. return nil, newError("unable to register Dispatcher").Base(err)
  85. }
  86. return d, nil
  87. }
  88. // Start implements common.Runnable.
  89. func (*DefaultDispatcher) Start() error {
  90. return nil
  91. }
  92. // Close implements common.Closable.
  93. func (*DefaultDispatcher) Close() error { return nil }
  94. func (d *DefaultDispatcher) getLink(ctx context.Context) (*core.Link, *core.Link) {
  95. opt := pipe.OptionsFromContext(ctx)
  96. uplinkReader, uplinkWriter := pipe.New(opt...)
  97. downlinkReader, downlinkWriter := pipe.New(opt...)
  98. inboundLink := &core.Link{
  99. Reader: downlinkReader,
  100. Writer: uplinkWriter,
  101. }
  102. outboundLink := &core.Link{
  103. Reader: uplinkReader,
  104. Writer: downlinkWriter,
  105. }
  106. user := protocol.UserFromContext(ctx)
  107. if user != nil && len(user.Email) > 0 {
  108. p := d.policy.ForLevel(user.Level)
  109. if p.Stats.UserUplink {
  110. name := "user>>>" + user.Email + ">>>traffic>>>uplink"
  111. if c, _ := core.GetOrRegisterStatCounter(d.stats, name); c != nil {
  112. inboundLink.Writer = &stats.SizeStatWriter{
  113. Counter: c,
  114. Writer: inboundLink.Writer,
  115. }
  116. }
  117. }
  118. if p.Stats.UserDownlink {
  119. name := "user>>>" + user.Email + ">>>traffic>>>downlink"
  120. if c, _ := core.GetOrRegisterStatCounter(d.stats, name); c != nil {
  121. outboundLink.Writer = &stats.SizeStatWriter{
  122. Counter: c,
  123. Writer: outboundLink.Writer,
  124. }
  125. }
  126. }
  127. }
  128. return inboundLink, outboundLink
  129. }
  130. func shouldOverride(result SniffResult, domainOverride []string) bool {
  131. for _, p := range domainOverride {
  132. if strings.HasPrefix(result.Protocol(), p) {
  133. return true
  134. }
  135. }
  136. return false
  137. }
  138. // Dispatch implements core.Dispatcher.
  139. func (d *DefaultDispatcher) Dispatch(ctx context.Context, destination net.Destination) (*core.Link, error) {
  140. if !destination.IsValid() {
  141. panic("Dispatcher: Invalid destination.")
  142. }
  143. ctx = proxy.ContextWithTarget(ctx, destination)
  144. inbound, outbound := d.getLink(ctx)
  145. sniffingConfig := proxyman.SniffingConfigFromContext(ctx)
  146. if destination.Network != net.Network_TCP || sniffingConfig == nil || !sniffingConfig.Enabled {
  147. go d.routedDispatch(ctx, outbound, destination)
  148. } else {
  149. go func() {
  150. cReader := &cachedReader{
  151. reader: outbound.Reader.(*pipe.Reader),
  152. }
  153. outbound.Reader = cReader
  154. result, err := sniffer(ctx, cReader)
  155. if err == nil {
  156. ctx = ContextWithSniffingResult(ctx, result)
  157. }
  158. if err == nil && shouldOverride(result, sniffingConfig.DestinationOverride) {
  159. domain := result.Domain()
  160. newError("sniffed domain: ", domain).WriteToLog(session.ExportIDToError(ctx))
  161. destination.Address = net.ParseAddress(domain)
  162. ctx = proxy.ContextWithTarget(ctx, destination)
  163. }
  164. d.routedDispatch(ctx, outbound, destination)
  165. }()
  166. }
  167. return inbound, nil
  168. }
  169. func sniffer(ctx context.Context, cReader *cachedReader) (SniffResult, error) {
  170. payload := buf.New()
  171. defer payload.Release()
  172. sniffer := NewSniffer()
  173. totalAttempt := 0
  174. for {
  175. select {
  176. case <-ctx.Done():
  177. return nil, ctx.Err()
  178. default:
  179. totalAttempt++
  180. if totalAttempt > 2 {
  181. return nil, errSniffingTimeout
  182. }
  183. cReader.Cache(payload)
  184. if !payload.IsEmpty() {
  185. result, err := sniffer.Sniff(payload.Bytes())
  186. if err != core.ErrNoClue {
  187. return result, err
  188. }
  189. }
  190. if payload.IsFull() {
  191. return nil, errUnknownContent
  192. }
  193. }
  194. }
  195. }
  196. func (d *DefaultDispatcher) routedDispatch(ctx context.Context, link *core.Link, destination net.Destination) {
  197. dispatcher := d.ohm.GetDefaultHandler()
  198. if d.router != nil {
  199. if tag, err := d.router.PickRoute(ctx); err == nil {
  200. if handler := d.ohm.GetHandler(tag); handler != nil {
  201. newError("taking detour [", tag, "] for [", destination, "]").WriteToLog(session.ExportIDToError(ctx))
  202. dispatcher = handler
  203. } else {
  204. newError("non existing tag: ", tag).AtWarning().WriteToLog(session.ExportIDToError(ctx))
  205. }
  206. } else {
  207. newError("default route for ", destination).WriteToLog(session.ExportIDToError(ctx))
  208. }
  209. }
  210. dispatcher.Dispatch(ctx, link)
  211. }
  212. func init() {
  213. common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
  214. return NewDefaultDispatcher(ctx, config.(*Config))
  215. }))
  216. }