tcp.go 2.1 KB

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