mux.go 7.5 KB

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