default.go 4.6 KB

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