mux.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  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.sessionManager.Close()
  106. m.inboundRay.InboundInput().Close()
  107. m.inboundRay.InboundOutput().CloseError()
  108. return
  109. case <-time.After(time.Second * 6):
  110. size := m.sessionManager.Size()
  111. if size == 0 && m.sessionManager.CloseIfNoSession() {
  112. m.cancel()
  113. }
  114. }
  115. }
  116. }
  117. func fetchInput(ctx context.Context, s *Session, output buf.Writer) {
  118. dest, _ := proxy.TargetFromContext(ctx)
  119. writer := &Writer{
  120. dest: dest,
  121. id: s.ID,
  122. writer: output,
  123. }
  124. defer writer.Close()
  125. defer s.CloseUplink()
  126. log.Trace(newError("dispatching request to ", dest))
  127. data, _ := s.input.ReadTimeout(time.Millisecond * 500)
  128. if data != nil {
  129. if err := writer.Write(data); err != nil {
  130. log.Trace(newError("failed to write first payload").Base(err))
  131. return
  132. }
  133. }
  134. if err := buf.PipeUntilEOF(signal.BackgroundTimer(), s.input, writer); err != nil {
  135. log.Trace(newError("failed to fetch all input").Base(err))
  136. }
  137. }
  138. func (m *Client) Dispatch(ctx context.Context, outboundRay ray.OutboundRay) bool {
  139. numSession := m.sessionManager.Size()
  140. if numSession >= int(m.concurrency) || numSession >= maxTotal {
  141. return false
  142. }
  143. select {
  144. case <-m.ctx.Done():
  145. return false
  146. default:
  147. }
  148. s := m.sessionManager.Allocate()
  149. if s == nil {
  150. return false
  151. }
  152. s.input = outboundRay.OutboundInput()
  153. s.output = outboundRay.OutboundOutput()
  154. go fetchInput(ctx, s, m.inboundRay.InboundInput())
  155. return true
  156. }
  157. func drain(reader *Reader) error {
  158. for {
  159. data, more, err := reader.Read()
  160. if err != nil {
  161. return err
  162. }
  163. data.Release()
  164. if !more {
  165. return nil
  166. }
  167. }
  168. }
  169. func pipe(reader *Reader, writer buf.Writer) error {
  170. for {
  171. data, more, err := reader.Read()
  172. if err != nil {
  173. return err
  174. }
  175. if err := writer.Write(data); err != nil {
  176. return err
  177. }
  178. if !more {
  179. return nil
  180. }
  181. }
  182. }
  183. func (m *Client) fetchOutput() {
  184. defer m.cancel()
  185. reader := NewReader(m.inboundRay.InboundOutput())
  186. L:
  187. for {
  188. meta, err := reader.ReadMetadata()
  189. if err != nil {
  190. log.Trace(newError("failed to read metadata").Base(err))
  191. break
  192. }
  193. var drainData bool
  194. switch meta.SessionStatus {
  195. case SessionStatusKeepAlive:
  196. drainData = true
  197. case SessionStatusEnd:
  198. if s, found := m.sessionManager.Get(meta.SessionID); found {
  199. s.CloseDownlink()
  200. s.output.Close()
  201. }
  202. drainData = true
  203. case SessionStatusNew:
  204. drainData = true
  205. case SessionStatusKeep:
  206. if !meta.Option.Has(OptionData) {
  207. break
  208. }
  209. if s, found := m.sessionManager.Get(meta.SessionID); found {
  210. if err := pipe(reader, s.output); err != nil {
  211. log.Trace(newError("failed to pipe data").Base(err))
  212. break L
  213. }
  214. }
  215. }
  216. if drainData && meta.Option.Has(OptionData) {
  217. if err := drain(reader); err != nil {
  218. log.Trace(newError("failed to drain data").Base(err))
  219. break
  220. }
  221. }
  222. }
  223. }
  224. type Server struct {
  225. dispatcher dispatcher.Interface
  226. }
  227. func NewServer(ctx context.Context) *Server {
  228. s := &Server{}
  229. space := app.SpaceFromContext(ctx)
  230. space.OnInitialize(func() error {
  231. d := dispatcher.FromSpace(space)
  232. if d == nil {
  233. return newError("no dispatcher in space")
  234. }
  235. s.dispatcher = d
  236. return nil
  237. })
  238. return s
  239. }
  240. func (s *Server) Dispatch(ctx context.Context, dest net.Destination) (ray.InboundRay, error) {
  241. if dest != muxCoolDestination {
  242. return s.dispatcher.Dispatch(ctx, dest)
  243. }
  244. ray := ray.NewRay(ctx)
  245. worker := &ServerWorker{
  246. dispatcher: s.dispatcher,
  247. outboundRay: ray,
  248. sessionManager: NewSessionManager(),
  249. }
  250. go worker.run(ctx)
  251. return ray, nil
  252. }
  253. type ServerWorker struct {
  254. dispatcher dispatcher.Interface
  255. outboundRay ray.OutboundRay
  256. sessionManager *SessionManager
  257. }
  258. func handle(ctx context.Context, s *Session, output buf.Writer) {
  259. writer := NewResponseWriter(s.ID, output)
  260. if err := buf.PipeUntilEOF(signal.BackgroundTimer(), s.input, writer); err != nil {
  261. log.Trace(newError("session ", s.ID, " ends: ").Base(err))
  262. }
  263. writer.Close()
  264. s.CloseDownlink()
  265. }
  266. func (w *ServerWorker) run(ctx context.Context) {
  267. input := w.outboundRay.OutboundInput()
  268. reader := NewReader(input)
  269. defer w.sessionManager.Close()
  270. L:
  271. for {
  272. select {
  273. case <-ctx.Done():
  274. return
  275. default:
  276. }
  277. meta, err := reader.ReadMetadata()
  278. if err != nil {
  279. log.Trace(newError("failed to read metadata").Base(err))
  280. return
  281. }
  282. var drainData bool
  283. switch meta.SessionStatus {
  284. case SessionStatusKeepAlive:
  285. drainData = true
  286. case SessionStatusEnd:
  287. if s, found := w.sessionManager.Get(meta.SessionID); found {
  288. s.CloseUplink()
  289. s.output.Close()
  290. }
  291. drainData = true
  292. case SessionStatusNew:
  293. log.Trace(newError("received request for ", meta.Target))
  294. inboundRay, err := w.dispatcher.Dispatch(ctx, meta.Target)
  295. if err != nil {
  296. log.Trace(newError("failed to dispatch request.").Base(err))
  297. drainData = true
  298. break
  299. }
  300. s := &Session{
  301. input: inboundRay.InboundOutput(),
  302. output: inboundRay.InboundInput(),
  303. parent: w.sessionManager,
  304. ID: meta.SessionID,
  305. }
  306. w.sessionManager.Add(s)
  307. go handle(ctx, s, w.outboundRay.OutboundOutput())
  308. if !meta.Option.Has(OptionData) {
  309. break
  310. }
  311. if err := pipe(reader, s.output); err != nil {
  312. log.Trace(newError("failed to read data").Base(err))
  313. break L
  314. }
  315. case SessionStatusKeep:
  316. if !meta.Option.Has(OptionData) {
  317. break
  318. }
  319. if s, found := w.sessionManager.Get(meta.SessionID); found {
  320. if err := pipe(reader, s.output); err != nil {
  321. log.Trace(newError("failed to read data").Base(err))
  322. break L
  323. }
  324. }
  325. }
  326. if meta.Option.Has(OptionData) && drainData {
  327. if err := drain(reader); err != nil {
  328. log.Trace(newError("failed to drain data").Base(err))
  329. break
  330. }
  331. }
  332. }
  333. }