default.go 5.5 KB

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