default.go 6.2 KB

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