mux.go 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  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 {
  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 := &Session{
  149. input: outboundRay.OutboundInput(),
  150. output: outboundRay.OutboundOutput(),
  151. parent: m.sessionManager,
  152. }
  153. m.sessionManager.Allocate(s)
  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. for {
  187. meta, err := reader.ReadMetadata()
  188. if err != nil {
  189. log.Trace(newError("failed to read metadata").Base(err))
  190. break
  191. }
  192. if meta.SessionStatus == SessionStatusKeepAlive {
  193. if meta.Option.Has(OptionData) {
  194. if err := drain(reader); err != nil {
  195. log.Trace(newError("failed to read data").Base(err))
  196. break
  197. }
  198. }
  199. continue
  200. }
  201. s, found := m.sessionManager.Get(meta.SessionID)
  202. if found && meta.SessionStatus == SessionStatusEnd {
  203. s.CloseDownlink()
  204. s.output.Close()
  205. }
  206. if !meta.Option.Has(OptionData) {
  207. continue
  208. }
  209. if found {
  210. err = pipe(reader, s.output)
  211. } else {
  212. err = drain(reader)
  213. }
  214. if err != nil {
  215. log.Trace(newError("failed to read data").Base(err))
  216. break
  217. }
  218. }
  219. }
  220. type Server struct {
  221. dispatcher dispatcher.Interface
  222. }
  223. func NewServer(ctx context.Context) *Server {
  224. s := &Server{}
  225. space := app.SpaceFromContext(ctx)
  226. space.OnInitialize(func() error {
  227. d := dispatcher.FromSpace(space)
  228. if d == nil {
  229. return newError("no dispatcher in space")
  230. }
  231. s.dispatcher = d
  232. return nil
  233. })
  234. return s
  235. }
  236. func (s *Server) Dispatch(ctx context.Context, dest net.Destination) (ray.InboundRay, error) {
  237. if dest != muxCoolDestination {
  238. return s.dispatcher.Dispatch(ctx, dest)
  239. }
  240. ray := ray.NewRay(ctx)
  241. worker := &ServerWorker{
  242. dispatcher: s.dispatcher,
  243. outboundRay: ray,
  244. sessionManager: NewSessionManager(),
  245. }
  246. go worker.run(ctx)
  247. return ray, nil
  248. }
  249. type ServerWorker struct {
  250. dispatcher dispatcher.Interface
  251. outboundRay ray.OutboundRay
  252. sessionManager *SessionManager
  253. }
  254. func handle(ctx context.Context, s *Session, output buf.Writer) {
  255. writer := NewResponseWriter(s.ID, output)
  256. if err := buf.PipeUntilEOF(signal.BackgroundTimer(), s.input, writer); err != nil {
  257. log.Trace(newError("session ", s.ID, " ends: ").Base(err))
  258. }
  259. writer.Close()
  260. s.CloseDownlink()
  261. }
  262. func (w *ServerWorker) run(ctx context.Context) {
  263. input := w.outboundRay.OutboundInput()
  264. reader := NewReader(input)
  265. for {
  266. select {
  267. case <-ctx.Done():
  268. return
  269. default:
  270. }
  271. meta, err := reader.ReadMetadata()
  272. if err != nil {
  273. log.Trace(newError("failed to read metadata").Base(err))
  274. return
  275. }
  276. if meta.SessionStatus == SessionStatusKeepAlive {
  277. if meta.Option.Has(OptionData) {
  278. if err := drain(reader); err != nil {
  279. log.Trace(newError("failed to read data").Base(err))
  280. break
  281. }
  282. }
  283. continue
  284. }
  285. s, found := w.sessionManager.Get(meta.SessionID)
  286. if found && meta.SessionStatus == SessionStatusEnd {
  287. s.CloseUplink()
  288. s.output.Close()
  289. }
  290. if meta.SessionStatus == 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. continue
  296. }
  297. s = &Session{
  298. input: inboundRay.InboundOutput(),
  299. output: inboundRay.InboundInput(),
  300. parent: w.sessionManager,
  301. ID: meta.SessionID,
  302. }
  303. w.sessionManager.Add(s)
  304. go handle(ctx, s, w.outboundRay.OutboundOutput())
  305. }
  306. if !meta.Option.Has(OptionData) {
  307. continue
  308. }
  309. if s != nil {
  310. err = pipe(reader, s.output)
  311. } else {
  312. err = drain(reader)
  313. }
  314. if err != nil {
  315. log.Trace(newError("failed to read data").Base(err))
  316. break
  317. }
  318. }
  319. }