mux.go 9.7 KB

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