default.go 6.7 KB

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