default.go 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154
  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/net"
  13. "v2ray.com/core/proxy"
  14. "v2ray.com/core/transport/ray"
  15. )
  16. var (
  17. errSniffingTimeout = newError("timeout on sniffing")
  18. )
  19. type DefaultDispatcher struct {
  20. ohm proxyman.OutboundHandlerManager
  21. router *router.Router
  22. }
  23. func NewDefaultDispatcher(ctx context.Context, config *dispatcher.Config) (*DefaultDispatcher, error) {
  24. space := app.SpaceFromContext(ctx)
  25. if space == nil {
  26. return nil, newError("no space in context")
  27. }
  28. d := &DefaultDispatcher{}
  29. space.OnInitialize(func() error {
  30. d.ohm = proxyman.OutboundHandlerManagerFromSpace(space)
  31. if d.ohm == nil {
  32. return newError("OutboundHandlerManager is not found in the space")
  33. }
  34. d.router = router.FromSpace(space)
  35. return nil
  36. })
  37. return d, nil
  38. }
  39. func (DefaultDispatcher) Start() error {
  40. return nil
  41. }
  42. func (DefaultDispatcher) Close() {}
  43. func (DefaultDispatcher) Interface() interface{} {
  44. return (*dispatcher.Interface)(nil)
  45. }
  46. type domainOrError struct {
  47. domain string
  48. err error
  49. }
  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 len(sniferList) == 0 {
  58. go d.routedDispatch(ctx, outbound, destination)
  59. } else {
  60. go func() {
  61. done := make(chan domainOrError)
  62. go snifer(ctx, sniferList, outbound, done)
  63. de := <-done
  64. if de.err != nil {
  65. log.Trace(newError("failed to snif").Base(de.err))
  66. }
  67. destination.Address = net.ParseAddress(de.domain)
  68. ctx = proxy.ContextWithTarget(ctx, destination)
  69. d.routedDispatch(ctx, outbound, destination)
  70. }()
  71. }
  72. return outbound, nil
  73. }
  74. func snifer(ctx context.Context, sniferList []proxyman.KnownProtocols, outbound ray.OutboundRay, done chan<- domainOrError) {
  75. payload := make([]byte, 2048)
  76. totalAttempt := 0
  77. for {
  78. select {
  79. case <-ctx.Done():
  80. done <- domainOrError{
  81. domain: "",
  82. err: ctx.Err(),
  83. }
  84. return
  85. case <-time.After(time.Millisecond * 100):
  86. totalAttempt++
  87. if totalAttempt > 5 {
  88. done <- domainOrError{
  89. domain: "",
  90. err: errSniffingTimeout,
  91. }
  92. return
  93. }
  94. mb := outbound.OutboundInput().Peek()
  95. nBytes, _ := mb.Read(payload)
  96. for _, protocol := range sniferList {
  97. var f func([]byte) (string, error)
  98. switch protocol {
  99. case proxyman.KnownProtocols_HTTP:
  100. f = SniffHTTP
  101. case proxyman.KnownProtocols_TLS:
  102. f = SniffTLS
  103. default:
  104. panic("Unsupported protocol")
  105. }
  106. domain, err := f(payload[:nBytes])
  107. if err != ErrMoreData {
  108. done <- domainOrError{
  109. domain: domain,
  110. err: err,
  111. }
  112. return
  113. }
  114. }
  115. }
  116. }
  117. }
  118. func (d *DefaultDispatcher) routedDispatch(ctx context.Context, outbound ray.OutboundRay, destination net.Destination) {
  119. dispatcher := d.ohm.GetDefaultHandler()
  120. if d.router != nil {
  121. if tag, err := d.router.TakeDetour(ctx); err == nil {
  122. if handler := d.ohm.GetHandler(tag); handler != nil {
  123. log.Trace(newError("taking detour [", tag, "] for [", destination, "]"))
  124. dispatcher = handler
  125. } else {
  126. log.Trace(newError("nonexisting tag: ", tag).AtWarning())
  127. }
  128. } else {
  129. log.Trace(newError("default route for ", destination))
  130. }
  131. }
  132. dispatcher.Dispatch(ctx, outbound)
  133. }
  134. func init() {
  135. common.Must(common.RegisterConfig((*dispatcher.Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
  136. return NewDefaultDispatcher(ctx, config.(*dispatcher.Config))
  137. }))
  138. }