mux.go 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  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.Base(err).Message("Proxyman|Mux|ClientManager: Failed to create client.")
  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. for {
  140. select {
  141. case <-m.ctx.Done():
  142. m.cleanup()
  143. return
  144. case id := <-m.session2Remove:
  145. m.access.Lock()
  146. delete(m.sessions, id)
  147. m.access.Unlock()
  148. }
  149. }
  150. }
  151. func (m *Client) cleanup() {
  152. m.access.Lock()
  153. defer m.access.Unlock()
  154. for _, s := range m.sessions {
  155. s.closeUplink()
  156. s.closeDownlink()
  157. s.output.CloseError()
  158. }
  159. }
  160. func fetchInput(ctx context.Context, s *session, output buf.Writer) {
  161. dest, _ := proxy.TargetFromContext(ctx)
  162. writer := &Writer{
  163. dest: dest,
  164. id: s.id,
  165. writer: output,
  166. }
  167. defer writer.Close()
  168. defer s.closeUplink()
  169. log.Info("Proxyman|Mux|Client: Dispatching request to ", dest)
  170. data, _ := s.input.ReadTimeout(time.Millisecond * 500)
  171. if data != nil {
  172. if err := writer.Write(data); err != nil {
  173. log.Info("Proxyman|Mux|Client: Failed to write first payload: ", err)
  174. return
  175. }
  176. }
  177. if err := buf.PipeUntilEOF(signal.BackgroundTimer(), s.input, writer); err != nil {
  178. log.Info("Proxyman|Mux|Client: Failed to fetch all input: ", err)
  179. }
  180. }
  181. func waitForDone(ctx context.Context, s *session) {
  182. <-ctx.Done()
  183. s.closeUplink()
  184. s.closeDownlink()
  185. s.output.Close()
  186. }
  187. func (m *Client) Dispatch(ctx context.Context, outboundRay ray.OutboundRay) bool {
  188. m.access.Lock()
  189. defer m.access.Unlock()
  190. if len(m.sessions) >= maxParallel {
  191. return false
  192. }
  193. if m.count >= maxTotal {
  194. return false
  195. }
  196. select {
  197. case <-m.ctx.Done():
  198. return false
  199. default:
  200. }
  201. m.count++
  202. id := m.count
  203. s := &session{
  204. input: outboundRay.OutboundInput(),
  205. output: outboundRay.OutboundOutput(),
  206. parent: m,
  207. id: id,
  208. }
  209. m.sessions[id] = s
  210. go fetchInput(ctx, s, m.inboundRay.InboundInput())
  211. go waitForDone(ctx, s)
  212. return true
  213. }
  214. func drain(reader *Reader) error {
  215. for {
  216. data, more, err := reader.Read()
  217. if err != nil {
  218. return err
  219. }
  220. data.Release()
  221. if !more {
  222. return nil
  223. }
  224. }
  225. }
  226. func pipe(reader *Reader, writer buf.Writer) error {
  227. for {
  228. data, more, err := reader.Read()
  229. if err != nil {
  230. return err
  231. }
  232. if err := writer.Write(data); err != nil {
  233. return err
  234. }
  235. if !more {
  236. return nil
  237. }
  238. }
  239. }
  240. func (m *Client) fetchOutput() {
  241. defer m.cancel()
  242. reader := NewReader(m.inboundRay.InboundOutput())
  243. for {
  244. meta, err := reader.ReadMetadata()
  245. if err != nil {
  246. log.Info("Proxyman|Mux|Client: Failed to read metadata: ", err)
  247. break
  248. }
  249. m.access.RLock()
  250. s, found := m.sessions[meta.SessionID]
  251. m.access.RUnlock()
  252. if found && meta.SessionStatus == SessionStatusEnd {
  253. s.closeDownlink()
  254. s.output.Close()
  255. }
  256. if !meta.Option.Has(OptionData) {
  257. continue
  258. }
  259. if found {
  260. err = pipe(reader, s.output)
  261. } else {
  262. err = drain(reader)
  263. }
  264. if err != nil {
  265. log.Info("Proxyman|Mux|Client: Failed to read data: ", err)
  266. break
  267. }
  268. }
  269. }
  270. type Server struct {
  271. dispatcher dispatcher.Interface
  272. }
  273. func NewServer(ctx context.Context) *Server {
  274. s := &Server{}
  275. space := app.SpaceFromContext(ctx)
  276. space.OnInitialize(func() error {
  277. d := dispatcher.FromSpace(space)
  278. if d == nil {
  279. return errors.New("Proxyman|Mux: No dispatcher in space.")
  280. }
  281. s.dispatcher = d
  282. return nil
  283. })
  284. return s
  285. }
  286. func (s *Server) Dispatch(ctx context.Context, dest net.Destination) (ray.InboundRay, error) {
  287. if dest != muxCoolDestination {
  288. return s.dispatcher.Dispatch(ctx, dest)
  289. }
  290. ray := ray.NewRay(ctx)
  291. worker := &ServerWorker{
  292. dispatcher: s.dispatcher,
  293. outboundRay: ray,
  294. sessions: make(map[uint16]*session),
  295. }
  296. go worker.run(ctx)
  297. return ray, nil
  298. }
  299. type ServerWorker struct {
  300. dispatcher dispatcher.Interface
  301. outboundRay ray.OutboundRay
  302. sessions map[uint16]*session
  303. access sync.RWMutex
  304. }
  305. func (w *ServerWorker) remove(id uint16) {
  306. w.access.Lock()
  307. delete(w.sessions, id)
  308. w.access.Unlock()
  309. }
  310. func handle(ctx context.Context, s *session, output buf.Writer) {
  311. writer := NewResponseWriter(s.id, output)
  312. if err := buf.PipeUntilEOF(signal.BackgroundTimer(), s.input, writer); err != nil {
  313. log.Info("Proxyman|Mux|ServerWorker: Session ", s.id, " ends: ", err)
  314. }
  315. writer.Close()
  316. s.closeDownlink()
  317. }
  318. func (w *ServerWorker) run(ctx context.Context) {
  319. input := w.outboundRay.OutboundInput()
  320. reader := NewReader(input)
  321. for {
  322. select {
  323. case <-ctx.Done():
  324. return
  325. default:
  326. }
  327. meta, err := reader.ReadMetadata()
  328. if err != nil {
  329. return
  330. }
  331. w.access.RLock()
  332. s, found := w.sessions[meta.SessionID]
  333. w.access.RUnlock()
  334. if found && meta.SessionStatus == SessionStatusEnd {
  335. s.closeUplink()
  336. s.output.Close()
  337. }
  338. if meta.SessionStatus == SessionStatusNew {
  339. log.Info("Proxyman|Mux|Server: Received request for ", meta.Target)
  340. inboundRay, err := w.dispatcher.Dispatch(ctx, meta.Target)
  341. if err != nil {
  342. log.Info("Proxyman|Mux: Failed to dispatch request: ", err)
  343. continue
  344. }
  345. s = &session{
  346. input: inboundRay.InboundOutput(),
  347. output: inboundRay.InboundInput(),
  348. parent: w,
  349. id: meta.SessionID,
  350. }
  351. w.access.Lock()
  352. w.sessions[meta.SessionID] = s
  353. w.access.Unlock()
  354. go handle(ctx, s, w.outboundRay.OutboundOutput())
  355. }
  356. if !meta.Option.Has(OptionData) {
  357. continue
  358. }
  359. if s != nil {
  360. err = pipe(reader, s.output)
  361. } else {
  362. err = drain(reader)
  363. }
  364. if err != nil {
  365. log.Info("Proxyman|Mux|ServerWorker: Failed to read data: ", err)
  366. break
  367. }
  368. }
  369. }