default.go 6.3 KB

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