mux.go 7.7 KB

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