mux.go 8.5 KB

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