default.go 4.1 KB

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