mux.go 9.0 KB

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