default.go 5.7 KB

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