tcp.go 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  1. // Copyright 2018 fatedier, [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. "net"
  17. "strconv"
  18. "sync"
  19. "github.com/fatedier/frp/server/ports"
  20. gerr "github.com/fatedier/golib/errors"
  21. )
  22. // TCPGroupCtl manage all TCPGroups
  23. type TCPGroupCtl struct {
  24. groups map[string]*TCPGroup
  25. // portManager is used to manage port
  26. portManager *ports.Manager
  27. mu sync.Mutex
  28. }
  29. // NewTCPGroupCtl return a new TcpGroupCtl
  30. func NewTCPGroupCtl(portManager *ports.Manager) *TCPGroupCtl {
  31. return &TCPGroupCtl{
  32. groups: make(map[string]*TCPGroup),
  33. portManager: portManager,
  34. }
  35. }
  36. // Listen is the wrapper for TCPGroup's Listen
  37. // If there are no group, we will create one here
  38. func (tgc *TCPGroupCtl) Listen(proxyName string, group string, groupKey string,
  39. addr string, port int) (l net.Listener, realPort int, err error) {
  40. tgc.mu.Lock()
  41. tcpGroup, ok := tgc.groups[group]
  42. if !ok {
  43. tcpGroup = NewTCPGroup(tgc)
  44. tgc.groups[group] = tcpGroup
  45. }
  46. tgc.mu.Unlock()
  47. return tcpGroup.Listen(proxyName, group, groupKey, addr, port)
  48. }
  49. // RemoveGroup remove TCPGroup from controller
  50. func (tgc *TCPGroupCtl) RemoveGroup(group string) {
  51. tgc.mu.Lock()
  52. defer tgc.mu.Unlock()
  53. delete(tgc.groups, group)
  54. }
  55. // TCPGroup route connections to different proxies
  56. type TCPGroup struct {
  57. group string
  58. groupKey string
  59. addr string
  60. port int
  61. realPort int
  62. acceptCh chan net.Conn
  63. index uint64
  64. tcpLn net.Listener
  65. lns []*TCPGroupListener
  66. ctl *TCPGroupCtl
  67. mu sync.Mutex
  68. }
  69. // NewTCPGroup return a new TCPGroup
  70. func NewTCPGroup(ctl *TCPGroupCtl) *TCPGroup {
  71. return &TCPGroup{
  72. lns: make([]*TCPGroupListener, 0),
  73. ctl: ctl,
  74. acceptCh: make(chan net.Conn),
  75. }
  76. }
  77. // Listen will return a new TCPGroupListener
  78. // if TCPGroup already has a listener, just add a new TCPGroupListener to the queues
  79. // otherwise, listen on the real address
  80. func (tg *TCPGroup) Listen(proxyName string, group string, groupKey string, addr string, port int) (ln *TCPGroupListener, realPort int, err error) {
  81. tg.mu.Lock()
  82. defer tg.mu.Unlock()
  83. if len(tg.lns) == 0 {
  84. // the first listener, listen on the real address
  85. realPort, err = tg.ctl.portManager.Acquire(proxyName, port)
  86. if err != nil {
  87. return
  88. }
  89. tcpLn, errRet := net.Listen("tcp", net.JoinHostPort(addr, strconv.Itoa(port)))
  90. if errRet != nil {
  91. err = errRet
  92. return
  93. }
  94. ln = newTCPGroupListener(group, tg, tcpLn.Addr())
  95. tg.group = group
  96. tg.groupKey = groupKey
  97. tg.addr = addr
  98. tg.port = port
  99. tg.realPort = realPort
  100. tg.tcpLn = tcpLn
  101. tg.lns = append(tg.lns, ln)
  102. if tg.acceptCh == nil {
  103. tg.acceptCh = make(chan net.Conn)
  104. }
  105. go tg.worker()
  106. } else {
  107. // address and port in the same group must be equal
  108. if tg.group != group || tg.addr != addr {
  109. err = ErrGroupParamsInvalid
  110. return
  111. }
  112. if tg.port != port {
  113. err = ErrGroupDifferentPort
  114. return
  115. }
  116. if tg.groupKey != groupKey {
  117. err = ErrGroupAuthFailed
  118. return
  119. }
  120. ln = newTCPGroupListener(group, tg, tg.lns[0].Addr())
  121. realPort = tg.realPort
  122. tg.lns = append(tg.lns, ln)
  123. }
  124. return
  125. }
  126. // worker is called when the real tcp listener has been created
  127. func (tg *TCPGroup) worker() {
  128. for {
  129. c, err := tg.tcpLn.Accept()
  130. if err != nil {
  131. return
  132. }
  133. err = gerr.PanicToError(func() {
  134. tg.acceptCh <- c
  135. })
  136. if err != nil {
  137. return
  138. }
  139. }
  140. }
  141. func (tg *TCPGroup) Accept() <-chan net.Conn {
  142. return tg.acceptCh
  143. }
  144. // CloseListener remove the TCPGroupListener from the TCPGroup
  145. func (tg *TCPGroup) CloseListener(ln *TCPGroupListener) {
  146. tg.mu.Lock()
  147. defer tg.mu.Unlock()
  148. for i, tmpLn := range tg.lns {
  149. if tmpLn == ln {
  150. tg.lns = append(tg.lns[:i], tg.lns[i+1:]...)
  151. break
  152. }
  153. }
  154. if len(tg.lns) == 0 {
  155. close(tg.acceptCh)
  156. tg.tcpLn.Close()
  157. tg.ctl.portManager.Release(tg.realPort)
  158. tg.ctl.RemoveGroup(tg.group)
  159. }
  160. }
  161. // TCPGroupListener
  162. type TCPGroupListener struct {
  163. groupName string
  164. group *TCPGroup
  165. addr net.Addr
  166. closeCh chan struct{}
  167. }
  168. func newTCPGroupListener(name string, group *TCPGroup, addr net.Addr) *TCPGroupListener {
  169. return &TCPGroupListener{
  170. groupName: name,
  171. group: group,
  172. addr: addr,
  173. closeCh: make(chan struct{}),
  174. }
  175. }
  176. // Accept will accept connections from TCPGroup
  177. func (ln *TCPGroupListener) Accept() (c net.Conn, err error) {
  178. var ok bool
  179. select {
  180. case <-ln.closeCh:
  181. return nil, ErrListenerClosed
  182. case c, ok = <-ln.group.Accept():
  183. if !ok {
  184. return nil, ErrListenerClosed
  185. }
  186. return c, nil
  187. }
  188. }
  189. func (ln *TCPGroupListener) Addr() net.Addr {
  190. return ln.addr
  191. }
  192. // Close close the listener
  193. func (ln *TCPGroupListener) Close() (err error) {
  194. close(ln.closeCh)
  195. // remove self from TcpGroup
  196. ln.group.CloseListener(ln)
  197. return
  198. }