tcp.go 2.1 KB

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