bridge.go 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. package reverse
  2. import (
  3. "context"
  4. "time"
  5. "github.com/xtls/xray-core/common/errors"
  6. "github.com/xtls/xray-core/common/mux"
  7. "github.com/xtls/xray-core/common/net"
  8. "github.com/xtls/xray-core/common/session"
  9. "github.com/xtls/xray-core/common/signal"
  10. "github.com/xtls/xray-core/common/task"
  11. "github.com/xtls/xray-core/features/routing"
  12. "github.com/xtls/xray-core/transport"
  13. "github.com/xtls/xray-core/transport/pipe"
  14. "google.golang.org/protobuf/proto"
  15. )
  16. // Bridge is a component in reverse proxy, that relays connections from Portal to local address.
  17. type Bridge struct {
  18. dispatcher routing.Dispatcher
  19. tag string
  20. domain string
  21. workers []*BridgeWorker
  22. monitorTask *task.Periodic
  23. }
  24. // NewBridge creates a new Bridge instance.
  25. func NewBridge(config *BridgeConfig, dispatcher routing.Dispatcher) (*Bridge, error) {
  26. if config.Tag == "" {
  27. return nil, errors.New("bridge tag is empty")
  28. }
  29. if config.Domain == "" {
  30. return nil, errors.New("bridge domain is empty")
  31. }
  32. b := &Bridge{
  33. dispatcher: dispatcher,
  34. tag: config.Tag,
  35. domain: config.Domain,
  36. }
  37. b.monitorTask = &task.Periodic{
  38. Execute: b.monitor,
  39. Interval: time.Second * 2,
  40. }
  41. return b, nil
  42. }
  43. func (b *Bridge) cleanup() {
  44. var activeWorkers []*BridgeWorker
  45. for _, w := range b.workers {
  46. if w.IsActive() {
  47. activeWorkers = append(activeWorkers, w)
  48. }
  49. if w.Closed() {
  50. if w.Timer != nil {
  51. w.Timer.SetTimeout(0)
  52. }
  53. }
  54. }
  55. if len(activeWorkers) != len(b.workers) {
  56. b.workers = activeWorkers
  57. }
  58. }
  59. func (b *Bridge) monitor() error {
  60. b.cleanup()
  61. var numConnections uint32
  62. var numWorker uint32
  63. for _, w := range b.workers {
  64. if w.IsActive() {
  65. numConnections += w.Connections()
  66. numWorker++
  67. }
  68. }
  69. if numWorker == 0 || numConnections/numWorker > 16 {
  70. worker, err := NewBridgeWorker(b.domain, b.tag, b.dispatcher)
  71. if err != nil {
  72. errors.LogWarningInner(context.Background(), err, "failed to create bridge worker")
  73. return nil
  74. }
  75. b.workers = append(b.workers, worker)
  76. }
  77. return nil
  78. }
  79. func (b *Bridge) Start() error {
  80. return b.monitorTask.Start()
  81. }
  82. func (b *Bridge) Close() error {
  83. return b.monitorTask.Close()
  84. }
  85. type BridgeWorker struct {
  86. Tag string
  87. Worker *mux.ServerWorker
  88. Dispatcher routing.Dispatcher
  89. State Control_State
  90. Timer *signal.ActivityTimer
  91. }
  92. func NewBridgeWorker(domain string, tag string, d routing.Dispatcher) (*BridgeWorker, error) {
  93. ctx := context.Background()
  94. ctx = session.ContextWithInbound(ctx, &session.Inbound{
  95. Tag: tag,
  96. })
  97. link, err := d.Dispatch(ctx, net.Destination{
  98. Network: net.Network_TCP,
  99. Address: net.DomainAddress(domain),
  100. Port: 0,
  101. })
  102. if err != nil {
  103. return nil, err
  104. }
  105. w := &BridgeWorker{
  106. Dispatcher: d,
  107. Tag: tag,
  108. }
  109. worker, err := mux.NewServerWorker(context.Background(), w, link)
  110. if err != nil {
  111. return nil, err
  112. }
  113. w.Worker = worker
  114. terminate := func() {
  115. worker.Close()
  116. }
  117. w.Timer = signal.CancelAfterInactivity(ctx, terminate, 60*time.Second)
  118. return w, nil
  119. }
  120. func (w *BridgeWorker) Type() interface{} {
  121. return routing.DispatcherType()
  122. }
  123. func (w *BridgeWorker) Start() error {
  124. return nil
  125. }
  126. func (w *BridgeWorker) Close() error {
  127. return nil
  128. }
  129. func (w *BridgeWorker) IsActive() bool {
  130. return w.State == Control_ACTIVE && !w.Worker.Closed()
  131. }
  132. func (w *BridgeWorker) Closed() bool {
  133. return w.Worker.Closed()
  134. }
  135. func (w *BridgeWorker) Connections() uint32 {
  136. return w.Worker.ActiveConnections()
  137. }
  138. func (w *BridgeWorker) handleInternalConn(link *transport.Link) {
  139. reader := link.Reader
  140. for {
  141. mb, err := reader.ReadMultiBuffer()
  142. if err != nil {
  143. if w.Timer != nil {
  144. if w.Closed() {
  145. w.Timer.SetTimeout(0)
  146. } else {
  147. w.Timer.SetTimeout(24 * time.Hour)
  148. }
  149. }
  150. return
  151. }
  152. if w.Timer != nil {
  153. w.Timer.Update()
  154. }
  155. for _, b := range mb {
  156. var ctl Control
  157. if err := proto.Unmarshal(b.Bytes(), &ctl); err != nil {
  158. errors.LogInfoInner(context.Background(), err, "failed to parse proto message")
  159. if w.Timer != nil {
  160. w.Timer.SetTimeout(0)
  161. }
  162. return
  163. }
  164. if ctl.State != w.State {
  165. w.State = ctl.State
  166. }
  167. }
  168. }
  169. }
  170. func (w *BridgeWorker) Dispatch(ctx context.Context, dest net.Destination) (*transport.Link, error) {
  171. if !isInternalDomain(dest) {
  172. if session.InboundFromContext(ctx) == nil {
  173. ctx = session.ContextWithInbound(ctx, &session.Inbound{
  174. Tag: w.Tag,
  175. })
  176. }
  177. return w.Dispatcher.Dispatch(ctx, dest)
  178. }
  179. opt := []pipe.Option{pipe.WithSizeLimit(16 * 1024)}
  180. uplinkReader, uplinkWriter := pipe.New(opt...)
  181. downlinkReader, downlinkWriter := pipe.New(opt...)
  182. go w.handleInternalConn(&transport.Link{
  183. Reader: downlinkReader,
  184. Writer: uplinkWriter,
  185. })
  186. return &transport.Link{
  187. Reader: uplinkReader,
  188. Writer: downlinkWriter,
  189. }, nil
  190. }
  191. func (w *BridgeWorker) DispatchLink(ctx context.Context, dest net.Destination, link *transport.Link) error {
  192. if !isInternalDomain(dest) {
  193. if session.InboundFromContext(ctx) == nil {
  194. ctx = session.ContextWithInbound(ctx, &session.Inbound{
  195. Tag: w.Tag,
  196. })
  197. }
  198. return w.Dispatcher.DispatchLink(ctx, dest, link)
  199. }
  200. if d, ok := w.Dispatcher.(routing.WrapLinkDispatcher); ok {
  201. link = d.WrapLink(ctx, link)
  202. }
  203. w.handleInternalConn(link)
  204. return nil
  205. }