default.go 6.2 KB

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