default.go 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  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/vio"
  16. "v2ray.com/core/features/outbound"
  17. "v2ray.com/core/features/policy"
  18. "v2ray.com/core/features/routing"
  19. "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.Manager
  73. router routing.Router
  74. policy policy.Manager
  75. stats stats.Manager
  76. }
  77. func init() {
  78. common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
  79. d := new(DefaultDispatcher)
  80. if err := core.RequireFeatures(ctx, func(om outbound.Manager, router routing.Router, pm policy.Manager, sm stats.Manager) error {
  81. return d.Init(config.(*Config), om, router, pm, sm)
  82. }); err != nil {
  83. return nil, err
  84. }
  85. return d, nil
  86. }))
  87. }
  88. // Init initializes DefaultDispatcher.
  89. func (d *DefaultDispatcher) Init(config *Config, om outbound.Manager, router routing.Router, pm policy.Manager, sm stats.Manager) error {
  90. d.ohm = om
  91. d.router = router
  92. d.policy = pm
  93. d.stats = sm
  94. return nil
  95. }
  96. // Type implements common.HasType.
  97. func (*DefaultDispatcher) Type() interface{} {
  98. return routing.DispatcherType()
  99. }
  100. // Start implements common.Runnable.
  101. func (*DefaultDispatcher) Start() error {
  102. return nil
  103. }
  104. // Close implements common.Closable.
  105. func (*DefaultDispatcher) Close() error { return nil }
  106. func (d *DefaultDispatcher) getLink(ctx context.Context) (*vio.Link, *vio.Link) {
  107. opt := pipe.OptionsFromContext(ctx)
  108. uplinkReader, uplinkWriter := pipe.New(opt...)
  109. downlinkReader, downlinkWriter := pipe.New(opt...)
  110. inboundLink := &vio.Link{
  111. Reader: downlinkReader,
  112. Writer: uplinkWriter,
  113. }
  114. outboundLink := &vio.Link{
  115. Reader: uplinkReader,
  116. Writer: downlinkWriter,
  117. }
  118. sessionInbound := session.InboundFromContext(ctx)
  119. var user *protocol.MemoryUser
  120. if sessionInbound != nil {
  121. user = sessionInbound.User
  122. }
  123. if user != nil && len(user.Email) > 0 {
  124. p := d.policy.ForLevel(user.Level)
  125. if p.Stats.UserUplink {
  126. name := "user>>>" + user.Email + ">>>traffic>>>uplink"
  127. if c, _ := stats.GetOrRegisterCounter(d.stats, name); c != nil {
  128. inboundLink.Writer = &vio.SizeStatWriter{
  129. Counter: c,
  130. Writer: inboundLink.Writer,
  131. }
  132. }
  133. }
  134. if p.Stats.UserDownlink {
  135. name := "user>>>" + user.Email + ">>>traffic>>>downlink"
  136. if c, _ := stats.GetOrRegisterCounter(d.stats, name); c != nil {
  137. outboundLink.Writer = &vio.SizeStatWriter{
  138. Counter: c,
  139. Writer: outboundLink.Writer,
  140. }
  141. }
  142. }
  143. }
  144. return inboundLink, outboundLink
  145. }
  146. func shouldOverride(result SniffResult, domainOverride []string) bool {
  147. for _, p := range domainOverride {
  148. if strings.HasPrefix(result.Protocol(), p) {
  149. return true
  150. }
  151. }
  152. return false
  153. }
  154. // Dispatch implements routing.Dispatcher.
  155. func (d *DefaultDispatcher) Dispatch(ctx context.Context, destination net.Destination) (*vio.Link, error) {
  156. if !destination.IsValid() {
  157. panic("Dispatcher: Invalid destination.")
  158. }
  159. ob := &session.Outbound{
  160. Target: destination,
  161. }
  162. ctx = session.ContextWithOutbound(ctx, ob)
  163. inbound, outbound := d.getLink(ctx)
  164. sniffingConfig := proxyman.SniffingConfigFromContext(ctx)
  165. if destination.Network != net.Network_TCP || sniffingConfig == nil || !sniffingConfig.Enabled {
  166. go d.routedDispatch(ctx, outbound, destination)
  167. } else {
  168. go func() {
  169. cReader := &cachedReader{
  170. reader: outbound.Reader.(*pipe.Reader),
  171. }
  172. outbound.Reader = cReader
  173. result, err := sniffer(ctx, cReader)
  174. if err == nil {
  175. ctx = ContextWithSniffingResult(ctx, result)
  176. }
  177. if err == nil && shouldOverride(result, sniffingConfig.DestinationOverride) {
  178. domain := result.Domain()
  179. newError("sniffed domain: ", domain).WriteToLog(session.ExportIDToError(ctx))
  180. destination.Address = net.ParseAddress(domain)
  181. ob.Target = destination
  182. }
  183. d.routedDispatch(ctx, outbound, destination)
  184. }()
  185. }
  186. return inbound, nil
  187. }
  188. func sniffer(ctx context.Context, cReader *cachedReader) (SniffResult, error) {
  189. payload := buf.New()
  190. defer payload.Release()
  191. sniffer := NewSniffer()
  192. totalAttempt := 0
  193. for {
  194. select {
  195. case <-ctx.Done():
  196. return nil, ctx.Err()
  197. default:
  198. totalAttempt++
  199. if totalAttempt > 2 {
  200. return nil, errSniffingTimeout
  201. }
  202. cReader.Cache(payload)
  203. if !payload.IsEmpty() {
  204. result, err := sniffer.Sniff(payload.Bytes())
  205. if err != common.ErrNoClue {
  206. return result, err
  207. }
  208. }
  209. if payload.IsFull() {
  210. return nil, errUnknownContent
  211. }
  212. }
  213. }
  214. }
  215. func (d *DefaultDispatcher) routedDispatch(ctx context.Context, link *vio.Link, destination net.Destination) {
  216. dispatcher := d.ohm.GetDefaultHandler()
  217. if d.router != nil {
  218. if tag, err := d.router.PickRoute(ctx); err == nil {
  219. if handler := d.ohm.GetHandler(tag); handler != nil {
  220. newError("taking detour [", tag, "] for [", destination, "]").WriteToLog(session.ExportIDToError(ctx))
  221. dispatcher = handler
  222. } else {
  223. newError("non existing tag: ", tag).AtWarning().WriteToLog(session.ExportIDToError(ctx))
  224. }
  225. } else {
  226. newError("default route for ", destination).WriteToLog(session.ExportIDToError(ctx))
  227. }
  228. }
  229. dispatcher.Dispatch(ctx, link)
  230. }