default.go 6.2 KB

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