mux.go 9.1 KB

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