default.go 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  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/proxy"
  13. "v2ray.com/core/transport/ray"
  14. )
  15. var (
  16. errSniffingTimeout = newError("timeout on sniffing")
  17. )
  18. // DefaultDispatcher is a default implementation of Dispatcher.
  19. type DefaultDispatcher struct {
  20. ohm core.OutboundHandlerManager
  21. router core.Router
  22. policy core.PolicyManager
  23. stats core.StatManager
  24. }
  25. // NewDefaultDispatcher create a new DefaultDispatcher.
  26. func NewDefaultDispatcher(ctx context.Context, config *Config) (*DefaultDispatcher, error) {
  27. v := core.MustFromContext(ctx)
  28. d := &DefaultDispatcher{
  29. ohm: v.OutboundHandlerManager(),
  30. router: v.Router(),
  31. policy: v.PolicyManager(),
  32. stats: v.Stats(),
  33. }
  34. if err := v.RegisterFeature((*core.Dispatcher)(nil), d); err != nil {
  35. return nil, newError("unable to register Dispatcher")
  36. }
  37. return d, nil
  38. }
  39. // Start implements common.Runnable.
  40. func (*DefaultDispatcher) Start() error {
  41. return nil
  42. }
  43. // Close implements common.Closable.
  44. func (*DefaultDispatcher) Close() error { return nil }
  45. func (d *DefaultDispatcher) getStatCounter(name string) core.StatCounter {
  46. c := d.stats.GetCounter(name)
  47. if c != nil {
  48. return c
  49. }
  50. c, err := d.stats.RegisterCounter(name)
  51. if err != nil {
  52. return nil
  53. }
  54. return c
  55. }
  56. func (d *DefaultDispatcher) getRayOption(user *protocol.User) []ray.Option {
  57. var rayOptions []ray.Option
  58. if user != nil && len(user.Email) > 0 {
  59. p := d.policy.ForLevel(user.Level)
  60. if p.Stats.UserUplink {
  61. name := "user>>>" + user.Email + ">>>traffic>>>uplink"
  62. if c := d.getStatCounter(name); c != nil {
  63. rayOptions = append(rayOptions, ray.WithUplinkStatCounter(c))
  64. }
  65. }
  66. if p.Stats.UserDownlink {
  67. name := "user>>>" + user.Email + ">>>traffic>>>downlink"
  68. if c := d.getStatCounter(name); c != nil {
  69. rayOptions = append(rayOptions, ray.WithDownlinkStatCounter(c))
  70. }
  71. }
  72. }
  73. return rayOptions
  74. }
  75. // Dispatch implements core.Dispatcher.
  76. func (d *DefaultDispatcher) Dispatch(ctx context.Context, destination net.Destination) (ray.InboundRay, error) {
  77. if !destination.IsValid() {
  78. panic("Dispatcher: Invalid destination.")
  79. }
  80. ctx = proxy.ContextWithTarget(ctx, destination)
  81. user := protocol.UserFromContext(ctx)
  82. rayOptions := d.getRayOption(user)
  83. outbound := ray.New(ctx, rayOptions...)
  84. snifferList := proxyman.ProtocolSniffersFromContext(ctx)
  85. if destination.Address.Family().IsDomain() || len(snifferList) == 0 {
  86. go d.routedDispatch(ctx, outbound, destination)
  87. } else {
  88. go func() {
  89. domain, err := sniffer(ctx, snifferList, outbound)
  90. if err == nil {
  91. newError("sniffed domain: ", domain).WithContext(ctx).WriteToLog()
  92. destination.Address = net.ParseAddress(domain)
  93. ctx = proxy.ContextWithTarget(ctx, destination)
  94. }
  95. d.routedDispatch(ctx, outbound, destination)
  96. }()
  97. }
  98. return outbound, nil
  99. }
  100. func sniffer(ctx context.Context, snifferList []proxyman.KnownProtocols, outbound ray.OutboundRay) (string, error) {
  101. payload := buf.New()
  102. defer payload.Release()
  103. sniffer := NewSniffer(snifferList)
  104. totalAttempt := 0
  105. for {
  106. select {
  107. case <-ctx.Done():
  108. return "", ctx.Err()
  109. default:
  110. totalAttempt++
  111. if totalAttempt > 5 {
  112. return "", errSniffingTimeout
  113. }
  114. outbound.OutboundInput().Peek(payload)
  115. if !payload.IsEmpty() {
  116. domain, err := sniffer.Sniff(payload.Bytes())
  117. if err != ErrMoreData {
  118. return domain, err
  119. }
  120. }
  121. if payload.IsFull() {
  122. return "", ErrInvalidData
  123. }
  124. time.Sleep(time.Millisecond * 100)
  125. }
  126. }
  127. }
  128. func (d *DefaultDispatcher) routedDispatch(ctx context.Context, outbound ray.OutboundRay, destination net.Destination) {
  129. dispatcher := d.ohm.GetDefaultHandler()
  130. if d.router != nil {
  131. if tag, err := d.router.PickRoute(ctx); err == nil {
  132. if handler := d.ohm.GetHandler(tag); handler != nil {
  133. newError("taking detour [", tag, "] for [", destination, "]").WithContext(ctx).WriteToLog()
  134. dispatcher = handler
  135. } else {
  136. newError("non existing tag: ", tag).AtWarning().WithContext(ctx).WriteToLog()
  137. }
  138. } else {
  139. newError("default route for ", destination).WithContext(ctx).WriteToLog()
  140. }
  141. }
  142. dispatcher.Dispatch(ctx, outbound)
  143. }
  144. func init() {
  145. common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
  146. return NewDefaultDispatcher(ctx, config.(*Config))
  147. }))
  148. }