mux.go 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  1. package mux
  2. //go:generate go run $GOPATH/src/v2ray.com/core/tools/generrorgen/main.go -pkg mux -path App,Proxyman,Mux
  3. import (
  4. "context"
  5. "sync"
  6. "time"
  7. "v2ray.com/core/app"
  8. "v2ray.com/core/app/dispatcher"
  9. "v2ray.com/core/app/log"
  10. "v2ray.com/core/app/proxyman"
  11. "v2ray.com/core/common/buf"
  12. "v2ray.com/core/common/net"
  13. "v2ray.com/core/common/signal"
  14. "v2ray.com/core/proxy"
  15. "v2ray.com/core/transport/ray"
  16. )
  17. const (
  18. maxTotal = 128
  19. )
  20. type ClientManager struct {
  21. access sync.Mutex
  22. clients []*Client
  23. proxy proxy.Outbound
  24. dialer proxy.Dialer
  25. config *proxyman.MultiplexingConfig
  26. }
  27. func NewClientManager(p proxy.Outbound, d proxy.Dialer, c *proxyman.MultiplexingConfig) *ClientManager {
  28. return &ClientManager{
  29. proxy: p,
  30. dialer: d,
  31. config: c,
  32. }
  33. }
  34. func (m *ClientManager) Dispatch(ctx context.Context, outboundRay ray.OutboundRay) error {
  35. m.access.Lock()
  36. defer m.access.Unlock()
  37. for _, client := range m.clients {
  38. if client.Dispatch(ctx, outboundRay) {
  39. return nil
  40. }
  41. }
  42. client, err := NewClient(m.proxy, m.dialer, m)
  43. if err != nil {
  44. return newError("failed to create client").Base(err)
  45. }
  46. m.clients = append(m.clients, client)
  47. client.Dispatch(ctx, outboundRay)
  48. return nil
  49. }
  50. func (m *ClientManager) onClientFinish() {
  51. m.access.Lock()
  52. defer m.access.Unlock()
  53. if len(m.clients) < 10 {
  54. return
  55. }
  56. activeClients := make([]*Client, 0, len(m.clients))
  57. for _, client := range m.clients {
  58. if !client.Closed() {
  59. activeClients = append(activeClients, client)
  60. }
  61. }
  62. m.clients = activeClients
  63. }
  64. type Client struct {
  65. sessionManager *SessionManager
  66. inboundRay ray.InboundRay
  67. ctx context.Context
  68. cancel context.CancelFunc
  69. manager *ClientManager
  70. session2Remove chan uint16
  71. concurrency uint32
  72. }
  73. var muxCoolDestination = net.TCPDestination(net.DomainAddress("v1.mux.cool"), net.Port(9527))
  74. func NewClient(p proxy.Outbound, dialer proxy.Dialer, m *ClientManager) (*Client, error) {
  75. ctx, cancel := context.WithCancel(context.Background())
  76. ctx = proxy.ContextWithTarget(ctx, muxCoolDestination)
  77. pipe := ray.NewRay(ctx)
  78. go p.Process(ctx, pipe, dialer)
  79. c := &Client{
  80. sessionManager: NewSessionManager(),
  81. inboundRay: pipe,
  82. ctx: ctx,
  83. cancel: cancel,
  84. manager: m,
  85. session2Remove: make(chan uint16, 16),
  86. concurrency: m.config.Concurrency,
  87. }
  88. go c.fetchOutput()
  89. go c.monitor()
  90. return c, nil
  91. }
  92. func (m *Client) Closed() bool {
  93. select {
  94. case <-m.ctx.Done():
  95. return true
  96. default:
  97. return false
  98. }
  99. }
  100. func (m *Client) monitor() {
  101. defer m.manager.onClientFinish()
  102. for {
  103. select {
  104. case <-m.ctx.Done():
  105. m.inboundRay.InboundInput().Close()
  106. m.inboundRay.InboundOutput().CloseError()
  107. return
  108. case <-time.After(time.Second * 6):
  109. size := m.sessionManager.Size()
  110. if size == 0 && m.sessionManager.CloseIfNoSession() {
  111. m.cancel()
  112. }
  113. }
  114. }
  115. }
  116. func fetchInput(ctx context.Context, s *Session, output buf.Writer) {
  117. dest, _ := proxy.TargetFromContext(ctx)
  118. writer := &Writer{
  119. dest: dest,
  120. id: s.ID,
  121. writer: output,
  122. }
  123. defer writer.Close()
  124. defer s.CloseUplink()
  125. log.Trace(newError("dispatching request to ", dest))
  126. data, _ := s.input.ReadTimeout(time.Millisecond * 500)
  127. if data != nil {
  128. if err := writer.Write(data); err != nil {
  129. log.Trace(newError("failed to write first payload").Base(err))
  130. return
  131. }
  132. }
  133. if err := buf.PipeUntilEOF(signal.BackgroundTimer(), s.input, writer); err != nil {
  134. log.Trace(newError("failed to fetch all input").Base(err))
  135. }
  136. }
  137. func (m *Client) Dispatch(ctx context.Context, outboundRay ray.OutboundRay) bool {
  138. numSession := m.sessionManager.Size()
  139. if numSession >= int(m.concurrency) || numSession >= maxTotal {
  140. return false
  141. }
  142. select {
  143. case <-m.ctx.Done():
  144. return false
  145. default:
  146. }
  147. s := m.sessionManager.Allocate()
  148. if s == nil {
  149. return false
  150. }
  151. s.input = outboundRay.OutboundInput()
  152. s.output = outboundRay.OutboundOutput()
  153. go fetchInput(ctx, s, m.inboundRay.InboundInput())
  154. return true
  155. }
  156. func drain(reader *Reader) error {
  157. for {
  158. data, more, err := reader.Read()
  159. if err != nil {
  160. return err
  161. }
  162. data.Release()
  163. if !more {
  164. return nil
  165. }
  166. }
  167. }
  168. func pipe(reader *Reader, writer buf.Writer) error {
  169. for {
  170. data, more, err := reader.Read()
  171. if err != nil {
  172. return err
  173. }
  174. if err := writer.Write(data); err != nil {
  175. return err
  176. }
  177. if !more {
  178. return nil
  179. }
  180. }
  181. }
  182. func (m *Client) fetchOutput() {
  183. defer m.cancel()
  184. reader := NewReader(m.inboundRay.InboundOutput())
  185. L:
  186. for {
  187. meta, err := reader.ReadMetadata()
  188. if err != nil {
  189. log.Trace(newError("failed to read metadata").Base(err))
  190. break
  191. }
  192. var drainData bool
  193. switch meta.SessionStatus {
  194. case SessionStatusKeepAlive:
  195. drainData = true
  196. case SessionStatusEnd:
  197. if s, found := m.sessionManager.Get(meta.SessionID); found {
  198. s.CloseDownlink()
  199. s.output.Close()
  200. }
  201. drainData = true
  202. case SessionStatusNew:
  203. drainData = true
  204. case SessionStatusKeep:
  205. if !meta.Option.Has(OptionData) {
  206. break
  207. }
  208. if s, found := m.sessionManager.Get(meta.SessionID); found {
  209. if err := pipe(reader, s.output); err != nil {
  210. log.Trace(newError("failed to pipe data").Base(err))
  211. break L
  212. }
  213. }
  214. }
  215. if drainData && meta.Option.Has(OptionData) {
  216. if err := drain(reader); err != nil {
  217. log.Trace(newError("failed to drain data").Base(err))
  218. break
  219. }
  220. }
  221. }
  222. }
  223. type Server struct {
  224. dispatcher dispatcher.Interface
  225. }
  226. func NewServer(ctx context.Context) *Server {
  227. s := &Server{}
  228. space := app.SpaceFromContext(ctx)
  229. space.OnInitialize(func() error {
  230. d := dispatcher.FromSpace(space)
  231. if d == nil {
  232. return newError("no dispatcher in space")
  233. }
  234. s.dispatcher = d
  235. return nil
  236. })
  237. return s
  238. }
  239. func (s *Server) Dispatch(ctx context.Context, dest net.Destination) (ray.InboundRay, error) {
  240. if dest != muxCoolDestination {
  241. return s.dispatcher.Dispatch(ctx, dest)
  242. }
  243. ray := ray.NewRay(ctx)
  244. worker := &ServerWorker{
  245. dispatcher: s.dispatcher,
  246. outboundRay: ray,
  247. sessionManager: NewSessionManager(),
  248. }
  249. go worker.run(ctx)
  250. return ray, nil
  251. }
  252. type ServerWorker struct {
  253. dispatcher dispatcher.Interface
  254. outboundRay ray.OutboundRay
  255. sessionManager *SessionManager
  256. }
  257. func handle(ctx context.Context, s *Session, output buf.Writer) {
  258. writer := NewResponseWriter(s.ID, output)
  259. if err := buf.PipeUntilEOF(signal.BackgroundTimer(), s.input, writer); err != nil {
  260. log.Trace(newError("session ", s.ID, " ends: ").Base(err))
  261. }
  262. writer.Close()
  263. s.CloseDownlink()
  264. }
  265. func (w *ServerWorker) run(ctx context.Context) {
  266. input := w.outboundRay.OutboundInput()
  267. reader := NewReader(input)
  268. L:
  269. for {
  270. select {
  271. case <-ctx.Done():
  272. return
  273. default:
  274. }
  275. meta, err := reader.ReadMetadata()
  276. if err != nil {
  277. log.Trace(newError("failed to read metadata").Base(err))
  278. return
  279. }
  280. var drainData bool
  281. switch meta.SessionStatus {
  282. case SessionStatusKeepAlive:
  283. drainData = true
  284. case SessionStatusEnd:
  285. if s, found := w.sessionManager.Get(meta.SessionID); found {
  286. s.CloseUplink()
  287. s.output.Close()
  288. }
  289. drainData = true
  290. case SessionStatusNew:
  291. log.Trace(newError("received request for ", meta.Target))
  292. inboundRay, err := w.dispatcher.Dispatch(ctx, meta.Target)
  293. if err != nil {
  294. log.Trace(newError("failed to dispatch request.").Base(err))
  295. drainData = true
  296. break
  297. }
  298. s := &Session{
  299. input: inboundRay.InboundOutput(),
  300. output: inboundRay.InboundInput(),
  301. parent: w.sessionManager,
  302. ID: meta.SessionID,
  303. }
  304. w.sessionManager.Add(s)
  305. go handle(ctx, s, w.outboundRay.OutboundOutput())
  306. if !meta.Option.Has(OptionData) {
  307. break
  308. }
  309. if err := pipe(reader, s.output); err != nil {
  310. log.Trace(newError("failed to read data").Base(err))
  311. break L
  312. }
  313. case SessionStatusKeep:
  314. if !meta.Option.Has(OptionData) {
  315. break
  316. }
  317. if s, found := w.sessionManager.Get(meta.SessionID); found {
  318. if err := pipe(reader, s.output); err != nil {
  319. log.Trace(newError("failed to read data").Base(err))
  320. break L
  321. }
  322. }
  323. }
  324. if meta.Option.Has(OptionData) && drainData {
  325. if err := drain(reader); err != nil {
  326. log.Trace(newError("failed to drain data").Base(err))
  327. break
  328. }
  329. }
  330. }
  331. }