mux.go 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  1. package mux
  2. //go:generate go run $GOPATH/src/v2ray.com/core/tools/generrorgen/main.go -pkg mux -path App,Proxyman,Mux
  3. import (
  4. "context"
  5. "io"
  6. "sync"
  7. "time"
  8. "v2ray.com/core/app"
  9. "v2ray.com/core/app/dispatcher"
  10. "v2ray.com/core/app/log"
  11. "v2ray.com/core/app/proxyman"
  12. "v2ray.com/core/common/buf"
  13. "v2ray.com/core/common/errors"
  14. "v2ray.com/core/common/net"
  15. "v2ray.com/core/common/signal"
  16. "v2ray.com/core/proxy"
  17. "v2ray.com/core/transport/ray"
  18. )
  19. const (
  20. maxTotal = 128
  21. )
  22. type ClientManager struct {
  23. access sync.Mutex
  24. clients []*Client
  25. proxy proxy.Outbound
  26. dialer proxy.Dialer
  27. config *proxyman.MultiplexingConfig
  28. }
  29. func NewClientManager(p proxy.Outbound, d proxy.Dialer, c *proxyman.MultiplexingConfig) *ClientManager {
  30. return &ClientManager{
  31. proxy: p,
  32. dialer: d,
  33. config: c,
  34. }
  35. }
  36. func (m *ClientManager) Dispatch(ctx context.Context, outboundRay ray.OutboundRay) error {
  37. m.access.Lock()
  38. defer m.access.Unlock()
  39. for _, client := range m.clients {
  40. if client.Dispatch(ctx, outboundRay) {
  41. return nil
  42. }
  43. }
  44. client, err := NewClient(m.proxy, m.dialer, m)
  45. if err != nil {
  46. return newError("failed to create client").Base(err)
  47. }
  48. m.clients = append(m.clients, client)
  49. client.Dispatch(ctx, outboundRay)
  50. return nil
  51. }
  52. func (m *ClientManager) onClientFinish() {
  53. m.access.Lock()
  54. defer m.access.Unlock()
  55. activeClients := make([]*Client, 0, len(m.clients))
  56. for _, client := range m.clients {
  57. if !client.Closed() {
  58. activeClients = append(activeClients, client)
  59. }
  60. }
  61. m.clients = activeClients
  62. }
  63. type Client struct {
  64. sessionManager *SessionManager
  65. inboundRay ray.InboundRay
  66. ctx context.Context
  67. cancel context.CancelFunc
  68. manager *ClientManager
  69. session2Remove chan uint16
  70. concurrency uint32
  71. }
  72. var muxCoolDestination = net.TCPDestination(net.DomainAddress("v1.mux.cool"), net.Port(9527))
  73. func NewClient(p proxy.Outbound, dialer proxy.Dialer, m *ClientManager) (*Client, error) {
  74. ctx, cancel := context.WithCancel(context.Background())
  75. ctx = proxy.ContextWithTarget(ctx, muxCoolDestination)
  76. pipe := ray.NewRay(ctx)
  77. go p.Process(ctx, pipe, dialer)
  78. c := &Client{
  79. sessionManager: NewSessionManager(),
  80. inboundRay: pipe,
  81. ctx: ctx,
  82. cancel: cancel,
  83. manager: m,
  84. session2Remove: make(chan uint16, 16),
  85. concurrency: m.config.Concurrency,
  86. }
  87. go c.fetchOutput()
  88. go c.monitor()
  89. return c, nil
  90. }
  91. func (m *Client) Closed() bool {
  92. select {
  93. case <-m.ctx.Done():
  94. return true
  95. default:
  96. return false
  97. }
  98. }
  99. func (m *Client) monitor() {
  100. defer m.manager.onClientFinish()
  101. for {
  102. select {
  103. case <-m.ctx.Done():
  104. m.sessionManager.Close()
  105. m.inboundRay.InboundInput().Close()
  106. m.inboundRay.InboundOutput().CloseError()
  107. return
  108. case <-time.After(time.Second * 6):
  109. size := m.sessionManager.Size()
  110. if size == 0 && m.sessionManager.CloseIfNoSession() {
  111. m.cancel()
  112. }
  113. }
  114. }
  115. }
  116. func fetchInput(ctx context.Context, s *Session, output buf.Writer) {
  117. dest, _ := proxy.TargetFromContext(ctx)
  118. writer := &Writer{
  119. dest: dest,
  120. id: s.ID,
  121. writer: output,
  122. }
  123. defer writer.Close()
  124. defer s.CloseUplink()
  125. log.Trace(newError("dispatching request to ", dest))
  126. data, _ := s.input.ReadTimeout(time.Millisecond * 500)
  127. if err := writer.Write(data); err != nil {
  128. log.Trace(newError("failed to write first payload").Base(err))
  129. return
  130. }
  131. if err := buf.Copy(signal.BackgroundTimer(), s.input, writer); err != nil {
  132. log.Trace(newError("failed to fetch all input").Base(err))
  133. }
  134. }
  135. func (m *Client) Dispatch(ctx context.Context, outboundRay ray.OutboundRay) bool {
  136. sm := m.sessionManager
  137. if sm.Size() >= int(m.concurrency) || sm.Count() >= maxTotal {
  138. return false
  139. }
  140. select {
  141. case <-m.ctx.Done():
  142. return false
  143. default:
  144. }
  145. s := sm.Allocate()
  146. if s == nil {
  147. return false
  148. }
  149. s.input = outboundRay.OutboundInput()
  150. s.output = outboundRay.OutboundOutput()
  151. go fetchInput(ctx, s, m.inboundRay.InboundInput())
  152. return true
  153. }
  154. func drain(reader *Reader) error {
  155. data, err := reader.Read()
  156. if err != nil {
  157. return err
  158. }
  159. data.Release()
  160. return nil
  161. }
  162. func pipe(reader *Reader, writer buf.Writer) error {
  163. data, err := reader.Read()
  164. if err != nil {
  165. return err
  166. }
  167. return writer.Write(data)
  168. }
  169. func (m *Client) handleStatueKeepAlive(meta *FrameMetadata, reader *Reader) error {
  170. if meta.Option.Has(OptionData) {
  171. return drain(reader)
  172. }
  173. return nil
  174. }
  175. func (m *Client) handleStatusNew(meta *FrameMetadata, reader *Reader) error {
  176. if meta.Option.Has(OptionData) {
  177. return drain(reader)
  178. }
  179. return nil
  180. }
  181. func (m *Client) handleStatusKeep(meta *FrameMetadata, reader *Reader) error {
  182. if !meta.Option.Has(OptionData) {
  183. return nil
  184. }
  185. if s, found := m.sessionManager.Get(meta.SessionID); found {
  186. return pipe(reader, s.output)
  187. }
  188. return drain(reader)
  189. }
  190. func (m *Client) handleStatusEnd(meta *FrameMetadata, reader *Reader) error {
  191. if s, found := m.sessionManager.Get(meta.SessionID); found {
  192. s.CloseDownlink()
  193. s.output.Close()
  194. }
  195. if meta.Option.Has(OptionData) {
  196. return drain(reader)
  197. }
  198. return nil
  199. }
  200. func (m *Client) fetchOutput() {
  201. defer m.cancel()
  202. reader := NewReader(m.inboundRay.InboundOutput())
  203. for {
  204. meta, err := reader.ReadMetadata()
  205. if err != nil {
  206. if errors.Cause(err) != io.EOF {
  207. log.Trace(newError("failed to read metadata").Base(err))
  208. }
  209. break
  210. }
  211. switch meta.SessionStatus {
  212. case SessionStatusKeepAlive:
  213. err = m.handleStatueKeepAlive(meta, reader)
  214. case SessionStatusEnd:
  215. err = m.handleStatusEnd(meta, reader)
  216. case SessionStatusNew:
  217. err = m.handleStatusNew(meta, reader)
  218. case SessionStatusKeep:
  219. err = m.handleStatusKeep(meta, reader)
  220. default:
  221. log.Trace(newError("unknown status: ", meta.SessionStatus).AtWarning())
  222. return
  223. }
  224. if err != nil {
  225. log.Trace(newError("failed to process data").Base(err))
  226. return
  227. }
  228. }
  229. }
  230. type Server struct {
  231. dispatcher dispatcher.Interface
  232. }
  233. func NewServer(ctx context.Context) *Server {
  234. s := &Server{}
  235. space := app.SpaceFromContext(ctx)
  236. space.OnInitialize(func() error {
  237. d := dispatcher.FromSpace(space)
  238. if d == nil {
  239. return newError("no dispatcher in space")
  240. }
  241. s.dispatcher = d
  242. return nil
  243. })
  244. return s
  245. }
  246. func (s *Server) Dispatch(ctx context.Context, dest net.Destination) (ray.InboundRay, error) {
  247. if dest != muxCoolDestination {
  248. return s.dispatcher.Dispatch(ctx, dest)
  249. }
  250. ray := ray.NewRay(ctx)
  251. worker := &ServerWorker{
  252. dispatcher: s.dispatcher,
  253. outboundRay: ray,
  254. sessionManager: NewSessionManager(),
  255. }
  256. go worker.run(ctx)
  257. return ray, nil
  258. }
  259. type ServerWorker struct {
  260. dispatcher dispatcher.Interface
  261. outboundRay ray.OutboundRay
  262. sessionManager *SessionManager
  263. }
  264. func handle(ctx context.Context, s *Session, output buf.Writer) {
  265. writer := NewResponseWriter(s.ID, output)
  266. if err := buf.Copy(signal.BackgroundTimer(), s.input, writer); err != nil {
  267. log.Trace(newError("session ", s.ID, " ends: ").Base(err))
  268. }
  269. writer.Close()
  270. s.CloseDownlink()
  271. }
  272. func (w *ServerWorker) handleStatusKeepAlive(meta *FrameMetadata, reader *Reader) error {
  273. if meta.Option.Has(OptionData) {
  274. return drain(reader)
  275. }
  276. return nil
  277. }
  278. func (w *ServerWorker) handleStatusNew(ctx context.Context, meta *FrameMetadata, reader *Reader) error {
  279. log.Trace(newError("received request for ", meta.Target))
  280. inboundRay, err := w.dispatcher.Dispatch(ctx, meta.Target)
  281. if err != nil {
  282. if meta.Option.Has(OptionData) {
  283. drain(reader)
  284. }
  285. return newError("failed to dispatch request.").Base(err)
  286. }
  287. s := &Session{
  288. input: inboundRay.InboundOutput(),
  289. output: inboundRay.InboundInput(),
  290. parent: w.sessionManager,
  291. ID: meta.SessionID,
  292. }
  293. w.sessionManager.Add(s)
  294. go handle(ctx, s, w.outboundRay.OutboundOutput())
  295. if meta.Option.Has(OptionData) {
  296. return pipe(reader, s.output)
  297. }
  298. return nil
  299. }
  300. func (w *ServerWorker) handleStatusKeep(meta *FrameMetadata, reader *Reader) error {
  301. if !meta.Option.Has(OptionData) {
  302. return nil
  303. }
  304. if s, found := w.sessionManager.Get(meta.SessionID); found {
  305. return pipe(reader, s.output)
  306. }
  307. return drain(reader)
  308. }
  309. func (w *ServerWorker) handleStatusEnd(meta *FrameMetadata, reader *Reader) error {
  310. if s, found := w.sessionManager.Get(meta.SessionID); found {
  311. s.CloseUplink()
  312. s.output.Close()
  313. }
  314. if meta.Option.Has(OptionData) {
  315. return drain(reader)
  316. }
  317. return nil
  318. }
  319. func (w *ServerWorker) run(ctx context.Context) {
  320. input := w.outboundRay.OutboundInput()
  321. reader := NewReader(input)
  322. defer w.sessionManager.Close()
  323. for {
  324. select {
  325. case <-ctx.Done():
  326. return
  327. default:
  328. }
  329. meta, err := reader.ReadMetadata()
  330. if err != nil {
  331. log.Trace(newError("failed to read metadata").Base(err))
  332. return
  333. }
  334. switch meta.SessionStatus {
  335. case SessionStatusKeepAlive:
  336. err = w.handleStatusKeepAlive(meta, reader)
  337. case SessionStatusEnd:
  338. err = w.handleStatusEnd(meta, reader)
  339. case SessionStatusNew:
  340. err = w.handleStatusNew(ctx, meta, reader)
  341. case SessionStatusKeep:
  342. err = w.handleStatusKeep(meta, reader)
  343. default:
  344. log.Trace(newError("unknown status: ", meta.SessionStatus).AtWarning())
  345. return
  346. }
  347. if err != nil {
  348. log.Trace(newError("failed to process data").Base(err))
  349. return
  350. }
  351. }
  352. }