bridge.go 5.2 KB

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