mux.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  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) checkAndRemove() {
  33. s.Lock()
  34. if s.uplinkClosed && s.downlinkClosed {
  35. s.parent.remove(s.id)
  36. }
  37. s.Unlock()
  38. }
  39. func (s *session) closeUplink() {
  40. s.Lock()
  41. s.uplinkClosed = true
  42. s.Unlock()
  43. s.checkAndRemove()
  44. }
  45. func (s *session) closeDownlink() {
  46. s.Lock()
  47. s.downlinkClosed = true
  48. s.Unlock()
  49. s.checkAndRemove()
  50. }
  51. type ClientManager struct {
  52. access sync.Mutex
  53. clients []*Client
  54. proxy proxy.Outbound
  55. dialer proxy.Dialer
  56. }
  57. func NewClientManager(p proxy.Outbound, d proxy.Dialer) *ClientManager {
  58. return &ClientManager{
  59. proxy: p,
  60. dialer: d,
  61. }
  62. }
  63. func (m *ClientManager) Dispatch(ctx context.Context, outboundRay ray.OutboundRay) error {
  64. m.access.Lock()
  65. defer m.access.Unlock()
  66. for _, client := range m.clients {
  67. if client.Dispatch(ctx, outboundRay) {
  68. return nil
  69. }
  70. }
  71. client, err := NewClient(m.proxy, m.dialer, m)
  72. if err != nil {
  73. return err
  74. }
  75. m.clients = append(m.clients, client)
  76. client.Dispatch(ctx, outboundRay)
  77. return nil
  78. }
  79. func (m *ClientManager) onClientFinish() {
  80. m.access.Lock()
  81. defer m.access.Unlock()
  82. nActive := 0
  83. for idx, client := range m.clients {
  84. if nActive != idx && !client.Closed() {
  85. m.clients[nActive] = client
  86. }
  87. }
  88. m.clients = m.clients[:nActive]
  89. }
  90. type Client struct {
  91. access sync.RWMutex
  92. count uint16
  93. sessions map[uint16]*session
  94. inboundRay ray.InboundRay
  95. ctx context.Context
  96. cancel context.CancelFunc
  97. manager *ClientManager
  98. }
  99. var muxCoolDestination = net.TCPDestination(net.DomainAddress("v1.mux.cool"), net.Port(9527))
  100. func NewClient(p proxy.Outbound, dialer proxy.Dialer, m *ClientManager) (*Client, error) {
  101. ctx, cancel := context.WithCancel(context.Background())
  102. ctx = proxy.ContextWithTarget(ctx, muxCoolDestination)
  103. pipe := ray.NewRay(ctx)
  104. err := p.Process(ctx, pipe, dialer)
  105. if err != nil {
  106. cancel()
  107. return nil, err
  108. }
  109. return &Client{
  110. sessions: make(map[uint16]*session, 256),
  111. inboundRay: pipe,
  112. ctx: ctx,
  113. cancel: cancel,
  114. manager: m,
  115. }, nil
  116. }
  117. func (m *Client) isFullyOccupied() bool {
  118. m.access.RLock()
  119. defer m.access.RUnlock()
  120. return len(m.sessions) >= maxParallel
  121. }
  122. func (m *Client) remove(id uint16) {
  123. m.access.Lock()
  124. defer m.access.Unlock()
  125. delete(m.sessions, id)
  126. if len(m.sessions) == 0 {
  127. m.cancel()
  128. m.inboundRay.InboundInput().Close()
  129. go m.manager.onClientFinish()
  130. }
  131. }
  132. func (m *Client) Closed() bool {
  133. select {
  134. case <-m.ctx.Done():
  135. return true
  136. default:
  137. return false
  138. }
  139. }
  140. func (m *Client) fetchInput(ctx context.Context, s *session) {
  141. dest, _ := proxy.TargetFromContext(ctx)
  142. writer := &Writer{
  143. dest: dest,
  144. id: s.id,
  145. writer: m.inboundRay.InboundInput(),
  146. }
  147. _, timer := signal.CancelAfterInactivity(ctx, time.Minute*5)
  148. if err := buf.PipeUntilEOF(timer, s.input, writer); err != nil {
  149. log.Info("Proxyman|Mux|Client: Failed to fetch all input: ", err)
  150. }
  151. writer.Close()
  152. s.closeUplink()
  153. }
  154. func (m *Client) Dispatch(ctx context.Context, outboundRay ray.OutboundRay) bool {
  155. m.access.Lock()
  156. defer m.access.Unlock()
  157. if len(m.sessions) >= maxParallel {
  158. return false
  159. }
  160. if m.count >= maxTotal {
  161. return false
  162. }
  163. select {
  164. case <-m.ctx.Done():
  165. return false
  166. default:
  167. }
  168. m.count++
  169. id := m.count
  170. s := &session{
  171. input: outboundRay.OutboundInput(),
  172. output: outboundRay.OutboundOutput(),
  173. parent: m,
  174. id: id,
  175. }
  176. m.sessions[id] = s
  177. go m.fetchInput(ctx, s)
  178. return true
  179. }
  180. func (m *Client) fetchOutput() {
  181. reader := NewReader(m.inboundRay.InboundOutput())
  182. for {
  183. meta, err := reader.ReadMetadata()
  184. if err != nil {
  185. break
  186. }
  187. m.access.RLock()
  188. s, found := m.sessions[meta.SessionID]
  189. m.access.RUnlock()
  190. if found && meta.SessionStatus == SessionStatusEnd {
  191. s.closeDownlink()
  192. s.output.Close()
  193. }
  194. if !meta.Option.Has(OptionData) {
  195. continue
  196. }
  197. for {
  198. data, more, err := reader.Read()
  199. if err != nil {
  200. break
  201. }
  202. if found {
  203. if err := s.output.Write(data); err != nil {
  204. break
  205. }
  206. }
  207. if !more {
  208. break
  209. }
  210. }
  211. }
  212. }
  213. type Server struct {
  214. dispatcher dispatcher.Interface
  215. }
  216. func NewServer(ctx context.Context) *Server {
  217. s := &Server{}
  218. space := app.SpaceFromContext(ctx)
  219. space.OnInitialize(func() error {
  220. d := dispatcher.FromSpace(space)
  221. if d == nil {
  222. return errors.New("Proxyman|Mux: No dispatcher in space.")
  223. }
  224. s.dispatcher = d
  225. return nil
  226. })
  227. return s
  228. }
  229. func (s *Server) Dispatch(ctx context.Context, dest net.Destination) (ray.InboundRay, error) {
  230. if dest != muxCoolDestination {
  231. return s.dispatcher.Dispatch(ctx, dest)
  232. }
  233. ray := ray.NewRay(ctx)
  234. worker := &ServerWorker{
  235. dispatcher: s.dispatcher,
  236. outboundRay: ray,
  237. sessions: make(map[uint16]*session),
  238. }
  239. go worker.run(ctx)
  240. return ray, nil
  241. }
  242. type ServerWorker struct {
  243. dispatcher dispatcher.Interface
  244. outboundRay ray.OutboundRay
  245. sessions map[uint16]*session
  246. access sync.RWMutex
  247. }
  248. func (w *ServerWorker) remove(id uint16) {
  249. w.access.Lock()
  250. delete(w.sessions, id)
  251. w.access.Unlock()
  252. }
  253. func (w *ServerWorker) handle(ctx context.Context, s *session) {
  254. for {
  255. select {
  256. case <-ctx.Done():
  257. return
  258. default:
  259. data, err := s.input.Read()
  260. if err != nil {
  261. return
  262. }
  263. w.outboundRay.OutboundOutput().Write(data)
  264. }
  265. }
  266. }
  267. func (w *ServerWorker) run(ctx context.Context) {
  268. input := w.outboundRay.OutboundInput()
  269. reader := NewReader(input)
  270. for {
  271. select {
  272. case <-ctx.Done():
  273. return
  274. default:
  275. }
  276. meta, err := reader.ReadMetadata()
  277. if err != nil {
  278. return
  279. }
  280. w.access.RLock()
  281. s, found := w.sessions[meta.SessionID]
  282. w.access.RUnlock()
  283. if found && meta.SessionStatus == SessionStatusEnd {
  284. s.closeUplink()
  285. s.output.Close()
  286. }
  287. if meta.SessionStatus == SessionStatusNew {
  288. inboundRay, err := w.dispatcher.Dispatch(ctx, meta.Target)
  289. if err != nil {
  290. log.Info("Proxyman|Mux: Failed to dispatch request: ", err)
  291. continue
  292. }
  293. s = &session{
  294. input: inboundRay.InboundOutput(),
  295. output: inboundRay.InboundInput(),
  296. parent: w,
  297. id: meta.SessionID,
  298. }
  299. w.access.Lock()
  300. w.sessions[meta.SessionID] = s
  301. w.access.Unlock()
  302. go w.handle(ctx, s)
  303. }
  304. if meta.Option.Has(OptionData) {
  305. for {
  306. data, more, err := reader.Read()
  307. if err != nil {
  308. break
  309. }
  310. if s != nil {
  311. s.output.Write(data)
  312. }
  313. if !more {
  314. break
  315. }
  316. }
  317. }
  318. }
  319. }