mux.go 9.1 KB

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