mux.go 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. package mux
  2. import (
  3. "context"
  4. "sync"
  5. "time"
  6. "v2ray.com/core/app/dispatcher"
  7. "v2ray.com/core/app/log"
  8. "v2ray.com/core/common/buf"
  9. "v2ray.com/core/common/net"
  10. "v2ray.com/core/common/signal"
  11. "v2ray.com/core/proxy"
  12. "v2ray.com/core/transport/ray"
  13. )
  14. const (
  15. maxParallel = 8
  16. maxTotal = 128
  17. )
  18. type manager interface {
  19. remove(id uint16)
  20. }
  21. type session struct {
  22. sync.Mutex
  23. input ray.InputStream
  24. output ray.OutputStream
  25. parent manager
  26. id uint16
  27. uplinkClosed bool
  28. downlinkClosed bool
  29. }
  30. func (s *session) checkAndRemove() {
  31. s.Lock()
  32. if s.uplinkClosed && s.downlinkClosed {
  33. s.parent.remove(s.id)
  34. }
  35. s.Unlock()
  36. }
  37. func (s *session) closeUplink() {
  38. s.Lock()
  39. s.uplinkClosed = true
  40. s.Unlock()
  41. s.checkAndRemove()
  42. }
  43. func (s *session) closeDownlink() {
  44. s.Lock()
  45. s.downlinkClosed = true
  46. s.Unlock()
  47. s.checkAndRemove()
  48. }
  49. type Client struct {
  50. access sync.RWMutex
  51. count uint16
  52. sessions map[uint16]*session
  53. inboundRay ray.InboundRay
  54. ctx context.Context
  55. cancel context.CancelFunc
  56. }
  57. var muxCoolDestination = net.TCPDestination(net.DomainAddress("v1.mux.cool"), net.Port(9527))
  58. func NewClient(p proxy.Outbound, dialer proxy.Dialer) (*Client, error) {
  59. ctx, cancel := context.WithCancel(context.Background())
  60. ctx = proxy.ContextWithTarget(ctx, muxCoolDestination)
  61. pipe := ray.NewRay(ctx)
  62. err := p.Process(ctx, pipe, dialer)
  63. if err != nil {
  64. cancel()
  65. return nil, err
  66. }
  67. return &Client{
  68. sessions: make(map[uint16]*session, 256),
  69. inboundRay: pipe,
  70. ctx: ctx,
  71. cancel: cancel,
  72. }, nil
  73. }
  74. func (m *Client) isFullyOccupied() bool {
  75. m.access.RLock()
  76. defer m.access.RUnlock()
  77. return len(m.sessions) >= maxParallel
  78. }
  79. func (m *Client) remove(id uint16) {
  80. m.access.Lock()
  81. defer m.access.Unlock()
  82. delete(m.sessions, id)
  83. if len(m.sessions) == 0 {
  84. m.cancel()
  85. m.inboundRay.InboundInput().Close()
  86. }
  87. }
  88. func (m *Client) Closed() bool {
  89. select {
  90. case <-m.ctx.Done():
  91. return true
  92. default:
  93. return false
  94. }
  95. }
  96. func (m *Client) fetchInput(ctx context.Context, s *session) {
  97. dest, _ := proxy.TargetFromContext(ctx)
  98. writer := &MuxWriter{
  99. dest: dest,
  100. id: s.id,
  101. writer: m.inboundRay.InboundInput(),
  102. }
  103. _, timer := signal.CancelAfterInactivity(ctx, time.Minute*5)
  104. buf.PipeUntilEOF(timer, s.input, writer)
  105. writer.Close()
  106. s.closeUplink()
  107. }
  108. func (m *Client) Dispatch(ctx context.Context, outboundRay ray.OutboundRay) bool {
  109. m.access.Lock()
  110. defer m.access.Unlock()
  111. if len(m.sessions) >= maxParallel {
  112. return false
  113. }
  114. if m.count >= maxTotal {
  115. return false
  116. }
  117. select {
  118. case <-m.ctx.Done():
  119. return false
  120. default:
  121. }
  122. m.count++
  123. id := m.count
  124. s := &session{
  125. input: outboundRay.OutboundInput(),
  126. output: outboundRay.OutboundOutput(),
  127. parent: m,
  128. id: id,
  129. }
  130. m.sessions[id] = s
  131. go m.fetchInput(ctx, s)
  132. return true
  133. }
  134. func (m *Client) fetchOutput() {
  135. reader := NewReader(m.inboundRay.InboundOutput())
  136. for {
  137. meta, err := reader.ReadMetadata()
  138. if err != nil {
  139. break
  140. }
  141. m.access.RLock()
  142. s, found := m.sessions[meta.SessionID]
  143. m.access.RUnlock()
  144. if found && meta.SessionStatus == SessionStatusEnd {
  145. s.closeDownlink()
  146. s.output.Close()
  147. }
  148. if !meta.Option.Has(OptionData) {
  149. continue
  150. }
  151. for {
  152. data, more, err := reader.Read()
  153. if err != nil {
  154. break
  155. }
  156. if found {
  157. if err := s.output.Write(data); err != nil {
  158. break
  159. }
  160. }
  161. if !more {
  162. break
  163. }
  164. }
  165. }
  166. }
  167. type Server struct {
  168. dispatcher dispatcher.Interface
  169. }
  170. func (s *Server) Dispatch(ctx context.Context, dest net.Destination) (ray.InboundRay, error) {
  171. if dest != muxCoolDestination {
  172. return s.dispatcher.Dispatch(ctx, dest)
  173. }
  174. ray := ray.NewRay(ctx)
  175. return ray, nil
  176. }
  177. type ServerWorker struct {
  178. dispatcher dispatcher.Interface
  179. outboundRay ray.OutboundRay
  180. sessions map[uint16]*session
  181. access sync.RWMutex
  182. }
  183. func (w *ServerWorker) remove(id uint16) {
  184. w.access.Lock()
  185. delete(w.sessions, id)
  186. w.access.Unlock()
  187. }
  188. func (w *ServerWorker) handle(ctx context.Context, s *session) {
  189. for {
  190. select {
  191. case <-ctx.Done():
  192. return
  193. default:
  194. data, err := s.input.Read()
  195. if err != nil {
  196. return
  197. }
  198. w.outboundRay.OutboundOutput().Write(data)
  199. }
  200. }
  201. }
  202. func (w *ServerWorker) run(ctx context.Context) {
  203. input := w.outboundRay.OutboundInput()
  204. reader := NewReader(input)
  205. for {
  206. select {
  207. case <-ctx.Done():
  208. return
  209. default:
  210. }
  211. meta, err := reader.ReadMetadata()
  212. if err != nil {
  213. return
  214. }
  215. w.access.RLock()
  216. s, found := w.sessions[meta.SessionID]
  217. w.access.RUnlock()
  218. if found && meta.SessionStatus == SessionStatusEnd {
  219. s.closeUplink()
  220. s.output.Close()
  221. }
  222. if meta.SessionStatus == SessionStatusNew {
  223. inboundRay, err := w.dispatcher.Dispatch(ctx, meta.Target)
  224. if err != nil {
  225. log.Info("Proxyman|Mux: Failed to dispatch request: ", err)
  226. continue
  227. }
  228. s = &session{
  229. input: inboundRay.InboundOutput(),
  230. output: inboundRay.InboundInput(),
  231. parent: w,
  232. id: meta.SessionID,
  233. }
  234. w.access.Lock()
  235. w.sessions[meta.SessionID] = s
  236. w.access.Unlock()
  237. go w.handle(ctx, s)
  238. }
  239. if meta.Option.Has(OptionData) {
  240. for {
  241. data, more, err := reader.Read()
  242. if err != nil {
  243. break
  244. }
  245. if s != nil {
  246. s.output.Write(data)
  247. }
  248. if !more {
  249. break
  250. }
  251. }
  252. }
  253. }
  254. }