mux.go 9.0 KB

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