default.go 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  1. // +build !confonly
  2. package dispatcher
  3. //go:generate go run v2ray.com/core/common/errors/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/log"
  13. "v2ray.com/core/common/net"
  14. "v2ray.com/core/common/protocol"
  15. "v2ray.com/core/common/session"
  16. "v2ray.com/core/features/outbound"
  17. "v2ray.com/core/features/policy"
  18. "v2ray.com/core/features/routing"
  19. routing_session "v2ray.com/core/features/routing/session"
  20. "v2ray.com/core/features/stats"
  21. "v2ray.com/core/transport"
  22. "v2ray.com/core/transport/pipe"
  23. )
  24. var (
  25. errSniffingTimeout = newError("timeout on sniffing")
  26. )
  27. type cachedReader struct {
  28. sync.Mutex
  29. reader *pipe.Reader
  30. cache buf.MultiBuffer
  31. }
  32. func (r *cachedReader) Cache(b *buf.Buffer) {
  33. mb, _ := r.reader.ReadMultiBufferTimeout(time.Millisecond * 100)
  34. r.Lock()
  35. if !mb.IsEmpty() {
  36. r.cache, _ = buf.MergeMulti(r.cache, mb)
  37. }
  38. b.Clear()
  39. rawBytes := b.Extend(buf.Size)
  40. n := r.cache.Copy(rawBytes)
  41. b.Resize(0, int32(n))
  42. r.Unlock()
  43. }
  44. func (r *cachedReader) readInternal() buf.MultiBuffer {
  45. r.Lock()
  46. defer r.Unlock()
  47. if r.cache != nil && !r.cache.IsEmpty() {
  48. mb := r.cache
  49. r.cache = nil
  50. return mb
  51. }
  52. return nil
  53. }
  54. func (r *cachedReader) ReadMultiBuffer() (buf.MultiBuffer, error) {
  55. mb := r.readInternal()
  56. if mb != nil {
  57. return mb, nil
  58. }
  59. return r.reader.ReadMultiBuffer()
  60. }
  61. func (r *cachedReader) ReadMultiBufferTimeout(timeout time.Duration) (buf.MultiBuffer, error) {
  62. mb := r.readInternal()
  63. if mb != nil {
  64. return mb, nil
  65. }
  66. return r.reader.ReadMultiBufferTimeout(timeout)
  67. }
  68. func (r *cachedReader) Interrupt() {
  69. r.Lock()
  70. if r.cache != nil {
  71. r.cache = buf.ReleaseMulti(r.cache)
  72. }
  73. r.Unlock()
  74. r.reader.Interrupt()
  75. }
  76. // DefaultDispatcher is a default implementation of Dispatcher.
  77. type DefaultDispatcher struct {
  78. ohm outbound.Manager
  79. router routing.Router
  80. policy policy.Manager
  81. stats stats.Manager
  82. }
  83. func init() {
  84. common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
  85. d := new(DefaultDispatcher)
  86. if err := core.RequireFeatures(ctx, func(om outbound.Manager, router routing.Router, pm policy.Manager, sm stats.Manager) error {
  87. return d.Init(config.(*Config), om, router, pm, sm)
  88. }); err != nil {
  89. return nil, err
  90. }
  91. return d, nil
  92. }))
  93. }
  94. // Init initializes DefaultDispatcher.
  95. func (d *DefaultDispatcher) Init(config *Config, om outbound.Manager, router routing.Router, pm policy.Manager, sm stats.Manager) error {
  96. d.ohm = om
  97. d.router = router
  98. d.policy = pm
  99. d.stats = sm
  100. return nil
  101. }
  102. // Type implements common.HasType.
  103. func (*DefaultDispatcher) Type() interface{} {
  104. return routing.DispatcherType()
  105. }
  106. // Start implements common.Runnable.
  107. func (*DefaultDispatcher) Start() error {
  108. return nil
  109. }
  110. // Close implements common.Closable.
  111. func (*DefaultDispatcher) Close() error { return nil }
  112. func (d *DefaultDispatcher) getLink(ctx context.Context) (*transport.Link, *transport.Link) {
  113. opt := pipe.OptionsFromContext(ctx)
  114. uplinkReader, uplinkWriter := pipe.New(opt...)
  115. downlinkReader, downlinkWriter := pipe.New(opt...)
  116. inboundLink := &transport.Link{
  117. Reader: downlinkReader,
  118. Writer: uplinkWriter,
  119. }
  120. outboundLink := &transport.Link{
  121. Reader: uplinkReader,
  122. Writer: downlinkWriter,
  123. }
  124. sessionInbound := session.InboundFromContext(ctx)
  125. var user *protocol.MemoryUser
  126. if sessionInbound != nil {
  127. user = sessionInbound.User
  128. }
  129. if user != nil && len(user.Email) > 0 {
  130. p := d.policy.ForLevel(user.Level)
  131. accessMessage := log.AccessMessageFromContext(ctx)
  132. if p.Stats.UserUplink {
  133. name := "user>>>" + user.Email + ">>>traffic>>>uplink"
  134. if c, _ := stats.GetOrRegisterCounter(d.stats, name); c != nil {
  135. inboundLink.Writer = &SizeStatWriter{
  136. Counter: c,
  137. Writer: inboundLink.Writer,
  138. Record: &accessMessage.BytesSent,
  139. }
  140. }
  141. }
  142. if p.Stats.UserDownlink {
  143. name := "user>>>" + user.Email + ">>>traffic>>>downlink"
  144. if c, _ := stats.GetOrRegisterCounter(d.stats, name); c != nil {
  145. outboundLink.Writer = &SizeStatWriter{
  146. Counter: c,
  147. Writer: outboundLink.Writer,
  148. Record: &accessMessage.BytesReceived,
  149. }
  150. }
  151. }
  152. }
  153. return inboundLink, outboundLink
  154. }
  155. func shouldOverride(result SniffResult, domainOverride []string) bool {
  156. for _, p := range domainOverride {
  157. if strings.HasPrefix(result.Protocol(), p) {
  158. return true
  159. }
  160. }
  161. return false
  162. }
  163. // Dispatch implements routing.Dispatcher.
  164. func (d *DefaultDispatcher) Dispatch(ctx context.Context, destination net.Destination) (*transport.Link, error) {
  165. if !destination.IsValid() {
  166. panic("Dispatcher: Invalid destination.")
  167. }
  168. ob := &session.Outbound{
  169. Target: destination,
  170. }
  171. ctx = session.ContextWithOutbound(ctx, ob)
  172. inbound, outbound := d.getLink(ctx)
  173. content := session.ContentFromContext(ctx)
  174. if content == nil {
  175. content = new(session.Content)
  176. ctx = session.ContextWithContent(ctx, content)
  177. }
  178. sniffingRequest := content.SniffingRequest
  179. if destination.Network != net.Network_TCP || !sniffingRequest.Enabled {
  180. go d.routedDispatch(ctx, outbound, destination)
  181. } else {
  182. go func() {
  183. cReader := &cachedReader{
  184. reader: outbound.Reader.(*pipe.Reader),
  185. }
  186. outbound.Reader = cReader
  187. result, err := sniffer(ctx, cReader)
  188. if err == nil {
  189. content.Protocol = result.Protocol()
  190. }
  191. if err == nil && shouldOverride(result, sniffingRequest.OverrideDestinationForProtocol) {
  192. domain := result.Domain()
  193. newError("sniffed domain: ", domain).WriteToLog(session.ExportIDToError(ctx))
  194. destination.Address = net.ParseAddress(domain)
  195. ob.Target = destination
  196. }
  197. d.routedDispatch(ctx, outbound, destination)
  198. }()
  199. }
  200. return inbound, nil
  201. }
  202. func sniffer(ctx context.Context, cReader *cachedReader) (SniffResult, error) {
  203. payload := buf.New()
  204. defer payload.Release()
  205. sniffer := NewSniffer()
  206. totalAttempt := 0
  207. for {
  208. select {
  209. case <-ctx.Done():
  210. return nil, ctx.Err()
  211. default:
  212. totalAttempt++
  213. if totalAttempt > 2 {
  214. return nil, errSniffingTimeout
  215. }
  216. cReader.Cache(payload)
  217. if !payload.IsEmpty() {
  218. result, err := sniffer.Sniff(payload.Bytes())
  219. if err != common.ErrNoClue {
  220. return result, err
  221. }
  222. }
  223. if payload.IsFull() {
  224. return nil, errUnknownContent
  225. }
  226. }
  227. }
  228. }
  229. func (d *DefaultDispatcher) routedDispatch(ctx context.Context, link *transport.Link, destination net.Destination) {
  230. var handler outbound.Handler
  231. if d.router != nil {
  232. if route, err := d.router.PickRoute(routing_session.AsRoutingContext(ctx)); err == nil {
  233. tag := route.GetOutboundTag()
  234. if h := d.ohm.GetHandler(tag); h != nil {
  235. newError("taking detour [", tag, "] for [", destination, "]").WriteToLog(session.ExportIDToError(ctx))
  236. handler = h
  237. } else {
  238. newError("non existing tag: ", tag).AtWarning().WriteToLog(session.ExportIDToError(ctx))
  239. }
  240. } else {
  241. newError("default route for ", destination).WriteToLog(session.ExportIDToError(ctx))
  242. }
  243. }
  244. if handler == nil {
  245. handler = d.ohm.GetDefaultHandler()
  246. }
  247. if handler == nil {
  248. newError("default outbound handler not exist").WriteToLog(session.ExportIDToError(ctx))
  249. common.Close(link.Writer)
  250. common.Interrupt(link.Reader)
  251. return
  252. }
  253. handler.Dispatch(ctx, link)
  254. if accessMessage := log.AccessMessageFromContext(ctx); accessMessage != nil {
  255. if tag := handler.Tag(); tag != "" {
  256. accessMessage.Detour = tag
  257. }
  258. log.Record(accessMessage)
  259. }
  260. }