default.go 4.2 KB

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