default.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. // +build !confonly
  2. package dispatcher
  3. //go:generate errorgen
  4. import (
  5. "context"
  6. "strings"
  7. "sync"
  8. "time"
  9. "v2ray.com/core"
  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. content := session.ContentFromContext(ctx)
  169. if content == nil {
  170. content = new(session.Content)
  171. ctx = session.ContextWithContent(ctx, content)
  172. }
  173. sniffingRequest := content.SniffingRequest
  174. if destination.Network != net.Network_TCP || !sniffingRequest.Enabled {
  175. go d.routedDispatch(ctx, outbound, destination)
  176. } else {
  177. go func() {
  178. cReader := &cachedReader{
  179. reader: outbound.Reader.(*pipe.Reader),
  180. }
  181. outbound.Reader = cReader
  182. result, err := sniffer(ctx, cReader)
  183. if err == nil {
  184. content.Protocol = result.Protocol()
  185. }
  186. if err == nil && shouldOverride(result, sniffingRequest.OverrideDestinationForProtocol) {
  187. domain := result.Domain()
  188. newError("sniffed domain: ", domain).WriteToLog(session.ExportIDToError(ctx))
  189. destination.Address = net.ParseAddress(domain)
  190. ob.Target = destination
  191. }
  192. d.routedDispatch(ctx, outbound, destination)
  193. }()
  194. }
  195. return inbound, nil
  196. }
  197. func sniffer(ctx context.Context, cReader *cachedReader) (SniffResult, error) {
  198. payload := buf.New()
  199. defer payload.Release()
  200. sniffer := NewSniffer()
  201. totalAttempt := 0
  202. for {
  203. select {
  204. case <-ctx.Done():
  205. return nil, ctx.Err()
  206. default:
  207. totalAttempt++
  208. if totalAttempt > 2 {
  209. return nil, errSniffingTimeout
  210. }
  211. cReader.Cache(payload)
  212. if !payload.IsEmpty() {
  213. result, err := sniffer.Sniff(payload.Bytes())
  214. if err != common.ErrNoClue {
  215. return result, err
  216. }
  217. }
  218. if payload.IsFull() {
  219. return nil, errUnknownContent
  220. }
  221. }
  222. }
  223. }
  224. func (d *DefaultDispatcher) routedDispatch(ctx context.Context, link *transport.Link, destination net.Destination) {
  225. var handler outbound.Handler
  226. if d.router != nil {
  227. if tag, err := d.router.PickRoute(ctx); err == nil {
  228. if h := d.ohm.GetHandler(tag); h != nil {
  229. newError("taking detour [", tag, "] for [", destination, "]").WriteToLog(session.ExportIDToError(ctx))
  230. handler = h
  231. } else {
  232. newError("non existing tag: ", tag).AtWarning().WriteToLog(session.ExportIDToError(ctx))
  233. }
  234. } else {
  235. newError("default route for ", destination).WriteToLog(session.ExportIDToError(ctx))
  236. }
  237. }
  238. if handler == nil {
  239. handler = d.ohm.GetDefaultHandler()
  240. }
  241. if handler == nil {
  242. newError("default outbound handler not exist").WriteToLog(session.ExportIDToError(ctx))
  243. common.Close(link.Writer)
  244. common.Interrupt(link.Reader)
  245. return
  246. }
  247. handler.Dispatch(ctx, link)
  248. }