default.go 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  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/common/stats"
  13. "v2ray.com/core/proxy"
  14. "v2ray.com/core/transport/pipe"
  15. )
  16. var (
  17. errSniffingTimeout = newError("timeout on sniffing")
  18. )
  19. type cachedReader struct {
  20. reader *pipe.Reader
  21. cache buf.MultiBuffer
  22. }
  23. func (r *cachedReader) Cache(b *buf.Buffer) {
  24. mb, _ := r.reader.ReadMultiBufferWithTimeout(time.Millisecond * 100)
  25. if !mb.IsEmpty() {
  26. common.Must(r.cache.WriteMultiBuffer(mb))
  27. }
  28. common.Must(b.Reset(func(x []byte) (int, error) {
  29. return r.cache.Copy(x), nil
  30. }))
  31. }
  32. func (r *cachedReader) ReadMultiBuffer() (buf.MultiBuffer, error) {
  33. if !r.cache.IsEmpty() {
  34. mb := r.cache
  35. r.cache = nil
  36. return mb, nil
  37. }
  38. return r.reader.ReadMultiBuffer()
  39. }
  40. func (r *cachedReader) CloseError() {
  41. r.cache.Release()
  42. r.reader.CloseError()
  43. }
  44. // DefaultDispatcher is a default implementation of Dispatcher.
  45. type DefaultDispatcher struct {
  46. ohm core.OutboundHandlerManager
  47. router core.Router
  48. policy core.PolicyManager
  49. stats core.StatManager
  50. }
  51. // NewDefaultDispatcher create a new DefaultDispatcher.
  52. func NewDefaultDispatcher(ctx context.Context, config *Config) (*DefaultDispatcher, error) {
  53. v := core.MustFromContext(ctx)
  54. d := &DefaultDispatcher{
  55. ohm: v.OutboundHandlerManager(),
  56. router: v.Router(),
  57. policy: v.PolicyManager(),
  58. stats: v.Stats(),
  59. }
  60. if err := v.RegisterFeature((*core.Dispatcher)(nil), d); err != nil {
  61. return nil, newError("unable to register Dispatcher").Base(err)
  62. }
  63. return d, nil
  64. }
  65. // Start implements common.Runnable.
  66. func (*DefaultDispatcher) Start() error {
  67. return nil
  68. }
  69. // Close implements common.Closable.
  70. func (*DefaultDispatcher) Close() error { return nil }
  71. func (d *DefaultDispatcher) getLink(ctx context.Context) (*core.Link, *core.Link) {
  72. uplinkReader, uplinkWriter := pipe.New()
  73. downlinkReader, downlinkWriter := pipe.New()
  74. inboundLink := &core.Link{
  75. Reader: downlinkReader,
  76. Writer: uplinkWriter,
  77. }
  78. outboundLink := &core.Link{
  79. Reader: uplinkReader,
  80. Writer: downlinkWriter,
  81. }
  82. user := protocol.UserFromContext(ctx)
  83. if user != nil && len(user.Email) > 0 {
  84. p := d.policy.ForLevel(user.Level)
  85. if p.Stats.UserUplink {
  86. name := "user>>>" + user.Email + ">>>traffic>>>uplink"
  87. if c, _ := core.GetOrRegisterStatCounter(d.stats, name); c != nil {
  88. inboundLink.Writer = &stats.SizeStatWriter{
  89. Counter: c,
  90. Writer: inboundLink.Writer,
  91. }
  92. }
  93. }
  94. if p.Stats.UserDownlink {
  95. name := "user>>>" + user.Email + ">>>traffic>>>downlink"
  96. if c, _ := core.GetOrRegisterStatCounter(d.stats, name); c != nil {
  97. outboundLink.Writer = &stats.SizeStatWriter{
  98. Counter: c,
  99. Writer: outboundLink.Writer,
  100. }
  101. }
  102. }
  103. }
  104. return inboundLink, outboundLink
  105. }
  106. // Dispatch implements core.Dispatcher.
  107. func (d *DefaultDispatcher) Dispatch(ctx context.Context, destination net.Destination) (*core.Link, error) {
  108. if !destination.IsValid() {
  109. panic("Dispatcher: Invalid destination.")
  110. }
  111. ctx = proxy.ContextWithTarget(ctx, destination)
  112. inbound, outbound := d.getLink(ctx)
  113. snifferList := proxyman.ProtocolSniffersFromContext(ctx)
  114. if destination.Address.Family().IsDomain() || len(snifferList) == 0 {
  115. go d.routedDispatch(ctx, outbound, destination)
  116. } else {
  117. go func() {
  118. cReader := &cachedReader{
  119. reader: outbound.Reader.(*pipe.Reader),
  120. }
  121. outbound.Reader = cReader
  122. domain, err := sniffer(ctx, snifferList, cReader)
  123. if err == nil {
  124. newError("sniffed domain: ", domain).WithContext(ctx).WriteToLog()
  125. destination.Address = net.ParseAddress(domain)
  126. ctx = proxy.ContextWithTarget(ctx, destination)
  127. }
  128. d.routedDispatch(ctx, outbound, destination)
  129. }()
  130. }
  131. return inbound, nil
  132. }
  133. func sniffer(ctx context.Context, snifferList []proxyman.KnownProtocols, cReader *cachedReader) (string, error) {
  134. payload := buf.New()
  135. defer payload.Release()
  136. sniffer := NewSniffer(snifferList)
  137. totalAttempt := 0
  138. for {
  139. select {
  140. case <-ctx.Done():
  141. return "", ctx.Err()
  142. default:
  143. totalAttempt++
  144. if totalAttempt > 5 {
  145. return "", errSniffingTimeout
  146. }
  147. cReader.Cache(payload)
  148. if !payload.IsEmpty() {
  149. domain, err := sniffer.Sniff(payload.Bytes())
  150. if err != ErrMoreData {
  151. return domain, err
  152. }
  153. }
  154. if payload.IsFull() {
  155. return "", ErrInvalidData
  156. }
  157. time.Sleep(time.Millisecond * 100)
  158. }
  159. }
  160. }
  161. func (d *DefaultDispatcher) routedDispatch(ctx context.Context, link *core.Link, destination net.Destination) {
  162. dispatcher := d.ohm.GetDefaultHandler()
  163. if d.router != nil {
  164. if tag, err := d.router.PickRoute(ctx); err == nil {
  165. if handler := d.ohm.GetHandler(tag); handler != nil {
  166. newError("taking detour [", tag, "] for [", destination, "]").WithContext(ctx).WriteToLog()
  167. dispatcher = handler
  168. } else {
  169. newError("non existing tag: ", tag).AtWarning().WithContext(ctx).WriteToLog()
  170. }
  171. } else {
  172. newError("default route for ", destination).WithContext(ctx).WriteToLog()
  173. }
  174. }
  175. dispatcher.Dispatch(ctx, link)
  176. }
  177. func init() {
  178. common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
  179. return NewDefaultDispatcher(ctx, config.(*Config))
  180. }))
  181. }