default.go 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  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. "time"
  6. "v2ray.com/core"
  7. "v2ray.com/core/app/proxyman"
  8. "v2ray.com/core/common"
  9. "v2ray.com/core/common/buf"
  10. "v2ray.com/core/common/net"
  11. "v2ray.com/core/common/protocol"
  12. "v2ray.com/core/common/stats"
  13. "v2ray.com/core/proxy"
  14. "v2ray.com/core/transport/pipe"
  15. )
  16. var (
  17. errSniffingTimeout = newError("timeout on sniffing")
  18. )
  19. type cachedReader struct {
  20. reader *pipe.Reader
  21. cache buf.MultiBuffer
  22. }
  23. func (r *cachedReader) Cache(b *buf.Buffer) {
  24. mb, _ := r.reader.ReadMultiBufferWithTimeout(time.Millisecond * 100)
  25. if !mb.IsEmpty() {
  26. common.Must(r.cache.WriteMultiBuffer(mb))
  27. }
  28. common.Must(b.Reset(func(x []byte) (int, error) {
  29. return r.cache.Copy(x), nil
  30. }))
  31. }
  32. func (r *cachedReader) ReadMultiBuffer() (buf.MultiBuffer, error) {
  33. if !r.cache.IsEmpty() {
  34. mb := r.cache
  35. r.cache = nil
  36. return mb, nil
  37. }
  38. return r.reader.ReadMultiBuffer()
  39. }
  40. func (r *cachedReader) CloseError() {
  41. r.cache.Release()
  42. r.reader.CloseError()
  43. }
  44. // DefaultDispatcher is a default implementation of Dispatcher.
  45. type DefaultDispatcher struct {
  46. ohm core.OutboundHandlerManager
  47. router core.Router
  48. policy core.PolicyManager
  49. stats core.StatManager
  50. }
  51. // NewDefaultDispatcher create a new DefaultDispatcher.
  52. func NewDefaultDispatcher(ctx context.Context, config *Config) (*DefaultDispatcher, error) {
  53. v := core.MustFromContext(ctx)
  54. d := &DefaultDispatcher{
  55. ohm: v.OutboundHandlerManager(),
  56. router: v.Router(),
  57. policy: v.PolicyManager(),
  58. stats: v.Stats(),
  59. }
  60. if err := v.RegisterFeature((*core.Dispatcher)(nil), d); err != nil {
  61. return nil, newError("unable to register Dispatcher").Base(err)
  62. }
  63. return d, nil
  64. }
  65. // Start implements common.Runnable.
  66. func (*DefaultDispatcher) Start() error {
  67. return nil
  68. }
  69. // Close implements common.Closable.
  70. func (*DefaultDispatcher) Close() error { return nil }
  71. func (d *DefaultDispatcher) getLink(ctx context.Context) (*core.Link, *core.Link) {
  72. opt := pipe.OptionsFromContext(ctx)
  73. uplinkReader, uplinkWriter := pipe.New(opt...)
  74. downlinkReader, downlinkWriter := pipe.New(opt...)
  75. inboundLink := &core.Link{
  76. Reader: downlinkReader,
  77. Writer: uplinkWriter,
  78. }
  79. outboundLink := &core.Link{
  80. Reader: uplinkReader,
  81. Writer: downlinkWriter,
  82. }
  83. user := protocol.UserFromContext(ctx)
  84. if user != nil && len(user.Email) > 0 {
  85. p := d.policy.ForLevel(user.Level)
  86. if p.Stats.UserUplink {
  87. name := "user>>>" + user.Email + ">>>traffic>>>uplink"
  88. if c, _ := core.GetOrRegisterStatCounter(d.stats, name); c != nil {
  89. inboundLink.Writer = &stats.SizeStatWriter{
  90. Counter: c,
  91. Writer: inboundLink.Writer,
  92. }
  93. }
  94. }
  95. if p.Stats.UserDownlink {
  96. name := "user>>>" + user.Email + ">>>traffic>>>downlink"
  97. if c, _ := core.GetOrRegisterStatCounter(d.stats, name); c != nil {
  98. outboundLink.Writer = &stats.SizeStatWriter{
  99. Counter: c,
  100. Writer: outboundLink.Writer,
  101. }
  102. }
  103. }
  104. }
  105. return inboundLink, outboundLink
  106. }
  107. // Dispatch implements core.Dispatcher.
  108. func (d *DefaultDispatcher) Dispatch(ctx context.Context, destination net.Destination) (*core.Link, error) {
  109. if !destination.IsValid() {
  110. panic("Dispatcher: Invalid destination.")
  111. }
  112. ctx = proxy.ContextWithTarget(ctx, destination)
  113. inbound, outbound := d.getLink(ctx)
  114. snifferList := proxyman.ProtocolSniffersFromContext(ctx)
  115. if destination.Address.Family().IsDomain() || destination.Network != net.Network_TCP || len(snifferList) == 0 {
  116. go d.routedDispatch(ctx, outbound, destination)
  117. } else {
  118. go func() {
  119. cReader := &cachedReader{
  120. reader: outbound.Reader.(*pipe.Reader),
  121. }
  122. outbound.Reader = cReader
  123. domain, err := sniffer(ctx, snifferList, cReader)
  124. if err == nil {
  125. newError("sniffed domain: ", domain).WithContext(ctx).WriteToLog()
  126. destination.Address = net.ParseAddress(domain)
  127. ctx = proxy.ContextWithTarget(ctx, destination)
  128. }
  129. d.routedDispatch(ctx, outbound, destination)
  130. }()
  131. }
  132. return inbound, nil
  133. }
  134. func sniffer(ctx context.Context, snifferList []proxyman.KnownProtocols, cReader *cachedReader) (string, error) {
  135. payload := buf.New()
  136. defer payload.Release()
  137. sniffer := NewSniffer(snifferList)
  138. totalAttempt := 0
  139. for {
  140. select {
  141. case <-ctx.Done():
  142. return "", ctx.Err()
  143. default:
  144. totalAttempt++
  145. if totalAttempt > 5 {
  146. return "", errSniffingTimeout
  147. }
  148. cReader.Cache(payload)
  149. if !payload.IsEmpty() {
  150. domain, err := sniffer.Sniff(payload.Bytes())
  151. if err != ErrMoreData {
  152. return domain, err
  153. }
  154. }
  155. if payload.IsFull() {
  156. return "", ErrInvalidData
  157. }
  158. time.Sleep(time.Millisecond * 100)
  159. }
  160. }
  161. }
  162. func (d *DefaultDispatcher) routedDispatch(ctx context.Context, link *core.Link, destination net.Destination) {
  163. dispatcher := d.ohm.GetDefaultHandler()
  164. if d.router != nil {
  165. if tag, err := d.router.PickRoute(ctx); err == nil {
  166. if handler := d.ohm.GetHandler(tag); handler != nil {
  167. newError("taking detour [", tag, "] for [", destination, "]").WithContext(ctx).WriteToLog()
  168. dispatcher = handler
  169. } else {
  170. newError("non existing tag: ", tag).AtWarning().WithContext(ctx).WriteToLog()
  171. }
  172. } else {
  173. newError("default route for ", destination).WithContext(ctx).WriteToLog()
  174. }
  175. }
  176. dispatcher.Dispatch(ctx, link)
  177. }
  178. func init() {
  179. common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
  180. return NewDefaultDispatcher(ctx, config.(*Config))
  181. }))
  182. }