frp/client/proxy/proxy.go

828 lines
20 KiB
Go
Raw Normal View History

2017-03-09 02:03:47 +08:00
// Copyright 2017 fatedier, fatedier@gmail.com
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
2018-12-09 22:06:22 +08:00
package proxy
2017-03-09 02:03:47 +08:00
import (
2017-10-24 22:53:20 +08:00
"bytes"
2019-10-12 20:13:12 +08:00
"context"
2017-03-09 02:03:47 +08:00
"io"
2017-03-13 02:44:47 +08:00
"net"
2019-03-11 15:53:58 +08:00
"strconv"
"strings"
2017-04-25 00:34:14 +08:00
"sync"
"time"
2017-03-09 02:03:47 +08:00
2018-05-08 02:13:30 +08:00
"github.com/fatedier/golib/errors"
2018-05-08 23:42:04 +08:00
frpIo "github.com/fatedier/golib/io"
2022-01-20 20:03:07 +08:00
libdial "github.com/fatedier/golib/net/dial"
2018-05-08 02:13:30 +08:00
"github.com/fatedier/golib/pool"
2019-03-05 11:18:17 +08:00
fmux "github.com/hashicorp/yamux"
2019-03-29 19:01:18 +08:00
pp "github.com/pires/go-proxyproto"
2019-11-03 01:20:49 +08:00
"golang.org/x/time/rate"
2022-08-29 01:02:53 +08:00
"github.com/fatedier/frp/pkg/config"
"github.com/fatedier/frp/pkg/msg"
plugin "github.com/fatedier/frp/pkg/plugin/client"
"github.com/fatedier/frp/pkg/proto/udp"
"github.com/fatedier/frp/pkg/util/limit"
frpNet "github.com/fatedier/frp/pkg/util/net"
"github.com/fatedier/frp/pkg/util/xlog"
2017-03-09 02:03:47 +08:00
)
2018-11-06 18:35:05 +08:00
// Proxy defines how to handle work connections for different proxy type.
2017-03-09 02:03:47 +08:00
type Proxy interface {
2017-03-12 02:03:24 +08:00
Run() error
2017-03-10 01:42:06 +08:00
// InWorkConn accept work connections registered to server.
2019-10-12 20:13:12 +08:00
InWorkConn(net.Conn, *msg.StartWorkConn)
2018-01-17 01:09:33 +08:00
2017-03-09 02:03:47 +08:00
Close()
}
2019-10-12 20:13:12 +08:00
func NewProxy(ctx context.Context, pxyConf config.ProxyConf, clientCfg config.ClientCommonConf, serverUDPPort int) (pxy Proxy) {
2019-11-03 01:20:49 +08:00
var limiter *rate.Limiter
2019-11-09 01:13:30 +08:00
limitBytes := pxyConf.GetBaseInfo().BandwidthLimit.Bytes()
if limitBytes > 0 && pxyConf.GetBaseInfo().BandwidthLimitMode == config.BandwidthLimitModeClient {
2019-11-03 01:20:49 +08:00
limiter = rate.NewLimiter(rate.Limit(float64(limitBytes)), int(limitBytes))
}
2017-03-13 02:44:47 +08:00
baseProxy := BaseProxy{
clientCfg: clientCfg,
serverUDPPort: serverUDPPort,
2019-11-03 01:20:49 +08:00
limiter: limiter,
2019-10-12 20:13:12 +08:00
xl: xlog.FromContextSafe(ctx),
ctx: ctx,
2017-03-13 02:44:47 +08:00
}
2017-03-09 02:03:47 +08:00
switch cfg := pxyConf.(type) {
2020-05-24 17:48:37 +08:00
case *config.TCPProxyConf:
pxy = &TCPProxy{
2019-01-31 16:49:23 +08:00
BaseProxy: &baseProxy,
2017-03-13 02:44:47 +08:00
cfg: cfg,
2017-03-09 02:03:47 +08:00
}
2020-05-24 17:48:37 +08:00
case *config.TCPMuxProxyConf:
pxy = &TCPMuxProxy{
BaseProxy: &baseProxy,
cfg: cfg,
}
2020-05-24 17:48:37 +08:00
case *config.UDPProxyConf:
pxy = &UDPProxy{
2019-01-31 16:49:23 +08:00
BaseProxy: &baseProxy,
2017-03-13 02:44:47 +08:00
cfg: cfg,
2017-03-09 02:03:47 +08:00
}
2020-05-24 17:48:37 +08:00
case *config.HTTPProxyConf:
pxy = &HTTPProxy{
2019-01-31 16:49:23 +08:00
BaseProxy: &baseProxy,
2017-03-13 02:44:47 +08:00
cfg: cfg,
2017-03-09 02:03:47 +08:00
}
2020-05-24 17:48:37 +08:00
case *config.HTTPSProxyConf:
pxy = &HTTPSProxy{
2019-01-31 16:49:23 +08:00
BaseProxy: &baseProxy,
2017-03-13 02:44:47 +08:00
cfg: cfg,
2017-03-09 02:03:47 +08:00
}
2020-05-24 17:48:37 +08:00
case *config.STCPProxyConf:
pxy = &STCPProxy{
2019-01-31 16:49:23 +08:00
BaseProxy: &baseProxy,
2017-06-26 03:02:33 +08:00
cfg: cfg,
}
2020-05-24 17:48:37 +08:00
case *config.XTCPProxyConf:
pxy = &XTCPProxy{
2019-01-31 16:49:23 +08:00
BaseProxy: &baseProxy,
2017-10-24 18:20:07 +08:00
cfg: cfg,
}
2020-05-24 17:48:37 +08:00
case *config.SUDPProxyConf:
pxy = &SUDPProxy{
2020-04-22 21:37:45 +08:00
BaseProxy: &baseProxy,
cfg: cfg,
closeCh: make(chan struct{}),
}
2017-03-09 02:03:47 +08:00
}
return
}
2017-03-13 02:44:47 +08:00
type BaseProxy struct {
closed bool
clientCfg config.ClientCommonConf
serverUDPPort int
2019-11-03 01:20:49 +08:00
limiter *rate.Limiter
2019-10-12 20:13:12 +08:00
mu sync.RWMutex
xl *xlog.Logger
ctx context.Context
2017-03-13 02:44:47 +08:00
}
2017-03-09 02:03:47 +08:00
// TCP
2020-05-24 17:48:37 +08:00
type TCPProxy struct {
2019-01-31 16:49:23 +08:00
*BaseProxy
2017-03-13 02:44:47 +08:00
2020-05-24 17:48:37 +08:00
cfg *config.TCPProxyConf
proxyPlugin plugin.Plugin
2017-03-09 02:03:47 +08:00
}
2020-05-24 17:48:37 +08:00
func (pxy *TCPProxy) Run() (err error) {
if pxy.cfg.Plugin != "" {
pxy.proxyPlugin, err = plugin.Create(pxy.cfg.Plugin, pxy.cfg.PluginParams)
if err != nil {
return
}
}
2017-03-12 02:03:24 +08:00
return
2017-03-09 02:03:47 +08:00
}
2020-05-24 17:48:37 +08:00
func (pxy *TCPProxy) Close() {
if pxy.proxyPlugin != nil {
pxy.proxyPlugin.Close()
}
2017-03-09 02:03:47 +08:00
}
2020-05-24 17:48:37 +08:00
func (pxy *TCPProxy) InWorkConn(conn net.Conn, m *msg.StartWorkConn) {
HandleTCPWorkConnection(pxy.ctx, &pxy.cfg.LocalSvrConf, pxy.proxyPlugin, pxy.cfg.GetBaseInfo(), pxy.limiter,
2019-11-03 01:20:49 +08:00
conn, []byte(pxy.clientCfg.Token), m)
2017-03-09 02:03:47 +08:00
}
// TCP Multiplexer
2020-05-24 17:48:37 +08:00
type TCPMuxProxy struct {
*BaseProxy
2020-05-24 17:48:37 +08:00
cfg *config.TCPMuxProxyConf
proxyPlugin plugin.Plugin
}
2020-05-24 17:48:37 +08:00
func (pxy *TCPMuxProxy) Run() (err error) {
if pxy.cfg.Plugin != "" {
pxy.proxyPlugin, err = plugin.Create(pxy.cfg.Plugin, pxy.cfg.PluginParams)
if err != nil {
return
}
}
return
}
2020-05-24 17:48:37 +08:00
func (pxy *TCPMuxProxy) Close() {
if pxy.proxyPlugin != nil {
pxy.proxyPlugin.Close()
}
}
2020-05-24 17:48:37 +08:00
func (pxy *TCPMuxProxy) InWorkConn(conn net.Conn, m *msg.StartWorkConn) {
HandleTCPWorkConnection(pxy.ctx, &pxy.cfg.LocalSvrConf, pxy.proxyPlugin, pxy.cfg.GetBaseInfo(), pxy.limiter,
conn, []byte(pxy.clientCfg.Token), m)
}
2017-03-09 02:03:47 +08:00
// HTTP
2020-05-24 17:48:37 +08:00
type HTTPProxy struct {
2019-01-31 16:49:23 +08:00
*BaseProxy
2017-03-13 02:44:47 +08:00
2020-05-24 17:48:37 +08:00
cfg *config.HTTPProxyConf
proxyPlugin plugin.Plugin
2017-03-09 02:03:47 +08:00
}
2020-05-24 17:48:37 +08:00
func (pxy *HTTPProxy) Run() (err error) {
if pxy.cfg.Plugin != "" {
pxy.proxyPlugin, err = plugin.Create(pxy.cfg.Plugin, pxy.cfg.PluginParams)
if err != nil {
return
}
}
2017-03-12 02:03:24 +08:00
return
2017-03-09 02:03:47 +08:00
}
2020-05-24 17:48:37 +08:00
func (pxy *HTTPProxy) Close() {
if pxy.proxyPlugin != nil {
pxy.proxyPlugin.Close()
}
2017-03-09 02:03:47 +08:00
}
2020-05-24 17:48:37 +08:00
func (pxy *HTTPProxy) InWorkConn(conn net.Conn, m *msg.StartWorkConn) {
HandleTCPWorkConnection(pxy.ctx, &pxy.cfg.LocalSvrConf, pxy.proxyPlugin, pxy.cfg.GetBaseInfo(), pxy.limiter,
2019-11-03 01:20:49 +08:00
conn, []byte(pxy.clientCfg.Token), m)
2017-03-09 02:03:47 +08:00
}
// HTTPS
2020-05-24 17:48:37 +08:00
type HTTPSProxy struct {
2019-01-31 16:49:23 +08:00
*BaseProxy
2017-03-13 02:44:47 +08:00
2020-05-24 17:48:37 +08:00
cfg *config.HTTPSProxyConf
proxyPlugin plugin.Plugin
2017-03-09 02:03:47 +08:00
}
2020-05-24 17:48:37 +08:00
func (pxy *HTTPSProxy) Run() (err error) {
if pxy.cfg.Plugin != "" {
pxy.proxyPlugin, err = plugin.Create(pxy.cfg.Plugin, pxy.cfg.PluginParams)
if err != nil {
return
}
}
2017-03-12 02:03:24 +08:00
return
2017-03-09 02:03:47 +08:00
}
2020-05-24 17:48:37 +08:00
func (pxy *HTTPSProxy) Close() {
if pxy.proxyPlugin != nil {
pxy.proxyPlugin.Close()
}
2017-03-09 02:03:47 +08:00
}
2020-05-24 17:48:37 +08:00
func (pxy *HTTPSProxy) InWorkConn(conn net.Conn, m *msg.StartWorkConn) {
HandleTCPWorkConnection(pxy.ctx, &pxy.cfg.LocalSvrConf, pxy.proxyPlugin, pxy.cfg.GetBaseInfo(), pxy.limiter,
2019-11-03 01:20:49 +08:00
conn, []byte(pxy.clientCfg.Token), m)
2017-03-10 02:01:17 +08:00
}
2017-06-26 03:02:33 +08:00
// STCP
2020-05-24 17:48:37 +08:00
type STCPProxy struct {
2019-01-31 16:49:23 +08:00
*BaseProxy
2017-06-26 03:02:33 +08:00
2020-05-24 17:48:37 +08:00
cfg *config.STCPProxyConf
2017-06-26 03:02:33 +08:00
proxyPlugin plugin.Plugin
}
2020-05-24 17:48:37 +08:00
func (pxy *STCPProxy) Run() (err error) {
2017-06-26 03:02:33 +08:00
if pxy.cfg.Plugin != "" {
pxy.proxyPlugin, err = plugin.Create(pxy.cfg.Plugin, pxy.cfg.PluginParams)
if err != nil {
return
}
}
return
}
2020-05-24 17:48:37 +08:00
func (pxy *STCPProxy) Close() {
2017-06-26 03:02:33 +08:00
if pxy.proxyPlugin != nil {
pxy.proxyPlugin.Close()
}
}
2020-05-24 17:48:37 +08:00
func (pxy *STCPProxy) InWorkConn(conn net.Conn, m *msg.StartWorkConn) {
HandleTCPWorkConnection(pxy.ctx, &pxy.cfg.LocalSvrConf, pxy.proxyPlugin, pxy.cfg.GetBaseInfo(), pxy.limiter,
2019-11-03 01:20:49 +08:00
conn, []byte(pxy.clientCfg.Token), m)
2017-06-26 03:02:33 +08:00
}
2017-10-24 18:20:07 +08:00
// XTCP
2020-05-24 17:48:37 +08:00
type XTCPProxy struct {
2019-01-31 16:49:23 +08:00
*BaseProxy
2017-10-24 18:20:07 +08:00
2020-05-24 17:48:37 +08:00
cfg *config.XTCPProxyConf
2017-10-24 18:20:07 +08:00
proxyPlugin plugin.Plugin
}
2020-05-24 17:48:37 +08:00
func (pxy *XTCPProxy) Run() (err error) {
2017-10-24 18:20:07 +08:00
if pxy.cfg.Plugin != "" {
pxy.proxyPlugin, err = plugin.Create(pxy.cfg.Plugin, pxy.cfg.PluginParams)
if err != nil {
return
}
}
return
}
2020-05-24 17:48:37 +08:00
func (pxy *XTCPProxy) Close() {
2017-10-24 18:20:07 +08:00
if pxy.proxyPlugin != nil {
pxy.proxyPlugin.Close()
}
}
2020-05-24 17:48:37 +08:00
func (pxy *XTCPProxy) InWorkConn(conn net.Conn, m *msg.StartWorkConn) {
2019-10-12 20:13:12 +08:00
xl := pxy.xl
2017-10-24 18:20:07 +08:00
defer conn.Close()
var natHoleSidMsg msg.NatHoleSid
err := msg.ReadMsgInto(conn, &natHoleSidMsg)
if err != nil {
2019-10-12 20:13:12 +08:00
xl.Error("xtcp read from workConn error: %v", err)
2017-10-24 18:20:07 +08:00
return
}
natHoleClientMsg := &msg.NatHoleClient{
ProxyName: pxy.cfg.ProxyName,
Sid: natHoleSidMsg.Sid,
}
serverAddr := pxy.clientCfg.NatHoleServerAddr
if serverAddr == "" {
serverAddr = pxy.clientCfg.ServerAddr
}
2017-10-24 18:20:07 +08:00
raddr, _ := net.ResolveUDPAddr("udp",
net.JoinHostPort(serverAddr, strconv.Itoa(pxy.serverUDPPort)))
2017-10-24 18:20:07 +08:00
clientConn, err := net.DialUDP("udp", nil, raddr)
2021-03-03 20:54:46 +08:00
if err != nil {
xl.Error("dial server udp addr error: %v", err)
return
}
2017-10-24 18:20:07 +08:00
defer clientConn.Close()
err = msg.WriteMsg(clientConn, natHoleClientMsg)
if err != nil {
2019-10-12 20:13:12 +08:00
xl.Error("send natHoleClientMsg to server error: %v", err)
2017-10-24 18:20:07 +08:00
return
}
2017-10-24 22:53:20 +08:00
// Wait for client address at most 5 seconds.
2017-10-24 18:20:07 +08:00
var natHoleRespMsg msg.NatHoleResp
2022-08-29 01:02:53 +08:00
_ = clientConn.SetReadDeadline(time.Now().Add(5 * time.Second))
2017-10-24 22:53:20 +08:00
buf := pool.GetBuf(1024)
n, err := clientConn.Read(buf)
if err != nil {
2019-10-12 20:13:12 +08:00
xl.Error("get natHoleRespMsg error: %v", err)
2017-10-24 22:53:20 +08:00
return
}
err = msg.ReadMsgInto(bytes.NewReader(buf[:n]), &natHoleRespMsg)
2017-10-24 18:20:07 +08:00
if err != nil {
2019-10-12 20:13:12 +08:00
xl.Error("get natHoleRespMsg error: %v", err)
2017-10-24 18:20:07 +08:00
return
}
2022-08-29 01:02:53 +08:00
_ = clientConn.SetReadDeadline(time.Time{})
_ = clientConn.Close()
if natHoleRespMsg.Error != "" {
2019-10-12 20:13:12 +08:00
xl.Error("natHoleRespMsg get error info: %s", natHoleRespMsg.Error)
return
}
2019-10-12 20:13:12 +08:00
xl.Trace("get natHoleRespMsg, sid [%s], client address [%s] visitor address [%s]", natHoleRespMsg.Sid, natHoleRespMsg.ClientAddr, natHoleRespMsg.VisitorAddr)
2017-10-24 18:20:07 +08:00
2019-03-11 15:53:58 +08:00
// Send detect message
host, portStr, err := net.SplitHostPort(natHoleRespMsg.VisitorAddr)
if err != nil {
xl.Error("get NatHoleResp visitor address [%s] error: %v", natHoleRespMsg.VisitorAddr, err)
2019-03-11 15:53:58 +08:00
}
2017-10-24 18:20:07 +08:00
laddr, _ := net.ResolveUDPAddr("udp", clientConn.LocalAddr().String())
port, err := strconv.ParseInt(portStr, 10, 64)
2019-03-11 15:53:58 +08:00
if err != nil {
2019-10-12 20:13:12 +08:00
xl.Error("get natHoleResp visitor address error: %v", natHoleRespMsg.VisitorAddr)
2019-03-11 15:53:58 +08:00
return
}
2022-08-29 01:02:53 +08:00
_ = pxy.sendDetectMsg(host, int(port), laddr, []byte(natHoleRespMsg.Sid))
2019-10-12 20:13:12 +08:00
xl.Trace("send all detect msg done")
2019-03-11 15:53:58 +08:00
2022-08-29 01:02:53 +08:00
if err := msg.WriteMsg(conn, &msg.NatHoleClientDetectOK{}); err != nil {
xl.Error("write message error: %v", err)
return
}
2019-03-11 15:53:58 +08:00
// Listen for clientConn's address and wait for visitor connection
lConn, err := net.ListenUDP("udp", laddr)
2017-10-24 18:20:07 +08:00
if err != nil {
xl.Error("listen on visitorConn's local address error: %v", err)
2017-10-24 18:20:07 +08:00
return
}
2019-03-11 15:53:58 +08:00
defer lConn.Close()
2017-10-24 18:20:07 +08:00
2022-08-29 01:02:53 +08:00
_ = lConn.SetReadDeadline(time.Now().Add(8 * time.Second))
2019-03-11 15:53:58 +08:00
sidBuf := pool.GetBuf(1024)
var uAddr *net.UDPAddr
n, uAddr, err = lConn.ReadFromUDP(sidBuf)
2017-10-24 18:20:07 +08:00
if err != nil {
2019-10-12 20:13:12 +08:00
xl.Warn("get sid from visitor error: %v", err)
2017-10-24 18:20:07 +08:00
return
}
2022-08-29 01:02:53 +08:00
_ = lConn.SetReadDeadline(time.Time{})
2019-03-11 15:53:58 +08:00
if string(sidBuf[:n]) != natHoleRespMsg.Sid {
2019-10-12 20:13:12 +08:00
xl.Warn("incorrect sid from visitor")
2019-03-11 15:53:58 +08:00
return
}
pool.PutBuf(sidBuf)
2019-10-12 20:13:12 +08:00
xl.Info("nat hole connection make success, sid [%s]", natHoleRespMsg.Sid)
2019-03-11 15:53:58 +08:00
2022-08-29 01:02:53 +08:00
if _, err := lConn.WriteToUDP(sidBuf[:n], uAddr); err != nil {
xl.Error("write uaddr error: %v", err)
return
}
2017-10-24 18:20:07 +08:00
2020-05-24 17:48:37 +08:00
kcpConn, err := frpNet.NewKCPConnFromUDP(lConn, false, uAddr.String())
2017-10-24 18:20:07 +08:00
if err != nil {
2019-10-12 20:13:12 +08:00
xl.Error("create kcp connection from udp connection error: %v", err)
2017-10-24 18:20:07 +08:00
return
}
2019-03-05 11:18:17 +08:00
fmuxCfg := fmux.DefaultConfig()
fmuxCfg.KeepAliveInterval = 5 * time.Second
fmuxCfg.LogOutput = io.Discard
2019-03-05 11:18:17 +08:00
sess, err := fmux.Server(kcpConn, fmuxCfg)
if err != nil {
2019-10-12 20:13:12 +08:00
xl.Error("create yamux server from kcp connection error: %v", err)
2019-03-05 11:18:17 +08:00
return
}
defer sess.Close()
muxConn, err := sess.Accept()
if err != nil {
2019-10-12 20:13:12 +08:00
xl.Error("accept for yamux connection error: %v", err)
2019-03-05 11:18:17 +08:00
return
}
HandleTCPWorkConnection(pxy.ctx, &pxy.cfg.LocalSvrConf, pxy.proxyPlugin, pxy.cfg.GetBaseInfo(), pxy.limiter,
2019-10-12 20:13:12 +08:00
muxConn, []byte(pxy.cfg.Sk), m)
2017-10-24 18:20:07 +08:00
}
2020-05-24 17:48:37 +08:00
func (pxy *XTCPProxy) sendDetectMsg(addr string, port int, laddr *net.UDPAddr, content []byte) (err error) {
2022-06-14 14:24:34 +08:00
daddr, err := net.ResolveUDPAddr("udp", net.JoinHostPort(addr, strconv.Itoa(port)))
2019-03-11 15:53:58 +08:00
if err != nil {
return err
}
tConn, err := net.DialUDP("udp", laddr, daddr)
if err != nil {
return err
}
2022-08-29 01:02:53 +08:00
// uConn := ipv4.NewConn(tConn)
// uConn.SetTTL(3)
2019-03-11 15:53:58 +08:00
2022-08-29 01:02:53 +08:00
if _, err := tConn.Write(content); err != nil {
return err
}
return tConn.Close()
2019-03-11 15:53:58 +08:00
}
2017-03-10 02:01:17 +08:00
// UDP
2020-05-24 17:48:37 +08:00
type UDPProxy struct {
2019-01-31 16:49:23 +08:00
*BaseProxy
2017-03-13 02:44:47 +08:00
2020-05-24 17:48:37 +08:00
cfg *config.UDPProxyConf
2017-03-13 02:44:47 +08:00
localAddr *net.UDPAddr
2020-05-24 17:48:37 +08:00
readCh chan *msg.UDPPacket
2020-05-24 17:48:37 +08:00
// include msg.UDPPacket and msg.Ping
sendCh chan msg.Message
2019-10-12 20:13:12 +08:00
workConn net.Conn
2017-03-10 02:01:17 +08:00
}
2020-05-24 17:48:37 +08:00
func (pxy *UDPProxy) Run() (err error) {
2022-06-14 14:24:34 +08:00
pxy.localAddr, err = net.ResolveUDPAddr("udp", net.JoinHostPort(pxy.cfg.LocalIP, strconv.Itoa(pxy.cfg.LocalPort)))
2017-03-13 02:44:47 +08:00
if err != nil {
return
}
2017-03-12 02:03:24 +08:00
return
2017-03-10 02:01:17 +08:00
}
2020-05-24 17:48:37 +08:00
func (pxy *UDPProxy) Close() {
2017-04-25 00:34:14 +08:00
pxy.mu.Lock()
defer pxy.mu.Unlock()
if !pxy.closed {
pxy.closed = true
if pxy.workConn != nil {
pxy.workConn.Close()
}
if pxy.readCh != nil {
close(pxy.readCh)
}
if pxy.sendCh != nil {
close(pxy.sendCh)
}
}
2017-03-10 02:01:17 +08:00
}
2020-05-24 17:48:37 +08:00
func (pxy *UDPProxy) InWorkConn(conn net.Conn, m *msg.StartWorkConn) {
2019-10-12 20:13:12 +08:00
xl := pxy.xl
xl.Info("incoming a new work connection for udp proxy, %s", conn.RemoteAddr().String())
2017-04-25 00:34:14 +08:00
// close resources releated with old workConn
pxy.Close()
2020-09-07 14:57:23 +08:00
var rwc io.ReadWriteCloser = conn
var err error
2019-11-03 01:20:49 +08:00
if pxy.limiter != nil {
2020-09-07 14:57:23 +08:00
rwc = frpIo.WrapReadWriteCloser(limit.NewReader(conn, pxy.limiter), limit.NewWriter(conn, pxy.limiter), func() error {
2019-11-03 01:20:49 +08:00
return conn.Close()
})
}
2020-09-07 14:57:23 +08:00
if pxy.cfg.UseEncryption {
rwc, err = frpIo.WithEncryption(rwc, []byte(pxy.clientCfg.Token))
if err != nil {
conn.Close()
xl.Error("create encryption stream error: %v", err)
return
}
}
if pxy.cfg.UseCompression {
rwc = frpIo.WithCompression(rwc)
}
conn = frpNet.WrapReadWriteCloserToConn(rwc, conn)
2019-11-03 01:20:49 +08:00
2017-04-25 00:34:14 +08:00
pxy.mu.Lock()
2017-03-13 02:44:47 +08:00
pxy.workConn = conn
2020-05-24 17:48:37 +08:00
pxy.readCh = make(chan *msg.UDPPacket, 1024)
pxy.sendCh = make(chan msg.Message, 1024)
2017-04-25 00:34:14 +08:00
pxy.closed = false
pxy.mu.Unlock()
2017-03-13 02:44:47 +08:00
2020-05-24 17:48:37 +08:00
workConnReaderFn := func(conn net.Conn, readCh chan *msg.UDPPacket) {
2017-03-13 02:44:47 +08:00
for {
2020-05-24 17:48:37 +08:00
var udpMsg msg.UDPPacket
2017-03-13 02:44:47 +08:00
if errRet := msg.ReadMsgInto(conn, &udpMsg); errRet != nil {
2019-10-12 20:13:12 +08:00
xl.Warn("read from workConn for udp error: %v", errRet)
2017-03-13 02:44:47 +08:00
return
}
if errRet := errors.PanicToError(func() {
2019-10-12 20:13:12 +08:00
xl.Trace("get udp package from workConn: %s", udpMsg.Content)
readCh <- &udpMsg
2017-03-13 02:44:47 +08:00
}); errRet != nil {
2019-10-12 20:13:12 +08:00
xl.Info("reader goroutine for udp work connection closed: %v", errRet)
2017-03-13 02:44:47 +08:00
return
}
}
}
workConnSenderFn := func(conn net.Conn, sendCh chan msg.Message) {
defer func() {
2019-10-12 20:13:12 +08:00
xl.Info("writer goroutine for udp work connection closed")
}()
2017-03-13 02:44:47 +08:00
var errRet error
for rawMsg := range sendCh {
switch m := rawMsg.(type) {
2020-05-24 17:48:37 +08:00
case *msg.UDPPacket:
2019-10-12 20:13:12 +08:00
xl.Trace("send udp package to workConn: %s", m.Content)
case *msg.Ping:
2019-10-12 20:13:12 +08:00
xl.Trace("send ping message to udp workConn")
}
if errRet = msg.WriteMsg(conn, rawMsg); errRet != nil {
2019-10-12 20:13:12 +08:00
xl.Error("udp work write error: %v", errRet)
2017-03-13 02:44:47 +08:00
return
}
}
}
2022-08-29 01:02:53 +08:00
heartbeatFn := func(sendCh chan msg.Message) {
var errRet error
for {
time.Sleep(time.Duration(30) * time.Second)
if errRet = errors.PanicToError(func() {
sendCh <- &msg.Ping{}
}); errRet != nil {
2019-10-12 20:13:12 +08:00
xl.Trace("heartbeat goroutine for udp work connection closed")
2017-05-17 16:02:31 +08:00
break
}
}
}
2017-03-13 02:44:47 +08:00
go workConnSenderFn(pxy.workConn, pxy.sendCh)
go workConnReaderFn(pxy.workConn, pxy.readCh)
2022-08-29 01:02:53 +08:00
go heartbeatFn(pxy.sendCh)
2020-05-24 17:48:37 +08:00
udp.Forwarder(pxy.localAddr, pxy.readCh, pxy.sendCh, int(pxy.clientCfg.UDPPacketSize))
2017-03-10 02:01:17 +08:00
}
2020-05-24 17:48:37 +08:00
type SUDPProxy struct {
2020-04-22 21:37:45 +08:00
*BaseProxy
2020-05-24 17:48:37 +08:00
cfg *config.SUDPProxyConf
2020-04-22 21:37:45 +08:00
localAddr *net.UDPAddr
closeCh chan struct{}
}
2020-05-24 17:48:37 +08:00
func (pxy *SUDPProxy) Run() (err error) {
2022-06-14 14:24:34 +08:00
pxy.localAddr, err = net.ResolveUDPAddr("udp", net.JoinHostPort(pxy.cfg.LocalIP, strconv.Itoa(pxy.cfg.LocalPort)))
2020-04-22 21:37:45 +08:00
if err != nil {
return
}
return
}
2020-05-24 17:48:37 +08:00
func (pxy *SUDPProxy) Close() {
2020-04-22 21:37:45 +08:00
pxy.mu.Lock()
defer pxy.mu.Unlock()
select {
case <-pxy.closeCh:
return
default:
close(pxy.closeCh)
}
}
2020-05-24 17:48:37 +08:00
func (pxy *SUDPProxy) InWorkConn(conn net.Conn, m *msg.StartWorkConn) {
2020-04-22 21:37:45 +08:00
xl := pxy.xl
xl.Info("incoming a new work connection for sudp proxy, %s", conn.RemoteAddr().String())
2020-09-07 14:57:23 +08:00
var rwc io.ReadWriteCloser = conn
var err error
2020-04-22 21:37:45 +08:00
if pxy.limiter != nil {
2020-09-07 14:57:23 +08:00
rwc = frpIo.WrapReadWriteCloser(limit.NewReader(conn, pxy.limiter), limit.NewWriter(conn, pxy.limiter), func() error {
2020-04-22 21:37:45 +08:00
return conn.Close()
})
}
2020-09-07 14:57:23 +08:00
if pxy.cfg.UseEncryption {
rwc, err = frpIo.WithEncryption(rwc, []byte(pxy.clientCfg.Token))
if err != nil {
conn.Close()
xl.Error("create encryption stream error: %v", err)
return
}
}
if pxy.cfg.UseCompression {
rwc = frpIo.WithCompression(rwc)
}
conn = frpNet.WrapReadWriteCloserToConn(rwc, conn)
2020-04-22 21:37:45 +08:00
workConn := conn
2020-05-24 17:48:37 +08:00
readCh := make(chan *msg.UDPPacket, 1024)
2020-04-22 21:37:45 +08:00
sendCh := make(chan msg.Message, 1024)
isClose := false
mu := &sync.Mutex{}
closeFn := func() {
mu.Lock()
defer mu.Unlock()
if isClose {
return
}
isClose = true
if workConn != nil {
workConn.Close()
}
close(readCh)
close(sendCh)
}
// udp service <- frpc <- frps <- frpc visitor <- user
2020-05-24 17:48:37 +08:00
workConnReaderFn := func(conn net.Conn, readCh chan *msg.UDPPacket) {
2020-04-22 21:37:45 +08:00
defer closeFn()
for {
// first to check sudp proxy is closed or not
select {
case <-pxy.closeCh:
xl.Trace("frpc sudp proxy is closed")
return
default:
}
2020-05-24 17:48:37 +08:00
var udpMsg msg.UDPPacket
2020-04-22 21:37:45 +08:00
if errRet := msg.ReadMsgInto(conn, &udpMsg); errRet != nil {
xl.Warn("read from workConn for sudp error: %v", errRet)
return
}
if errRet := errors.PanicToError(func() {
readCh <- &udpMsg
}); errRet != nil {
xl.Warn("reader goroutine for sudp work connection closed: %v", errRet)
return
}
}
}
// udp service -> frpc -> frps -> frpc visitor -> user
workConnSenderFn := func(conn net.Conn, sendCh chan msg.Message) {
defer func() {
closeFn()
xl.Info("writer goroutine for sudp work connection closed")
}()
var errRet error
for rawMsg := range sendCh {
switch m := rawMsg.(type) {
2020-05-24 17:48:37 +08:00
case *msg.UDPPacket:
2020-04-22 21:37:45 +08:00
xl.Trace("frpc send udp package to frpc visitor, [udp local: %v, remote: %v], [tcp work conn local: %v, remote: %v]",
m.LocalAddr.String(), m.RemoteAddr.String(), conn.LocalAddr().String(), conn.RemoteAddr().String())
case *msg.Ping:
xl.Trace("frpc send ping message to frpc visitor")
}
if errRet = msg.WriteMsg(conn, rawMsg); errRet != nil {
xl.Error("sudp work write error: %v", errRet)
return
}
}
}
2022-08-29 01:02:53 +08:00
heartbeatFn := func(sendCh chan msg.Message) {
2020-04-22 21:37:45 +08:00
ticker := time.NewTicker(30 * time.Second)
defer func() {
ticker.Stop()
closeFn()
}()
var errRet error
for {
select {
case <-ticker.C:
if errRet = errors.PanicToError(func() {
sendCh <- &msg.Ping{}
}); errRet != nil {
xl.Warn("heartbeat goroutine for sudp work connection closed")
return
}
case <-pxy.closeCh:
xl.Trace("frpc sudp proxy is closed")
return
}
}
}
go workConnSenderFn(workConn, sendCh)
go workConnReaderFn(workConn, readCh)
2022-08-29 01:02:53 +08:00
go heartbeatFn(sendCh)
2020-04-22 21:37:45 +08:00
2020-05-24 17:48:37 +08:00
udp.Forwarder(pxy.localAddr, readCh, sendCh, int(pxy.clientCfg.UDPPacketSize))
2020-04-22 21:37:45 +08:00
}
2017-03-10 02:01:17 +08:00
// Common handler for tcp work connections.
2020-05-24 17:48:37 +08:00
func HandleTCPWorkConnection(ctx context.Context, localInfo *config.LocalSvrConf, proxyPlugin plugin.Plugin,
2022-08-29 01:02:53 +08:00
baseInfo *config.BaseProxyConf, limiter *rate.Limiter, workConn net.Conn, encKey []byte, m *msg.StartWorkConn,
) {
2019-10-12 20:13:12 +08:00
xl := xlog.FromContextSafe(ctx)
var (
remote io.ReadWriteCloser
err error
)
2017-03-10 02:01:17 +08:00
remote = workConn
2019-11-03 01:20:49 +08:00
if limiter != nil {
remote = frpIo.WrapReadWriteCloser(limit.NewReader(workConn, limiter), limit.NewWriter(workConn, limiter), func() error {
return workConn.Close()
})
}
2018-01-23 16:31:59 +08:00
2019-10-12 20:13:12 +08:00
xl.Trace("handle tcp work connection, use_encryption: %t, use_compression: %t",
baseInfo.UseEncryption, baseInfo.UseCompression)
2017-03-10 02:01:17 +08:00
if baseInfo.UseEncryption {
2017-10-25 02:49:56 +08:00
remote, err = frpIo.WithEncryption(remote, encKey)
2017-03-10 02:01:17 +08:00
if err != nil {
2018-01-23 16:31:59 +08:00
workConn.Close()
2019-10-12 20:13:12 +08:00
xl.Error("create encryption stream error: %v", err)
2017-03-10 02:01:17 +08:00
return
}
}
if baseInfo.UseCompression {
2017-06-06 18:48:40 +08:00
remote = frpIo.WithCompression(remote)
2017-03-10 02:01:17 +08:00
}
// check if we need to send proxy protocol info
var extraInfo []byte
if baseInfo.ProxyProtocolVersion != "" {
if m.SrcAddr != "" && m.SrcPort != 0 {
if m.DstAddr == "" {
m.DstAddr = "127.0.0.1"
}
srcAddr, _ := net.ResolveTCPAddr("tcp", net.JoinHostPort(m.SrcAddr, strconv.Itoa(int(m.SrcPort))))
dstAddr, _ := net.ResolveTCPAddr("tcp", net.JoinHostPort(m.DstAddr, strconv.Itoa(int(m.DstPort))))
h := &pp.Header{
Command: pp.PROXY,
SourceAddr: srcAddr,
DestinationAddr: dstAddr,
}
if strings.Contains(m.SrcAddr, ".") {
h.TransportProtocol = pp.TCPv4
} else {
h.TransportProtocol = pp.TCPv6
}
if baseInfo.ProxyProtocolVersion == "v1" {
h.Version = 1
} else if baseInfo.ProxyProtocolVersion == "v2" {
h.Version = 2
}
buf := bytes.NewBuffer(nil)
2022-08-29 01:02:53 +08:00
_, _ = h.WriteTo(buf)
extraInfo = buf.Bytes()
}
}
if proxyPlugin != nil {
// if plugin is set, let plugin handle connections first
2019-10-12 20:13:12 +08:00
xl.Debug("handle by plugin: %s", proxyPlugin.Name())
proxyPlugin.Handle(remote, workConn, extraInfo)
2019-10-12 20:13:12 +08:00
xl.Debug("handle by plugin finished")
return
2020-05-24 17:48:37 +08:00
}
localConn, err := libdial.Dial(
net.JoinHostPort(localInfo.LocalIP, strconv.Itoa(localInfo.LocalPort)),
libdial.WithTimeout(10*time.Second),
)
2020-05-24 17:48:37 +08:00
if err != nil {
workConn.Close()
xl.Error("connect to local service [%s:%d] error: %v", localInfo.LocalIP, localInfo.LocalPort, err)
return
}
2019-03-29 19:01:18 +08:00
2020-05-24 17:48:37 +08:00
xl.Debug("join connections, localConn(l[%s] r[%s]) workConn(l[%s] r[%s])", localConn.LocalAddr().String(),
localConn.RemoteAddr().String(), workConn.LocalAddr().String(), workConn.RemoteAddr().String())
2019-03-29 19:01:18 +08:00
2020-05-24 17:48:37 +08:00
if len(extraInfo) > 0 {
2022-08-29 01:02:53 +08:00
if _, err := localConn.Write(extraInfo); err != nil {
workConn.Close()
xl.Error("write extraInfo to local conn error: %v", err)
return
}
}
2020-05-24 17:48:37 +08:00
2023-03-11 19:34:06 +08:00
_, _, errs := frpIo.Join(localConn, remote)
2020-05-24 17:48:37 +08:00
xl.Debug("join connections closed")
2023-03-11 19:34:06 +08:00
if len(errs) > 0 {
xl.Trace("join connections errors: %v", errs)
}
2017-03-09 02:03:47 +08:00
}