tcpmux.go 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  1. // Copyright 2020 guylewin, [email protected]
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package group
  15. import (
  16. "context"
  17. "fmt"
  18. "net"
  19. "sync"
  20. "github.com/fatedier/frp/pkg/consts"
  21. "github.com/fatedier/frp/pkg/util/tcpmux"
  22. "github.com/fatedier/frp/pkg/util/vhost"
  23. gerr "github.com/fatedier/golib/errors"
  24. )
  25. // TCPMuxGroupCtl manage all TCPMuxGroups
  26. type TCPMuxGroupCtl struct {
  27. groups map[string]*TCPMuxGroup
  28. // portManager is used to manage port
  29. tcpMuxHTTPConnectMuxer *tcpmux.HTTPConnectTCPMuxer
  30. mu sync.Mutex
  31. }
  32. // NewTCPMuxGroupCtl return a new TCPMuxGroupCtl
  33. func NewTCPMuxGroupCtl(tcpMuxHTTPConnectMuxer *tcpmux.HTTPConnectTCPMuxer) *TCPMuxGroupCtl {
  34. return &TCPMuxGroupCtl{
  35. groups: make(map[string]*TCPMuxGroup),
  36. tcpMuxHTTPConnectMuxer: tcpMuxHTTPConnectMuxer,
  37. }
  38. }
  39. // Listen is the wrapper for TCPMuxGroup's Listen
  40. // If there are no group, we will create one here
  41. func (tmgc *TCPMuxGroupCtl) Listen(ctx context.Context, multiplexer string, group string, groupKey string,
  42. domain string) (l net.Listener, err error) {
  43. tmgc.mu.Lock()
  44. tcpMuxGroup, ok := tmgc.groups[group]
  45. if !ok {
  46. tcpMuxGroup = NewTCPMuxGroup(tmgc)
  47. tmgc.groups[group] = tcpMuxGroup
  48. }
  49. tmgc.mu.Unlock()
  50. switch multiplexer {
  51. case consts.HTTPConnectTCPMultiplexer:
  52. return tcpMuxGroup.HTTPConnectListen(ctx, group, groupKey, domain)
  53. default:
  54. err = fmt.Errorf("unknown multiplexer [%s]", multiplexer)
  55. return
  56. }
  57. }
  58. // RemoveGroup remove TCPMuxGroup from controller
  59. func (tmgc *TCPMuxGroupCtl) RemoveGroup(group string) {
  60. tmgc.mu.Lock()
  61. defer tmgc.mu.Unlock()
  62. delete(tmgc.groups, group)
  63. }
  64. // TCPMuxGroup route connections to different proxies
  65. type TCPMuxGroup struct {
  66. group string
  67. groupKey string
  68. domain string
  69. acceptCh chan net.Conn
  70. index uint64
  71. tcpMuxLn net.Listener
  72. lns []*TCPMuxGroupListener
  73. ctl *TCPMuxGroupCtl
  74. mu sync.Mutex
  75. }
  76. // NewTCPMuxGroup return a new TCPMuxGroup
  77. func NewTCPMuxGroup(ctl *TCPMuxGroupCtl) *TCPMuxGroup {
  78. return &TCPMuxGroup{
  79. lns: make([]*TCPMuxGroupListener, 0),
  80. ctl: ctl,
  81. acceptCh: make(chan net.Conn),
  82. }
  83. }
  84. // Listen will return a new TCPMuxGroupListener
  85. // if TCPMuxGroup already has a listener, just add a new TCPMuxGroupListener to the queues
  86. // otherwise, listen on the real address
  87. func (tmg *TCPMuxGroup) HTTPConnectListen(ctx context.Context, group string, groupKey string, domain string) (ln *TCPMuxGroupListener, err error) {
  88. tmg.mu.Lock()
  89. defer tmg.mu.Unlock()
  90. if len(tmg.lns) == 0 {
  91. // the first listener, listen on the real address
  92. routeConfig := &vhost.RouteConfig{
  93. Domain: domain,
  94. }
  95. tcpMuxLn, errRet := tmg.ctl.tcpMuxHTTPConnectMuxer.Listen(ctx, routeConfig)
  96. if errRet != nil {
  97. return nil, errRet
  98. }
  99. ln = newTCPMuxGroupListener(group, tmg, tcpMuxLn.Addr())
  100. tmg.group = group
  101. tmg.groupKey = groupKey
  102. tmg.domain = domain
  103. tmg.tcpMuxLn = tcpMuxLn
  104. tmg.lns = append(tmg.lns, ln)
  105. if tmg.acceptCh == nil {
  106. tmg.acceptCh = make(chan net.Conn)
  107. }
  108. go tmg.worker()
  109. } else {
  110. // domain in the same group must be equal
  111. if tmg.group != group || tmg.domain != domain {
  112. return nil, ErrGroupParamsInvalid
  113. }
  114. if tmg.groupKey != groupKey {
  115. return nil, ErrGroupAuthFailed
  116. }
  117. ln = newTCPMuxGroupListener(group, tmg, tmg.lns[0].Addr())
  118. tmg.lns = append(tmg.lns, ln)
  119. }
  120. return
  121. }
  122. // worker is called when the real TCP listener has been created
  123. func (tmg *TCPMuxGroup) worker() {
  124. for {
  125. c, err := tmg.tcpMuxLn.Accept()
  126. if err != nil {
  127. return
  128. }
  129. err = gerr.PanicToError(func() {
  130. tmg.acceptCh <- c
  131. })
  132. if err != nil {
  133. return
  134. }
  135. }
  136. }
  137. func (tmg *TCPMuxGroup) Accept() <-chan net.Conn {
  138. return tmg.acceptCh
  139. }
  140. // CloseListener remove the TCPMuxGroupListener from the TCPMuxGroup
  141. func (tmg *TCPMuxGroup) CloseListener(ln *TCPMuxGroupListener) {
  142. tmg.mu.Lock()
  143. defer tmg.mu.Unlock()
  144. for i, tmpLn := range tmg.lns {
  145. if tmpLn == ln {
  146. tmg.lns = append(tmg.lns[:i], tmg.lns[i+1:]...)
  147. break
  148. }
  149. }
  150. if len(tmg.lns) == 0 {
  151. close(tmg.acceptCh)
  152. tmg.tcpMuxLn.Close()
  153. tmg.ctl.RemoveGroup(tmg.group)
  154. }
  155. }
  156. // TCPMuxGroupListener
  157. type TCPMuxGroupListener struct {
  158. groupName string
  159. group *TCPMuxGroup
  160. addr net.Addr
  161. closeCh chan struct{}
  162. }
  163. func newTCPMuxGroupListener(name string, group *TCPMuxGroup, addr net.Addr) *TCPMuxGroupListener {
  164. return &TCPMuxGroupListener{
  165. groupName: name,
  166. group: group,
  167. addr: addr,
  168. closeCh: make(chan struct{}),
  169. }
  170. }
  171. // Accept will accept connections from TCPMuxGroup
  172. func (ln *TCPMuxGroupListener) Accept() (c net.Conn, err error) {
  173. var ok bool
  174. select {
  175. case <-ln.closeCh:
  176. return nil, ErrListenerClosed
  177. case c, ok = <-ln.group.Accept():
  178. if !ok {
  179. return nil, ErrListenerClosed
  180. }
  181. return c, nil
  182. }
  183. }
  184. func (ln *TCPMuxGroupListener) Addr() net.Addr {
  185. return ln.addr
  186. }
  187. // Close close the listener
  188. func (ln *TCPMuxGroupListener) Close() (err error) {
  189. close(ln.closeCh)
  190. // remove self from TcpMuxGroup
  191. ln.group.CloseListener(ln)
  192. return
  193. }