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