mux.go 8.4 KB

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