| // |
| 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 |
| 15 | package proxy |
| 16 |
| 17 | import ( |
| 18 | "fmt" |
| 19 | "net" |
| 20 | "reflect" |
| 21 | "strconv" |
| 22 |
| 23 | v1 "github.com/fatedier/frp/pkg/config/v1" |
| 24 | ) |
| 25 |
| 26 | func init() { |
| 27 | RegisterProxyFactory(reflect.TypeFor[*v1.TCPProxyConfig](), NewTCPProxy) |
| 28 | } |
| 29 |
| 30 | type TCPProxy struct { |
| 31 | *BaseProxy |
| 32 | cfg *v1.TCPProxyConfig |
| 33 |
| 34 | realBindPort int |
| 35 | } |
| 36 |
| 37 | func NewTCPProxy(baseProxy *BaseProxy) Proxy { |
| 38 | unwrapped, ok := baseProxy.GetConfigurer().(*v1.TCPProxyConfig) |
| 39 | if !ok { |
| 40 | return nil |
| 41 | } |
| 42 | baseProxy.usedPortsNum = 1 |
| 43 | return &TCPProxy{ |
| 44 | BaseProxy: baseProxy, |
| 45 | cfg: unwrapped, |
| 46 | } |
| 47 | } |
| 48 |
| 49 | func (pxy *TCPProxy) Run() (remoteAddr string, err error) { |
| 50 | xl := pxy.xl |
| 51 | if pxy.cfg.LoadBalancer.Group != "" { |
| 52 | l, realBindPort, errRet := pxy.rc.TCPGroupCtl.Listen(pxy.name, pxy.cfg.LoadBalancer.Group, pxy.cfg.LoadBalancer.GroupKey, |
| 53 | pxy.serverCfg.ProxyBindAddr, pxy.cfg.RemotePort) |
| 54 | if errRet != nil { |
| 55 | err = errRet |
| 56 | return |
| 57 | } |
| 58 | defer func() { |
| 59 | if err != nil { |
| 60 | l.Close() |
| 61 | } |
| 62 | }() |
| 63 | pxy.realBindPort = realBindPort |
| 64 | pxy.listeners = append(pxy.listeners, l) |
| 65 | xl.Infof("tcp proxy listen port [%d] in group [%s]", pxy.cfg.RemotePort, pxy.cfg.LoadBalancer.Group) |
| 66 | } else { |
| 67 | pxy.realBindPort, err = pxy.rc.TCPPortManager.Acquire(pxy.name, pxy.cfg.RemotePort) |
| 68 | if err != nil { |
| 69 | return |
| 70 | } |
| 71 | defer func() { |
| 72 | if err != nil { |
| 73 | pxy.rc.TCPPortManager.Release(pxy.realBindPort) |
| 74 | } |
| 75 | }() |
| 76 | listener, errRet := net.Listen("tcp", net.JoinHostPort(pxy.serverCfg.ProxyBindAddr, strconv.Itoa(pxy.realBindPort))) |
| 77 | if errRet != nil { |
| 78 | err = errRet |
| 79 | return |
| 80 | } |
| 81 | pxy.listeners = append(pxy.listeners, listener) |
| 82 | xl.Infof("tcp proxy listen port [%d]", pxy.cfg.RemotePort) |
| 83 | } |
| 84 |
| 85 | pxy.cfg.RemotePort = pxy.realBindPort |
| 86 | remoteAddr = fmt.Sprintf(":%d", pxy.realBindPort) |
| 87 | pxy.startCommonTCPListenersHandler() |
| 88 | return |
| 89 | } |
| 90 |
| 91 | func (pxy *TCPProxy) Close() { |
| 92 | pxy.BaseProxy.Close() |
| 93 | if pxy.cfg.LoadBalancer.Group == "" { |
| 94 | pxy.rc.TCPPortManager.Release(pxy.realBindPort) |
| 95 | } |
| 96 | } |