mux.go 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  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. data, err := reader.Read()
  159. if err != nil {
  160. return err
  161. }
  162. data.Release()
  163. return nil
  164. }
  165. func pipe(reader *Reader, writer buf.Writer) error {
  166. data, err := reader.Read()
  167. if err != nil {
  168. return err
  169. }
  170. return writer.Write(data)
  171. }
  172. func (m *Client) handleStatueKeepAlive(meta *FrameMetadata, reader *Reader) error {
  173. if meta.Option.Has(OptionData) {
  174. return drain(reader)
  175. }
  176. return nil
  177. }
  178. func (m *Client) handleStatusNew(meta *FrameMetadata, reader *Reader) error {
  179. if meta.Option.Has(OptionData) {
  180. return drain(reader)
  181. }
  182. return nil
  183. }
  184. func (m *Client) handleStatusKeep(meta *FrameMetadata, reader *Reader) error {
  185. if !meta.Option.Has(OptionData) {
  186. return nil
  187. }
  188. if s, found := m.sessionManager.Get(meta.SessionID); found {
  189. return pipe(reader, s.output)
  190. }
  191. return drain(reader)
  192. }
  193. func (m *Client) handleStatusEnd(meta *FrameMetadata, reader *Reader) error {
  194. if s, found := m.sessionManager.Get(meta.SessionID); found {
  195. s.CloseDownlink()
  196. s.output.Close()
  197. }
  198. if meta.Option.Has(OptionData) {
  199. return drain(reader)
  200. }
  201. return nil
  202. }
  203. func (m *Client) fetchOutput() {
  204. defer m.cancel()
  205. reader := NewReader(m.inboundRay.InboundOutput())
  206. for {
  207. meta, err := reader.ReadMetadata()
  208. if err != nil {
  209. log.Trace(newError("failed to read metadata").Base(err))
  210. break
  211. }
  212. switch meta.SessionStatus {
  213. case SessionStatusKeepAlive:
  214. err = m.handleStatueKeepAlive(meta, reader)
  215. case SessionStatusEnd:
  216. err = m.handleStatusEnd(meta, reader)
  217. case SessionStatusNew:
  218. err = m.handleStatusNew(meta, reader)
  219. case SessionStatusKeep:
  220. err = m.handleStatusKeep(meta, reader)
  221. default:
  222. log.Trace(newError("unknown status: ", meta.SessionStatus).AtWarning())
  223. return
  224. }
  225. if err != nil {
  226. log.Trace(newError("failed to process data").Base(err))
  227. return
  228. }
  229. }
  230. }
  231. type Server struct {
  232. dispatcher dispatcher.Interface
  233. }
  234. func NewServer(ctx context.Context) *Server {
  235. s := &Server{}
  236. space := app.SpaceFromContext(ctx)
  237. space.OnInitialize(func() error {
  238. d := dispatcher.FromSpace(space)
  239. if d == nil {
  240. return newError("no dispatcher in space")
  241. }
  242. s.dispatcher = d
  243. return nil
  244. })
  245. return s
  246. }
  247. func (s *Server) Dispatch(ctx context.Context, dest net.Destination) (ray.InboundRay, error) {
  248. if dest != muxCoolDestination {
  249. return s.dispatcher.Dispatch(ctx, dest)
  250. }
  251. ray := ray.NewRay(ctx)
  252. worker := &ServerWorker{
  253. dispatcher: s.dispatcher,
  254. outboundRay: ray,
  255. sessionManager: NewSessionManager(),
  256. }
  257. go worker.run(ctx)
  258. return ray, nil
  259. }
  260. type ServerWorker struct {
  261. dispatcher dispatcher.Interface
  262. outboundRay ray.OutboundRay
  263. sessionManager *SessionManager
  264. }
  265. func handle(ctx context.Context, s *Session, output buf.Writer) {
  266. writer := NewResponseWriter(s.ID, output)
  267. if err := buf.PipeUntilEOF(signal.BackgroundTimer(), s.input, writer); err != nil {
  268. log.Trace(newError("session ", s.ID, " ends: ").Base(err))
  269. }
  270. writer.Close()
  271. s.CloseDownlink()
  272. }
  273. func (w *ServerWorker) handleStatusKeepAlive(meta *FrameMetadata, reader *Reader) error {
  274. if meta.Option.Has(OptionData) {
  275. return drain(reader)
  276. }
  277. return nil
  278. }
  279. func (w *ServerWorker) handleStatusNew(ctx context.Context, meta *FrameMetadata, reader *Reader) error {
  280. log.Trace(newError("received request for ", meta.Target))
  281. inboundRay, err := w.dispatcher.Dispatch(ctx, meta.Target)
  282. if err != nil {
  283. if meta.Option.Has(OptionData) {
  284. drain(reader)
  285. }
  286. return newError("failed to dispatch request.").Base(err)
  287. }
  288. s := &Session{
  289. input: inboundRay.InboundOutput(),
  290. output: inboundRay.InboundInput(),
  291. parent: w.sessionManager,
  292. ID: meta.SessionID,
  293. }
  294. w.sessionManager.Add(s)
  295. go handle(ctx, s, w.outboundRay.OutboundOutput())
  296. if meta.Option.Has(OptionData) {
  297. return pipe(reader, s.output)
  298. }
  299. return nil
  300. }
  301. func (w *ServerWorker) handleStatusKeep(meta *FrameMetadata, reader *Reader) error {
  302. if !meta.Option.Has(OptionData) {
  303. return nil
  304. }
  305. if s, found := w.sessionManager.Get(meta.SessionID); found {
  306. return pipe(reader, s.output)
  307. }
  308. return drain(reader)
  309. }
  310. func (w *ServerWorker) handleStatusEnd(meta *FrameMetadata, reader *Reader) error {
  311. if s, found := w.sessionManager.Get(meta.SessionID); found {
  312. s.CloseUplink()
  313. s.output.Close()
  314. }
  315. if meta.Option.Has(OptionData) {
  316. return drain(reader)
  317. }
  318. return nil
  319. }
  320. func (w *ServerWorker) run(ctx context.Context) {
  321. input := w.outboundRay.OutboundInput()
  322. reader := NewReader(input)
  323. defer w.sessionManager.Close()
  324. for {
  325. select {
  326. case <-ctx.Done():
  327. return
  328. default:
  329. }
  330. meta, err := reader.ReadMetadata()
  331. if err != nil {
  332. log.Trace(newError("failed to read metadata").Base(err))
  333. return
  334. }
  335. switch meta.SessionStatus {
  336. case SessionStatusKeepAlive:
  337. err = w.handleStatusKeepAlive(meta, reader)
  338. case SessionStatusEnd:
  339. err = w.handleStatusEnd(meta, reader)
  340. case SessionStatusNew:
  341. err = w.handleStatusNew(ctx, meta, reader)
  342. case SessionStatusKeep:
  343. err = w.handleStatusKeep(meta, reader)
  344. default:
  345. log.Trace(newError("unknown status: ", meta.SessionStatus).AtWarning())
  346. return
  347. }
  348. if err != nil {
  349. log.Trace(newError("failed to process data").Base(err))
  350. return
  351. }
  352. }
  353. }