default.go 6.4 KB

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