default.go 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146
  1. package impl
  2. //go:generate go run $GOPATH/src/v2ray.com/core/tools/generrorgen/main.go -pkg impl -path App,Dispatcher,Default
  3. import (
  4. "context"
  5. "time"
  6. "v2ray.com/core/app"
  7. "v2ray.com/core/app/dispatcher"
  8. "v2ray.com/core/app/log"
  9. "v2ray.com/core/app/proxyman"
  10. "v2ray.com/core/app/router"
  11. "v2ray.com/core/common"
  12. "v2ray.com/core/common/buf"
  13. "v2ray.com/core/common/net"
  14. "v2ray.com/core/proxy"
  15. "v2ray.com/core/transport/ray"
  16. )
  17. var (
  18. errSniffingTimeout = newError("timeout on sniffing")
  19. )
  20. // DefaultDispatcher is a default implementation of Dispatcher.
  21. type DefaultDispatcher struct {
  22. ohm proxyman.OutboundHandlerManager
  23. router *router.Router
  24. }
  25. // NewDefaultDispatcher create a new DefaultDispatcher.
  26. func NewDefaultDispatcher(ctx context.Context, config *dispatcher.Config) (*DefaultDispatcher, error) {
  27. space := app.SpaceFromContext(ctx)
  28. if space == nil {
  29. return nil, newError("no space in context")
  30. }
  31. d := &DefaultDispatcher{}
  32. space.OnInitialize(func() error {
  33. d.ohm = proxyman.OutboundHandlerManagerFromSpace(space)
  34. if d.ohm == nil {
  35. return newError("OutboundHandlerManager is not found in the space")
  36. }
  37. d.router = router.FromSpace(space)
  38. return nil
  39. })
  40. return d, nil
  41. }
  42. func (*DefaultDispatcher) Start() error {
  43. return nil
  44. }
  45. func (*DefaultDispatcher) Close() {}
  46. func (*DefaultDispatcher) Interface() interface{} {
  47. return (*dispatcher.Interface)(nil)
  48. }
  49. // Dispatch implements Dispatcher.Interface.
  50. func (d *DefaultDispatcher) Dispatch(ctx context.Context, destination net.Destination) (ray.InboundRay, error) {
  51. if !destination.IsValid() {
  52. panic("Dispatcher: Invalid destination.")
  53. }
  54. ctx = proxy.ContextWithTarget(ctx, destination)
  55. outbound := ray.NewRay(ctx)
  56. sniferList := proxyman.ProtocoSniffersFromContext(ctx)
  57. if destination.Address.Family().IsDomain() || len(sniferList) == 0 {
  58. go d.routedDispatch(ctx, outbound, destination)
  59. } else {
  60. go func() {
  61. domain, err := snifer(ctx, sniferList, outbound)
  62. if err == nil {
  63. log.Trace(newError("sniffed domain: ", domain))
  64. destination.Address = net.ParseAddress(domain)
  65. ctx = proxy.ContextWithTarget(ctx, destination)
  66. }
  67. d.routedDispatch(ctx, outbound, destination)
  68. }()
  69. }
  70. return outbound, nil
  71. }
  72. func snifer(ctx context.Context, sniferList []proxyman.KnownProtocols, outbound ray.OutboundRay) (string, error) {
  73. payload := buf.New()
  74. defer payload.Release()
  75. totalAttempt := 0
  76. for {
  77. select {
  78. case <-ctx.Done():
  79. return "", ctx.Err()
  80. case <-time.After(time.Millisecond * 100):
  81. totalAttempt++
  82. if totalAttempt > 5 {
  83. return "", errSniffingTimeout
  84. }
  85. outbound.OutboundInput().Peek(payload)
  86. if payload.IsEmpty() {
  87. continue
  88. }
  89. for _, protocol := range sniferList {
  90. var f func([]byte) (string, error)
  91. switch protocol {
  92. case proxyman.KnownProtocols_HTTP:
  93. f = SniffHTTP
  94. case proxyman.KnownProtocols_TLS:
  95. f = SniffTLS
  96. default:
  97. panic("Unsupported protocol")
  98. }
  99. domain, err := f(payload.Bytes())
  100. if err != ErrMoreData {
  101. return domain, err
  102. }
  103. }
  104. if payload.IsFull() {
  105. return "", ErrInvalidData
  106. }
  107. }
  108. }
  109. }
  110. func (d *DefaultDispatcher) routedDispatch(ctx context.Context, outbound ray.OutboundRay, destination net.Destination) {
  111. dispatcher := d.ohm.GetDefaultHandler()
  112. if d.router != nil {
  113. if tag, err := d.router.TakeDetour(ctx); err == nil {
  114. if handler := d.ohm.GetHandler(tag); handler != nil {
  115. log.Trace(newError("taking detour [", tag, "] for [", destination, "]"))
  116. dispatcher = handler
  117. } else {
  118. log.Trace(newError("nonexisting tag: ", tag).AtWarning())
  119. }
  120. } else {
  121. log.Trace(newError("default route for ", destination))
  122. }
  123. }
  124. dispatcher.Dispatch(ctx, outbound)
  125. }
  126. func init() {
  127. common.Must(common.RegisterConfig((*dispatcher.Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
  128. return NewDefaultDispatcher(ctx, config.(*dispatcher.Config))
  129. }))
  130. }