tcpmux.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  1. // Copyright 2020 guylewin, guy@lewin.co.il
  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. gerr "github.com/fatedier/golib/errors"
  21. v1 "github.com/fatedier/frp/pkg/config/v1"
  22. "github.com/fatedier/frp/pkg/util/tcpmux"
  23. "github.com/fatedier/frp/pkg/util/vhost"
  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(
  42. ctx context.Context,
  43. multiplexer, group, groupKey string,
  44. routeConfig vhost.RouteConfig,
  45. ) (l net.Listener, err error) {
  46. tmgc.mu.Lock()
  47. tcpMuxGroup, ok := tmgc.groups[group]
  48. if !ok {
  49. tcpMuxGroup = NewTCPMuxGroup(tmgc)
  50. tmgc.groups[group] = tcpMuxGroup
  51. }
  52. tmgc.mu.Unlock()
  53. switch v1.TCPMultiplexerType(multiplexer) {
  54. case v1.TCPMultiplexerHTTPConnect:
  55. return tcpMuxGroup.HTTPConnectListen(ctx, group, groupKey, routeConfig)
  56. default:
  57. err = fmt.Errorf("unknown multiplexer [%s]", multiplexer)
  58. return
  59. }
  60. }
  61. // RemoveGroup remove TCPMuxGroup from controller
  62. func (tmgc *TCPMuxGroupCtl) RemoveGroup(group string) {
  63. tmgc.mu.Lock()
  64. defer tmgc.mu.Unlock()
  65. delete(tmgc.groups, group)
  66. }
  67. // TCPMuxGroup route connections to different proxies
  68. type TCPMuxGroup struct {
  69. group string
  70. groupKey string
  71. domain string
  72. routeByHTTPUser string
  73. username string
  74. password string
  75. acceptCh chan net.Conn
  76. tcpMuxLn net.Listener
  77. lns []*TCPMuxGroupListener
  78. ctl *TCPMuxGroupCtl
  79. mu sync.Mutex
  80. }
  81. // NewTCPMuxGroup return a new TCPMuxGroup
  82. func NewTCPMuxGroup(ctl *TCPMuxGroupCtl) *TCPMuxGroup {
  83. return &TCPMuxGroup{
  84. lns: make([]*TCPMuxGroupListener, 0),
  85. ctl: ctl,
  86. acceptCh: make(chan net.Conn),
  87. }
  88. }
  89. // Listen will return a new TCPMuxGroupListener
  90. // if TCPMuxGroup already has a listener, just add a new TCPMuxGroupListener to the queues
  91. // otherwise, listen on the real address
  92. func (tmg *TCPMuxGroup) HTTPConnectListen(
  93. ctx context.Context,
  94. group, groupKey string,
  95. routeConfig vhost.RouteConfig,
  96. ) (ln *TCPMuxGroupListener, err error) {
  97. tmg.mu.Lock()
  98. defer tmg.mu.Unlock()
  99. if len(tmg.lns) == 0 {
  100. // the first listener, listen on the real address
  101. tcpMuxLn, errRet := tmg.ctl.tcpMuxHTTPConnectMuxer.Listen(ctx, &routeConfig)
  102. if errRet != nil {
  103. return nil, errRet
  104. }
  105. ln = newTCPMuxGroupListener(group, tmg, tcpMuxLn.Addr())
  106. tmg.group = group
  107. tmg.groupKey = groupKey
  108. tmg.domain = routeConfig.Domain
  109. tmg.routeByHTTPUser = routeConfig.RouteByHTTPUser
  110. tmg.username = routeConfig.Username
  111. tmg.password = routeConfig.Password
  112. tmg.tcpMuxLn = tcpMuxLn
  113. tmg.lns = append(tmg.lns, ln)
  114. if tmg.acceptCh == nil {
  115. tmg.acceptCh = make(chan net.Conn)
  116. }
  117. go tmg.worker()
  118. } else {
  119. // route config in the same group must be equal
  120. if tmg.group != group || tmg.domain != routeConfig.Domain ||
  121. tmg.routeByHTTPUser != routeConfig.RouteByHTTPUser ||
  122. tmg.username != routeConfig.Username ||
  123. tmg.password != routeConfig.Password {
  124. return nil, ErrGroupParamsInvalid
  125. }
  126. if tmg.groupKey != groupKey {
  127. return nil, ErrGroupAuthFailed
  128. }
  129. ln = newTCPMuxGroupListener(group, tmg, tmg.lns[0].Addr())
  130. tmg.lns = append(tmg.lns, ln)
  131. }
  132. return
  133. }
  134. // worker is called when the real TCP listener has been created
  135. func (tmg *TCPMuxGroup) worker() {
  136. for {
  137. c, err := tmg.tcpMuxLn.Accept()
  138. if err != nil {
  139. return
  140. }
  141. err = gerr.PanicToError(func() {
  142. tmg.acceptCh <- c
  143. })
  144. if err != nil {
  145. return
  146. }
  147. }
  148. }
  149. func (tmg *TCPMuxGroup) Accept() <-chan net.Conn {
  150. return tmg.acceptCh
  151. }
  152. // CloseListener remove the TCPMuxGroupListener from the TCPMuxGroup
  153. func (tmg *TCPMuxGroup) CloseListener(ln *TCPMuxGroupListener) {
  154. tmg.mu.Lock()
  155. defer tmg.mu.Unlock()
  156. for i, tmpLn := range tmg.lns {
  157. if tmpLn == ln {
  158. tmg.lns = append(tmg.lns[:i], tmg.lns[i+1:]...)
  159. break
  160. }
  161. }
  162. if len(tmg.lns) == 0 {
  163. close(tmg.acceptCh)
  164. tmg.tcpMuxLn.Close()
  165. tmg.ctl.RemoveGroup(tmg.group)
  166. }
  167. }
  168. // TCPMuxGroupListener
  169. type TCPMuxGroupListener struct {
  170. groupName string
  171. group *TCPMuxGroup
  172. addr net.Addr
  173. closeCh chan struct{}
  174. }
  175. func newTCPMuxGroupListener(name string, group *TCPMuxGroup, addr net.Addr) *TCPMuxGroupListener {
  176. return &TCPMuxGroupListener{
  177. groupName: name,
  178. group: group,
  179. addr: addr,
  180. closeCh: make(chan struct{}),
  181. }
  182. }
  183. // Accept will accept connections from TCPMuxGroup
  184. func (ln *TCPMuxGroupListener) Accept() (c net.Conn, err error) {
  185. var ok bool
  186. select {
  187. case <-ln.closeCh:
  188. return nil, ErrListenerClosed
  189. case c, ok = <-ln.group.Accept():
  190. if !ok {
  191. return nil, ErrListenerClosed
  192. }
  193. return c, nil
  194. }
  195. }
  196. func (ln *TCPMuxGroupListener) Addr() net.Addr {
  197. return ln.addr
  198. }
  199. // Close close the listener
  200. func (ln *TCPMuxGroupListener) Close() (err error) {
  201. close(ln.closeCh)
  202. // remove self from TcpMuxGroup
  203. ln.group.CloseListener(ln)
  204. return
  205. }