default.go 6.3 KB

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