tcp.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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. "github.com/fatedier/frp/models/config"
  18. frpNet "github.com/fatedier/frp/utils/net"
  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. if pxy.cfg.Group != "" {
  27. l, realPort, errRet := pxy.rc.TcpGroupCtl.Listen(pxy.name, pxy.cfg.Group, pxy.cfg.GroupKey, pxy.serverCfg.ProxyBindAddr, pxy.cfg.RemotePort)
  28. if errRet != nil {
  29. err = errRet
  30. return
  31. }
  32. defer func() {
  33. if err != nil {
  34. l.Close()
  35. }
  36. }()
  37. pxy.realPort = realPort
  38. listener := frpNet.WrapLogListener(l)
  39. listener.AddLogPrefix(pxy.name)
  40. pxy.listeners = append(pxy.listeners, listener)
  41. pxy.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 := frpNet.ListenTcp(pxy.serverCfg.ProxyBindAddr, pxy.realPort)
  53. if errRet != nil {
  54. err = errRet
  55. return
  56. }
  57. listener.AddLogPrefix(pxy.name)
  58. pxy.listeners = append(pxy.listeners, listener)
  59. pxy.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) Close() {
  70. pxy.BaseProxy.Close()
  71. if pxy.cfg.Group == "" {
  72. pxy.rc.TcpPortManager.Release(pxy.realPort)
  73. }
  74. }