mux.go 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456
  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 manager interface {
  21. remove(id uint16)
  22. }
  23. type session struct {
  24. sync.Mutex
  25. input ray.InputStream
  26. output ray.OutputStream
  27. parent manager
  28. id uint16
  29. uplinkClosed bool
  30. downlinkClosed bool
  31. }
  32. func (s *session) closeUplink() {
  33. var allDone bool
  34. s.Lock()
  35. s.uplinkClosed = true
  36. allDone = s.uplinkClosed && s.downlinkClosed
  37. s.Unlock()
  38. if allDone {
  39. s.parent.remove(s.id)
  40. }
  41. }
  42. func (s *session) closeDownlink() {
  43. var allDone bool
  44. s.Lock()
  45. s.downlinkClosed = true
  46. allDone = s.uplinkClosed && s.downlinkClosed
  47. s.Unlock()
  48. if allDone {
  49. s.parent.remove(s.id)
  50. }
  51. }
  52. type ClientManager struct {
  53. access sync.Mutex
  54. clients []*Client
  55. proxy proxy.Outbound
  56. dialer proxy.Dialer
  57. config *proxyman.MultiplexingConfig
  58. }
  59. func NewClientManager(p proxy.Outbound, d proxy.Dialer, c *proxyman.MultiplexingConfig) *ClientManager {
  60. return &ClientManager{
  61. proxy: p,
  62. dialer: d,
  63. config: c,
  64. }
  65. }
  66. func (m *ClientManager) Dispatch(ctx context.Context, outboundRay ray.OutboundRay) error {
  67. m.access.Lock()
  68. defer m.access.Unlock()
  69. for _, client := range m.clients {
  70. if client.Dispatch(ctx, outboundRay) {
  71. return nil
  72. }
  73. }
  74. client, err := NewClient(m.proxy, m.dialer, m)
  75. if err != nil {
  76. return newError("failed to create client").Base(err)
  77. }
  78. m.clients = append(m.clients, client)
  79. client.Dispatch(ctx, outboundRay)
  80. return nil
  81. }
  82. func (m *ClientManager) onClientFinish() {
  83. m.access.Lock()
  84. defer m.access.Unlock()
  85. if len(m.clients) < 10 {
  86. return
  87. }
  88. activeClients := make([]*Client, 0, len(m.clients))
  89. for _, client := range m.clients {
  90. if !client.Closed() {
  91. activeClients = append(activeClients, client)
  92. }
  93. }
  94. m.clients = activeClients
  95. }
  96. type Client struct {
  97. access sync.RWMutex
  98. count uint16
  99. sessions map[uint16]*session
  100. inboundRay ray.InboundRay
  101. ctx context.Context
  102. cancel context.CancelFunc
  103. manager *ClientManager
  104. session2Remove chan uint16
  105. concurrency uint32
  106. }
  107. var muxCoolDestination = net.TCPDestination(net.DomainAddress("v1.mux.cool"), net.Port(9527))
  108. func NewClient(p proxy.Outbound, dialer proxy.Dialer, m *ClientManager) (*Client, error) {
  109. ctx, cancel := context.WithCancel(context.Background())
  110. ctx = proxy.ContextWithTarget(ctx, muxCoolDestination)
  111. pipe := ray.NewRay(ctx)
  112. go p.Process(ctx, pipe, dialer)
  113. c := &Client{
  114. sessions: make(map[uint16]*session, 256),
  115. inboundRay: pipe,
  116. ctx: ctx,
  117. cancel: cancel,
  118. manager: m,
  119. count: 0,
  120. session2Remove: make(chan uint16, 16),
  121. concurrency: m.config.Concurrency,
  122. }
  123. go c.fetchOutput()
  124. go c.monitor()
  125. return c, nil
  126. }
  127. func (m *Client) remove(id uint16) {
  128. select {
  129. case m.session2Remove <- id:
  130. default:
  131. // Probably not gonna happen.
  132. }
  133. }
  134. func (m *Client) Closed() bool {
  135. select {
  136. case <-m.ctx.Done():
  137. return true
  138. default:
  139. return false
  140. }
  141. }
  142. func (m *Client) monitor() {
  143. defer m.manager.onClientFinish()
  144. for {
  145. select {
  146. case <-m.ctx.Done():
  147. m.cleanup()
  148. return
  149. case id := <-m.session2Remove:
  150. m.access.Lock()
  151. delete(m.sessions, id)
  152. if len(m.sessions) == 0 {
  153. m.cancel()
  154. }
  155. m.access.Unlock()
  156. }
  157. }
  158. }
  159. func (m *Client) cleanup() {
  160. m.access.Lock()
  161. defer m.access.Unlock()
  162. m.inboundRay.InboundInput().Close()
  163. m.inboundRay.InboundOutput().CloseError()
  164. for _, s := range m.sessions {
  165. s.closeUplink()
  166. s.closeDownlink()
  167. s.output.CloseError()
  168. }
  169. }
  170. func fetchInput(ctx context.Context, s *session, output buf.Writer) {
  171. dest, _ := proxy.TargetFromContext(ctx)
  172. writer := &Writer{
  173. dest: dest,
  174. id: s.id,
  175. writer: output,
  176. }
  177. defer writer.Close()
  178. defer s.closeUplink()
  179. log.Trace(newError("dispatching request to ", dest))
  180. data, _ := s.input.ReadTimeout(time.Millisecond * 500)
  181. if data != nil {
  182. if err := writer.Write(data); err != nil {
  183. log.Trace(newError("failed to write first payload").Base(err))
  184. return
  185. }
  186. }
  187. if err := buf.PipeUntilEOF(signal.BackgroundTimer(), s.input, writer); err != nil {
  188. log.Trace(newError("failed to fetch all input").Base(err))
  189. }
  190. }
  191. func waitForDone(ctx context.Context, s *session) {
  192. <-ctx.Done()
  193. s.closeUplink()
  194. s.closeDownlink()
  195. s.output.Close()
  196. }
  197. func (m *Client) Dispatch(ctx context.Context, outboundRay ray.OutboundRay) bool {
  198. m.access.Lock()
  199. defer m.access.Unlock()
  200. if len(m.sessions) >= int(m.concurrency) {
  201. return false
  202. }
  203. if m.count >= maxTotal {
  204. return false
  205. }
  206. select {
  207. case <-m.ctx.Done():
  208. return false
  209. default:
  210. }
  211. m.count++
  212. id := m.count
  213. s := &session{
  214. input: outboundRay.OutboundInput(),
  215. output: outboundRay.OutboundOutput(),
  216. parent: m,
  217. id: id,
  218. }
  219. m.sessions[id] = s
  220. go fetchInput(ctx, s, m.inboundRay.InboundInput())
  221. go waitForDone(ctx, s)
  222. return true
  223. }
  224. func drain(reader *Reader) error {
  225. for {
  226. data, more, err := reader.Read()
  227. if err != nil {
  228. return err
  229. }
  230. data.Release()
  231. if !more {
  232. return nil
  233. }
  234. }
  235. }
  236. func pipe(reader *Reader, writer buf.Writer) error {
  237. for {
  238. data, more, err := reader.Read()
  239. if err != nil {
  240. return err
  241. }
  242. if err := writer.Write(data); err != nil {
  243. return err
  244. }
  245. if !more {
  246. return nil
  247. }
  248. }
  249. }
  250. func (m *Client) fetchOutput() {
  251. defer m.cancel()
  252. reader := NewReader(m.inboundRay.InboundOutput())
  253. for {
  254. meta, err := reader.ReadMetadata()
  255. if err != nil {
  256. log.Trace(newError("failed to read metadata").Base(err))
  257. break
  258. }
  259. if meta.SessionStatus == SessionStatusKeepAlive {
  260. if meta.Option.Has(OptionData) {
  261. if err := drain(reader); err != nil {
  262. log.Trace(newError("failed to read data").Base(err))
  263. break
  264. }
  265. }
  266. continue
  267. }
  268. m.access.RLock()
  269. s, found := m.sessions[meta.SessionID]
  270. m.access.RUnlock()
  271. if found && meta.SessionStatus == SessionStatusEnd {
  272. s.closeDownlink()
  273. s.output.Close()
  274. }
  275. if !meta.Option.Has(OptionData) {
  276. continue
  277. }
  278. if found {
  279. err = pipe(reader, s.output)
  280. } else {
  281. err = drain(reader)
  282. }
  283. if err != nil {
  284. log.Trace(newError("failed to read data").Base(err))
  285. break
  286. }
  287. }
  288. }
  289. type Server struct {
  290. dispatcher dispatcher.Interface
  291. }
  292. func NewServer(ctx context.Context) *Server {
  293. s := &Server{}
  294. space := app.SpaceFromContext(ctx)
  295. space.OnInitialize(func() error {
  296. d := dispatcher.FromSpace(space)
  297. if d == nil {
  298. return newError("no dispatcher in space")
  299. }
  300. s.dispatcher = d
  301. return nil
  302. })
  303. return s
  304. }
  305. func (s *Server) Dispatch(ctx context.Context, dest net.Destination) (ray.InboundRay, error) {
  306. if dest != muxCoolDestination {
  307. return s.dispatcher.Dispatch(ctx, dest)
  308. }
  309. ray := ray.NewRay(ctx)
  310. worker := &ServerWorker{
  311. dispatcher: s.dispatcher,
  312. outboundRay: ray,
  313. sessions: make(map[uint16]*session),
  314. }
  315. go worker.run(ctx)
  316. return ray, nil
  317. }
  318. type ServerWorker struct {
  319. dispatcher dispatcher.Interface
  320. outboundRay ray.OutboundRay
  321. sessions map[uint16]*session
  322. access sync.RWMutex
  323. }
  324. func (w *ServerWorker) remove(id uint16) {
  325. w.access.Lock()
  326. delete(w.sessions, id)
  327. w.access.Unlock()
  328. }
  329. func handle(ctx context.Context, s *session, output buf.Writer) {
  330. writer := NewResponseWriter(s.id, output)
  331. if err := buf.PipeUntilEOF(signal.BackgroundTimer(), s.input, writer); err != nil {
  332. log.Trace(newError("session ", s.id, " ends: ").Base(err))
  333. }
  334. writer.Close()
  335. s.closeDownlink()
  336. }
  337. func (w *ServerWorker) run(ctx context.Context) {
  338. input := w.outboundRay.OutboundInput()
  339. reader := NewReader(input)
  340. for {
  341. select {
  342. case <-ctx.Done():
  343. return
  344. default:
  345. }
  346. meta, err := reader.ReadMetadata()
  347. if err != nil {
  348. log.Trace(newError("failed to read metadata").Base(err))
  349. return
  350. }
  351. if meta.SessionStatus == SessionStatusKeepAlive {
  352. if meta.Option.Has(OptionData) {
  353. if err := drain(reader); err != nil {
  354. log.Trace(newError("failed to read data").Base(err))
  355. break
  356. }
  357. }
  358. continue
  359. }
  360. w.access.RLock()
  361. s, found := w.sessions[meta.SessionID]
  362. w.access.RUnlock()
  363. if found && meta.SessionStatus == SessionStatusEnd {
  364. s.closeUplink()
  365. s.output.Close()
  366. }
  367. if meta.SessionStatus == SessionStatusNew {
  368. log.Trace(newError("received request for ", meta.Target))
  369. inboundRay, err := w.dispatcher.Dispatch(ctx, meta.Target)
  370. if err != nil {
  371. log.Trace(newError("failed to dispatch request.").Base(err))
  372. continue
  373. }
  374. s = &session{
  375. input: inboundRay.InboundOutput(),
  376. output: inboundRay.InboundInput(),
  377. parent: w,
  378. id: meta.SessionID,
  379. }
  380. w.access.Lock()
  381. w.sessions[meta.SessionID] = s
  382. w.access.Unlock()
  383. go handle(ctx, s, w.outboundRay.OutboundOutput())
  384. }
  385. if !meta.Option.Has(OptionData) {
  386. continue
  387. }
  388. if s != nil {
  389. err = pipe(reader, s.output)
  390. } else {
  391. err = drain(reader)
  392. }
  393. if err != nil {
  394. log.Trace(newError("failed to read data").Base(err))
  395. break
  396. }
  397. }
  398. }