mux.go 8.0 KB

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