default.go 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  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 destination.Address.Family().IsDomain() || 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. return
  67. }
  68. log.Trace(newError("sniffed domain: ", de.domain))
  69. destination.Address = net.ParseAddress(de.domain)
  70. ctx = proxy.ContextWithTarget(ctx, destination)
  71. d.routedDispatch(ctx, outbound, destination)
  72. }()
  73. }
  74. return outbound, nil
  75. }
  76. func snifer(ctx context.Context, sniferList []proxyman.KnownProtocols, outbound ray.OutboundRay, done chan<- domainOrError) {
  77. payload := make([]byte, 2048)
  78. totalAttempt := 0
  79. for {
  80. select {
  81. case <-ctx.Done():
  82. done <- domainOrError{
  83. domain: "",
  84. err: ctx.Err(),
  85. }
  86. return
  87. case <-time.After(time.Millisecond * 100):
  88. totalAttempt++
  89. if totalAttempt > 5 {
  90. done <- domainOrError{
  91. domain: "",
  92. err: errSniffingTimeout,
  93. }
  94. return
  95. }
  96. mb := outbound.OutboundInput().Peek()
  97. if mb.IsEmpty() {
  98. continue
  99. }
  100. nBytes, _ := mb.Read(payload)
  101. for _, protocol := range sniferList {
  102. var f func([]byte) (string, error)
  103. switch protocol {
  104. case proxyman.KnownProtocols_HTTP:
  105. f = SniffHTTP
  106. case proxyman.KnownProtocols_TLS:
  107. f = SniffTLS
  108. default:
  109. panic("Unsupported protocol")
  110. }
  111. domain, err := f(payload[:nBytes])
  112. if err != ErrMoreData {
  113. done <- domainOrError{
  114. domain: domain,
  115. err: err,
  116. }
  117. return
  118. }
  119. }
  120. if nBytes == 2048 {
  121. done <- domainOrError{
  122. domain: "",
  123. err: ErrInvalidData,
  124. }
  125. return
  126. }
  127. }
  128. }
  129. }
  130. func (d *DefaultDispatcher) routedDispatch(ctx context.Context, outbound ray.OutboundRay, destination net.Destination) {
  131. dispatcher := d.ohm.GetDefaultHandler()
  132. if d.router != nil {
  133. if tag, err := d.router.TakeDetour(ctx); err == nil {
  134. if handler := d.ohm.GetHandler(tag); handler != nil {
  135. log.Trace(newError("taking detour [", tag, "] for [", destination, "]"))
  136. dispatcher = handler
  137. } else {
  138. log.Trace(newError("nonexisting tag: ", tag).AtWarning())
  139. }
  140. } else {
  141. log.Trace(newError("default route for ", destination))
  142. }
  143. }
  144. dispatcher.Dispatch(ctx, outbound)
  145. }
  146. func init() {
  147. common.Must(common.RegisterConfig((*dispatcher.Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
  148. return NewDefaultDispatcher(ctx, config.(*dispatcher.Config))
  149. }))
  150. }