portal.go 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  1. package reverse
  2. import (
  3. "context"
  4. "sync"
  5. "time"
  6. "github.com/xtls/xray-core/common"
  7. "github.com/xtls/xray-core/common/buf"
  8. "github.com/xtls/xray-core/common/errors"
  9. "github.com/xtls/xray-core/common/mux"
  10. "github.com/xtls/xray-core/common/net"
  11. "github.com/xtls/xray-core/common/serial"
  12. "github.com/xtls/xray-core/common/session"
  13. "github.com/xtls/xray-core/common/signal"
  14. "github.com/xtls/xray-core/common/task"
  15. "github.com/xtls/xray-core/features/outbound"
  16. "github.com/xtls/xray-core/transport"
  17. "github.com/xtls/xray-core/transport/pipe"
  18. "google.golang.org/protobuf/proto"
  19. )
  20. type Portal struct {
  21. ohm outbound.Manager
  22. tag string
  23. domain string
  24. picker *StaticMuxPicker
  25. client *mux.ClientManager
  26. }
  27. func NewPortal(config *PortalConfig, ohm outbound.Manager) (*Portal, error) {
  28. if config.Tag == "" {
  29. return nil, errors.New("portal tag is empty")
  30. }
  31. if config.Domain == "" {
  32. return nil, errors.New("portal domain is empty")
  33. }
  34. picker, err := NewStaticMuxPicker()
  35. if err != nil {
  36. return nil, err
  37. }
  38. return &Portal{
  39. ohm: ohm,
  40. tag: config.Tag,
  41. domain: config.Domain,
  42. picker: picker,
  43. client: &mux.ClientManager{
  44. Picker: picker,
  45. },
  46. }, nil
  47. }
  48. func (p *Portal) Start() error {
  49. return p.ohm.AddHandler(context.Background(), &Outbound{
  50. portal: p,
  51. tag: p.tag,
  52. })
  53. }
  54. func (p *Portal) Close() error {
  55. return p.ohm.RemoveHandler(context.Background(), p.tag)
  56. }
  57. func (p *Portal) HandleConnection(ctx context.Context, link *transport.Link) error {
  58. outbounds := session.OutboundsFromContext(ctx)
  59. ob := outbounds[len(outbounds)-1]
  60. if ob == nil {
  61. return errors.New("outbound metadata not found").AtError()
  62. }
  63. if isDomain(ob.Target, p.domain) {
  64. muxClient, err := mux.NewClientWorker(*link, mux.ClientStrategy{})
  65. if err != nil {
  66. return errors.New("failed to create mux client worker").Base(err).AtWarning()
  67. }
  68. worker, err := NewPortalWorker(muxClient)
  69. if err != nil {
  70. return errors.New("failed to create portal worker").Base(err)
  71. }
  72. p.picker.AddWorker(worker)
  73. if _, ok := link.Reader.(*pipe.Reader); !ok {
  74. select {
  75. case <-ctx.Done():
  76. case <-muxClient.WaitClosed():
  77. }
  78. }
  79. return nil
  80. }
  81. if ob.Target.Network == net.Network_UDP && ob.OriginalTarget.Address != nil && ob.OriginalTarget.Address != ob.Target.Address {
  82. link.Reader = &buf.EndpointOverrideReader{Reader: link.Reader, Dest: ob.Target.Address, OriginalDest: ob.OriginalTarget.Address}
  83. link.Writer = &buf.EndpointOverrideWriter{Writer: link.Writer, Dest: ob.Target.Address, OriginalDest: ob.OriginalTarget.Address}
  84. }
  85. return p.client.Dispatch(ctx, link)
  86. }
  87. type Outbound struct {
  88. portal *Portal
  89. tag string
  90. }
  91. func (o *Outbound) Tag() string {
  92. return o.tag
  93. }
  94. func (o *Outbound) Dispatch(ctx context.Context, link *transport.Link) {
  95. if err := o.portal.HandleConnection(ctx, link); err != nil {
  96. errors.LogInfoInner(ctx, err, "failed to process reverse connection")
  97. common.Interrupt(link.Writer)
  98. common.Interrupt(link.Reader)
  99. }
  100. }
  101. func (o *Outbound) Start() error {
  102. return nil
  103. }
  104. func (o *Outbound) Close() error {
  105. return nil
  106. }
  107. // SenderSettings implements outbound.Handler.
  108. func (o *Outbound) SenderSettings() *serial.TypedMessage {
  109. return nil
  110. }
  111. // ProxySettings implements outbound.Handler.
  112. func (o *Outbound) ProxySettings() *serial.TypedMessage {
  113. return nil
  114. }
  115. type StaticMuxPicker struct {
  116. access sync.Mutex
  117. workers []*PortalWorker
  118. cTask *task.Periodic
  119. }
  120. func NewStaticMuxPicker() (*StaticMuxPicker, error) {
  121. p := &StaticMuxPicker{}
  122. p.cTask = &task.Periodic{
  123. Execute: p.cleanup,
  124. Interval: time.Second * 30,
  125. }
  126. p.cTask.Start()
  127. return p, nil
  128. }
  129. func (p *StaticMuxPicker) cleanup() error {
  130. p.access.Lock()
  131. defer p.access.Unlock()
  132. var activeWorkers []*PortalWorker
  133. for _, w := range p.workers {
  134. if !w.Closed() {
  135. activeWorkers = append(activeWorkers, w)
  136. } else {
  137. w.timer.SetTimeout(0)
  138. }
  139. }
  140. if len(activeWorkers) != len(p.workers) {
  141. p.workers = activeWorkers
  142. }
  143. return nil
  144. }
  145. func (p *StaticMuxPicker) PickAvailable() (*mux.ClientWorker, error) {
  146. p.access.Lock()
  147. defer p.access.Unlock()
  148. if len(p.workers) == 0 {
  149. return nil, errors.New("empty worker list")
  150. }
  151. var minIdx int = -1
  152. var minConn uint32 = 9999
  153. for i, w := range p.workers {
  154. if w.draining {
  155. continue
  156. }
  157. if w.IsFull() {
  158. continue
  159. }
  160. if w.client.ActiveConnections() < minConn {
  161. minConn = w.client.ActiveConnections()
  162. minIdx = i
  163. }
  164. }
  165. if minIdx == -1 {
  166. for i, w := range p.workers {
  167. if w.IsFull() {
  168. continue
  169. }
  170. if w.client.ActiveConnections() < minConn {
  171. minConn = w.client.ActiveConnections()
  172. minIdx = i
  173. }
  174. }
  175. }
  176. if minIdx != -1 {
  177. return p.workers[minIdx].client, nil
  178. }
  179. return nil, errors.New("no mux client worker available")
  180. }
  181. func (p *StaticMuxPicker) AddWorker(worker *PortalWorker) {
  182. p.access.Lock()
  183. defer p.access.Unlock()
  184. p.workers = append(p.workers, worker)
  185. }
  186. type PortalWorker struct {
  187. client *mux.ClientWorker
  188. control *task.Periodic
  189. writer buf.Writer
  190. reader buf.Reader
  191. draining bool
  192. counter uint32
  193. timer *signal.ActivityTimer
  194. }
  195. func NewPortalWorker(client *mux.ClientWorker) (*PortalWorker, error) {
  196. opt := []pipe.Option{pipe.WithSizeLimit(16 * 1024)}
  197. uplinkReader, uplinkWriter := pipe.New(opt...)
  198. downlinkReader, downlinkWriter := pipe.New(opt...)
  199. ctx := context.Background()
  200. outbounds := []*session.Outbound{{
  201. Target: net.UDPDestination(net.DomainAddress(internalDomain), 0),
  202. }}
  203. ctx = session.ContextWithOutbounds(ctx, outbounds)
  204. f := client.Dispatch(ctx, &transport.Link{
  205. Reader: uplinkReader,
  206. Writer: downlinkWriter,
  207. })
  208. if !f {
  209. return nil, errors.New("unable to dispatch control connection")
  210. }
  211. terminate := func() {
  212. client.Close()
  213. }
  214. w := &PortalWorker{
  215. client: client,
  216. reader: downlinkReader,
  217. writer: uplinkWriter,
  218. timer: signal.CancelAfterInactivity(ctx, terminate, 24*time.Hour), // // prevent leak
  219. }
  220. w.control = &task.Periodic{
  221. Execute: w.heartbeat,
  222. Interval: time.Second * 2,
  223. }
  224. w.control.Start()
  225. return w, nil
  226. }
  227. func (w *PortalWorker) heartbeat() error {
  228. if w.Closed() {
  229. return errors.New("client worker stopped")
  230. }
  231. if w.draining || w.writer == nil {
  232. return errors.New("already disposed")
  233. }
  234. msg := &Control{}
  235. msg.FillInRandom()
  236. if w.client.TotalConnections() > 256 {
  237. w.draining = true
  238. msg.State = Control_DRAIN
  239. defer func() {
  240. common.Close(w.writer)
  241. common.Interrupt(w.reader)
  242. w.writer = nil
  243. }()
  244. }
  245. w.counter = (w.counter + 1) % 5
  246. if w.draining || w.counter == 1 {
  247. b, err := proto.Marshal(msg)
  248. common.Must(err)
  249. mb := buf.MergeBytes(nil, b)
  250. w.timer.Update()
  251. return w.writer.WriteMultiBuffer(mb)
  252. }
  253. return nil
  254. }
  255. func (w *PortalWorker) IsFull() bool {
  256. return w.client.IsFull()
  257. }
  258. func (w *PortalWorker) Closed() bool {
  259. return w.client.Closed()
  260. }