tcp.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. // Copyright 2019 fatedier, fatedier@gmail.com
  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 proxy
  15. import (
  16. "fmt"
  17. "net"
  18. "strconv"
  19. "golang.org/x/time/rate"
  20. "github.com/fatedier/frp/pkg/config"
  21. )
  22. type TCPProxy struct {
  23. *BaseProxy
  24. cfg *config.TCPProxyConf
  25. realPort int
  26. }
  27. func (pxy *TCPProxy) Run() (remoteAddr string, err error) {
  28. xl := pxy.xl
  29. if pxy.cfg.Group != "" {
  30. l, realPort, errRet := pxy.rc.TCPGroupCtl.Listen(pxy.name, pxy.cfg.Group, pxy.cfg.GroupKey, pxy.serverCfg.ProxyBindAddr, pxy.cfg.RemotePort)
  31. if errRet != nil {
  32. err = errRet
  33. return
  34. }
  35. defer func() {
  36. if err != nil {
  37. l.Close()
  38. }
  39. }()
  40. pxy.realPort = realPort
  41. pxy.listeners = append(pxy.listeners, l)
  42. xl.Info("tcp proxy listen port [%d] in group [%s]", pxy.cfg.RemotePort, pxy.cfg.Group)
  43. } else {
  44. pxy.realPort, err = pxy.rc.TCPPortManager.Acquire(pxy.name, pxy.cfg.RemotePort)
  45. if err != nil {
  46. return
  47. }
  48. defer func() {
  49. if err != nil {
  50. pxy.rc.TCPPortManager.Release(pxy.realPort)
  51. }
  52. }()
  53. listener, errRet := net.Listen("tcp", net.JoinHostPort(pxy.serverCfg.ProxyBindAddr, strconv.Itoa(pxy.realPort)))
  54. if errRet != nil {
  55. err = errRet
  56. return
  57. }
  58. pxy.listeners = append(pxy.listeners, listener)
  59. xl.Info("tcp proxy listen port [%d]", pxy.cfg.RemotePort)
  60. }
  61. pxy.cfg.RemotePort = pxy.realPort
  62. remoteAddr = fmt.Sprintf(":%d", pxy.realPort)
  63. pxy.startListenHandler(pxy, HandleUserTCPConnection)
  64. return
  65. }
  66. func (pxy *TCPProxy) GetConf() config.ProxyConf {
  67. return pxy.cfg
  68. }
  69. func (pxy *TCPProxy) GetLimiter() *rate.Limiter {
  70. return pxy.limiter
  71. }
  72. func (pxy *TCPProxy) Close() {
  73. pxy.BaseProxy.Close()
  74. if pxy.cfg.Group == "" {
  75. pxy.rc.TCPPortManager.Release(pxy.realPort)
  76. }
  77. }