default.go 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  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").Base(err)
  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) getRayOption(user *protocol.User) []ray.Option {
  46. var rayOptions []ray.Option
  47. if user != nil && len(user.Email) > 0 {
  48. p := d.policy.ForLevel(user.Level)
  49. if p.Stats.UserUplink {
  50. name := "user>>>" + user.Email + ">>>traffic>>>uplink"
  51. if c, _ := core.GetOrRegisterStatCounter(d.stats, name); c != nil {
  52. rayOptions = append(rayOptions, ray.WithUplinkStatCounter(c))
  53. }
  54. }
  55. if p.Stats.UserDownlink {
  56. name := "user>>>" + user.Email + ">>>traffic>>>downlink"
  57. if c, _ := core.GetOrRegisterStatCounter(d.stats, name); c != nil {
  58. rayOptions = append(rayOptions, ray.WithDownlinkStatCounter(c))
  59. }
  60. }
  61. }
  62. return rayOptions
  63. }
  64. // Dispatch implements core.Dispatcher.
  65. func (d *DefaultDispatcher) Dispatch(ctx context.Context, destination net.Destination) (ray.InboundRay, error) {
  66. if !destination.IsValid() {
  67. panic("Dispatcher: Invalid destination.")
  68. }
  69. ctx = proxy.ContextWithTarget(ctx, destination)
  70. user := protocol.UserFromContext(ctx)
  71. rayOptions := d.getRayOption(user)
  72. outbound := ray.New(ctx, rayOptions...)
  73. snifferList := proxyman.ProtocolSniffersFromContext(ctx)
  74. if destination.Address.Family().IsDomain() || len(snifferList) == 0 {
  75. go d.routedDispatch(ctx, outbound, destination)
  76. } else {
  77. go func() {
  78. domain, err := sniffer(ctx, snifferList, outbound)
  79. if err == nil {
  80. newError("sniffed domain: ", domain).WithContext(ctx).WriteToLog()
  81. destination.Address = net.ParseAddress(domain)
  82. ctx = proxy.ContextWithTarget(ctx, destination)
  83. }
  84. d.routedDispatch(ctx, outbound, destination)
  85. }()
  86. }
  87. return outbound, nil
  88. }
  89. func sniffer(ctx context.Context, snifferList []proxyman.KnownProtocols, outbound ray.OutboundRay) (string, error) {
  90. payload := buf.New()
  91. defer payload.Release()
  92. sniffer := NewSniffer(snifferList)
  93. totalAttempt := 0
  94. for {
  95. select {
  96. case <-ctx.Done():
  97. return "", ctx.Err()
  98. default:
  99. totalAttempt++
  100. if totalAttempt > 5 {
  101. return "", errSniffingTimeout
  102. }
  103. outbound.OutboundInput().Peek(payload)
  104. if !payload.IsEmpty() {
  105. domain, err := sniffer.Sniff(payload.Bytes())
  106. if err != ErrMoreData {
  107. return domain, err
  108. }
  109. }
  110. if payload.IsFull() {
  111. return "", ErrInvalidData
  112. }
  113. time.Sleep(time.Millisecond * 100)
  114. }
  115. }
  116. }
  117. func (d *DefaultDispatcher) routedDispatch(ctx context.Context, outbound ray.OutboundRay, destination net.Destination) {
  118. dispatcher := d.ohm.GetDefaultHandler()
  119. if d.router != nil {
  120. if tag, err := d.router.PickRoute(ctx); err == nil {
  121. if handler := d.ohm.GetHandler(tag); handler != nil {
  122. newError("taking detour [", tag, "] for [", destination, "]").WithContext(ctx).WriteToLog()
  123. dispatcher = handler
  124. } else {
  125. newError("non existing tag: ", tag).AtWarning().WithContext(ctx).WriteToLog()
  126. }
  127. } else {
  128. newError("default route for ", destination).WithContext(ctx).WriteToLog()
  129. }
  130. }
  131. dispatcher.Dispatch(ctx, outbound)
  132. }
  133. func init() {
  134. common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
  135. return NewDefaultDispatcher(ctx, config.(*Config))
  136. }))
  137. }