default.go 6.0 KB

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